From 8448e70a60025839fc67d35bc9fddf9b0687d8d4 Mon Sep 17 00:00:00 2001 From: Shai Almog <67850168+shai-almog@users.noreply.github.com> Date: Fri, 27 Nov 2026 07:59:28 +0200 Subject: [PATCH 01/25] Python: transpiler typing, runtime speedups and fixes; core JSON, hashing and SQLite speedups Collects the transpiler, runtime, build and core changes made while running large real-world Python packages through the toolchain. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/parparvm-tests.yml | 4 + .github/workflows/python-bench.yml | 17 +- .../src/com/codename1/annotations/Fused.java | 1 + .../src/com/codename1/db/Database.java | 296 +- .../com/codename1/db/ThreadSafeDatabase.java | 39 + .../src/com/codename1/db/sql/MySql.java | 8 +- .../com/codename1/db/sql/Placeholders.java | 19 + .../src/com/codename1/db/sql/QueryRows.java | 13 + .../com/codename1/impl/AbstractDBCursor.java | 105 + .../impl/CodenameOneImplementation.java | 14 + .../com/codename1/impl/SQLStatementCache.java | 91 + .../codename1/impl/SQLStatementSplitter.java | 18 +- .../com/codename1/impl/SqlFunctionBridge.java | 143 + .../com/codename1/io/JSONParseException.java | 53 + .../src/com/codename1/io/JSONParser.java | 387 +- .../com/codename1/io/JSONValueFactory.java | 221 + .../src/com/codename1/io/JSONWriter.java | 42 +- .../src/com/codename1/io/gzip/CRC32.java | 28 +- .../src/com/codename1/security/Hash.java | 74 + .../codename1/security/MessageDigestImpl.java | 1600 ++ .../src/com/codename1/security/Pbkdf2.java | 48 +- CodenameOne/src/com/codename1/ui/Display.java | 14 + NOTICE | 112 + .../com/codename1/impl/javase/SEDatabase.java | 65 + .../impl/html5/database/DatabaseImpl.java | 65 + .../impl/html5/database/SQLiteNative.java | 9 + Ports/JavaScriptPort/src/main/webapp/port.js | 93 + Ports/LinuxPort/nativeSources/cn1_linux_db.c | 97 + Ports/LinuxPort/nativeSources/cn1_linux_io.c | 11 + .../codename1/impl/linux/LinuxDatabase.java | 218 +- .../impl/linux/LinuxImplementation.java | 17 + .../com/codename1/impl/linux/LinuxNative.java | 36 + .../nativeSources/cn1_windows_db.c | 97 + .../impl/windows/WindowsDatabase.java | 218 +- .../impl/windows/WindowsImplementation.java | 12 + .../codename1/impl/windows/WindowsNative.java | 34 + Ports/iOSPort/nativeSources/IOSNative.m | 92 +- .../com/codename1/impl/ios/DatabaseImpl.java | 146 +- .../src/com/codename1/impl/ios/IOSNative.java | 15 + docs/developer-guide/Python-Interop.asciidoc | 126 +- docs/developer-guide/developer-guide.asciidoc | 2 + maven/backend/spotbugs-exclude.xml | 1 + .../com/codename1/maven/BackendPackager.java | 99 +- .../com/codename1/maven/PythonLineMapper.java | 42 +- .../maven/PythonPackageResolver.java | 142 +- .../codename1/maven/PythonProjectBuilder.java | 150 +- .../maven/PythonProjectImporter.java | 16 +- .../CommandAnnotationProcessor.java | 17 +- .../codename1/maven/PythonLineMapperTest.java | 21 +- .../codename1/maven/PythonProjectTest.java | 43 + .../java/com/codename1/gradle/AppSupport.java | 7 +- .../gradle/tasks/TranspilePythonTask.java | 9 +- .../codename1/maven/BackendPackageMojo.java | 10 +- .../maven/ImportPythonProjectMojo.java | 18 +- .../codename1/maven/TranspilePythonMojo.java | 1 + maven/core-unittests/spotbugs-exclude.xml | 18 + maven/python-runtime/spotbugs-exclude.xml | 89 +- .../com/codename1/python/runtime/Abc.java | 169 + .../codename1/python/runtime/Annotations.java | 164 + .../codename1/python/runtime/ArgArrays.java | 81 + .../codename1/python/runtime/AttrSite.java | 780 +- .../python/runtime/BuiltinSubclass.java | 143 +- .../codename1/python/runtime/Builtins.java | 835 +- .../codename1/python/runtime/Cn1Platform.java | 46 + .../com/codename1/python/runtime/Cn1Sql.java | 122 +- .../com/codename1/python/runtime/Codecs.java | 368 +- .../codename1/python/runtime/EnumMeta.java | 195 + .../python/runtime/ExceptionGroups.java | 35 +- .../codename1/python/runtime/ExpatRun.java | 702 + .../codename1/python/runtime/Formatting.java | 261 +- .../codename1/python/runtime/Functools.java | 316 + .../com/codename1/python/runtime/Gil.java | 23 +- .../com/codename1/python/runtime/Hashing.java | 17 + .../codename1/python/runtime/HeapqBisect.java | 336 + .../codename1/python/runtime/ItemWalk.java | 121 + .../codename1/python/runtime/Itertools.java | 1062 ++ .../com/codename1/python/runtime/KeySite.java | 72 + .../python/runtime/MathFunctions.java | 46 +- .../python/runtime/NativeModule.java | 35 + .../com/codename1/python/runtime/NumPy.java | 34 +- .../codename1/python/runtime/Operator.java | 337 + .../java/com/codename1/python/runtime/Py.java | 848 +- .../com/codename1/python/runtime/PyAes.java | 68 + .../codename1/python/runtime/PyBinascii.java | 152 + .../codename1/python/runtime/PyBuiltin.java | 304 +- .../codename1/python/runtime/PyByteArray.java | 54 +- .../com/codename1/python/runtime/PyBytes.java | 367 +- .../com/codename1/python/runtime/PyCode.java | 2 +- .../python/runtime/PyCollections.java | 198 + .../codename1/python/runtime/PyComplex.java | 16 +- .../com/codename1/python/runtime/PyDict.java | 654 +- .../codename1/python/runtime/PyException.java | 12 +- .../codename1/python/runtime/PyFunction.java | 1288 +- .../codename1/python/runtime/PyGenerator.java | 265 +- .../python/runtime/PyGenericAlias.java | 21 +- .../codename1/python/runtime/PyHashlib.java | 126 + .../com/codename1/python/runtime/PyImage.java | 78 +- .../codename1/python/runtime/PyInstance.java | 557 +- .../com/codename1/python/runtime/PyInt.java | 49 +- .../codename1/python/runtime/PyJavaIter.java | 12 + .../com/codename1/python/runtime/PyJson.java | 762 + .../com/codename1/python/runtime/PyList.java | 232 +- .../com/codename1/python/runtime/PyMatch.java | 2 +- .../python/runtime/PyMemoryView.java | 26 +- .../codename1/python/runtime/PyMethod.java | 105 + .../codename1/python/runtime/PyModule.java | 225 +- .../codename1/python/runtime/PyObject.java | 105 +- .../codename1/python/runtime/PyObjects.java | 97 + .../python/runtime/PyPackageData.java | 176 + .../codename1/python/runtime/PyProperty.java | 6 +- .../com/codename1/python/runtime/PyRange.java | 56 +- .../codename1/python/runtime/PyServer.java | 20 +- .../com/codename1/python/runtime/PySet.java | 58 +- .../com/codename1/python/runtime/PySlice.java | 28 +- .../com/codename1/python/runtime/PySql.java | 107 +- .../python/runtime/PyStaticMethod.java | 10 + .../com/codename1/python/runtime/PyStr.java | 265 +- .../codename1/python/runtime/PyStruct.java | 191 + .../codename1/python/runtime/PyStructSeq.java | 45 + .../com/codename1/python/runtime/PySuper.java | 10 + .../com/codename1/python/runtime/PyTuple.java | 344 +- .../com/codename1/python/runtime/PyType.java | 1138 +- .../com/codename1/python/runtime/PyUnion.java | 14 +- .../com/codename1/python/runtime/PyZlib.java | 66 +- .../com/codename1/python/runtime/Regex.java | 1069 +- .../codename1/python/runtime/RegexMatch.java | 475 + .../com/codename1/python/runtime/Shape.java | 56 +- .../codename1/python/runtime/StdModules.java | 1218 +- .../codename1/python/runtime/StoreSite.java | 315 + .../codename1/python/runtime/StrFormat.java | 32 +- .../codename1/python/runtime/TypeMethods.java | 1047 +- .../com/codename1/python/runtime/Typed.java | 524 +- .../com/codename1/python/runtime/Unicode.java | 38 + .../python/runtime/UnicodeTables.java | 11 +- .../com/codename1/python/runtime/Utf8.java | 191 +- .../com/codename1/python/runtime/XmlScan.java | 1173 ++ .../third-party/unicode/LICENSE.txt | 39 + .../tools/gen_unicode_tables.py | 20 +- maven/python-transpiler/pom.xml | 2 + maven/python-transpiler/spotbugs-exclude.xml | 19 + .../python/transpiler/analyze/Desugar.java | 80 + .../python/transpiler/analyze/GenInline.java | 843 + .../transpiler/analyze/ScopeBuilder.java | 2 + .../codename1/python/transpiler/api/Main.java | 53 +- .../transpiler/api/PythonTranspiler.java | 560 +- .../codename1/python/transpiler/ast/Node.java | 23 +- .../python/transpiler/ast/Scope.java | 10 + .../transpiler/codegen/AliasLowering.java | 278 + .../transpiler/codegen/ArgparseLowering.java | 463 + .../transpiler/codegen/AttrsLowering.java | 1082 ++ .../transpiler/codegen/BuildTimeBases.java | 558 + .../transpiler/codegen/BuiltinSigs.java | 79 + .../codegen/ClassArgSpecialize.java | 654 + .../codegen/ClassDecoratorLowering.java | 316 + .../transpiler/codegen/ClassPathReader.java | 87 + .../python/transpiler/codegen/Closed.java | 160 - .../transpiler/codegen/ClosedNameSetattr.java | 449 + .../transpiler/codegen/CobbleLowering.java | 385 + .../codegen/ColorValueLowering.java | 249 + .../codegen/ConstArgSpecialize.java | 1189 ++ .../transpiler/codegen/ConstantDefaults.java | 141 + .../codegen/CustomPropertyLowering.java | 339 + .../transpiler/codegen/DataclassInit.java | 1097 ++ .../transpiler/codegen/DeclarativeMap.java | 1816 +++ .../python/transpiler/codegen/DefAssign.java | 57 +- .../transpiler/codegen/DictItemsSetattr.java | 457 + .../python/transpiler/codegen/Directives.java | 454 + .../python/transpiler/codegen/Emitter.java | 3012 +++- .../transpiler/codegen/EntryPointTable.java | 176 + .../transpiler/codegen/EnumLowering.java | 527 + .../codegen/FlaskProxyLowering.java | 284 + .../transpiler/codegen/GenLowering.java | 203 +- .../python/transpiler/codegen/GenTarget.java | 62 + .../transpiler/codegen/ImmutableSlots.java | 565 + .../python/transpiler/codegen/Infer.java | 13586 ++++++++++++++-- .../codegen/JavaInteropGenerator.java | 23 + .../transpiler/codegen/Jinja2Lowering.java | 573 + .../transpiler/codegen/KnownHelpers.java | 372 + .../python/transpiler/codegen/KwAttrInit.java | 1031 ++ .../python/transpiler/codegen/Layouts.java | 2468 ++- .../transpiler/codegen/LiteralAttrStore.java | 447 + .../python/transpiler/codegen/Liveness.java | 2060 +++ .../python/transpiler/codegen/LoopUnroll.java | 2509 +++ .../codegen/NamedStyleLowering.java | 186 + .../codegen/NamedTupleLowering.java | 542 + .../transpiler/codegen/OxmlDeclarative.java | 963 ++ .../transpiler/codegen/ProtocolChecks.java | 160 + .../transpiler/codegen/PydanticLowering.java | 521 + .../transpiler/codegen/PytestLowering.java | 477 + .../codegen/SerialisableMethods.java | 423 + .../transpiler/codegen/SetNameDescriptor.java | 444 + .../transpiler/codegen/ShadowTypes.java | 16 +- .../codegen/SqlAlchemyLowering.java | 749 + .../transpiler/codegen/StyleableLowering.java | 200 + .../codegen/ThreadLocalLowering.java | 302 + .../python/transpiler/codegen/Ty.java | 248 +- .../python/transpiler/codegen/TypedEmit.java | 6145 ++++++- .../transpiler/codegen/WholeProgram.java | 998 ++ .../python/transpiler/parser/Parser.java | 381 +- .../transpiler/parser/UnicodeNames.java | 38 +- .../com/codename1/python/site/PIL/Image.py | 82 +- .../codename1/python/site/attr/__init__.py | 441 +- .../codename1/python/site/cobble/__init__.py | 60 + .../python/site/cryptography/__init__.py | 11 + .../site/cryptography/hazmat/__init__.py | 4 + .../cryptography/hazmat/backends/__init__.py | 8 + .../hazmat/primitives/__init__.py | 4 + .../hazmat/primitives/ciphers/__init__.py | 77 + .../hazmat/primitives/ciphers/algorithms.py | 19 + .../hazmat/primitives/ciphers/modes.py | 18 + .../python/site/dateutil/relativedelta.py | 10 +- .../python/site/fastapi/applications.py | 5 +- .../codename1/python/site/fastapi/params.py | 6 +- .../codename1/python/site/flask/__init__.py | 16 +- .../codename1/python/site/httpx/__init__.py | 631 +- .../codename1/python/site/httpx2/__init__.py | 11 + .../codename1/python/site/httpx2/_config.py | 5 + .../codename1/python/site/jinja2/__init__.py | 166 +- .../codename1/python/site/jiter/__init__.py | 331 + .../codename1/python/site/lxml/__init__.py | 13 + .../com/codename1/python/site/lxml/_xpath.py | 990 ++ .../com/codename1/python/site/lxml/etree.py | 1907 +++ .../codename1/python/site/magika/__init__.py | 412 + .../codename1/python/site/numpy/__init__.py | 45 +- .../codename1/python/site/pandas/__init__.py | 167 +- .../python/site/pydantic/__init__.py | 619 +- .../python/site/pydantic/dataclasses.py | 36 +- .../codename1/python/site/pydantic/fields.py | 8 + .../python/site/pydantic_core/__init__.py | 30 + .../python/site/pypdfium2/__init__.py | 33 + .../codename1/python/site/pytest/__init__.py | 576 +- .../python/site/pytest_httpx/__init__.py | 5 + .../python/site/pytest_httpx2/__init__.py | 241 + .../python/site/requests/__init__.py | 31 +- .../python/site/sqlalchemy/_cn1dbapi.py | 20 +- .../python/site/sqlalchemy/orm/__init__.py | 643 +- .../python/site/starlette/datastructures.py | 13 +- .../python/site/typing_extensions/__init__.py | 23 + .../codename1/python/site/yaml/__init__.py | 192 +- .../codename1/python/stdlib/_interpqueues.py | 41 + .../codename1/python/stdlib/_interpreters.py | 59 + .../codename1/python/stdlib/_markupbase.py | 41 + .../com/codename1/python/stdlib/abc.py | 63 +- .../com/codename1/python/stdlib/argparse.py | 115 +- .../com/codename1/python/stdlib/array.py | 309 + .../com/codename1/python/stdlib/ast.py | 133 + .../{asyncio.py => asyncio/__init__.py} | 279 +- .../python/stdlib/asyncio/_transports.py | 364 + .../python/stdlib/asyncio/base_events.py | 9 + .../python/stdlib/asyncio/futures.py | 15 + .../python/stdlib/asyncio/subprocess.py | 83 + .../com/codename1/python/stdlib/binascii.py | 52 +- .../com/codename1/python/stdlib/bisect.py | 38 +- .../com/codename1/python/stdlib/calendar.py | 164 + .../com/codename1/python/stdlib/codecs.py | 196 + .../python/stdlib/collections/__init__.py | 45 +- .../python/stdlib/collections/abc.py | 20 +- .../stdlib/concurrent/futures/__init__.py | 1 + .../com/codename1/python/stdlib/contextlib.py | 36 +- .../codename1/python/stdlib/contextvars.py | 129 + .../com/codename1/python/stdlib/copy.py | 76 +- .../com/codename1/python/stdlib/copyreg.py | 12 +- .../com/codename1/python/stdlib/csv.py | 44 +- .../codename1/python/stdlib/dataclasses.py | 304 +- .../com/codename1/python/stdlib/datetime.py | 117 +- .../com/codename1/python/stdlib/decimal.py | 119 +- .../com/codename1/python/stdlib/difflib.py | 267 + .../codename1/python/stdlib/email/message.py | 47 + .../codename1/python/stdlib/email/utils.py | 311 + .../python/stdlib/encodings/__init__.py | 45 + .../python/stdlib/encodings/aliases.py | 38 + .../python/stdlib/encodings/ascii.py | 23 + .../python/stdlib/encodings/latin_1.py | 23 + .../python/stdlib/encodings/utf_8.py | 23 + .../python/stdlib/encodings/utf_8_sig.py | 23 + .../com/codename1/python/stdlib/enum.py | 321 +- .../com/codename1/python/stdlib/errno.py | 127 + .../com/codename1/python/stdlib/fractions.py | 9 +- .../com/codename1/python/stdlib/functools.py | 146 +- .../com/codename1/python/stdlib/gettext.py | 85 + .../com/codename1/python/stdlib/hashlib.py | 343 +- .../com/codename1/python/stdlib/heapq.py | 66 +- .../codename1/python/stdlib/html/parser.py | 451 + .../codename1/python/stdlib/http/__init__.py | 108 +- .../python/stdlib/importlib/__init__.py | 43 + .../python/stdlib/importlib/machinery.py | 29 + .../stdlib/importlib/metadata/__init__.py | 257 + .../codename1/python/stdlib/importlib/util.py | 53 + .../com/codename1/python/stdlib/inspect.py | 129 +- .../com/codename1/python/stdlib/io.py | 42 +- .../com/codename1/python/stdlib/ipaddress.py | 493 + .../com/codename1/python/stdlib/itertools.py | 289 +- .../com/codename1/python/stdlib/json.py | 53 + .../com/codename1/python/stdlib/keyword.py | 23 + .../com/codename1/python/stdlib/locale.py | 80 + .../python/stdlib/logging/__init__.py | 29 +- .../com/codename1/python/stdlib/mimetypes.py | 291 + .../com/codename1/python/stdlib/ntpath.py | 169 + .../com/codename1/python/stdlib/nturl2path.py | 41 + .../com/codename1/python/stdlib/operator.py | 78 +- .../codename1/python/stdlib/os/__init__.py | 150 +- .../com/codename1/python/stdlib/pathlib.py | 23 +- .../com/codename1/python/stdlib/pickle.py | 9 +- .../com/codename1/python/stdlib/platform.py | 130 + .../com/codename1/python/stdlib/posixpath.py | 45 + .../com/codename1/python/stdlib/pprint.py | 11 +- .../com/codename1/python/stdlib/queue.py | 4 + .../com/codename1/python/stdlib/random.py | 19 +- .../codename1/python/stdlib/re/__init__.py | 180 +- .../com/codename1/python/stdlib/re/_engine.py | 21 +- .../com/codename1/python/stdlib/readline.py | 160 + .../com/codename1/python/stdlib/runpy.py | 15 + .../com/codename1/python/stdlib/selectors.py | 71 + .../com/codename1/python/stdlib/shutil.py | 196 +- .../com/codename1/python/stdlib/signal.py | 118 + .../com/codename1/python/stdlib/socket.py | 259 + .../python/stdlib/sqlite3/__init__.py | 280 +- .../com/codename1/python/stdlib/ssl.py | 240 + .../com/codename1/python/stdlib/string.py | 27 +- .../com/codename1/python/stdlib/stringprep.py | 133 + .../com/codename1/python/stdlib/struct.py | 16 + .../com/codename1/python/stdlib/subprocess.py | 113 + .../com/codename1/python/stdlib/tempfile.py | 246 + .../com/codename1/python/stdlib/threading.py | 12 +- .../com/codename1/python/stdlib/time.py | 55 +- .../com/codename1/python/stdlib/types.py | 32 +- .../com/codename1/python/stdlib/typing.py | 290 +- .../codename1/python/stdlib/unicodedata.py | 543 + .../codename1/python/stdlib/urllib/parse.py | 179 +- .../com/codename1/python/stdlib/uuid.py | 80 +- .../com/codename1/python/stdlib/warnings.py | 6 +- .../com/codename1/python/stdlib/weakref.py | 3 + .../codename1/python/stdlib/xml/__init__.py | 5 + .../python/stdlib/xml/dom/NodeFilter.py | 31 + .../python/stdlib/xml/dom/__init__.py | 133 + .../codename1/python/stdlib/xml/dom/domreg.py | 68 + .../python/stdlib/xml/dom/expatbuilder.py | 789 + .../python/stdlib/xml/dom/minicompat.py | 61 + .../python/stdlib/xml/dom/minidom.py | 1757 ++ .../python/stdlib/xml/dom/pulldom.py | 333 + .../python/stdlib/xml/dom/xmlbuilder.py | 137 + .../python/stdlib/xml/etree/ElementPath.py | 361 + .../python/stdlib/xml/etree/ElementTree.py | 1073 ++ .../python/stdlib/xml/etree/__init__.py | 4 + .../python/stdlib/xml/parsers/__init__.py | 4 + .../stdlib/xml/parsers/expat/__init__.py | 1176 ++ .../python/stdlib/xml/parsers/expat/errors.py | 79 + .../python/stdlib/xml/parsers/expat/model.py | 16 + .../python/stdlib/xml/sax/__init__.py | 52 + .../python/stdlib/xml/sax/_exceptions.py | 72 + .../python/stdlib/xml/sax/expatreader.py | 350 + .../python/stdlib/xml/sax/handler.py | 112 + .../python/stdlib/xml/sax/saxutils.py | 302 + .../python/stdlib/xml/sax/xmlreader.py | 230 + .../com/codename1/python/stdlib/zipfile.py | 11 + .../python/transpiler/parser/NameAliases.txt | 579 + .../python/transpiler/runtime-names.txt | 1132 ++ .../python/transpiler/AliasLoweringTest.java | 84 + .../transpiler/ArgArrayFreeCallsTest.java | 121 + .../python/transpiler/ConformanceTest.java | 58 +- .../python/transpiler/DirectivesTest.java | 197 + .../codename1/python/transpiler/JvmSql.java | 57 +- .../python/transpiler/RuntimeNamesTest.java | 94 + .../python/transpiler/TypedShapeTest.java | 135 + .../python/transpiler/UnsupportedTest.java | 12 +- .../resources/conformance/accumulators.out | 5 + .../resources/conformance/accumulators.py | 62 + .../conformance/annotation_tables.out | 36 + .../conformance/annotation_tables.py | 60 + .../conformance/argparse_computed_dest.out | 11 + .../conformance/argparse_computed_dest.py | 33 + .../conformance/argparse_computed_dest.strict | 3 + .../resources/conformance/attrs_pkg.strict | 3 + .../resources/conformance/attrs_static.out | 91 + .../resources/conformance/attrs_static.py | 386 + .../conformance/attrs_value_deco.out | 1 + .../resources/conformance/attrs_value_deco.py | 4 + .../conformance/attrs_value_deco.strict | 1 + .../test/resources/conformance/bound_init.out | 15 + .../test/resources/conformance/bound_init.py | 57 + .../conformance/builtins_lowered.out | 33 + .../resources/conformance/builtins_lowered.py | 88 + .../resources/conformance/bytes_kinds.out | 34 + .../test/resources/conformance/bytes_kinds.py | 81 + .../resources/conformance/bytes_typed.out | 8 + .../test/resources/conformance/bytes_typed.py | 25 + .../conformance/call_dunder_typed.out | 6 + .../conformance/call_dunder_typed.py | 58 + .../conformance/call_global_tuple.out | 2 + .../conformance/call_global_tuple.py | 23 + .../conformance/class_arg_specialize.out | 3 + .../conformance/class_arg_specialize.py | 36 + .../conformance/class_constant_fold.out | 8 + .../conformance/class_constant_fold.py | 89 + .../resources/conformance/class_statics.out | 5 + .../resources/conformance/class_statics.py | 48 + .../conformance/classmethod_via_self.out | 1 + .../conformance/classmethod_via_self.py | 43 + .../conformance/closed_name_setattr.out | 2 + .../conformance/closed_name_setattr.py | 33 + .../resources/conformance/closure_params.out | 9 + .../resources/conformance/closure_params.py | 88 + .../test/resources/conformance/cobble_pkg.out | 10 + .../test/resources/conformance/cobble_pkg.py | 85 + .../resources/conformance/codec_roundtrip.out | 5 + .../resources/conformance/codec_roundtrip.py | 12 + .../test/resources/conformance/comptyped_.out | 13 + .../test/resources/conformance/comptyped_.py | 97 + .../conformance/const_arg_specialize.out | 3 + .../conformance/const_arg_specialize.py | 47 + .../conformance/csv_dialect_name.out | 3 + .../resources/conformance/csv_dialect_name.py | 4 + .../resources/conformance/dataclass_init.out | 20 + .../resources/conformance/dataclass_init.py | 94 + .../conformance/dict_subclass_missing.out | 4 + .../conformance/dict_subclass_missing.py | 41 + .../test/resources/conformance/dict_typed.out | 4 + .../test/resources/conformance/dict_typed.py | 73 + .../src/test/resources/conformance/enum_.out | 1 + .../src/test/resources/conformance/enum_.py | 17 + .../test/resources/conformance/etree_iter.out | 23 + .../test/resources/conformance/etree_iter.py | 33 + .../test/resources/conformance/fold_pct.out | 5 + .../test/resources/conformance/fold_pct.py | 51 + .../test/resources/conformance/gen_flat.out | 13 + .../test/resources/conformance/gen_flat.py | 71 + .../test/resources/conformance/gen_inline.out | 9 + .../test/resources/conformance/gen_inline.py | 114 + .../conformance/getattribute_dunder.strict | 2 + .../conformance/guessed_overrides.out | 17 + .../conformance/guessed_overrides.py | 127 + .../conformance/hashlib_blake2_blocks.out | 27 + .../conformance/hashlib_blake2_blocks.py | 21 + .../resources/conformance/hero_fastpaths.out | 34 + .../resources/conformance/hero_fastpaths.py | 135 + .../test/resources/conformance/hero_ports.out | 26 + .../test/resources/conformance/hero_ports.py | 167 + .../resources/conformance/immutable_slots.out | 8 + .../resources/conformance/immutable_slots.py | 125 + .../resources/conformance/introspect.strict | 1 + .../conformance/isinstance_mixin_base.out | 2 + .../conformance/isinstance_mixin_base.py | 42 + .../conformance/jinja_loader_names.strict | 1 + .../conformance/jinja_loader_names/main.py | 5 + .../jinja_loader_names/templates/page.html | 1 + .../conformance/jinja_loader_unseen.py | 4 + .../conformance/jinja_loader_unseen.strict | 1 + .../conformance/known_attr_names.out | 4 + .../resources/conformance/known_attr_names.py | 61 + .../resources/conformance/known_helpers_.out | 13 + .../known_helpers_/bs4/__init__.py | 10 + .../known_helpers_/bs4/_deprecation.py | 38 + .../conformance/known_helpers_/bs4/element.py | 29 + .../conformance/known_helpers_/main.py | 18 + .../resources/conformance/kwonly_logging.out | 6 + .../resources/conformance/kwonly_logging.py | 17 + .../resources/conformance/kwonly_typed.out | 14 + .../resources/conformance/kwonly_typed.py | 74 + .../test/resources/conformance/kwshared_.out | 11 + .../test/resources/conformance/kwshared_.py | 110 + .../test/resources/conformance/liveness_.out | 6 + .../conformance/liveness_/lp/__init__.py | 11 + .../liveness_/lp/backends/__init__.py | 0 .../liveness_/lp/backends/_fast.py | 1 + .../liveness_/lp/backends/_slow.py | 1 + .../conformance/liveness_/lp/chain.py | 3 + .../conformance/liveness_/lp/lazyattr.py | 1 + .../conformance/liveness_/lp/leaf.py | 1 + .../resources/conformance/liveness_/lp/mid.py | 3 + .../liveness_/lp/plugins/__init__.py | 0 .../conformance/liveness_/lp/plugins/alpha.py | 1 + .../conformance/liveness_/lp/plugins/beta.py | 1 + .../conformance/liveness_/lp/star.py | 3 + .../conformance/liveness_/lp/unused.py | 1 + .../resources/conformance/liveness_/main.py | 30 + .../resources/conformance/loop_unroll.out | 10 + .../test/resources/conformance/loop_unroll.py | 108 + .../conformance/loop_unroll_comp.out | 5 + .../resources/conformance/loop_unroll_comp.py | 63 + .../conformance/loop_unroll_fold.out | 2 + .../resources/conformance/loop_unroll_fold.py | 29 + .../conformance/loop_unroll_stores.out | 6 + .../conformance/loop_unroll_stores.py | 51 + .../conformance/metaclass_layout.out | 7 + .../resources/conformance/metaclass_layout.py | 95 + .../resources/conformance/method_patching.out | 6 + .../resources/conformance/method_patching.py | 104 + .../conformance/mixin_first_base.out | 6 + .../resources/conformance/mixin_first_base.py | 87 + .../resources/conformance/mixin_layouts.out | 7 + .../resources/conformance/mixin_layouts.py | 80 + .../resources/conformance/mixin_super_mro.out | 5 + .../resources/conformance/mixin_super_mro.py | 58 + .../resources/conformance/modnames_.strict | 3 + .../conformance/namedtuple_classes.out | 11 + .../conformance/namedtuple_classes.py | 64 + .../conformance/namedtuple_percent.out | 8 + .../conformance/namedtuple_percent.py | 19 + .../test/resources/conformance/new_copy.out | 7 + .../test/resources/conformance/new_copy.py | 120 + .../resources/conformance/new_copy.strict | 2 + .../conformance/object_init_call.out | 5 + .../resources/conformance/object_init_call.py | 74 + .../conformance/object_protocol_.strict | 2 + .../test/resources/conformance/openmix_.out | 7 + .../resources/conformance/openmix_/base.py | 33 + .../resources/conformance/openmix_/main.py | 49 + .../test/resources/conformance/oxmlreg_.out | 7 + .../conformance/oxmlreg_/lxml/__init__.py | 0 .../conformance/oxmlreg_/lxml/etree.py | 114 + .../resources/conformance/oxmlreg_/main.py | 24 + .../conformance/oxmlreg_/oxpkg/__init__.py | 27 + .../conformance/oxmlreg_/oxpkg/exc.py | 2 + .../conformance/oxmlreg_/oxpkg/ns.py | 129 + .../conformance/oxmlreg_/oxpkg/shapes.py | 55 + .../conformance/oxmlreg_/oxpkg/util.py | 116 + .../conformance/oxmlreg_/oxpkg/xmlchemy.py | 718 + .../conformance/patch_init_class.out | 2 + .../resources/conformance/patch_init_class.py | 12 + .../test/resources/conformance/pickle_.strict | 3 + .../resources/conformance/probe_rebound.out | 2 + .../resources/conformance/probe_rebound.py | 34 + .../conformance/protocol_runtime_.out | 8 + .../conformance/protocol_runtime_.py | 63 + .../conformance/pytest_monkeypatch.out | 6 + .../conformance/pytest_monkeypatch.py | 27 + .../pytest_monkeypatch_receiver.out | 5 + .../pytest_monkeypatch_receiver.py | 41 + .../test/resources/conformance/raise_jump.out | 3 + .../test/resources/conformance/raise_jump.py | 48 + .../resources/conformance/random_hashlib.out | 13 + .../resources/conformance/random_hashlib.py | 20 + .../test/resources/conformance/re_subn.out | 3 + .../src/test/resources/conformance/re_subn.py | 4 + .../resources/conformance/rebounddeco_.out | 2 + .../resources/conformance/rebounddeco_.py | 32 + .../conformance/reduce_protocol.strict | 3 + .../resources/conformance/scalar_probes.out | 5 + .../resources/conformance/scalar_probes.py | 49 + .../setattr_before_property.strict | 2 + .../test/resources/conformance/shelve_.strict | 3 + .../resources/conformance/slot_dispatch.out | 10 + .../resources/conformance/slot_dispatch.py | 101 + .../conformance/slot_dispatch.strict | 1 + .../test/resources/conformance/specdoor_.out | 6 + .../resources/conformance/specdoor_/main.py | 37 + .../resources/conformance/split_loops.out | 7 + .../test/resources/conformance/split_loops.py | 44 + .../test/resources/conformance/split_ws.out | 62 + .../test/resources/conformance/split_ws.py | 21 + .../conformance/sqlalchemy_model_init.out | 7 + .../conformance/sqlalchemy_model_init.py | 55 + .../test/resources/conformance/sqlite3_.out | 5 + .../test/resources/conformance/sqlite3_.py | 20 + .../resources/conformance/sqlite_scan.out | 14 + .../test/resources/conformance/sqlite_scan.py | 38 + .../conformance/starred_arg_reach.out | 6 + .../conformance/starred_arg_reach.py | 50 + .../test/resources/conformance/strings.out | 1 + .../src/test/resources/conformance/strings.py | 2 + .../conformance/super_mro_uniform.out | 7 + .../conformance/super_mro_uniform.py | 34 + .../resources/conformance/system_random.out | 13 + .../resources/conformance/system_random.py | 31 + .../resources/conformance/typed_lowerings.out | 14 + .../resources/conformance/typed_lowerings.py | 91 + .../conformance/typed_str_params.out | 92 + .../resources/conformance/typed_str_params.py | 119 + .../test/resources/conformance/typedcells.out | 8 + .../test/resources/conformance/typedcells.py | 130 + .../resources/conformance/typeddecorated.out | 5 + .../resources/conformance/typeddecorated.py | 77 + .../resources/conformance/typedfallback.out | 11 + .../resources/conformance/typedfallback.py | 122 + .../test/resources/conformance/typedgen.out | 19 + .../test/resources/conformance/typedgen.py | 165 + .../resources/conformance/typedlambda.out | 4 + .../test/resources/conformance/typedlambda.py | 34 + .../resources/conformance/typedlambda2.out | 3 + .../resources/conformance/typedlambda2.py | 27 + .../resources/conformance/typedloops2.out | 2 + .../test/resources/conformance/typedloops2.py | 22 + .../resources/conformance/typednesteddef.out | 4 + .../resources/conformance/typednesteddef.py | 92 + .../resources/conformance/typedrebound.out | 3 + .../resources/conformance/typedrebound.py | 31 + .../test/resources/conformance/typedstar.out | 5 + .../test/resources/conformance/typedstar.py | 44 + .../test/resources/conformance/typedstmts.out | 9 + .../test/resources/conformance/typedstmts.py | 108 + .../resources/conformance/typedsubaug.out | 4 + .../test/resources/conformance/typedsubaug.py | 38 + .../resources/conformance/typedunbound.out | 26 + .../resources/conformance/typedunbound.py | 187 + .../resources/conformance/typedwalrus.out | 4 + .../test/resources/conformance/typedwalrus.py | 45 + .../resources/conformance/typing_cast.out | 2 + .../test/resources/conformance/typing_cast.py | 30 + .../conformance/typing_cast_class.out | 2 + .../conformance/typing_cast_class.py | 32 + .../conformance/unbound_class_call.out | 3 + .../conformance/unbound_class_call.py | 63 + .../resources/conformance/unittest_.strict | 8 + .../conformance/unittest_mock_.strict | 22 + .../resources/conformance/weakref_.strict | 5 + .../test/resources/conformance/xdefault_.out | 9 + .../resources/conformance/xdefault_/base.py | 28 + .../resources/conformance/xdefault_/main.py | 57 + .../test/resources/conformance/xmixin_.out | 6 + .../resources/conformance/xmixin_/base.py | 19 + .../resources/conformance/xmixin_/detect.py | 23 + .../resources/conformance/xmixin_/main.py | 25 + .../test/resources/conformance/xmodsub_.out | 11 + .../resources/conformance/xmodsub_/base.py | 38 + .../resources/conformance/xmodsub_/main.py | 75 + .../test/resources/conformance/xmodtyped_.out | 12 + .../resources/conformance/xmodtyped_/attrs.py | 15 + .../conformance/xmodtyped_/elements.py | 64 + .../conformance/xmodtyped_/filters.py | 35 + .../resources/conformance/xmodtyped_/late.py | 10 + .../resources/conformance/xmodtyped_/main.py | 50 + .../test/resources/conformance/xshadow_.out | 4 + .../resources/conformance/xshadow_/base.py | 20 + .../resources/conformance/xshadow_/main.py | 18 + .../test/resources/conformance/xstore_.out | 5 + .../resources/conformance/xstore_/holder.py | 17 + .../resources/conformance/xstore_/main.py | 18 + .../resources/conformance/xstore_/poke.py | 7 + .../resources/conformance/yieldtyped_.out | 5 + .../test/resources/conformance/yieldtyped_.py | 58 + .../third-party/cpython/LICENSE.txt | 46 + .../third-party/pyyaml/LICENSE | 20 + scripts/python-bench/build_parparvm.sh | 57 +- scripts/python-bench/conformance_parparvm.sh | 9 +- scripts/python-bench/container/Containerfile | 37 + scripts/python-bench/container/run.sh | 23 + .../com/codename1/io/FileSystemStorage.java | 26 + scripts/python-bench/kernels/bytes_codec.py | 20 + scripts/python-bench/kernels/closures.py | 28 + scripts/python-bench/kernels/exceptions.py | 37 + scripts/python-bench/kernels/generators.py | 40 + scripts/python-bench/kernels/json_codec.py | 71 + scripts/python-bench/kernels/objects.py | 50 + scripts/python-bench/kernels/regex_text.py | 24 + scripts/python-bench/kernels/sqlite_rows.py | 61 + scripts/python-bench/kernels/str_ops.py | 24 + scripts/python-bench/kernels/xml_etree.py | 31 + scripts/python-bench/kernels/zz_closparts.py | 65 + scripts/python-bench/kernels/zz_core.py | 422 + scripts/python-bench/kernels/zz_esc.py | 188 + scripts/python-bench/kernels/zz_expat.py | 64 + scripts/python-bench/kernels/zz_gendrain.py | 50 + scripts/python-bench/kernels/zz_genparts.py | 120 + scripts/python-bench/kernels/zz_gz.py | 131 + scripts/python-bench/kernels/zz_insert.py | 13 + scripts/python-bench/kernels/zz_lam.py | 42 + scripts/python-bench/kernels/zz_nodb.py | 58 + scripts/python-bench/kernels/zz_pragma.py | 12 + scripts/python-bench/kernels/zz_re.py | 136 + scripts/python-bench/kernels/zz_recall.py | 117 + scripts/python-bench/kernels/zz_rehot.py | 186 + scripts/python-bench/kernels/zz_shapes.py | 157 + scripts/python-bench/kernels/zz_sqlconf.py | 173 + .../python-bench/kernels/zz_sqlconf_body.py | 152 + scripts/python-bench/run_bench.py | 8 +- scripts/python/gen-unicodedata.py | 140 + .../src/cn1_db_sqlite_impl.h | 324 + vm/ByteCodeTranslator/src/cn1_globals.h | 249 +- vm/ByteCodeTranslator/src/cn1_globals.m | 331 +- vm/ByteCodeTranslator/src/cn1_intrinsics.h | 126 +- vm/ByteCodeTranslator/src/cn1_sqlite3.c | 9 +- .../tools/translator/ByteCodeClass.java | 147 +- .../tools/translator/BytecodeMethod.java | 407 +- .../tools/translator/InlineIntrinsics.java | 6 + .../translator/JavascriptNativeRegistry.java | 4 + .../tools/translator/LambdaCarriers.java | 3 +- .../codename1/tools/translator/Parser.java | 56 +- .../bytecodes/ArrayLoadExpression.java | 29 +- .../bytecodes/BasicInstruction.java | 7 + .../translator/bytecodes/CustomInvoke.java | 5 +- .../translator/bytecodes/Instruction.java | 14 + .../bytecodes/LabelInstruction.java | 2 +- .../tools/translator/bytecodes/TryCatch.java | 4 +- .../translator/bytecodes/TypeInstruction.java | 18 +- .../tools/translator/bytecodes/VarOp.java | 13 + .../src/javascript/parparvm_runtime.js | 22 + vm/ByteCodeTranslator/src/nativeMethods.m | 605 +- vm/CLAUDE.md | 9 + vm/JavaAPI/src/java/lang/String.java | 190 +- vm/JavaAPI/src/java/lang/Throwable.java | 18 +- vm/backend/demo/dbcheck/com/demo/DbCheck.java | 58 + .../demo/selftest/com/demo/SelfTest.java | 5 + .../impl/javase/com/codename1/backend/Db.java | 140 +- .../parparvm/com/codename1/backend/Db.java | 534 +- vm/backend/native/cn1_backend_db.c | 178 + .../src/com/codename1/backend/Backend.java | 25 + .../src/com/codename1/backend/Database.java | 472 +- .../src/com/codename1/backend/DbPool.java | 6 +- .../src/com/codename1/backend/Tracing.java | 29 + .../src/com/codename1/cli/CommandLine.java | 6 + vm/benchmarks/run-gc-verify.sh | 55 +- .../src/com/bench/EarlyFreeAudit.java | 35 + vm/benchmarks/src/com/bench/GraceAudit.java | 81 +- .../src/com/bench/GraceAuditWorkload.java | 130 + vm/benchmarks/translate-and-build.sh | 3 +- vm/selfhost/compile-dist.sh | 23 +- vm/selfhost/reuse-objects.py | 64 + .../BulkConformanceIntegrationTest.java | 2 + .../translator/SetjmpFrameVolatileTest.java | 89 +- .../tools/translator/GcVerifyApp.java | 17 +- .../bulk/ConstantIndexRunChecks.java | 120 + 711 files changed, 117608 insertions(+), 7347 deletions(-) create mode 100644 CodenameOne/src/com/codename1/impl/SQLStatementCache.java create mode 100644 CodenameOne/src/com/codename1/impl/SqlFunctionBridge.java create mode 100644 CodenameOne/src/com/codename1/io/JSONParseException.java create mode 100644 CodenameOne/src/com/codename1/io/JSONValueFactory.java create mode 100644 maven/python-runtime/src/main/java/com/codename1/python/runtime/Abc.java create mode 100644 maven/python-runtime/src/main/java/com/codename1/python/runtime/Annotations.java create mode 100644 maven/python-runtime/src/main/java/com/codename1/python/runtime/ArgArrays.java create mode 100644 maven/python-runtime/src/main/java/com/codename1/python/runtime/Cn1Platform.java create mode 100644 maven/python-runtime/src/main/java/com/codename1/python/runtime/EnumMeta.java create mode 100644 maven/python-runtime/src/main/java/com/codename1/python/runtime/ExpatRun.java create mode 100644 maven/python-runtime/src/main/java/com/codename1/python/runtime/Functools.java create mode 100644 maven/python-runtime/src/main/java/com/codename1/python/runtime/HeapqBisect.java create mode 100644 maven/python-runtime/src/main/java/com/codename1/python/runtime/ItemWalk.java create mode 100644 maven/python-runtime/src/main/java/com/codename1/python/runtime/Itertools.java create mode 100644 maven/python-runtime/src/main/java/com/codename1/python/runtime/KeySite.java create mode 100644 maven/python-runtime/src/main/java/com/codename1/python/runtime/Operator.java create mode 100644 maven/python-runtime/src/main/java/com/codename1/python/runtime/PyAes.java create mode 100644 maven/python-runtime/src/main/java/com/codename1/python/runtime/PyBinascii.java create mode 100644 maven/python-runtime/src/main/java/com/codename1/python/runtime/PyCollections.java create mode 100644 maven/python-runtime/src/main/java/com/codename1/python/runtime/PyHashlib.java create mode 100644 maven/python-runtime/src/main/java/com/codename1/python/runtime/PyJson.java create mode 100644 maven/python-runtime/src/main/java/com/codename1/python/runtime/PyObjects.java create mode 100644 maven/python-runtime/src/main/java/com/codename1/python/runtime/PyPackageData.java create mode 100644 maven/python-runtime/src/main/java/com/codename1/python/runtime/PyStruct.java create mode 100644 maven/python-runtime/src/main/java/com/codename1/python/runtime/PyStructSeq.java create mode 100644 maven/python-runtime/src/main/java/com/codename1/python/runtime/RegexMatch.java create mode 100644 maven/python-runtime/src/main/java/com/codename1/python/runtime/StoreSite.java create mode 100644 maven/python-runtime/src/main/java/com/codename1/python/runtime/XmlScan.java create mode 100644 maven/python-runtime/third-party/unicode/LICENSE.txt create mode 100644 maven/python-transpiler/src/main/java/com/codename1/python/transpiler/analyze/GenInline.java create mode 100644 maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/AliasLowering.java create mode 100644 maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/ArgparseLowering.java create mode 100644 maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/AttrsLowering.java create mode 100644 maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/BuildTimeBases.java create mode 100644 maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/BuiltinSigs.java create mode 100644 maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/ClassArgSpecialize.java create mode 100644 maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/ClassDecoratorLowering.java delete mode 100644 maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/Closed.java create mode 100644 maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/ClosedNameSetattr.java create mode 100644 maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/CobbleLowering.java create mode 100644 maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/ColorValueLowering.java create mode 100644 maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/ConstArgSpecialize.java create mode 100644 maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/ConstantDefaults.java create mode 100644 maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/CustomPropertyLowering.java create mode 100644 maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/DataclassInit.java create mode 100644 maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/DeclarativeMap.java create mode 100644 maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/DictItemsSetattr.java create mode 100644 maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/Directives.java create mode 100644 maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/EntryPointTable.java create mode 100644 maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/EnumLowering.java create mode 100644 maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/FlaskProxyLowering.java create mode 100644 maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/GenTarget.java create mode 100644 maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/ImmutableSlots.java create mode 100644 maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/Jinja2Lowering.java create mode 100644 maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/KnownHelpers.java create mode 100644 maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/KwAttrInit.java create mode 100644 maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/LiteralAttrStore.java create mode 100644 maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/Liveness.java create mode 100644 maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/LoopUnroll.java create mode 100644 maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/NamedStyleLowering.java create mode 100644 maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/NamedTupleLowering.java create mode 100644 maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/OxmlDeclarative.java create mode 100644 maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/ProtocolChecks.java create mode 100644 maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/PydanticLowering.java create mode 100644 maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/PytestLowering.java create mode 100644 maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/SerialisableMethods.java create mode 100644 maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/SetNameDescriptor.java create mode 100644 maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/SqlAlchemyLowering.java create mode 100644 maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/StyleableLowering.java create mode 100644 maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/ThreadLocalLowering.java create mode 100644 maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/WholeProgram.java create mode 100644 maven/python-transpiler/src/main/resources/com/codename1/python/site/cobble/__init__.py create mode 100644 maven/python-transpiler/src/main/resources/com/codename1/python/site/cryptography/__init__.py create mode 100644 maven/python-transpiler/src/main/resources/com/codename1/python/site/cryptography/hazmat/__init__.py create mode 100644 maven/python-transpiler/src/main/resources/com/codename1/python/site/cryptography/hazmat/backends/__init__.py create mode 100644 maven/python-transpiler/src/main/resources/com/codename1/python/site/cryptography/hazmat/primitives/__init__.py create mode 100644 maven/python-transpiler/src/main/resources/com/codename1/python/site/cryptography/hazmat/primitives/ciphers/__init__.py create mode 100644 maven/python-transpiler/src/main/resources/com/codename1/python/site/cryptography/hazmat/primitives/ciphers/algorithms.py create mode 100644 maven/python-transpiler/src/main/resources/com/codename1/python/site/cryptography/hazmat/primitives/ciphers/modes.py create mode 100644 maven/python-transpiler/src/main/resources/com/codename1/python/site/httpx2/__init__.py create mode 100644 maven/python-transpiler/src/main/resources/com/codename1/python/site/httpx2/_config.py create mode 100644 maven/python-transpiler/src/main/resources/com/codename1/python/site/jiter/__init__.py create mode 100644 maven/python-transpiler/src/main/resources/com/codename1/python/site/lxml/__init__.py create mode 100644 maven/python-transpiler/src/main/resources/com/codename1/python/site/lxml/_xpath.py create mode 100644 maven/python-transpiler/src/main/resources/com/codename1/python/site/lxml/etree.py create mode 100644 maven/python-transpiler/src/main/resources/com/codename1/python/site/magika/__init__.py create mode 100644 maven/python-transpiler/src/main/resources/com/codename1/python/site/pydantic/fields.py create mode 100644 maven/python-transpiler/src/main/resources/com/codename1/python/site/pydantic_core/__init__.py create mode 100644 maven/python-transpiler/src/main/resources/com/codename1/python/site/pypdfium2/__init__.py create mode 100644 maven/python-transpiler/src/main/resources/com/codename1/python/site/pytest_httpx/__init__.py create mode 100644 maven/python-transpiler/src/main/resources/com/codename1/python/site/pytest_httpx2/__init__.py create mode 100644 maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/_interpqueues.py create mode 100644 maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/_interpreters.py create mode 100644 maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/_markupbase.py create mode 100644 maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/array.py create mode 100644 maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/ast.py rename maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/{asyncio.py => asyncio/__init__.py} (73%) create mode 100644 maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/asyncio/_transports.py create mode 100644 maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/asyncio/base_events.py create mode 100644 maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/asyncio/futures.py create mode 100644 maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/asyncio/subprocess.py create mode 100644 maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/calendar.py create mode 100644 maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/codecs.py create mode 100644 maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/contextvars.py create mode 100644 maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/difflib.py create mode 100644 maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/email/utils.py create mode 100644 maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/encodings/__init__.py create mode 100644 maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/encodings/aliases.py create mode 100644 maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/encodings/ascii.py create mode 100644 maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/encodings/latin_1.py create mode 100644 maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/encodings/utf_8.py create mode 100644 maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/encodings/utf_8_sig.py create mode 100644 maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/errno.py create mode 100644 maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/gettext.py create mode 100644 maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/html/parser.py create mode 100644 maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/importlib/__init__.py create mode 100644 maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/importlib/machinery.py create mode 100644 maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/importlib/metadata/__init__.py create mode 100644 maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/importlib/util.py create mode 100644 maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/ipaddress.py create mode 100644 maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/keyword.py create mode 100644 maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/locale.py create mode 100644 maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/mimetypes.py create mode 100644 maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/ntpath.py create mode 100644 maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/nturl2path.py create mode 100644 maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/platform.py create mode 100644 maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/posixpath.py create mode 100644 maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/readline.py create mode 100644 maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/runpy.py create mode 100644 maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/selectors.py create mode 100644 maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/signal.py create mode 100644 maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/socket.py create mode 100644 maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/ssl.py create mode 100644 maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/stringprep.py create mode 100644 maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/subprocess.py create mode 100644 maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/tempfile.py create mode 100644 maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/unicodedata.py create mode 100644 maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/xml/__init__.py create mode 100644 maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/xml/dom/NodeFilter.py create mode 100644 maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/xml/dom/__init__.py create mode 100644 maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/xml/dom/domreg.py create mode 100644 maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/xml/dom/expatbuilder.py create mode 100644 maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/xml/dom/minicompat.py create mode 100644 maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/xml/dom/minidom.py create mode 100644 maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/xml/dom/pulldom.py create mode 100644 maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/xml/dom/xmlbuilder.py create mode 100644 maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/xml/etree/ElementPath.py create mode 100644 maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/xml/etree/ElementTree.py create mode 100644 maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/xml/etree/__init__.py create mode 100644 maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/xml/parsers/__init__.py create mode 100644 maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/xml/parsers/expat/__init__.py create mode 100644 maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/xml/parsers/expat/errors.py create mode 100644 maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/xml/parsers/expat/model.py create mode 100644 maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/xml/sax/__init__.py create mode 100644 maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/xml/sax/_exceptions.py create mode 100644 maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/xml/sax/expatreader.py create mode 100644 maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/xml/sax/handler.py create mode 100644 maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/xml/sax/saxutils.py create mode 100644 maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/xml/sax/xmlreader.py create mode 100644 maven/python-transpiler/src/main/resources/com/codename1/python/transpiler/parser/NameAliases.txt create mode 100644 maven/python-transpiler/src/main/resources/com/codename1/python/transpiler/runtime-names.txt create mode 100644 maven/python-transpiler/src/test/java/com/codename1/python/transpiler/AliasLoweringTest.java create mode 100644 maven/python-transpiler/src/test/java/com/codename1/python/transpiler/ArgArrayFreeCallsTest.java create mode 100644 maven/python-transpiler/src/test/java/com/codename1/python/transpiler/DirectivesTest.java create mode 100644 maven/python-transpiler/src/test/java/com/codename1/python/transpiler/RuntimeNamesTest.java create mode 100644 maven/python-transpiler/src/test/java/com/codename1/python/transpiler/TypedShapeTest.java create mode 100644 maven/python-transpiler/src/test/resources/conformance/accumulators.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/accumulators.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/annotation_tables.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/annotation_tables.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/argparse_computed_dest.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/argparse_computed_dest.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/argparse_computed_dest.strict create mode 100644 maven/python-transpiler/src/test/resources/conformance/attrs_pkg.strict create mode 100644 maven/python-transpiler/src/test/resources/conformance/attrs_static.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/attrs_static.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/attrs_value_deco.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/attrs_value_deco.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/attrs_value_deco.strict create mode 100644 maven/python-transpiler/src/test/resources/conformance/bound_init.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/bound_init.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/builtins_lowered.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/builtins_lowered.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/bytes_kinds.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/bytes_kinds.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/bytes_typed.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/bytes_typed.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/call_dunder_typed.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/call_dunder_typed.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/call_global_tuple.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/call_global_tuple.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/class_arg_specialize.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/class_arg_specialize.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/class_constant_fold.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/class_constant_fold.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/class_statics.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/class_statics.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/classmethod_via_self.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/classmethod_via_self.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/closed_name_setattr.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/closed_name_setattr.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/closure_params.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/closure_params.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/cobble_pkg.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/cobble_pkg.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/codec_roundtrip.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/codec_roundtrip.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/comptyped_.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/comptyped_.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/const_arg_specialize.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/const_arg_specialize.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/csv_dialect_name.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/csv_dialect_name.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/dataclass_init.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/dataclass_init.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/dict_subclass_missing.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/dict_subclass_missing.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/dict_typed.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/dict_typed.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/etree_iter.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/etree_iter.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/fold_pct.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/fold_pct.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/gen_flat.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/gen_flat.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/gen_inline.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/gen_inline.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/getattribute_dunder.strict create mode 100644 maven/python-transpiler/src/test/resources/conformance/guessed_overrides.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/guessed_overrides.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/hashlib_blake2_blocks.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/hashlib_blake2_blocks.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/hero_fastpaths.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/hero_fastpaths.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/hero_ports.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/hero_ports.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/immutable_slots.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/immutable_slots.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/introspect.strict create mode 100644 maven/python-transpiler/src/test/resources/conformance/isinstance_mixin_base.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/isinstance_mixin_base.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/jinja_loader_names.strict create mode 100644 maven/python-transpiler/src/test/resources/conformance/jinja_loader_names/main.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/jinja_loader_names/templates/page.html create mode 100644 maven/python-transpiler/src/test/resources/conformance/jinja_loader_unseen.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/jinja_loader_unseen.strict create mode 100644 maven/python-transpiler/src/test/resources/conformance/known_attr_names.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/known_attr_names.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/known_helpers_.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/known_helpers_/bs4/__init__.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/known_helpers_/bs4/_deprecation.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/known_helpers_/bs4/element.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/known_helpers_/main.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/kwonly_logging.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/kwonly_logging.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/kwonly_typed.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/kwonly_typed.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/kwshared_.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/kwshared_.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/liveness_.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/liveness_/lp/__init__.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/liveness_/lp/backends/__init__.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/liveness_/lp/backends/_fast.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/liveness_/lp/backends/_slow.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/liveness_/lp/chain.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/liveness_/lp/lazyattr.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/liveness_/lp/leaf.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/liveness_/lp/mid.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/liveness_/lp/plugins/__init__.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/liveness_/lp/plugins/alpha.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/liveness_/lp/plugins/beta.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/liveness_/lp/star.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/liveness_/lp/unused.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/liveness_/main.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/loop_unroll.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/loop_unroll.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/loop_unroll_comp.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/loop_unroll_comp.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/loop_unroll_fold.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/loop_unroll_fold.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/loop_unroll_stores.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/loop_unroll_stores.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/metaclass_layout.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/metaclass_layout.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/method_patching.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/method_patching.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/mixin_first_base.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/mixin_first_base.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/mixin_layouts.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/mixin_layouts.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/mixin_super_mro.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/mixin_super_mro.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/modnames_.strict create mode 100644 maven/python-transpiler/src/test/resources/conformance/namedtuple_classes.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/namedtuple_classes.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/namedtuple_percent.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/namedtuple_percent.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/new_copy.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/new_copy.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/new_copy.strict create mode 100644 maven/python-transpiler/src/test/resources/conformance/object_init_call.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/object_init_call.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/object_protocol_.strict create mode 100644 maven/python-transpiler/src/test/resources/conformance/openmix_.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/openmix_/base.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/openmix_/main.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/oxmlreg_.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/oxmlreg_/lxml/__init__.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/oxmlreg_/lxml/etree.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/oxmlreg_/main.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/oxmlreg_/oxpkg/__init__.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/oxmlreg_/oxpkg/exc.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/oxmlreg_/oxpkg/ns.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/oxmlreg_/oxpkg/shapes.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/oxmlreg_/oxpkg/util.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/oxmlreg_/oxpkg/xmlchemy.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/patch_init_class.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/patch_init_class.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/pickle_.strict create mode 100644 maven/python-transpiler/src/test/resources/conformance/probe_rebound.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/probe_rebound.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/protocol_runtime_.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/protocol_runtime_.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/pytest_monkeypatch.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/pytest_monkeypatch.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/pytest_monkeypatch_receiver.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/pytest_monkeypatch_receiver.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/raise_jump.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/raise_jump.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/re_subn.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/re_subn.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/rebounddeco_.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/rebounddeco_.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/reduce_protocol.strict create mode 100644 maven/python-transpiler/src/test/resources/conformance/scalar_probes.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/scalar_probes.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/setattr_before_property.strict create mode 100644 maven/python-transpiler/src/test/resources/conformance/shelve_.strict create mode 100644 maven/python-transpiler/src/test/resources/conformance/slot_dispatch.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/slot_dispatch.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/slot_dispatch.strict create mode 100644 maven/python-transpiler/src/test/resources/conformance/specdoor_.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/specdoor_/main.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/split_loops.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/split_loops.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/split_ws.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/split_ws.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/sqlalchemy_model_init.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/sqlalchemy_model_init.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/sqlite_scan.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/sqlite_scan.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/starred_arg_reach.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/starred_arg_reach.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/super_mro_uniform.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/super_mro_uniform.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/system_random.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/system_random.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/typed_lowerings.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/typed_lowerings.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/typed_str_params.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/typed_str_params.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/typedcells.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/typedcells.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/typeddecorated.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/typeddecorated.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/typedfallback.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/typedfallback.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/typedgen.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/typedgen.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/typedlambda.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/typedlambda.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/typedlambda2.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/typedlambda2.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/typedloops2.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/typedloops2.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/typednesteddef.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/typednesteddef.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/typedrebound.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/typedrebound.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/typedstar.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/typedstar.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/typedstmts.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/typedstmts.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/typedsubaug.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/typedsubaug.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/typedunbound.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/typedunbound.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/typedwalrus.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/typedwalrus.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/typing_cast.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/typing_cast.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/typing_cast_class.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/typing_cast_class.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/unbound_class_call.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/unbound_class_call.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/unittest_.strict create mode 100644 maven/python-transpiler/src/test/resources/conformance/unittest_mock_.strict create mode 100644 maven/python-transpiler/src/test/resources/conformance/weakref_.strict create mode 100644 maven/python-transpiler/src/test/resources/conformance/xdefault_.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/xdefault_/base.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/xdefault_/main.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/xmixin_.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/xmixin_/base.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/xmixin_/detect.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/xmixin_/main.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/xmodsub_.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/xmodsub_/base.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/xmodsub_/main.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/xmodtyped_.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/xmodtyped_/attrs.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/xmodtyped_/elements.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/xmodtyped_/filters.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/xmodtyped_/late.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/xmodtyped_/main.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/xshadow_.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/xshadow_/base.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/xshadow_/main.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/xstore_.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/xstore_/holder.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/xstore_/main.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/xstore_/poke.py create mode 100644 maven/python-transpiler/src/test/resources/conformance/yieldtyped_.out create mode 100644 maven/python-transpiler/src/test/resources/conformance/yieldtyped_.py create mode 100644 maven/python-transpiler/third-party/cpython/LICENSE.txt create mode 100644 maven/python-transpiler/third-party/pyyaml/LICENSE create mode 100644 scripts/python-bench/container/Containerfile create mode 100755 scripts/python-bench/container/run.sh create mode 100644 scripts/python-bench/kernels/bytes_codec.py create mode 100644 scripts/python-bench/kernels/closures.py create mode 100644 scripts/python-bench/kernels/exceptions.py create mode 100644 scripts/python-bench/kernels/generators.py create mode 100644 scripts/python-bench/kernels/json_codec.py create mode 100644 scripts/python-bench/kernels/objects.py create mode 100644 scripts/python-bench/kernels/regex_text.py create mode 100644 scripts/python-bench/kernels/sqlite_rows.py create mode 100644 scripts/python-bench/kernels/str_ops.py create mode 100644 scripts/python-bench/kernels/xml_etree.py create mode 100644 scripts/python-bench/kernels/zz_closparts.py create mode 100644 scripts/python-bench/kernels/zz_core.py create mode 100644 scripts/python-bench/kernels/zz_esc.py create mode 100644 scripts/python-bench/kernels/zz_expat.py create mode 100644 scripts/python-bench/kernels/zz_gendrain.py create mode 100644 scripts/python-bench/kernels/zz_genparts.py create mode 100644 scripts/python-bench/kernels/zz_gz.py create mode 100644 scripts/python-bench/kernels/zz_insert.py create mode 100644 scripts/python-bench/kernels/zz_lam.py create mode 100644 scripts/python-bench/kernels/zz_nodb.py create mode 100644 scripts/python-bench/kernels/zz_pragma.py create mode 100644 scripts/python-bench/kernels/zz_re.py create mode 100644 scripts/python-bench/kernels/zz_recall.py create mode 100644 scripts/python-bench/kernels/zz_rehot.py create mode 100644 scripts/python-bench/kernels/zz_shapes.py create mode 100644 scripts/python-bench/kernels/zz_sqlconf.py create mode 100644 scripts/python-bench/kernels/zz_sqlconf_body.py create mode 100644 scripts/python/gen-unicodedata.py create mode 100644 vm/benchmarks/src/com/bench/EarlyFreeAudit.java create mode 100644 vm/benchmarks/src/com/bench/GraceAuditWorkload.java create mode 100755 vm/selfhost/reuse-objects.py create mode 100644 vm/tests/src/test/resources/com/codename1/tools/translator/bulk/ConstantIndexRunChecks.java diff --git a/.github/workflows/parparvm-tests.yml b/.github/workflows/parparvm-tests.yml index fddd50b3072..da8db419439 100644 --- a/.github/workflows/parparvm-tests.yml +++ b/.github/workflows/parparvm-tests.yml @@ -76,6 +76,8 @@ on: - 'CodenameOne/src/com/codename1/io/gzip/**' - 'CodenameOne/src/com/codename1/io/outbox/**' - 'CodenameOne/src/com/codename1/io/JSONParser.java' + - 'CodenameOne/src/com/codename1/io/JSONParseException.java' + - 'CodenameOne/src/com/codename1/io/JSONValueFactory.java' - 'CodenameOne/src/com/codename1/io/PrettyPrinter.java' - 'CodenameOne/src/com/codename1/io/JSONParseCallback.java' - 'CodenameOne/src/com/codename1/io/JSONSanitizer.java' @@ -180,6 +182,8 @@ on: - 'CodenameOne/src/com/codename1/io/gzip/**' - 'CodenameOne/src/com/codename1/io/outbox/**' - 'CodenameOne/src/com/codename1/io/JSONParser.java' + - 'CodenameOne/src/com/codename1/io/JSONParseException.java' + - 'CodenameOne/src/com/codename1/io/JSONValueFactory.java' - 'CodenameOne/src/com/codename1/io/PrettyPrinter.java' - 'CodenameOne/src/com/codename1/io/JSONParseCallback.java' - 'CodenameOne/src/com/codename1/io/JSONSanitizer.java' diff --git a/.github/workflows/python-bench.yml b/.github/workflows/python-bench.yml index fefafb5a670..83d7842f936 100644 --- a/.github/workflows/python-bench.yml +++ b/.github/workflows/python-bench.yml @@ -24,7 +24,9 @@ on: # The ParparVM arm translates and compiles with these. - 'vm/ByteCodeTranslator/**' - 'vm/JavaAPI/**' - - 'vm/selfhost/compile-dist.sh' + # The native arm is a Linux port application (embedded, headless). + - 'Ports/LinuxPort/**' + - 'maven/linux/**' # Transpiled Python runs on the core's classes (collections, io/gzip). - 'CodenameOne/src/**' - 'maven/core/**' @@ -83,7 +85,7 @@ jobs: JAVA_HOME="$JAVA_HOME_8" bash ../scripts/ci/retry.sh mvn -B -q install -DskipTests \ -Dmaven.javadoc.skip=true -Dmaven.source.skip=true \ -Dmaven.repo.local="$GITHUB_WORKSPACE/m2" \ - -pl core,python-transpiler,compat-testing,backend -am + -pl core,linux,python-transpiler,compat-testing,backend -am # Without -am: core was installed above, and re-resolving it here would # rebuild it on the wrong JDK. @@ -171,16 +173,19 @@ jobs: timeout-minutes: 60 env: PYBENCH_M2: ${{ github.workspace }}/m2 + CN1_DISPLAY: headless steps: - uses: actions/checkout@v4 - name: Use Google's copy of Maven Central first uses: ./.github/actions/maven-central-mirror - - name: Install clang + # clang, cmake and the libraries the embedded Linux port links. + - name: Install the native toolchain run: | bash scripts/ci/apt-get-update.sh - sudo apt-get install -y clang time + sudo apt-get install -y clang time cmake ninja-build pkg-config \ + libfreetype-dev libpng-dev libjpeg-dev zlib1g-dev libssl-dev libcurl4-openssl-dev # The translator runs on JDK 8, the generated Java compiles on JDK 17. - name: Set up JDK 8 @@ -224,11 +229,7 @@ jobs: run: scripts/python-bench/conformance_parparvm.sh - name: Measure and gate - # Each kernel's clang pass compiled one file at a time, six minutes - # a kernel. In parallel, with -flto=thin on the compile and the link, - # the binary is the one a single clang invocation makes. run: | - export CN1_COMPILE_JOBS="$(nproc)" python3 scripts/python-bench/parparvm_table.py --json python-bench-parparvm.json --check \ | tee -a "$GITHUB_STEP_SUMMARY" diff --git a/CodenameOne/src/com/codename1/annotations/Fused.java b/CodenameOne/src/com/codename1/annotations/Fused.java index e13f76ae883..f851727d82b 100644 --- a/CodenameOne/src/com/codename1/annotations/Fused.java +++ b/CodenameOne/src/com/codename1/annotations/Fused.java @@ -32,5 +32,6 @@ /// their pixel `int[]`/`byte[]` data. @Retention(RetentionPolicy.CLASS) @Target(ElementType.TYPE) +@com.codename1.impl.SharedWithBackend public @interface Fused { } diff --git a/CodenameOne/src/com/codename1/db/Database.java b/CodenameOne/src/com/codename1/db/Database.java index dad0542760d..c91c8c84be0 100644 --- a/CodenameOne/src/com/codename1/db/Database.java +++ b/CodenameOne/src/com/codename1/db/Database.java @@ -22,6 +22,8 @@ */ package com.codename1.db; +import java.util.function.Function; + import com.codename1.impl.CodenameOneImplementation; import com.codename1.impl.SQLStatementSplitter; import com.codename1.io.FileSystemStorage; @@ -204,6 +206,24 @@ public static Database openOrCreate(String databaseName) throws IOException { return Display.getInstance().openOrCreate(databaseName); } + /// Whether `#openInMemory()` is supported on this platform. + public static boolean isInMemorySupported() { + return Display.getInstance().isInMemoryDatabaseSupported(); + } + + /// Opens a new private database held entirely in memory: nothing is + /// written to storage, and the data is gone once it is closed. Each call + /// opens a database of its own. Faster than a file for scratch data, since + /// no transaction touches the disk. + /// + /// #### Throws + /// + /// - `IOException`: where the platform has no in-memory databases (see + /// `#isInMemorySupported()`) + public static Database openInMemory() throws IOException { + return Display.getInstance().openInMemoryDatabase(); + } + /// Indicates weather a database exists /// /// **NOTE:** Not supported in the Javascript port. Will always return false. @@ -819,6 +839,129 @@ public void changeKey(DatabaseConfig config) throws IOException { "Changing the database key is not supported on this platform"); } + /// A column of `row` in its storage class: null, a `Long`, a `Double`, a `String` or a + /// `byte[]`, as [Row#getColumnType(int)] reports it. + /// + /// Reading the type and then calling the matching getter does the same, but a cursor of the + /// SQLite ports answers this with one engine call per type and value instead of three, and + /// checks the cursor once instead of twice. A row whose engine reports no type + /// (`COLUMN_UNKNOWN`) answers the text. + /// + /// #### Parameters + /// + /// - `row`: the current row of a cursor + /// - `index`: the column, from 0 + /// + /// #### Returns + /// + /// the value, or null for SQL NULL + /// + /// #### Throws + /// + /// - `IOException`: if the value cannot be read + /// Every value of `row` into `out`, each as `#getValue(Row, int)` reads + /// it, in one step where the engine allows. Answers false where a + /// column's storage class cannot be told (`#COLUMN_UNKNOWN`) or the row is + /// not one of a database cursor, leaving `out` for the caller to fill its + /// own way. + /// + /// #### Throws + /// + /// - `IOException`: when the row cannot be read + public static boolean getValues(Row row, Object[] out) throws IOException { + if (row instanceof com.codename1.impl.AbstractDBCursor) { + return ((com.codename1.impl.AbstractDBCursor) row).getValues(out); + } + return false; + } + + public static Object getValue(Row row, int index) throws IOException { + if (row instanceof com.codename1.impl.AbstractDBCursor) { + return ((com.codename1.impl.AbstractDBCursor) row).getValue(index); + } + switch (row.getColumnType(index)) { + case COLUMN_NULL: + return null; + case COLUMN_INTEGER: + return Long.valueOf(row.getLong(index)); + case COLUMN_FLOAT: + return Double.valueOf(row.getDouble(index)); + case COLUMN_BLOB: + return row.getBlob(index); + default: + return row.getString(index); + } + } + + /// The number of rows the most recent INSERT, UPDATE or DELETE on this + /// connection changed, as SQLite's `changes()` reports it. + /// + /// The default implementation asks the engine with a query; ports whose + /// engine they call directly answer without one. + /// + /// #### Throws + /// + /// - `IOException`: if the engine cannot be asked + public long changes() throws IOException { + return queryLong("SELECT changes()"); + } + + /// The rowid of the most recent successful INSERT on this connection, as + /// SQLite's `last_insert_rowid()` reports it, or 0 when there was none. + /// + /// The default implementation asks the engine with a query; ports whose + /// engine they call directly answer without one. + /// + /// #### Throws + /// + /// - `IOException`: if the engine cannot be asked + public long lastInsertRowId() throws IOException { + return queryLong("SELECT last_insert_rowid()"); + } + + private long queryLong(String sql) throws IOException { + Cursor c = executeQuery(sql); + try { + return c.next() ? c.getRow().getLong(0) : 0; + } finally { + c.close(); + } + } + + /// True when [#createFunction(String, int, Function)] works on this + /// database. Android's framework SQLite has no API for it, and the + /// browser's database is not SQLite. + public boolean supportsFunctions() { + return false; + } + + /// Makes a Java function callable from SQL on this connection, under + /// `name` with `argCount` arguments (-1 for any number), replacing a + /// function of the same name and arity. A `null` function removes it. + /// + /// The function receives the arguments, each `null` (SQL NULL), a `Long`, a + /// `Double`, a `String` or a `byte[]`, and answers one of those same types; + /// a `Boolean` is stored as 1 or 0, and any other `Number` as a `Long` or a + /// `Double`. A `RuntimeException` it throws fails the statement with its + /// message. It runs on the thread stepping the statement, once for every + /// row the statement evaluates it on. + /// + /// Check [#supportsFunctions()] first: where the platform's engine can't + /// call back into the application (Android's framework SQLite has no API + /// for it), this throws and the caller has to compute the value itself. + /// + /// The default implementation reports that the platform cannot do it; it + /// is concrete rather than abstract because `Database` is subclassed + /// outside this repository. + /// + /// #### Throws + /// + /// - `IOException`: if the platform has no SQL functions, or the engine + /// refuses the definition + public void createFunction(String name, int argCount, Function function) throws IOException { + throw new IOException("SQL functions are not supported on this platform"); + } + /// `Row#getColumnType(int)`: the value is SQL NULL. public static final int COLUMN_NULL = 0; /// `Row#getColumnType(int)`: the value is stored as a signed integer. @@ -966,6 +1109,15 @@ protected void noteScriptTransactionControl(String sql) { if (sql == null) { return; } + if (isPlainStatement(sql)) { + return; + } + if (sql.indexOf(';') < 0 && !mayControlTransaction(sql)) { + if (mentionsAttachment(sql)) { + reconcileAttachments(); + } + return; + } String[] statements = SQLStatementSplitter.split(sql); for (String statement : statements) { String keyword = transactionControlKeyword(statement); @@ -1005,11 +1157,76 @@ protected void noteScriptTransactionControl(String sql) { /// Whether a script could have changed what is attached, cheaply enough to ask every time. private static boolean mentionsAttachment(String sql) { - String upper = sql.toUpperCase(); // Both words, because one is not a substring of the other: a standalone DETACH left the // reservation in place until the connection closed, and every delete, conversion and key - // change on that database was refused in the meantime. - return upper.indexOf("ATTACH") >= 0 || upper.indexOf("DETACH") >= 0; + // change on that database was refused in the meantime. Compared in place rather than + // through toUpperCase(), which allocates on every statement and folds by locale. + int last = sql.length() - 6; + for (int iter = 0; iter <= last; iter++) { + char c = sql.charAt(iter); + if ((c == 'A' || c == 'a') && sql.regionMatches(true, iter + 1, "TTACH", 0, 5)) { + return true; + } + if ((c == 'D' || c == 'd') && sql.regionMatches(true, iter + 1, "ETACH", 0, 5)) { + return true; + } + } + return false; + } + + /// SQL strings already found plain by [#isPlainStatement(String)], by identity. + private final String[] plainStatements = new String[8]; + private int plainNext; + + /// Whether `sql` is one statement that neither attaches nor detaches a database and + /// neither opens nor ends a transaction or savepoint: the statement nearly every call runs, + /// for which the attachment and transaction bookkeeping has nothing to do. + /// + /// Remembered by identity for the last few strings, so a statement an application keeps in a + /// constant (or a binding layer keeps in its statement cache) is read once rather than on + /// every execution. A string that is not plain is never remembered and is read each time. + /// + /// #### Parameters + /// + /// - `sql`: the SQL about to run + /// + /// #### Returns + /// + /// true when the bookkeeping may be skipped for it + protected final boolean isPlainStatement(String sql) { + if (sql == null) { + return false; + } + for (String known : plainStatements) { + if (known == sql) { //NOPMD CompareObjectsWithEquals - identity is the point + return true; + } + } + boolean plain = (sql.indexOf(';') < 0 || !SQLStatementSplitter.isMultiStatement(sql)) + && !mentionsAttachment(sql) && !mayControlTransaction(sql); + if (plain) { + plainStatements[plainNext] = sql; + plainNext = (plainNext + 1) % plainStatements.length; + } + return plain; + } + + /// Whether a single statement's leading keyword is `keyword`, an upper-case ASCII word, + /// compared in place. + private static boolean leadingKeywordIs(String statement, String keyword) { + int start = skipLeadingTrivia(statement, 0); + int end = start + keyword.length(); + return statement.regionMatches(true, start, keyword, 0, keyword.length()) + && (end >= statement.length() || !isKeywordChar(statement.charAt(end))); + } + + /// Whether a statement with no `;` in it could change the transaction or savepoint state, + /// read without splitting it or copying its keyword: nearly every statement an application + /// runs answers no, and this runs after each of them. + private static boolean mayControlTransaction(String statement) { + return leadingKeywordIs(statement, "BEGIN") || leadingKeywordIs(statement, "COMMIT") + || leadingKeywordIs(statement, "END") || leadingKeywordIs(statement, "ROLLBACK") + || leadingKeywordIs(statement, "SAVEPOINT") || leadingKeywordIs(statement, "RELEASE"); } /// The databases this connection has attached, by the schema name they were attached as. @@ -1082,7 +1299,8 @@ protected void reserveAttachments(String sql) throws IOException { // Every execute path on every port passes through here, which makes it the first place a // refusal from the previous statement's reconciliation can be thrown from. requireAttachmentsHeld(); - if (sql == null) { + if (sql == null || isPlainStatement(sql) || !mentionsAttachment(sql)) { + // No ATTACH anywhere in the text, so no statement of it can lead with one. return; } for (String statement : SQLStatementSplitter.split(sql)) { @@ -1181,7 +1399,8 @@ protected void reserveAttachments(String sql) throws IOException { /// - `IOException`: if a database it may attach is being deleted or converted protected void reserveAttachments(String sql, Object[] params) throws IOException { reserveAttachments(sql); - if (params == null || params.length == 0 || sql == null || !mentionsAttachment(sql)) { + if (params == null || params.length == 0 || sql == null || isPlainStatement(sql) + || !mentionsAttachment(sql)) { return; } if ("ATTACH".equals(leadingKeyword(sql))) { @@ -1566,7 +1785,7 @@ private static String[] attachmentTargetTokens(String statement) { String[] words = splitWords(statement.substring(leadingKeywordEnd(statement))); java.util.Vector target = new java.util.Vector(); for (String word : words) { - String upper = word.toUpperCase(); + String upper = upperAscii(word); if (target.isEmpty() && "DATABASE".equals(upper)) { // The optional keyword, which is not part of the filename. continue; @@ -2159,7 +2378,7 @@ protected void requireQueryStatement(String sql) throws IOException { // that only ever reads would otherwise never be told its ATTACH was undone, and would // read "no such table" as a database that has lost its contents. requireAttachmentsHeld(); - if (isLegacyBehavior() || sql == null) { + if (isLegacyBehavior() || sql == null || isPlainStatement(sql)) { return; } String keyword = leadingKeyword(sql); @@ -2762,6 +2981,69 @@ public void execute(String sql, Object... params) throws IOException { } } + /// The message of the last failure [#executeStatus(String, Object[], long[])] reported. + private String statusMessage; + + /// Runs an update statement and answers whether it succeeded, rather than throwing. + /// + /// The same statement and parameters as [#execute(String, Object...)], for a caller that runs + /// many statements in a loop. An exception unwinds through every frame that has a handler, and + /// on a native runtime each such frame pays for setting the handler up on every call, whether + /// or not anything throws; a port whose engine reports a status overrides this to check that + /// code instead, with no handler anywhere on the way. This implementation wraps the throwing + /// method, so every port answers the same thing. + /// + /// #### Parameters + /// + /// - `sql`: the sql to execute + /// + /// - `params`: the values to bind, as for [#execute(String, Object...)]; null for none + /// + /// - `counts`: null, or an array of at least two that receives, when the statement ran, what + /// [#changes()] and [#lastInsertRowId()] would answer next + /// + /// #### Returns + /// + /// 0 when the statement ran, otherwise a non-zero code; [#getStatusMessage()] then says why + public int executeStatus(String sql, Object[] params, long[] counts) { + try { + execute(sql, params); + if (counts != null) { + counts[0] = changes(); + counts[1] = lastInsertRowId(); + } + return 0; + } catch (IOException err) { + return failStatus(err.getMessage(), 1); + } + } + + /// The message of the last failure [#executeStatus(String, Object[], long[])] reported. + /// + /// #### Returns + /// + /// the message, or null if no failure was reported yet + public String getStatusMessage() { + return statusMessage; + } + + /// Records a failure for [#getStatusMessage()] and answers its code, for a port's + /// [#executeStatus(String, Object[], long[])]. + /// + /// #### Parameters + /// + /// - `message`: why the statement failed + /// + /// - `code`: the non-zero code to report + /// + /// #### Returns + /// + /// `code` + protected final int failStatus(String message, int code) { + statusMessage = message; + return code; + } + /// Renders parameters as text for ports that have not implemented typed binding. /// /// This is the fallback path only. Ports that can bind by type override the varargs methods diff --git a/CodenameOne/src/com/codename1/db/ThreadSafeDatabase.java b/CodenameOne/src/com/codename1/db/ThreadSafeDatabase.java index e3a3076f6fa..a2e5efa717f 100644 --- a/CodenameOne/src/com/codename1/db/ThreadSafeDatabase.java +++ b/CodenameOne/src/com/codename1/db/ThreadSafeDatabase.java @@ -23,6 +23,8 @@ package com.codename1.db; +import java.util.function.Function; + import com.codename1.util.EasyThread; import com.codename1.util.RunnableWithResultSync; @@ -320,6 +322,43 @@ public void run() throws IOException { }); } + @Override + public long changes() throws IOException { + return ((Long) invokeWithException(new RunnableWithResponseOrIOException() { + @Override + public Object run() throws IOException { + return Long.valueOf(underlying.changes()); + } + })).longValue(); + } + + @Override + public long lastInsertRowId() throws IOException { + return ((Long) invokeWithException(new RunnableWithResponseOrIOException() { + @Override + public Object run() throws IOException { + return Long.valueOf(underlying.lastInsertRowId()); + } + })).longValue(); + } + + @Override + public boolean supportsFunctions() { + return underlying.supportsFunctions(); + } + + @Override + public void createFunction(final String name, final int argCount, final Function function) + throws IOException { + // The function then runs on the worker too, the thread that steps every statement. + invokeWithException(new RunnableWithIOException() { + @Override + public void run() throws IOException { + underlying.createFunction(name, argCount, function); + } + }); + } + /// Closes the database on the worker, and shuts the worker down. /// /// Idempotent, and synchronous: it returns with the database closed, so a `delete()` on the diff --git a/CodenameOne/src/com/codename1/db/sql/MySql.java b/CodenameOne/src/com/codename1/db/sql/MySql.java index 732e46ce8a4..42268f2f8e4 100644 --- a/CodenameOne/src/com/codename1/db/sql/MySql.java +++ b/CodenameOne/src/com/codename1/db/sql/MySql.java @@ -674,15 +674,13 @@ private long executePrepared(int statementId, Object[] params, Column[] columns, readPacket(); // EOF ending the definitions if (rows != null) { String[] kinds = new String[resultColumns]; + String[] names = new String[resultColumns]; for (int iter = 0 ; iter < resultColumns ; iter++) { kinds[iter] = kind(resultDefinitions[iter].type); + names[iter] = resultDefinitions[iter].name; } rows.setColumnTypes(kinds); - String[] labels = new String[resultColumns]; - for (int iter = 0 ; iter < resultColumns ; iter++) { - labels[iter] = resultDefinitions[iter].name; - } - rows.setColumnNames(labels); + rows.setColumnNames(names); } while (true) { Packet packet = readPacket(); diff --git a/CodenameOne/src/com/codename1/db/sql/Placeholders.java b/CodenameOne/src/com/codename1/db/sql/Placeholders.java index 592d5cf9492..4f9c880f120 100644 --- a/CodenameOne/src/com/codename1/db/sql/Placeholders.java +++ b/CodenameOne/src/com/codename1/db/sql/Placeholders.java @@ -630,6 +630,25 @@ private static int terminator(String sql, int from, boolean nestedComments, at += 5; continue; } + if (isWordChar(c)) { + // ONE STEP PER WORD, not per character. This runs on every + // statement a backend executes, and asking for three keywords at + // every character was most of what a short INSERT cost to send. + // Stepping over the whole word is exact: every character inside + // a word is a word character whose predecessor is one too, so no + // keyword can match there and skip() acts on none of them (its + // only word-character case, a dollar quote, needs a non-word + // character before it). + int end = at + 1; + while (end < length && isWordChar(sql.charAt(end))) { + end++; + } + char first = (char) (c | 0x20); + if (first != 'b' && first != 'c' && first != 'e') { + at = end; + continue; + } + } if (isWord(sql, at, "begin")) { // ONLY A BLOCK BEGIN COUNTS. "BEGIN;" and "BEGIN TRANSACTION;" // open a TRANSACTION and are a whole statement on their own, so diff --git a/CodenameOne/src/com/codename1/db/sql/QueryRows.java b/CodenameOne/src/com/codename1/db/sql/QueryRows.java index da2d1b61734..7913d3a8164 100644 --- a/CodenameOne/src/com/codename1/db/sql/QueryRows.java +++ b/CodenameOne/src/com/codename1/db/sql/QueryRows.java @@ -63,6 +63,19 @@ public String[] getColumnNames() { return columnNames == null ? null : (String[]) columnNames.clone(); } + /// The column names themselves, not a copy, for a caller that only reads + /// them -- the generated DB-API connection does so on every statement, where + /// a copy per call was an allocation per statement. Must not be changed. + public String[] sharedColumnNames() { + return columnNames; + } + + /// Takes `columnNames` as it is rather than copying it; the caller hands over + /// an array nothing changes afterwards. + public void adoptColumnNames(String[] columnNames) { + this.columnNames = columnNames; + } + public void setColumnNames(String[] columnNames) { this.columnNames = columnNames == null ? null : (String[]) columnNames.clone(); } diff --git a/CodenameOne/src/com/codename1/impl/AbstractDBCursor.java b/CodenameOne/src/com/codename1/impl/AbstractDBCursor.java index 4cbde36cdae..4d732a4a3c1 100644 --- a/CodenameOne/src/com/codename1/impl/AbstractDBCursor.java +++ b/CodenameOne/src/com/codename1/impl/AbstractDBCursor.java @@ -508,6 +508,111 @@ public int getColumnType(int index) throws IOException { return cachedColumnType(index); } + /// Every value of the current row into `out`, each as `#getValue(int)` + /// reads it, in one step where the engine can (`#readRow(Object[])`). + /// Answers false, with `out` unspecified, where a column's storage class + /// cannot be told (`Database#COLUMN_UNKNOWN`), for the caller to read + /// those its own way. + /// + /// #### Throws + /// + /// - `IOException`: when the cursor is closed, not on a row, or `out` is + /// shorter than the row + public boolean getValues(Object[] out) throws IOException { + checkOpen(); + if (!onRow) { + throw new IOException("The cursor is not on a row"); + } + if (knownColumnCount < 0) { + knownColumnCount = columnCount(); + } + int n = knownColumnCount; + if (out.length < n) { + throw new IOException("The array holds " + out.length + " values and the row has " + n); + } + anythingRead = true; + if (!readByGetter() && readRow(out)) { + lastReadWasNull = n > 0 && out[n - 1] == null; + return true; + } + for (int i = 0; i < n; i++) { + if (cachedColumnType(i) == Database.COLUMN_UNKNOWN) { + return false; + } + out[i] = getValue(i); + } + return true; + } + + /// Whether a getter has already read a value of this row; a type taken + /// after that may describe the converted value, not the stored one. + private boolean readByGetter() { + if (typeStamps != null) { + for (int stamp : typeStamps) { + if (stamp == rowStamp) { + return true; + } + } + } + return false; + } + + /// Reads the whole current row into `out` -- null, `Long`, `Double`, + /// `String` or `byte[]` by storage class -- for `#getValues(Object[])`. + /// Answers false where the engine has no such read, the default; the + /// caller has checked the cursor and the length. + protected boolean readRow(Object[] out) throws IOException { + return false; + } + + /// The value of a column on the current row in its storage class: null, a `Long`, a + /// `Double`, a `String` or a `byte[]`, with one engine call for the type and one for the + /// value. A cursor whose engine cannot report types answers the text, as `getString` would. + /// + /// Behind [com.codename1.db.Database#getValue(com.codename1.db.Row, int)], which is the + /// public way to reach it. + /// + /// #### Parameters + /// + /// - `index`: the column, from 0 + /// + /// #### Returns + /// + /// the value, or null for SQL NULL + /// + /// #### Throws + /// + /// - `IOException`: if the cursor is closed, not on a row, or the index is out of range + public Object getValue(int index) throws IOException { + checkOpen(); + if (!onRow) { + throw new IOException("The cursor is not on a row"); + } + checkColumn(index); + anythingRead = true; + int type = cachedColumnType(index); + switch (type) { + case Database.COLUMN_NULL: + lastReadWasNull = true; + return null; + case Database.COLUMN_INTEGER: + lastReadWasNull = false; + return Long.valueOf(readLong(index)); + case Database.COLUMN_FLOAT: + lastReadWasNull = false; + return Double.valueOf(readDouble(index)); + case Database.COLUMN_TEXT: + lastReadWasNull = false; + return readString(index); + case Database.COLUMN_BLOB: + lastReadWasNull = false; + return readBlob(index); + default: + lastReadWasNull = isNullAt(index); + return lastReadWasNull ? null : readString(index); + } + } + /// Guards a value read and updates the null latch. private void beginRead(int index) throws IOException { checkOpen(); diff --git a/CodenameOne/src/com/codename1/impl/CodenameOneImplementation.java b/CodenameOne/src/com/codename1/impl/CodenameOneImplementation.java index 4c450a6b76a..80d323375a7 100644 --- a/CodenameOne/src/com/codename1/impl/CodenameOneImplementation.java +++ b/CodenameOne/src/com/codename1/impl/CodenameOneImplementation.java @@ -11169,6 +11169,20 @@ public Database openOrCreateDB(String databaseName) throws IOException { return null; } + /// Whether `#openInMemoryDB()` is supported on this platform. + public boolean isInMemoryDatabaseSupported() { + return false; + } + + /// Opens a new private database held in memory, gone once closed. + /// + /// #### Throws + /// + /// - `IOException`: where the platform has no in-memory databases + public Database openInMemoryDB() throws IOException { + throw new IOException("In-memory databases are not supported on this platform"); + } + /// Opens or creates an encrypted database. /// /// Ports that support encryption override this. The default implementation handles the diff --git a/CodenameOne/src/com/codename1/impl/SQLStatementCache.java b/CodenameOne/src/com/codename1/impl/SQLStatementCache.java new file mode 100644 index 00000000000..7cbdd1de36a --- /dev/null +++ b/CodenameOne/src/com/codename1/impl/SQLStatementCache.java @@ -0,0 +1,91 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.impl; + +/// Prepared statements a C-backed SQLite port keeps between executions of the same SQL. +/// +/// Preparing is parsing: for a short INSERT it costs more than running it, and code that writes +/// a row at a time sends the same text again and again. The port takes a statement out with +/// `take`, runs and resets it, and hands it back with `put`; a statement is never in the cache +/// while it runs, so a failure leaves nothing half-stepped behind -- the port finalizes it +/// instead of returning it. Statement handles are opaque here, the port finalizes whatever `put` +/// evicts and everything `drain` returns, and must drain before closing the connection, because +/// SQLite refuses to close one with a statement still alive. +public final class SQLStatementCache { + private static final int SIZE = 16; + private final String[] sql = new String[SIZE]; + private final long[] stmt = new long[SIZE]; + private int next; + + /// The cached statement for `text`, removed from the cache, or 0 when there is none. + public long take(String text) { + for (int iter = 0; iter < SIZE; iter++) { + String s = sql[iter]; + // Identity first: callers usually pass the same string object each time. + if (s != null && (s == text || s.equals(text))) { //NOPMD CompareObjectsWithEquals - identity is the fast path, equals follows + long out = stmt[iter]; + sql[iter] = null; + stmt[iter] = 0; + return out; + } + } + return 0; + } + + /// Caches a reset statement for `text`, and answers the statement it displaced, which the + /// caller must finalize, or 0. + public long put(String text, long statement) { + for (int iter = 0; iter < SIZE; iter++) { + if (sql[iter] == null) { + sql[iter] = text; + stmt[iter] = statement; + return 0; + } + } + long evicted = stmt[next]; + sql[next] = text; + stmt[next] = statement; + next = (next + 1) % SIZE; + return evicted; + } + + /// Empties the cache and answers every statement it held, for the caller to finalize. + public long[] drain() { + int count = 0; + for (int iter = 0; iter < SIZE; iter++) { + if (sql[iter] != null) { + count++; + } + } + long[] out = new long[count]; + int pos = 0; + for (int iter = 0; iter < SIZE; iter++) { + if (sql[iter] != null) { + out[pos++] = stmt[iter]; + sql[iter] = null; + stmt[iter] = 0; + } + } + return out; + } +} diff --git a/CodenameOne/src/com/codename1/impl/SQLStatementSplitter.java b/CodenameOne/src/com/codename1/impl/SQLStatementSplitter.java index 277430b777c..719cf74efc5 100644 --- a/CodenameOne/src/com/codename1/impl/SQLStatementSplitter.java +++ b/CodenameOne/src/com/codename1/impl/SQLStatementSplitter.java @@ -67,6 +67,13 @@ public static String[] split(String sql) { if (sql == null) { return new String[0]; } + if (sql.indexOf(';') < 0) { + // A statement ends only at a semicolon, so text without one is a single candidate: + // what the scan below would answer, without the scan. Every execute on every port + // splits its SQL more than once (attachments, transaction control, the + // single-statement check), and almost all of it is one statement. + return hasContent(sql) ? new String[] {sql.trim()} : new String[0]; + } int length = sql.length(); int statementStart = 0; boolean sawCreate = false; @@ -564,16 +571,15 @@ private static boolean isParameterNamePart(char c) { } private static void addIfNotBlank(List statements, String candidate) { - String trimmed = stripToContent(candidate); - if (trimmed.length() > 0) { + if (hasContent(candidate)) { statements.add(candidate.trim()); } } /// Returns the statement with comments and whitespace removed, purely to decide whether it /// carries any actual SQL. A chunk that is only a trailing comment is not a statement. - private static String stripToContent(String sql) { - StringBuilder out = new StringBuilder(); + /// True when the text holds anything but whitespace and comments. + private static boolean hasContent(String sql) { int length = sql.length(); int iter = 0; while (iter < length) { @@ -587,11 +593,11 @@ private static String stripToContent(String sql) { continue; } if (c > ' ') { - out.append(c); + return true; } iter++; } - return out.toString(); + return false; } private static int skipQuoted(String sql, int openIndex, char quote) { diff --git a/CodenameOne/src/com/codename1/impl/SqlFunctionBridge.java b/CodenameOne/src/com/codename1/impl/SqlFunctionBridge.java new file mode 100644 index 00000000000..7a2b0c5f517 --- /dev/null +++ b/CodenameOne/src/com/codename1/impl/SqlFunctionBridge.java @@ -0,0 +1,143 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.impl; + +import java.util.function.Function; +import com.codename1.util.StringUtil; + +import java.util.ArrayList; + +/// What every port whose database is SQLite in C shares to call a +/// [Function]: the table that turns the id SQLite holds into the function, +/// and the conversion of arguments and the result. A port supplies only the +/// natives that read an argument and set the result. +/// +/// The engine calls back on the thread that steps the statement, and a +/// connection is used by one thread at a time, so the table is never touched +/// by two threads at once. +public abstract class SqlFunctionBridge { + /// `sqlite3_value_type`: SQLITE_INTEGER. + public static final int SQLITE_INTEGER = 1; + /// `sqlite3_value_type`: SQLITE_FLOAT. + public static final int SQLITE_FLOAT = 2; + /// `sqlite3_value_type`: SQLITE_TEXT. + public static final int SQLITE_TEXT = 3; + /// `sqlite3_value_type`: SQLITE_BLOB. + public static final int SQLITE_BLOB = 4; + + private final ArrayList> functions = new ArrayList>(); + + /// The id the engine is handed for a function. Ids are never reused, so a + /// statement still holding an old one cannot reach a later function. + public int register(Function function) { + functions.add(function); + return functions.size() - 1; + } + + /// Called from the native trampoline, while the engine waits, to compute + /// one value of function `id` and hand it back through `ctx`. + public void call(long ctx, int id, int argc, long argv) { + // Looked up outside the try: the cast the generic get carries must not + // sit under a handler (ParparVM does not check it, see check-cast-semantics.sh). + Function f = id >= 0 && id < functions.size() ? functions.get(id) : null; + if (f == null) { + resultError(ctx, StringUtil.getBytes("no such function")); + return; + } + try { + Object[] args = new Object[argc]; + for (int i = 0; i < argc; i++) { + args[i] = argument(argv, i); + } + result(ctx, f.apply(args)); + } catch (Throwable t) { //NOPMD AvoidCatchingThrowable - an exception must not unwind through SQLite's C frames + String m = t.getMessage(); + resultError(ctx, StringUtil.getBytes(m == null ? t.toString() : m)); + } + } + + private Object argument(long argv, int i) { + switch (valueType(argv, i)) { + case SQLITE_INTEGER: + return Long.valueOf(valueLong(argv, i)); + case SQLITE_FLOAT: + return Double.valueOf(valueDouble(argv, i)); + case SQLITE_TEXT: + return StringUtil.newString(valueText(argv, i)); + case SQLITE_BLOB: + byte[] b = valueBlob(argv, i); + return b == null ? new byte[0] : b; + default: + return null; + } + } + + private void result(long ctx, Object v) { + if (v == null) { + resultNull(ctx); + } else if (v instanceof Boolean) { + resultLong(ctx, ((Boolean) v).booleanValue() ? 1 : 0); + } else if (v instanceof Double || v instanceof Float) { + resultDouble(ctx, ((Number) v).doubleValue()); + } else if (v instanceof Number) { + resultLong(ctx, ((Number) v).longValue()); + } else if (v instanceof byte[]) { + resultBlob(ctx, (byte[]) v); + } else { + resultText(ctx, StringUtil.getBytes(v.toString())); + } + } + + /// `sqlite3_value_type` of argument `i`. + protected abstract int valueType(long argv, int i); + + /// `sqlite3_value_int64` of argument `i`. + protected abstract long valueLong(long argv, int i); + + /// `sqlite3_value_double` of argument `i`. + protected abstract double valueDouble(long argv, int i); + + /// The UTF-8 text of argument `i`. + protected abstract byte[] valueText(long argv, int i); + + /// The bytes of argument `i`. + protected abstract byte[] valueBlob(long argv, int i); + + /// `sqlite3_result_null`. + protected abstract void resultNull(long ctx); + + /// `sqlite3_result_int64`. + protected abstract void resultLong(long ctx, long v); + + /// `sqlite3_result_double`. + protected abstract void resultDouble(long ctx, double v); + + /// `sqlite3_result_text` of UTF-8 bytes. + protected abstract void resultText(long ctx, byte[] utf8); + + /// `sqlite3_result_blob`. + protected abstract void resultBlob(long ctx, byte[] v); + + /// `sqlite3_result_error` of a UTF-8 message. + protected abstract void resultError(long ctx, byte[] utf8); +} diff --git a/CodenameOne/src/com/codename1/io/JSONParseException.java b/CodenameOne/src/com/codename1/io/JSONParseException.java new file mode 100644 index 00000000000..bfb2259dadb --- /dev/null +++ b/CodenameOne/src/com/codename1/io/JSONParseException.java @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.io; + +import java.io.IOException; + +/// Thrown by [JSONParser#parseStrict(String)] and its overloads for a document +/// that is not JSON, carrying where in the text reading stopped. +@com.codename1.impl.SharedWithBackend +public class JSONParseException extends IOException { + private final int offset; + + /// Creates the exception. + /// + /// #### Parameters + /// + /// - `message`: what was wrong + /// + /// - `offset`: the character offset at which it was found, or -1 + public JSONParseException(String message, int offset) { + super(message); + this.offset = offset; + } + + /// The character offset in the document at which the error was found. + /// + /// #### Returns + /// + /// the offset, or -1 when no single position applies + public int getOffset() { + return offset; + } +} diff --git a/CodenameOne/src/com/codename1/io/JSONParser.java b/CodenameOne/src/com/codename1/io/JSONParser.java index d7dd85fd8ae..93ab17df45f 100644 --- a/CodenameOne/src/com/codename1/io/JSONParser.java +++ b/CodenameOne/src/com/codename1/io/JSONParser.java @@ -905,8 +905,47 @@ private static void writeJsonValue(StringBuilder sb, Object o) { } private static void writeJsonString(StringBuilder sb, String s) { + appendQuoted(sb, s, false); + } + + private static final char[] HEX_DIGITS = "0123456789abcdef".toCharArray(); + + /// Appends `s` to `sb` as a quoted JSON string. + /// + /// `"`, `\` and the control characters below U+0020 are escaped, the + /// common ones by their short forms. With `asciiOnly` every character above + /// U+007E is written as a backslash-u escape too (a supplementary character as its + /// surrogate pair), so the output is pure ASCII whatever the input. A string + /// that needs no escape is appended in one call. + /// + /// #### Parameters + /// + /// - `sb`: the destination + /// + /// - `s`: the string to write + /// + /// - `asciiOnly`: true to escape everything outside printable ASCII + public static void appendQuoted(StringBuilder sb, String s, boolean asciiOnly) { + int n = s.length(); + char limit = asciiOnly ? (char) 0x7f : (char) 0xffff; + int i = 0; + while (i < n) { + char c = s.charAt(i); + if (c < 0x20 || c == '"' || c == '\\' || c >= limit) { + break; + } + i++; + } sb.append('"'); - for (int i = 0; i < s.length(); i++) { + if (i == n) { + sb.append(s); + sb.append('"'); + return; + } + if (i > 0) { + sb.append(s, 0, i); + } + for (; i < n; i++) { char c = s.charAt(i); switch (c) { case '"': @@ -931,13 +970,10 @@ private static void writeJsonString(StringBuilder sb, String s) { sb.append("\\t"); break; default: - if (c < 0x20) { - sb.append("\\u"); - String h = Integer.toHexString(c); - for (int p = h.length(); p < 4; p++) { - sb.append('0'); - } - sb.append(h); + if (c < 0x20 || c >= limit) { + sb.append('\\').append('u') + .append(HEX_DIGITS[c >> 12 & 15]).append(HEX_DIGITS[c >> 8 & 15]) + .append(HEX_DIGITS[c >> 4 & 15]).append(HEX_DIGITS[c & 15]); } else { sb.append(c); } @@ -1532,20 +1568,54 @@ public static Object parseStrict(String json) throws IOException { /// /// - `IOException`: for a null or malformed document, naming the offset public static Object parseStrict(String json, boolean exactIntegers) throws IOException { + return parseStrict(json, exactIntegers ? EXACT_INTEGERS : DEFAULT_VALUES); + } + + /// Parses one complete JSON document strictly, as [#parseStrict(String)] + /// does, building every value with `factory`. + /// + /// The factory decides what an object, an array and each scalar become, so a + /// caller can read a document straight into its own types; see + /// [JSONValueFactory]. Errors throw a [JSONParseException] naming the offset. + /// + /// #### Parameters + /// + /// - `json`: the document + /// + /// - `factory`: builds the values + /// + /// #### Returns + /// + /// the value the factory built for the document's top-level value + /// + /// #### Throws + /// + /// - `IOException`: for a null or malformed document + public static Object parseStrict(String json, JSONValueFactory factory) throws IOException { if (json == null) { - throw new IOException("No JSON to parse"); + throw new JSONParseException("No JSON to parse", -1); } - StrictReader p = new StrictReader(json, exactIntegers); + StrictReader p = new StrictReader(json, factory); p.skipWhitespace(); Object value = p.readValue(); p.skipWhitespace(); if (p.pos < json.length()) { - throw new IOException("Trailing content at offset " + p.pos); + throw new JSONParseException("Trailing content at offset " + p.pos, p.pos); } return value; } - /// The recursive-descent reader behind [#parseStrict(String, boolean)]. + private static final JSONValueFactory DEFAULT_VALUES = new JSONValueFactory(); + + /// What `exactIntegers` asks for: an integer beyond a long as [RawJson]. + private static final JSONValueFactory EXACT_INTEGERS = new JSONValueFactory() { + @Override + public Object bigInteger(String digits) { + return new RawJson(digits); + } + }; + + /// The recursive-descent reader behind [#parseStrict(String, JSONValueFactory)]. private static final class StrictReader { /// How deep a document may nest before it is refused. The reader is /// recursive, so nesting depth is stack depth, and a server parses whatever @@ -1558,18 +1628,29 @@ private static final class StrictReader { private static final int MAX_DEPTH = 512; private final String src; - private final boolean exactIntegers; + private final int len; + private final JSONValueFactory factory; + private final boolean nonFinite; + private final boolean controls; private int pos; private int depth; + private StringBuilder scratch; //NOPMD AvoidStringBufferField - one parse's string scratch, dropped with the reader - StrictReader(String src, boolean exactIntegers) { + StrictReader(String src, JSONValueFactory factory) { this.src = src; - this.exactIntegers = exactIntegers; + this.len = src.length(); + this.factory = factory; + this.nonFinite = factory.allowNonFinite(); + this.controls = factory.allowControlCharacters(); + } + + private static JSONParseException error(String message, int at) { + return new JSONParseException(message + " at offset " + at, at); } Object readValue() throws IOException { - if (pos >= src.length()) { - throw new IOException("Unexpected end of JSON"); + if (pos >= len) { + throw error("Unexpected end of JSON", pos); } char c = src.charAt(pos); switch (c) { @@ -1578,13 +1659,34 @@ Object readValue() throws IOException { case '[': return readNested(false); case '"': - return readString(); + return factory.string(readString()); case 't': - return readLiteral("true", Boolean.TRUE); + readLiteral("true"); + return factory.bool(true); case 'f': - return readLiteral("false", Boolean.FALSE); + readLiteral("false"); + return factory.bool(false); case 'n': - return readLiteral("null", null); + readLiteral("null"); + return factory.nullValue(); + case 'N': + if (nonFinite) { + readLiteral("NaN"); + return factory.decimal(Double.NaN); + } + return readNumber(); + case 'I': + if (nonFinite) { + readLiteral("Infinity"); + return factory.decimal(Double.POSITIVE_INFINITY); + } + return readNumber(); + case '-': + if (nonFinite && src.startsWith("-Infinity", pos)) { + pos += 9; + return factory.decimal(Double.NEGATIVE_INFINITY); + } + return readNumber(); default: return readNumber(); } @@ -1592,7 +1694,7 @@ Object readValue() throws IOException { private Object readNested(boolean object) throws IOException { if (depth >= MAX_DEPTH) { - throw new IOException("JSON nested deeper than " + MAX_DEPTH); + throw error("JSON nested deeper than " + MAX_DEPTH, pos); } depth++; try { @@ -1605,58 +1707,58 @@ private Object readNested(boolean object) throws IOException { } } - private Map readObject() throws IOException { - Map out = new LinkedHashMap(); + private Object readObject() throws IOException { + Object out = factory.newObject(); pos++; skipWhitespace(); if (peek() == '}') { pos++; - return out; + return factory.endObject(out); } while (true) { skipWhitespace(); if (peek() != '"') { - throw new IOException("Expected a key at offset " + pos); + throw error("Expected a key", pos); } - String key = readString(); + String key = readKey(); skipWhitespace(); if (peek() != ':') { - throw new IOException("Expected ':' at offset " + pos); + throw error("Expected ':'", pos); } pos++; skipWhitespace(); - out.put(key, readValue()); + factory.put(out, key, readValue()); skipWhitespace(); char c = peek(); pos++; if (c == '}') { - return out; + return factory.endObject(out); } if (c != ',') { - throw new IOException("Expected ',' or '}' at offset " + (pos - 1)); + throw error("Expected ',' or '}'", pos - 1); } } } - private List readArray() throws IOException { - List out = new ArrayList(); + private Object readArray() throws IOException { + Object out = factory.newArray(); pos++; skipWhitespace(); if (peek() == ']') { pos++; - return out; + return factory.endArray(out); } while (true) { skipWhitespace(); - out.add(readValue()); + factory.add(out, readValue()); skipWhitespace(); char c = peek(); pos++; if (c == ']') { - return out; + return factory.endArray(out); } if (c != ',') { - throw new IOException("Expected ',' or ']' at offset " + (pos - 1)); + throw error("Expected ',' or ']'", pos - 1); } } } @@ -1674,31 +1776,94 @@ private static int hexDigit(char c) { return -1; } - @SuppressWarnings("PMD.SwitchStmtsShouldHaveDefault") + /// Keys seen in this document, by hash of their characters. Objects in + /// a document repeat the same few member names, so each name becomes + /// one String shared by every object, as CPython's decoder memoizes + /// keys: a thousand records hold one "id", not a thousand. + /// Keys seen recently, by hash: a document repeats its keys, and one string per + /// key name serves every object that has it. One table for every parse, so a parse + /// allocates none. Readers on other threads may overwrite a slot, which is harmless: + /// a slot holds an immutable string and is only used once it matches, so a lost + /// write costs one substring. + private static final String[] KEYS = new String[64]; + + private String readKey() throws IOException { + int start = pos + 1; + int h = 0; + int i = start; + while (i < len) { + char c = src.charAt(i); + if (c == '"' || c == '\\' || c < 0x20) { + break; + } + h = 31 * h + c; + i++; + } + if (i >= len || src.charAt(i) != '"' || i - start > 64) { + return readString(); + } + int n = i - start; + String[] table = KEYS; + int slot = (h ^ (h >>> 16)) & (table.length - 1); + String k = table[slot]; + if (k == null || k.length() != n || !src.regionMatches(start, k, 0, n)) { + k = src.substring(start, i); + table[slot] = k; + } + pos = i + 1; + return k; + } + + /// Most strings have no escape: those are one substring of the source, + /// which keeps the compact Latin-1 form where the source has it, and + /// nothing is copied through a builder. private String readString() throws IOException { - pos++; - StringBuilder out = new StringBuilder(); + int start = ++pos; + while (pos < len) { + char c = src.charAt(pos); + if (c == '"') { + return src.substring(start, pos++); + } + if (c == '\\') { + break; + } + // RFC 8259: everything below U+0020 arrives escaped; taking it + // literally accepts documents a conforming parser upstream + // rejects, and the two then disagree about where a string ends. + if (c < 0x20 && !controls) { + throw error("A control character must be escaped in a JSON string", pos); + } + pos++; + } + StringBuilder out = scratch; + if (out == null) { + out = new StringBuilder(); + scratch = out; + } + out.setLength(0); + out.append(src, start, pos); + return readEscaped(out); + } + + @SuppressWarnings("PMD.SwitchStmtsShouldHaveDefault") + private String readEscaped(StringBuilder out) throws IOException { while (true) { - if (pos >= src.length()) { - throw new IOException("Unterminated string"); + if (pos >= len) { + throw error("Unterminated string", pos); } char c = src.charAt(pos++); if (c == '"') { return out.toString(); } if (c != '\\') { - // RFC 8259: everything below U+0020 arrives escaped; taking it - // literally accepts documents a conforming parser upstream - // rejects, and the two then disagree about where a string ends. - if (c < 0x20) { - throw new IOException("A control character must be escaped in a " - + "JSON string, at offset " + (pos - 1)); + if (c < 0x20 && !controls) { + throw error("A control character must be escaped in a JSON string", pos - 1); } out.append(c); continue; } - if (pos >= src.length()) { - throw new IOException("Unterminated escape"); + if (pos >= len) { + throw error("Unterminated escape", pos); } char esc = src.charAt(pos++); switch (esc) { @@ -1727,8 +1892,8 @@ private String readString() throws IOException { out.append('\t'); break; case 'u': - if (pos + 4 > src.length()) { - throw new IOException("Truncated unicode escape"); + if (pos + 4 > len) { + throw error("Truncated unicode escape", pos); } // Four ASCII hex digits, exactly: parseInt took a sign and // any Unicode digit, three spellings of one character @@ -1737,7 +1902,7 @@ private String readString() throws IOException { for (int k = 0; k < 4; k++) { int d = hexDigit(src.charAt(pos + k)); if (d < 0) { - throw new IOException("Malformed unicode escape at offset " + pos); + throw error("Malformed unicode escape", pos); } escaped = escaped * 16 + d; } @@ -1745,69 +1910,121 @@ private String readString() throws IOException { pos += 4; break; default: - throw new IOException("Unknown escape \\" + esc); + throw error("Unknown escape \\" + esc, pos - 1); } } } - private Object readLiteral(String literal, Object value) throws IOException { + private void readLiteral(String literal) throws IOException { if (!src.startsWith(literal, pos)) { - throw new IOException("Expected " + literal + " at offset " + pos); + throw error("Expected " + literal, pos); } pos += literal.length(); - return value; } + private static final double[] POW10 = {1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, + 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19, 1e20, 1e21, 1e22}; + private static boolean isDigit(char c) { return c >= '0' && c <= '9'; } /// A number by the grammar rather than by what Java happens to parse: - /// `+1`, `01`, `.5` and `1.` are not JSON numbers. + /// `+1`, `01`, `.5` and `1.` are not JSON numbers. An integer of up to 18 + /// digits is accumulated as it is read, with no substring. private Object readNumber() throws IOException { int start = pos; - boolean floating = false; - if (pos < src.length() && src.charAt(pos) == '-') { + boolean negative = false; + if (pos < len && src.charAt(pos) == '-') { + negative = true; pos++; } int intStart = pos; - if (pos < src.length() && src.charAt(pos) == '0') { + long acc = 0; + if (pos < len && src.charAt(pos) == '0') { pos++; - if (pos < src.length() && isDigit(src.charAt(pos))) { - throw new IOException("A leading zero is not a JSON number, at offset " + start); + if (pos < len && isDigit(src.charAt(pos))) { + throw error("A leading zero is not a JSON number", start); } } else { - while (pos < src.length() && isDigit(src.charAt(pos))) { + while (pos < len) { + char d = src.charAt(pos); + if (!isDigit(d)) { + break; + } + acc = acc * 10 + (d - '0'); pos++; } } if (pos == intStart) { - throw new IOException("Expected a digit at offset " + intStart); + throw error("Expected a digit", intStart); } - if (pos < src.length() && src.charAt(pos) == '.') { + int intDigits = pos - intStart; + boolean floating = false; + // Significant digits so far in acc (a leading zero is not one), and + // the power of ten acc is scaled by. + int sig = acc == 0 ? 0 : intDigits; + int scale = 0; + if (pos < len && src.charAt(pos) == '.') { floating = true; pos++; int fracStart = pos; - while (pos < src.length() && isDigit(src.charAt(pos))) { + while (pos < len) { + char d = src.charAt(pos); + if (!isDigit(d)) { + break; + } + if (sig < 18) { + acc = acc * 10 + (d - '0'); + scale--; + if (acc != 0) { + sig++; + } + } else { + sig = 99; + } pos++; } if (pos == fracStart) { - throw new IOException("Expected a digit after '.' at offset " + fracStart); + throw error("Expected a digit after '.'", fracStart); } } - if (pos < src.length() && (src.charAt(pos) == 'e' || src.charAt(pos) == 'E')) { + if (pos < len && (src.charAt(pos) == 'e' || src.charAt(pos) == 'E')) { floating = true; pos++; - if (pos < src.length() && (src.charAt(pos) == '-' || src.charAt(pos) == '+')) { + boolean expNegative = false; + if (pos < len && (src.charAt(pos) == '-' || src.charAt(pos) == '+')) { + expNegative = src.charAt(pos) == '-'; pos++; } int expStart = pos; - while (pos < src.length() && isDigit(src.charAt(pos))) { + int exp = 0; + while (pos < len && isDigit(src.charAt(pos))) { + if (exp < 10000) { + exp = exp * 10 + (src.charAt(pos) - '0'); + } pos++; } if (pos == expStart) { - throw new IOException("Expected a digit in the exponent at offset " + expStart); + throw error("Expected a digit in the exponent", expStart); } + scale += expNegative ? -exp : exp; + } + if (!floating && intDigits <= 18) { + return factory.integer(negative ? -acc : acc); + } + // Clinger's fast path: a mantissa below 2^53 and a power of ten up + // to 10^22 are both exact doubles, so one multiplication or division + // is the correctly rounded value -- the answer parseDouble gives, + // without building a string for it. + if (floating && intDigits <= 18 && sig <= 15 && scale >= -22 && scale <= 22) { + double v = (double) acc; + if (scale < 0) { + v /= POW10[-scale]; + } else { + v *= POW10[scale]; + } + return factory.decimal(negative ? -v : v); } String text = src.substring(start, pos); if (floating) { @@ -1815,24 +2032,23 @@ private Object readNumber() throws IOException { try { parsed = Double.parseDouble(text); } catch (NumberFormatException err) { - throw new IOException("Malformed number '" + text + "'", err); + JSONParseException e = error("Malformed number '" + text + "'", start); + e.initCause(err); + throw e; } // parseDouble answers Infinity for 1e999 rather than throwing, and - // the writer emits null for it: refuse it here instead. - if (Double.isNaN(parsed) || Double.isInfinite(parsed)) { - throw new IOException("Number out of range for JSON: '" + text + "'"); + // the writer emits null for it: refuse it here unless asked. + if (!nonFinite && (Double.isNaN(parsed) || Double.isInfinite(parsed))) { + throw error("Number out of range for JSON: '" + text + "'", start); } - return Double.valueOf(parsed); + return factory.decimal(parsed); } // Integers stay integers: a long through a double loses precision above // 2^53, and ids and amounts are exactly the values that get large. if (fitsLong(text)) { - return Long.valueOf(Long.parseLong(text)); + return factory.integer(Long.parseLong(text)); } - if (exactIntegers) { - return new RawJson(text); - } - throw new IOException("Malformed number '" + text + "'"); + return factory.bigInteger(text); } /// The token is digits with an optional minus sign; decides without @@ -1851,14 +2067,14 @@ private static boolean fitsLong(String text) { } private char peek() throws IOException { - if (pos >= src.length()) { - throw new IOException("Unexpected end of JSON"); + if (pos >= len) { + throw error("Unexpected end of JSON", pos); } return src.charAt(pos); } void skipWhitespace() { - while (pos < src.length()) { + while (pos < len) { char c = src.charAt(pos); if (c == ' ' || c == '\t' || c == '\n' || c == '\r') { pos++; @@ -1869,7 +2085,6 @@ void skipWhitespace() { } } - static class ReaderClass { char[] buffer; int buffOffset; diff --git a/CodenameOne/src/com/codename1/io/JSONValueFactory.java b/CodenameOne/src/com/codename1/io/JSONValueFactory.java new file mode 100644 index 00000000000..427d0180e61 --- /dev/null +++ b/CodenameOne/src/com/codename1/io/JSONValueFactory.java @@ -0,0 +1,221 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.io; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/// Builds the values [JSONParser#parseStrict(String, JSONValueFactory)] reads. +/// +/// The strict reader calls these methods as it walks a document, and whatever +/// they return is what the containers hold, so a caller can parse straight into +/// its own types instead of converting a tree of maps and lists afterwards. A +/// language runtime builds its own dictionaries and numbers this way, and a data +/// binder can build its objects without a second pass. +/// +/// This class answers exactly what [JSONParser#parseStrict(String)] answers: a +/// `LinkedHashMap` per object, an `ArrayList` per array, `String`, `Boolean`, +/// `null`, `Long` for an integer and `Double` for any other number. Override the +/// methods whose result should differ. Containers are opened, filled in document +/// order and closed; a value is complete when it is handed to its parent. +/// +/// Two relaxations of RFC 8259 are off unless a subclass turns them on: +/// [#allowNonFinite()] for `NaN`, `Infinity`, `-Infinity` and numbers too large +/// for a double, and [#allowControlCharacters()] for unescaped control +/// characters inside strings. +@com.codename1.impl.SharedWithBackend +public class JSONValueFactory { + /// Opens an object. + /// + /// #### Returns + /// + /// the new, empty container, handed back to [#put(Object, String, Object)] + /// and [#endObject(Object)] + public Object newObject() { + return new LinkedHashMap(); + } + + /// Adds one member to an object opened by [#newObject()]. A key may repeat; + /// the reader passes every occurrence in order. + /// + /// #### Parameters + /// + /// - `object`: the container + /// + /// - `key`: the member name + /// + /// - `value`: the member value + @SuppressWarnings("unchecked") + public void put(Object object, String key, Object value) { + ((Map) object).put(key, value); + } + + /// Closes an object. + /// + /// #### Parameters + /// + /// - `object`: the container + /// + /// #### Returns + /// + /// the value the parent receives, normally the container itself + public Object endObject(Object object) { + return object; + } + + /// Opens an array. + /// + /// #### Returns + /// + /// the new, empty container + public Object newArray() { + return new ArrayList(); + } + + /// Appends one element to an array opened by [#newArray()]. + /// + /// #### Parameters + /// + /// - `array`: the container + /// + /// - `value`: the element + @SuppressWarnings("unchecked") + public void add(Object array, Object value) { + ((List) array).add(value); + } + + /// Closes an array. + /// + /// #### Parameters + /// + /// - `array`: the container + /// + /// #### Returns + /// + /// the value the parent receives, normally the container itself + public Object endArray(Object array) { + return array; + } + + /// A string value. Member names are not passed here. + /// + /// #### Parameters + /// + /// - `value`: the decoded string + /// + /// #### Returns + /// + /// the value to store + public Object string(String value) { + return value; + } + + /// An integer that fits a `long`. + /// + /// #### Parameters + /// + /// - `value`: the integer + /// + /// #### Returns + /// + /// the value to store + public Object integer(long value) { + return Long.valueOf(value); + } + + /// An integer too large for a `long`. + /// + /// #### Parameters + /// + /// - `digits`: the integer as written, with its sign + /// + /// #### Returns + /// + /// the value to store + /// + /// #### Throws + /// + /// - `IOException`: to refuse it, which this class does + public Object bigInteger(String digits) throws java.io.IOException { + throw new java.io.IOException("Malformed number '" + digits + "'"); + } + + /// A number with a fraction or an exponent, or a non-finite one when + /// [#allowNonFinite()] is on. + /// + /// #### Parameters + /// + /// - `value`: the number + /// + /// #### Returns + /// + /// the value to store + public Object decimal(double value) { + return Double.valueOf(value); + } + + /// `true` or `false`. + /// + /// #### Parameters + /// + /// - `value`: the literal + /// + /// #### Returns + /// + /// the value to store + public Object bool(boolean value) { + return value ? Boolean.TRUE : Boolean.FALSE; + } + + /// `null`. + /// + /// #### Returns + /// + /// the value to store + public Object nullValue() { + return null; + } + + /// Whether `NaN`, `Infinity` and `-Infinity` are read, and a number such + /// as `1e999` is read as infinite rather than refused. JavaScript's and + /// Python's JSON writers emit these. + /// + /// #### Returns + /// + /// false, as RFC 8259 requires + public boolean allowNonFinite() { + return false; + } + + /// Whether a control character below U+0020 may appear unescaped inside a + /// string. + /// + /// #### Returns + /// + /// false, as RFC 8259 requires + public boolean allowControlCharacters() { + return false; + } +} diff --git a/CodenameOne/src/com/codename1/io/JSONWriter.java b/CodenameOne/src/com/codename1/io/JSONWriter.java index d01de29f3e9..f3f0dcf4839 100644 --- a/CodenameOne/src/com/codename1/io/JSONWriter.java +++ b/CodenameOne/src/com/codename1/io/JSONWriter.java @@ -1,17 +1,24 @@ /* * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Codename One designates this + * published by the Free Software Foundation. Codename One designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details. + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. */ package com.codename1.io; @@ -202,31 +209,6 @@ private static void writeJson(Object o, StringBuilder sb) { } private static void writeString(String s, StringBuilder sb) { - sb.append('"'); - int n = s.length(); - for (int i = 0; i < n; i++) { - char c = s.charAt(i); - switch (c) { - case '"': sb.append("\\\""); break; - case '\\': sb.append("\\\\"); break; - case '\n': sb.append("\\n"); break; - case '\r': sb.append("\\r"); break; - case '\t': sb.append("\\t"); break; - case '\b': sb.append("\\b"); break; - case '\f': sb.append("\\f"); break; - default: - if (c < 0x20) { - sb.append("\\u"); - String hex = Integer.toHexString(c); - for (int p = hex.length(); p < 4; p++) { - sb.append('0'); - } - sb.append(hex); - } else { - sb.append(c); - } - } - } - sb.append('"'); + JSONParser.appendQuoted(sb, s, false); } } diff --git a/CodenameOne/src/com/codename1/io/gzip/CRC32.java b/CodenameOne/src/com/codename1/io/gzip/CRC32.java index dd694da1b44..6f25d534bbf 100644 --- a/CodenameOne/src/com/codename1/io/gzip/CRC32.java +++ b/CodenameOne/src/com/codename1/io/gzip/CRC32.java @@ -40,6 +40,7 @@ final public class CRC32 implements Checksum { // The following logic has come from zlib.1.2. private static final int GF2_DIM = 32; private static int[] crc_table = null; + private static final int[] SLICES; static { crc_table = new int[256]; @@ -55,6 +56,19 @@ final public class CRC32 implements Checksum { } crc_table[n] = c; } + // Slice-by-8, as zlib does: T[k][n] is the CRC of byte n followed by + // k zero bytes, so eight bytes are folded in with eight independent + // lookups instead of eight dependent ones. Zip and gzip reading spent + // more time here than in inflate itself. + SLICES = new int[8 * 256]; + System.arraycopy(crc_table, 0, SLICES, 0, 256); + for (int n = 0; n < 256; n++) { + int c = crc_table[n]; + for (int k = 1; k < 8; k++) { + c = crc_table[c & 0xff] ^ (c >>> 8); + SLICES[k * 256 + n] = c; + } + } } /* @@ -144,8 +158,18 @@ public static int[] getCRC32Table() { @Override public void update(byte[] buf, int index, int len) { int c = ~v; - while (--len >= 0) { - c = crc_table[(c ^ buf[index++]) & 0xff] ^ (c >>> 8); + int[] t = SLICES; + int i = index; + int end = index + len; + while (end - i >= 8) { + int lo = c ^ (buf[i] & 0xff | (buf[i + 1] & 0xff) << 8 | (buf[i + 2] & 0xff) << 16 | buf[i + 3] << 24); + c = t[1792 + (lo & 0xff)] ^ t[1536 + (lo >>> 8 & 0xff)] ^ t[1280 + (lo >>> 16 & 0xff)] ^ t[1024 + (lo >>> 24)] + ^ t[768 + (buf[i + 4] & 0xff)] ^ t[512 + (buf[i + 5] & 0xff)] ^ t[256 + (buf[i + 6] & 0xff)] + ^ t[buf[i + 7] & 0xff]; + i += 8; + } + while (i < end) { + c = t[(c ^ buf[i++]) & 0xff] ^ (c >>> 8); } v = ~c; } diff --git a/CodenameOne/src/com/codename1/security/Hash.java b/CodenameOne/src/com/codename1/security/Hash.java index 0dbb4ed663f..cbbe3a465ac 100644 --- a/CodenameOne/src/com/codename1/security/Hash.java +++ b/CodenameOne/src/com/codename1/security/Hash.java @@ -115,6 +115,68 @@ public static Hash create(String algorithm) { return new Hash(MessageDigestImpl.create(algorithm)); } + /// A BLAKE2b hash (RFC 7693), optionally keyed, salted and personalised. + /// + /// #### Parameters + /// + /// - `digestSize`: bytes of output, 1 to 64 + /// + /// - `key`: the MAC key, at most 64 bytes; empty for a plain hash + /// + /// - `salt`: at most 16 bytes, zero padded; may be empty + /// + /// - `person`: the personalisation string, at most 16 bytes, zero padded; + /// may be empty + /// + /// #### Throws + /// + /// - `CryptoException`: if a size is out of range + public static Hash blake2b(int digestSize, byte[] key, byte[] salt, byte[] person) { + return blake2(true, digestSize, key, salt, person); + } + + /// A BLAKE2s hash (RFC 7693), the 32-bit variant of [#blake2b]. + /// + /// #### Parameters + /// + /// - `digestSize`: bytes of output, 1 to 32 + /// + /// - `key`: the MAC key, at most 32 bytes; empty for a plain hash + /// + /// - `salt`: at most 8 bytes, zero padded; may be empty + /// + /// - `person`: the personalisation string, at most 8 bytes, zero padded; + /// may be empty + /// + /// #### Throws + /// + /// - `CryptoException`: if a size is out of range + public static Hash blake2s(int digestSize, byte[] key, byte[] salt, byte[] person) { + return blake2(false, digestSize, key, salt, person); + } + + private static Hash blake2(boolean big, int digestSize, byte[] key, byte[] salt, byte[] person) { + int max = big ? 64 : 32; + int half = big ? 16 : 8; + byte[] k = key == null ? new byte[0] : key; + byte[] s = salt == null ? new byte[0] : salt; + byte[] p = person == null ? new byte[0] : person; + if (digestSize < 1 || digestSize > max || k.length > max || s.length > half || p.length > half) { + throw new CryptoException("BLAKE2 parameters out of range"); + } + return new Hash(new MessageDigestImpl.Blake2(big, digestSize, k, s, p)); + } + + /// An independent hash in the same state as this one: a shared prefix is + /// hashed once and each copy finished on its own. + /// + /// #### Returns + /// + /// the copy; updating either leaves the other unchanged + public Hash copy() { + return new Hash(impl.copy()); + } + /// Feeds the entire array into the running hash. /// /// #### Parameters @@ -152,6 +214,18 @@ public byte[] digest() { return impl.digest(); } + /// The digest of everything fed so far, leaving the hash running: more + /// input may follow and [#digest()] still answers for all of it. This is + /// `copy().digest()` without the copy where the algorithm can finish + /// over its own state and put it back, as BLAKE2 does. + /// + /// #### Returns + /// + /// the raw digest bytes (algorithm specific length) + public byte[] peekDigest() { + return impl.peekDigest(); + } + /// Convenience: feed `data` then return the digest. public byte[] digest(byte[] data) { impl.update(data, 0, data.length); diff --git a/CodenameOne/src/com/codename1/security/MessageDigestImpl.java b/CodenameOne/src/com/codename1/security/MessageDigestImpl.java index 8001a5bbc5d..294ce8b8fc9 100644 --- a/CodenameOne/src/com/codename1/security/MessageDigestImpl.java +++ b/CodenameOne/src/com/codename1/security/MessageDigestImpl.java @@ -35,6 +35,14 @@ abstract class MessageDigestImpl { abstract byte[] digest(); abstract int digestLength(); abstract void reset(); + /// An independent digest in the same state, so a common prefix is hashed + /// once and finished several ways. + abstract MessageDigestImpl copy(); + + /// The digest so far, this digest left as it was. + byte[] peekDigest() { + return copy().digest(); + } static MessageDigestImpl create(String algorithm) { if (algorithm == null) { @@ -96,6 +104,14 @@ abstract static class Block64 extends MessageDigestImpl { abstract void processBlock(byte[] block, int offset); abstract void writeStateBigEndian(byte[] out); + /// Copies the block buffer and the byte count into `to`. + final T copyBlockTo(T to) { + System.arraycopy(buffer, 0, to.buffer, 0, bufferLen); + to.bufferLen = bufferLen; + to.byteCount = byteCount; + return to; + } + @Override void update(byte[] data, int offset, int length) { byteCount += length; @@ -177,6 +193,16 @@ final byte[] finishCommon(boolean bigEndianLength) { // =============================================================== // MD5 -- RFC 1321 (little-endian length, little-endian word loads) static final class Md5 extends Block64 { + @Override + MessageDigestImpl copy() { + Md5 c = copyBlockTo(new Md5()); + c.a = a; + c.b = b; + c.c = this.c; + c.d = d; + return c; + } + int a; int b; int c; @@ -340,6 +366,17 @@ void processBlock(byte[] block, int o) { // =============================================================== // SHA-1 -- RFC 3174 static final class Sha1 extends Block64 { + @Override + MessageDigestImpl copy() { + Sha1 c = copyBlockTo(new Sha1()); + c.h0 = h0; + c.h1 = h1; + c.h2 = h2; + c.h3 = h3; + c.h4 = h4; + return c; + } + int h0; int h1; int h2; @@ -468,6 +505,20 @@ static final class Sha256Family extends Block64 { reset(); } + @Override + MessageDigestImpl copy() { + Sha256Family c = copyBlockTo(new Sha256Family(truncated)); + c.h0 = h0; + c.h1 = h1; + c.h2 = h2; + c.h3 = h3; + c.h4 = h4; + c.h5 = h5; + c.h6 = h6; + c.h7 = h7; + return c; + } + @Override public void reset() { if (truncated) { @@ -603,6 +654,23 @@ static final class Sha512Family extends MessageDigestImpl { reset(); } + @Override + MessageDigestImpl copy() { + Sha512Family c = new Sha512Family(truncated); + c.h0 = h0; + c.h1 = h1; + c.h2 = h2; + c.h3 = h3; + c.h4 = h4; + c.h5 = h5; + c.h6 = h6; + c.h7 = h7; + System.arraycopy(buffer, 0, c.buffer, 0, bufferLen); + c.bufferLen = bufferLen; + c.byteCount = byteCount; + return c; + } + @Override public void reset() { if (truncated) { @@ -803,6 +871,15 @@ static final class Keccak extends MessageDigestImpl { this.buffer = new byte[rate]; } + @Override + MessageDigestImpl copy() { + Keccak c = new Keccak(outLen, domain); + System.arraycopy(state, 0, c.state, 0, 25); + System.arraycopy(buffer, 0, c.buffer, 0, bufferLen); + c.bufferLen = bufferLen; + return c; + } + @Override public void reset() { for (int i = 0; i < 25; i++) { @@ -1051,6 +1128,17 @@ static void writeBE64(byte[] out, int o, long v) { // RIPEMD-160 (Dobbertin, Bosselaers, Preneel), unrolled: both lines of // 80 steps run on locals, and the sixteen message words are read once. static final class Ripemd160 extends Block64 { + @Override + MessageDigestImpl copy() { + Ripemd160 c = copyBlockTo(new Ripemd160()); + c.h0 = h0; + c.h1 = h1; + c.h2 = h2; + c.h3 = h3; + c.h4 = h4; + return c; + } + int h0; int h1; int h2; @@ -1305,4 +1393,1516 @@ private static void right(int[] x, int ra, int rb, int rc, int rd, int re, int[] out[4] = re; } } + + /// BLAKE2b and BLAKE2s, sequential mode. BLAKE2s keeps its 32-bit words + /// in the low half of each long, so one compression function serves + /// both. + // Fused: h and buf are allocated with the instance as one block. Neither + // escapes it -- they are only read, copied out of and passed to calls -- as + // the annotation's contract requires; a hash object is made per hash. + @com.codename1.annotations.Fused + static final class Blake2 extends MessageDigestImpl { + private static final long[] IV_B = {0x6a09e667f3bcc908L, 0xbb67ae8584caa73bL, 0x3c6ef372fe94f82bL, + 0xa54ff53a5f1d36f1L, 0x510e527fade682d1L, 0x9b05688c2b3e6c1fL, 0x1f83d9abfb41bd6bL, + 0x5be0cd19137e2179L}; + private static final int[] IV_S = {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, + 0x9b05688c, 0x1f83d9ab, 0x5be0cd19}; + private static final byte[][] SIGMA = { + {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}, + {14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3}, + {11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4}, + {7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8}, + {9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13}, + {2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9}, + {12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11}, + {13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10}, + {6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5}, + {10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0}}; + + final boolean big; + final int digestSize; + private final byte[] key; + private final byte[] salt; + private final byte[] person; + final long[] h = new long[8]; + // Always the BLAKE2b block size, so the allocation is unconditional and + // can be fused; BLAKE2s uses the first `blockSize` (64) bytes. + final byte[] buf = new byte[128]; + final int blockSize; + int bufLen; + long t0; + long t1; + // BLAKE2s's working arrays, made on its first block: a hash object is + // made per hash. BLAKE2b keeps all of its words in locals. + private long[] v; + private long[] m; + + Blake2(boolean big, int digestSize, byte[] key, byte[] salt, byte[] person) { + this.big = big; + this.digestSize = digestSize; + this.key = key; + this.salt = salt; + this.person = person; + blockSize = big ? 128 : 64; + reset(); + } + + @Override + void reset() { + bufLen = 0; + t0 = 0; + t1 = 0; + // Only a key block needs the buffer clear: it is the key padded with + // zeros to a whole block. Without a key, digest() zero pads from + // bufLen itself, and clearing here cost a pass over the block on + // every hash -- most hashes are one short block. + if (key.length > 0) { + for (int i = 0; i < blockSize; i++) { + buf[i] = 0; + } + } + if (big) { + h[0] = IV_B[0] ^ (0x01010000L | (long) key.length << 8 | digestSize); + for (int i = 1; i < 8; i++) { + h[i] = IV_B[i]; + } + h[4] ^= word(salt, 0, 8); + h[5] ^= word(salt, 8, 8); + h[6] ^= word(person, 0, 8); + h[7] ^= word(person, 8, 8); + } else { + h[0] = (IV_S[0] ^ (0x01010000 | key.length << 8 | digestSize)) & 0xffffffffL; + for (int i = 1; i < 8; i++) { + h[i] = IV_S[i] & 0xffffffffL; + } + h[4] ^= word(salt, 0, 4); + h[5] ^= word(salt, 4, 4); + h[6] ^= word(person, 0, 4); + h[7] ^= word(person, 4, 4); + } + if (key.length > 0) { + System.arraycopy(key, 0, buf, 0, key.length); + bufLen = blockSize; + } + } + + /// The little-endian word of `w` bytes at `off`, zero padded. + private static long word(byte[] b, int off, int w) { + if (off >= b.length) { + return 0; + } + long r = 0; + for (int i = w - 1; i >= 0; i--) { + r = r << 8 | (off + i < b.length ? b[off + i] & 0xff : 0); + } + return r; + } + + @Override + void update(byte b) { + update(new byte[] {b}, 0, 1); + } + + @Override + int digestLength() { + return digestSize; + } + + @Override + void update(byte[] b, int off, int len) { + int bs = blockSize; + while (len > 0) { + // The last block is compressed in finish(), flagged final, so + // a full buffer is held back until more input arrives. + if (bufLen == bs) { + count(bs); + compress(buf, 0, false); + bufLen = 0; + } + int n = Math.min(bs - bufLen, len); + System.arraycopy(b, off, buf, bufLen, n); + bufLen += n; + off += n; + len -= n; + } + } + + private void count(int n) { + if (big) { + t0 += n; + if (Long.compareUnsigned(t0, n) < 0) { + t1++; + } + } else { + t0 += n; + } + } + + private void compress(byte[] b, int off, boolean last) { + if (big) { + compressBig(b, last); + return; + } + if (v == null) { + m = new long[16]; + v = new long[16]; + } + for (int i = 0; i < 16; i++) { + m[i] = le32(b, off + 4 * i) & 0xffffffffL; + } + for (int i = 0; i < 8; i++) { + v[i] = h[i]; + v[i + 8] = IV_S[i] & 0xffffffffL; + } + v[12] ^= t0 & 0xffffffffL; + v[13] ^= t0 >>> 32; + if (last) { + v[14] ^= 0xffffffffL; + } + for (int r = 0; r < 10; r++) { + byte[] s = SIGMA[r]; + gs(0, 4, 8, 12, m[s[0]], m[s[1]]); + gs(1, 5, 9, 13, m[s[2]], m[s[3]]); + gs(2, 6, 10, 14, m[s[4]], m[s[5]]); + gs(3, 7, 11, 15, m[s[6]], m[s[7]]); + gs(0, 5, 10, 15, m[s[8]], m[s[9]]); + gs(1, 6, 11, 12, m[s[10]], m[s[11]]); + gs(2, 7, 8, 13, m[s[12]], m[s[13]]); + gs(3, 4, 9, 14, m[s[14]], m[s[15]]); + } + for (int i = 0; i < 8; i++) { + h[i] ^= v[i] ^ v[i + 8]; + } + } + + /// BLAKE2b's compression with the sixteen words of the state and the sixteen + /// message words in locals and all twelve rounds written out, the message + /// schedule folded into which local each mix reads. The state lives in + /// registers for the whole of it, and the rounds read no array at all: an + /// indexed schedule cost two checked loads per mix. + private void compressBig(byte[] b, boolean last) { + // The message words, read straight into locals: eight independent + // byte loads per word, where a gather loop over the block (one + // byte an iteration, a branch per byte to store each word) was a + // dependency chain of 128 steps before the first round could start. + // Written out rather than through a helper, which the C compiler + // left as a call per word. b is always this object's own 128-byte + // block buffer. + long m0 = b[0] & 0xffL | (b[1] & 0xffL) << 8 | (b[2] & 0xffL) << 16 | (b[3] & 0xffL) << 24 + | (b[4] & 0xffL) << 32 | (b[5] & 0xffL) << 40 | (b[6] & 0xffL) << 48 | (long) b[7] << 56; + long m1 = b[8] & 0xffL | (b[9] & 0xffL) << 8 | (b[10] & 0xffL) << 16 | (b[11] & 0xffL) << 24 + | (b[12] & 0xffL) << 32 | (b[13] & 0xffL) << 40 | (b[14] & 0xffL) << 48 | (long) b[15] << 56; + long m2 = b[16] & 0xffL | (b[17] & 0xffL) << 8 | (b[18] & 0xffL) << 16 | (b[19] & 0xffL) << 24 + | (b[20] & 0xffL) << 32 | (b[21] & 0xffL) << 40 | (b[22] & 0xffL) << 48 | (long) b[23] << 56; + long m3 = b[24] & 0xffL | (b[25] & 0xffL) << 8 | (b[26] & 0xffL) << 16 | (b[27] & 0xffL) << 24 + | (b[28] & 0xffL) << 32 | (b[29] & 0xffL) << 40 | (b[30] & 0xffL) << 48 | (long) b[31] << 56; + long m4 = b[32] & 0xffL | (b[33] & 0xffL) << 8 | (b[34] & 0xffL) << 16 | (b[35] & 0xffL) << 24 + | (b[36] & 0xffL) << 32 | (b[37] & 0xffL) << 40 | (b[38] & 0xffL) << 48 | (long) b[39] << 56; + long m5 = b[40] & 0xffL | (b[41] & 0xffL) << 8 | (b[42] & 0xffL) << 16 | (b[43] & 0xffL) << 24 + | (b[44] & 0xffL) << 32 | (b[45] & 0xffL) << 40 | (b[46] & 0xffL) << 48 | (long) b[47] << 56; + long m6 = b[48] & 0xffL | (b[49] & 0xffL) << 8 | (b[50] & 0xffL) << 16 | (b[51] & 0xffL) << 24 + | (b[52] & 0xffL) << 32 | (b[53] & 0xffL) << 40 | (b[54] & 0xffL) << 48 | (long) b[55] << 56; + long m7 = b[56] & 0xffL | (b[57] & 0xffL) << 8 | (b[58] & 0xffL) << 16 | (b[59] & 0xffL) << 24 + | (b[60] & 0xffL) << 32 | (b[61] & 0xffL) << 40 | (b[62] & 0xffL) << 48 | (long) b[63] << 56; + long m8 = b[64] & 0xffL | (b[65] & 0xffL) << 8 | (b[66] & 0xffL) << 16 | (b[67] & 0xffL) << 24 + | (b[68] & 0xffL) << 32 | (b[69] & 0xffL) << 40 | (b[70] & 0xffL) << 48 | (long) b[71] << 56; + long m9 = b[72] & 0xffL | (b[73] & 0xffL) << 8 | (b[74] & 0xffL) << 16 | (b[75] & 0xffL) << 24 + | (b[76] & 0xffL) << 32 | (b[77] & 0xffL) << 40 | (b[78] & 0xffL) << 48 | (long) b[79] << 56; + long m10 = b[80] & 0xffL | (b[81] & 0xffL) << 8 | (b[82] & 0xffL) << 16 | (b[83] & 0xffL) << 24 + | (b[84] & 0xffL) << 32 | (b[85] & 0xffL) << 40 | (b[86] & 0xffL) << 48 | (long) b[87] << 56; + long m11 = b[88] & 0xffL | (b[89] & 0xffL) << 8 | (b[90] & 0xffL) << 16 | (b[91] & 0xffL) << 24 + | (b[92] & 0xffL) << 32 | (b[93] & 0xffL) << 40 | (b[94] & 0xffL) << 48 | (long) b[95] << 56; + long m12 = b[96] & 0xffL | (b[97] & 0xffL) << 8 | (b[98] & 0xffL) << 16 | (b[99] & 0xffL) << 24 + | (b[100] & 0xffL) << 32 | (b[101] & 0xffL) << 40 | (b[102] & 0xffL) << 48 | (long) b[103] << 56; + long m13 = b[104] & 0xffL | (b[105] & 0xffL) << 8 | (b[106] & 0xffL) << 16 | (b[107] & 0xffL) << 24 + | (b[108] & 0xffL) << 32 | (b[109] & 0xffL) << 40 | (b[110] & 0xffL) << 48 | (long) b[111] << 56; + long m14 = b[112] & 0xffL | (b[113] & 0xffL) << 8 | (b[114] & 0xffL) << 16 | (b[115] & 0xffL) << 24 + | (b[116] & 0xffL) << 32 | (b[117] & 0xffL) << 40 | (b[118] & 0xffL) << 48 | (long) b[119] << 56; + long m15 = b[120] & 0xffL | (b[121] & 0xffL) << 8 | (b[122] & 0xffL) << 16 | (b[123] & 0xffL) << 24 + | (b[124] & 0xffL) << 32 | (b[125] & 0xffL) << 40 | (b[126] & 0xffL) << 48 | (long) b[127] << 56; + long[] hw = h; + long v0 = hw[0]; + long v1 = hw[1]; + long v2 = hw[2]; + long v3 = hw[3]; + long v4 = hw[4]; + long v5 = hw[5]; + long v6 = hw[6]; + long v7 = hw[7]; + long v8 = 0x6a09e667f3bcc908L; + long v9 = 0xbb67ae8584caa73bL; + long v10 = 0x3c6ef372fe94f82bL; + long v11 = 0xa54ff53a5f1d36f1L; + long v12 = 0x510e527fade682d1L ^ t0; + long v13 = 0x9b05688c2b3e6c1fL ^ t1; + long v14 = last ? ~0x1f83d9abfb41bd6bL : 0x1f83d9abfb41bd6bL; + long v15 = 0x5be0cd19137e2179L; + long w; + // round 0 + v0 += v4 + m0; + w = v12 ^ v0; + v12 = w >>> 32 | w << 32; + v8 += v12; + w = v4 ^ v8; + v4 = w >>> 24 | w << 40; + v0 += v4 + m1; + w = v12 ^ v0; + v12 = w >>> 16 | w << 48; + v8 += v12; + w = v4 ^ v8; + v4 = w >>> 63 | w << 1; + v1 += v5 + m2; + w = v13 ^ v1; + v13 = w >>> 32 | w << 32; + v9 += v13; + w = v5 ^ v9; + v5 = w >>> 24 | w << 40; + v1 += v5 + m3; + w = v13 ^ v1; + v13 = w >>> 16 | w << 48; + v9 += v13; + w = v5 ^ v9; + v5 = w >>> 63 | w << 1; + v2 += v6 + m4; + w = v14 ^ v2; + v14 = w >>> 32 | w << 32; + v10 += v14; + w = v6 ^ v10; + v6 = w >>> 24 | w << 40; + v2 += v6 + m5; + w = v14 ^ v2; + v14 = w >>> 16 | w << 48; + v10 += v14; + w = v6 ^ v10; + v6 = w >>> 63 | w << 1; + v3 += v7 + m6; + w = v15 ^ v3; + v15 = w >>> 32 | w << 32; + v11 += v15; + w = v7 ^ v11; + v7 = w >>> 24 | w << 40; + v3 += v7 + m7; + w = v15 ^ v3; + v15 = w >>> 16 | w << 48; + v11 += v15; + w = v7 ^ v11; + v7 = w >>> 63 | w << 1; + v0 += v5 + m8; + w = v15 ^ v0; + v15 = w >>> 32 | w << 32; + v10 += v15; + w = v5 ^ v10; + v5 = w >>> 24 | w << 40; + v0 += v5 + m9; + w = v15 ^ v0; + v15 = w >>> 16 | w << 48; + v10 += v15; + w = v5 ^ v10; + v5 = w >>> 63 | w << 1; + v1 += v6 + m10; + w = v12 ^ v1; + v12 = w >>> 32 | w << 32; + v11 += v12; + w = v6 ^ v11; + v6 = w >>> 24 | w << 40; + v1 += v6 + m11; + w = v12 ^ v1; + v12 = w >>> 16 | w << 48; + v11 += v12; + w = v6 ^ v11; + v6 = w >>> 63 | w << 1; + v2 += v7 + m12; + w = v13 ^ v2; + v13 = w >>> 32 | w << 32; + v8 += v13; + w = v7 ^ v8; + v7 = w >>> 24 | w << 40; + v2 += v7 + m13; + w = v13 ^ v2; + v13 = w >>> 16 | w << 48; + v8 += v13; + w = v7 ^ v8; + v7 = w >>> 63 | w << 1; + v3 += v4 + m14; + w = v14 ^ v3; + v14 = w >>> 32 | w << 32; + v9 += v14; + w = v4 ^ v9; + v4 = w >>> 24 | w << 40; + v3 += v4 + m15; + w = v14 ^ v3; + v14 = w >>> 16 | w << 48; + v9 += v14; + w = v4 ^ v9; + v4 = w >>> 63 | w << 1; + // round 1 + v0 += v4 + m14; + w = v12 ^ v0; + v12 = w >>> 32 | w << 32; + v8 += v12; + w = v4 ^ v8; + v4 = w >>> 24 | w << 40; + v0 += v4 + m10; + w = v12 ^ v0; + v12 = w >>> 16 | w << 48; + v8 += v12; + w = v4 ^ v8; + v4 = w >>> 63 | w << 1; + v1 += v5 + m4; + w = v13 ^ v1; + v13 = w >>> 32 | w << 32; + v9 += v13; + w = v5 ^ v9; + v5 = w >>> 24 | w << 40; + v1 += v5 + m8; + w = v13 ^ v1; + v13 = w >>> 16 | w << 48; + v9 += v13; + w = v5 ^ v9; + v5 = w >>> 63 | w << 1; + v2 += v6 + m9; + w = v14 ^ v2; + v14 = w >>> 32 | w << 32; + v10 += v14; + w = v6 ^ v10; + v6 = w >>> 24 | w << 40; + v2 += v6 + m15; + w = v14 ^ v2; + v14 = w >>> 16 | w << 48; + v10 += v14; + w = v6 ^ v10; + v6 = w >>> 63 | w << 1; + v3 += v7 + m13; + w = v15 ^ v3; + v15 = w >>> 32 | w << 32; + v11 += v15; + w = v7 ^ v11; + v7 = w >>> 24 | w << 40; + v3 += v7 + m6; + w = v15 ^ v3; + v15 = w >>> 16 | w << 48; + v11 += v15; + w = v7 ^ v11; + v7 = w >>> 63 | w << 1; + v0 += v5 + m1; + w = v15 ^ v0; + v15 = w >>> 32 | w << 32; + v10 += v15; + w = v5 ^ v10; + v5 = w >>> 24 | w << 40; + v0 += v5 + m12; + w = v15 ^ v0; + v15 = w >>> 16 | w << 48; + v10 += v15; + w = v5 ^ v10; + v5 = w >>> 63 | w << 1; + v1 += v6 + m0; + w = v12 ^ v1; + v12 = w >>> 32 | w << 32; + v11 += v12; + w = v6 ^ v11; + v6 = w >>> 24 | w << 40; + v1 += v6 + m2; + w = v12 ^ v1; + v12 = w >>> 16 | w << 48; + v11 += v12; + w = v6 ^ v11; + v6 = w >>> 63 | w << 1; + v2 += v7 + m11; + w = v13 ^ v2; + v13 = w >>> 32 | w << 32; + v8 += v13; + w = v7 ^ v8; + v7 = w >>> 24 | w << 40; + v2 += v7 + m7; + w = v13 ^ v2; + v13 = w >>> 16 | w << 48; + v8 += v13; + w = v7 ^ v8; + v7 = w >>> 63 | w << 1; + v3 += v4 + m5; + w = v14 ^ v3; + v14 = w >>> 32 | w << 32; + v9 += v14; + w = v4 ^ v9; + v4 = w >>> 24 | w << 40; + v3 += v4 + m3; + w = v14 ^ v3; + v14 = w >>> 16 | w << 48; + v9 += v14; + w = v4 ^ v9; + v4 = w >>> 63 | w << 1; + // round 2 + v0 += v4 + m11; + w = v12 ^ v0; + v12 = w >>> 32 | w << 32; + v8 += v12; + w = v4 ^ v8; + v4 = w >>> 24 | w << 40; + v0 += v4 + m8; + w = v12 ^ v0; + v12 = w >>> 16 | w << 48; + v8 += v12; + w = v4 ^ v8; + v4 = w >>> 63 | w << 1; + v1 += v5 + m12; + w = v13 ^ v1; + v13 = w >>> 32 | w << 32; + v9 += v13; + w = v5 ^ v9; + v5 = w >>> 24 | w << 40; + v1 += v5 + m0; + w = v13 ^ v1; + v13 = w >>> 16 | w << 48; + v9 += v13; + w = v5 ^ v9; + v5 = w >>> 63 | w << 1; + v2 += v6 + m5; + w = v14 ^ v2; + v14 = w >>> 32 | w << 32; + v10 += v14; + w = v6 ^ v10; + v6 = w >>> 24 | w << 40; + v2 += v6 + m2; + w = v14 ^ v2; + v14 = w >>> 16 | w << 48; + v10 += v14; + w = v6 ^ v10; + v6 = w >>> 63 | w << 1; + v3 += v7 + m15; + w = v15 ^ v3; + v15 = w >>> 32 | w << 32; + v11 += v15; + w = v7 ^ v11; + v7 = w >>> 24 | w << 40; + v3 += v7 + m13; + w = v15 ^ v3; + v15 = w >>> 16 | w << 48; + v11 += v15; + w = v7 ^ v11; + v7 = w >>> 63 | w << 1; + v0 += v5 + m10; + w = v15 ^ v0; + v15 = w >>> 32 | w << 32; + v10 += v15; + w = v5 ^ v10; + v5 = w >>> 24 | w << 40; + v0 += v5 + m14; + w = v15 ^ v0; + v15 = w >>> 16 | w << 48; + v10 += v15; + w = v5 ^ v10; + v5 = w >>> 63 | w << 1; + v1 += v6 + m3; + w = v12 ^ v1; + v12 = w >>> 32 | w << 32; + v11 += v12; + w = v6 ^ v11; + v6 = w >>> 24 | w << 40; + v1 += v6 + m6; + w = v12 ^ v1; + v12 = w >>> 16 | w << 48; + v11 += v12; + w = v6 ^ v11; + v6 = w >>> 63 | w << 1; + v2 += v7 + m7; + w = v13 ^ v2; + v13 = w >>> 32 | w << 32; + v8 += v13; + w = v7 ^ v8; + v7 = w >>> 24 | w << 40; + v2 += v7 + m1; + w = v13 ^ v2; + v13 = w >>> 16 | w << 48; + v8 += v13; + w = v7 ^ v8; + v7 = w >>> 63 | w << 1; + v3 += v4 + m9; + w = v14 ^ v3; + v14 = w >>> 32 | w << 32; + v9 += v14; + w = v4 ^ v9; + v4 = w >>> 24 | w << 40; + v3 += v4 + m4; + w = v14 ^ v3; + v14 = w >>> 16 | w << 48; + v9 += v14; + w = v4 ^ v9; + v4 = w >>> 63 | w << 1; + // round 3 + v0 += v4 + m7; + w = v12 ^ v0; + v12 = w >>> 32 | w << 32; + v8 += v12; + w = v4 ^ v8; + v4 = w >>> 24 | w << 40; + v0 += v4 + m9; + w = v12 ^ v0; + v12 = w >>> 16 | w << 48; + v8 += v12; + w = v4 ^ v8; + v4 = w >>> 63 | w << 1; + v1 += v5 + m3; + w = v13 ^ v1; + v13 = w >>> 32 | w << 32; + v9 += v13; + w = v5 ^ v9; + v5 = w >>> 24 | w << 40; + v1 += v5 + m1; + w = v13 ^ v1; + v13 = w >>> 16 | w << 48; + v9 += v13; + w = v5 ^ v9; + v5 = w >>> 63 | w << 1; + v2 += v6 + m13; + w = v14 ^ v2; + v14 = w >>> 32 | w << 32; + v10 += v14; + w = v6 ^ v10; + v6 = w >>> 24 | w << 40; + v2 += v6 + m12; + w = v14 ^ v2; + v14 = w >>> 16 | w << 48; + v10 += v14; + w = v6 ^ v10; + v6 = w >>> 63 | w << 1; + v3 += v7 + m11; + w = v15 ^ v3; + v15 = w >>> 32 | w << 32; + v11 += v15; + w = v7 ^ v11; + v7 = w >>> 24 | w << 40; + v3 += v7 + m14; + w = v15 ^ v3; + v15 = w >>> 16 | w << 48; + v11 += v15; + w = v7 ^ v11; + v7 = w >>> 63 | w << 1; + v0 += v5 + m2; + w = v15 ^ v0; + v15 = w >>> 32 | w << 32; + v10 += v15; + w = v5 ^ v10; + v5 = w >>> 24 | w << 40; + v0 += v5 + m6; + w = v15 ^ v0; + v15 = w >>> 16 | w << 48; + v10 += v15; + w = v5 ^ v10; + v5 = w >>> 63 | w << 1; + v1 += v6 + m5; + w = v12 ^ v1; + v12 = w >>> 32 | w << 32; + v11 += v12; + w = v6 ^ v11; + v6 = w >>> 24 | w << 40; + v1 += v6 + m10; + w = v12 ^ v1; + v12 = w >>> 16 | w << 48; + v11 += v12; + w = v6 ^ v11; + v6 = w >>> 63 | w << 1; + v2 += v7 + m4; + w = v13 ^ v2; + v13 = w >>> 32 | w << 32; + v8 += v13; + w = v7 ^ v8; + v7 = w >>> 24 | w << 40; + v2 += v7 + m0; + w = v13 ^ v2; + v13 = w >>> 16 | w << 48; + v8 += v13; + w = v7 ^ v8; + v7 = w >>> 63 | w << 1; + v3 += v4 + m15; + w = v14 ^ v3; + v14 = w >>> 32 | w << 32; + v9 += v14; + w = v4 ^ v9; + v4 = w >>> 24 | w << 40; + v3 += v4 + m8; + w = v14 ^ v3; + v14 = w >>> 16 | w << 48; + v9 += v14; + w = v4 ^ v9; + v4 = w >>> 63 | w << 1; + // round 4 + v0 += v4 + m9; + w = v12 ^ v0; + v12 = w >>> 32 | w << 32; + v8 += v12; + w = v4 ^ v8; + v4 = w >>> 24 | w << 40; + v0 += v4 + m0; + w = v12 ^ v0; + v12 = w >>> 16 | w << 48; + v8 += v12; + w = v4 ^ v8; + v4 = w >>> 63 | w << 1; + v1 += v5 + m5; + w = v13 ^ v1; + v13 = w >>> 32 | w << 32; + v9 += v13; + w = v5 ^ v9; + v5 = w >>> 24 | w << 40; + v1 += v5 + m7; + w = v13 ^ v1; + v13 = w >>> 16 | w << 48; + v9 += v13; + w = v5 ^ v9; + v5 = w >>> 63 | w << 1; + v2 += v6 + m2; + w = v14 ^ v2; + v14 = w >>> 32 | w << 32; + v10 += v14; + w = v6 ^ v10; + v6 = w >>> 24 | w << 40; + v2 += v6 + m4; + w = v14 ^ v2; + v14 = w >>> 16 | w << 48; + v10 += v14; + w = v6 ^ v10; + v6 = w >>> 63 | w << 1; + v3 += v7 + m10; + w = v15 ^ v3; + v15 = w >>> 32 | w << 32; + v11 += v15; + w = v7 ^ v11; + v7 = w >>> 24 | w << 40; + v3 += v7 + m15; + w = v15 ^ v3; + v15 = w >>> 16 | w << 48; + v11 += v15; + w = v7 ^ v11; + v7 = w >>> 63 | w << 1; + v0 += v5 + m14; + w = v15 ^ v0; + v15 = w >>> 32 | w << 32; + v10 += v15; + w = v5 ^ v10; + v5 = w >>> 24 | w << 40; + v0 += v5 + m1; + w = v15 ^ v0; + v15 = w >>> 16 | w << 48; + v10 += v15; + w = v5 ^ v10; + v5 = w >>> 63 | w << 1; + v1 += v6 + m11; + w = v12 ^ v1; + v12 = w >>> 32 | w << 32; + v11 += v12; + w = v6 ^ v11; + v6 = w >>> 24 | w << 40; + v1 += v6 + m12; + w = v12 ^ v1; + v12 = w >>> 16 | w << 48; + v11 += v12; + w = v6 ^ v11; + v6 = w >>> 63 | w << 1; + v2 += v7 + m6; + w = v13 ^ v2; + v13 = w >>> 32 | w << 32; + v8 += v13; + w = v7 ^ v8; + v7 = w >>> 24 | w << 40; + v2 += v7 + m8; + w = v13 ^ v2; + v13 = w >>> 16 | w << 48; + v8 += v13; + w = v7 ^ v8; + v7 = w >>> 63 | w << 1; + v3 += v4 + m3; + w = v14 ^ v3; + v14 = w >>> 32 | w << 32; + v9 += v14; + w = v4 ^ v9; + v4 = w >>> 24 | w << 40; + v3 += v4 + m13; + w = v14 ^ v3; + v14 = w >>> 16 | w << 48; + v9 += v14; + w = v4 ^ v9; + v4 = w >>> 63 | w << 1; + // round 5 + v0 += v4 + m2; + w = v12 ^ v0; + v12 = w >>> 32 | w << 32; + v8 += v12; + w = v4 ^ v8; + v4 = w >>> 24 | w << 40; + v0 += v4 + m12; + w = v12 ^ v0; + v12 = w >>> 16 | w << 48; + v8 += v12; + w = v4 ^ v8; + v4 = w >>> 63 | w << 1; + v1 += v5 + m6; + w = v13 ^ v1; + v13 = w >>> 32 | w << 32; + v9 += v13; + w = v5 ^ v9; + v5 = w >>> 24 | w << 40; + v1 += v5 + m10; + w = v13 ^ v1; + v13 = w >>> 16 | w << 48; + v9 += v13; + w = v5 ^ v9; + v5 = w >>> 63 | w << 1; + v2 += v6 + m0; + w = v14 ^ v2; + v14 = w >>> 32 | w << 32; + v10 += v14; + w = v6 ^ v10; + v6 = w >>> 24 | w << 40; + v2 += v6 + m11; + w = v14 ^ v2; + v14 = w >>> 16 | w << 48; + v10 += v14; + w = v6 ^ v10; + v6 = w >>> 63 | w << 1; + v3 += v7 + m8; + w = v15 ^ v3; + v15 = w >>> 32 | w << 32; + v11 += v15; + w = v7 ^ v11; + v7 = w >>> 24 | w << 40; + v3 += v7 + m3; + w = v15 ^ v3; + v15 = w >>> 16 | w << 48; + v11 += v15; + w = v7 ^ v11; + v7 = w >>> 63 | w << 1; + v0 += v5 + m4; + w = v15 ^ v0; + v15 = w >>> 32 | w << 32; + v10 += v15; + w = v5 ^ v10; + v5 = w >>> 24 | w << 40; + v0 += v5 + m13; + w = v15 ^ v0; + v15 = w >>> 16 | w << 48; + v10 += v15; + w = v5 ^ v10; + v5 = w >>> 63 | w << 1; + v1 += v6 + m7; + w = v12 ^ v1; + v12 = w >>> 32 | w << 32; + v11 += v12; + w = v6 ^ v11; + v6 = w >>> 24 | w << 40; + v1 += v6 + m5; + w = v12 ^ v1; + v12 = w >>> 16 | w << 48; + v11 += v12; + w = v6 ^ v11; + v6 = w >>> 63 | w << 1; + v2 += v7 + m15; + w = v13 ^ v2; + v13 = w >>> 32 | w << 32; + v8 += v13; + w = v7 ^ v8; + v7 = w >>> 24 | w << 40; + v2 += v7 + m14; + w = v13 ^ v2; + v13 = w >>> 16 | w << 48; + v8 += v13; + w = v7 ^ v8; + v7 = w >>> 63 | w << 1; + v3 += v4 + m1; + w = v14 ^ v3; + v14 = w >>> 32 | w << 32; + v9 += v14; + w = v4 ^ v9; + v4 = w >>> 24 | w << 40; + v3 += v4 + m9; + w = v14 ^ v3; + v14 = w >>> 16 | w << 48; + v9 += v14; + w = v4 ^ v9; + v4 = w >>> 63 | w << 1; + // round 6 + v0 += v4 + m12; + w = v12 ^ v0; + v12 = w >>> 32 | w << 32; + v8 += v12; + w = v4 ^ v8; + v4 = w >>> 24 | w << 40; + v0 += v4 + m5; + w = v12 ^ v0; + v12 = w >>> 16 | w << 48; + v8 += v12; + w = v4 ^ v8; + v4 = w >>> 63 | w << 1; + v1 += v5 + m1; + w = v13 ^ v1; + v13 = w >>> 32 | w << 32; + v9 += v13; + w = v5 ^ v9; + v5 = w >>> 24 | w << 40; + v1 += v5 + m15; + w = v13 ^ v1; + v13 = w >>> 16 | w << 48; + v9 += v13; + w = v5 ^ v9; + v5 = w >>> 63 | w << 1; + v2 += v6 + m14; + w = v14 ^ v2; + v14 = w >>> 32 | w << 32; + v10 += v14; + w = v6 ^ v10; + v6 = w >>> 24 | w << 40; + v2 += v6 + m13; + w = v14 ^ v2; + v14 = w >>> 16 | w << 48; + v10 += v14; + w = v6 ^ v10; + v6 = w >>> 63 | w << 1; + v3 += v7 + m4; + w = v15 ^ v3; + v15 = w >>> 32 | w << 32; + v11 += v15; + w = v7 ^ v11; + v7 = w >>> 24 | w << 40; + v3 += v7 + m10; + w = v15 ^ v3; + v15 = w >>> 16 | w << 48; + v11 += v15; + w = v7 ^ v11; + v7 = w >>> 63 | w << 1; + v0 += v5 + m0; + w = v15 ^ v0; + v15 = w >>> 32 | w << 32; + v10 += v15; + w = v5 ^ v10; + v5 = w >>> 24 | w << 40; + v0 += v5 + m7; + w = v15 ^ v0; + v15 = w >>> 16 | w << 48; + v10 += v15; + w = v5 ^ v10; + v5 = w >>> 63 | w << 1; + v1 += v6 + m6; + w = v12 ^ v1; + v12 = w >>> 32 | w << 32; + v11 += v12; + w = v6 ^ v11; + v6 = w >>> 24 | w << 40; + v1 += v6 + m3; + w = v12 ^ v1; + v12 = w >>> 16 | w << 48; + v11 += v12; + w = v6 ^ v11; + v6 = w >>> 63 | w << 1; + v2 += v7 + m9; + w = v13 ^ v2; + v13 = w >>> 32 | w << 32; + v8 += v13; + w = v7 ^ v8; + v7 = w >>> 24 | w << 40; + v2 += v7 + m2; + w = v13 ^ v2; + v13 = w >>> 16 | w << 48; + v8 += v13; + w = v7 ^ v8; + v7 = w >>> 63 | w << 1; + v3 += v4 + m8; + w = v14 ^ v3; + v14 = w >>> 32 | w << 32; + v9 += v14; + w = v4 ^ v9; + v4 = w >>> 24 | w << 40; + v3 += v4 + m11; + w = v14 ^ v3; + v14 = w >>> 16 | w << 48; + v9 += v14; + w = v4 ^ v9; + v4 = w >>> 63 | w << 1; + // round 7 + v0 += v4 + m13; + w = v12 ^ v0; + v12 = w >>> 32 | w << 32; + v8 += v12; + w = v4 ^ v8; + v4 = w >>> 24 | w << 40; + v0 += v4 + m11; + w = v12 ^ v0; + v12 = w >>> 16 | w << 48; + v8 += v12; + w = v4 ^ v8; + v4 = w >>> 63 | w << 1; + v1 += v5 + m7; + w = v13 ^ v1; + v13 = w >>> 32 | w << 32; + v9 += v13; + w = v5 ^ v9; + v5 = w >>> 24 | w << 40; + v1 += v5 + m14; + w = v13 ^ v1; + v13 = w >>> 16 | w << 48; + v9 += v13; + w = v5 ^ v9; + v5 = w >>> 63 | w << 1; + v2 += v6 + m12; + w = v14 ^ v2; + v14 = w >>> 32 | w << 32; + v10 += v14; + w = v6 ^ v10; + v6 = w >>> 24 | w << 40; + v2 += v6 + m1; + w = v14 ^ v2; + v14 = w >>> 16 | w << 48; + v10 += v14; + w = v6 ^ v10; + v6 = w >>> 63 | w << 1; + v3 += v7 + m3; + w = v15 ^ v3; + v15 = w >>> 32 | w << 32; + v11 += v15; + w = v7 ^ v11; + v7 = w >>> 24 | w << 40; + v3 += v7 + m9; + w = v15 ^ v3; + v15 = w >>> 16 | w << 48; + v11 += v15; + w = v7 ^ v11; + v7 = w >>> 63 | w << 1; + v0 += v5 + m5; + w = v15 ^ v0; + v15 = w >>> 32 | w << 32; + v10 += v15; + w = v5 ^ v10; + v5 = w >>> 24 | w << 40; + v0 += v5 + m0; + w = v15 ^ v0; + v15 = w >>> 16 | w << 48; + v10 += v15; + w = v5 ^ v10; + v5 = w >>> 63 | w << 1; + v1 += v6 + m15; + w = v12 ^ v1; + v12 = w >>> 32 | w << 32; + v11 += v12; + w = v6 ^ v11; + v6 = w >>> 24 | w << 40; + v1 += v6 + m4; + w = v12 ^ v1; + v12 = w >>> 16 | w << 48; + v11 += v12; + w = v6 ^ v11; + v6 = w >>> 63 | w << 1; + v2 += v7 + m8; + w = v13 ^ v2; + v13 = w >>> 32 | w << 32; + v8 += v13; + w = v7 ^ v8; + v7 = w >>> 24 | w << 40; + v2 += v7 + m6; + w = v13 ^ v2; + v13 = w >>> 16 | w << 48; + v8 += v13; + w = v7 ^ v8; + v7 = w >>> 63 | w << 1; + v3 += v4 + m2; + w = v14 ^ v3; + v14 = w >>> 32 | w << 32; + v9 += v14; + w = v4 ^ v9; + v4 = w >>> 24 | w << 40; + v3 += v4 + m10; + w = v14 ^ v3; + v14 = w >>> 16 | w << 48; + v9 += v14; + w = v4 ^ v9; + v4 = w >>> 63 | w << 1; + // round 8 + v0 += v4 + m6; + w = v12 ^ v0; + v12 = w >>> 32 | w << 32; + v8 += v12; + w = v4 ^ v8; + v4 = w >>> 24 | w << 40; + v0 += v4 + m15; + w = v12 ^ v0; + v12 = w >>> 16 | w << 48; + v8 += v12; + w = v4 ^ v8; + v4 = w >>> 63 | w << 1; + v1 += v5 + m14; + w = v13 ^ v1; + v13 = w >>> 32 | w << 32; + v9 += v13; + w = v5 ^ v9; + v5 = w >>> 24 | w << 40; + v1 += v5 + m9; + w = v13 ^ v1; + v13 = w >>> 16 | w << 48; + v9 += v13; + w = v5 ^ v9; + v5 = w >>> 63 | w << 1; + v2 += v6 + m11; + w = v14 ^ v2; + v14 = w >>> 32 | w << 32; + v10 += v14; + w = v6 ^ v10; + v6 = w >>> 24 | w << 40; + v2 += v6 + m3; + w = v14 ^ v2; + v14 = w >>> 16 | w << 48; + v10 += v14; + w = v6 ^ v10; + v6 = w >>> 63 | w << 1; + v3 += v7 + m0; + w = v15 ^ v3; + v15 = w >>> 32 | w << 32; + v11 += v15; + w = v7 ^ v11; + v7 = w >>> 24 | w << 40; + v3 += v7 + m8; + w = v15 ^ v3; + v15 = w >>> 16 | w << 48; + v11 += v15; + w = v7 ^ v11; + v7 = w >>> 63 | w << 1; + v0 += v5 + m12; + w = v15 ^ v0; + v15 = w >>> 32 | w << 32; + v10 += v15; + w = v5 ^ v10; + v5 = w >>> 24 | w << 40; + v0 += v5 + m2; + w = v15 ^ v0; + v15 = w >>> 16 | w << 48; + v10 += v15; + w = v5 ^ v10; + v5 = w >>> 63 | w << 1; + v1 += v6 + m13; + w = v12 ^ v1; + v12 = w >>> 32 | w << 32; + v11 += v12; + w = v6 ^ v11; + v6 = w >>> 24 | w << 40; + v1 += v6 + m7; + w = v12 ^ v1; + v12 = w >>> 16 | w << 48; + v11 += v12; + w = v6 ^ v11; + v6 = w >>> 63 | w << 1; + v2 += v7 + m1; + w = v13 ^ v2; + v13 = w >>> 32 | w << 32; + v8 += v13; + w = v7 ^ v8; + v7 = w >>> 24 | w << 40; + v2 += v7 + m4; + w = v13 ^ v2; + v13 = w >>> 16 | w << 48; + v8 += v13; + w = v7 ^ v8; + v7 = w >>> 63 | w << 1; + v3 += v4 + m10; + w = v14 ^ v3; + v14 = w >>> 32 | w << 32; + v9 += v14; + w = v4 ^ v9; + v4 = w >>> 24 | w << 40; + v3 += v4 + m5; + w = v14 ^ v3; + v14 = w >>> 16 | w << 48; + v9 += v14; + w = v4 ^ v9; + v4 = w >>> 63 | w << 1; + // round 9 + v0 += v4 + m10; + w = v12 ^ v0; + v12 = w >>> 32 | w << 32; + v8 += v12; + w = v4 ^ v8; + v4 = w >>> 24 | w << 40; + v0 += v4 + m2; + w = v12 ^ v0; + v12 = w >>> 16 | w << 48; + v8 += v12; + w = v4 ^ v8; + v4 = w >>> 63 | w << 1; + v1 += v5 + m8; + w = v13 ^ v1; + v13 = w >>> 32 | w << 32; + v9 += v13; + w = v5 ^ v9; + v5 = w >>> 24 | w << 40; + v1 += v5 + m4; + w = v13 ^ v1; + v13 = w >>> 16 | w << 48; + v9 += v13; + w = v5 ^ v9; + v5 = w >>> 63 | w << 1; + v2 += v6 + m7; + w = v14 ^ v2; + v14 = w >>> 32 | w << 32; + v10 += v14; + w = v6 ^ v10; + v6 = w >>> 24 | w << 40; + v2 += v6 + m6; + w = v14 ^ v2; + v14 = w >>> 16 | w << 48; + v10 += v14; + w = v6 ^ v10; + v6 = w >>> 63 | w << 1; + v3 += v7 + m1; + w = v15 ^ v3; + v15 = w >>> 32 | w << 32; + v11 += v15; + w = v7 ^ v11; + v7 = w >>> 24 | w << 40; + v3 += v7 + m5; + w = v15 ^ v3; + v15 = w >>> 16 | w << 48; + v11 += v15; + w = v7 ^ v11; + v7 = w >>> 63 | w << 1; + v0 += v5 + m15; + w = v15 ^ v0; + v15 = w >>> 32 | w << 32; + v10 += v15; + w = v5 ^ v10; + v5 = w >>> 24 | w << 40; + v0 += v5 + m11; + w = v15 ^ v0; + v15 = w >>> 16 | w << 48; + v10 += v15; + w = v5 ^ v10; + v5 = w >>> 63 | w << 1; + v1 += v6 + m9; + w = v12 ^ v1; + v12 = w >>> 32 | w << 32; + v11 += v12; + w = v6 ^ v11; + v6 = w >>> 24 | w << 40; + v1 += v6 + m14; + w = v12 ^ v1; + v12 = w >>> 16 | w << 48; + v11 += v12; + w = v6 ^ v11; + v6 = w >>> 63 | w << 1; + v2 += v7 + m3; + w = v13 ^ v2; + v13 = w >>> 32 | w << 32; + v8 += v13; + w = v7 ^ v8; + v7 = w >>> 24 | w << 40; + v2 += v7 + m12; + w = v13 ^ v2; + v13 = w >>> 16 | w << 48; + v8 += v13; + w = v7 ^ v8; + v7 = w >>> 63 | w << 1; + v3 += v4 + m13; + w = v14 ^ v3; + v14 = w >>> 32 | w << 32; + v9 += v14; + w = v4 ^ v9; + v4 = w >>> 24 | w << 40; + v3 += v4 + m0; + w = v14 ^ v3; + v14 = w >>> 16 | w << 48; + v9 += v14; + w = v4 ^ v9; + v4 = w >>> 63 | w << 1; + // round 10 + v0 += v4 + m0; + w = v12 ^ v0; + v12 = w >>> 32 | w << 32; + v8 += v12; + w = v4 ^ v8; + v4 = w >>> 24 | w << 40; + v0 += v4 + m1; + w = v12 ^ v0; + v12 = w >>> 16 | w << 48; + v8 += v12; + w = v4 ^ v8; + v4 = w >>> 63 | w << 1; + v1 += v5 + m2; + w = v13 ^ v1; + v13 = w >>> 32 | w << 32; + v9 += v13; + w = v5 ^ v9; + v5 = w >>> 24 | w << 40; + v1 += v5 + m3; + w = v13 ^ v1; + v13 = w >>> 16 | w << 48; + v9 += v13; + w = v5 ^ v9; + v5 = w >>> 63 | w << 1; + v2 += v6 + m4; + w = v14 ^ v2; + v14 = w >>> 32 | w << 32; + v10 += v14; + w = v6 ^ v10; + v6 = w >>> 24 | w << 40; + v2 += v6 + m5; + w = v14 ^ v2; + v14 = w >>> 16 | w << 48; + v10 += v14; + w = v6 ^ v10; + v6 = w >>> 63 | w << 1; + v3 += v7 + m6; + w = v15 ^ v3; + v15 = w >>> 32 | w << 32; + v11 += v15; + w = v7 ^ v11; + v7 = w >>> 24 | w << 40; + v3 += v7 + m7; + w = v15 ^ v3; + v15 = w >>> 16 | w << 48; + v11 += v15; + w = v7 ^ v11; + v7 = w >>> 63 | w << 1; + v0 += v5 + m8; + w = v15 ^ v0; + v15 = w >>> 32 | w << 32; + v10 += v15; + w = v5 ^ v10; + v5 = w >>> 24 | w << 40; + v0 += v5 + m9; + w = v15 ^ v0; + v15 = w >>> 16 | w << 48; + v10 += v15; + w = v5 ^ v10; + v5 = w >>> 63 | w << 1; + v1 += v6 + m10; + w = v12 ^ v1; + v12 = w >>> 32 | w << 32; + v11 += v12; + w = v6 ^ v11; + v6 = w >>> 24 | w << 40; + v1 += v6 + m11; + w = v12 ^ v1; + v12 = w >>> 16 | w << 48; + v11 += v12; + w = v6 ^ v11; + v6 = w >>> 63 | w << 1; + v2 += v7 + m12; + w = v13 ^ v2; + v13 = w >>> 32 | w << 32; + v8 += v13; + w = v7 ^ v8; + v7 = w >>> 24 | w << 40; + v2 += v7 + m13; + w = v13 ^ v2; + v13 = w >>> 16 | w << 48; + v8 += v13; + w = v7 ^ v8; + v7 = w >>> 63 | w << 1; + v3 += v4 + m14; + w = v14 ^ v3; + v14 = w >>> 32 | w << 32; + v9 += v14; + w = v4 ^ v9; + v4 = w >>> 24 | w << 40; + v3 += v4 + m15; + w = v14 ^ v3; + v14 = w >>> 16 | w << 48; + v9 += v14; + w = v4 ^ v9; + v4 = w >>> 63 | w << 1; + // round 11 + v0 += v4 + m14; + w = v12 ^ v0; + v12 = w >>> 32 | w << 32; + v8 += v12; + w = v4 ^ v8; + v4 = w >>> 24 | w << 40; + v0 += v4 + m10; + w = v12 ^ v0; + v12 = w >>> 16 | w << 48; + v8 += v12; + w = v4 ^ v8; + v4 = w >>> 63 | w << 1; + v1 += v5 + m4; + w = v13 ^ v1; + v13 = w >>> 32 | w << 32; + v9 += v13; + w = v5 ^ v9; + v5 = w >>> 24 | w << 40; + v1 += v5 + m8; + w = v13 ^ v1; + v13 = w >>> 16 | w << 48; + v9 += v13; + w = v5 ^ v9; + v5 = w >>> 63 | w << 1; + v2 += v6 + m9; + w = v14 ^ v2; + v14 = w >>> 32 | w << 32; + v10 += v14; + w = v6 ^ v10; + v6 = w >>> 24 | w << 40; + v2 += v6 + m15; + w = v14 ^ v2; + v14 = w >>> 16 | w << 48; + v10 += v14; + w = v6 ^ v10; + v6 = w >>> 63 | w << 1; + v3 += v7 + m13; + w = v15 ^ v3; + v15 = w >>> 32 | w << 32; + v11 += v15; + w = v7 ^ v11; + v7 = w >>> 24 | w << 40; + v3 += v7 + m6; + w = v15 ^ v3; + v15 = w >>> 16 | w << 48; + v11 += v15; + w = v7 ^ v11; + v7 = w >>> 63 | w << 1; + v0 += v5 + m1; + w = v15 ^ v0; + v15 = w >>> 32 | w << 32; + v10 += v15; + w = v5 ^ v10; + v5 = w >>> 24 | w << 40; + v0 += v5 + m12; + w = v15 ^ v0; + v15 = w >>> 16 | w << 48; + v10 += v15; + w = v5 ^ v10; + v5 = w >>> 63 | w << 1; + v1 += v6 + m0; + w = v12 ^ v1; + v12 = w >>> 32 | w << 32; + v11 += v12; + w = v6 ^ v11; + v6 = w >>> 24 | w << 40; + v1 += v6 + m2; + w = v12 ^ v1; + v12 = w >>> 16 | w << 48; + v11 += v12; + w = v6 ^ v11; + v6 = w >>> 63 | w << 1; + v2 += v7 + m11; + w = v13 ^ v2; + v13 = w >>> 32 | w << 32; + v8 += v13; + w = v7 ^ v8; + v7 = w >>> 24 | w << 40; + v2 += v7 + m7; + w = v13 ^ v2; + v13 = w >>> 16 | w << 48; + v8 += v13; + w = v7 ^ v8; + v7 = w >>> 63 | w << 1; + v3 += v4 + m5; + w = v14 ^ v3; + v14 = w >>> 32 | w << 32; + v9 += v14; + w = v4 ^ v9; + v4 = w >>> 24 | w << 40; + v3 += v4 + m3; + w = v14 ^ v3; + v14 = w >>> 16 | w << 48; + v9 += v14; + w = v4 ^ v9; + v4 = w >>> 63 | w << 1; + hw[0] ^= v0 ^ v8; + hw[1] ^= v1 ^ v9; + hw[2] ^= v2 ^ v10; + hw[3] ^= v3 ^ v11; + hw[4] ^= v4 ^ v12; + hw[5] ^= v5 ^ v13; + hw[6] ^= v6 ^ v14; + hw[7] ^= v7 ^ v15; + } + + private void gs(int a, int b, int c, int d, long x, long y) { + int va = (int) v[a]; + int vb = (int) v[b]; + int vc = (int) v[c]; + int vd = (int) v[d]; + va = va + vb + (int) x; + vd = Integer.rotateRight(vd ^ va, 16); + vc = vc + vd; + vb = Integer.rotateRight(vb ^ vc, 12); + va = va + vb + (int) y; + vd = Integer.rotateRight(vd ^ va, 8); + vc = vc + vd; + vb = Integer.rotateRight(vb ^ vc, 7); + v[a] = va & 0xffffffffL; + v[b] = vb & 0xffffffffL; + v[c] = vc & 0xffffffffL; + v[d] = vd & 0xffffffffL; + } + + @Override + MessageDigestImpl copy() { + Blake2 c = new Blake2(big, digestSize, key, salt, person); + System.arraycopy(h, 0, c.h, 0, 8); + System.arraycopy(buf, 0, c.buf, 0, blockSize); + c.bufLen = bufLen; + c.t0 = t0; + c.t1 = t1; + return c; + } + + @Override + byte[] digest() { + byte[] out = finish(); + reset(); + return out; + } + + /// Finishing changes only the chain words and the counters (the + /// padding lands past bufLen, where more input overwrites it), so + /// they are saved and put back instead of copying the whole digest: + /// hashlib's digest() and hexdigest() made a copy per call. + @Override + byte[] peekDigest() { + long[] hw = h; + long h0 = hw[0]; + long h1 = hw[1]; + long h2 = hw[2]; + long h3 = hw[3]; + long h4 = hw[4]; + long h5 = hw[5]; + long h6 = hw[6]; + long h7 = hw[7]; + long s0 = t0; + long s1 = t1; + byte[] out = finish(); + hw[0] = h0; + hw[1] = h1; + hw[2] = h2; + hw[3] = h3; + hw[4] = h4; + hw[5] = h5; + hw[6] = h6; + hw[7] = h7; + t0 = s0; + t1 = s1; + return out; + } + + private byte[] finish() { + count(bufLen); + // One copy from a block of zeros: a loop from bufLen is not one the + // bounds-check pass can prove, so it was a checked store per byte where + // C pads with memset; a primitive arraycopy is a plain memmove. + System.arraycopy(ZERO_BLOCK, 0, buf, bufLen, blockSize - bufLen); + compress(buf, 0, true); + // Shifts, not i / w and i % w: with w a variable those were two + // divisions per digest byte. + int sh = big ? 3 : 2; + int lane = (1 << sh) - 1; + byte[] out = new byte[digestSize]; + for (int i = 0; i < out.length; i++) { + out[i] = (byte) (h[i >>> sh] >>> ((i & lane) << 3)); + } + return out; + } + + /// Zeros to pad the last block with; never written. + private static final byte[] ZERO_BLOCK = new byte[128]; + + private static int le32(byte[] b, int i) { + return b[i] & 0xff | (b[i + 1] & 0xff) << 8 | (b[i + 2] & 0xff) << 16 | (b[i + 3] & 0xff) << 24; + } + } } diff --git a/CodenameOne/src/com/codename1/security/Pbkdf2.java b/CodenameOne/src/com/codename1/security/Pbkdf2.java index 42faddeff09..3fb9bfaf330 100644 --- a/CodenameOne/src/com/codename1/security/Pbkdf2.java +++ b/CodenameOne/src/com/codename1/security/Pbkdf2.java @@ -77,22 +77,64 @@ public static byte[] hmacSha256(byte[] password, byte[] salt, int iterations, in return derive(Hash.SHA256, password, salt, iterations, length); } - private static byte[] derive(String hash, byte[] password, byte[] salt, int iterations, int length) { + /// PBKDF2 (RFC 8018) with HMAC over any algorithm [Hmac#create(String, byte[])] + /// accepts. SHA-256 and SHA-512 take the engine's native derivation when + /// one is installed; see [#hmacSha512] for the other parameters. + /// + /// #### Throws + /// - `CryptoException`: if an argument is null or out of range, or the + /// algorithm has no HMAC + public static byte[] derive(String hash, byte[] password, byte[] salt, int iterations, int length) { if (password == null || salt == null) { throw new CryptoException("password and salt must not be null"); } if (iterations < 1 || length < 1) { throw new CryptoException("iterations and length must be positive"); } - byte[] fast = CryptoEngine.get().pbkdf2(hash, password, salt, iterations, length); + String a = MessageDigestImpl.normalise(hash); + if (!"SHA256".equals(a) && !"SHA512".equals(a)) { + return portable(hash, password, salt, iterations, length); + } + String name = "SHA512".equals(a) ? Hash.SHA512 : Hash.SHA256; + byte[] fast = CryptoEngine.get().pbkdf2(name, password, salt, iterations, length); if (fast != null && fast.length == length) { return fast; } - return Hash.SHA512.equals(hash) + return Hash.SHA512.equals(name) ? portable512(password, salt, iterations, length) : portable256(password, salt, iterations, length); } + /// The derivation over a streaming [Hmac], for the algorithms with no + /// specialised loop. + static byte[] portable(String hash, byte[] password, byte[] salt, int iterations, int length) { + Hmac mac = Hmac.create(hash, password); + int hLen = mac.tagLength(); + byte[] out = new byte[length]; + byte[] counter = new byte[4]; + int pos = 0; + for (int index = 1; pos < length; index++) { + counter[0] = (byte) (index >>> 24); + counter[1] = (byte) (index >>> 16); + counter[2] = (byte) (index >>> 8); + counter[3] = (byte) index; + mac.update(salt); + byte[] u = mac.doFinal(counter); + byte[] t = new byte[hLen]; + System.arraycopy(u, 0, t, 0, hLen); + for (int i = 1; i < iterations; i++) { + u = mac.doFinal(u); + for (int j = 0; j < hLen; j++) { + t[j] ^= u[j]; + } + } + int n = Math.min(hLen, length - pos); + System.arraycopy(t, 0, out, pos, n); + pos += n; + } + return out; + } + /// The Java derivation with HMAC-SHA-512, whatever engine is installed: /// what an engine falls back to, and what the tests hold a native one to. static byte[] portable512(byte[] password, byte[] salt, int iterations, int length) { diff --git a/CodenameOne/src/com/codename1/ui/Display.java b/CodenameOne/src/com/codename1/ui/Display.java index 076f2246865..7573a42bb31 100644 --- a/CodenameOne/src/com/codename1/ui/Display.java +++ b/CodenameOne/src/com/codename1/ui/Display.java @@ -8408,6 +8408,20 @@ public Database openOrCreate(String databaseName) throws IOException { return impl.openOrCreateDB(databaseName); } + /// Whether `#openInMemoryDatabase()` is supported on this platform. + public boolean isInMemoryDatabaseSupported() { + return impl.isInMemoryDatabaseSupported(); + } + + /// Opens a new private database held in memory, gone once closed. + /// + /// #### Throws + /// + /// - `IOException`: where the platform has no in-memory databases + public Database openInMemoryDatabase() throws IOException { + return impl.openInMemoryDB(); + } + /// Opens an encrypted database or creates one if it does not exist. /// /// Prefer `com.codename1.db.Database#openOrCreate(java.lang.String, com.codename1.db.DatabaseConfig)`, diff --git a/NOTICE b/NOTICE index b2de9b78026..1efb622e835 100644 --- a/NOTICE +++ b/NOTICE @@ -286,6 +286,118 @@ Pillow's notice: Copyright (c) 1996-2003 by Fredrik Lundh Licensed under the MIT-CMU (HPND) license; the full text is in the file. +================================================================================ +CPython standard library +================================================================================ + +Some modules of the Python runtime's standard library, in +maven/python-transpiler (src/main/resources/com/codename1/python/stdlib), are +derived from the modules of the same name in CPython's Lib directory and retain +the Python Software Foundation's notice: _markupbase, asyncio.subprocess, +calendar, difflib, encodings, fractions, gettext, html.parser, importlib.util, +ipaddress, locale, logging, mimetypes, ntpath, pickle, platform, pprint, selectors, shutil, stringprep, subprocess, +tempfile, xml.dom, xml.dom.NodeFilter, xml.dom.domreg, xml.dom.expatbuilder, +xml.dom.minicompat, xml.dom.minidom, xml.dom.pulldom, xml.dom.xmlbuilder, +xml.etree.ElementPath, xml.etree.ElementTree, xml.sax, xml.sax._exceptions, +xml.sax.expatreader, xml.sax.handler, xml.sax.saxutils, xml.sax.xmlreader. Each +file names its origin and summarises the changes. + + Copyright (c) 2001 Python Software Foundation; All Rights Reserved + Licensed under the Python Software Foundation License Version 2; the full + text is in maven/python-transpiler/third-party/cpython/LICENSE.txt. + +================================================================================ +PyYAML +================================================================================ + +The yaml package of the Python runtime (maven/python-transpiler, src/main/resources/com/codename1/python/site/yaml) is derived from PyYAML's lib/yaml (https://pyyaml.org), combined into one module and rewritten for the Codename One Python runtime. PyYAML is distributed under the MIT license: + + Copyright (c) 2017-2021 Ingy döt Net + Copyright (c) 2006-2016 Kirill Simonov + + Permission is hereby granted, free of charge, to any person obtaining a copy of + this software and associated documentation files (the "Software"), to deal in + the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do + so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. + +================================================================================ +ElementTree (Fredrik Lundh) +================================================================================ + +xml.etree.ElementTree and xml.etree.ElementPath are derived from CPython's modules of the same name, which carry Fredrik Lundh's notice (retained in each file): + + Copyright (c) 1999-2008 by Fredrik Lundh + + By obtaining, using, and/or copying this software and/or its associated + documentation, you agree that you have read, understood, and will comply with + the following terms and conditions: permission to use, copy, modify, and + distribute this software and its associated documentation for any purpose and + without fee is hereby granted, provided that the above copyright notice + appears in all copies, and that both that copyright notice and this permission + notice appear in supporting documentation, and that the name of Secret Labs AB + or the author not be used in advertising or publicity pertaining to + distribution of the software without specific, written prior permission. SECRET + LABS AB AND THE AUTHOR DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE. + +================================================================================ +subprocess (Peter Astrand) +================================================================================ + +subprocess is derived from CPython's Lib/subprocess.py, which carries (retained in the file): + + Copyright (c) 2003-2005 by Peter Astrand + + Licensed to PSF under a Contributor Agreement. + +================================================================================ +platform (Marc-Andre Lemburg, eGenix.com) +================================================================================ + +platform is derived from CPython's Lib/platform.py, which carries (retained in the file): + + Copyright (c) 1999-2000, Marc-Andre Lemburg; mailto:mal@lemburg.com + Copyright (c) 2000-2010, eGenix.com Software GmbH; mailto:info@egenix.com + + Permission to use, copy, modify, and distribute this software and its + documentation for any purpose and without fee or royalty is hereby granted, + provided that the above copyright notice appear in all copies and that both + that copyright notice and this permission notice appear in supporting + documentation or portions thereof, including modifications, that you make. + +================================================================================ +logging (Vinay Sajip) +================================================================================ + +logging is derived from CPython's Lib/logging/__init__.py, which carries (retained in the file): + + Copyright 2001-2022 by Vinay Sajip. All Rights Reserved. + + Permission to use, copy, modify, and distribute this software and its + documentation for any purpose and without fee is hereby granted, provided that + the above copyright notice appear in all copies and that both that copyright + notice and this permission notice appear in supporting documentation, and that + the name of Vinay Sajip not be used in advertising or publicity pertaining to + distribution of the software without specific, written prior permission. + +================================================================================ +Unicode Character Database +================================================================================ + +The character property and case mapping tables of the Python runtime (maven/python-runtime, UnicodeTables.java) are generated from the Unicode Character Database, Copyright (c) 1991-2026 Unicode, Inc., licensed under the Unicode License v3. The full text is in maven/python-runtime/third-party/unicode/LICENSE.txt. + ================================================================================ Aileron (font) ================================================================================ diff --git a/Ports/JavaSE/src/com/codename1/impl/javase/SEDatabase.java b/Ports/JavaSE/src/com/codename1/impl/javase/SEDatabase.java index 84bd112951d..41dde3b8b96 100644 --- a/Ports/JavaSE/src/com/codename1/impl/javase/SEDatabase.java +++ b/Ports/JavaSE/src/com/codename1/impl/javase/SEDatabase.java @@ -25,6 +25,7 @@ import com.codename1.db.Cursor; import com.codename1.db.Database; import com.codename1.db.DatabaseConfig; +import java.util.function.Function; import com.codename1.impl.SQLStatementSplitter; import java.io.File; @@ -684,6 +685,70 @@ private void requireSingleStatement(String sql) throws IOException { } } + @Override + public boolean supportsFunctions() { + return true; + } + + @Override + public void createFunction(String name, int argCount, final Function function) throws IOException { + checkOpen(); + try { + if (function == null) { + org.sqlite.Function.destroy(conn, name, argCount); + return; + } + org.sqlite.Function.create(conn, name, new org.sqlite.Function() { + @Override + protected void xFunc() throws SQLException { + Object[] args = new Object[args()]; + for (int i = 0; i < args.length; i++) { + switch (value_type(i)) { + case org.sqlite.core.Codes.SQLITE_INTEGER: + args[i] = Long.valueOf(value_long(i)); + break; + case org.sqlite.core.Codes.SQLITE_FLOAT: + args[i] = Double.valueOf(value_double(i)); + break; + case org.sqlite.core.Codes.SQLITE_BLOB: + args[i] = value_blob(i); + break; + case org.sqlite.core.Codes.SQLITE_TEXT: + args[i] = value_text(i); + break; + default: + args[i] = null; + } + } + Object v; + try { + v = function.apply(args); + } catch (RuntimeException e) { + // error() makes the message the statement's; a thrown SQLException + // would reach SQLite as its toString(). + error(e.getMessage() == null ? e.toString() : e.getMessage()); + return; + } + if (v == null) { + result(); + } else if (v instanceof Boolean) { + result(((Boolean) v).booleanValue() ? 1 : 0); + } else if (v instanceof Double || v instanceof Float) { + result(((Number) v).doubleValue()); + } else if (v instanceof Number) { + result(((Number) v).longValue()); + } else if (v instanceof byte[]) { + result((byte[]) v); + } else { + result(v.toString()); + } + } + }, argCount, 0); + } catch (SQLException e) { + throw new IOException(e.getMessage(), e); + } + } + @Override public void execute(String sql) throws IOException { checkOpen(); diff --git a/Ports/JavaScriptPort/src/main/java/com/codename1/impl/html5/database/DatabaseImpl.java b/Ports/JavaScriptPort/src/main/java/com/codename1/impl/html5/database/DatabaseImpl.java index 3cb423f6711..35df7a04cf2 100644 --- a/Ports/JavaScriptPort/src/main/java/com/codename1/impl/html5/database/DatabaseImpl.java +++ b/Ports/JavaScriptPort/src/main/java/com/codename1/impl/html5/database/DatabaseImpl.java @@ -33,6 +33,7 @@ import java.io.IOException; import java.util.ArrayList; import java.util.List; +import java.util.function.Function; /** * Database for the JavaScript port, backed by SQLite compiled to WebAssembly. @@ -151,6 +152,70 @@ private boolean openOrFail(String name) throws IOException { * inside one does not reach here as a Java throwable, it unwinds the worker and hangs every * thread waiting on the call. */ + /** Every function registered on any connection, by the id SQLite hands back. */ + private static final List> FUNCTIONS = new ArrayList>(); + + @Override + public boolean supportsFunctions() { + return true; + } + + @Override + public void createFunction(String name, int argCount, Function function) throws IOException { + int id = -1; + if (function != null) { + id = FUNCTIONS.size(); + FUNCTIONS.add(function); + } + checkNative(SQLiteNative.createFunction(peer, name, argCount, id)); + } + + /** + * Runs a registered function for SQLite, called by port.js from inside the engine while a + * statement steps, and driven to completion synchronously there: a function that blocks + * (waits on a lock, a network call) fails the statement instead. + * + *

port.js hands each argument over as SQLite stores it, an integer or a real as its text so + * that a 64-bit value arrives exact, with {@code kinds} saying which (1 integer, 2 real, 3 + * text, 4 blob, 5 null). The answer is {kind, value} in the same coding, with kind 0 and the + * message for an exception, which fails the statement with that message. + */ + static Object[] callFunction(int id, Object[] args, int[] kinds) { + try { + for (int i = 0; i < args.length; i++) { + if (kinds[i] == 1) { + args[i] = Long.valueOf(Long.parseLong(String.valueOf(args[i]))); + } else if (kinds[i] == 2) { + args[i] = Double.valueOf(Double.parseDouble(String.valueOf(args[i]))); + } + } + Function f = id >= 0 && id < FUNCTIONS.size() ? FUNCTIONS.get(id) : null; + if (f == null) { + return new Object[] {"0", "no such function"}; + } + Object v = f.apply(args); + if (v == null) { + return new Object[] {"5", null}; + } + if (v instanceof Boolean) { + return new Object[] {"1", ((Boolean) v).booleanValue() ? "1" : "0"}; + } + if (v instanceof Long || v instanceof Integer || v instanceof Short || v instanceof Byte) { + return new Object[] {"1", String.valueOf(((Number) v).longValue())}; + } + if (v instanceof Number) { + return new Object[] {"2", String.valueOf(((Number) v).doubleValue())}; + } + if (v instanceof byte[]) { + return new Object[] {"4", v}; + } + return new Object[] {"3", String.valueOf(v)}; + } catch (RuntimeException e) { + String m = e.getMessage(); + return new Object[] {"0", m == null ? e.toString() : m}; + } + } + private static void checkNative(boolean ok) throws IOException { if (!ok) { throw new IOException(SQLiteNative.lastError()); diff --git a/Ports/JavaScriptPort/src/main/java/com/codename1/impl/html5/database/SQLiteNative.java b/Ports/JavaScriptPort/src/main/java/com/codename1/impl/html5/database/SQLiteNative.java index 9030b841dd2..e44cdeeddcf 100644 --- a/Ports/JavaScriptPort/src/main/java/com/codename1/impl/html5/database/SQLiteNative.java +++ b/Ports/JavaScriptPort/src/main/java/com/codename1/impl/html5/database/SQLiteNative.java @@ -173,4 +173,13 @@ private SQLiteNative() { public static native double columnDouble(long stmtPeer, int col); public static native long columnLong(long stmtPeer, int col); + + /** + * Registers, or with {@code id} -1 removes, the SQL function {@code name} of {@code argCount} + * arguments on the connection. SQLite calls it back through + * {@code DatabaseImpl.callFunction(int, Object[], int[])} with {@code id}. + * + * @return false on failure, with the reason in {@link #lastError()} + */ + public static native boolean createFunction(long dbPeer, String name, int argCount, int id); } diff --git a/Ports/JavaScriptPort/src/main/webapp/port.js b/Ports/JavaScriptPort/src/main/webapp/port.js index 0f75c25956f..b4a6a35e266 100644 --- a/Ports/JavaScriptPort/src/main/webapp/port.js +++ b/Ports/JavaScriptPort/src/main/webapp/port.js @@ -7624,6 +7624,99 @@ bindNative(["cn1_com_codename1_impl_html5_database_SQLiteNative_isCipherAvailabl return cn1SqlitePool ? !!cn1SqlitePoolVfs : cn1SqliteMemoryVfs !== "memdb"; }); +/** + * A scalar SQL function whose body is Java (Database.createFunction). + * + * The oo1 createFunction converts arguments with sqlite3_values_to_js, which turns every integer + * that fits a double into a JS number and so loses whether SQLite held an INTEGER or a REAL -- + * a function that returns its argument would hand 1 back as 1.0. Arguments are therefore read + * here with their own SQLite type: an integer as its exact 64-bit text, a real as its text, text, + * a blob as a byte[], NULL as null; DatabaseImpl.callFunction parses the numbers. The result + * comes back as [kind, value] with the same codes ("0" is an error message) and is set with the + * matching sqlite3_result_* call, an integer through BigInt so 64 bits survive. + * + * The Java side runs synchronously inside sqlite3_step, so it must not block; a function that + * does is reported as this function's error rather than suspending the statement. + */ +function cn1SqliteCallJavaFunction(id, args, kinds) { + const fn = global.cn1_com_codename1_impl_html5_database_DatabaseImpl_callFunction_int_java_lang_Object_1ARRAY_int_1ARRAY_R_java_lang_Object_1ARRAY + || global.cn1_com_codename1_impl_html5_database_DatabaseImpl_callFunction___int_java_lang_Object_1ARRAY_int_1ARRAY_R_java_lang_Object_1ARRAY; + return cn1_ivsDrive(fn(id, args, kinds), "DatabaseImpl.callFunction"); +} + +bindNative(["cn1_com_codename1_impl_html5_database_SQLiteNative_createFunction_long_java_lang_String_int_int_R_boolean", "cn1_com_codename1_impl_html5_database_SQLiteNative_createFunction___long_java_lang_String_int_int_R_boolean"], + function(dbId, name, argCount, id) { + return cn1SqliteGuard(function() { + const db = cn1SqliteLookup(Number(dbId)); + const capi = cn1Sqlite.capi; + const wasm = cn1Sqlite.wasm; + const fnId = id | 0; + const ptrSize = wasm.pointerSize || 4; + const xFunc = wasm.installFunction("v(pip)", function(ctx, argc, argv) { + try { + const n = argc | 0; + const args = jvm.newArray(n, "java_lang_Object", 1); + const kinds = jvm.newArray(n, "JAVA_INT", 1); + for (let i = 0; i < n; i++) { + const v = wasm.peekPtr(argv + i * ptrSize); + const t = capi.sqlite3_value_type(v); + if (t === capi.SQLITE_INTEGER) { + kinds[i] = 1; + args[i] = jvm.createStringLiteral(String(capi.sqlite3_value_int64(v))); + } else if (t === capi.SQLITE_FLOAT) { + kinds[i] = 2; + args[i] = jvm.createStringLiteral(String(capi.sqlite3_value_double(v))); + } else if (t === capi.SQLITE_TEXT) { + kinds[i] = 3; + args[i] = jvm.createStringLiteral(String(capi.sqlite3_value_to_js(v))); + } else if (t === capi.SQLITE_BLOB) { + kinds[i] = 4; + const bytes = capi.sqlite3_value_to_js(v) || new Uint8Array(0); + const out = jvm.newArray(bytes.length | 0, "JAVA_BYTE", 1); + for (let j = 0; j < out.length; j++) { + const u = bytes[j] | 0; + out[j] = u > 127 ? u - 256 : u; + } + args[i] = out; + } else { + kinds[i] = 5; + args[i] = null; + } + } + const r = cn1SqliteCallJavaFunction(fnId, args, kinds); + const kind = jvm.toNativeString(r[0]); + const value = r[1]; + if (kind === "0") { + capi.sqlite3_result_error_js(ctx, value == null ? "error" : jvm.toNativeString(value)); + } else if (kind === "1") { + capi.sqlite3_result_int64(ctx, BigInt(jvm.toNativeString(value))); + } else if (kind === "2") { + capi.sqlite3_result_double(ctx, Number(jvm.toNativeString(value))); + } else if (kind === "3") { + capi.sqlite3_result_js(ctx, jvm.toNativeString(value)); + } else if (kind === "4") { + const bytes = new Uint8Array(value.length | 0); + for (let j = 0; j < bytes.length; j++) { + bytes[j] = value[j] & 0xff; + } + capi.sqlite3_result_js(ctx, bytes); + } else { + capi.sqlite3_result_null(ctx); + } + } catch (err) { + capi.sqlite3_result_error_js(ctx, err && err.message ? String(err.message) : String(err)); + } + }); + const rc = capi.sqlite3_create_function_v2(db.pointer, jvm.toNativeString(name), argCount | 0, + capi.SQLITE_UTF8, 0, xFunc, 0, 0, 0); + if (rc !== 0) { + wasm.uninstallFunction(xFunc); + throw new Error(capi.sqlite3_errmsg(db.pointer)); + } + return true; + }, false); + }); + bindNative(["cn1_com_codename1_impl_html5_database_SQLiteNative_exists_java_lang_String_R_boolean", "cn1_com_codename1_impl_html5_database_SQLiteNative_exists___java_lang_String_R_boolean"], function(name) { return cn1SqliteGuard(function() { diff --git a/Ports/LinuxPort/nativeSources/cn1_linux_db.c b/Ports/LinuxPort/nativeSources/cn1_linux_db.c index fd460ee46d0..5f26cf65df9 100644 --- a/Ports/LinuxPort/nativeSources/cn1_linux_db.c +++ b/Ports/LinuxPort/nativeSources/cn1_linux_db.c @@ -29,6 +29,7 @@ #include "cn1_db_sqlite_impl.h" CN1_DB_DEFINE_NATIVES(cn1DbLinuxEngine) +CN1_DB_DEFINE_FUNCTION_NATIVES(cn1DbLinuxEngine, com_codename1_impl_linux_LinuxDatabase_sqlFunctionCall___long_int_int_long) /* * The entry points, spelled out rather than pasted together. @@ -157,3 +158,99 @@ JAVA_VOID com_codename1_impl_linux_LinuxNative_sqlStmtFinalize___long(CODENAME_O JAVA_VOID com_codename1_impl_linux_LinuxNative_sqlStmtReset___long(CODENAME_ONE_THREAD_STATE, JAVA_LONG __cn1Arg1) { cn1DbLinuxEngine_sqlStmtReset___long(threadStateData, __cn1Arg1); } + +JAVA_INT com_codename1_impl_linux_LinuxNative_sqlDbCreateFunction___long_byte_1ARRAY_int_int_R_int(CODENAME_ONE_THREAD_STATE, JAVA_LONG __cn1Arg1, JAVA_OBJECT __cn1Arg2, JAVA_INT __cn1Arg3, JAVA_INT __cn1Arg4) { + return cn1DbLinuxEngine_sqlDbCreateFunction___long_byte_1ARRAY_int_int_R_int(threadStateData, __cn1Arg1, __cn1Arg2, __cn1Arg3, __cn1Arg4); +} + +JAVA_INT com_codename1_impl_linux_LinuxNative_sqlValueType___long_int_R_int(CODENAME_ONE_THREAD_STATE, JAVA_LONG __cn1Arg1, JAVA_INT __cn1Arg2) { + return cn1DbLinuxEngine_sqlValueType___long_int_R_int(threadStateData, __cn1Arg1, __cn1Arg2); +} + +JAVA_LONG com_codename1_impl_linux_LinuxNative_sqlValueLong___long_int_R_long(CODENAME_ONE_THREAD_STATE, JAVA_LONG __cn1Arg1, JAVA_INT __cn1Arg2) { + return cn1DbLinuxEngine_sqlValueLong___long_int_R_long(threadStateData, __cn1Arg1, __cn1Arg2); +} + +JAVA_DOUBLE com_codename1_impl_linux_LinuxNative_sqlValueDouble___long_int_R_double(CODENAME_ONE_THREAD_STATE, JAVA_LONG __cn1Arg1, JAVA_INT __cn1Arg2) { + return cn1DbLinuxEngine_sqlValueDouble___long_int_R_double(threadStateData, __cn1Arg1, __cn1Arg2); +} + +JAVA_OBJECT com_codename1_impl_linux_LinuxNative_sqlValueText___long_int_R_byte_1ARRAY(CODENAME_ONE_THREAD_STATE, JAVA_LONG __cn1Arg1, JAVA_INT __cn1Arg2) { + return cn1DbLinuxEngine_sqlValueText___long_int_R_byte_1ARRAY(threadStateData, __cn1Arg1, __cn1Arg2); +} + +JAVA_OBJECT com_codename1_impl_linux_LinuxNative_sqlValueBlob___long_int_R_byte_1ARRAY(CODENAME_ONE_THREAD_STATE, JAVA_LONG __cn1Arg1, JAVA_INT __cn1Arg2) { + return cn1DbLinuxEngine_sqlValueBlob___long_int_R_byte_1ARRAY(threadStateData, __cn1Arg1, __cn1Arg2); +} + +JAVA_VOID com_codename1_impl_linux_LinuxNative_sqlResultNull___long(CODENAME_ONE_THREAD_STATE, JAVA_LONG __cn1Arg1) { + cn1DbLinuxEngine_sqlResultNull___long(threadStateData, __cn1Arg1); +} + +JAVA_VOID com_codename1_impl_linux_LinuxNative_sqlResultLong___long_long(CODENAME_ONE_THREAD_STATE, JAVA_LONG __cn1Arg1, JAVA_LONG __cn1Arg2) { + cn1DbLinuxEngine_sqlResultLong___long_long(threadStateData, __cn1Arg1, __cn1Arg2); +} + +JAVA_VOID com_codename1_impl_linux_LinuxNative_sqlResultDouble___long_double(CODENAME_ONE_THREAD_STATE, JAVA_LONG __cn1Arg1, JAVA_DOUBLE __cn1Arg2) { + cn1DbLinuxEngine_sqlResultDouble___long_double(threadStateData, __cn1Arg1, __cn1Arg2); +} + +JAVA_VOID com_codename1_impl_linux_LinuxNative_sqlResultText___long_byte_1ARRAY(CODENAME_ONE_THREAD_STATE, JAVA_LONG __cn1Arg1, JAVA_OBJECT __cn1Arg2) { + cn1DbLinuxEngine_sqlResultText___long_byte_1ARRAY(threadStateData, __cn1Arg1, __cn1Arg2); +} + +JAVA_VOID com_codename1_impl_linux_LinuxNative_sqlResultBlob___long_byte_1ARRAY(CODENAME_ONE_THREAD_STATE, JAVA_LONG __cn1Arg1, JAVA_OBJECT __cn1Arg2) { + cn1DbLinuxEngine_sqlResultBlob___long_byte_1ARRAY(threadStateData, __cn1Arg1, __cn1Arg2); +} + +JAVA_VOID com_codename1_impl_linux_LinuxNative_sqlResultError___long_byte_1ARRAY(CODENAME_ONE_THREAD_STATE, JAVA_LONG __cn1Arg1, JAVA_OBJECT __cn1Arg2) { + cn1DbLinuxEngine_sqlResultError___long_byte_1ARRAY(threadStateData, __cn1Arg1, __cn1Arg2); +} + +JAVA_LONG com_codename1_impl_linux_LinuxNative_sqlDbChanges___long_R_long(CODENAME_ONE_THREAD_STATE, JAVA_LONG __cn1Arg1) { + return cn1DbLinuxEngine_sqlDbChanges___long_R_long(threadStateData, __cn1Arg1); +} + +JAVA_LONG com_codename1_impl_linux_LinuxNative_sqlDbLastInsertRowid___long_R_long(CODENAME_ONE_THREAD_STATE, JAVA_LONG __cn1Arg1) { + return cn1DbLinuxEngine_sqlDbLastInsertRowid___long_R_long(threadStateData, __cn1Arg1); +} + +JAVA_INT com_codename1_impl_linux_LinuxNative_sqlColType___long_int_R_int(CODENAME_ONE_THREAD_STATE, JAVA_LONG __cn1Arg1, JAVA_INT __cn1Arg2) { + return cn1DbLinuxEngine_sqlColType___long_int_R_int(threadStateData, __cn1Arg1, __cn1Arg2); +} + +JAVA_VOID com_codename1_impl_linux_LinuxNative_sqlStmtBindString___long_int_java_lang_String(CODENAME_ONE_THREAD_STATE, JAVA_LONG __cn1Arg1, JAVA_INT __cn1Arg2, JAVA_OBJECT __cn1Arg3) { + cn1DbLinuxEngine_sqlStmtBindString___long_int_java_lang_String(threadStateData, __cn1Arg1, __cn1Arg2, __cn1Arg3); +} + +JAVA_OBJECT com_codename1_impl_linux_LinuxNative_sqlColString___long_int_R_java_lang_String(CODENAME_ONE_THREAD_STATE, JAVA_LONG __cn1Arg1, JAVA_INT __cn1Arg2) { + return cn1DbLinuxEngine_sqlColString___long_int_R_java_lang_String(threadStateData, __cn1Arg1, __cn1Arg2); +} + +JAVA_OBJECT com_codename1_impl_linux_LinuxNative_sqlColNameString___long_int_R_java_lang_String(CODENAME_ONE_THREAD_STATE, JAVA_LONG __cn1Arg1, JAVA_INT __cn1Arg2) { + return cn1DbLinuxEngine_sqlColNameString___long_int_R_java_lang_String(threadStateData, __cn1Arg1, __cn1Arg2); +} + +JAVA_BOOLEAN com_codename1_impl_linux_LinuxNative_sqlRowValues___long_java_lang_Object_1ARRAY_R_boolean(CODENAME_ONE_THREAD_STATE, JAVA_LONG __cn1Arg1, JAVA_OBJECT __cn1Arg2) { + return cn1DbLinuxEngine_sqlRowValues___long_java_lang_Object_1ARRAY_R_boolean(threadStateData, __cn1Arg1, __cn1Arg2); +} + +JAVA_INT com_codename1_impl_linux_LinuxNative_sqlStmtStepStatus___long_R_int(CODENAME_ONE_THREAD_STATE, JAVA_LONG __cn1Arg1) { + return cn1DbLinuxEngine_sqlStmtStepStatus___long_R_int(threadStateData, __cn1Arg1); +} + +JAVA_LONG com_codename1_impl_linux_LinuxNative_sqlStmtPrepareStatus___long_java_lang_String_R_long(CODENAME_ONE_THREAD_STATE, JAVA_LONG __cn1Arg1, JAVA_OBJECT __cn1Arg2) { + return cn1DbLinuxEngine_sqlStmtPrepareStatus___long_java_lang_String_R_long(threadStateData, __cn1Arg1, __cn1Arg2); +} + +JAVA_OBJECT com_codename1_impl_linux_LinuxNative_sqlDbErrorText___long_R_java_lang_String(CODENAME_ONE_THREAD_STATE, JAVA_LONG __cn1Arg1) { + return cn1DbLinuxEngine_sqlDbErrorText___long_R_java_lang_String(threadStateData, __cn1Arg1); +} + +JAVA_INT com_codename1_impl_linux_LinuxNative_sqlStmtRunStatus___long_java_lang_Object_1ARRAY_long_1ARRAY_R_int(CODENAME_ONE_THREAD_STATE, JAVA_LONG __cn1Arg1, JAVA_OBJECT __cn1Arg2, JAVA_OBJECT __cn1Arg3) { + return cn1DbLinuxEngine_sqlStmtRunStatus___long_java_lang_Object_1ARRAY_long_1ARRAY_R_int(threadStateData, __cn1Arg1, __cn1Arg2, __cn1Arg3); +} + +JAVA_INT com_codename1_impl_linux_LinuxNative_sqlStmtFinalizeStatus___long_R_int(CODENAME_ONE_THREAD_STATE, JAVA_LONG __cn1Arg1) { + return cn1DbLinuxEngine_sqlStmtFinalizeStatus___long_R_int(threadStateData, __cn1Arg1); +} diff --git a/Ports/LinuxPort/nativeSources/cn1_linux_io.c b/Ports/LinuxPort/nativeSources/cn1_linux_io.c index 69cdc7e3e04..ad76168c02d 100644 --- a/Ports/LinuxPort/nativeSources/cn1_linux_io.c +++ b/Ports/LinuxPort/nativeSources/cn1_linux_io.c @@ -340,6 +340,17 @@ JAVA_LONG com_codename1_impl_linux_LinuxNative_fileLength___java_lang_String_R_l return (p && stat(p, &st) == 0) ? (JAVA_LONG) st.st_size : 0; } +// Milliseconds since the epoch, or -1 when the file cannot be stat'ed (the +// value CodenameOneImplementation answers for a port without the call). +JAVA_LONG com_codename1_impl_linux_LinuxNative_fileLastModified___java_lang_String_R_long(CODENAME_ONE_THREAD_STATE, JAVA_OBJECT path) { + const char* p = cn1JStr(threadStateData, path); + struct stat st; + if (!p || stat(p, &st) != 0) { + return -1; + } + return (JAVA_LONG) st.st_mtim.tv_sec * 1000 + st.st_mtim.tv_nsec / 1000000; +} + JAVA_VOID com_codename1_impl_linux_LinuxNative_fileDelete___java_lang_String(CODENAME_ONE_THREAD_STATE, JAVA_OBJECT path) { const char* p = cn1JStr(threadStateData, path); if (p) { diff --git a/Ports/LinuxPort/src/com/codename1/impl/linux/LinuxDatabase.java b/Ports/LinuxPort/src/com/codename1/impl/linux/LinuxDatabase.java index f218dbf3e09..ffbca6ec5ba 100644 --- a/Ports/LinuxPort/src/com/codename1/impl/linux/LinuxDatabase.java +++ b/Ports/LinuxPort/src/com/codename1/impl/linux/LinuxDatabase.java @@ -26,9 +26,10 @@ import com.codename1.db.Database; import com.codename1.db.DatabaseConfig; import com.codename1.db.DatabaseEncryptionException; +import java.util.function.Function; import com.codename1.impl.AbstractDBCursor; import com.codename1.impl.SQLStatementSplitter; -import com.codename1.impl.SQLText; +import com.codename1.impl.SqlFunctionBridge; import java.io.IOException; import java.util.ArrayList; @@ -44,6 +45,70 @@ class LinuxDatabase extends Database { private long peer; + /// The functions every connection of this process has registered; SQLite holds only the id. + private static final SqlFunctionBridge FUNCTIONS = new SqlFunctionBridge() { + @Override + protected int valueType(long argv, int i) { + return LinuxNative.sqlValueType(argv, i); + } + + @Override + protected long valueLong(long argv, int i) { + return LinuxNative.sqlValueLong(argv, i); + } + + @Override + protected double valueDouble(long argv, int i) { + return LinuxNative.sqlValueDouble(argv, i); + } + + @Override + protected byte[] valueText(long argv, int i) { + return LinuxNative.sqlValueText(argv, i); + } + + @Override + protected byte[] valueBlob(long argv, int i) { + return LinuxNative.sqlValueBlob(argv, i); + } + + @Override + protected void resultNull(long ctx) { + LinuxNative.sqlResultNull(ctx); + } + + @Override + protected void resultLong(long ctx, long v) { + LinuxNative.sqlResultLong(ctx, v); + } + + @Override + protected void resultDouble(long ctx, double v) { + LinuxNative.sqlResultDouble(ctx, v); + } + + @Override + protected void resultText(long ctx, byte[] utf8) { + LinuxNative.sqlResultText(ctx, utf8); + } + + @Override + protected void resultBlob(long ctx, byte[] v) { + LinuxNative.sqlResultBlob(ctx, v); + } + + @Override + protected void resultError(long ctx, byte[] utf8) { + LinuxNative.sqlResultError(ctx, utf8); + } + }; + + /// Called by the engine (cn1_linux_db.c) while a statement calls a Java function. + static void sqlFunctionCall(long ctx, int id, int argc, long argv) { + FUNCTIONS.call(ctx, id, argc, argv); + } + + /** * The name this database was opened under. Retained because a managed key resolves its * keystore alias from the database name, and changeKey() would otherwise have nothing to @@ -52,6 +117,7 @@ class LinuxDatabase extends Database { private final String databaseName; private final List openCursors = new ArrayList(); + private final com.codename1.impl.SQLStatementCache statements = new com.codename1.impl.SQLStatementCache(); /// SQLite's success code. private static final int SQLITE_OK = 0; @@ -172,7 +238,7 @@ private void requireSingleStatement(String sql) throws IOException { if (isLegacyBehavior()) { return; } - if (SQLStatementSplitter.isMultiStatement(sql)) { + if (!isPlainStatement(sql) && SQLStatementSplitter.isMultiStatement(sql)) { throw new IOException("This method takes a single SQL statement, but the string " + "contains " + SQLStatementSplitter.countStatements(sql) + ". Use execute(String) to run a script."); @@ -241,6 +307,11 @@ public void close() throws IOException { for (int iter = 0; iter < cursors.length; iter++) { cursors[iter].databaseClosed(); } + // SQLite will not close a connection whose statements are still alive. + long[] cached = statements.drain(); + for (int iter = 0; iter < cached.length; iter++) { + LinuxNative.sqlStmtFinalize(cached[iter]); + } long closing = peer; peer = 0; try { @@ -257,6 +328,32 @@ public void close() throws IOException { } } + @Override + public long changes() throws IOException { + checkOpen(); + return LinuxNative.sqlDbChanges(peer); + } + + @Override + public long lastInsertRowId() throws IOException { + checkOpen(); + return LinuxNative.sqlDbLastInsertRowid(peer); + } + + @Override + public boolean supportsFunctions() { + return true; + } + + @Override + public void createFunction(String name, int argCount, Function function) throws IOException { + checkOpen(); + int id = function == null ? -1 : FUNCTIONS.register(function); + if (LinuxNative.sqlDbCreateFunction(peer, com.codename1.util.StringUtil.getBytes(name), argCount, id) != 0) { + throw new IOException("Could not create the SQL function " + name); + } + } + @Override public void changeKey(DatabaseConfig config) throws IOException { checkOpen(); @@ -337,9 +434,23 @@ public void execute(String sql, Object... params) throws IOException { reserveAttachments(sql, params); requireSingleStatement(sql); try { - long stmt = LinuxNative.sqlStmtPrepare(peer, sql); + long stmt = statements.take(sql); + if (stmt == 0) { + stmt = LinuxNative.sqlStmtPrepare(peer, sql); + } + // bind finalizes the statement itself when it throws. bind(stmt, params); - LinuxNative.sqlStmtExecuteAndFinalize(stmt); + try { + while (LinuxNative.sqlStmtStep(stmt)) { + // Rows of a statement run for its effect are discarded, as before. + } + } catch (IOException err) { + LinuxNative.sqlStmtFinalize(stmt); + throw err; + } + // Reset releases what the run holds, so a cached statement keeps no lock. + LinuxNative.sqlStmtReset(stmt); + LinuxNative.sqlStmtFinalize(statements.put(sql, stmt)); // The names on success only -- a statement that failed opened no savepoint. noteScriptTransactionControl(sql); } finally { @@ -350,12 +461,56 @@ public void execute(String sql, Object... params) throws IOException { } } + /// The status form of [#execute(String, Object...)], with no handler on the way for the + /// statement nearly every call runs: one plain statement on an open connection, its + /// parameters ones the engine binds directly. Anything else -- and the bookkeeping after a + /// failure -- takes the inherited path, which wraps the throwing method. + @Override + public int executeStatus(String sql, Object[] params, long[] counts) { + if (peer == 0 || params == null || !isPlainStatement(sql)) { + return super.executeStatus(sql, params, counts); + } + long stmt = statements.take(sql); + if (stmt == 0) { + stmt = LinuxNative.sqlStmtPrepareStatus(peer, sql); + if (stmt == 0) { + return failStatus(LinuxNative.sqlDbErrorText(peer), 1); + } + } + int rc = LinuxNative.sqlStmtRunStatus(stmt, params, counts); + if (rc == 0) { + // A plain statement that ran changed no transaction state. + LinuxNative.sqlStmtFinalizeStatus(statements.put(sql, stmt)); + return 0; + } + return statementFailed(sql, params, counts, stmt, rc); + } + + /// The cold half of [#executeStatus(String, Object[], long[])], kept apart so that its handler is + /// set up only when a statement did not run. + private int statementFailed(String sql, Object[] params, long[] counts, long stmt, int rc) { + if (rc == -2 || rc == -3) { + // Nothing ran: a parameter only Java binds, or a count the throwing path words. + LinuxNative.sqlStmtFinalizeStatus(statements.put(sql, stmt)); + return super.executeStatus(sql, params, counts); + } + String message = LinuxNative.sqlDbErrorText(peer); + LinuxNative.sqlStmtFinalizeStatus(stmt); + try { + // As execute does after any run: ON CONFLICT ROLLBACK ends the transaction as it fails. + noteEngineTransactionState(LinuxNative.sqlDbInTransaction(peer)); + } catch (IOException err) { + return failStatus(err.getMessage(), rc); + } + return failStatus(message, rc); + } + @Override public Cursor executeQuery(String sql) throws IOException { checkOpen(); requireSingleStatement(sql); requireQueryStatement(sql); - long stmt = LinuxNative.sqlStmtPrepare(peer, sql); + long stmt = prepareCached(sql); // A statement with placeholders and no arguments would otherwise run with every slot left // as NULL rather than reporting the missing parameters. The check is a no-op in legacy // mode, where running it unbound is the behaviour applications were written against. @@ -375,7 +530,7 @@ public Cursor executeQuery(String sql, String[] params) throws IOException { checkOpen(); requireSingleStatement(sql); requireQueryStatement(sql); - long stmt = LinuxNative.sqlStmtPrepare(peer, sql); + long stmt = prepareCached(sql); bindText(stmt, params); return register(new CursorImpl(stmt), sql); } @@ -392,13 +547,29 @@ public Cursor executeQuery(String sql, Object... params) throws IOException { checkOpen(); requireSingleStatement(sql); requireQueryStatement(sql); - long stmt = LinuxNative.sqlStmtPrepare(peer, sql); + long stmt = prepareCached(sql); bind(stmt, params); return register(new CursorImpl(stmt), sql); } + private long prepareCached(String sql) throws IOException { + long stmt = statements.take(sql); + return stmt != 0 ? stmt : LinuxNative.sqlStmtPrepare(peer, sql); + } + + /// Takes back a closed cursor's statement, reset, for the next query with the same SQL. + void recycle(String sql, long stmt) throws IOException { + if (peer == 0 || sql == null) { + LinuxNative.sqlStmtFinalize(stmt); + return; + } + LinuxNative.sqlStmtReset(stmt); + LinuxNative.sqlStmtFinalize(statements.put(sql, stmt)); + } + private Cursor register(CursorImpl cursor, String sql) { cursor.owner = this; + cursor.cacheKey = sql; // A statement that writes must never be re-executed to move backwards: this cursor is // stepped to run it, so a getCount() or last() would write again. The cursor refuses // rather than doing it twice. @@ -451,7 +622,7 @@ private void bindText(long stmt, String[] params) throws IOException { if (params[iter] == null) { LinuxNative.sqlStmtBindNull(stmt, iter + 1); } else { - LinuxNative.sqlStmtBindText(stmt, iter + 1, SQLText.toUTF8(params[iter])); + LinuxNative.sqlStmtBindString(stmt, iter + 1, params[iter]); } } } catch (IOException err) { @@ -492,7 +663,7 @@ private void bindEach(long stmt, Object[] params) throws IOException { } else if (p instanceof byte[]) { LinuxNative.sqlStmtBindBlob(stmt, index, (byte[]) p); } else if (p instanceof String) { - LinuxNative.sqlStmtBindText(stmt, index, SQLText.toUTF8((String) p)); + LinuxNative.sqlStmtBindString(stmt, index, (String) p); } else if (p instanceof Double || p instanceof Float) { LinuxNative.sqlStmtBindDouble(stmt, index, ((Number) p).doubleValue()); } else if (p instanceof Long || p instanceof Integer || p instanceof Short @@ -501,7 +672,7 @@ private void bindEach(long stmt, Object[] params) throws IOException { } else if (p instanceof Boolean) { LinuxNative.sqlStmtBindLong(stmt, index, ((Boolean) p).booleanValue() ? 1 : 0); } else { - LinuxNative.sqlStmtBindText(stmt, index, SQLText.toUTF8(p.toString())); + LinuxNative.sqlStmtBindString(stmt, index, p.toString()); } } } @@ -509,6 +680,7 @@ private void bindEach(long stmt, Object[] params) throws IOException { /** Cursor over a compiled statement; seeks by resetting and stepping again. */ static class CursorImpl extends AbstractDBCursor { private long stmt; + String cacheKey; LinuxDatabase owner; CursorImpl(long stmt) { @@ -568,7 +740,11 @@ protected void closeImpl() throws IOException { if (stmt != 0) { long closing = stmt; stmt = 0; - LinuxNative.sqlStmtFinalize(closing); + if (owner != null) { + owner.recycle(cacheKey, closing); + } else { + LinuxNative.sqlStmtFinalize(closing); + } } } @@ -579,7 +755,23 @@ protected int columnCount() throws IOException { @Override protected String columnLabel(int columnIndex) throws IOException { - return SQLText.fromUTF8(LinuxNative.sqlColName(stmt, columnIndex)); + return LinuxNative.sqlColNameString(stmt, columnIndex); + } + + @Override + protected boolean capturesColumnTypeBeforeRead() { + // sqlite3_column_type is undefined once a getter has converted the value. + return true; + } + + @Override + protected int columnType(int index) throws IOException { + return LinuxNative.sqlColType(stmt, index); + } + + @Override + protected boolean readRow(Object[] out) throws IOException { + return LinuxNative.sqlRowValues(stmt, out); } @Override @@ -589,7 +781,7 @@ protected boolean isNullAt(int index) throws IOException { @Override protected String readString(int index) throws IOException { - return SQLText.fromUTF8(LinuxNative.sqlColText(stmt, index)); + return LinuxNative.sqlColString(stmt, index); } @Override diff --git a/Ports/LinuxPort/src/com/codename1/impl/linux/LinuxImplementation.java b/Ports/LinuxPort/src/com/codename1/impl/linux/LinuxImplementation.java index 013b963d92b..9cac6a45397 100644 --- a/Ports/LinuxPort/src/com/codename1/impl/linux/LinuxImplementation.java +++ b/Ports/LinuxPort/src/com/codename1/impl/linux/LinuxImplementation.java @@ -3728,6 +3728,11 @@ public long getFileLength(String file) { return LinuxNative.fileLength(stripFileUrl(file)); } + @Override + public long getFileLastModified(String file) { + return LinuxNative.fileLastModified(stripFileUrl(file)); + } + @Override public boolean isDirectory(String file) { return LinuxNative.fileIsDirectory(stripFileUrl(file)); @@ -4580,6 +4585,18 @@ public com.codename1.db.Database openOrCreateDB(String databaseName) throws java return openOrCreateDB(databaseName, null); } + @Override + public boolean isInMemoryDatabaseSupported() { + return true; + } + + @Override + public com.codename1.db.Database openInMemoryDB() throws java.io.IOException { + // SQLite's own name for a private in-memory database. The open registry files every + // such connection under the one key, which no real file has: a count, never a refusal. + return new LinuxDatabase(":memory:", ":memory:", null); + } + @Override public com.codename1.db.Database openOrCreateDB(String databaseName, com.codename1.db.DatabaseConfig config) throws java.io.IOException { diff --git a/Ports/LinuxPort/src/com/codename1/impl/linux/LinuxNative.java b/Ports/LinuxPort/src/com/codename1/impl/linux/LinuxNative.java index fcd63e65297..3c4b29952bf 100644 --- a/Ports/LinuxPort/src/com/codename1/impl/linux/LinuxNative.java +++ b/Ports/LinuxPort/src/com/codename1/impl/linux/LinuxNative.java @@ -744,6 +744,8 @@ public static native boolean verifyData(String algorithm, byte[] publicKeyX509, public static native long fileLength(String path); + public static native long fileLastModified(String path); + public static native void fileDelete(String path); public static native void fileMkdir(String path); @@ -1337,6 +1339,8 @@ public static native void gl3dEndPost(long contextPeer, long brightPipeline, lon public static native void sqlDbExecScript(long dbPeer, String sql) throws java.io.IOException; + public static native long sqlDbChanges(long dbPeer); + public static native long sqlDbLastInsertRowid(long dbPeer); public static native long sqlStmtPrepare(long dbPeer, String sql) throws java.io.IOException; public static native int sqlStmtParameterCount(long stmtPeer) throws java.io.IOException; public static native void sqlStmtBindNull(long stmtPeer, int index) throws java.io.IOException; @@ -1354,8 +1358,25 @@ public static native void gl3dEndPost(long contextPeer, long brightPipeline, lon public static native int sqlColCount(long stmtPeer) throws java.io.IOException; public static native byte[] sqlColName(long stmtPeer, int col) throws java.io.IOException; + public static native int sqlColType(long stmtPeer, int col); public static native boolean sqlColIsNull(long stmtPeer, int col) throws java.io.IOException; public static native byte[] sqlColText(long stmtPeer, int col) throws java.io.IOException; + // Text as a String read or built in place by the native, with no UTF-8 byte[] in between. + public static native void sqlStmtBindString(long stmtPeer, int index, String value) throws java.io.IOException; + public static native String sqlColString(long stmtPeer, int col) throws java.io.IOException; + public static native String sqlColNameString(long stmtPeer, int col) throws java.io.IOException; + // The whole current row, written into the caller's array; false when it is too short. + public static native boolean sqlRowValues(long stmtPeer, Object[] out); + // SQLite's result code instead of an exception, and the connection's message of the last one. + public static native int sqlStmtStepStatus(long stmtPeer); + // 0 when the statement does not compile; the message is then sqlDbErrorText's. + public static native long sqlStmtPrepareStatus(long dbPeer, String sql); + public static native String sqlDbErrorText(long dbPeer); + public static native int sqlStmtFinalizeStatus(long stmtPeer); + // Bind, step to the end and reset in one call: 0, -3 for a parameter count the statement does + // not take, -2 for a parameter only Java binds (nothing ran), else SQLite's code. On 0, + // counts (if not null) receives the changes and the last row id. + public static native int sqlStmtRunStatus(long stmtPeer, Object[] params, long[] counts); public static native byte[] sqlColBlob(long stmtPeer, int col) throws java.io.IOException; public static native double sqlColDouble(long stmtPeer, int col) throws java.io.IOException; public static native long sqlColLong(long stmtPeer, int col) throws java.io.IOException; @@ -1419,4 +1440,19 @@ public static native void gl3dEndPost(long contextPeer, long brightPipeline, lon public static native byte[] nfcTransmit(long card, byte[] apdu); /** Releases a card handle returned by nfcWaitCard(). */ public static native void nfcDisconnect(long card); + // SQL functions written in Java (Database.createFunction). The engine calls back into + // the port's database class (sqlFunctionCall), which reads the arguments and sets the + // result through these while sqlite3_step waits. + public static native int sqlDbCreateFunction(long dbPeer, byte[] nameUtf8, int argCount, int id); + public static native int sqlValueType(long argv, int index); + public static native long sqlValueLong(long argv, int index); + public static native double sqlValueDouble(long argv, int index); + public static native byte[] sqlValueText(long argv, int index); + public static native byte[] sqlValueBlob(long argv, int index); + public static native void sqlResultNull(long ctx); + public static native void sqlResultLong(long ctx, long value); + public static native void sqlResultDouble(long ctx, double value); + public static native void sqlResultText(long ctx, byte[] utf8); + public static native void sqlResultBlob(long ctx, byte[] value); + public static native void sqlResultError(long ctx, byte[] utf8); } diff --git a/Ports/WindowsPort/nativeSources/cn1_windows_db.c b/Ports/WindowsPort/nativeSources/cn1_windows_db.c index 8ed25226e06..b44a95d67d3 100644 --- a/Ports/WindowsPort/nativeSources/cn1_windows_db.c +++ b/Ports/WindowsPort/nativeSources/cn1_windows_db.c @@ -29,6 +29,7 @@ #include "cn1_db_sqlite_impl.h" CN1_DB_DEFINE_NATIVES(cn1DbWindowsEngine) +CN1_DB_DEFINE_FUNCTION_NATIVES(cn1DbWindowsEngine, com_codename1_impl_windows_WindowsDatabase_sqlFunctionCall___long_int_int_long) /* * The entry points, spelled out rather than pasted together. @@ -157,3 +158,99 @@ JAVA_VOID com_codename1_impl_windows_WindowsNative_sqlStmtFinalize___long(CODENA JAVA_VOID com_codename1_impl_windows_WindowsNative_sqlStmtReset___long(CODENAME_ONE_THREAD_STATE, JAVA_LONG __cn1Arg1) { cn1DbWindowsEngine_sqlStmtReset___long(threadStateData, __cn1Arg1); } + +JAVA_INT com_codename1_impl_windows_WindowsNative_sqlDbCreateFunction___long_byte_1ARRAY_int_int_R_int(CODENAME_ONE_THREAD_STATE, JAVA_LONG __cn1Arg1, JAVA_OBJECT __cn1Arg2, JAVA_INT __cn1Arg3, JAVA_INT __cn1Arg4) { + return cn1DbWindowsEngine_sqlDbCreateFunction___long_byte_1ARRAY_int_int_R_int(threadStateData, __cn1Arg1, __cn1Arg2, __cn1Arg3, __cn1Arg4); +} + +JAVA_INT com_codename1_impl_windows_WindowsNative_sqlValueType___long_int_R_int(CODENAME_ONE_THREAD_STATE, JAVA_LONG __cn1Arg1, JAVA_INT __cn1Arg2) { + return cn1DbWindowsEngine_sqlValueType___long_int_R_int(threadStateData, __cn1Arg1, __cn1Arg2); +} + +JAVA_LONG com_codename1_impl_windows_WindowsNative_sqlValueLong___long_int_R_long(CODENAME_ONE_THREAD_STATE, JAVA_LONG __cn1Arg1, JAVA_INT __cn1Arg2) { + return cn1DbWindowsEngine_sqlValueLong___long_int_R_long(threadStateData, __cn1Arg1, __cn1Arg2); +} + +JAVA_DOUBLE com_codename1_impl_windows_WindowsNative_sqlValueDouble___long_int_R_double(CODENAME_ONE_THREAD_STATE, JAVA_LONG __cn1Arg1, JAVA_INT __cn1Arg2) { + return cn1DbWindowsEngine_sqlValueDouble___long_int_R_double(threadStateData, __cn1Arg1, __cn1Arg2); +} + +JAVA_OBJECT com_codename1_impl_windows_WindowsNative_sqlValueText___long_int_R_byte_1ARRAY(CODENAME_ONE_THREAD_STATE, JAVA_LONG __cn1Arg1, JAVA_INT __cn1Arg2) { + return cn1DbWindowsEngine_sqlValueText___long_int_R_byte_1ARRAY(threadStateData, __cn1Arg1, __cn1Arg2); +} + +JAVA_OBJECT com_codename1_impl_windows_WindowsNative_sqlValueBlob___long_int_R_byte_1ARRAY(CODENAME_ONE_THREAD_STATE, JAVA_LONG __cn1Arg1, JAVA_INT __cn1Arg2) { + return cn1DbWindowsEngine_sqlValueBlob___long_int_R_byte_1ARRAY(threadStateData, __cn1Arg1, __cn1Arg2); +} + +JAVA_VOID com_codename1_impl_windows_WindowsNative_sqlResultNull___long(CODENAME_ONE_THREAD_STATE, JAVA_LONG __cn1Arg1) { + cn1DbWindowsEngine_sqlResultNull___long(threadStateData, __cn1Arg1); +} + +JAVA_VOID com_codename1_impl_windows_WindowsNative_sqlResultLong___long_long(CODENAME_ONE_THREAD_STATE, JAVA_LONG __cn1Arg1, JAVA_LONG __cn1Arg2) { + cn1DbWindowsEngine_sqlResultLong___long_long(threadStateData, __cn1Arg1, __cn1Arg2); +} + +JAVA_VOID com_codename1_impl_windows_WindowsNative_sqlResultDouble___long_double(CODENAME_ONE_THREAD_STATE, JAVA_LONG __cn1Arg1, JAVA_DOUBLE __cn1Arg2) { + cn1DbWindowsEngine_sqlResultDouble___long_double(threadStateData, __cn1Arg1, __cn1Arg2); +} + +JAVA_VOID com_codename1_impl_windows_WindowsNative_sqlResultText___long_byte_1ARRAY(CODENAME_ONE_THREAD_STATE, JAVA_LONG __cn1Arg1, JAVA_OBJECT __cn1Arg2) { + cn1DbWindowsEngine_sqlResultText___long_byte_1ARRAY(threadStateData, __cn1Arg1, __cn1Arg2); +} + +JAVA_VOID com_codename1_impl_windows_WindowsNative_sqlResultBlob___long_byte_1ARRAY(CODENAME_ONE_THREAD_STATE, JAVA_LONG __cn1Arg1, JAVA_OBJECT __cn1Arg2) { + cn1DbWindowsEngine_sqlResultBlob___long_byte_1ARRAY(threadStateData, __cn1Arg1, __cn1Arg2); +} + +JAVA_VOID com_codename1_impl_windows_WindowsNative_sqlResultError___long_byte_1ARRAY(CODENAME_ONE_THREAD_STATE, JAVA_LONG __cn1Arg1, JAVA_OBJECT __cn1Arg2) { + cn1DbWindowsEngine_sqlResultError___long_byte_1ARRAY(threadStateData, __cn1Arg1, __cn1Arg2); +} + +JAVA_LONG com_codename1_impl_windows_WindowsNative_sqlDbChanges___long_R_long(CODENAME_ONE_THREAD_STATE, JAVA_LONG __cn1Arg1) { + return cn1DbWindowsEngine_sqlDbChanges___long_R_long(threadStateData, __cn1Arg1); +} + +JAVA_LONG com_codename1_impl_windows_WindowsNative_sqlDbLastInsertRowid___long_R_long(CODENAME_ONE_THREAD_STATE, JAVA_LONG __cn1Arg1) { + return cn1DbWindowsEngine_sqlDbLastInsertRowid___long_R_long(threadStateData, __cn1Arg1); +} + +JAVA_INT com_codename1_impl_windows_WindowsNative_sqlColType___long_int_R_int(CODENAME_ONE_THREAD_STATE, JAVA_LONG __cn1Arg1, JAVA_INT __cn1Arg2) { + return cn1DbWindowsEngine_sqlColType___long_int_R_int(threadStateData, __cn1Arg1, __cn1Arg2); +} + +JAVA_VOID com_codename1_impl_windows_WindowsNative_sqlStmtBindString___long_int_java_lang_String(CODENAME_ONE_THREAD_STATE, JAVA_LONG __cn1Arg1, JAVA_INT __cn1Arg2, JAVA_OBJECT __cn1Arg3) { + cn1DbWindowsEngine_sqlStmtBindString___long_int_java_lang_String(threadStateData, __cn1Arg1, __cn1Arg2, __cn1Arg3); +} + +JAVA_OBJECT com_codename1_impl_windows_WindowsNative_sqlColString___long_int_R_java_lang_String(CODENAME_ONE_THREAD_STATE, JAVA_LONG __cn1Arg1, JAVA_INT __cn1Arg2) { + return cn1DbWindowsEngine_sqlColString___long_int_R_java_lang_String(threadStateData, __cn1Arg1, __cn1Arg2); +} + +JAVA_OBJECT com_codename1_impl_windows_WindowsNative_sqlColNameString___long_int_R_java_lang_String(CODENAME_ONE_THREAD_STATE, JAVA_LONG __cn1Arg1, JAVA_INT __cn1Arg2) { + return cn1DbWindowsEngine_sqlColNameString___long_int_R_java_lang_String(threadStateData, __cn1Arg1, __cn1Arg2); +} + +JAVA_BOOLEAN com_codename1_impl_windows_WindowsNative_sqlRowValues___long_java_lang_Object_1ARRAY_R_boolean(CODENAME_ONE_THREAD_STATE, JAVA_LONG __cn1Arg1, JAVA_OBJECT __cn1Arg2) { + return cn1DbWindowsEngine_sqlRowValues___long_java_lang_Object_1ARRAY_R_boolean(threadStateData, __cn1Arg1, __cn1Arg2); +} + +JAVA_INT com_codename1_impl_windows_WindowsNative_sqlStmtStepStatus___long_R_int(CODENAME_ONE_THREAD_STATE, JAVA_LONG __cn1Arg1) { + return cn1DbWindowsEngine_sqlStmtStepStatus___long_R_int(threadStateData, __cn1Arg1); +} + +JAVA_LONG com_codename1_impl_windows_WindowsNative_sqlStmtPrepareStatus___long_java_lang_String_R_long(CODENAME_ONE_THREAD_STATE, JAVA_LONG __cn1Arg1, JAVA_OBJECT __cn1Arg2) { + return cn1DbWindowsEngine_sqlStmtPrepareStatus___long_java_lang_String_R_long(threadStateData, __cn1Arg1, __cn1Arg2); +} + +JAVA_OBJECT com_codename1_impl_windows_WindowsNative_sqlDbErrorText___long_R_java_lang_String(CODENAME_ONE_THREAD_STATE, JAVA_LONG __cn1Arg1) { + return cn1DbWindowsEngine_sqlDbErrorText___long_R_java_lang_String(threadStateData, __cn1Arg1); +} + +JAVA_INT com_codename1_impl_windows_WindowsNative_sqlStmtRunStatus___long_java_lang_Object_1ARRAY_long_1ARRAY_R_int(CODENAME_ONE_THREAD_STATE, JAVA_LONG __cn1Arg1, JAVA_OBJECT __cn1Arg2, JAVA_OBJECT __cn1Arg3) { + return cn1DbWindowsEngine_sqlStmtRunStatus___long_java_lang_Object_1ARRAY_long_1ARRAY_R_int(threadStateData, __cn1Arg1, __cn1Arg2, __cn1Arg3); +} + +JAVA_INT com_codename1_impl_windows_WindowsNative_sqlStmtFinalizeStatus___long_R_int(CODENAME_ONE_THREAD_STATE, JAVA_LONG __cn1Arg1) { + return cn1DbWindowsEngine_sqlStmtFinalizeStatus___long_R_int(threadStateData, __cn1Arg1); +} diff --git a/Ports/WindowsPort/src/com/codename1/impl/windows/WindowsDatabase.java b/Ports/WindowsPort/src/com/codename1/impl/windows/WindowsDatabase.java index 13670849aa4..f686863632f 100644 --- a/Ports/WindowsPort/src/com/codename1/impl/windows/WindowsDatabase.java +++ b/Ports/WindowsPort/src/com/codename1/impl/windows/WindowsDatabase.java @@ -26,9 +26,10 @@ import com.codename1.db.Database; import com.codename1.db.DatabaseConfig; import com.codename1.db.DatabaseEncryptionException; +import java.util.function.Function; import com.codename1.impl.AbstractDBCursor; import com.codename1.impl.SQLStatementSplitter; -import com.codename1.impl.SQLText; +import com.codename1.impl.SqlFunctionBridge; import java.io.IOException; import java.util.ArrayList; @@ -44,6 +45,70 @@ class WindowsDatabase extends Database { private long peer; + /// The functions every connection of this process has registered; SQLite holds only the id. + private static final SqlFunctionBridge FUNCTIONS = new SqlFunctionBridge() { + @Override + protected int valueType(long argv, int i) { + return WindowsNative.sqlValueType(argv, i); + } + + @Override + protected long valueLong(long argv, int i) { + return WindowsNative.sqlValueLong(argv, i); + } + + @Override + protected double valueDouble(long argv, int i) { + return WindowsNative.sqlValueDouble(argv, i); + } + + @Override + protected byte[] valueText(long argv, int i) { + return WindowsNative.sqlValueText(argv, i); + } + + @Override + protected byte[] valueBlob(long argv, int i) { + return WindowsNative.sqlValueBlob(argv, i); + } + + @Override + protected void resultNull(long ctx) { + WindowsNative.sqlResultNull(ctx); + } + + @Override + protected void resultLong(long ctx, long v) { + WindowsNative.sqlResultLong(ctx, v); + } + + @Override + protected void resultDouble(long ctx, double v) { + WindowsNative.sqlResultDouble(ctx, v); + } + + @Override + protected void resultText(long ctx, byte[] utf8) { + WindowsNative.sqlResultText(ctx, utf8); + } + + @Override + protected void resultBlob(long ctx, byte[] v) { + WindowsNative.sqlResultBlob(ctx, v); + } + + @Override + protected void resultError(long ctx, byte[] utf8) { + WindowsNative.sqlResultError(ctx, utf8); + } + }; + + /// Called by the engine (cn1_windows_db.c) while a statement calls a Java function. + static void sqlFunctionCall(long ctx, int id, int argc, long argv) { + FUNCTIONS.call(ctx, id, argc, argv); + } + + /** * The name this database was opened under. Retained because a managed key resolves its * keystore alias from the database name, and changeKey() would otherwise have nothing to @@ -52,6 +117,7 @@ class WindowsDatabase extends Database { private final String databaseName; private final List openCursors = new ArrayList(); + private final com.codename1.impl.SQLStatementCache statements = new com.codename1.impl.SQLStatementCache(); /// SQLite's success code. private static final int SQLITE_OK = 0; @@ -303,7 +369,7 @@ private void requireSingleStatement(String sql) throws IOException { if (isLegacyBehavior()) { return; } - if (SQLStatementSplitter.isMultiStatement(sql)) { + if (!isPlainStatement(sql) && SQLStatementSplitter.isMultiStatement(sql)) { throw new IOException("This method takes a single SQL statement, but the string " + "contains " + SQLStatementSplitter.countStatements(sql) + ". Use execute(String) to run a script."); @@ -372,6 +438,11 @@ public void close() throws IOException { for (int iter = 0; iter < cursors.length; iter++) { cursors[iter].databaseClosed(); } + // SQLite will not close a connection whose statements are still alive. + long[] cached = statements.drain(); + for (int iter = 0; iter < cached.length; iter++) { + WindowsNative.sqlStmtFinalize(cached[iter]); + } long closing = peer; peer = 0; try { @@ -389,6 +460,32 @@ public void close() throws IOException { } } + @Override + public long changes() throws IOException { + checkOpen(); + return WindowsNative.sqlDbChanges(peer); + } + + @Override + public long lastInsertRowId() throws IOException { + checkOpen(); + return WindowsNative.sqlDbLastInsertRowid(peer); + } + + @Override + public boolean supportsFunctions() { + return true; + } + + @Override + public void createFunction(String name, int argCount, Function function) throws IOException { + checkOpen(); + int id = function == null ? -1 : FUNCTIONS.register(function); + if (WindowsNative.sqlDbCreateFunction(peer, com.codename1.util.StringUtil.getBytes(name), argCount, id) != 0) { + throw new IOException("Could not create the SQL function " + name); + } + } + @Override public void changeKey(DatabaseConfig config) throws IOException { checkOpen(); @@ -481,9 +578,23 @@ public void execute(String sql, Object... params) throws IOException { reserveAttachments(sql, params); requireSingleStatement(sql); try { - long stmt = WindowsNative.sqlStmtPrepare(peer, sql); + long stmt = statements.take(sql); + if (stmt == 0) { + stmt = WindowsNative.sqlStmtPrepare(peer, sql); + } + // bind finalizes the statement itself when it throws. bind(stmt, params); - WindowsNative.sqlStmtExecuteAndFinalize(stmt); + try { + while (WindowsNative.sqlStmtStep(stmt)) { + // Rows of a statement run for its effect are discarded, as before. + } + } catch (IOException err) { + WindowsNative.sqlStmtFinalize(stmt); + throw err; + } + // Reset releases what the run holds, so a cached statement keeps no lock. + WindowsNative.sqlStmtReset(stmt); + WindowsNative.sqlStmtFinalize(statements.put(sql, stmt)); // The names on success only -- a statement that failed opened no savepoint. noteScriptTransactionControl(sql); } finally { @@ -494,12 +605,56 @@ public void execute(String sql, Object... params) throws IOException { } } + /// The status form of [#execute(String, Object...)], with no handler on the way for the + /// statement nearly every call runs: one plain statement on an open connection, its + /// parameters ones the engine binds directly. Anything else -- and the bookkeeping after a + /// failure -- takes the inherited path, which wraps the throwing method. + @Override + public int executeStatus(String sql, Object[] params, long[] counts) { + if (peer == 0 || params == null || !isPlainStatement(sql)) { + return super.executeStatus(sql, params, counts); + } + long stmt = statements.take(sql); + if (stmt == 0) { + stmt = WindowsNative.sqlStmtPrepareStatus(peer, sql); + if (stmt == 0) { + return failStatus(WindowsNative.sqlDbErrorText(peer), 1); + } + } + int rc = WindowsNative.sqlStmtRunStatus(stmt, params, counts); + if (rc == 0) { + // A plain statement that ran changed no transaction state. + WindowsNative.sqlStmtFinalizeStatus(statements.put(sql, stmt)); + return 0; + } + return statementFailed(sql, params, counts, stmt, rc); + } + + /// The cold half of [#executeStatus(String, Object[], long[])], kept apart so that its handler is + /// set up only when a statement did not run. + private int statementFailed(String sql, Object[] params, long[] counts, long stmt, int rc) { + if (rc == -2 || rc == -3) { + // Nothing ran: a parameter only Java binds, or a count the throwing path words. + WindowsNative.sqlStmtFinalizeStatus(statements.put(sql, stmt)); + return super.executeStatus(sql, params, counts); + } + String message = WindowsNative.sqlDbErrorText(peer); + WindowsNative.sqlStmtFinalizeStatus(stmt); + try { + // As execute does after any run: ON CONFLICT ROLLBACK ends the transaction as it fails. + noteEngineTransactionState(WindowsNative.sqlDbInTransaction(peer)); + } catch (IOException err) { + return failStatus(err.getMessage(), rc); + } + return failStatus(message, rc); + } + @Override public Cursor executeQuery(String sql) throws IOException { checkOpen(); requireSingleStatement(sql); requireQueryStatement(sql); - long stmt = WindowsNative.sqlStmtPrepare(peer, sql); + long stmt = prepareCached(sql); // A statement with placeholders and no arguments would otherwise run with every slot left // as NULL rather than reporting the missing parameters. The check is a no-op in legacy // mode, where running it unbound is the behaviour applications were written against. @@ -519,7 +674,7 @@ public Cursor executeQuery(String sql, String[] params) throws IOException { checkOpen(); requireSingleStatement(sql); requireQueryStatement(sql); - long stmt = WindowsNative.sqlStmtPrepare(peer, sql); + long stmt = prepareCached(sql); bindText(stmt, params); return register(new CursorImpl(stmt), sql); } @@ -536,13 +691,29 @@ public Cursor executeQuery(String sql, Object... params) throws IOException { checkOpen(); requireSingleStatement(sql); requireQueryStatement(sql); - long stmt = WindowsNative.sqlStmtPrepare(peer, sql); + long stmt = prepareCached(sql); bind(stmt, params); return register(new CursorImpl(stmt), sql); } + private long prepareCached(String sql) throws IOException { + long stmt = statements.take(sql); + return stmt != 0 ? stmt : WindowsNative.sqlStmtPrepare(peer, sql); + } + + /// Takes back a closed cursor's statement, reset, for the next query with the same SQL. + void recycle(String sql, long stmt) throws IOException { + if (peer == 0 || sql == null) { + WindowsNative.sqlStmtFinalize(stmt); + return; + } + WindowsNative.sqlStmtReset(stmt); + WindowsNative.sqlStmtFinalize(statements.put(sql, stmt)); + } + private Cursor register(CursorImpl cursor, String sql) { cursor.owner = this; + cursor.cacheKey = sql; // A statement that writes must never be re-executed to move backwards: this cursor is // stepped to run it, so a getCount() or last() would write again. The cursor refuses // rather than doing it twice. @@ -595,7 +766,7 @@ private void bindText(long stmt, String[] params) throws IOException { if (params[iter] == null) { WindowsNative.sqlStmtBindNull(stmt, iter + 1); } else { - WindowsNative.sqlStmtBindText(stmt, iter + 1, SQLText.toUTF8(params[iter])); + WindowsNative.sqlStmtBindString(stmt, iter + 1, params[iter]); } } } catch (IOException err) { @@ -636,7 +807,7 @@ private void bindEach(long stmt, Object[] params) throws IOException { } else if (p instanceof byte[]) { WindowsNative.sqlStmtBindBlob(stmt, index, (byte[]) p); } else if (p instanceof String) { - WindowsNative.sqlStmtBindText(stmt, index, SQLText.toUTF8((String) p)); + WindowsNative.sqlStmtBindString(stmt, index, (String) p); } else if (p instanceof Double || p instanceof Float) { WindowsNative.sqlStmtBindDouble(stmt, index, ((Number) p).doubleValue()); } else if (p instanceof Long || p instanceof Integer || p instanceof Short @@ -645,7 +816,7 @@ private void bindEach(long stmt, Object[] params) throws IOException { } else if (p instanceof Boolean) { WindowsNative.sqlStmtBindLong(stmt, index, ((Boolean) p).booleanValue() ? 1 : 0); } else { - WindowsNative.sqlStmtBindText(stmt, index, SQLText.toUTF8(p.toString())); + WindowsNative.sqlStmtBindString(stmt, index, p.toString()); } } } @@ -653,6 +824,7 @@ private void bindEach(long stmt, Object[] params) throws IOException { /** Cursor over a compiled statement; seeks by resetting and stepping again. */ static class CursorImpl extends AbstractDBCursor { private long stmt; + String cacheKey; WindowsDatabase owner; CursorImpl(long stmt) { @@ -712,7 +884,11 @@ protected void closeImpl() throws IOException { if (stmt != 0) { long closing = stmt; stmt = 0; - WindowsNative.sqlStmtFinalize(closing); + if (owner != null) { + owner.recycle(cacheKey, closing); + } else { + WindowsNative.sqlStmtFinalize(closing); + } } } @@ -723,7 +899,23 @@ protected int columnCount() throws IOException { @Override protected String columnLabel(int columnIndex) throws IOException { - return SQLText.fromUTF8(WindowsNative.sqlColName(stmt, columnIndex)); + return WindowsNative.sqlColNameString(stmt, columnIndex); + } + + @Override + protected boolean capturesColumnTypeBeforeRead() { + // sqlite3_column_type is undefined once a getter has converted the value. + return true; + } + + @Override + protected int columnType(int index) throws IOException { + return WindowsNative.sqlColType(stmt, index); + } + + @Override + protected boolean readRow(Object[] out) throws IOException { + return WindowsNative.sqlRowValues(stmt, out); } @Override @@ -733,7 +925,7 @@ protected boolean isNullAt(int index) throws IOException { @Override protected String readString(int index) throws IOException { - return SQLText.fromUTF8(WindowsNative.sqlColText(stmt, index)); + return WindowsNative.sqlColString(stmt, index); } @Override diff --git a/Ports/WindowsPort/src/com/codename1/impl/windows/WindowsImplementation.java b/Ports/WindowsPort/src/com/codename1/impl/windows/WindowsImplementation.java index 30bbe2b0ec9..efc30135bba 100644 --- a/Ports/WindowsPort/src/com/codename1/impl/windows/WindowsImplementation.java +++ b/Ports/WindowsPort/src/com/codename1/impl/windows/WindowsImplementation.java @@ -4095,6 +4095,18 @@ public com.codename1.db.Database openOrCreateDB(String databaseName) throws java return openOrCreateDB(databaseName, null); } + @Override + public boolean isInMemoryDatabaseSupported() { + return true; + } + + @Override + public com.codename1.db.Database openInMemoryDB() throws java.io.IOException { + // SQLite's own name for a private in-memory database. The open registry files every + // such connection under the one key, which no real file has: a count, never a refusal. + return new WindowsDatabase(":memory:", ":memory:", null); + } + @Override public com.codename1.db.Database openOrCreateDB(String databaseName, com.codename1.db.DatabaseConfig config) throws java.io.IOException { diff --git a/Ports/WindowsPort/src/com/codename1/impl/windows/WindowsNative.java b/Ports/WindowsPort/src/com/codename1/impl/windows/WindowsNative.java index bf4ab3c16a5..41949122dc4 100644 --- a/Ports/WindowsPort/src/com/codename1/impl/windows/WindowsNative.java +++ b/Ports/WindowsPort/src/com/codename1/impl/windows/WindowsNative.java @@ -1254,6 +1254,8 @@ public static native void gl3dEndPost(long contextPeer, long brightPipeline, lon public static native void sqlDbExecScript(long dbPeer, String sql) throws java.io.IOException; + public static native long sqlDbChanges(long dbPeer); + public static native long sqlDbLastInsertRowid(long dbPeer); public static native long sqlStmtPrepare(long dbPeer, String sql) throws java.io.IOException; public static native int sqlStmtParameterCount(long stmtPeer) throws java.io.IOException; public static native void sqlStmtBindNull(long stmtPeer, int index) throws java.io.IOException; @@ -1271,11 +1273,43 @@ public static native void gl3dEndPost(long contextPeer, long brightPipeline, lon public static native int sqlColCount(long stmtPeer) throws java.io.IOException; public static native byte[] sqlColName(long stmtPeer, int col) throws java.io.IOException; + public static native int sqlColType(long stmtPeer, int col); public static native boolean sqlColIsNull(long stmtPeer, int col) throws java.io.IOException; public static native byte[] sqlColText(long stmtPeer, int col) throws java.io.IOException; + // Text as a String read or built in place by the native, with no UTF-8 byte[] in between. + public static native void sqlStmtBindString(long stmtPeer, int index, String value) throws java.io.IOException; + public static native String sqlColString(long stmtPeer, int col) throws java.io.IOException; + public static native String sqlColNameString(long stmtPeer, int col) throws java.io.IOException; + // The whole current row, written into the caller's array; false when it is too short. + public static native boolean sqlRowValues(long stmtPeer, Object[] out); + // SQLite's result code instead of an exception, and the connection's message of the last one. + public static native int sqlStmtStepStatus(long stmtPeer); + // 0 when the statement does not compile; the message is then sqlDbErrorText's. + public static native long sqlStmtPrepareStatus(long dbPeer, String sql); + public static native String sqlDbErrorText(long dbPeer); + public static native int sqlStmtFinalizeStatus(long stmtPeer); + // Bind, step to the end and reset in one call: 0, -3 for a parameter count the statement does + // not take, -2 for a parameter only Java binds (nothing ran), else SQLite's code. On 0, + // counts (if not null) receives the changes and the last row id. + public static native int sqlStmtRunStatus(long stmtPeer, Object[] params, long[] counts); public static native byte[] sqlColBlob(long stmtPeer, int col) throws java.io.IOException; public static native double sqlColDouble(long stmtPeer, int col) throws java.io.IOException; public static native long sqlColLong(long stmtPeer, int col) throws java.io.IOException; + // SQL functions written in Java (Database.createFunction). The engine calls back into + // the port's database class (sqlFunctionCall), which reads the arguments and sets the + // result through these while sqlite3_step waits. + public static native int sqlDbCreateFunction(long dbPeer, byte[] nameUtf8, int argCount, int id); + public static native int sqlValueType(long argv, int index); + public static native long sqlValueLong(long argv, int index); + public static native double sqlValueDouble(long argv, int index); + public static native byte[] sqlValueText(long argv, int index); + public static native byte[] sqlValueBlob(long argv, int index); + public static native void sqlResultNull(long ctx); + public static native void sqlResultLong(long ctx, long value); + public static native void sqlResultDouble(long ctx, double value); + public static native void sqlResultText(long ctx, byte[] utf8); + public static native void sqlResultBlob(long ctx, byte[] value); + public static native void sqlResultError(long ctx, byte[] utf8); /// True when the exe was built for the embedded (kiosk) target /// (`windows.embedded=true`, cn1_windows_embedded.cpp): a constant of the diff --git a/Ports/iOSPort/nativeSources/IOSNative.m b/Ports/iOSPort/nativeSources/IOSNative.m index 5d18ae9238d..070b42bfd52 100644 --- a/Ports/iOSPort/nativeSources/IOSNative.m +++ b/Ports/iOSPort/nativeSources/IOSNative.m @@ -13517,6 +13517,14 @@ JAVA_BOOLEAN com_codename1_impl_ios_IOSNative_sqlDbInTransaction___long(CN1_THRE return sqlite3_get_autocommit((sqlite3*)dbPeer) ? JAVA_FALSE : JAVA_TRUE; } +JAVA_LONG com_codename1_impl_ios_IOSNative_sqlDbChanges___long_R_long(CN1_THREAD_STATE_MULTI_ARG JAVA_OBJECT instanceObject, JAVA_LONG dbPeer) { + return (JAVA_LONG)sqlite3_changes((sqlite3*)dbPeer); +} + +JAVA_LONG com_codename1_impl_ios_IOSNative_sqlDbLastInsertRowid___long_R_long(CN1_THREAD_STATE_MULTI_ARG JAVA_OBJECT instanceObject, JAVA_LONG dbPeer) { + return (JAVA_LONG)sqlite3_last_insert_rowid((sqlite3*)dbPeer); +} + void com_codename1_impl_ios_IOSNative_sqlDbExecScript___long_java_lang_String(CN1_THREAD_STATE_MULTI_ARG JAVA_OBJECT instanceObject, JAVA_LONG dbPeer, JAVA_OBJECT sql) { sqlite3* db = (sqlite3*)dbPeer; const char* chrs = stringToUTF8(CN1_THREAD_STATE_PASS_ARG sql); @@ -13635,6 +13643,83 @@ void com_codename1_impl_ios_IOSNative_sqlStmtFinalize___long(CN1_THREAD_STATE_MU } } +// SQL functions written in Java (Database.createFunction). SQLite calls cn1JavaSqlFunction on the +// thread stepping the statement; DatabaseImpl.sqlFunctionCall reads the arguments and sets the +// result back through the natives below. The engine holds only the function's id. +extern void com_codename1_impl_ios_DatabaseImpl_sqlFunctionCall___long_int_int_long(CODENAME_ONE_THREAD_STATE, JAVA_LONG ctx, JAVA_INT fid, JAVA_INT argc, JAVA_LONG argv); + +static void cn1JavaSqlFunction(sqlite3_context* c, int argc, sqlite3_value** v) { + com_codename1_impl_ios_DatabaseImpl_sqlFunctionCall___long_int_int_long(getThreadLocalData(), + (JAVA_LONG)(intptr_t)c, (JAVA_INT)(intptr_t)sqlite3_user_data(c), argc, (JAVA_LONG)(intptr_t)v); +} + +static JAVA_OBJECT cn1SqlBytes(const void* bytes, int length) { + return nsDataToByteArr([NSData dataWithBytes:(bytes == NULL ? "" : bytes) length:(NSUInteger)(length < 0 ? 0 : length)]); +} + +JAVA_INT com_codename1_impl_ios_IOSNative_sqlDbCreateFunction___long_byte_1ARRAY_int_int_R_int(CN1_THREAD_STATE_MULTI_ARG JAVA_OBJECT instanceObject, JAVA_LONG dbPeer, JAVA_OBJECT name, JAVA_INT argc, JAVA_INT fid) { + JAVA_ARRAY arr = (JAVA_ARRAY)name; + char buf[256]; + int n = arr->length < 255 ? arr->length : 255; + memcpy(buf, CN1_ARRAY_DATA(arr), n); + buf[n] = 0; + return sqlite3_create_function_v2((sqlite3*)(intptr_t)dbPeer, buf, argc, SQLITE_UTF8, + (void*)(intptr_t)fid, fid < 0 ? NULL : cn1JavaSqlFunction, NULL, NULL, NULL); +} + +JAVA_INT com_codename1_impl_ios_IOSNative_sqlValueType___long_int_R_int(CN1_THREAD_STATE_MULTI_ARG JAVA_OBJECT instanceObject, JAVA_LONG argv, JAVA_INT i) { + return sqlite3_value_type(((sqlite3_value**)(intptr_t)argv)[i]); +} + +JAVA_LONG com_codename1_impl_ios_IOSNative_sqlValueLong___long_int_R_long(CN1_THREAD_STATE_MULTI_ARG JAVA_OBJECT instanceObject, JAVA_LONG argv, JAVA_INT i) { + return (JAVA_LONG)sqlite3_value_int64(((sqlite3_value**)(intptr_t)argv)[i]); +} + +JAVA_DOUBLE com_codename1_impl_ios_IOSNative_sqlValueDouble___long_int_R_double(CN1_THREAD_STATE_MULTI_ARG JAVA_OBJECT instanceObject, JAVA_LONG argv, JAVA_INT i) { + return sqlite3_value_double(((sqlite3_value**)(intptr_t)argv)[i]); +} + +JAVA_OBJECT com_codename1_impl_ios_IOSNative_sqlValueText___long_int_R_byte_1ARRAY(CN1_THREAD_STATE_MULTI_ARG JAVA_OBJECT instanceObject, JAVA_LONG argv, JAVA_INT i) { + sqlite3_value* v = ((sqlite3_value**)(intptr_t)argv)[i]; + const unsigned char* t = sqlite3_value_text(v); + return cn1SqlBytes(t, t == NULL ? 0 : sqlite3_value_bytes(v)); +} + +JAVA_OBJECT com_codename1_impl_ios_IOSNative_sqlValueBlob___long_int_R_byte_1ARRAY(CN1_THREAD_STATE_MULTI_ARG JAVA_OBJECT instanceObject, JAVA_LONG argv, JAVA_INT i) { + sqlite3_value* v = ((sqlite3_value**)(intptr_t)argv)[i]; + const void* b = sqlite3_value_blob(v); + return cn1SqlBytes(b, b == NULL ? 0 : sqlite3_value_bytes(v)); +} + +void com_codename1_impl_ios_IOSNative_sqlResultNull___long(CN1_THREAD_STATE_MULTI_ARG JAVA_OBJECT instanceObject, JAVA_LONG ctx) { + sqlite3_result_null((sqlite3_context*)(intptr_t)ctx); +} + +void com_codename1_impl_ios_IOSNative_sqlResultLong___long_long(CN1_THREAD_STATE_MULTI_ARG JAVA_OBJECT instanceObject, JAVA_LONG ctx, JAVA_LONG v) { + sqlite3_result_int64((sqlite3_context*)(intptr_t)ctx, (sqlite3_int64)v); +} + +void com_codename1_impl_ios_IOSNative_sqlResultDouble___long_double(CN1_THREAD_STATE_MULTI_ARG JAVA_OBJECT instanceObject, JAVA_LONG ctx, JAVA_DOUBLE v) { + sqlite3_result_double((sqlite3_context*)(intptr_t)ctx, v); +} + +void com_codename1_impl_ios_IOSNative_sqlResultText___long_byte_1ARRAY(CN1_THREAD_STATE_MULTI_ARG JAVA_OBJECT instanceObject, JAVA_LONG ctx, JAVA_OBJECT v) { + JAVA_ARRAY arr = (JAVA_ARRAY)v; + sqlite3_result_text((sqlite3_context*)(intptr_t)ctx, arr->length > 0 ? (const char*)CN1_ARRAY_DATA(arr) : "", + arr->length, SQLITE_TRANSIENT); +} + +void com_codename1_impl_ios_IOSNative_sqlResultBlob___long_byte_1ARRAY(CN1_THREAD_STATE_MULTI_ARG JAVA_OBJECT instanceObject, JAVA_LONG ctx, JAVA_OBJECT v) { + JAVA_ARRAY arr = (JAVA_ARRAY)v; + sqlite3_result_blob((sqlite3_context*)(intptr_t)ctx, arr->length > 0 ? CN1_ARRAY_DATA(arr) : (const void*)"", + arr->length, SQLITE_TRANSIENT); +} + +void com_codename1_impl_ios_IOSNative_sqlResultError___long_byte_1ARRAY(CN1_THREAD_STATE_MULTI_ARG JAVA_OBJECT instanceObject, JAVA_LONG ctx, JAVA_OBJECT v) { + JAVA_ARRAY arr = (JAVA_ARRAY)v; + sqlite3_result_error((sqlite3_context*)(intptr_t)ctx, (const char*)CN1_ARRAY_DATA(arr), arr->length); +} + void com_codename1_impl_ios_IOSNative_sqlStmtExecuteAndFinalize___long(CN1_THREAD_STATE_MULTI_ARG JAVA_OBJECT instanceObject, JAVA_LONG statementPeer) { sqlite3_stmt* stmt = (sqlite3_stmt*)statementPeer; int rc; @@ -17902,11 +17987,8 @@ JAVA_BOOLEAN com_codename1_impl_ios_IOSNative_isAsyncEditMode___R_boolean(CN1_TH } JAVA_VOID com_codename1_impl_ios_IOSNative_printStackTraceToStream___java_lang_Throwable_java_io_Writer(CODENAME_ONE_THREAD_STATE, JAVA_OBJECT thisObj, JAVA_OBJECT exception, JAVA_OBJECT writer) { - struct obj__java_lang_Throwable* th = (struct obj__java_lang_Throwable*)exception; - if(th->java_lang_Throwable_stack == JAVA_NULL) { - java_lang_Throwable_fillInStack__(threadStateData, exception); - } - virtual_java_io_Writer_write___java_lang_String(threadStateData, writer, th->java_lang_Throwable_stack); + // A throw records frames only; cn1ThrowableStack renders them. + virtual_java_io_Writer_write___java_lang_String(threadStateData, writer, cn1ThrowableStack(threadStateData, exception)); } JAVA_BOOLEAN com_codename1_impl_ios_IOSNative_canExecute___java_lang_String_R_boolean(CN1_THREAD_STATE_MULTI_ARG JAVA_OBJECT instanceObject, JAVA_OBJECT url) { diff --git a/Ports/iOSPort/src/com/codename1/impl/ios/DatabaseImpl.java b/Ports/iOSPort/src/com/codename1/impl/ios/DatabaseImpl.java index a5962954aff..b309fa98f74 100644 --- a/Ports/iOSPort/src/com/codename1/impl/ios/DatabaseImpl.java +++ b/Ports/iOSPort/src/com/codename1/impl/ios/DatabaseImpl.java @@ -29,6 +29,8 @@ import com.codename1.impl.AbstractDBCursor; import com.codename1.impl.SQLStatementSplitter; import com.codename1.impl.SQLText; +import com.codename1.impl.SqlFunctionBridge; +import java.util.function.Function; import java.io.IOException; import java.util.Vector; @@ -39,11 +41,101 @@ class DatabaseImpl extends Database { private long peer; + /** The functions every connection has registered; SQLite holds only the id. */ + private static final SqlFunctionBridge FUNCTIONS = new SqlFunctionBridge() { + @Override + protected int valueType(long argv, int i) { + return IOSImplementation.nativeInstance.sqlValueType(argv, i); + } + + @Override + protected long valueLong(long argv, int i) { + return IOSImplementation.nativeInstance.sqlValueLong(argv, i); + } + + @Override + protected double valueDouble(long argv, int i) { + return IOSImplementation.nativeInstance.sqlValueDouble(argv, i); + } + + @Override + protected byte[] valueText(long argv, int i) { + return IOSImplementation.nativeInstance.sqlValueText(argv, i); + } + + @Override + protected byte[] valueBlob(long argv, int i) { + return IOSImplementation.nativeInstance.sqlValueBlob(argv, i); + } + + @Override + protected void resultNull(long ctx) { + IOSImplementation.nativeInstance.sqlResultNull(ctx); + } + + @Override + protected void resultLong(long ctx, long v) { + IOSImplementation.nativeInstance.sqlResultLong(ctx, v); + } + + @Override + protected void resultDouble(long ctx, double v) { + IOSImplementation.nativeInstance.sqlResultDouble(ctx, v); + } + + @Override + protected void resultText(long ctx, byte[] utf8) { + IOSImplementation.nativeInstance.sqlResultText(ctx, utf8); + } + + @Override + protected void resultBlob(long ctx, byte[] v) { + IOSImplementation.nativeInstance.sqlResultBlob(ctx, v); + } + + @Override + protected void resultError(long ctx, byte[] utf8) { + IOSImplementation.nativeInstance.sqlResultError(ctx, utf8); + } + }; + + /** Called by the engine (IOSNative.m) while a statement calls a Java function. */ + static void sqlFunctionCall(long ctx, int id, int argc, long argv) { + FUNCTIONS.call(ctx, id, argc, argv); + } + + @Override + public long changes() throws IOException { + checkOpen(); + return IOSImplementation.nativeInstance.sqlDbChanges(peer); + } + + @Override + public long lastInsertRowId() throws IOException { + checkOpen(); + return IOSImplementation.nativeInstance.sqlDbLastInsertRowid(peer); + } + + @Override + public boolean supportsFunctions() { + return true; + } + + @Override + public void createFunction(String name, int argCount, Function function) throws IOException { + checkOpen(); + int id = function == null ? -1 : FUNCTIONS.register(function); + if (IOSImplementation.nativeInstance.sqlDbCreateFunction(peer, com.codename1.util.StringUtil.getBytes(name), argCount, id) != 0) { + throw new IOException("Could not create the SQL function " + name); + } + } + /** * Cursors opened from this database. Closing the database finalizes its statements, so the * cursors have to be marked dead rather than left holding freed pointers. */ private final Vector openCursors = new Vector(); + private final com.codename1.impl.SQLStatementCache statements = new com.codename1.impl.SQLStatementCache(); /** The file this connection is open on, for the shared registry a key change consults. */ private final String openKey; @@ -153,7 +245,7 @@ private void requireSingleStatement(String sql) throws IOException { if (isLegacyBehavior()) { return; } - if (SQLStatementSplitter.isMultiStatement(sql)) { + if (!isPlainStatement(sql) && SQLStatementSplitter.isMultiStatement(sql)) { throw new IOException("This method takes a single SQL statement, but the string " + "contains " + SQLStatementSplitter.countStatements(sql) + ". Use execute(String) to run a script."); @@ -224,6 +316,11 @@ public void close() throws IOException { for (int iter = 0; iter < cursors.length; iter++) { ((CursorImpl)cursors[iter]).databaseClosed(); } + // SQLite will not close a connection whose statements are still alive. + long[] cached = statements.drain(); + for (int iter = 0; iter < cached.length; iter++) { + IOSImplementation.nativeInstance.sqlStmtFinalize(cached[iter]); + } long closing = peer; peer = 0; try { @@ -335,9 +432,23 @@ public void execute(String sql, Object... params) throws IOException { return; } try { - long stmt = IOSImplementation.nativeInstance.sqlStmtPrepare(peer, sql); + long stmt = statements.take(sql); + if (stmt == 0) { + stmt = IOSImplementation.nativeInstance.sqlStmtPrepare(peer, sql); + } + // bind finalizes the statement itself when it throws. bind(stmt, params); - IOSImplementation.nativeInstance.sqlStmtExecuteAndFinalize(stmt); + try { + while (IOSImplementation.nativeInstance.sqlStmtStep(stmt)) { + // Rows of a statement run for its effect are discarded, as before. + } + } catch (IOException err) { + IOSImplementation.nativeInstance.sqlStmtFinalize(stmt); + throw err; + } + // Reset releases what the run holds, so a cached statement keeps no lock. + IOSImplementation.nativeInstance.sqlStmtReset(stmt); + IOSImplementation.nativeInstance.sqlStmtFinalize(statements.put(sql, stmt)); // The names on success only -- a statement that failed opened no savepoint. noteScriptTransactionControl(sql); } finally { @@ -353,7 +464,7 @@ public Cursor executeQuery(String sql, String[] params) throws IOException { checkOpen(); requireSingleStatement(sql); requireQueryStatement(sql); - long stmt = IOSImplementation.nativeInstance.sqlStmtPrepare(peer, sql); + long stmt = prepareCached(sql); bindText(stmt, params); return register(new CursorImpl(stmt), sql); } @@ -373,7 +484,7 @@ public Cursor executeQuery(String sql, Object... params) throws IOException { if (isLegacyBehavior()) { return executeQuery(sql, coerceToText(params, "executeQuery")); } - long stmt = IOSImplementation.nativeInstance.sqlStmtPrepare(peer, sql); + long stmt = prepareCached(sql); bind(stmt, params); return register(new CursorImpl(stmt), sql); } @@ -390,7 +501,7 @@ public Cursor executeQuery(String sql) throws IOException { // Prepared rather than handed to sqlDbExecQuery, which binds nothing when given a null // argument array: a statement with placeholders would run with every slot left as NULL // instead of reporting the parameters the caller did not supply. - long stmt = IOSImplementation.nativeInstance.sqlStmtPrepare(peer, sql); + long stmt = prepareCached(sql); // Finalized here because this path does not go through the bind helpers, which are what // own the statement everywhere else. try { @@ -402,8 +513,24 @@ public Cursor executeQuery(String sql) throws IOException { return register(new CursorImpl(stmt), sql); } + private long prepareCached(String sql) throws IOException { + long stmt = statements.take(sql); + return stmt != 0 ? stmt : IOSImplementation.nativeInstance.sqlStmtPrepare(peer, sql); + } + + /// Takes back a closed cursor's statement, reset, for the next query with the same SQL. + void recycle(String sql, long stmt) throws IOException { + if (peer == 0 || sql == null) { + IOSImplementation.nativeInstance.sqlStmtFinalize(stmt); + return; + } + IOSImplementation.nativeInstance.sqlStmtReset(stmt); + IOSImplementation.nativeInstance.sqlStmtFinalize(statements.put(sql, stmt)); + } + private Cursor register(CursorImpl cursor, String sql) { cursor.owner = this; + cursor.cacheKey = sql; // A statement that writes must never be re-executed to move backwards: this cursor is // stepped to run it, so a getCount() or last() would write again. The cursor refuses // rather than doing it twice. @@ -528,6 +655,7 @@ private void bindEach(long stmt, Object[] params) throws IOException { */ static class CursorImpl extends AbstractDBCursor { private long stmt; + String cacheKey; DatabaseImpl owner; CursorImpl(long stmt) { @@ -588,7 +716,11 @@ protected void closeImpl() throws IOException { if (stmt != 0) { long closing = stmt; stmt = 0; - IOSImplementation.nativeInstance.sqlStmtFinalize(closing); + if (owner != null) { + owner.recycle(cacheKey, closing); + } else { + IOSImplementation.nativeInstance.sqlStmtFinalize(closing); + } } } diff --git a/Ports/iOSPort/src/com/codename1/impl/ios/IOSNative.java b/Ports/iOSPort/src/com/codename1/impl/ios/IOSNative.java index 44ef0532098..9c53e9362fa 100644 --- a/Ports/iOSPort/src/com/codename1/impl/ios/IOSNative.java +++ b/Ports/iOSPort/src/com/codename1/impl/ios/IOSNative.java @@ -1013,6 +1013,8 @@ native void gl3dDrawArrays(long contextPeer, long pipelinePeer, long vboPeer, in native void sqlDbExec(long dbPeer, String sql, String[] args); /** Whether the engine reports a transaction in progress, which is sqlite3_get_autocommit. */ native boolean sqlDbInTransaction(long dbPeer); + native long sqlDbChanges(long dbPeer); + native long sqlDbLastInsertRowid(long dbPeer); /** Runs an entire script through sqlite3_exec, which handles multiple statements. */ native void sqlDbExecScript(long dbPeer, String sql); @@ -1021,6 +1023,19 @@ native void gl3dDrawArrays(long contextPeer, long pipelinePeer, long vboPeer, in /** Compiles a statement, returning the sqlite3_stmt peer. */ native long sqlStmtPrepare(long dbPeer, String sql); + // SQL functions written in Java; see DatabaseImpl.sqlFunctionCall. + native int sqlDbCreateFunction(long dbPeer, byte[] nameUtf8, int argCount, int id); + native int sqlValueType(long argv, int index); + native long sqlValueLong(long argv, int index); + native double sqlValueDouble(long argv, int index); + native byte[] sqlValueText(long argv, int index); + native byte[] sqlValueBlob(long argv, int index); + native void sqlResultNull(long ctx); + native void sqlResultLong(long ctx, long value); + native void sqlResultDouble(long ctx, double value); + native void sqlResultText(long ctx, byte[] utf8); + native void sqlResultBlob(long ctx, byte[] value); + native void sqlResultError(long ctx, byte[] utf8); native int sqlStmtParameterCount(long statementPeer); native void sqlStmtBindNull(long statementPeer, int index); /** Binds SQL text as UTF-8 bytes; see com.codename1.impl.SQLText for why not a String. */ diff --git a/docs/developer-guide/Python-Interop.asciidoc b/docs/developer-guide/Python-Interop.asciidoc index 4a3bd2a5c94..c871b547128 100644 --- a/docs/developer-guide/Python-Interop.asciidoc +++ b/docs/developer-guide/Python-Interop.asciidoc @@ -13,10 +13,17 @@ runs at the speed of the equivalent Java. Two things follow from compiling ahead of time rather than interpreting: -* The program is known in full at build time. A module imported by a - name computed while the program runs, `exec`, `eval` and `compile` of a - string, and frame introspection are build errors that name the file and the - line. None of them reaches a device as a hidden failure. +* The program is known in full at build time. A module imported by a name + computed while the program runs, `exec` and `eval` of a string, and the + tracing hooks (`sys.settrace`, `sys.setprofile`) are build errors that + name the file and the line, in your own sources and in a package from + PyPI alike. They're errors only where the program reaches them: a + function nothing calls isn't compiled, and libraries keep most such calls + in code an application never runs, such as a command line option. For one + the program does reach, a line in `cn1-python.properties` leaves the + function out or replaces it with Java; see + <>. `sys._getframe` works, + answered from the call stack. * Packages with C extensions are supported. The package's Python is translated like your own code, and each compiled module is replaced by a Java class with the same functions; see <>. @@ -220,6 +227,26 @@ the real package: native font. Those results are drawn by the platform, so they look right but aren't Pillow's exact pixels. | `flask`, `fastapi`, `uvicorn` | See <>. +| `lxml` | `lxml.etree` in Python: lxml's tree model (parents, tails, + `nsmap`), custom element classes, `XMLParser` and `iterparse`, XPath 1.0, + and `tostring` byte for byte as libxml2 writes it. That's what + `python-pptx` and `mammoth` use. XSLT, schemas, `lxml.objectify` and + `lxml.html` aren't provided. +| `magika` | Magika's API and result shape, answered from file signatures and + the contents of ZIP and OLE containers rather than from Google's neural + model, which needs `onnxruntime`. A content it can't place is `unknown`. +| `cryptography` | AES in CBC and ECB modes from + `hazmat.primitives.ciphers`, over `com.codename1.security.Cipher`: what + `pdfminer.six` needs to read encrypted PDFs. +| `jiter`, `pydantic_core` | The parts the `openai` SDK imports: `jiter`'s + JSON parser with its partial mode, and ``pydantic_core``'s sentinel and + error types. +| `pypdfium2`, `cobble` | `pypdfium2` imports and reports every document + as one it can't render, as `pdfplumber` expects from a PDF it can't draw. + `cobble` generates its data class methods as closures instead of with + `exec`. +| `pytest-httpx` | The `httpx_mock` and `httpx2_mock` fixtures, for testing + code that uses `httpx`. | `typing_extensions`, `six`, `tabulate`, `idna`, `packaging` | |=== @@ -248,6 +275,91 @@ delete its line from the lock, or the file itself, and import again. You can also copy a package's sources into the source directory by hand; they translate like the application's own modules. +[[python-directives]] +==== Leaving code out of a build + +The build translates the whole program at once, the application and every +package together, so it knows which functions the program can reach. A +function that nothing calls, names or can find by a computed name isn't +compiled. Its body is replaced by one that raises, saying the function was +left out, so a package's command line code or an optional feature costs +nothing in an application that never uses it. + +Code the program does reach has to translate. `eval`, `exec`, `__import__` +and the frame hooks of `sys` run or inspect Python that wasn't compiled +with the program, so a function that uses one and is reached fails the +build. The error lists every such place at once, and ends with the line +that fixes it: + +[source,text] +---- +llm/cli.py:4424:9: a translated program cannot run or inspect code that was not compiled with it, and this one reaches code that does: + llm/cli.py:4424:9: exec() in llm.cli._tools_from_code + sqlite_utils/utils.py:534:9: exec() in sqlite_utils.utils._compile_code +Name each of those functions in cn1-python.properties, beside the Python sources. To leave them out (each then raises if it is called): + remove=llm.cli._tools_from_code,sqlite_utils.utils._compile_code +---- + +`cn1-python.properties` sits in `src/main/python`. Each line names +functions as `module.function` or `module.Class.method`, separated by +commas, and a key can appear on as many lines as you like. It reaches into +any package, however deep, without an edit to the package. + +[cols="1,3",options="header"] +|=== +| Line | Meaning +| `remove=` | Leaves the function out. It raises `RuntimeError`, naming + itself, if something calls it after all. +| `replace=` | Replaces the function's body with Java you write. Everything + else about the function stays: its name, its decorators, its place in the + class. +| `keep=` | Compiles a function the build would leave out, for one that's + only reached from Java or in a way the build can't see. +|=== + +`remove=` also takes more than one function at a time: + +[cols="1,3",options="header"] +|=== +| Name | What's left out +| `pkg.module.Class` | Every method of the class. The class itself stays, so + code that imports it, tests against it or derives from it still runs. +| `pkg.module` | The whole module. +| `pkg` | The package and every module under it. +|=== + +A module that's left out can still be imported, and so can a name from it. +That matters because a package usually imports all of its modules as it +loads. The error comes at the first use: calling something the module would +have held, reading an attribute of it, or deriving a class from it raises +`RuntimeError`, naming the module and the line that removed it. Use this +for the parts of a large package an application never touches, such as the +API surface of a client library it calls one endpoint of. + +A name that matches nothing in the program is an error, so a directive +never goes stale without the build saying so. + +For `replace=`, the build writes a class per module into the project's Java +sources, `com.codename1.python.ext.Shims`, with a stub for each +function. The comment over a stub lists the values it receives: + +[source,java] +---- +public final class SqliteUtilsUtilsShims { + public static void install() { + // args: code, imports, column + NativeModule.replace("sqlite_utils.utils._compile_code", args -> { + throw NativeModule.notReplaced("sqlite_utils.utils._compile_code"); + }); + } +} +---- + +The file is yours. The build writes it once and never overwrites it. Until +you fill a stub in, calling its function raises `NotImplementedError` with +the function's name. When you add a function to `replace=` for a module +whose class already exists, add its `NativeModule.replace` call by hand. + [[python-c-extensions]] ==== C extensions @@ -306,6 +418,12 @@ storage class SQLite recorded for it. The Linux, Windows and JavaScript ports don't report storage classes, so a value comes back as an `int` or a `float` when its text is a number, and as a `str` otherwise. +`create_function` registers a Python function for use in SQL where the +platform's SQLite accepts one, which is on the JVM. iOS, Android and the +other ports expose no way to register one, so there it raises +`NotSupportedError`; compute the value in Python before the query, or after +it. + [[python-backends]] === Python backends diff --git a/docs/developer-guide/developer-guide.asciidoc b/docs/developer-guide/developer-guide.asciidoc index e48cd5dfde4..c9213e504ab 100644 --- a/docs/developer-guide/developer-guide.asciidoc +++ b/docs/developer-guide/developer-guide.asciidoc @@ -344,6 +344,8 @@ include::Unity-Interop.asciidoc[] include::Python-Interop.asciidoc[] +include::Python-Hero-Ports.asciidoc[] + include::Desktop-Interop.asciidoc[] include::Kotlin-Multiplatform-Interop.asciidoc[] diff --git a/maven/backend/spotbugs-exclude.xml b/maven/backend/spotbugs-exclude.xml index 42a5acf1fe4..c6c73346386 100644 --- a/maven/backend/spotbugs-exclude.xml +++ b/maven/backend/spotbugs-exclude.xml @@ -54,6 +54,7 @@ + diff --git a/maven/build-engine/src/main/java/com/codename1/maven/BackendPackager.java b/maven/build-engine/src/main/java/com/codename1/maven/BackendPackager.java index acb935ce16a..b1572a95f17 100644 --- a/maven/build-engine/src/main/java/com/codename1/maven/BackendPackager.java +++ b/maven/build-engine/src/main/java/com/codename1/maven/BackendPackager.java @@ -419,6 +419,8 @@ private void generateControllers(File classes, File work) throws BuildExecutionE // commands and no controller takes this pass's CliApplication as its own. com.codename1.maven.processors.CommandAnnotationProcessor commands = new com.codename1.maven.processors.CommandAnnotationProcessor(); + // Forced for the reason the entity flavour is: see setBackendModule. + commands.setBackendModule(true); try { commands.start(ctx); for (AnnotatedClass cls : index.values()) { @@ -1182,6 +1184,15 @@ private void link(File translated, File binary) // always set both; this half had only the first. command.add("-DCN1_BACKEND_NO_SQLITE"); } + // The collector's floors for a server process, as vm/backend/build.sh + // sets them (its comments have the measurements): collect from 4MB of + // garbage rather than the VM's 24MB, and hold the heap near the live + // set while the collector is mostly idle. This goal set neither, so a + // packaged binary let its trigger climb to the 128MB ceiling -- the + // llm hero app peaked at a 200MB footprint, and 100-125MB with these, + // at the same wall time. Before the cflags, which may override them. + command.add("-DCN1_BIBOP_GC_MIN_TRIGGER_BYTES=" + (4 * 1024 * 1024)); + command.add("-DCN1_BIBOP_TIGHT_SURVIVAL_PERCENT=66"); if (cflags != null && cflags.trim().length() > 0) { command.addAll(Arrays.asList(cflags.trim().split("\\s+"))); } @@ -1192,6 +1203,7 @@ private void link(File translated, File binary) if (cFiles == null) { throw new BuildExecutionException("The translator produced nothing in " + sourceDir); } + List sources = new ArrayList(); for (File file : cFiles) { String name = file.getName(); // .S as well as .c, which is what vm/backend/build.sh compiles. The @@ -1201,14 +1213,44 @@ private void link(File translated, File binary) // undefined and this goal could not produce a binary at all. // Generated resource assembly is in the same position. if (name.endsWith(".c") || name.endsWith(".S") || name.endsWith(".s")) { - command.add(file.getAbsolutePath()); + sources.add(file); } } - command.addAll(Arrays.asList("-lm", "-lpthread", "-lssl", "-lcrypto", "-lnghttp2")); + // Each file to an object on every core, then one link. A single clang + // given every file compiles them one after another: a Python tool of a + // few thousand modules took 37 minutes on one core. Nothing is lost by + // splitting, since without LTO clang optimises each file on its own + // either way. + File objects = new File(sourceDir.getParentFile(), simpleName + "-obj"); + emptyDirs(objects); + mkdirs(objects); if (System.getProperty("os.name", "").startsWith("Linux")) { // libcurl is opened on the first outbound request (cn1_backend_web.c), // so an idle server never maps it or the TLS stack it was built with. + // A compile flag, so it goes before the objects are compiled. command.add("-DCN1_BACKEND_CURL_DLOPEN"); + } + List compiled = compileObjects(new ArrayList(command), sources, objects); + StringBuilder list = new StringBuilder(); + for (File object : compiled) { + list.append('"').append(object.getAbsolutePath().replace("\\", "\\\\") + .replace("\"", "\\\"")).append("\"\n"); + } + // Through a response file rather than on the command line: thousands of + // objects outgrow the kernel's argument limit (E2BIG) and the linker + // could not be started at all. Both clang and gcc read @file. + File responseFile = new File(sourceDir.getParentFile(), "c-objects.rsp"); + try { + java.nio.file.Files.write(responseFile.toPath(), + list.toString().getBytes(java.nio.charset.StandardCharsets.UTF_8)); + } catch (IOException err) { + throw new BuildExecutionException("Could not write " + responseFile + ": " + + err.getMessage(), err); + } + command.add("@" + responseFile.getAbsolutePath()); + command.addAll(Arrays.asList("-lm", "-lpthread", "-lssl", "-lcrypto", "-lnghttp2")); + if (System.getProperty("os.name", "").startsWith("Linux")) { + // dlopen, for the libcurl the define above loads on demand. command.add("-ldl"); } else { command.add("-lcurl"); @@ -1216,7 +1258,7 @@ private void link(File translated, File binary) command.add(deadStripFlag(System.getProperty("os.name", ""))); command.add("-o"); command.add(binary.getAbsolutePath()); - run(command, host.baseDir(), "compile the generated C"); + run(command, host.baseDir(), "link the generated C"); } /** @@ -1758,6 +1800,57 @@ protected void collectJava(File dir, List out) { } } + /// Compiles every source to an object in `objects` with `flags`, one + /// compiler per core, and answers the objects in source order. The first + /// failure is reported with the compiler's output, as a single compile was. + private List compileObjects(final List flags, List sources, File objects) + throws BuildExecutionException, BuildFailureException { + List out = new ArrayList(); + List> pending = new ArrayList>(); + java.util.concurrent.ExecutorService pool = java.util.concurrent.Executors.newFixedThreadPool( + Math.max(1, Runtime.getRuntime().availableProcessors())); + try { + int index = 0; + for (final File source : sources) { + // Numbered: two sources may share a name once the suffix is dropped. + final File object = new File(objects, (index++) + "-" + source.getName() + ".o"); + out.add(object); + pending.add(pool.submit(new java.util.concurrent.Callable() { + @Override + public Void call() throws Exception { + List cmd = new ArrayList(flags); + cmd.add("-c"); + cmd.add(source.getAbsolutePath()); + cmd.add("-o"); + cmd.add(object.getAbsolutePath()); + run(cmd, host.baseDir(), "compile the generated C (" + source.getName() + ")"); + return null; + } + })); + } + for (java.util.concurrent.Future f : pending) { + try { + f.get(); + } catch (java.util.concurrent.ExecutionException err) { + Throwable cause = err.getCause(); + if (cause instanceof BuildFailureException) { + throw (BuildFailureException) cause; + } + if (cause instanceof BuildExecutionException) { + throw (BuildExecutionException) cause; + } + throw new BuildExecutionException("Could not compile the generated C", cause); + } + } + } catch (InterruptedException err) { + Thread.currentThread().interrupt(); + throw new BuildExecutionException("Interrupted while compiling the generated C", err); + } finally { + pool.shutdownNow(); + } + return out; + } + protected void run(List command, File directory, String what) throws BuildExecutionException, BuildFailureException { try { diff --git a/maven/build-engine/src/main/java/com/codename1/maven/PythonLineMapper.java b/maven/build-engine/src/main/java/com/codename1/maven/PythonLineMapper.java index 3fe0a75ad41..373754531db 100644 --- a/maven/build-engine/src/main/java/com/codename1/maven/PythonLineMapper.java +++ b/maven/build-engine/src/main/java/com/codename1/maven/PythonLineMapper.java @@ -142,18 +142,50 @@ String smap(String javaFile) { } } + /// The index of a line-table part, `$cn1PyLines` being 0 and + /// `$cn1PyLines$N` being N; -1 for any other field. A long table is + /// split over several constants because one holds at most 65535 bytes. + static int part(String name) { + if (!name.startsWith(FIELD)) { + return -1; + } + if (name.length() == FIELD.length()) { + return 0; + } + if (name.charAt(FIELD.length()) != '$' || name.length() == FIELD.length() + 1) { + return -1; + } + int n = 0; + for (int i = FIELD.length() + 1; i < name.length(); i++) { + char c = name.charAt(i); + if (c < '0' || c > '9' || n > 100000) { + return -1; + } + n = n * 10 + (c - '0'); + } + return n; + } + static Table read(byte[] bytes) { - final String[] value = new String[1]; + final TreeMap parts = new TreeMap(); new ClassReader(bytes).accept(new ClassVisitor(Opcodes.ASM9) { @Override public FieldVisitor visitField(int access, String name, String desc, String signature, Object v) { - if (FIELD.equals(name) && v instanceof String) { - value[0] = (String) v; + int p = part(name); + if (p >= 0 && v instanceof String) { + parts.put(p, (String) v); } return null; } }, ClassReader.SKIP_CODE); - return value[0] == null ? null : new Table(value[0]); + if (!parts.containsKey(0)) { + return null; + } + StringBuilder value = new StringBuilder(); + for (String s : parts.values()) { + value.append(s); + } + return new Table(value.toString()); } static byte[] rewrite(byte[] bytes, final Table t) { @@ -167,7 +199,7 @@ public void visitSource(String source, String debug) { @Override public FieldVisitor visitField(int access, String name, String desc, String signature, Object v) { - return FIELD.equals(name) ? null : super.visitField(access, name, desc, signature, v); + return part(name) >= 0 ? null : super.visitField(access, name, desc, signature, v); } @Override diff --git a/maven/build-engine/src/main/java/com/codename1/maven/PythonPackageResolver.java b/maven/build-engine/src/main/java/com/codename1/maven/PythonPackageResolver.java index 4f25107578f..f8d149cd9bf 100644 --- a/maven/build-engine/src/main/java/com/codename1/maven/PythonPackageResolver.java +++ b/maven/build-engine/src/main/java/com/codename1/maven/PythonPackageResolver.java @@ -108,6 +108,8 @@ public static final class Result { public final List installed = new ArrayList(); /// Requirements the runtime provides, by name. public final List provided = new ArrayList(); + /// Package-installer tooling that was required but not installed. + public final List skipped = new ArrayList(); /// The compiled modules found, by dotted name, each with the Java /// class that stands in for it. public final Map nativeModules = new TreeMap(); @@ -149,6 +151,8 @@ public Result resolve(List requirements, File commonDir) throws BuildExc Map chosen = new LinkedHashMap(); Map sources = new TreeMap(); Map> nativeByDist = new LinkedHashMap>(); + Map data = new TreeMap(); + List distributions = new ArrayList(); Deque queue = new ArrayDeque(); for (String line : requirements) { PythonRequirement r = PythonRequirement.parse(line); @@ -165,6 +169,14 @@ public Result resolve(List requirements, File commonDir) throws BuildExc } continue; } + if (installerTooling(r.name)) { + if (!result.skipped.contains(r.name)) { + result.skipped.add(r.name); + log.info("Not installing " + r.name + ", required by " + item[1] + + ": an application cannot install packages at run time"); + } + continue; + } Pinned have = chosen.get(r.name); if (have != null) { if (!r.accepts(have.version)) { @@ -179,6 +191,8 @@ public Result resolve(List requirements, File commonDir) throws BuildExc byte[] archive = fetchVerified(p); Unpacked u = unpack(p, archive); sources.putAll(u.sources); + data.putAll(u.data); + distributions.add(distribution(p, u)); nativeByDist.put(p.name, u.nativeModules); result.installed.add(p.name + "==" + p.version); for (String dep : u.requires) { @@ -189,7 +203,8 @@ public Result resolve(List requirements, File commonDir) throws BuildExc } } try { - writeTree(target, sources); + sources.put(DISTRIBUTIONS_MODULE + ".py", distributionsModule(distributions)); + writeTree(target, sources, data); writeLock(new File(target, LOCK), chosen.values()); PythonExtensionStubs stubs = new PythonExtensionStubs(sources); for (Map.Entry> e : nativeByDist.entrySet()) { @@ -212,6 +227,16 @@ public Result resolve(List requirements, File commonDir) throws BuildExc return result; } + /// Whether `name` is the packaging toolchain -- pip, setuptools, wheel. + /// A tool such as llm requires them for its "install a plugin" command, + /// which shells out to pip; an application's packages are fixed when it + /// is built, so nothing can call them, and translating them would add + /// about ten megabytes of source to every build. + static boolean installerTooling(String name) { + String n = PythonRequirement.normalize(name); + return "pip".equals(n) || "setuptools".equals(n) || "wheel".equals(n); + } + /// Whether the runtime provides the distribution `name`: its import /// name is a standard or mapped module. static boolean providedByRuntime(String name) { @@ -230,6 +255,9 @@ static boolean providedByRuntime(String name) { case "attrs": module = "attr"; break; + case "beautifulsoup4": + module = "bs4"; + break; case "typing-extensions": module = "typing_extensions"; break; @@ -356,6 +384,11 @@ static final class Unpacked { final Map sources = new TreeMap(); final List nativeModules = new ArrayList(); final List requires = new ArrayList(); + /// Package data: every other file the package installs beside its + /// modules, by path relative to site-packages. + final Map data = new TreeMap(); + /// The wheel's `entry_points.txt`, or empty. + String entryPoints = ""; } static Unpacked unpack(Pinned p, byte[] archive) throws BuildException { @@ -375,6 +408,8 @@ private static Unpacked fromWheel(Map entries) { if (top.endsWith(".dist-info")) { if (path.endsWith("/METADATA")) { requiresDist(new String(e.getValue(), StandardCharsets.UTF_8), u.requires); + } else if (path.endsWith("/entry_points.txt")) { + u.entryPoints = new String(e.getValue(), StandardCharsets.UTF_8); } continue; } @@ -447,9 +482,30 @@ private static void take(String path, byte[] data, Unpacked u) { if (!u.nativeModules.contains(dotted)) { u.nativeModules.add(dotted); } + return; + } + if (isPackageData(path, name)) { + u.data.put(path, data); } } + /// Whether a non-module file of a package ships with the application as + /// package data (`PyPackageData`): anything a library may open beside + /// its modules, but not type stubs, C sources or packaging markers. + static boolean isPackageData(String path, String name) { + if (!path.contains("/") || name.startsWith(".") || path.contains("/__pycache__/")) { + return false; + } + String[] skip = {".pyi", ".pyc", ".pyo", ".c", ".h", ".cpp", ".pxd", ".pyx", ".so", ".pyd", ".dll", + ".dylib", ".lib", ".a", ".o"}; + for (String suffix : skip) { + if (name.endsWith(suffix)) { + return false; + } + } + return !"py.typed".equals(name); + } + private static void requiresDist(String metadata, List into) { for (String line : metadata.split("\n")) { if (line.isEmpty() || line.equals("\r")) { @@ -550,8 +606,22 @@ private static byte[] readAll(InputStream in) throws IOException { return out.toByteArray(); } - /// Makes `target` hold exactly `sources`, keeping the lock and index. - private static void writeTree(File target, Map sources) throws IOException { + /// Makes `target` hold exactly `sources` and the package `data`, + /// keeping the lock and index. The data files written are listed in + /// [#DATA_MANIFEST], so the next install removes the ones it no longer + /// has. + private static void writeTree(File target, Map sources, Map data) + throws IOException { + File manifest = new File(target, DATA_MANIFEST); + if (manifest.isFile()) { + for (String line : new String(Files.readAllBytes(manifest.toPath()), StandardCharsets.UTF_8) + .split("\n")) { + File old = new File(target, line.trim()); + if (line.trim().length() > 0 && old.isFile() && !data.containsKey(line.trim())) { + Files.delete(old.toPath()); + } + } + } if (target.isDirectory()) { deletePy(target); } @@ -560,6 +630,72 @@ private static void writeTree(File target, Map sources) throws I Files.createDirectories(f.getParentFile().toPath()); Files.write(f.toPath(), e.getValue().getBytes(StandardCharsets.UTF_8)); } + StringBuilder list = new StringBuilder(); + for (Map.Entry e : data.entrySet()) { + File f = new File(target, e.getKey()); + Files.createDirectories(f.getParentFile().toPath()); + Files.write(f.toPath(), e.getValue()); + list.append(e.getKey()).append('\n'); + } + Files.createDirectories(target.toPath()); + Files.write(manifest.toPath(), list.toString().getBytes(StandardCharsets.UTF_8)); + } + + /// The module `importlib.metadata` reads the installed distributions + /// from: a translated program has no site-packages to scan. + public static final String DISTRIBUTIONS_MODULE = "_cn1_distributions"; + /// The list of package data files the last install wrote. + public static final String DATA_MANIFEST = "cn1-package-data.txt"; + + private static String[] distribution(Pinned p, Unpacked u) { + java.util.Set top = new java.util.TreeSet(); + for (String path : u.sources.keySet()) { + int slash = path.indexOf('/'); + top.add(slash < 0 ? path.substring(0, path.length() - 3) : path.substring(0, slash)); + } + StringBuilder requires = new StringBuilder(); + for (String r : u.requires) { + requires.append(pyString(r)).append(", "); + } + StringBuilder tops = new StringBuilder(); + for (String t : top) { + tops.append(pyString(t)).append(", "); + } + return new String[] {p.name, p.version, requires.toString(), u.entryPoints, tops.toString()}; + } + + static String distributionsModule(List distributions) { + StringBuilder b = new StringBuilder(); + b.append("\"\"\"The installed distributions, written by cn1:import-python-project for") + .append(" importlib.metadata.\"\"\"\n"); + b.append("DISTRIBUTIONS = {\n"); + for (String[] d : distributions) { + b.append(" ").append(pyString(d[0])).append(": {\"version\": ").append(pyString(d[1])) + .append(", \"requires\": [").append(d[2]).append("], \"entry_points\": ") + .append(pyString(d[3])).append(", \"top_level\": [").append(d[4]).append("]},\n"); + } + b.append("}\n"); + return b.toString(); + } + + /// A Python string literal for `s`, ASCII only. + static String pyString(String s) { + StringBuilder b = new StringBuilder("\""); + for (int i = 0; i < s.length(); i++) { + char c = s.charAt(i); + if (c == '\\' || c == '"') { + b.append('\\').append(c); + } else if (c == '\n') { + b.append("\\n"); + } else if (c == '\r') { + b.append("\\r"); + } else if (c < 0x20 || c > 0x7e) { + b.append(String.format("\\u%04x", (int) c)); + } else { + b.append(c); + } + } + return b.append('"').toString(); } private static void deletePy(File dir) throws IOException { diff --git a/maven/build-engine/src/main/java/com/codename1/maven/PythonProjectBuilder.java b/maven/build-engine/src/main/java/com/codename1/maven/PythonProjectBuilder.java index d6414037660..0653a14c746 100644 --- a/maven/build-engine/src/main/java/com/codename1/maven/PythonProjectBuilder.java +++ b/maven/build-engine/src/main/java/com/codename1/maven/PythonProjectBuilder.java @@ -87,6 +87,21 @@ public PythonProjectBuilder virtualThreadStack(String size) { return this; } + private File packageDataDir; + + /// Where to write `cn1python.dat`, the package data the Python modules + /// read beside their `__file__` (`PyPackageData`): a directory whose + /// contents ship at the root of the application, the build's classes + /// directory. Null writes none. + public PythonProjectBuilder packageData(File dir) { + this.packageDataDir = dir; + return this; + } + + /// The name of the package data resource. Must match + /// `PyPackageData.RESOURCE`. + public static final String PACKAGE_DATA = "cn1python.dat"; + /// The jars and class directories `from java. import ` /// resolves against: the project's compile class path, whose /// `java-runtime` supplies the device's `java.*`. The project's own @@ -192,14 +207,29 @@ public boolean run() throws BuildException { } Map sources = new TreeMap(); Map nativeModules = new TreeMap(); + // The PyPI packages' paths. + java.util.Set libraries = new java.util.TreeSet(); try { collect(sourceDir, "", sources); + // What to keep, leave out or replace with Java, read by the + // transpiler with the modules. + File directives = new File(sourceDir, DIRECTIVES); + if (directives.isFile()) { + sources.put(DIRECTIVES, new String(Files.readAllBytes(directives.toPath()), + StandardCharsets.UTF_8)); + } // PyPI packages import resolved beside the project; the // project's own file wins where both have one. File packages = new File(sourceDir.getParentFile(), PythonPackageResolver.PACKAGES_DIR); if (packages.isDirectory()) { Map vendored = new TreeMap(); collect(packages, "", vendored); + for (String k : vendored.keySet()) { + if (k.endsWith(".py")) { + libraries.add(k); + } + } + libraries.removeAll(sources.keySet()); vendored.putAll(sources); sources = vendored; nativeModules = PythonExtensionStubs.readIndex(new File(packages, PythonExtensionStubs.INDEX)); @@ -223,13 +253,19 @@ public boolean run() throws BuildException { } Map out; try { + List deferred = new ArrayList(); out = PythonTranspiler.transpile(sources, entry, withProjectClasses(sources), nativeModules, - stackBytes()); + stackBytes(), libraries, deferred); + for (String d : deferred) { + log.info("Python: " + d); + } + installShims(out); } catch (PythonSyntaxError e) { throw new BuildException("src/main/python/" + e.file + ":" + e.line + ":" + e.col + ": " + e.reason, e); } catch (IllegalArgumentException e) { throw new BuildException(e.getMessage(), e); } + writePackageData(); int written = sync(out); if (written == 0) { log.info("Python sources are up to date"); @@ -240,6 +276,57 @@ public boolean run() throws BuildException { return true; } + /// The file of build directives, in the Python source root. + static final String DIRECTIVES = "cn1-python.properties"; + + private static final String SHIM_DIR = "com/codename1/python/ext/"; + + /// Moves the Java a `replace=` directive asks for out of the generated + /// sources and into the project's own, where the developer fills it in. + /// A class the project already has is left exactly as it is: a function + /// it does not yet answer for says so, by name, when it is called. + private void installShims(Map out) throws BuildException { + List shims = new ArrayList(); + for (String k : out.keySet()) { + if (k.startsWith(SHIM_DIR) && k.endsWith("Shims.java")) { + shims.add(k); + } + } + for (String k : shims) { + String text = out.remove(k); + if (javaSourceDir == null) { + throw new BuildException(DIRECTIVES + " has a replace= line, and this build has no Java" + + " source directory to write " + k + " into"); + } + File f = new File(javaSourceDir, k.replace('/', File.separatorChar)); + if (f.isFile()) { + continue; + } + try { + File dir = f.getParentFile(); + if (dir != null) { + Files.createDirectories(dir.toPath()); + } + Files.write(f.toPath(), text.getBytes(StandardCharsets.US_ASCII)); + } catch (IOException e) { + throw new BuildException("Could not write " + f + ": " + e.getMessage(), e); + } + log.warn("Wrote " + f + ": the Java that replaces Python named by replace= in " + DIRECTIVES + + ". Fill it in; until then those functions raise when they are called."); + } + } + + /// Must match `Jinja2Lowering.isTemplateFile` in the transpiler. + private static boolean isTemplateFile(String name) { + String[] kinds = {".html", ".htm", ".j2", ".jinja", ".jinja2", ".tmpl", ".tpl", ".xml", ".txt", ".md"}; + for (String k : kinds) { + if (name.endsWith(k)) { + return true; + } + } + return false; + } + private static void collect(File dir, String prefix, Map into) throws IOException { File[] children = dir.listFiles(); if (children == null) { @@ -252,6 +339,9 @@ private static void collect(File dir, String prefix, Map into) t collect(c, prefix + c.getName() + "/", into); } } else if (c.getName().endsWith(".py")) { + into.put(prefix + c.getName(), new String(Files.readAllBytes(c.toPath()), StandardCharsets.UTF_8)); } else if (isTemplateFile(c.getName())) { + // A template jinja2's loaders read: the transpiler lexes it at + // build time; it also ships as package data. into.put(prefix + c.getName(), new String(Files.readAllBytes(c.toPath()), StandardCharsets.UTF_8)); } } @@ -259,6 +349,64 @@ private static void collect(File dir, String prefix, Map into) t /// Makes the output directory hold exactly `files`, writing only those /// whose text changed. Returns how many were written or removed. + /// Packs the non-module files of `python-packages` and of the project's + /// own sources, the project's winning where both have one, into + /// [#PACKAGE_DATA]; removes it when there are none. + private void writePackageData() throws BuildException { + if (packageDataDir == null) { + return; + } + Map data = new TreeMap(); + File packages = new File(sourceDir.getParentFile(), PythonPackageResolver.PACKAGES_DIR); + if (packages.isDirectory()) { + collectData(packages, "", data, true); + } + collectData(sourceDir, "", data, false); + File target = new File(packageDataDir, PACKAGE_DATA); + try { + if (data.isEmpty()) { + Files.deleteIfExists(target.toPath()); + return; + } + java.io.ByteArrayOutputStream bytes = new java.io.ByteArrayOutputStream(); + java.io.DataOutputStream out = new java.io.DataOutputStream(bytes); + out.writeInt(data.size()); + for (Map.Entry e : data.entrySet()) { + byte[] b = Files.readAllBytes(e.getValue().toPath()); + out.writeUTF(e.getKey()); + out.writeInt(b.length); + out.write(b); + } + out.flush(); + byte[] packed = bytes.toByteArray(); + if (target.isFile() && Arrays.equals(Files.readAllBytes(target.toPath()), packed)) { + return; + } + Files.createDirectories(packageDataDir.toPath()); + Files.write(target.toPath(), packed); + log.info("Packed " + data.size() + " Python package data file(s) into " + target); + } catch (IOException e) { + throw new BuildException("Could not write " + target + ": " + e.getMessage(), e); + } + } + + private static void collectData(File dir, String prefix, Map into, boolean packages) { + File[] children = dir.listFiles(); + if (children == null) { + return; + } + for (File c : children) { + String rel = prefix + c.getName(); + if (c.isDirectory()) { + if (!c.getName().startsWith(".") && !"__pycache__".equals(c.getName())) { + collectData(c, rel + "/", into, packages); + } + } else if (!c.getName().endsWith(".py") && PythonPackageResolver.isPackageData(rel, c.getName())) { + into.put(rel, c); + } + } + } + private int sync(Map files) throws BuildException { int changed = 0; try { diff --git a/maven/build-engine/src/main/java/com/codename1/maven/PythonProjectImporter.java b/maven/build-engine/src/main/java/com/codename1/maven/PythonProjectImporter.java index f657c0c0602..e30a8cbaa8c 100644 --- a/maven/build-engine/src/main/java/com/codename1/maven/PythonProjectImporter.java +++ b/maven/build-engine/src/main/java/com/codename1/maven/PythonProjectImporter.java @@ -113,8 +113,13 @@ public Result importProject(File source, File commonDir, String mainPackage, Str String txt = read(new File(source, "requirements.txt")); r.requirements.addAll(requirements(pyproject, txt)); r.requirementSpecs.addAll(requirementSpecs(pyproject, txt)); - if (r.mainModule != null) { - updateSetting(new File(commonDir, "codenameone_settings.properties"), r.mainModule); + File settings = new File(commonDir, "codenameone_settings.properties"); + // Only an application has the settings file. A command-line project + // (backend-only) runs main.py as __main__ and has no setting to + // record; writing the file there would make the plugin take the + // project for an application. + if (r.mainModule != null && settings.exists()) { + updateSetting(settings, r.mainModule); if (mainPackage != null && mainClass != null && mainPackage.length() > 0 && mainClass.length() > 0) { writeEntryPoint(new File(commonDir, "src/main/java"), mainPackage, mainClass); } @@ -282,7 +287,12 @@ private void copy(File src, File dest, String path, Set imported, Result if (SKIPPED.contains(n) || n.endsWith(".egg-info") || n.endsWith(".dist-info")) { continue; } - if (f.isDirectory() || n.endsWith(".py")) { + // The build directives travel with the sources: without them the + // build stops on exactly the functions they name (an exec() in a + // command line module the application never calls), and the + // error tells the developer to write the file the import dropped. + if (f.isDirectory() || n.endsWith(".py") + || (path.length() == 0 && n.equals(PythonProjectBuilder.DIRECTIVES))) { copy(f, new File(dest, n), path.length() == 0 ? n : path + "/" + n, imported, r); } } diff --git a/maven/build-engine/src/main/java/com/codename1/maven/processors/CommandAnnotationProcessor.java b/maven/build-engine/src/main/java/com/codename1/maven/processors/CommandAnnotationProcessor.java index 25fffc5d063..5382031bc15 100644 --- a/maven/build-engine/src/main/java/com/codename1/maven/processors/CommandAnnotationProcessor.java +++ b/maven/build-engine/src/main/java/com/codename1/maven/processors/CommandAnnotationProcessor.java @@ -1174,6 +1174,7 @@ static String generatePythonApplication(String appName) { sb.append(" /** The application's name, sys.argv[0] for the program. */\n"); sb.append(" public static final String NAME = ").append(quote(appName)).append(";\n\n"); sb.append(" public static void main(String[] args) {\n"); + sb.append(" com.codename1.backend.Backend.prepareRuntime();\n"); sb.append(" com.codename1.python.runtime.Py.setArgv(NAME, args);\n"); sb.append(" int code = PythonModules.runMain();\n"); sb.append(" System.out.flush();\n"); @@ -1188,7 +1189,21 @@ static String generatePythonApplication(String appName) { /// classpath, or, in the native packager, compiled into the very tree being /// translated. An application has neither, and runs its Python from its /// Lifecycle instead. - private static boolean isBackendModule(ProcessorContext ctx) { + /// Set by the native packager, whose class path leaves the backend runtime + /// out (BackendPackager.compileClasspathWithoutRuntime) and so cannot answer + /// isBackendModule: read from that class path, a Python command-line tool + /// got no entry point and every native build of one failed with "No entry + /// point". The same reason OrmAnnotationProcessor.setBackendFlavour exists. + private boolean backendModule; + + public void setBackendModule(boolean backendModule) { + this.backendModule = backendModule; + } + + private boolean isBackendModule(ProcessorContext ctx) { + if (backendModule) { + return true; + } String entry = "com/codename1/cli/CommandLine.class"; return new File(ctx.getOutputClassDir(), entry.replace('/', File.separatorChar)).isFile() || onCompileClasspath(ctx, entry); diff --git a/maven/build-engine/src/test/java/com/codename1/maven/PythonLineMapperTest.java b/maven/build-engine/src/test/java/com/codename1/maven/PythonLineMapperTest.java index 942dce5dbb0..d566231aa21 100644 --- a/maven/build-engine/src/test/java/com/codename1/maven/PythonLineMapperTest.java +++ b/maven/build-engine/src/test/java/com/codename1/maven/PythonLineMapperTest.java @@ -94,6 +94,25 @@ public void rewritesLinesSourceAndDropsTheTable() throws Exception { assertEquals(0, PythonLineMapper.apply(classes)); } + @Test + public void joinsATableSplitOverSeveralConstants() throws Exception { + // A table past one constant's 65535 bytes is split, even inside a + // pair; the parts are joined by index, not by declaration order. + String split = SOURCE.replace("private static final String $cn1PyLines = \"app/util.py\\n5:3,7:4,9:9\";", + "private static final String $cn1PyLines$2 = \":9\"; private static final String $cn1PyLines = " + + "\"app/util.py\\n5:3,7\"; private static final String $cn1PyLines$1 = \":4,9\";"); + assertTrue(split.contains("$cn1PyLines$2")); + File classes = tmp.newFolder("classes"); + CompatFixtures.compile(tmp.newFolder(), classes, "com/codename1/generated/python/py_app$2eutil.java", split); + assertEquals(2, PythonLineMapper.apply(classes)); + Seen outer = scan(new File(classes, PythonLineMapper.PACKAGE_DIR + "/py_app$2eutil.class")); + assertEquals("util.py", outer.source); + assertFalse("every part is removed", outer.hasTable); + assertEquals("[3, 4, 9]", new java.util.TreeSet(outer.lines).toString()); + assertEquals(-1, PythonLineMapper.part("$cn1PyLinesX")); + assertEquals(-1, PythonLineMapper.part("$cn1PyLines$")); + } + @Test public void otherClassesAreLeftAlone() throws Exception { File classes = tmp.newFolder("classes"); @@ -124,7 +143,7 @@ public void visitSource(String source, String debug) { @Override public FieldVisitor visitField(int access, String name, String desc, String sig, Object v) { - s.hasTable |= PythonLineMapper.FIELD.equals(name); + s.hasTable |= PythonLineMapper.part(name) >= 0; return null; } diff --git a/maven/build-engine/src/test/java/com/codename1/maven/PythonProjectTest.java b/maven/build-engine/src/test/java/com/codename1/maven/PythonProjectTest.java index b7e1de54cdc..11012044e9a 100644 --- a/maven/build-engine/src/test/java/com/codename1/maven/PythonProjectTest.java +++ b/maven/build-engine/src/test/java/com/codename1/maven/PythonProjectTest.java @@ -103,6 +103,20 @@ public void reimportRemovesWhatTheProjectNoLongerHas() throws Exception { new File(common, "src/main/java").exists()); } + @Test + public void theBuildDirectivesComeWithTheSources() throws Exception { + write(new File(project, "src/cn1-python.properties"), "remove=textstats.cli.main\n"); + write(new File(project, "src/textstats/cn1-python.properties"), "not at the root\n"); + importer().importProject(project, common, null, null); + assertEquals("remove=textstats.cli.main\n", read(new File(python, "cn1-python.properties"))); + assertFalse("only the root's directives are the build's", + new File(python, "textstats/cn1-python.properties").exists()); + assertTrue(new File(project, "src/cn1-python.properties").delete()); + importer().importProject(project, common, null, null); + assertFalse("a re-import removes directives the project no longer has", + new File(python, "cn1-python.properties").exists()); + } + @Test public void flatProjectsFindTheirEntryModule() throws Exception { File flat = tmp.newFolder("flat"); @@ -220,6 +234,35 @@ public void unsupportedCodeNamesTheFileAndLine() throws Exception { } } + /// `replace=` in `cn1-python.properties`: the Java to fill in goes into + /// the project's own sources, once, and never into the generated ones, + /// where a second copy of the class would not compile. + @Test + public void replacedFunctionsGetAJavaClassTheProjectOwns() throws Exception { + File src = tmp.newFolder("py"); + write(new File(src, "main.py"), "import tools\nprint(tools.run('1'))\n"); + write(new File(src, "tools.py"), "def run(text):\n return eval(text)\n"); + File out = tmp.newFolder("gen"); + File java = tmp.newFolder("java"); + try { + builder(src, out, null).javaSources(java, new File(tmp.getRoot(), "scratch1")).run(); + fail(); + } catch (BuildException expected) { + assertTrue(expected.getMessage(), expected.getMessage().contains("remove=tools.run")); + } + write(new File(src, PythonProjectBuilder.DIRECTIVES), "replace=tools.run\n"); + assertTrue(builder(src, out, null).javaSources(java, new File(tmp.getRoot(), "scratch2")).run()); + File shim = new File(java, "com/codename1/python/ext/ToolsShims.java"); + assertTrue(read(shim), read(shim).contains("NativeModule.replace(\"tools.run\"")); + assertFalse(new File(out, "com/codename1/python/ext/ToolsShims.java").exists()); + assertTrue(read(new File(out, "com/codename1/generated/python/PythonModules.java")) + .contains("com.codename1.python.ext.ToolsShims.install()")); + write(shim, read(shim).replace("throw NativeModule.notReplaced(\"tools.run\");", "return args[0];")); + String mine = read(shim); + assertTrue(builder(src, out, null).javaSources(java, new File(tmp.getRoot(), "scratch3")).run()); + assertEquals(mine, read(shim)); + } + private static File javaFor(File out, String module) { return new File(out, "com/codename1/generated/python/" + com.codename1.python.transpiler.api.PythonTranspiler.className(module) + ".java"); diff --git a/maven/codenameone-gradle-plugin/src/main/java/com/codename1/gradle/AppSupport.java b/maven/codenameone-gradle-plugin/src/main/java/com/codename1/gradle/AppSupport.java index b5af9ad1cf4..1887b1985a9 100644 --- a/maven/codenameone-gradle-plugin/src/main/java/com/codename1/gradle/AppSupport.java +++ b/maven/codenameone-gradle-plugin/src/main/java/com/codename1/gradle/AppSupport.java @@ -1283,7 +1283,10 @@ static void registerPython(Project project, ProjectLayout layout, CodenameOneExt common(t, project, layout, ext, userProperties); t.setDescription("Transpiles the Python sources in src/main/python to Java"); t.getPythonDirectory().set(pythonDir); - t.getSources().from(project.fileTree(pythonDir, f -> f.include("**/*.py"))); + // Every file: a data file beside a module ships in cn1python.dat. + t.getSources().from(project.fileTree(pythonDir)); + t.getSources().from(project.fileTree(new File(pythonDir.getParentFile(), + com.codename1.maven.PythonPackageResolver.PACKAGES_DIR))); if (pythonMain != null) { t.getMainModule().set(pythonMain); } @@ -1296,8 +1299,10 @@ static void registerPython(Project project, ProjectLayout layout, CodenameOneExt t.getJavaSourceDirectory().set(javaDir); t.getJavaSources().from(project.fileTree(javaDir, f -> f.include("**/*.java"))); t.getJavaImportsDirectory().set(new File(layout.buildDir(), "cn1-python-java-imports")); + t.getPackageDataDirectory().set(new File(layout.buildDir(), "cn1-python-resources")); }); main.getJava().srcDir(python.flatMap(com.codename1.gradle.tasks.TranspilePythonTask::getOutputDirectory)); + main.getResources().srcDir(python.flatMap(com.codename1.gradle.tasks.TranspilePythonTask::getPackageDataDirectory)); } /// The javac annotation processor that writes the source a project compiles diff --git a/maven/codenameone-gradle-plugin/src/main/java/com/codename1/gradle/tasks/TranspilePythonTask.java b/maven/codenameone-gradle-plugin/src/main/java/com/codename1/gradle/tasks/TranspilePythonTask.java index 714bb64b29a..086d5d3d517 100644 --- a/maven/codenameone-gradle-plugin/src/main/java/com/codename1/gradle/tasks/TranspilePythonTask.java +++ b/maven/codenameone-gradle-plugin/src/main/java/com/codename1/gradle/tasks/TranspilePythonTask.java @@ -87,6 +87,12 @@ public abstract class TranspilePythonTask extends Cn1Task { @OutputDirectory public abstract DirectoryProperty getOutputDirectory(); + /// Where `cn1python.dat` (the Python package data) is written: a + /// directory packaged at the root of the application's resources. + @org.gradle.api.tasks.Optional + @OutputDirectory + public abstract DirectoryProperty getPackageDataDirectory(); + @TaskAction public void transpile() { try { @@ -95,7 +101,8 @@ public void transpile() { .classPath(new java.util.ArrayList(getJavaClassPath().getFiles())) .javaSources(getJavaSourceDirectory().get().getAsFile(), getJavaImportsDirectory().get().getAsFile()) - .virtualThreadStack(getVirtualThreadStack().getOrNull()).run(); + .virtualThreadStack(getVirtualThreadStack().getOrNull()) + .packageData(getPackageDataDirectory().getAsFile().getOrNull()).run(); } catch (BuildException ex) { throw new GradleException(ex.getMessage(), ex.getCause() == null ? ex : ex.getCause()); } diff --git a/maven/codenameone-maven-plugin/src/main/java/com/codename1/maven/BackendPackageMojo.java b/maven/codenameone-maven-plugin/src/main/java/com/codename1/maven/BackendPackageMojo.java index 2cb5541b7bb..83919964d85 100644 --- a/maven/codenameone-maven-plugin/src/main/java/com/codename1/maven/BackendPackageMojo.java +++ b/maven/codenameone-maven-plugin/src/main/java/com/codename1/maven/BackendPackageMojo.java @@ -84,6 +84,13 @@ public class BackendPackageMojo extends AbstractMojo { @Parameter(defaultValue = "${project}", readonly = true, required = true) private MavenProject project; + /// The project as the forked compile left it. A source root a goal in the + /// fork adds -- the Python transpiler's generated sources -- is recorded on + /// this copy only, so the packager reads it: from [#project] a Python + /// command-line tool's program never reached the native build. + @Parameter(defaultValue = "${executedProject}", readonly = true) + private MavenProject executedProject; + @Parameter(defaultValue = "${reactorProjects}", readonly = true) private java.util.List reactorProjects; @@ -227,7 +234,8 @@ private void webAppBesideTheBinary() throws BuildExecutionException { /** The engine packager, answering from this mojo's project and parameters. */ private BackendPackager packager() throws MojoExecutionException { - BackendPackager p = new BackendPackager(new MavenModuleHost(project, MavenLog.of(getLog()))) { + BackendPackager p = new BackendPackager(new MavenModuleHost( + executedProject != null ? executedProject : project, MavenLog.of(getLog()))) { @Override protected String binaryName() { return project.getArtifactId(); diff --git a/maven/codenameone-maven-plugin/src/main/java/com/codename1/maven/ImportPythonProjectMojo.java b/maven/codenameone-maven-plugin/src/main/java/com/codename1/maven/ImportPythonProjectMojo.java index 9018313a1c5..2df2a6d5238 100644 --- a/maven/codenameone-maven-plugin/src/main/java/com/codename1/maven/ImportPythonProjectMojo.java +++ b/maven/codenameone-maven-plugin/src/main/java/com/codename1/maven/ImportPythonProjectMojo.java @@ -69,14 +69,23 @@ protected void executeImpl() throws MojoExecutionException, MojoFailureException throw new MojoFailureException("Name the Python project to import: -Dsource=/path/to/my-python-app"); } File common = getCN1ProjectDir(); + // A command-line tool is a backend-only project with the Python at its + // root's src/main/python; its pom carries the python profile already. + boolean tool = common == null && project != null + && UpdateCodenameOneMojo.isBackendOnlyRoot(project.getBasedir()); + if (tool) { + common = project.getBasedir(); + } if (common == null) { - throw new MojoExecutionException("Run this from a Codename One application project"); + throw new MojoExecutionException("Run this from a Codename One application or command-line project"); } if (!PythonProjectBuilder.isPythonProject(PythonProjectImporter.sourceRoot(from))) { // Before the pom is touched: a mistyped path must change nothing. throw new MojoFailureException(from + " has no Python sources"); } - wirePython(common); + if (!tool) { + wirePython(common); + } String pkg = properties == null ? null : properties.getProperty("codename1.packageName"); String main = properties == null ? null : properties.getProperty("codename1.mainName"); PythonProjectImporter.Result r; @@ -89,6 +98,11 @@ protected void executeImpl() throws MojoExecutionException, MojoFailureException + (r.removedFiles == 0 ? "" : "; removed " + r.removedFiles + " the project no longer has")); getLog().info(r.mainModule == null ? "No entry module was found: the sources are imported as a library" : "Entry module: " + r.mainModule); + if (tool && !"main".equals(r.mainModule)) { + throw new MojoFailureException("A command-line tool runs main.py as __main__, and " + from + + " has " + (r.mainModule == null ? "no entry module" : "the entry module " + r.mainModule) + + ": add a main.py that runs it"); + } if (r.requirementSpecs.isEmpty()) { return; } diff --git a/maven/codenameone-maven-plugin/src/main/java/com/codename1/maven/TranspilePythonMojo.java b/maven/codenameone-maven-plugin/src/main/java/com/codename1/maven/TranspilePythonMojo.java index 2b45c77e54f..ffab3808423 100644 --- a/maven/codenameone-maven-plugin/src/main/java/com/codename1/maven/TranspilePythonMojo.java +++ b/maven/codenameone-maven-plugin/src/main/java/com/codename1/maven/TranspilePythonMojo.java @@ -70,6 +70,7 @@ protected void executeImpl() throws MojoExecutionException, MojoFailureException } PythonProjectBuilder builder = new PythonProjectBuilder(pythonSourceDir, pythonOutputDir, entry, MavenLog.of(getLog())).classPath(compileClassPath()) + .packageData(new File(project.getBuild().getOutputDirectory())) .javaSources(new File(project.getBuild().getSourceDirectory()), new File(project.getBuild().getDirectory(), "python-java-imports")) .virtualThreadStack(properties == null ? null diff --git a/maven/core-unittests/spotbugs-exclude.xml b/maven/core-unittests/spotbugs-exclude.xml index 5764dc82656..549337e557b 100644 --- a/maven/core-unittests/spotbugs-exclude.xml +++ b/maven/core-unittests/spotbugs-exclude.xml @@ -488,4 +488,22 @@ + + + + + + + + + + + + + + + diff --git a/maven/python-runtime/spotbugs-exclude.xml b/maven/python-runtime/spotbugs-exclude.xml index fb9b2efec44..5852a1d0484 100644 --- a/maven/python-runtime/spotbugs-exclude.xml +++ b/maven/python-runtime/spotbugs-exclude.xml @@ -54,6 +54,14 @@ + + + + + + @@ -109,7 +117,56 @@ - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -117,4 +174,34 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/maven/python-runtime/src/main/java/com/codename1/python/runtime/Abc.java b/maven/python-runtime/src/main/java/com/codename1/python/runtime/Abc.java new file mode 100644 index 00000000000..1e74340cadb --- /dev/null +++ b/maven/python-runtime/src/main/java/com/codename1/python/runtime/Abc.java @@ -0,0 +1,169 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.python.runtime; + +import java.util.ArrayList; +import java.util.TreeSet; + +/// `abc.ABCMeta`, done by the runtime as CPython's `_abc` does it in C. +/// +/// The build is closed world: a class whose metaclass is a Python class +/// deriving from `type` has no layout, and the old `abc.py` metaclass also +/// read every abstract name with a computed `getattr`. Here `ABCMeta` is a +/// builtin metaclass the runtime knows by identity, so a class it governs +/// keeps a layout and the fast construction paths: [PyType#finish] computes +/// `__abstractmethods__` once, when the class is made, constructing a class +/// with any of them left raises the TypeError `ABCMeta.__call__` raised, and +/// `isinstance`/`issubclass` consult `__subclasshook__`, the registry and the +/// registries of the class's subclasses, in that order, as before. +final class Abc { + private Abc() { + } + + /// The metaclass object `abc.ABCMeta` is bound to. + static final PyType META = metaType(); + + private static PyType metaType() { + PyType t = new PyType("ABCMeta", new PyType[] {Py.TYPE_TYPE}, null); + t.dict.put("__module__", "abc"); + t.define("register", PyBuiltin.method(t, "register", a -> register(a[0], a[1]))); + // Called by name too (a Python metaclass deriving from ABCMeta and + // calling super()); the runtime itself goes to subclassCheck. + t.define("__instancecheck__", PyBuiltin.method(t, "__instancecheck__", + a -> Py.bool(subclassCheck((PyType) a[0], Py.typeOf(a[1]))))); + t.define("__subclasscheck__", PyBuiltin.method(t, "__subclasscheck__", + a -> Py.bool(a[1] instanceof PyType && subclassCheck((PyType) a[0], (PyType) a[1])))); + return t; + } + + static boolean governs(PyType k) { + // A Python metaclass deriving from ABCMeta keeps these checks unless + // it overrides them, as it would in CPython. + return k.meta != null && k.meta.isSubtype(META) && !(k.meta.lookup("__instancecheck__") instanceof PyFunction) + && !(k.meta.lookup("__subclasscheck__") instanceof PyFunction); + } + + /// `ABCMeta.register(cls, subclass)`: a virtual subclass, answered by + /// [#subclassCheck] from now on. Returns the subclass, so it decorates. + static Object register(Object cls, Object subclass) { + if (!(cls instanceof PyType) || !(subclass instanceof PyType)) { + throw Py.typeError("Can only register classes"); + } + PyType k = (PyType) cls; + PyType s = (PyType) subclass; + if (!subclassCheck(k, s)) { + if (k.abcRegistry == null) { + k.abcRegistry = new ArrayList(); + } + k.abcRegistry.add(s); + } + return subclass; + } + + /// What `ABCMeta.__new__` computed: the names bound abstract in the + /// class body, and those abstract in a base that the class still finds + /// abstract, as a frozenset in the class dict. + static void init(PyType k) { + TreeSet names = new TreeSet(); + for (java.util.Map.Entry e : k.dict.entrySet()) { + if (isAbstract(e.getValue())) { + names.add(e.getKey()); + } + } + for (PyType b : k.bases) { + Object am = b.lookup("__abstractmethods__"); + if (am instanceof PySet) { + for (Object n : ((PySet) am).toArray()) { + if (n instanceof String && isAbstract(k.lookup((String) n))) { + names.add((String) n); + } + } + } + } + Object[] items = names.toArray(); + k.dict.put("__abstractmethods__", PySet.frozenConstants(items)); + k.abstractNames = items.length == 0 ? null : names.toArray(new String[items.length]); + } + + /// The TypeError constructing a class with abstract methods raises. + static PyException instantiationError(PyType k) { + String[] n = k.abstractNames; + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < n.length; i++) { + sb.append(i == 0 ? "" : ", ").append('\'').append(n[i]).append('\''); + } + return Py.typeError("Can't instantiate abstract class " + k.name + " without an implementation for abstract method" + + (n.length > 1 ? "s " : " ") + sb); + } + + static boolean isAbstract(Object v) { + Object f = v; + if (f instanceof PyClassMethod) { + f = ((PyClassMethod) f).func; + } else if (f instanceof PyStaticMethod) { + f = ((PyStaticMethod) f).func; + } else if (f instanceof PyProperty) { + PyProperty p = (PyProperty) f; + return flagged(p.fget) || flagged(p.fset) || flagged(p.fdel); + } + return flagged(f); + } + + private static boolean flagged(Object f) { + if (f == null || f == Py.NONE) { //NOPMD CompareObjectsWithEquals - identity is meant + return false; + } + Object a = Py.obj(f).getAttrOrNull("__isabstractmethod__"); + return a != null && Py.isTrue(a); + } + + /// `ABCMeta.__subclasscheck__(cls, c)`. + static boolean subclassCheck(PyType cls, PyType c) { + if (c.isSubtype(cls)) { + return true; + } + Object hook = cls.lookup("__subclasshook__") == null ? null : cls.getAttrOrNull("__subclasshook__"); + if (hook != null) { + Object ok = Py.obj(hook).call1(c); + if (ok != Py.NOT_IMPLEMENTED) { //NOPMD CompareObjectsWithEquals - identity is meant + return Py.isTrue(ok); + } + } + if (cls.abcRegistry != null) { + for (PyType k : c.mro) { + for (PyType r : cls.abcRegistry) { + if (k == r || r.subclassCheck(k)) { //NOPMD CompareObjectsWithEquals - identity is meant + return true; + } + } + } + } + for (PyType sub : cls.subclassList()) { + if (sub.subclassCheck(c)) { + return true; + } + } + return false; + } +} diff --git a/maven/python-runtime/src/main/java/com/codename1/python/runtime/Annotations.java b/maven/python-runtime/src/main/java/com/codename1/python/runtime/Annotations.java new file mode 100644 index 00000000000..e11208be016 --- /dev/null +++ b/maven/python-runtime/src/main/java/com/codename1/python/runtime/Annotations.java @@ -0,0 +1,164 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.python.runtime; + +/// Evaluates the annotations of a function from the table the build wrote +/// for it, when something reads `__annotations__`. +/// +/// Nearly every annotation is a name, an attribute of one, a subscript or a +/// union of those. Compiled, each function carried a method that builds +/// them and a class to hold it, for a value most programs never ask for; +/// written down, it is one string constant and this loop. +public final class Annotations { + private Annotations() { + } + + /// Records the annotation of one name of a class body, `name: T`, in the + /// class's `__annotations__`. `entry` is a table of that one annotation. + public static void set(Object cls, PyModule module, String entry) { + Object[] kv = build(module, entry); + Py.setitem(Py.getattr(cls, "__annotations__"), kv[0], kv[1]); + } + + /// The annotations as `name, value` pairs, in the order written. + /// + /// The table is one instruction a line: `=name` opens an annotation, + /// `!text` is what it is when evaluating it raises (None without one), + /// and the rest is its expression in postfix order -- `g`/`b` a name + /// looked up in the module first or in the builtins first, `a` an + /// attribute, `s` a subscript, `|` a union, `t`/`l` a tuple or list of + /// the count that follows, `c` a str and `N`, `T`, `F`, `E` the + /// constants. + static Object[] build(PyModule module, String table) { + int count = 0; + for (int i = 0; i < table.length(); i++) { + if (table.charAt(i) == '=' && (i == 0 || table.charAt(i - 1) == '\n')) { + count++; + } + } + Object[] out = new Object[count * 2]; + Object[] stack = new Object[8]; + int sp = 0; + int entry = -1; + boolean failed = false; + String otherwise = null; + int at = 0; + while (at < table.length()) { + int end = table.indexOf('\n', at); + char op = table.charAt(at); + String arg = table.substring(at + 1, end); + at = end + 1; + if (op == '=') { + if (entry >= 0) { + out[entry * 2 + 1] = value(stack, sp, failed, otherwise); + } + entry++; + out[entry * 2] = arg; + sp = 0; + failed = false; + otherwise = null; + continue; + } + if (op == '!') { + otherwise = arg; + continue; + } + if (failed) { + continue; + } + if (sp == stack.length) { + Object[] wider = new Object[sp * 2]; + System.arraycopy(stack, 0, wider, 0, sp); + stack = wider; + } + try { + sp = step(module, op, arg, stack, sp); + } catch (PyException e) { + // A forward reference, a generic the runtime does not model: + // the annotation is its name, never a failed definition. + failed = true; + } + } + if (entry >= 0) { + out[entry * 2 + 1] = value(stack, sp, failed, otherwise); + } + return out; + } + + private static Object value(Object[] stack, int sp, boolean failed, String otherwise) { + if (failed || sp != 1) { + return otherwise == null ? Py.NONE : otherwise; + } + return stack[0]; + } + + private static int step(PyModule module, char op, String arg, Object[] stack, int sp) { + switch (op) { + case 'g': + case 'b': { + Object v = op == 'b' ? Builtins.lookup(arg) : module.getGlobal(arg); + if (v == null) { + v = op == 'b' ? module.getGlobal(arg) : Builtins.lookup(arg); + } + if (v == null) { + throw Py.nameError(arg); + } + stack[sp] = v; + return sp + 1; + } + case 'a': + stack[sp - 1] = Py.getattr(stack[sp - 1], arg); + return sp; + case 's': + stack[sp - 2] = Py.getitem(stack[sp - 2], stack[sp - 1]); + return sp - 1; + case '|': + stack[sp - 2] = Py.or(stack[sp - 2], stack[sp - 1]); + return sp - 1; + case 't': + case 'l': { + int n = Integer.parseInt(arg); + Object[] items = new Object[n]; + System.arraycopy(stack, sp - n, items, 0, n); + stack[sp - n] = op == 't' ? (Object) new PyTuple(items) : new PyList(items); + return sp - n + 1; + } + case 'c': + stack[sp] = arg.length() == 0 ? Py.EMPTY_STR : arg; + return sp + 1; + case 'N': + stack[sp] = Py.NONE; + return sp + 1; + case 'T': + stack[sp] = Py.TRUE; + return sp + 1; + case 'F': + stack[sp] = Py.FALSE; + return sp + 1; + default: + stack[sp] = Py.ELLIPSIS; + return sp + 1; + } + } +} diff --git a/maven/python-runtime/src/main/java/com/codename1/python/runtime/ArgArrays.java b/maven/python-runtime/src/main/java/com/codename1/python/runtime/ArgArrays.java new file mode 100644 index 00000000000..9bbced6acf2 --- /dev/null +++ b/maven/python-runtime/src/main/java/com/codename1/python/runtime/ArgArrays.java @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.python.runtime; + +/// Argument arrays lent to a callee that reads them and lets them go. +/// +/// A builtin written over an array -- `str.format`, a dataclass `__init__`, +/// a module function taking ten options -- was handed a new one on every +/// call. Here one array per length is kept, taken for the call and given +/// back once it returns: a nested call finds the slot empty and gets an array +/// of its own, and one that raises simply never gives its array back, so no +/// handler is needed. Python code here runs on one thread at a time. +/// +/// ONLY for a callee that keeps nothing of the array after it returns -- not +/// the array, and not a view over it. One that stores it (a tuple of the +/// arguments, an exception's `args`) must be handed a new array instead. +final class ArgArrays { + private static final int MAX = 16; + private static final Object[][] SPARE = new Object[MAX + 1][]; + + private ArgArrays() { + } + + /// An array of exactly `n` elements, every one null. + static Object[] take(int n) { + if (n > MAX) { + return new Object[n]; + } + Object[] a = SPARE[n]; + if (a == null) { + return new Object[n]; + } + SPARE[n] = null; + return a; + } + + /// Hands `a` back, cleared so it holds on to nothing. + static void give(Object[] a) { + int n = a.length; + if (n > MAX) { + return; + } + for (int i = 0; i < n; i++) { + a[i] = null; + } + SPARE[n] = a; + } + + /// How many calls have built an argument array because the callee had no + /// fixed-arity path for them. Read by a test that holds the common call + /// shapes at zero; the count costs one increment on a path that already + /// allocates. + static long fallbacks; + + /// Counts `a` as one [#fallbacks] and hands it back. + static Object[] fallback(Object[] a) { + fallbacks++; + return a; + } + +} diff --git a/maven/python-runtime/src/main/java/com/codename1/python/runtime/AttrSite.java b/maven/python-runtime/src/main/java/com/codename1/python/runtime/AttrSite.java index fd6747cec69..24f6b6ce3fb 100644 --- a/maven/python-runtime/src/main/java/com/codename1/python/runtime/AttrSite.java +++ b/maven/python-runtime/src/main/java/com/codename1/python/runtime/AttrSite.java @@ -45,11 +45,35 @@ public final class AttrSite { /// How many receiver layouts a site remembers. static final int WAYS = 4; + /// Overflow entries a megamorphic read site keeps past its four ways. + static final int HASHED = 256; private static final int NONE = 0; private static final int SLOT = 1; private static final int CLASS_ATTR = 2; + /// A compiled field (`PyInstance.fieldIndex`), read by index; an unset + /// one still takes the generic read, which finds the class's value. + private static final int FIELD = 3; private static final int BUILTIN = 3; + /// The instance lacks the attribute: no slot, no field, nothing in the + /// class, and no `__getattribute__` or `__getattr__` that could answer + /// it. Only [#getOrMiss] answers from it; a plain read still raises. + private static final int MISSING = 5; + /// Hit-path kinds only (gkN): a class attribute read through an instance + /// that is a plain value, returned as it is, or a property, whose getter + /// runs. Both are what getSlow's CLASS_ATTR answer would be. + private static final int CONST = 6; + private static final int PROP = 7; + /// `obj.__dict__` of an instance whose class has no `__dict__` of its + /// own and no `__getattribute__`: the instance's one live view, without + /// the generic read (class lookup, own-attribute probe, name compares) + /// it took on every access. + private static final int DICT = 8; + /// The layout [#getOrMiss] last found missing, checked before the ways: + /// a probe that misses usually misses on one class. + private PyType missType; + private Shape missShape; + private int missVersion; private final String name; /// A builtin method this site calls directly when the receiver is that @@ -66,28 +90,30 @@ public final class AttrSite { private static final int I_CLEAR = 7; private static final int I_STARTSWITH = 8; private static final int I_ENDSWITH = 9; + private static final int I_STRIP = 10; + private static final int I_LSTRIP = 11; + private static final int I_RSTRIP = 12; + private static final int I_FIND = 13; + private static final int I_RFIND = 14; + private static final int I_REPLACE = 15; + private static final int I_ADD = 16; // Reads and calls. An entry with a null shape is a non-instance receiver // type (BUILTIN or NONE). All entries are valid only while getVersion is // the current class version. private int getVersion = -1; + /// A method call on a str receiver -- `s.encode()`, `s.startswith(...)`, + /// the commonest receiver of all -- answered from one entry: the general + /// path below tested three classes, asked Py.typeOf and scanned the ways, + /// which measured as much as the encode itself. + private int strVersion = -1; + private Object strMethod; private int getUsed; - private int getNext; - private final PyType[] getTypes = new PyType[WAYS]; - private final Shape[] getShapes = new Shape[WAYS]; - private final int[] getKinds = new int[WAYS]; - private final int[] getSlots = new int[WAYS]; - private final Object[] getValues = new Object[WAYS]; - - // Stores: a slot hit when the instance already has the attribute, or a - // shape transition when the store adds it. - private int setVersion = -1; - private int setUsed; - private int setNext; - private final PyType[] setTypes = new PyType[WAYS]; - private final Shape[] setShapes = new Shape[WAYS]; - private final int[] setSlots = new int[WAYS]; - private final Shape[] setTos = new Shape[WAYS]; + private PyType[] getTypes; + private Shape[] getShapes; + private int[] getKinds; + private int[] getSlots; + private Object[] getValues; // The same entries again as plain fields, which the hit paths compare: // a field is a load, an array element a bounds-checked call in @@ -114,22 +140,21 @@ public final class AttrSite { private Object gf1; private Object gf2; private Object gf3; - private PyType st0; - private PyType st1; - private PyType st2; - private PyType st3; - private Shape ss0; - private Shape ss1; - private Shape ss2; - private Shape ss3; - private int si0; - private int si1; - private int si2; - private int si3; - private Shape sto0; - private Shape sto1; - private Shape sto2; - private Shape sto3; + private Object gv0; + private Object gv1; + private Object gv2; + private Object gv3; + + /// A site for each name of `names`, one a line: the sites of a module, + /// which generated code holds as one table. + public static AttrSite[] table(String names) { + String[] each = Py.names(names); + AttrSite[] out = new AttrSite[each.length]; + for (int i = 0; i < each.length; i++) { + out[i] = new AttrSite(each[i]); + } + return out; + } public AttrSite(String name) { this.name = name.intern(); @@ -156,6 +181,20 @@ private static int intrinsicOf(String name) { return I_STARTSWITH; case "endswith": return I_ENDSWITH; + case "strip": + return I_STRIP; + case "lstrip": + return I_LSTRIP; + case "rstrip": + return I_RSTRIP; + case "find": + return I_FIND; + case "rfind": + return I_RFIND; + case "replace": + return I_REPLACE; + case "add": + return I_ADD; default: return I_NONE; } @@ -166,8 +205,12 @@ private int findGet(PyType t, Shape shape) { if (getVersion != PyType.version) { getVersion = PyType.version; getUsed = 0; - getNext = 0; gt0 = gt1 = gt2 = gt3 = null; + gv0 = gv1 = gv2 = gv3 = null; + if (getTypes != null && getTypes.length > WAYS) { + // The overflow entries name layouts of the old version. + getTypes = null; + } return -1; } for (int k = 0; k < getUsed; k++) { @@ -175,32 +218,86 @@ private int findGet(PyType t, Shape shape) { return k; } } + if (getTypes != null && getTypes.length > WAYS) { + int k = WAYS + hash(t, shape); + if (getTypes[k] == t && getShapes[k] == shape) { //NOPMD CompareObjectsWithEquals - identity is meant + return k; + } + } return -1; } + /// [#findGet] for a caller whose four ways just missed: the overflow + /// slot is probed first, so a megamorphic site -- psparser's methods read + /// `self.x` on instances of half a dozen parser classes -- finds its + /// entry without comparing the ways a second time. An entry lives in + /// exactly one place (addGet runs only after findGet failed), so a miss + /// here still scans the ways. + private int findGetOverflowFirst(PyType t, Shape shape) { + if (getVersion == PyType.version && getTypes != null && getTypes.length > WAYS) { + int k = WAYS + hash(t, shape); + if (getTypes[k] == t && getShapes[k] == shape) { //NOPMD CompareObjectsWithEquals - identity is meant + return k; + } + } + return findGet(t, shape); + } + + /// The overflow slot of a layout. A megamorphic site -- one attribute + /// read on instances of dozens of classes, as an XML binding that defines + /// a class per tag does -- used to evict round robin past four layouts, + /// so nearly every read missed and went back to the class dictionaries. + private static int hash(PyType t, Shape shape) { + int h = t.id * 0x9E3779B1 + (shape == null ? 0 : shape.id * 0x85EBCA6B); + return h >>> (32 - 8); + } + private int addGet(PyType t, Shape shape, int kind, int slot, Object value) { int k; if (getUsed < WAYS) { k = getUsed++; } else { - k = getNext; - getNext = (getNext + 1) % WAYS; + k = WAYS + hash(t, shape); + if (getTypes.length == WAYS) { + getTypes = java.util.Arrays.copyOf(getTypes, WAYS + HASHED); + getShapes = java.util.Arrays.copyOf(getShapes, WAYS + HASHED); + getKinds = java.util.Arrays.copyOf(getKinds, WAYS + HASHED); + getSlots = java.util.Arrays.copyOf(getSlots, WAYS + HASHED); + getValues = java.util.Arrays.copyOf(getValues, WAYS + HASHED); + } + } + if (getTypes == null) { + // Made on the first entry: most sites of a large program are in + // code that never runs, and five arrays each was most of what a + // site weighed. + getTypes = new PyType[WAYS]; + getShapes = new Shape[WAYS]; + getKinds = new int[WAYS]; + getSlots = new int[WAYS]; + getValues = new Object[WAYS]; } getTypes[k] = t; getShapes[k] = shape; getKinds[k] = kind; getSlots[k] = slot; getValues[k] = value; - int fast = kind == SLOT ? SLOT : NONE; - Object f = kind == CLASS_ATTR && value instanceof PyFunction ? value : null; + int fast = kind == SLOT || kind == FIELD || kind == DICT ? kind : NONE; + if (kind == CLASS_ATTR) { + if (value instanceof PyProperty) { + fast = PROP; + } else if (!(value instanceof PyObject) && value != null) { + fast = CONST; + } + } + Object f = kind == CLASS_ATTR && takesReceiver(value) ? value : null; if (k == 0) { - gt0 = t; gs0 = shape; gk0 = fast; gi0 = slot; gf0 = f; + gt0 = t; gs0 = shape; gk0 = fast; gi0 = slot; gf0 = f; gv0 = value; } else if (k == 1) { - gt1 = t; gs1 = shape; gk1 = fast; gi1 = slot; gf1 = f; + gt1 = t; gs1 = shape; gk1 = fast; gi1 = slot; gf1 = f; gv1 = value; } else if (k == 2) { - gt2 = t; gs2 = shape; gk2 = fast; gi2 = slot; gf2 = f; - } else { - gt3 = t; gs3 = shape; gk3 = fast; gi3 = slot; gf3 = f; + gt2 = t; gs2 = shape; gk2 = fast; gi2 = slot; gf2 = f; gv2 = value; + } else if (k == 3) { + gt3 = t; gs3 = shape; gk3 = fast; gi3 = slot; gf3 = f; gv3 = value; } return k; } @@ -213,26 +310,213 @@ public Object get(Object o) { if (getVersion == PyType.version) { PyType t = i.cls; Shape s = i.shape; - if (gs0 == s && gt0 == t && gk0 == SLOT) { //NOPMD CompareObjectsWithEquals - identity is meant - return i.slots[gi0]; + if (gs0 == s && gt0 == t) { //NOPMD CompareObjectsWithEquals - identity is meant + if (gk0 == SLOT) { + return i.slots[gi0]; + } + if (gk0 == FIELD) { + Object v = i.getField(gi0); + if (v != null) { + return v; + } + } + if (gk0 == CONST) { + return gv0; + } + if (gk0 == PROP) { + return ((PyProperty) gv0).get(i); + } + if (gk0 == DICT) { + return i.dictView(); + } } - if (gs1 == s && gt1 == t && gk1 == SLOT) { //NOPMD CompareObjectsWithEquals - identity is meant - return i.slots[gi1]; + if (gs1 == s && gt1 == t) { //NOPMD CompareObjectsWithEquals - identity is meant + if (gk1 == SLOT) { + return i.slots[gi1]; + } + if (gk1 == FIELD) { + Object v = i.getField(gi1); + if (v != null) { + return v; + } + } + if (gk1 == CONST) { + return gv1; + } + if (gk1 == PROP) { + return ((PyProperty) gv1).get(i); + } + if (gk1 == DICT) { + return i.dictView(); + } } - if (gs2 == s && gt2 == t && gk2 == SLOT) { //NOPMD CompareObjectsWithEquals - identity is meant - return i.slots[gi2]; + if (gs2 == s && gt2 == t) { //NOPMD CompareObjectsWithEquals - identity is meant + if (gk2 == SLOT) { + return i.slots[gi2]; + } + if (gk2 == FIELD) { + Object v = i.getField(gi2); + if (v != null) { + return v; + } + } + if (gk2 == CONST) { + return gv2; + } + if (gk2 == PROP) { + return ((PyProperty) gv2).get(i); + } + if (gk2 == DICT) { + return i.dictView(); + } } - if (gs3 == s && gt3 == t && gk3 == SLOT) { //NOPMD CompareObjectsWithEquals - identity is meant - return i.slots[gi3]; + if (gs3 == s && gt3 == t) { //NOPMD CompareObjectsWithEquals - identity is meant + if (gk3 == SLOT) { + return i.slots[gi3]; + } + if (gk3 == FIELD) { + Object v = i.getField(gi3); + if (v != null) { + return v; + } + } + if (gk3 == CONST) { + return gv3; + } + if (gk3 == PROP) { + return ((PyProperty) gv3).get(i); + } + if (gk3 == DICT) { + return i.dictView(); + } } } return getSlow(i); } + return attrOf(o); + } + + // ---- module receivers -------------------------------------------------- + // `mod.name` / `mod.name(...)`: the site remembers where the name lives in + // the one module it last saw. A slot is re-read every time (null means it + // was deleted, so look again); a name in the module's `extra` map is + // trusted while the module's stamp is unchanged. Only a name the module + // itself holds is cached, so `__name__`, `__dict__` and the PEP 562 + // `__getattr__` hook always take the full lookup. + private PyModule mMod; + private int mSlot = -1; + private int mStamp; + private Object mVal; + + private Object attrOf(Object o) { + if (o instanceof PyModule) { + PyModule m = (PyModule) o; + if (m == mMod) { //NOPMD CompareObjectsWithEquals - identity is meant + if (mSlot >= 0) { + Object v = m.slots[mSlot]; + if (v != null) { + return v; + } + } else if (mStamp == m.extraStamp) { + return mVal; + } + } + return moduleMiss(m); + } return Py.obj(o).getAttr(name); } + private Object moduleMiss(PyModule m) { + int s = m.slotIndexOf(name); + if (s >= 0 && m.slots[s] != null) { + mMod = m; + mSlot = s; + mVal = null; + return m.slots[s]; + } + Object v = s < 0 ? m.extraOrNull(name) : null; + if (v != null) { + mMod = m; + mSlot = -1; + mStamp = m.extraStamp; + mVal = v; + return v; + } + return m.getAttr(name); + } + + /// `obj.name` for a miss probe (see [Py#MISS]): [Py#MISS] when the read + /// would raise AttributeError without running any code -- remembered per + /// class and shape like a hit -- and a caught AttributeError from code + /// that did run comes back as a miss carrying it. + public Object getOrMiss(Object o) { + if (o instanceof PyInstance) { + PyInstance i = (PyInstance) o; + PyType cls = i.cls; + Shape shape = i.shape; + if (missType == cls && missShape == shape && missVersion == PyType.version) { //NOPMD CompareObjectsWithEquals - identity is meant + return Py.MISS; + } + int k = findGet(cls, shape); + if (k >= 0 && getKinds[k] == MISSING) { + missType = cls; + missShape = shape; + missVersion = PyType.version; + return Py.MISS; + } + // A dunder (`__dict__`, `__class__`) is answered by the object + // itself, never from the shape or the class: it cannot be proved + // missing here. + if (k < 0 && !name.startsWith("__") && !cls.hasCustomGetattribute() && cls.lookup("__getattr__") == null + && i.fieldIndex(name) < 0 && (shape == null || shape.indexOf(name) < 0) + && cls.lookup(name) == null) { + addGet(cls, shape, MISSING, 0, null); + missType = cls; + missShape = shape; + missVersion = PyType.version; + return Py.MISS; + } + } + try { + if (!(o instanceof PyInstance)) { + // getAttr is getAttrOrNull plus a throw, so a null here is + // exactly the AttributeError a plain read raises -- without + // allocating and unwinding one per probe. + Object v = Py.obj(o).getAttrOrNull(name); + return v == null ? Py.MISS : v; + } + return get(o); + } catch (PyException e) { + if (e.matches(Py.ATTRIBUTE_ERROR)) { + return new Py.Miss(e); + } + throw e; + } + } + + /// The class [#classLacks] last found without this attribute. + private PyType lackType; + private int lackVersion; + + /// Whether an instance of `cls` with no attribute of its own would miss + /// this one: the class, its bases and `__getattr__` all lack it. The + /// typed code asks this for an object it never made, whose fields it + /// knows; a class given the attribute later answers false from then on. + public boolean classLacks(PyType cls) { + if (lackType == cls && lackVersion == PyType.version) { //NOPMD CompareObjectsWithEquals - identity is meant + return true; + } + if (name.startsWith("__") || cls.hasCustomGetattribute() || cls.lookup("__getattr__") != null + || cls.lookup(name) != null) { + return false; + } + lackType = cls; + lackVersion = PyType.version; + return true; + } + private Object getSlow(PyInstance i) { - int k = findGet(i.cls, i.shape); + int k = findGetOverflowFirst(i.cls, i.shape); if (k >= 0) { int kind = getKinds[k]; if (kind == SLOT) { @@ -241,6 +525,15 @@ private Object getSlow(PyInstance i) { if (kind == CLASS_ATTR) { return Py.bindAttr(getValues[k], i); } + if (kind == DICT) { + return i.dictView(); + } + if (kind == FIELD) { + Object v = i.getField(getSlots[k]); + if (v != null) { + return v; + } + } return i.getAttr(name); } return fillGet(i); @@ -259,9 +552,21 @@ private Object fillGet(PyInstance i) { int slot = 0; Object value = null; Object clsAttr = cls.lookup(name); - // A compiled field is read by the generated code itself; this site - // only sees it unset, and must not remember that. - if (!(clsAttr instanceof PyProperty) && !cls.hasCustomGetattribute() && i.fieldIndex(name) < 0) { + // A compiled field is remembered by its index, not its value: a read + // from code that cannot name the Java class -- another module -- finds + // it set, and one that finds it unset takes the generic read. + int field = i.fieldIndex(name); + if (clsAttr instanceof PyProperty && !cls.hasCustomGetattribute()) { + // A property is a data descriptor: it answers before the + // instance's own attributes, so while the class is unchanged + // (getVersion) every read is its getter. bindAttr calls it. + kind = CLASS_ATTR; + value = clsAttr; + } else if (field >= 0 && !(clsAttr instanceof PyProperty) && !readsThroughGet(clsAttr) && !cls.hasCustomGetattribute()) { + kind = FIELD; + slot = field; + } else if (!(clsAttr instanceof PyProperty) && !readsThroughGet(clsAttr) && !cls.hasCustomGetattribute() + && field < 0) { slot = shape == null ? -1 : shape.indexOf(name); if (slot >= 0) { kind = SLOT; @@ -270,109 +575,24 @@ private Object fillGet(PyInstance i) { value = clsAttr; } } + if (kind == NONE && clsAttr == null && result == i.dictViewOrNull() //NOPMD CompareObjectsWithEquals - identity is meant + && !cls.hasCustomGetattribute()) { + // The generic read answered the instance's own view: no class + // attribute, no own attribute and no __getattribute__ stand in + // front of it, and a change to any of those moves the class + // version or the shape this entry is keyed on. + kind = DICT; + } addGet(cls, shape, kind, slot, value); return result; } - // ---- stores -------------------------------------------------------------- - - public void set(Object o, Object v) { - if (o instanceof PyInstance) { - PyInstance i = (PyInstance) o; - if (setVersion == PyType.version) { - PyType t = i.cls; - Shape s = i.shape; - if (ss0 == s && st0 == t && sto0 == null) { //NOPMD CompareObjectsWithEquals - identity is meant - i.slots[si0] = v; - return; - } - if (ss1 == s && st1 == t && sto1 == null) { //NOPMD CompareObjectsWithEquals - identity is meant - i.slots[si1] = v; - return; - } - if (ss2 == s && st2 == t && sto2 == null) { //NOPMD CompareObjectsWithEquals - identity is meant - i.slots[si2] = v; - return; - } - if (ss3 == s && st3 == t && sto3 == null) { //NOPMD CompareObjectsWithEquals - identity is meant - i.slots[si3] = v; - return; - } - } - setSlow(i, v); - return; - } - Py.obj(o).setAttr(name, v); - } - - private void setSlow(PyInstance i, Object v) { - if (setVersion == PyType.version) { - PyType t = i.cls; - Shape s = i.shape; - for (int k = 0; k < setUsed; k++) { - if (setTypes[k] == t && setShapes[k] == s) { //NOPMD CompareObjectsWithEquals - identity is meant - Shape to = setTos[k]; - if (to == null) { - i.slots[setSlots[k]] = v; - } else { - i.append(to, v); - } - return; - } - } - } else { - setVersion = PyType.version; - setUsed = 0; - setNext = 0; - st0 = st1 = st2 = st3 = null; - } - fillSet(i, v); - } - - private void addSet(PyType t, Shape shape, int slot, Shape to) { - int k; - if (setUsed < WAYS) { - k = setUsed++; - } else { - k = setNext; - setNext = (setNext + 1) % WAYS; - } - setTypes[k] = t; - setShapes[k] = shape; - setSlots[k] = slot; - setTos[k] = to; - if (k == 0) { - st0 = t; ss0 = shape; si0 = slot; sto0 = to; - } else if (k == 1) { - st1 = t; ss1 = shape; si1 = slot; sto1 = to; - } else if (k == 2) { - st2 = t; ss2 = shape; si2 = slot; sto2 = to; - } else { - st3 = t; ss3 = shape; si3 = slot; sto3 = to; - } - } - - private void fillSet(PyInstance i, Object v) { - PyType cls = i.cls; - Object clsAttr = cls.lookup(name); - Object sa = cls.lookup("__setattr__"); - boolean plain = !(clsAttr instanceof PyProperty) && (sa == null || sa instanceof PyBuiltin) - && i.fieldIndex(name) < 0; - Shape before = i.shape; - i.setAttr(name, v); - if (!plain || setVersion != PyType.version) { - return; - } - Shape after = i.shape; - if (before == after) { //NOPMD CompareObjectsWithEquals - identity is meant - addSet(cls, before, after == null ? -1 : after.indexOf(name), null); - } else { - // Adding the attribute moved the instance to a new shape. Remember - // both the transition (the next new instance) and the slot on the - // new shape (the next store to an instance already initialised). - addSet(cls, before, 0, after); - addSet(cls, after, after.indexOf(name), null); - } + /// A class attribute that is an instance of a class with `__get__` -- a + /// descriptor written in Python -- answers every read by calling it, so + /// neither the instance's own value nor the attribute itself may be + /// remembered in its place. + private static boolean readsThroughGet(Object clsAttr) { + return clsAttr instanceof PyInstance && ((PyInstance) clsAttr).cls.lookup("__get__") != null; } // ---- calls --------------------------------------------------------------- @@ -400,9 +620,12 @@ public Object call0(Object o) { if (intrinsic == I_SPLIT) { return TypeMethods.split(v, null, -1); } + if (intrinsic == I_STRIP || intrinsic == I_LSTRIP || intrinsic == I_RSTRIP) { + return Py.str(TypeMethods.strip(v, null, intrinsic != I_RSTRIP, intrinsic != I_LSTRIP)); + } } Object f = method(o); - return f != null ? Py.obj(f).call1(o) : Py.obj(Py.obj(o).getAttr(name)).call0(); + return f != null ? (f instanceof PyObject ? (PyObject) f : Py.obj(f)).call1(o) : Py.obj(attrOf(o)).call0(); } public Object call1(Object o, Object a) { @@ -413,6 +636,12 @@ public Object call1(Object o, Object a) { ((PyList) o).append(a); return Py.NONE; } + // PySet is final, so this is exactly set or frozenset; addItem + // refuses the frozen one as the method would. + if (intrinsic == I_ADD && o instanceof PySet) { + ((PySet) o).addItem(a); + return Py.NONE; + } if (o instanceof String) { if (intrinsic == I_SPLIT) { return TypeMethods.split(((String) o), a, -1); @@ -426,6 +655,9 @@ public Object call1(Object o, Object a) { if (intrinsic == I_ENDSWITH && a instanceof String) { return Py.bool(((String) o).endsWith((String) a)); } + if ((intrinsic == I_FIND || intrinsic == I_RFIND) && a instanceof String) { + return PyInt.of(TypeMethods.findWhole((String) o, (String) a, intrinsic == I_RFIND)); + } } if (intrinsic == I_GET && o instanceof PyDict && o.getClass() == PyDict.class) { Object v = ((PyDict) o).getOrNull(a); @@ -433,43 +665,100 @@ public Object call1(Object o, Object a) { } } Object f = method(o); - return f != null ? Py.obj(f).call2(o, a) : Py.obj(Py.obj(o).getAttr(name)).call1(a); + return f != null ? (f instanceof PyObject ? (PyObject) f : Py.obj(f)).call2(o, a) : Py.obj(attrOf(o)).call1(a); + } + + /// `o.name(...)` where `name` is a compiled field of `o`'s class and + /// `f` is that field as the caller read it, null when the receiver is + /// of another class or the field is unset. A set field is the + /// instance's own attribute, which a method call reads first, so it is + /// called without the site: pdfminer's tokenizer keeps its state as a + /// bound method in `self._parse1` and calls it per token, and every + /// parser class it runs on passes through several layouts as optional + /// attributes appear, which drove the site megamorphic. + public Object callF0(Object f, Object o) { + return f != null ? Py.call(f) : call0(o); + } + + public Object callF1(Object f, Object o, Object a) { + return f != null ? Py.call(f, a) : call1(o, a); + } + + public Object callF2(Object f, Object o, Object a, Object b) { + return f != null ? Py.call(f, a, b) : call2(o, a, b); + } + + public Object callF3(Object f, Object o, Object a, Object b, Object c) { + return f != null ? Py.call(f, a, b, c) : call3(o, a, b, c); } public Object call2(Object o, Object a, Object b) { + if (intrinsic == I_REPLACE && o instanceof String && a instanceof String && b instanceof String + && ((String) a).length() > 0) { + return Py.str(((String) o).replace((String) a, (String) b)); + } if (intrinsic == I_GET && o != null && o.getClass() == PyDict.class) { Object v = ((PyDict) o).getOrNull(a); return v != null ? v : b; } Object f = method(o); - return f != null ? Py.obj(f).call3(o, a, b) : Py.obj(Py.obj(o).getAttr(name)).call2(a, b); + return f != null ? (f instanceof PyObject ? (PyObject) f : Py.obj(f)).call3(o, a, b) : Py.obj(attrOf(o)).call2(a, b); } public Object call3(Object o, Object a, Object b, Object c) { Object f = method(o); - return f != null ? Py.obj(f).call4(o, a, b, c) : Py.obj(Py.obj(o).getAttr(name)).call3(a, b, c); + return f != null ? (f instanceof PyObject ? (PyObject) f : Py.obj(f)).call4(o, a, b, c) : Py.obj(attrOf(o)).call3(a, b, c); } public Object call4(Object o, Object a, Object b, Object c, Object d) { Object f = method(o); - return f != null ? Py.obj(f).call5(o, a, b, c, d) : Py.obj(Py.obj(o).getAttr(name)).call4(a, b, c, d); + return f != null ? (f instanceof PyObject ? (PyObject) f : Py.obj(f)).call5(o, a, b, c, d) : Py.obj(attrOf(o)).call4(a, b, c, d); } public Object call5(Object o, Object a, Object b, Object c, Object d, Object e) { Object f = method(o); - return f != null ? Py.obj(f).call6(o, a, b, c, d, e) - : Py.obj(Py.obj(o).getAttr(name)).call5(a, b, c, d, e); + return f != null ? (f instanceof PyObject ? (PyObject) f : Py.obj(f)).call6(o, a, b, c, d, e) + : Py.obj(attrOf(o)).call5(a, b, c, d, e); } - /// `o.name(...)` with six arguments: a module's function (`_cn1re.run`) - /// takes them directly; a method, which needs a seventh for the - /// receiver, gets the array. public Object call6(Object o, Object a, Object b, Object c, Object d, Object e, Object f) { - Object m = method(o); - if (m != null) { - return Py.obj(m).call(new Object[] {o, a, b, c, d, e, f}, Py.NO_KW); - } - return Py.obj(Py.obj(o).getAttr(name)).call6(a, b, c, d, e, f); + Object fm = method(o); + return fm != null ? Py.obj(fm).call7(o, a, b, c, d, e, f) : Py.obj(attrOf(o)).call6(a, b, c, d, e, f); + } + + public Object call7(Object o, Object a, Object b, Object c, Object d, Object e, Object f, Object g) { + Object fm = method(o); + return fm != null ? Py.obj(fm).call8(o, a, b, c, d, e, f, g) : Py.obj(attrOf(o)).call7(a, b, c, d, e, f, g); + } + + public Object call8(Object o, Object a, Object b, Object c, Object d, Object e, Object f, Object g, Object h) { + Object fm = method(o); + return fm != null ? Py.obj(fm).call9(o, a, b, c, d, e, f, g, h) : Py.obj(attrOf(o)).call8(a, b, c, d, e, f, g, h); + } + + public Object call9(Object o, Object a, Object b, Object c, Object d, Object e, Object f, Object g, Object h, Object i) { + Object fm = method(o); + return fm != null ? Py.obj(fm).call10(o, a, b, c, d, e, f, g, h, i) : Py.obj(attrOf(o)).call9(a, b, c, d, e, f, g, h, i); + } + + public Object call10(Object o, Object a, Object b, Object c, Object d, Object e, Object f, Object g, Object h, Object i, Object j) { + Object fm = method(o); + return fm != null ? Py.obj(fm).call11(o, a, b, c, d, e, f, g, h, i, j) : Py.obj(attrOf(o)).call10(a, b, c, d, e, f, g, h, i, j); + } + + public Object call11(Object o, Object a, Object b, Object c, Object d, Object e, Object f, Object g, Object h, Object i, Object j, Object k) { + Object fm = method(o); + return fm != null ? Py.obj(fm).call12(o, a, b, c, d, e, f, g, h, i, j, k) : Py.obj(attrOf(o)).call11(a, b, c, d, e, f, g, h, i, j, k); + } + + public Object call12(Object o, Object a, Object b, Object c, Object d, Object e, Object f, Object g, Object h, Object i, Object j, Object k, Object l) { + Object fm = method(o); + return fm != null ? Py.obj(fm).call13(o, a, b, c, d, e, f, g, h, i, j, k, l) : Py.obj(attrOf(o)).call12(a, b, c, d, e, f, g, h, i, j, k, l); + } + + public Object call13(Object o, Object a, Object b, Object c, Object d, Object e, Object f, Object g, Object h, Object i, Object j, Object k, Object l, Object m) { + Object fm = method(o); + return fm != null ? Py.obj(fm).call14(o, a, b, c, d, e, f, g, h, i, j, k, l, m) : Py.obj(attrOf(o)).call13(a, b, c, d, e, f, g, h, i, j, k, l, m); } /// `o.name(...)` with seven or more arguments. `args[0]` is a slot the @@ -479,16 +768,156 @@ public Object callN(Object o, Object[] args) { Object f = method(o); if (f != null) { args[0] = o; - return Py.obj(f).call(args, Py.NO_KW); + return (f instanceof PyObject ? (PyObject) f : Py.obj(f)).call(args, Py.NO_KW); + } + Object[] rest = new Object[args.length - 1]; + System.arraycopy(args, 1, rest, 0, rest.length); + return Py.obj(attrOf(o)).call(rest, Py.NO_KW); + } + + /// `o.name(..., key=value)`: [#callN] with keyword names. A method of the + /// receiver's class is called with the receiver written into the empty + /// first slot, so the call makes neither a bound method nor a second + /// argument array. + public Object callKw(Object o, Object[] args, String[] kwNames) { + Object f = method(o); + if (f != null) { + args[0] = o; + return (f instanceof PyObject ? (PyObject) f : Py.obj(f)).call(args, kwNames); } Object[] rest = new Object[args.length - 1]; System.arraycopy(args, 1, rest, 0, rest.length); - return Py.obj(Py.obj(o).getAttr(name)).call(rest, Py.NO_KW); + return Py.obj(get(o)).call(rest, kwNames); + } + + /// [#callKw] of a fixed arity: the receiver plus at most thirteen arguments, + /// with no argument array at the call site. + public Object callKwF(Object o, String[] kwNames, Object a) { + Object fn = method(o); + if (fn != null) { + return Py.obj(fn).callKwF(kwNames, o, a); + } + return Py.obj(get(o)).callKwF(kwNames, a); + } + + public Object callKwF(Object o, String[] kwNames, Object a, Object b) { + Object fn = method(o); + if (fn != null) { + return Py.obj(fn).callKwF(kwNames, o, a, b); + } + return Py.obj(get(o)).callKwF(kwNames, a, b); + } + + public Object callKwF(Object o, String[] kwNames, Object a, Object b, Object c) { + Object fn = method(o); + if (fn != null) { + return Py.obj(fn).callKwF(kwNames, o, a, b, c); + } + return Py.obj(get(o)).callKwF(kwNames, a, b, c); + } + + public Object callKwF(Object o, String[] kwNames, Object a, Object b, Object c, Object d) { + Object fn = method(o); + if (fn != null) { + return Py.obj(fn).callKwF(kwNames, o, a, b, c, d); + } + return Py.obj(get(o)).callKwF(kwNames, a, b, c, d); + } + + public Object callKwF(Object o, String[] kwNames, Object a, Object b, Object c, Object d, Object e) { + Object fn = method(o); + if (fn != null) { + return Py.obj(fn).callKwF(kwNames, o, a, b, c, d, e); + } + return Py.obj(get(o)).callKwF(kwNames, a, b, c, d, e); + } + + public Object callKwF(Object o, String[] kwNames, Object a, Object b, Object c, Object d, Object e, Object f) { + Object fn = method(o); + if (fn != null) { + return Py.obj(fn).callKwF(kwNames, o, a, b, c, d, e, f); + } + return Py.obj(get(o)).callKwF(kwNames, a, b, c, d, e, f); + } + + public Object callKwF(Object o, String[] kwNames, Object a, Object b, Object c, Object d, Object e, Object f, Object g) { + Object fn = method(o); + if (fn != null) { + return Py.obj(fn).callKwF(kwNames, o, a, b, c, d, e, f, g); + } + return Py.obj(get(o)).callKwF(kwNames, a, b, c, d, e, f, g); + } + + public Object callKwF(Object o, String[] kwNames, Object a, Object b, Object c, Object d, Object e, Object f, Object g, Object h) { + Object fn = method(o); + if (fn != null) { + return Py.obj(fn).callKwF(kwNames, o, a, b, c, d, e, f, g, h); + } + return Py.obj(get(o)).callKwF(kwNames, a, b, c, d, e, f, g, h); + } + + public Object callKwF(Object o, String[] kwNames, Object a, Object b, Object c, Object d, Object e, Object f, Object g, Object h, Object i) { + Object fn = method(o); + if (fn != null) { + return Py.obj(fn).callKwF(kwNames, o, a, b, c, d, e, f, g, h, i); + } + return Py.obj(get(o)).callKwF(kwNames, a, b, c, d, e, f, g, h, i); + } + + public Object callKwF(Object o, String[] kwNames, Object a, Object b, Object c, Object d, Object e, Object f, Object g, Object h, Object i, Object j) { + Object fn = method(o); + if (fn != null) { + return Py.obj(fn).callKwF(kwNames, o, a, b, c, d, e, f, g, h, i, j); + } + return Py.obj(get(o)).callKwF(kwNames, a, b, c, d, e, f, g, h, i, j); + } + + public Object callKwF(Object o, String[] kwNames, Object a, Object b, Object c, Object d, Object e, Object f, Object g, Object h, Object i, Object j, Object k) { + Object fn = method(o); + if (fn != null) { + return Py.obj(fn).callKwF(kwNames, o, a, b, c, d, e, f, g, h, i, j, k); + } + return Py.obj(get(o)).callKwF(kwNames, a, b, c, d, e, f, g, h, i, j, k); + } + + public Object callKwF(Object o, String[] kwNames, Object a, Object b, Object c, Object d, Object e, Object f, Object g, Object h, Object i, Object j, Object k, Object l) { + Object fn = method(o); + if (fn != null) { + return Py.obj(fn).callKwF(kwNames, o, a, b, c, d, e, f, g, h, i, j, k, l); + } + return Py.obj(get(o)).callKwF(kwNames, a, b, c, d, e, f, g, h, i, j, k, l); + } + + public Object callKwF(Object o, String[] kwNames, Object a, Object b, Object c, Object d, Object e, Object f, Object g, Object h, Object i, Object j, Object k, Object l, Object m) { + Object fn = method(o); + if (fn != null) { + return Py.obj(fn).callKwF(kwNames, o, a, b, c, d, e, f, g, h, i, j, k, l, m); + } + return Py.obj(get(o)).callKwF(kwNames, a, b, c, d, e, f, g, h, i, j, k, l, m); + } + + /// True for a class attribute whose read through an instance is only + /// `PyMethod(self, attr)` (see `Py.bindAttr`): calling it with the + /// receiver prepended is the same call without the bound method. A + /// builtin binds that way too (`PyBuiltin.bind`), which is how a stdlib + /// class method written in Java (`re.Pattern.match`, `defaultdict`'s + /// `__missing__`) costs no allocation per call. + private static boolean takesReceiver(Object v) { + return v instanceof PyFunction + || v instanceof PyBuiltin && !"__new__".equals(((PyBuiltin) v).name); } /// The function to call with the receiver prepended, when the call needs /// no bound method; otherwise null and the caller goes the generic way. private Object method(Object o) { + if (o instanceof String) { + if (strVersion != PyType.version) { + Object m = Py.STR_TYPE.lookup(name); + strMethod = m instanceof PyBuiltin ? m : null; + strVersion = PyType.version; + } + return strMethod; + } if (o instanceof PyInstance) { PyInstance i = (PyInstance) o; if (getVersion == PyType.version) { @@ -507,12 +936,13 @@ private Object method(Object o) { return gf3; } } - int k = findGet(i.cls, i.shape); + int k = findGetOverflowFirst(i.cls, i.shape); if (k >= 0) { - return getKinds[k] == CLASS_ATTR && getValues[k] instanceof PyFunction ? getValues[k] : null; + return getKinds[k] == CLASS_ATTR && takesReceiver(getValues[k]) ? getValues[k] : null; } Object clsAttr = i.cls.lookup(name); - if (i.cls.hasCustomGetattribute() || clsAttr instanceof PyProperty || i.fieldIndex(name) >= 0) { + if (i.cls.hasCustomGetattribute() || clsAttr instanceof PyProperty || readsThroughGet(clsAttr) + || i.fieldIndex(name) >= 0) { addGet(i.cls, i.shape, NONE, 0, null); return null; } @@ -523,7 +953,7 @@ private Object method(Object o) { } if (clsAttr != null) { addGet(i.cls, i.shape, CLASS_ATTR, 0, clsAttr); - return clsAttr instanceof PyFunction ? clsAttr : null; + return takesReceiver(clsAttr) ? clsAttr : null; } addGet(i.cls, i.shape, NONE, 0, null); return null; @@ -537,7 +967,7 @@ private Object method(Object o) { return getKinds[k] == BUILTIN ? getValues[k] : null; } Object m = t.lookup(name); - int kind = m instanceof PyBuiltin ? BUILTIN : NONE; + int kind = m instanceof PyBuiltin && takesReceiver(m) ? BUILTIN : NONE; addGet(t, null, kind, 0, m); return kind == BUILTIN ? m : null; } diff --git a/maven/python-runtime/src/main/java/com/codename1/python/runtime/BuiltinSubclass.java b/maven/python-runtime/src/main/java/com/codename1/python/runtime/BuiltinSubclass.java index 5b36b904028..71c7c302dc6 100644 --- a/maven/python-runtime/src/main/java/com/codename1/python/runtime/BuiltinSubclass.java +++ b/maven/python-runtime/src/main/java/com/codename1/python/runtime/BuiltinSubclass.java @@ -58,6 +58,43 @@ static boolean mutable(PyType t) { return t == Py.LIST_TYPE || t == Py.DICT_TYPE || t == Py.SET_TYPE || t == Py.PROPERTY_TYPE; //NOPMD CompareObjectsWithEquals - identity is meant } + /// `dict.__getitem__`, whose receiver stays wrapped: reached on an + /// instance of a dict subclass (`super().__getitem__(k)` in a + /// `defaultdict` subclass) a miss calls `type(self).__missing__`, as + /// CPython's lookup does, which the unwrapped dict cannot know. The + /// instance's own `getItem` is not asked, since it would re-enter the + /// subclass's `__getitem__` override. The fixed-arity call takes no + /// argument array, and a plain dict goes straight to its own lookup. + private static void dictGetitem(PyType t) { + t.define("__getitem__", PyBuiltin.methodKwSelf(t, "__getitem__", (a, kw) -> { + if (a.length != 2) { + throw Py.typeError("expected 1 argument, got " + (a.length - 1)); + } + return dictGetitem2(a[0], a[1]); + }).withSelf2(BuiltinSubclass::dictGetitem2)); + } + + private static Object dictGetitem2(Object self, Object key) { + if (self instanceof PyInstance) { + PyInstance inst = (PyInstance) self; + Object k = key instanceof PyInstance && ((PyInstance) key).base != null ? ((PyInstance) key).base : key; + if (inst.base instanceof PyDict) { + PyType c = inst.cls; + c.hasBuiltinGetitem(); + Object missing = c.missingMethod(); + if (missing == null) { + return Py.obj(inst.base).getItem(k); + } + Object v = ((PyDict) inst.base).getOrNull(k); + return v != null ? v : Py.obj(missing).call2(self, key); + } + return Py.obj(self).getItem(k); + } + Object k = key instanceof PyInstance && ((PyInstance) key).base != null ? ((PyInstance) key).base : key; + Object r = Py.obj(self).getItem(k); + return r == null ? Py.NOT_IMPLEMENTED : r; + } + private static void binary(PyType t, String name, Binary op) { t.define(name, PyBuiltin.method(t, name, a -> { if (a.length != 2) { @@ -69,11 +106,17 @@ private static void binary(PyType t, String name, Binary op) { ? ((PyInstance) a[1]).base : a[1]; Object r = op.apply(Py.obj(a[0]), other); return r == null ? Py.NOT_IMPLEMENTED : r; + }).with2((self, x) -> { + // The fixed-arity call (`x in s`, `s == y` on an instance of a + // subclass): the receiver arrives unwrapped, no argument arrays. + Object other = x instanceof PyInstance && ((PyInstance) x).base != null ? ((PyInstance) x).base : x; + Object r = op.apply(Py.obj(self), other); + return r == null ? Py.NOT_IMPLEMENTED : r; })); } private static void unary(PyType t, String name, Unary op) { - t.define(name, PyBuiltin.method(t, name, a -> op.apply(Py.obj(a[0])))); + t.define(name, PyBuiltin.method(t, name, a -> op.apply(Py.obj(a[0]))).with1(self -> op.apply(Py.obj(self)))); } private static void arithmetic(PyType t) { @@ -94,9 +137,16 @@ private static void arithmetic(PyType t) { unary(t, "__neg__", PyObject::neg); unary(t, "__pos__", PyObject::pos); unary(t, "__abs__", s -> Builtins.lookup("abs") instanceof PyObject - ? ((PyObject) Builtins.lookup("abs")).call(new Object[] {s}, Py.NO_KW) : null); + ? ((PyObject) Builtins.lookup("abs")).call1(s) : null); unary(t, "__float__", s -> Py.ofFloat(s.asDouble())); - unary(t, "__bool__", s -> Py.bool(s.isTrue())); + // The truth of the builtin value an instance wraps. Marked, so that + // PyType.truthMethods recognizes it and `if s:` on a str subclass + // (bs4's NavigableString) asks the String itself: it called this + // builtin and made a PyStr view of the String for every test. + PyBuiltin b = PyBuiltin.method(t, "__bool__", a -> Py.bool(Py.isTrue(a[0]))) + .with1(s -> Py.bool(Py.isTrue(s))); + b.baseTruth = true; + t.define("__bool__", b); } private static void bits(PyType t) { @@ -134,14 +184,18 @@ private static void container(PyType t) { unary(t, "__len__", s -> PyInt.of(s.len())); unary(t, "__iter__", PyObject::iter); binary(t, "__contains__", (s, x) -> Py.bool(s.contains(x))); - binary(t, "__getitem__", PyObject::getItem); + if (t == Py.DICT_TYPE) { //NOPMD CompareObjectsWithEquals - identity is meant + dictGetitem(t); + } else { + binary(t, "__getitem__", PyObject::getItem); + } if (t == Py.LIST_TYPE || t == Py.DICT_TYPE || t == Py.BYTEARRAY_TYPE || t == Py.MEMORYVIEW_TYPE) { //NOPMD CompareObjectsWithEquals - identity is meant - t.define("__setitem__", PyBuiltin.method(t, "__setitem__", a -> { - Py.obj(a[0]).setItem(a[1], a[2]); + t.define("__setitem__", PyBuiltin.method3(t, "__setitem__", (a0, a1, a2) -> { + Py.obj(a0).setItem(a1, a2); return Py.NONE; })); - t.define("__delitem__", PyBuiltin.method(t, "__delitem__", a -> { - Py.obj(a[0]).delItem(a[1]); + t.define("__delitem__", PyBuiltin.method2(t, "__delitem__", (a0, a1) -> { + Py.obj(a0).delItem(a1); return Py.NONE; })); } @@ -153,30 +207,70 @@ private static void newMethod(final PyType t) { if (args.length == 0 || !(args[0] instanceof PyType)) { throw Py.notATypeObject(t.name, args); } - PyType cls = (PyType) args[0]; - if (!cls.isSubtype(t)) { - throw Py.typeError(t.name + ".__new__(" + cls.name + "): " + cls.name + " is not a subtype of " - + t.name); - } + PyType cls = newTarget(t, args[0]); Object[] rest = new Object[args.length - 1]; System.arraycopy(args, 1, rest, 0, rest.length); - Object v = t.factory.create(t, rest, kw); - if (cls == t) { //NOPMD CompareObjectsWithEquals - identity is meant - return v; + return wrapNew(t, cls, t.factory.create(t, rest, kw)); + }).withTwo((c, a) -> { + // `str.__new__(cls, value)`, which bs4 runs for every text node: no + // argument arrays, and the value is made the way `str(value)` makes it. + if (!(c instanceof PyType)) { + throw Py.notATypeObject(t.name, new Object[] {c, a}); } - PyInstance o = cls.newInstance(); - o.base = v; - return o; + PyType cls = newTarget(t, c); + Object v = t.unary != null ? t.unary.create(a) : t.factory.create(t, new Object[] {a}, Py.NO_KW); + return wrapNew(t, cls, v); }))); } + private static PyType newTarget(PyType t, Object c) { + PyType cls = (PyType) c; + if (!cls.isSubtype(t)) { + throw Py.typeError(t.name + ".__new__(" + cls.name + "): " + cls.name + " is not a subtype of " + + t.name); + } + return cls; + } + + private static Object wrapNew(PyType t, PyType cls, Object v) { + if (cls == t) { //NOPMD CompareObjectsWithEquals - identity is meant + return v; + } + PyInstance o = cls.newInstance(); + o.base = v; + return o; + } + /// `T.__init__(self, *args)` of a mutable builtin `T`: refills the value. private static void initMethod(final PyType t) { - t.define("__init__", PyBuiltin.methodKw(t, "__init__", (args, kw) -> { + t.define("__init__", initImpl(t).lendingTwo()); + } + + private static PyBuiltin initImpl(final PyType t) { + return PyBuiltin.methodKwSelf(t, "__init__", (args, kw) -> { + Object self0 = PyBuiltin.base(t, args[0]); + if (kw.length == 0 && args.length <= 2 && !(self0 instanceof PyProperty)) { + // `list.__init__(self, it)` from a subclass constructor, as + // bs4's ResultSet does per search: refill from the iterable + // directly rather than building a fresh value to copy. + // CPython clears a list or a set first and never a dict. + if (self0 instanceof PyList) { + PyList l = (PyList) self0; + l.clear(); + if (args.length == 2) { + l.extend(args[1]); + } + return Py.NONE; + } + if (self0 instanceof PyDict && args.length == 2 && args[1] instanceof PyDict) { + ((PyDict) self0).update(args[1]); + return Py.NONE; + } + } Object[] rest = new Object[args.length - 1]; System.arraycopy(args, 1, rest, 0, rest.length); Object fresh = t.factory.create(t, rest, kw); - Object self = args[0]; + Object self = self0; if (self instanceof PyProperty && fresh instanceof PyProperty) { ((PyProperty) self).fill((PyProperty) fresh); } else if (self instanceof PyList) { @@ -184,9 +278,8 @@ private static void initMethod(final PyType t) { l.clear(); l.extend(fresh); } else if (self instanceof PyDict) { - PyDict d = (PyDict) self; - d.clear(); - d.update(fresh); + // dict.__init__ adds to what is there; it never clears. + ((PyDict) self).update(fresh); } else if (self instanceof PySet) { PySet s = (PySet) self; s.clear(); @@ -196,7 +289,7 @@ private static void initMethod(final PyType t) { } } return Py.NONE; - })); + }); } static void install() { diff --git a/maven/python-runtime/src/main/java/com/codename1/python/runtime/Builtins.java b/maven/python-runtime/src/main/java/com/codename1/python/runtime/Builtins.java index 7eb17d0c7d9..d5223a5744a 100644 --- a/maven/python-runtime/src/main/java/com/codename1/python/runtime/Builtins.java +++ b/maven/python-runtime/src/main/java/com/codename1/python/runtime/Builtins.java @@ -58,10 +58,15 @@ static void writeOut(String s) { throw Py.notATypeObject("object", a); } return ((PyType) a[0]).newInstance(); + }).with1(t -> { + if (!(t instanceof PyType)) { + throw Py.notATypeObject("object", new Object[] {t}); + } + return ((PyType) t).newInstance(); }); /// Marks an optional argument that was not passed. private static final Object ABSENT = new PyStr(""); - public static final PyBuiltin OBJECT_INIT = PyBuiltin.positional("__init__", a -> Py.NONE); + public static final PyBuiltin OBJECT_INIT = PyBuiltin.positional("__init__", a -> Py.NONE).with1(a -> Py.NONE); public static final Object PRINT = new PyBuiltin("print", (args, kw) -> { Args a = new Args("print", args, kw).check(Integer.MAX_VALUE, "sep", "end", "file", "flush"); @@ -101,7 +106,7 @@ static void writeOut(String s) { public static final Object LEN = PyBuiltin.unary("len", x -> PyInt.of(Py.len(x))); /// `object.__hash__`, which the object type reads without defining it. - static final Object OBJECT_HASH = PyBuiltin.positional("__hash__", a -> Py.of((long) System.identityHashCode(a[0]))); + static final Object OBJECT_HASH = PyBuiltin.fixed1("__hash__", a0 -> Py.of((long) System.identityHashCode(a0))); public static final Object REPR = PyBuiltin.unary("repr", x -> Py.str(Py.toRepr(x))); public static final Object ASCII = PyBuiltin.unary("ascii", x -> Py.str(asciiOnly(Py.toRepr(x)))); @@ -109,8 +114,9 @@ static void writeOut(String s) { public static final Object ID = PyBuiltin.unary("id", x -> PyInt.of(System.identityHashCode(x))); public static final Object ABS = PyBuiltin.unary("abs", x -> abs(x)); public static final Object CALLABLE = PyBuiltin.unary("callable", x -> Py.bool(isCallable(x))); - public static final Object ITER = PyBuiltin.positional("iter", a -> iter(a)); - public static final Object NEXT = PyBuiltin.positional("next", a -> next(a)); + public static final Object ITER = PyBuiltin.positional("iter", a -> iter(a)).with1(Py::iter); + public static final Object NEXT = PyBuiltin.positional("next", a -> next(a)) + .with1(x -> next(x, null, false)).with2((x, d) -> next(x, d, true)); public static final Object AITER = PyBuiltin.unary("aiter", x -> Py.callMethod(x, "__aiter__")); // anext with a default is an awaitable that answers the default on StopAsyncIteration; the // asyncio module supplies that wrapper, so the builtin covers the one-argument form. @@ -127,23 +133,32 @@ static void writeOut(String s) { public static final Object OCT = PyBuiltin.unary("oct", x -> Py.str(Formatting.format(x, "#o"))); public static final Object BIN = PyBuiltin.unary("bin", x -> Py.str(Formatting.format(x, "#b"))); public static final Object FORMAT = PyBuiltin.positional("format", a -> Py.format(a[0], a.length > 1 ? Py.toStr(a[1]) : "")); - public static final Object DIVMOD = PyBuiltin.positional("divmod", a -> PyTuple.of(Py.floordiv(a[0], a[1]), Py.mod(a[0], a[1]))); + public static final Object DIVMOD = PyBuiltin.fixed2("divmod", (a0, a1) -> Py.tuple(Py.floordiv(a0, a1), Py.mod(a0, a1))); public static final Object POW = PyBuiltin.positional("pow", a -> pow(a)); - public static final Object ROUND = new PyBuiltin("round", (args, kw) -> round(new Args("round", args, kw).check(2, "number", "ndigits"))); - public static final Object ISINSTANCE = PyBuiltin.positional("isinstance", a -> Py.bool(Py.isinstance(a[0], a[1]))) + public static final Object ROUND = new PyBuiltin("round", (args, kw) -> round(new Args("round", args, kw).check(2, "number", "ndigits"))) + .withFixed(x -> round(x, Py.NONE), Builtins::round); + /// What the body of a function the build removed is: it raises, with + /// the message the build wrote for it. + public static final Object CN1_REMOVED = PyBuiltin.fixed1("__cn1_removed__", a0 -> { + throw Py.runtimeError(String.valueOf(a0)); + }); + /// What the body of a function the build replaced calls: the Java + /// registered for its name, with the function's own arguments. + public static final Object CN1_REPLACED = PyBuiltin.positional("__cn1_replaced__", a -> NativeModule.replaced(a)); + public static final Object ISINSTANCE = PyBuiltin.fixed2("isinstance", (a0, a1) -> Py.bool(Py.isinstance(a0, a1))) .with2((x, t) -> Py.bool(Py.isinstance(x, t))); - public static final Object ISSUBCLASS = PyBuiltin.positional("issubclass", a -> Py.bool(issubclass(a[0], a[1]))) + public static final Object ISSUBCLASS = PyBuiltin.fixed2("issubclass", (a0, a1) -> Py.bool(issubclass(a0, a1))) .with2((x, t) -> Py.bool(issubclass(x, t))); public static final Object GETATTR = PyBuiltin.positional("getattr", a -> getattr(a)) .with2((o, n) -> Py.obj(o).getAttr(Py.toStr(n))) .with3(Builtins::getattr3); - public static final Object SETATTR = PyBuiltin.positional("setattr", a -> { - Py.obj(a[0]).setAttr(Py.toStr(a[1]), a[2]); + public static final Object SETATTR = PyBuiltin.fixed3("setattr", (a0, a1, a2) -> { + Py.obj(a0).setAttr(Py.toStr(a1), a2); return Py.NONE; }); - public static final Object HASATTR = PyBuiltin.positional("hasattr", a -> { + public static final Object HASATTR = PyBuiltin.fixed2("hasattr", (a0, a1) -> { try { - return Py.bool(Py.obj(a[0]).getAttrOrNull(Py.toStr(a[1])) != null); + return Py.bool(Py.obj(a0).getAttrOrNull(Py.toStr(a1)) != null); } catch (PyException e) { if (e.matches(Py.ATTRIBUTE_ERROR)) { return Py.FALSE; @@ -151,33 +166,87 @@ static void writeOut(String s) { throw e; } }); - public static final Object DELATTR = PyBuiltin.positional("delattr", a -> { - Py.obj(a[0]).delAttr(Py.toStr(a[1])); + public static final Object DELATTR = PyBuiltin.fixed2("delattr", (a0, a1) -> { + Py.obj(a0).delAttr(Py.toStr(a1)); return Py.NONE; }); public static final Object VARS = PyBuiltin.unary("vars", x -> Py.obj(x).getAttr("__dict__")); public static final Object DIR = PyBuiltin.unary("dir", x -> dir(x)); public static final Object SUM = new PyBuiltin("sum", (args, kw) -> sum(new Args("sum", args, kw).check(2, "start"))); - public static final Object MIN = new PyBuiltin("min", (args, kw) -> minMax("min", args, kw, true)); - public static final Object MAX = new PyBuiltin("max", (args, kw) -> minMax("max", args, kw, false)); - public static final Object ANY = PyBuiltin.positional("any", a -> { - Object it = Py.iter(one("any", a)); + public static final Object MIN = new PyBuiltin("min", (args, kw) -> minMax("min", args, kw, true)) + .with1(x -> minMax1("min", x, true)).with2((x, y) -> Py.ltBool(y, x) ? y : x) + .with3((x, y, z) -> { + Object m = Py.ltBool(y, x) ? y : x; + return Py.ltBool(z, m) ? z : m; + }) + .with4((x, y, z, w) -> { + Object m = Py.ltBool(y, x) ? y : x; + m = Py.ltBool(z, m) ? z : m; + return Py.ltBool(w, m) ? w : m; + }); + public static final Object MAX = new PyBuiltin("max", (args, kw) -> minMax("max", args, kw, false)) + .with1(x -> minMax1("max", x, false)).with2((x, y) -> Py.ltBool(x, y) ? y : x) + .with3((x, y, z) -> { + Object m = Py.ltBool(x, y) ? y : x; + return Py.ltBool(m, z) ? z : m; + }) + .with4((x, y, z, w) -> { + Object m = Py.ltBool(x, y) ? y : x; + m = Py.ltBool(m, z) ? z : m; + return Py.ltBool(m, w) ? w : m; + }); + public static final Object ANY = PyBuiltin.positional("any", a -> any(one("any", a))).with1(Builtins::any); + + private static Object any(Object iterable) { + Object it = Py.iter(iterable); + if (it instanceof PyGenerator) { + // A generator expression, the usual argument: stepped under ONE + // handler (see PyList.extend), not a try per value. + PyGenerator g = (PyGenerator) it; + try { + for (Object v = PyGenerator.loopNext(g); v != null; v = PyGenerator.loopNext(g)) { + if (Py.isTrue(v)) { + return Py.TRUE; + } + } + } catch (Throwable e) { + throw PyGenerator.loopEscape(g, e); + } + return Py.FALSE; + } for (Object v = Py.next(it); v != null; v = Py.next(it)) { if (Py.isTrue(v)) { return Py.TRUE; } } return Py.FALSE; - }); - public static final Object ALL = PyBuiltin.positional("all", a -> { - Object it = Py.iter(one("all", a)); + } + public static final Object ALL = PyBuiltin.positional("all", a -> all(one("all", a))).with1(Builtins::all); + + private static Object all(Object iterable) { + Object it = Py.iter(iterable); + if (it instanceof PyGenerator) { + // A generator expression, the usual argument: stepped under ONE + // handler (see PyList.extend), not a try per value. + PyGenerator g = (PyGenerator) it; + try { + for (Object v = PyGenerator.loopNext(g); v != null; v = PyGenerator.loopNext(g)) { + if (!Py.isTrue(v)) { + return Py.FALSE; + } + } + } catch (Throwable e) { + throw PyGenerator.loopEscape(g, e); + } + return Py.TRUE; + } for (Object v = Py.next(it); v != null; v = Py.next(it)) { if (!Py.isTrue(v)) { return Py.FALSE; } } return Py.TRUE; - }); + } public static final Object SORTED = new PyBuiltin("sorted", (args, kw) -> { Args a = new Args("sorted", args, kw).check(1, "key", "reverse"); PyList l = new PyList(); @@ -185,25 +254,40 @@ static void writeOut(String s) { Object rev = a.kw("reverse"); l.sort(a.kw("key"), rev != null && Py.isTrue(rev)); return l; + }).with1(x -> { + PyList l = new PyList(); + l.extend(x); + l.sort(null, false); + return l; }); public static final Object REVERSED = PyBuiltin.unary("reversed", x -> reversed(x)); public static final Object ENUMERATE = new PyBuiltin("enumerate", (args, kw) -> { Args a = new Args("enumerate", args, kw).check(2, "iterable", "start"); - final Object it = Py.iter(a.required(0, "iterable")); - Object start = a.get(1, "start", PyInt.of(0)); + return enumerate(a.required(0, "iterable"), a.get(1, "start", PyInt.of(0))); + }).with1(x -> enumerate(x, PyInt.of(0))).with2(Builtins::enumerate); + + private static Object enumerate(Object iterable, Object start) { + final Object it = Py.iter(iterable); final Object[] n = {start}; return new PyJavaIter(() -> { Object v = Py.next(it); if (v == null) { return null; } - Object r = PyTuple.of(n[0], v); + Object r = Py.tuple(n[0], v); n[0] = Py.add(n[0], PyInt.of(1)); return r; }); - }); + } public static final Object ZIP = new PyBuiltin("zip", (args, kw) -> { Args a = new Args("zip", args, kw).check(Integer.MAX_VALUE, "strict"); + Object strictT = a.kw("strict"); + if (a.npos > 0 && (strictT == null || !Py.isTrue(strictT))) { + Object z = zipTuples(args, a.npos); + if (z != null) { + return z; + } + } final Object[] its = new Object[a.npos]; for (int i = 0; i < its.length; i++) { its[i] = Py.iter(args[i]); @@ -233,8 +317,117 @@ static void writeOut(String s) { } return new PyTuple(row); }); - }); + }).with2(Builtins::zip2); + + /// `zip(a, b)`, the usual call: the iterator alone, with none of the + /// argument array and keyword binding of the general form. Pulls from + /// `a` first, as that form does. + private static Object zip2(Object x, Object y) { + if ((x instanceof PyTuple || x instanceof PyList && x.getClass() == PyList.class) && y instanceof PyTuple) { //NOPMD CompareObjectsWithEquals - exactly list: a subclass may override __iter__ + return new PyJavaIter(new ZipSeq(x, ((PyTuple) y).arr())); + } + final Object i0 = Py.iter(x); + final Object i1 = Py.iter(y); + return new PyJavaIter(() -> { + Object v0 = Py.next(i0); + if (v0 == null) { + return null; + } + Object v1 = Py.next(i1); + return v1 == null ? null : Py.tuple(v0, v1); + }); + } + /// `zip(a, b)` of a tuple or list and a tuple: `dict(zip(keys, row))`, + /// the way sqlite-utils makes every row a dict, reads the pairs straight + /// out of it ([#drainInto]) rather than through a tuple for each. A list + /// is read live, as its iterator reads it, so one that changes size while + /// zipped ends where list iteration would. + static final class ZipSeq implements PyJavaIter.Source { + private final PyList list; + private final Object[] keys; + private final Object[] values; + private int pos; + + ZipSeq(Object x, Object[] values) { + this.list = x instanceof PyList ? (PyList) x : null; + this.keys = x instanceof PyTuple ? ((PyTuple) x).arr() : null; + this.values = values; + } + + private Object key(int p) { + if (keys != null) { + return p < keys.length ? keys[p] : null; + } + return p < list.size() ? list.get(p) : null; + } + + @Override + public Object next() { + int p = pos; + if (p >= values.length) { + return null; + } + Object k = key(p); + if (k == null) { + return null; + } + pos = p + 1; + return Py.tuple(k, values[p]); + } + + /// Stores every pair left into `d`, in order, as `d[k] = v` each. + void drainInto(PyDict d) { + for (int p = pos; p < values.length; p++) { + Object k = key(p); + if (k == null) { + break; + } + pos = p + 1; + d.setItem(k, values[p]); + } + } + } + + /// `zip(*rows)` over tuples, the transpose pdfplumber's merge_bboxes + /// does per word: tuples cannot change, so each column is read by index, + /// with no iterator per argument and no next() call per item. Null + /// when any argument is not a tuple. + private static Object zipTuples(Object[] args, int n) { + final Object[][] cols = new Object[n][]; + int len = Integer.MAX_VALUE; + for (int i = 0; i < n; i++) { + if (!(args[i] instanceof PyTuple)) { + return null; + } + cols[i] = ((PyTuple) args[i]).arr(); + len = Math.min(len, cols[i].length); + } + final int end = len; + final int[] pos = new int[1]; + return new PyJavaIter(() -> { + int p = pos[0]; + if (p >= end) { + return null; + } + pos[0] = p + 1; + if (cols.length == 2) { + return Py.tuple(cols[0][p], cols[1][p]); + } + Object[] row = new Object[cols.length]; + for (int i = 0; i < row.length; i++) { + row[i] = cols[i][p]; + } + return new PyTuple(row); + }); + } + public static final Object MAP = PyBuiltin.positional("map", a -> { + if (a.length == 2) { + return map1(a[0], a[1]); + } + if (a.length == 3) { + return new MapIter(Py.obj(a[0]), new Feed(a[1]), new Feed(a[2])); + } final Object f = a[0]; final Object[] its = new Object[a.length - 1]; for (int i = 0; i < its.length; i++) { @@ -250,19 +443,145 @@ static void writeOut(String s) { } return Py.obj(f).call(row, Py.NO_KW); }); - }); - public static final Object FILTER = PyBuiltin.positional("filter", a -> { - final Object f = a[0]; - final Object it = Py.iter(a[1]); - return new PyJavaIter(() -> { - for (Object v = Py.next(it); v != null; v = Py.next(it)) { - if (f == Py.NONE ? Py.isTrue(v) : Py.isTrue(Py.obj(f).call(new Object[] {v}, Py.NO_KW))) { //NOPMD CompareObjectsWithEquals - identity is meant + }).with2(Builtins::map1).with3((a0, a1, a2) -> new MapIter(Py.obj(a0), new Feed(a1), new Feed(a2))); + + /// `map(f, iterable)`, the usual case: a one-argument call per item. + private static Object map1(Object f, Object iterable) { + return new MapIter(Py.obj(f), new Feed(iterable), null); + } + + public static final Object FILTER = PyBuiltin.fixed2("filter", (a0, a1) -> + new FilterIter(a0 == Py.NONE ? null : Py.obj(a0), new Feed(a1))); //NOPMD CompareObjectsWithEquals - identity is meant + + /// The source of a map or filter: a list or tuple read by index (a + /// list's length read again each step, as its own iterator does), any + /// other iterable through its iterator. No iterator object and no + /// next() call per value for the usual list argument. + static final class Feed { + private final PyList list; + private final Object[] arr; + private final Object it; + private int i; + + Feed(Object iterable) { + if (iterable instanceof PyList) { + list = (PyList) iterable; + arr = null; + it = null; + } else if (iterable instanceof PyTuple) { + list = null; + arr = ((PyTuple) iterable).arr(); + it = null; + } else { + list = null; + arr = null; + it = Py.iter(iterable); + } + } + + Object next() { + int k = i; + if (list != null) { + if (k >= list.size) { + return null; + } + i = k + 1; + return list.get(k); + } + if (arr != null) { + if (k >= arr.length) { + return null; + } + i = k + 1; + return arr[k]; + } + return Py.next(it); + } + } + + /// `map(f, a)` and `map(f, a, b)`: a call1 or call2 per item, no row array. + static final class MapIter extends PyObject { + private final PyObject fn; + private final Feed a; + private final Feed b; + private boolean done; + + MapIter(PyObject fn, Feed a, Feed b) { + this.fn = fn; + this.a = a; + this.b = b; + } + + @Override + public PyType type() { + return Py.ITERATOR_TYPE; + } + + @Override + public Object iter() { + return this; + } + + @Override + public Object next() { + if (done) { + return null; + } + Object x = a.next(); + if (x == null) { + done = true; + return null; + } + if (b == null) { + return fn.call1(x); + } + Object y = b.next(); + if (y == null) { + done = true; + return null; + } + return fn.call2(x, y); + } + } + + /// `filter(f, iterable)`; `f` null for `filter(None, ...)`. + static final class FilterIter extends PyObject { + private final PyObject fn; + private final Feed src; + private boolean done; + + FilterIter(PyObject fn, Feed src) { + this.fn = fn; + this.src = src; + } + + @Override + public PyType type() { + return Py.ITERATOR_TYPE; + } + + @Override + public Object iter() { + return this; + } + + @Override + public Object next() { + if (done) { + return null; + } + final Feed s = src; + final PyObject f = fn; + for (Object v = s.next(); v != null; v = s.next()) { + if (f == null ? Py.isTrue(v) : Py.isTrue(f.call1(v))) { return v; } } + done = true; return null; - }); - }); + } + } + public static final Object SUPER = PyBuiltin.positional("super", a -> { if (a.length != 2 || !(a[0] instanceof PyType)) { throw Py.runtimeError("super(): no arguments"); @@ -326,6 +645,15 @@ static void install() { Py.obj(a[0]).setAttr(Py.toStr(a[1]), a[2]); } return Py.NONE; + }).with3((self, name, value) -> { + if (self instanceof PyInstance) { + ((PyInstance) self).setAttrObject(Py.toStr(name), value); + } else if (self instanceof PyType) { + ((PyType) self).setAttrDirect(Py.toStr(name), value); + } else { + Py.obj(self).setAttr(Py.toStr(name), value); + } + return Py.NONE; })); o.define("__getattribute__", PyBuiltin.positional("__getattribute__", a -> { // The lookup without __getattr__: what a class's own @@ -341,25 +669,22 @@ static void install() { })); // The reduction protocol's defaults are written in Python, in copyreg, // which pickle and copy import; object only forwards to them. - o.define("__reduce_ex__", PyBuiltin.positional("__reduce_ex__", - a -> Py.call(Py.importFrom(Py.importModule("copyreg"), "_reduce_ex"), a[0], a[1]))); - o.define("__reduce__", PyBuiltin.positional("__reduce__", - a -> Py.call(Py.importFrom(Py.importModule("copyreg"), "_reduce"), a[0]))); - o.define("__getstate__", PyBuiltin.positional("__getstate__", - a -> Py.call(Py.importFrom(Py.importModule("copyreg"), "_getstate"), a[0]))); - o.define("__delattr__", PyBuiltin.positional("__delattr__", a -> { - if (a[0] instanceof PyInstance) { - ((PyInstance) a[0]).delAttrDirect(Py.toStr(a[1])); - } else if (a[0] instanceof PyType) { - ((PyType) a[0]).delAttrDirect(Py.toStr(a[1])); + o.define("__reduce_ex__", PyBuiltin.fixed2("__reduce_ex__", (a0, a1) -> Py.call(Py.importFrom(Py.importModule("copyreg"), "_reduce_ex"), a0, a1))); + o.define("__reduce__", PyBuiltin.fixed1("__reduce__", a0 -> Py.call(Py.importFrom(Py.importModule("copyreg"), "_reduce"), a0))); + o.define("__getstate__", PyBuiltin.fixed1("__getstate__", a0 -> Py.call(Py.importFrom(Py.importModule("copyreg"), "_getstate"), a0))); + o.define("__delattr__", PyBuiltin.fixed2("__delattr__", (a0, a1) -> { + if (a0 instanceof PyInstance) { + ((PyInstance) a0).delAttrDirect(Py.toStr(a1)); + } else if (a0 instanceof PyType) { + ((PyType) a0).delAttrDirect(Py.toStr(a1)); } else { - Py.obj(a[0]).delAttr(Py.toStr(a[1])); + Py.obj(a0).delAttr(Py.toStr(a1)); } return Py.NONE; })); - o.define("__repr__", PyBuiltin.positional("__repr__", a -> Py.str("<" + Py.typeOf(a[0]).name - + " object at 0x" + Integer.toHexString(System.identityHashCode(a[0])) + ">"))); - o.define("__str__", PyBuiltin.positional("__str__", a -> Py.str(Py.toRepr(a[0])))); + o.define("__repr__", PyBuiltin.fixed1("__repr__", a0 -> Py.str("<" + Py.typeOf(a0).fullName() + + " object at 0x" + Integer.toHexString(System.identityHashCode(a0)) + ">"))); + o.define("__str__", PyBuiltin.fixed1("__str__", a0 -> Py.str(Py.toRepr(a0)))); installExceptions(); installFactories(); TypeMethods.install(); @@ -373,19 +698,25 @@ static void install() { names(); } + /// BaseException's own `__init__` and `__new__`: a type that has both + /// builds an instance from a message directly (`PyType.plainException`). + static Object BASE_EXCEPTION_INIT; //NOPMD MutableStaticState - set once, at install + static Object BASE_EXCEPTION_NEW; //NOPMD MutableStaticState - set once, at install + private static void installExceptions() { PyType b = Py.BASE_EXCEPTION; - b.define("__init__", PyBuiltin.method(b, "__init__", a -> { + BASE_EXCEPTION_INIT = PyBuiltin.method(b, "__init__", a -> { Object[] rest = new Object[a.length - 1]; System.arraycopy(a, 1, rest, 0, rest.length); if (a[0] instanceof PyInstance) { ((PyInstance) a[0]).setAttrDirect("args", new PyTuple(rest)); } return Py.NONE; - })); + }); + b.define("__init__", BASE_EXCEPTION_INIT); // Keyword arguments are accepted and ignored, as CPython's are: they // are for a subclass's __init__, and args holds the positional ones. - b.define("__new__", new PyStaticMethod(new PyBuiltin("__new__", (all, kw) -> { + BASE_EXCEPTION_NEW = new PyStaticMethod(new PyBuiltin("__new__", (all, kw) -> { Object[] a = all; if (kw.length > 0) { a = new Object[all.length - kw.length]; @@ -404,36 +735,39 @@ private static void installExceptions() { System.arraycopy(a, 1, rest, 0, rest.length); e.setAttrDirect("args", new PyTuple(rest)); return e; - }))); - b.define("__str__", PyBuiltin.positional("__str__", a -> { - Object[] args = exceptionArgs(a[0]); + })); + b.define("__new__", BASE_EXCEPTION_NEW); + b.define("__str__", PyBuiltin.fixed1("__str__", a0 -> { + Object[] args = exceptionArgs(a0); if (args.length == 0) { return Py.EMPTY_STR; } if (args.length == 1) { - if (Py.typeOf(a[0]).isSubtype(Py.KEY_ERROR)) { + if (Py.typeOf(a0).isSubtype(Py.KEY_ERROR)) { return Py.str(Py.toRepr(args[0])); } return Py.str(Py.toStr(args[0])); } return Py.str(new PyTuple(args).repr()); })); - b.define("__repr__", PyBuiltin.positional("__repr__", a -> { - Object[] args = exceptionArgs(a[0]); + b.define("__repr__", PyBuiltin.fixed1("__repr__", a0 -> { + Object[] args = exceptionArgs(a0); String inner = args.length == 1 ? Py.toRepr(args[0]) : Py.joinRepr("", args, args.length, ""); - return Py.str(Py.typeOf(a[0]).name + "(" + inner + ")"); + return Py.str(Py.typeOf(a0).name + "(" + inner + ")"); })); installOsError(); - b.define("with_traceback", PyBuiltin.positional("with_traceback", a -> a[0])); + installUnicodeError(Py.UNICODE_DECODE_ERROR, "decode"); + installUnicodeError(Py.UNICODE_ENCODE_ERROR, "encode"); + b.define("with_traceback", PyBuiltin.fixed1("with_traceback", a0 -> a0)); b.define("__cause__", Py.NONE); b.define("__context__", Py.NONE); b.define("__suppress_context__", Py.FALSE); b.define("__traceback__", Py.NONE); - Py.STOP_ITERATION.define("value", new PyProperty(PyBuiltin.positional("value", a -> { - Object[] args = exceptionArgs(a[0]); + Py.STOP_ITERATION.define("value", new PyProperty(PyBuiltin.fixed1("value", a0 -> { + Object[] args = exceptionArgs(a0); return args.length == 0 ? Py.NONE : args[0]; }), null, null)); - Py.SYSTEM_EXIT.define("code", new PyProperty(PyBuiltin.positional("code", a -> systemExitCode(a[0])), + Py.SYSTEM_EXIT.define("code", new PyProperty(PyBuiltin.fixed1("code", a0 -> systemExitCode(a0)), null, null)); } @@ -496,9 +830,9 @@ private static void installOsError() { e.setAttrDirect("args", new PyTuple(args)); return Py.NONE; })); - t.define("__str__", PyBuiltin.positional("__str__", a -> { - if (a[0] instanceof PyInstance) { - PyInstance e = (PyInstance) a[0]; + t.define("__str__", PyBuiltin.fixed1("__str__", a0 -> { + if (a0 instanceof PyInstance) { + PyInstance e = (PyInstance) a0; Object errno = orNone(e.own("errno")); Object strerror = orNone(e.own("strerror")); Object filename = orNone(e.own("filename")); @@ -515,13 +849,63 @@ private static void installOsError() { return Py.str(head); } } - return Py.call(Py.BASE_EXCEPTION.lookup("__str__"), a[0]); + return Py.call(Py.BASE_EXCEPTION.lookup("__str__"), a0); + })); + } + + /// UnicodeDecodeError(encoding, object, start, end, reason) and its + /// encode twin keep their parts as attributes, which a decoder that + /// retries past the bad bytes reads (`e.start`), and format the message + /// from them. + private static void installUnicodeError(PyType t, String verb) { + t.define("__init__", PyBuiltin.method(t, "__init__", a -> { + if (!(a[0] instanceof PyInstance)) { + return Py.NONE; + } + PyInstance e = (PyInstance) a[0]; + int n = a.length - 1; + Object[] args = new Object[n]; + System.arraycopy(a, 1, args, 0, n); + if (n == 5) { + e.setAttrDirect("encoding", a[1]); + e.setAttrDirect("object", a[2]); + e.setAttrDirect("start", a[3]); + e.setAttrDirect("end", a[4]); + e.setAttrDirect("reason", a[5]); + } + e.setAttrDirect("args", new PyTuple(args)); + return Py.NONE; + })); + t.define("__str__", PyBuiltin.fixed1("__str__", a0 -> { + if (a0 instanceof PyInstance && ((PyInstance) a0).own("reason") != null) { + PyInstance e = (PyInstance) a0; + long start = Py.asLong(e.own("start")); + long end = Py.asLong(e.own("end")); + String head = "'" + Py.toStr(e.own("encoding")) + "' codec can't " + verb + " "; + Object obj = e.own("object"); + if (end == start + 1) { + byte[] raw = PyBytes.like(obj); + if (raw == null) { + String text = Py.toStr(obj); + int cp = text.codePointAt(Character.offsetByCodePoints(text, 0, (int) start)); + head += "character '" + Codecs.escape(cp) + "'"; + } else { + String h = Integer.toHexString(raw[(int) start] & 0xff); + head += "byte 0x" + (h.length() < 2 ? "0" + h : h); + } + head += " in position " + start; + } else { + head += (PyBytes.like(obj) == null ? "characters" : "bytes") + " in position " + start + "-" + (end - 1); + } + return Py.str(head + ": " + Py.toStr(e.own("reason"))); + } + return Py.call(Py.BASE_EXCEPTION.lookup("__str__"), a0); })); } static Object[] exceptionArgs(Object e) { Object args = ((PyInstance) e).own("args"); - return args instanceof PyTuple ? ((PyTuple) args).items : Py.NO_ARGS; + return args instanceof PyTuple ? ((PyTuple) args).arr() : Py.NO_ARGS; } private static void installFactories() { @@ -545,7 +929,7 @@ private static void installFactories() { return PyInt.of(0); } if (base != null) { - return PyInt.parse(intText(x, true), (int) Py.asLong(base)); + return PyInt.parse(intText(x, true), (int) Py.asLong(base), x); } return toInt(x); }; @@ -553,6 +937,30 @@ private static void installFactories() { Py.STR_TYPE.unary = x -> Py.str(Py.toStr(x)); Py.FLOAT_TYPE.unary = Builtins::toFloat; Py.BOOL_TYPE.unary = x -> Py.bool(Py.isTrue(x)); + // One-argument construction of the exact builtin types runs without + // an argument array; the factories below take every other call. + Py.TUPLE_TYPE.unary = x -> x instanceof PyTuple ? x : new PyTuple(Py.toArray(x)); + Py.LIST_TYPE.unary = x -> { + PyList l = new PyList(); + l.extend(x); + return l; + }; + Py.DICT_TYPE.unary = x -> { + PyDict d = new PyDict(); + d.update(x); + return d; + }; + Py.SET_TYPE.unary = x -> PySet.of(x, false); + Py.FROZENSET_TYPE.unary = x -> PySet.of(x, true); + Py.TYPE_TYPE.unary = Py::typeOf; + Py.INT_TYPE.binary = (x, base) -> PyInt.parse(intText(x, true), (int) Py.asLong(base), x); + Py.STR_TYPE.binary = (x, enc) -> { + if (!(x instanceof PyBytes)) { + throw Py.typeError("decoding to str: need a bytes-like object, " + Py.typeOf(x).name + " found"); + } + return Py.str(Codecs.decodeKeep(((PyBytes) x).value, Py.toStr(enc), "strict")); + }; + Py.RANGE_TYPE.unary = x -> new PyRange(0, Py.index(x), 1); Py.BOOL_TYPE.factory = (t, args, kw) -> Py.bool(args.length > 0 && Py.isTrue(args[0])); Py.FLOAT_TYPE.factory = (t, args, kw) -> args.length == 0 ? Py.ofFloat(0) : toFloat(args[0]); Py.STR_TYPE.factory = (t, args, kw) -> { @@ -564,7 +972,7 @@ private static void installFactories() { if (!(p[0] instanceof PyBytes)) { throw Py.typeError("decoding to str: need a bytes-like object, " + Py.typeOf(p[0]).name + " found"); } - return Py.str(Codecs.decode(((PyBytes) p[0]).value, p[1] == ABSENT ? "utf-8" : Py.toStr(p[1]), + return Py.str(Codecs.decodeKeep(((PyBytes) p[0]).value, p[1] == ABSENT ? "utf-8" : Py.toStr(p[1]), p[2] == ABSENT ? "strict" : Py.toStr(p[2]))); }; Py.LIST_TYPE.factory = (t, args, kw) -> { @@ -661,27 +1069,27 @@ private static void installFactories() { PyProperty p = property(a[0]); return a.length < 2 || a[1] == Py.NONE ? a[0] : p.get(a[1]); })); - Py.PROPERTY_TYPE.define("__set__", PyBuiltin.positional("__set__", a -> { - property(a[0]).set(a[1], a[2]); + Py.PROPERTY_TYPE.define("__set__", PyBuiltin.fixed3("__set__", (a0, a1, a2) -> { + property(a0).set(a1, a2); return Py.NONE; })); - Py.PROPERTY_TYPE.define("__delete__", PyBuiltin.positional("__delete__", a -> { - property(a[0]).delete(a[1]); + Py.PROPERTY_TYPE.define("__delete__", PyBuiltin.fixed2("__delete__", (a0, a1) -> { + property(a0).delete(a1); return Py.NONE; })); // On the type rather than only on PyProperty, so an instance of a // property subclass has them too; a copy keeps the receiver's class. - Py.PROPERTY_TYPE.define("getter", PyBuiltin.positional("getter", a -> { - PyProperty p = property(a[0]); - return propertyCopy(a[0], a[1], p.fset, p.fdel); + Py.PROPERTY_TYPE.define("getter", PyBuiltin.fixed2("getter", (a0, a1) -> { + PyProperty p = property(a0); + return propertyCopy(a0, a1, p.fset, p.fdel); })); - Py.PROPERTY_TYPE.define("setter", PyBuiltin.positional("setter", a -> { - PyProperty p = property(a[0]); - return propertyCopy(a[0], p.fget, a[1], p.fdel); + Py.PROPERTY_TYPE.define("setter", PyBuiltin.fixed2("setter", (a0, a1) -> { + PyProperty p = property(a0); + return propertyCopy(a0, p.fget, a1, p.fdel); })); - Py.PROPERTY_TYPE.define("deleter", PyBuiltin.positional("deleter", a -> { - PyProperty p = property(a[0]); - return propertyCopy(a[0], p.fget, p.fset, a[1]); + Py.PROPERTY_TYPE.define("deleter", PyBuiltin.fixed2("deleter", (a0, a1) -> { + PyProperty p = property(a0); + return propertyCopy(a0, p.fget, p.fset, a1); })); String[] parts = {"fget", "fset", "fdel"}; for (int i = 0; i < parts.length; i++) { @@ -751,7 +1159,12 @@ private static void names() { NAMES.put(t.name, t); } // What the transpiler rewrites a `match` case into (see PyMatch). - NAMES.put("__cn1_match__", PyBuiltin.positional("__cn1_match__", a -> PyMatch.match(a[0], a[1]))); + NAMES.put("__cn1_match__", PyBuiltin.fixed2("__cn1_match__", (a0, a1) -> PyMatch.match(a0, a1))); + // What the transpiler rewrites `try: x = next(it) except + // StopIteration:` into: no exception is raised when `next` is the + // builtin, and one a shadowing `next` raises is caught here. + NAMES.put("__cn1_stop__", NEXT_STOP); + NAMES.put("__cn1_next_or_stop__", PyBuiltin.fixed2("__cn1_next_or_stop__", Builtins::nextOrStop)); ExceptionGroups.names(NAMES); // open() is io.open, written in Python; the transpiler bundles `io` // into any program that mentions open. @@ -764,9 +1177,12 @@ private static void names() { NAMES.put("False", Py.FALSE); NAMES.put("NotImplemented", Py.NOT_IMPLEMENTED); NAMES.put("Ellipsis", Py.ELLIPSIS); + // True, as under CPython without -O: assert statements run. + NAMES.put("__debug__", Py.TRUE); Object[] fns = {PRINT, LEN, REPR, ASCII, HASH, ID, ABS, CALLABLE, ITER, NEXT, ORD, CHR, HEX, OCT, BIN, FORMAT, DIVMOD, POW, ROUND, ISINSTANCE, ISSUBCLASS, GETATTR, SETATTR, HASATTR, DELATTR, VARS, DIR, - SUM, MIN, MAX, ANY, ALL, SORTED, REVERSED, ENUMERATE, ZIP, MAP, FILTER, SUPER, INPUT, AITER, ANEXT}; + SUM, MIN, MAX, ANY, ALL, SORTED, REVERSED, ENUMERATE, ZIP, MAP, FILTER, SUPER, INPUT, AITER, ANEXT, + CN1_REMOVED, CN1_REPLACED}; for (Object fn : fns) { NAMES.put(((PyBuiltin) fn).name, fn); } @@ -804,21 +1220,40 @@ static Object toInt(Object x) { return Py.mul(PyInt.parse(Formatting.fixed(Math.abs(d), 0), 10), PyInt.of(d < 0 ? -1 : 1)); } if (x instanceof String || x instanceof PyBytes || x instanceof PyByteArray) { - return PyInt.parse(intText(x, false), 10); + return PyInt.parse(intText(x, false), 10, x); } Object m = Py.typeOf(x).lookup("__int__"); if (m == null) { m = Py.typeOf(x).lookup("__index__"); } if (m != null) { - return Py.obj(m).call(new Object[] {x}, Py.NO_KW); + return Py.obj(m).call1(x); + } + Object text = textBase(x); + if (text != null) { + return toInt(text); } throw Py.typeError("int() argument must be a string, a bytes-like object or a real number, not '" + Py.typeOf(x).name + "'"); } + /// The str, bytes or bytearray an instance of a subclass of one of them + /// holds, which int(), float() and complex() parse as they parse the + /// base value; null for anything else. + static Object textBase(Object x) { + if (x instanceof PyInstance) { + Object b = ((PyInstance) x).base; + if (b instanceof String || b instanceof PyStr || b instanceof PyBytes || b instanceof PyByteArray) { + return b; + } + } + return null; + } + /// The text `int()` parses: a str, or the ASCII of a bytes-like value. - private static String intText(Object x, boolean explicitBase) { + private static String intText(Object value, boolean explicitBase) { + Object text = textBase(value); + Object x = text != null ? text : value; if (x instanceof String) { return (String) x; } @@ -833,11 +1268,7 @@ private static String intText(Object x, boolean explicitBase) { throw Py.typeError("int() argument must be a string, a bytes-like object or a real number, not '" + Py.typeOf(x).name + "'"); } - char[] c = new char[b.length]; - for (int i = 0; i < b.length; i++) { - c[i] = (char) (b[i] & 0xff); - } - return new String(c); + return Codecs.latin1(b, 0, b.length); } static Object toFloat(Object x) { @@ -847,6 +1278,10 @@ static Object toFloat(Object x) { if (Py.isInt(x)) { return Py.ofFloat(Py.asDouble(x)); } + Object text = textBase(x); + if (text != null && Py.typeOf(x).lookup("__float__") == null) { + return toFloat(text); + } if (x instanceof String) { String raw = ((String) x).trim(); String s = raw.replace("_", ""); @@ -874,12 +1309,8 @@ static Object toFloat(Object x) { byte[] b = x instanceof PyStr ? null : PyBytes.like(x); if (b != null) { // float(b"1.5") parses the bytes as ASCII text. - char[] cs = new char[b.length]; - for (int i = 0; i < b.length; i++) { - cs[i] = (char) (b[i] & 0xff); - } try { - return toFloat(new String(cs)); + return toFloat(Codecs.latin1(b, 0, b.length)); } catch (PyException e) { throw Py.valueError("could not convert string to float: " + Py.toRepr(x)); //NOPMD PreserveStackTrace - CPython's error has no cause } @@ -953,7 +1384,7 @@ private static Object abs(Object x) { if (m == null) { throw Py.typeError("bad operand type for abs(): '" + Py.typeOf(x).name + "'"); } - return Py.obj(m).call(new Object[] {x}, Py.NO_KW); + return Py.obj(m).call1(x); } static boolean isCallable(Object x) { @@ -974,21 +1405,68 @@ private static Object iter(Object[] a) { } private static Object next(Object[] a) { - Object v = Py.next(a[0]); + return next(a[0], a.length > 1 ? a[1] : null, a.length > 1); + } + + private static Object next(Object it, Object fallback, boolean hasFallback) { + Object v = Py.next(it); if (v == null) { - if (a.length > 1) { - return a[1]; + if (hasFallback) { + return fallback; } - if (a[0] instanceof PyGenerator) { - // A finished generator's StopIteration carries its return value. - throw PyGenerator.stopIteration(((PyGenerator) a[0]).returned()); - } - throw new PyException(Py.STOP_ITERATION.call(Py.NO_ARGS, Py.NO_KW)); + throw exhausted(it); } return v; } + /// The marker `__cn1_next_or_stop__` answers for an exhausted iterator. + static final Object NEXT_STOP = new PyObject() { + @Override + public PyType type() { + return Py.OBJECT_TYPE; + } + }; + + /// `__cn1_next_or_stop__(f, it)`, which the desugared + /// `try: x = next(it) except StopIteration:` calls; compiled code calls + /// it directly, as the name cannot be rebound. + public static Object nextOrStop(Object f, Object it) { + if (f == NEXT) { + Object v = Py.next(it); + return v == null ? NEXT_STOP : v; + } + try { + return Py.call(f, it); + } catch (PyException e) { + if (e.matches(Py.STOP_ITERATION)) { + return NEXT_STOP; + } + throw e; + } + } + + /// The StopIteration `next(it)` raises once `it` is exhausted. + static PyException exhausted(Object it) { + if (it instanceof PyGenerator) { + // A finished generator's StopIteration carries its return value. + return PyGenerator.stopIteration(((PyGenerator) it).returned()); + } + return new PyException(Py.STOP_ITERATION.call(Py.NO_ARGS, Py.NO_KW)); + } + static Object ord(Object x) { + if (x instanceof String) { + // One code point is one char, or a surrogate pair: no count of + // the whole string for what is nearly always one char. + String s = (String) x; + int n = s.length(); + if (n == 1) { + return PyInt.of(s.charAt(0)); + } + if (n == 2 && Character.isHighSurrogate(s.charAt(0)) && Character.isLowSurrogate(s.charAt(1))) { + return PyInt.of(Character.toCodePoint(s.charAt(0), s.charAt(1))); + } + } if (!(x instanceof String) || PyStr.codePoints((String) x) != 1) { throw Py.typeError("ord() expected a character, but string of length " + (x instanceof String ? PyStr.codePoints((String) x) : 0) + " found"); @@ -1038,12 +1516,14 @@ private static Object pow(Object[] a) { } private static Object round(Args a) { - Object x = a.required(0, "number"); - Object nd = a.get(1, "ndigits", Py.NONE); + return round(a.required(0, "number"), a.get(1, "ndigits", Py.NONE)); + } + + private static Object round(Object x, Object nd) { if (x instanceof PyInstance) { Object m = Py.typeOf(x).lookup("__round__"); if (m != null) { - return nd == Py.NONE ? Py.obj(m).call(new Object[] {x}, Py.NO_KW) : Py.obj(m).call(new Object[] {x, nd}, Py.NO_KW); //NOPMD CompareObjectsWithEquals - identity is meant + return nd == Py.NONE ? Py.obj(m).call1(x) : Py.obj(m).call2(x, nd); //NOPMD CompareObjectsWithEquals - identity is meant } } if (Py.isInt(x)) { @@ -1086,7 +1566,7 @@ private static boolean issubclass(Object c, Object t) { throw Py.typeError("issubclass() arg 1 must be a class"); } if (t instanceof PyTuple) { - Object[] items = ((PyTuple) t).items; + Object[] items = ((PyTuple) t).arr(); for (Object item : items) { if (issubclass(c, item)) { return true; @@ -1095,7 +1575,11 @@ private static boolean issubclass(Object c, Object t) { return false; } if (!(t instanceof PyType)) { - throw Py.typeError("issubclass() arg 2 must be a class, a tuple of classes, or a union"); + Object check = Py.typeOf(t).lookup("__subclasscheck__"); + if (check == null) { + throw Py.typeError("issubclass() arg 2 must be a class, a tuple of classes, or a union"); + } + return Py.isTrue(Py.call(check, t, c)); } return ((PyType) t).subclassCheck((PyType) c); } @@ -1146,7 +1630,30 @@ private static Object dir(Object o) { } private static Object sum(Args a) { - Object it = Py.iter(a.required(0, "iterable")); + Object src = a.required(0, "iterable"); + if (src instanceof PyRange && a.get(1, "start", null) == null) { + // The values of a range are known: add them as longs, no iterator and + // no box per value. An overflow is left to the general loop below, + // which promotes to a big int from a fresh iterator. + PyRange r = (PyRange) src; + long n = r.length(); + long acc = 0; + long v = r.start; + boolean ok = true; + for (long i = 0; i < n; i++) { + long t = acc + v; + if (((acc ^ t) & (v ^ t)) < 0) { + ok = false; + break; + } + acc = t; + v += r.step; + } + if (ok) { + return PyInt.of(acc); + } + } + Object it = Py.iter(src); Object acc = a.get(1, "start", PyInt.of(0)); if (acc instanceof String) { throw Py.typeError("sum() can't sum strings [use ''.join(seq) instead]"); @@ -1162,8 +1669,10 @@ private static Object sum(Args a) { boolean floatMode = false; for (Object v = Py.next(it); v != null; v = Py.next(it)) { if (intMode) { - if (Py.isInt(v) && !Py.intView(v).isBig()) { - long b = Py.intView(v).value; + // A small int is a Long; read it as one. intView builds a PyInt per + // value above the cache, which was most of what sum(range(n)) did. + if (v instanceof Long) { + long b = ((Long) v).longValue(); long r = ia + b; if (((ia ^ r) & (b ^ r)) >= 0) { ia = r; @@ -1214,7 +1723,71 @@ private static Object sum(Args a) { return acc; } + /// `min(iterable)` / `max(iterable)` with no key or default. + private static Object minMax1(String fn, Object iterable, boolean min) { + Object[] items = null; + int n = 0; + if (iterable instanceof PyTuple) { + items = ((PyTuple) iterable).arr(); + n = items.length; + } else if (iterable instanceof PyList) { + PyList l = (PyList) iterable; + if (l.floats == null && l.ints == null) { + items = l.items; + n = l.size; + } + } + if (items != null && n > 0) { + // A tuple or list is read in place, and two floats or two ints + // compared as such: pdfplumber's merge_bboxes takes min and max + // of each column of a word's character boxes. + Object best = items[0]; + for (int i = 1; i < n; i++) { + Object v = items[i]; + if (min ? less(v, best) : less(best, v)) { + best = v; + } + } + return best; + } + Object it = Py.iter(iterable); + Object best = Py.next(it); + if (best == null) { + throw Py.valueError(fn + "() iterable argument is empty"); + } + for (Object v = Py.next(it); v != null; v = Py.next(it)) { + if (min ? Py.ltBool(v, best) : Py.ltBool(best, v)) { + best = v; + } + } + return best; + } + + /// `a < b` as a bool, directly for two floats or two ints. + private static boolean less(Object a, Object b) { + if (a instanceof Double && b instanceof Double) { + return ((Double) a).doubleValue() < ((Double) b).doubleValue(); + } + if (a instanceof Long && b instanceof Long) { + return ((Long) a).longValue() < ((Long) b).longValue(); + } + return Py.ltBool(a, b); + } + private static Object minMax(String fn, Object[] args, String[] kw, boolean min) { + if (kw.length == 0 && args.length >= 2) { + // min(a, b, ...) with no key: a straight scan over the arguments, + // with no argument parsing, tuple or iterator. pdfminer's + // apply_matrix_rect calls it four times per rectangle. + Object best = args[0]; + for (int i = 1; i < args.length; i++) { + Object v = args[i]; + if (min ? less(v, best) : less(best, v)) { + best = v; + } + } + return best; + } Args a = new Args(fn, args, kw).check(Integer.MAX_VALUE, "key", "default"); Object key = a.kw("key"); if (key == Py.NONE) { //NOPMD CompareObjectsWithEquals - identity is meant @@ -1232,11 +1805,27 @@ private static Object minMax(String fn, Object[] args, String[] kw, boolean min) } Object best = null; Object bestKey = null; - for (Object v = Py.next(it); v != null; v = Py.next(it)) { - Object k = key == null ? v : Py.obj(key).call(new Object[] {v}, Py.NO_KW); - if (best == null || (min ? Py.ltBool(k, bestKey) : Py.ltBool(bestKey, k))) { - best = v; - bestKey = k; + if (it instanceof PyGenerator) { + // Stepped under one handler (see PyList.extend). + PyGenerator g = (PyGenerator) it; + try { + for (Object v = PyGenerator.loopNext(g); v != null; v = PyGenerator.loopNext(g)) { + Object k = key == null ? v : Py.obj(key).call1(v); + if (best == null || (min ? Py.ltBool(k, bestKey) : Py.ltBool(bestKey, k))) { + best = v; + bestKey = k; + } + } + } catch (Throwable e) { + throw PyGenerator.loopEscape(g, e); + } + } else { + for (Object v = Py.next(it); v != null; v = Py.next(it)) { + Object k = key == null ? v : Py.obj(key).call1(v); + if (best == null || (min ? Py.ltBool(k, bestKey) : Py.ltBool(bestKey, k))) { + best = v; + bestKey = k; + } } } if (best == null) { @@ -1251,7 +1840,7 @@ private static Object minMax(String fn, Object[] args, String[] kw, boolean min) private static Object reversed(Object seq) { Object m = Py.typeOf(seq).lookup("__reversed__"); if (m != null) { - return Py.obj(m).call(new Object[] {seq}, Py.NO_KW); + return Py.obj(m).call1(seq); } if (seq instanceof PyInstance && ((PyInstance) seq).base != null) { // A subclass of a built-in reverses as its built-in value does. diff --git a/maven/python-runtime/src/main/java/com/codename1/python/runtime/Cn1Platform.java b/maven/python-runtime/src/main/java/com/codename1/python/runtime/Cn1Platform.java new file mode 100644 index 00000000000..99c3d973404 --- /dev/null +++ b/maven/python-runtime/src/main/java/com/codename1/python/runtime/Cn1Platform.java @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.python.runtime; + +import com.codename1.io.Util; +import com.codename1.ui.Display; + +/// What a client application lends the runtime from the port: its resource +/// lookup and its AES. The generated bootstrap of a client application calls +/// [#install]; a server or command-line program never names this class, so its +/// translation never reaches `Display` or `Util`, which a server's class +/// library does not have. +public final class Cn1Platform { + private Cn1Platform() { + } + + /// Installs the client's resource lookup and cipher. + public static void install() { + PyPackageData.setOpener(name -> Display.isInitialized() + ? Display.getInstance().getResourceAsStream(PyPackageData.class, name) : null); + PyAes.setCipher((encrypt, transformation, key, iv, data) -> encrypt + ? Util.aesEncrypt(transformation, key, iv, null, data) + : Util.aesDecrypt(transformation, key, iv, null, data)); + } +} diff --git a/maven/python-runtime/src/main/java/com/codename1/python/runtime/Cn1Sql.java b/maven/python-runtime/src/main/java/com/codename1/python/runtime/Cn1Sql.java index acbb10f4962..4a541cd974a 100644 --- a/maven/python-runtime/src/main/java/com/codename1/python/runtime/Cn1Sql.java +++ b/maven/python-runtime/src/main/java/com/codename1/python/runtime/Cn1Sql.java @@ -26,6 +26,7 @@ import com.codename1.db.Cursor; import com.codename1.db.Database; import com.codename1.db.Row; +import java.util.function.Function; import java.io.IOException; /// SQLite through Codename One's `Database`: the platform's own engine on @@ -46,6 +47,10 @@ public static void installDefault() { @Override public Connection open(String name) throws IOException { boolean memory = ":memory:".equals(name) || name.length() == 0; + if (memory && Database.isInMemorySupported()) { + return new Conn(Database.openInMemory(), null); + } + // A platform without in-memory databases gets a file of its own, deleted on close. String dbName = memory ? "cn1py-memory-" + System.currentTimeMillis() + "-" + MEMORY_COUNT.getAndIncrement() + ".db" : localName(name); if (memory && Database.exists(dbName)) { @@ -72,9 +77,63 @@ private static final class Conn extends Connection { this.deleteOnClose = deleteOnClose; } + @Override + public boolean createFunction(String name, int nargs, Function body) throws IOException { + if (!db.supportsFunctions()) { + return false; + } + db.createFunction(name, nargs, body); + return true; + } + + /// One result per nesting depth, reused: a caller reads its result + /// before it runs anything else, and Python runs one thread at a time. + /// A SQL function that executes a statement while one is stepping is + /// the only nesting, and it gets the next depth's. The depth is the + /// function wrapper's to count, so a run takes no handler to undo it. + private static final Result[] RESULTS = new Result[8]; + + /// What [Database#executeStatus(String, Object[], long[])] writes the changes and the + /// last row id into; read straight after, so one serves every depth. + private static final long[] COUNTS = new long[2]; + @Override public Result run(String sql, Object[] params, boolean query) throws IOException { - Result r = new Result(); + return fill(slot(), sql, params, query); + } + + @Override + public Result runStatus(String sql, Object[] params, boolean query) { + if (query) { + return super.runStatus(sql, params, query); + } + Result r = slot(); + if (db.executeStatus(sql, params, COUNTS) != 0) { + return failStatus(db.getStatusMessage()); + } + if (isChange(sql)) { + r.changes = COUNTS[0]; + r.lastRowId = COUNTS[1]; + } + return r; + } + + private static Result slot() { + int depth = nesting; + if (depth >= RESULTS.length) { + return new Result(); + } + Result r = RESULTS[depth]; + if (r == null) { + r = new Result(); + RESULTS[depth] = r; + } else { + r.clear(); + } + return r; + } + + private Result fill(Result r, String sql, Object[] params, boolean query) throws IOException { if (query) { Cursor c = params.length == 0 ? db.executeQuery(sql) : db.executeQuery(sql, params); try { @@ -86,8 +145,10 @@ public Result run(String sql, Object[] params, boolean query) throws IOException while (c.next()) { Row row = c.getRow(); Object[] values = new Object[n]; - for (int i = 0; i < n; i++) { - values[i] = value(row, i); + if (!Database.getValues(row, values)) { + for (int i = 0; i < n; i++) { + values[i] = value(row, i); + } } r.rows.add(values); } @@ -102,35 +163,18 @@ public Result run(String sql, Object[] params, boolean query) throws IOException db.execute(sql, params); } if (isChange(sql)) { - Cursor c = db.executeQuery("SELECT changes(), last_insert_rowid()"); - try { - if (c.next()) { - Row row = c.getRow(); - r.changes = row.getLong(0); - r.lastRowId = row.getLong(1); - } - } finally { - c.close(); - } + r.changes = db.changes(); + r.lastRowId = db.lastInsertRowId(); } return r; } private static Object value(Row row, int i) throws IOException { - switch (row.getColumnType(i)) { - case Database.COLUMN_NULL: - return null; - case Database.COLUMN_INTEGER: - return Long.valueOf(row.getLong(i)); - case Database.COLUMN_FLOAT: - return Double.valueOf(row.getDouble(i)); - case Database.COLUMN_TEXT: - return row.getString(i); - case Database.COLUMN_BLOB: - return row.getBlob(i); - default: - return inferred(row.getString(i)); + if (row.getColumnType(i) == Database.COLUMN_UNKNOWN) { + return inferred(row.getString(i)); } + // The type is cached by the cursor, so this reads only the value. + return Database.getValue(row, i); } @Override @@ -158,13 +202,25 @@ public void close() throws IOException { } /// Whether a statement is one whose changes and row id are reported. + /// Whether the statement's first word is INSERT, UPDATE, DELETE or REPLACE, compared in place: + /// this runs on every statement, and a copy of the word would be garbage each time. static boolean isChange(String sql) { - String w = firstWord(sql); - return "INSERT".equalsIgnoreCase(w) || "UPDATE".equalsIgnoreCase(w) || "DELETE".equalsIgnoreCase(w) - || "REPLACE".equalsIgnoreCase(w); + int s = wordStart(sql); + int e = s; + int n = sql.length(); + while (e < n && isAsciiLetter(sql.charAt(e))) { + e++; + } + return isWord(sql, s, e, "INSERT") || isWord(sql, s, e, "UPDATE") || isWord(sql, s, e, "DELETE") + || isWord(sql, s, e, "REPLACE"); + } + + private static boolean isWord(String sql, int s, int e, String word) { + return e - s == word.length() && sql.regionMatches(true, s, word, 0, word.length()); } - static String firstWord(String sql) { + /// Where the first word starts, past spaces, comments and opening parentheses. + private static int wordStart(String sql) { int i = 0; int n = sql.length(); while (i < n) { @@ -182,11 +238,7 @@ static String firstWord(String sql) { break; } } - int s = i; - while (i < n && isAsciiLetter(sql.charAt(i))) { - i++; - } - return sql.substring(s, i); + return i; } private static boolean isAsciiLetter(char c) { diff --git a/maven/python-runtime/src/main/java/com/codename1/python/runtime/Codecs.java b/maven/python-runtime/src/main/java/com/codename1/python/runtime/Codecs.java index 212817ca129..618367a6d34 100644 --- a/maven/python-runtime/src/main/java/com/codename1/python/runtime/Codecs.java +++ b/maven/python-runtime/src/main/java/com/codename1/python/runtime/Codecs.java @@ -24,21 +24,69 @@ package com.codename1.python.runtime; import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; /// `str.encode` / `bytes.decode` for the encodings Codename One supports on -/// every platform: UTF-8, ASCII and Latin-1. Any other name is a -/// LookupError rather than a silent fallback, so a program that needs -/// another charset fails where it asks for it. +/// every platform: UTF-8, ASCII and Latin-1, plus the two that file formats +/// mandate rather than a locale picks -- UTF-16, which PDF text strings and +/// OLE compound files (`.msg`, `.xls`) store, and code page 437, the ZIP +/// specification's encoding for entry names without the UTF-8 flag. Any +/// other name is a LookupError rather than a silent fallback, so a program +/// that needs another charset fails where it asks for it. This is not a +/// step toward the JDK's charset list: a locale charset (Shift-JIS, cp1252) +/// stays unsupported. final class Codecs { + /// Code page 437's characters for bytes 0x80-0xFF; the low half is ASCII. + private static final String CP437_HIGH = + "\u00c7\u00fc\u00e9\u00e2\u00e4\u00e0\u00e5\u00e7" + + "\u00ea\u00eb\u00e8\u00ef\u00ee\u00ec\u00c4\u00c5" + + "\u00c9\u00e6\u00c6\u00f4\u00f6\u00f2\u00fb\u00f9" + + "\u00ff\u00d6\u00dc\u00a2\u00a3\u00a5\u20a7\u0192" + + "\u00e1\u00ed\u00f3\u00fa\u00f1\u00d1\u00aa\u00ba" + + "\u00bf\u2310\u00ac\u00bd\u00bc\u00a1\u00ab\u00bb" + + "\u2591\u2592\u2593\u2502\u2524\u2561\u2562\u2556" + + "\u2555\u2563\u2551\u2557\u255d\u255c\u255b\u2510" + + "\u2514\u2534\u252c\u251c\u2500\u253c\u255e\u255f" + + "\u255a\u2554\u2569\u2566\u2560\u2550\u256c\u2567" + + "\u2568\u2564\u2565\u2559\u2558\u2552\u2553\u256b" + + "\u256a\u2518\u250c\u2588\u2584\u258c\u2590\u2580" + + "\u03b1\u00df\u0393\u03c0\u03a3\u03c3\u00b5\u03c4" + + "\u03a6\u0398\u03a9\u03b4\u221e\u03c6\u03b5\u2229" + + "\u2261\u00b1\u2265\u2264\u2320\u2321\u00f7\u2248" + + "\u00b0\u2219\u00b7\u221a\u207f\u00b2\u25a0\u00a0"; + private Codecs() { } - /// A normalised codec name: `utf-8`, `ascii` or `latin-1`. + /// `b[off..off+len)` as Latin-1 characters: one copy straight into a compact + /// (one byte per character) string, on the device and on the JVM alike. + /// The Charset overload: the name overload looks the charset up on every + /// call and declares a checked exception, whose handler costs a setjmp on + /// ParparVM. + static String latin1(byte[] b, int off, int len) { + return new String(b, off, len, StandardCharsets.ISO_8859_1); + } + + /// A normalised codec name: `utf-8`, `utf-8-sig`, `ascii`, `latin-1`, `utf-16`, + /// `utf-16-le`, `utf-16-be` or `cp437`. static String normalize(String encoding) { + // The spellings programs actually pass, answered without folding a copy. + if ("utf-8".equals(encoding) || "utf8".equals(encoding) || "UTF-8".equals(encoding)) { + return "utf-8"; + } + if ("latin-1".equals(encoding) || "latin1".equals(encoding) || "iso-8859-1".equals(encoding)) { + return "latin-1"; + } + if ("ascii".equals(encoding)) { + return "ascii"; + } String e = TypeMethods.asciiLower(encoding).replace('_', '-'); if ("utf-8".equals(e) || "utf8".equals(e) || "u8".equals(e) || "utf".equals(e)) { return "utf-8"; } + if ("utf-8-sig".equals(e) || "utf8-sig".equals(e)) { + return "utf-8-sig"; + } if ("ascii".equals(e) || "us-ascii".equals(e) || "646".equals(e)) { return "ascii"; } @@ -46,16 +94,108 @@ static String normalize(String encoding) { || "l1".equals(e) || "8859".equals(e) || "cp819".equals(e)) { return "latin-1"; } + if ("utf-16".equals(e) || "utf16".equals(e) || "u16".equals(e)) { + return "utf-16"; + } + if ("utf-16-le".equals(e) || "utf-16le".equals(e)) { + return "utf-16-le"; + } + if ("utf-16-be".equals(e) || "utf-16be".equals(e)) { + return "utf-16-be"; + } + if ("cp437".equals(e) || "437".equals(e) || "ibm437".equals(e)) { + return "cp437"; + } throw Py.error(Py.LOOKUP_ERROR, "unknown encoding: " + encoding); } + /// The UTF-8 bytes a str was decoded from, by the str's identity: what + /// PyPy keeps for every str, since it stores text as UTF-8. Encoding + /// such a str back to UTF-8 then shares the array instead of + /// transcoding it, which is safe because a `bytes` never changes. + private static final class Source { + final String s; + final byte[] b; + + Source(String s, byte[] b) { + this.s = s; + this.b = b; + } + } + + private static final Source[] SOURCES = new Source[256]; + + /// Strings shorter than this are cheaper to encode again than to record. + private static final int SOURCE_MIN = 32; + + private static int sourceSlot(String s) { + int h = System.identityHashCode(s); + h ^= h >>> 16; + h *= 0x45d9f3b; + h ^= h >>> 16; + return h & (SOURCES.length - 1); + } + + /// [#decode] of a `bytes` object's own array, which never changes: a + /// UTF-8 result remembers it for [#encodeShared]. + static String decodeKeep(byte[] b, String encoding, String errors) { + String r = decode(b, encoding, errors); + if (b.length >= SOURCE_MIN && "strict".equals(errors) && "utf-8".equals(normalize(encoding))) { + SOURCES[sourceSlot(r)] = new Source(r, b); + } + return r; + } + + /// [#encode] into a new `bytes` object, which may share its array with + /// the `bytes` the str was decoded from. + static byte[] encodeShared(String s, String encoding, String errors) { + if (s.length() >= SOURCE_MIN) { + Source c = SOURCES[sourceSlot(s)]; + if (c != null && c.s == s && "utf-8".equals(normalize(encoding))) { //NOPMD CompareObjectsWithEquals - identity is meant + return c.b; + } + } + return encode(s, encoding, errors); + } + static byte[] encode(String s, String encoding, String errors) { String enc = normalize(encoding); if ("utf-8".equals(enc)) { - return Utf8.encode(s); + return errors == null || "strict".equals(errors) ? Utf8.encode(s) : encodeUtf8(s, errors); + } + if ("utf-8-sig".equals(enc)) { + byte[] body = Utf8.encode(s); + byte[] out = new byte[body.length + 3]; + out[0] = (byte) 0xef; + out[1] = (byte) 0xbb; + out[2] = (byte) 0xbf; + System.arraycopy(body, 0, out, 3, body.length); + return out; + } + if (enc.startsWith("utf-16")) { + return encodeUtf16(s, enc); + } + if ("cp437".equals(enc)) { + return encodeCp437(s, errors); } int limit = "ascii".equals(enc) ? 0x80 : 0x100; - ByteArrayOutputStream out = new ByteArrayOutputStream(s.length()); + // Text that fits the encoding, which is nearly all of it, is one array + // filled in place. The stream below is for the error handlers, and it + // takes a monitor for every byte written. + int n = s.length(); + byte[] plain = new byte[n]; + int fit = 0; + while (fit < n) { + char c = s.charAt(fit); + if (c >= limit) { + break; + } + plain[fit++] = (byte) c; + } + if (fit == n) { + return plain; + } + ByteArrayOutputStream out = new ByteArrayOutputStream(n); int i = 0; while (i < s.length()) { int cp = Character.codePointAt(s, i); @@ -67,23 +207,69 @@ static byte[] encode(String s, String encoding, String errors) { continue; } else if ("replace".equals(errors)) { out.write('?'); + } else if ("xmlcharrefreplace".equals(errors)) { + writeAscii(out, "&#" + cp + ";"); + } else if ("backslashreplace".equals(errors)) { + String hex = Integer.toHexString(cp); + String pad = cp < 0x100 ? "\\x00" : cp < 0x10000 ? "\\u0000" : "\\U00000000"; + writeAscii(out, pad.substring(0, pad.length() - hex.length()) + hex); } else { - throw Py.error(Py.UNICODE_ENCODE_ERROR, "'" + (limit == 0x80 ? "ascii" : "latin-1") - + "' codec can't encode character '" + escape(cp) + "' in position " - + PyStr.cpIndex(s, pos) + ": ordinal not in range(" + limit + ")"); + int at = PyStr.cpIndex(s, pos); + throw Py.encodeError(limit == 0x80 ? "ascii" : "latin-1", s, at, at + 1, + "ordinal not in range(" + limit + ")"); } } return out.toByteArray(); } + private static void writeAscii(ByteArrayOutputStream out, String s) { + for (int k = 0; k < s.length(); k++) { + out.write(s.charAt(k)); + } + } + static String decode(byte[] b, String encoding, String errors) { String enc = normalize(encoding); if ("utf-8".equals(enc)) { return Utf8.decode(b, errors); } + if ("utf-8-sig".equals(enc)) { + if (b.length >= 3 && (b[0] & 0xff) == 0xef && (b[1] & 0xff) == 0xbb && (b[2] & 0xff) == 0xbf) { + byte[] rest = new byte[b.length - 3]; + System.arraycopy(b, 3, rest, 0, rest.length); + return Utf8.decode(rest, errors); + } + return Utf8.decode(b, errors); + } + if (enc.startsWith("utf-16")) { + return decodeUtf16(b, enc, errors); + } + if ("cp437".equals(enc)) { + StringBuilder sb = new StringBuilder(b.length); + for (byte x : b) { + int c = x & 0xff; + sb.append(c < 0x80 ? (char) c : CP437_HIGH.charAt(c - 0x80)); + } + return sb.toString(); + } boolean ascii = "ascii".equals(enc); + // Latin-1, and ASCII until a byte above 0x7f: one char per byte into + // an array. pdfminer decodes every content stream token this way, and + // a StringBuilder appending char by char was a twentieth of the + // conversion's time. + int at = b.length; + if (ascii) { + at = 0; + while (at < b.length && b[at] >= 0) { + at++; + } + } + if (at == b.length) { + return latin1(b, 0, b.length); + } StringBuilder sb = new StringBuilder(b.length); - for (int i = 0; i < b.length; i++) { + sb.append(latin1(b, 0, at)); + for (int i = at; i < b.length; i++) { int c = b[i] & 0xff; if (ascii && c >= 0x80) { if ("ignore".equals(errors)) { @@ -93,17 +279,173 @@ static String decode(byte[] b, String encoding, String errors) { sb.append('\uFFFD'); continue; } - throw Py.error(Py.UNICODE_DECODE_ERROR, "'ascii' codec can't decode byte 0x" + Integer.toHexString(c) - + " in position " + i + ": ordinal not in range(128)"); + throw Py.decodeError("ascii", b, i, i + 1, "ordinal not in range(128)"); } sb.append((char) c); } return sb.toString(); } + /// UTF-8 under a named error handler. The strict encoder writes a lone + /// surrogate as U+FFFD rather than scan every string for one (see + /// [Utf8#encode]); a caller naming a handler gets what it defines: + /// `surrogatepass` writes the surrogate's own three bytes, + /// `surrogateescape` turns U+DC80..U+DCFF back into the byte it stands + /// for, `ignore` drops it and `replace` writes `?`. + private static byte[] encodeUtf8(String s, String errors) { + int n = s.length(); + ByteArrayOutputStream out = null; + int from = 0; + for (int i = 0; i < n; i++) { + char c = s.charAt(i); + if ((c & 0xf800) != 0xd800) { + continue; + } + if ((c & 0xfc00) == 0xd800 && i + 1 < n && (s.charAt(i + 1) & 0xfc00) == 0xdc00) { + i++; + continue; + } + if (out == null) { + out = new ByteArrayOutputStream(n + 8); + } + byte[] head = Utf8.encode(s.substring(from, i)); + out.write(head, 0, head.length); + from = i + 1; + if ("surrogatepass".equals(errors)) { + out.write(0xe0 | c >> 12); + out.write(0x80 | c >> 6 & 0x3f); + out.write(0x80 | c & 0x3f); + } else if ("surrogateescape".equals(errors) && c >= 0xdc80 && c <= 0xdcff) { + out.write(c & 0xff); + } else if ("replace".equals(errors)) { + out.write('?'); + } else if ("backslashreplace".equals(errors)) { + String hex = Integer.toHexString(c); + out.write('\\'); + out.write('u'); + for (int k = 0; k < hex.length(); k++) { + out.write(hex.charAt(k)); + } + } else if (!"ignore".equals(errors)) { + int at = PyStr.cpIndex(s, i); + throw Py.encodeError("utf-8", s, at, at + 1, "surrogates not allowed"); + } + } + if (out == null) { + return Utf8.encode(s); + } + byte[] tail = Utf8.encode(s.substring(from)); + out.write(tail, 0, tail.length); + return out.toByteArray(); + } + + /// `utf-16` writes a byte order mark and little-endian units, as CPython + /// does on every platform Codename One runs on; the `-le`/`-be` forms + /// write no mark. A Java string is already UTF-16, so a lone surrogate + /// is written as it is, as `surrogatepass` would. + private static byte[] encodeUtf16(String s, String enc) { + boolean big = "utf-16-be".equals(enc); + boolean bom = "utf-16".equals(enc); + byte[] out = new byte[s.length() * 2 + (bom ? 2 : 0)]; + int o = 0; + if (bom) { + out[o++] = (byte) 0xff; + out[o++] = (byte) 0xfe; + } + for (int i = 0; i < s.length(); i++) { + char c = s.charAt(i); + if (big) { + out[o++] = (byte) (c >> 8); + out[o++] = (byte) c; + } else { + out[o++] = (byte) c; + out[o++] = (byte) (c >> 8); + } + } + return out; + } + + /// `utf-16` reads a byte order mark when there is one and takes + /// little-endian otherwise; the `-le`/`-be` forms keep a mark as U+FEFF. + private static String decodeUtf16(byte[] b, String enc, String errors) { + boolean big = "utf-16-be".equals(enc); + int i = 0; + if ("utf-16".equals(enc) && b.length >= 2) { + if ((b[0] & 0xff) == 0xff && (b[1] & 0xff) == 0xfe) { + i = 2; + } else if ((b[0] & 0xff) == 0xfe && (b[1] & 0xff) == 0xff) { + big = true; + i = 2; + } + } + boolean strict = !"replace".equals(errors) && !"ignore".equals(errors); + String name = "utf-16".equals(enc) ? "utf-16-" + (big ? "be" : "le") : enc; + StringBuilder sb = new StringBuilder(b.length / 2); + while (i + 1 < b.length) { + char c = unit(b, i, big); + if (Character.isHighSurrogate(c)) { + if (i + 3 < b.length && Character.isLowSurrogate(unit(b, i + 2, big))) { + sb.append(c).append(unit(b, i + 2, big)); + i += 4; + continue; + } + if (i + 3 >= b.length && strict) { + throw Py.decodeError(name, b, i, b.length, "unexpected end of data"); + } + if (strict) { + throw Py.decodeError(name, b, i, i + 2, "illegal UTF-16 surrogate"); + } + } else if (Character.isLowSurrogate(c)) { + if (strict) { + throw Py.decodeError(name, b, i, i + 2, "illegal encoding"); + } + } else { + sb.append(c); + i += 2; + continue; + } + if ("replace".equals(errors)) { + sb.append('\ufffd'); + } + i += 2; + } + if (i < b.length) { + if (strict) { + throw Py.decodeError(name, b, i, b.length, "truncated data"); + } + if ("replace".equals(errors)) { + sb.append('\ufffd'); + } + } + return sb.toString(); + } + + private static char unit(byte[] b, int i, boolean big) { + int hi = b[big ? i : i + 1] & 0xff; + int lo = b[big ? i + 1 : i] & 0xff; + return (char) (hi << 8 | lo); + } + + private static byte[] encodeCp437(String s, String errors) { + ByteArrayOutputStream out = new ByteArrayOutputStream(s.length()); + for (int i = 0; i < s.length(); i++) { + char c = s.charAt(i); + int at = c < 0x80 ? c : CP437_HIGH.indexOf(c); + if (at >= 0) { + out.write(c < 0x80 ? c : at + 0x80); + } else if ("replace".equals(errors)) { + out.write('?'); + } else if (!"ignore".equals(errors)) { + throw Py.encodeError("charmap", s, PyStr.cpIndex(s, i), PyStr.cpIndex(s, i) + 1, + "character maps to "); + } + } + return out.toByteArray(); + } + /// `repr`'s escape of a code point: backslash-x for Latin-1, backslash-u /// below 0x10000, backslash-U above. - private static String escape(int cp) { + static String escape(int cp) { if (cp < 0x100) { String h = Integer.toHexString(cp); return "\\x" + (h.length() < 2 ? "0" + h : h); diff --git a/maven/python-runtime/src/main/java/com/codename1/python/runtime/EnumMeta.java b/maven/python-runtime/src/main/java/com/codename1/python/runtime/EnumMeta.java new file mode 100644 index 00000000000..97b916f2e03 --- /dev/null +++ b/maven/python-runtime/src/main/java/com/codename1/python/runtime/EnumMeta.java @@ -0,0 +1,195 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.python.runtime; + +import java.util.concurrent.atomic.AtomicReference; + +/// `enum.EnumType`, a builtin metaclass the runtime implements, as `Abc` is +/// for `abc.ABCMeta`. Its class-level protocol -- calling the class looks a +/// value up, iterating it walks the members, `in`, `len`, `[name]`, +/// `__members__`, `repr` -- is written here, over the tables the class keeps +/// (`_member_map_`, `_member_names_`, `_value2member_map_`), which the +/// compiler fills once, member by member, right after the class statement +/// (the transpiler's EnumLowering). Nothing here makes a member or looks +/// one up by a name computed at run time. What a Python metaclass's +/// `__new__` did besides -- the tables themselves -- runs right after the +/// class is made ([#init]), so the class is an ordinary class with a layout. +final class EnumMeta { + private EnumMeta() { + } + + /// The metaclass object `enum.EnumType` is bound to. + static final PyType META = metaType(); + + /// `enum._finish(cls, boundary)`, which sets the class's tables up. + private static final AtomicReference FINISH = new AtomicReference(); + + private static PyType metaType() { + PyType t = new PyType("EnumType", new PyType[] {Py.TYPE_TYPE}, null); + t.dict.put("__module__", "enum"); + t.dict.put("__iter__", PyBuiltin.method1(t, "__iter__", EnumMeta::iterOf)); + t.dict.put("__reversed__", PyBuiltin.method1(t, "__reversed__", EnumMeta::reversedOf)); + t.dict.put("__len__", PyBuiltin.method1(t, "__len__", k -> (long) len((PyType) k))); + t.dict.put("__contains__", PyBuiltin.method2(t, "__contains__", + (k, v) -> Py.bool(contains((PyType) k, v)))); + t.dict.put("__getitem__", PyBuiltin.method2(t, "__getitem__", (k, n) -> getItem((PyType) k, n))); + t.dict.put("__bool__", PyBuiltin.method1(t, "__bool__", k -> Py.bool(true))); + t.dict.put("__repr__", PyBuiltin.method1(t, "__repr__", k -> repr((PyType) k))); + t.dict.put("__members__", new PyProperty(PyBuiltin.fixed1("__members__", + k -> table((PyType) k, "_member_map_").copy()), null, null)); + return t; + } + + /// Whether `k` is made by this metaclass (or a Python one deriving from it). + static boolean governs(PyType k) { + return k.meta != null && k.meta.isSubtype(META); + } + + /// `_cn1op.enum_install(finish)`: keeps `enum._finish` for [#init]. + static Object install(Object finish) { + FINISH.set(finish); + return Py.NONE; + } + + /// Sets up the tables of the class `k` just made, with the + /// `boundary=` keyword of its class statement (None when absent). + static void init(PyType k, Object boundary) { + Object f = FINISH.get(); + if (f != null) { + Py.obj(f).call(new Object[] {k, boundary}, new String[0]); + } + } + + private static PyDict table(PyType k, String name) { + Object t = k.lookup(name); + if (!(t instanceof PyDict)) { + throw Py.typeError("enum " + k.name + " has no " + name); + } + return (PyDict) t; + } + + private static PyList names(PyType k) { + Object t = k.lookup("_member_names_"); + if (!(t instanceof PyList)) { + throw Py.typeError("enum " + k.name + " has no _member_names_"); + } + return (PyList) t; + } + + /// The members of `k`, in definition order. + private static PyList members(PyType k) { + PyList n = names(k); + PyDict map = table(k, "_member_map_"); + PyList out = new PyList(n.size()); + for (int i = 0; i < n.size(); i++) { + out.append(map.getItem(n.get(i))); + } + return out; + } + + static Object iterOf(Object k) { + return Py.iter(members((PyType) k)); + } + + static Object reversedOf(Object k) { + PyList m = members((PyType) k); + PyList out = new PyList(m.size()); + for (int i = m.size() - 1; i >= 0; i--) { + out.append(m.get(i)); + } + return Py.iter(out); + } + + static int len(PyType k) { + return names(k).size(); + } + + static Object getItem(PyType k, Object name) { + return table(k, "_member_map_").getItem(name); + } + + static String repr(PyType k) { + Object flag = k.lookup("_is_flag_"); + return (flag != null && Py.isTrue(flag) ? ""; + } + + static boolean contains(PyType k, Object v) { + if (Py.typeOf(v).isSubtype(k)) { + return true; + } + if (hashable(v) && table(k, "_value2member_map_").getOrNull(v) != null) { + return true; + } + Object u = k.lookup("_unhashable_values_"); + return u instanceof PyList && ((PyList) u).contains(v); + } + + private static boolean hashable(Object v) { + return !(v instanceof PyList) && !(v instanceof PyDict) && !(v instanceof PySet); + } + + /// `cls(value)`: the member whose value is `value`, else what the + /// class's `_missing_` answers. Never makes a member: those are all + /// made once, after the class statement. The functional API + /// (`Color = Enum('Color', 'RED GREEN')`) is lowered to a class statement by the + /// compiler; any form it could not lower is refused. + static Object call(PyType k, Object[] args, String[] kwNames) { + if (args.length != 1 || kwNames.length != 0) { + throw Py.typeError(k.name + "(): the functional enum API is supported only as a module-level" + + " assignment of Enum(name, names), names a string or a list of literals, which the compiler" + + " turns into a class statement"); + } + Object value = args[0]; + if (Py.typeOf(value).isSubtype(k)) { + return value; + } + if (hashable(value)) { + Object m = table(k, "_value2member_map_").getOrNull(value); + if (m != null) { + return m; + } + } + Object result = Py.call(Py.getattr(k, "_missing_"), value); + if (Py.typeOf(result).isSubtype(k)) { + return result; + } + if (result == Py.NONE) { //NOPMD CompareObjectsWithEquals - identity is meant + throw Py.valueError(Py.obj(value).repr() + " is not a valid " + k.name); + } + throw Py.typeError("error in " + k.name + "._missing_: returned " + Py.obj(result).repr() + + " instead of None or a valid member"); + } + + /// `cls.name = value`: refuses to rebind a member to anything else. + static void setAttr(PyType k, String name, Object value) { + Object t = k.lookup("_member_map_"); + if (t instanceof PyDict) { + Object old = ((PyDict) t).getOrNull(name); + if (old != null && old != value) { //NOPMD CompareObjectsWithEquals - identity is meant + throw Py.attributeError("cannot reassign member '" + name + "'"); + } + } + k.setAttrDirect(name, value); + } +} diff --git a/maven/python-runtime/src/main/java/com/codename1/python/runtime/ExceptionGroups.java b/maven/python-runtime/src/main/java/com/codename1/python/runtime/ExceptionGroups.java index 3a40e7deddb..929105d66fd 100644 --- a/maven/python-runtime/src/main/java/com/codename1/python/runtime/ExceptionGroups.java +++ b/maven/python-runtime/src/main/java/com/codename1/python/runtime/ExceptionGroups.java @@ -47,31 +47,30 @@ static void install() { return create((PyType) a[0], a[1], a[2]); }))); b.define("__init__", PyBuiltin.positional("__init__", a -> Py.NONE)); - b.define("__str__", PyBuiltin.positional("__str__", a -> { - int n = exceptions(a[0]).length; - return Py.str(Py.toStr(message(a[0])) + " (" + n + " sub-exception" + (n == 1 ? "" : "s") + ")"); + b.define("__str__", PyBuiltin.fixed1("__str__", a0 -> { + int n = exceptions(a0).length; + return Py.str(Py.toStr(message(a0)) + " (" + n + " sub-exception" + (n == 1 ? "" : "s") + ")"); })); - b.define("split", PyBuiltin.positional("split", a -> { - Object[] r = split(a[0], a[1]); - return new PyTuple(new Object[] {r[0] == null ? Py.NONE : r[0], r[1] == null ? Py.NONE : r[1]}); + b.define("split", PyBuiltin.fixed2("split", (a0, a1) -> { + Object[] r = split(a0, a1); + return Py.tuple(r[0] == null ? Py.NONE : r[0], r[1] == null ? Py.NONE : r[1]); })); - b.define("subgroup", PyBuiltin.positional("subgroup", a -> { - Object m = split(a[0], a[1])[0]; + b.define("subgroup", PyBuiltin.fixed2("subgroup", (a0, a1) -> { + Object m = split(a0, a1)[0]; return m == null ? Py.NONE : m; })); - b.define("derive", PyBuiltin.positional("derive", a -> create(Py.BASE_EXCEPTION_GROUP, message(a[0]), a[1]))); + b.define("derive", PyBuiltin.fixed2("derive", (a0, a1) -> create(Py.BASE_EXCEPTION_GROUP, message(a0), a1))); } static void names(Map names) { - names.put("__cn1_except_star__", PyBuiltin.positional("__cn1_except_star__", a -> new ExceptStar(a[0]))); - names.put("__cn1_except_star_take__", PyBuiltin.positional("__cn1_except_star_take__", - a -> star(a[0]).take(a[1]))); - names.put("__cn1_except_star_raised__", PyBuiltin.positional("__cn1_except_star_raised__", a -> { - star(a[0]).raised.add(a[1]); + names.put("__cn1_except_star__", PyBuiltin.fixed1("__cn1_except_star__", a0 -> new ExceptStar(a0))); + names.put("__cn1_except_star_take__", PyBuiltin.fixed2("__cn1_except_star_take__", (a0, a1) -> star(a0).take(a1))); + names.put("__cn1_except_star_raised__", PyBuiltin.fixed2("__cn1_except_star_raised__", (a0, a1) -> { + star(a0).raised.add(a1); return Py.NONE; })); - names.put("__cn1_except_star_finish__", PyBuiltin.positional("__cn1_except_star_finish__", a -> { - star(a[0]).finish(); + names.put("__cn1_except_star_finish__", PyBuiltin.fixed1("__cn1_except_star_finish__", a0 -> { + star(a0).finish(); return Py.NONE; })); } @@ -106,7 +105,7 @@ static PyInstance create(PyType cls, Object message, Object excs) { throw Py.typeError("Cannot nest BaseExceptions in an ExceptionGroup"); } PyInstance e = cls.newInstance(); - e.setAttrDirect("args", new PyTuple(new Object[] {message, excs})); + e.setAttrDirect("args", Py.tuple(message, excs)); e.setAttrDirect("message", message); e.setAttrDirect("exceptions", new PyTuple(items)); return e; @@ -224,7 +223,7 @@ public PyType type() { } Object take(Object type) { - Object[] ts = type instanceof PyTuple ? ((PyTuple) type).items : new Object[] {type}; + Object[] ts = type instanceof PyTuple ? ((PyTuple) type).arr() : new Object[] {type}; for (Object x : ts) { if (x instanceof PyType && ((PyType) x).isSubtype(Py.BASE_EXCEPTION_GROUP)) { throw Py.typeError("catching ExceptionGroup with except* is not allowed. Use except instead."); diff --git a/maven/python-runtime/src/main/java/com/codename1/python/runtime/ExpatRun.java b/maven/python-runtime/src/main/java/com/codename1/python/runtime/ExpatRun.java new file mode 100644 index 00000000000..1618979628b --- /dev/null +++ b/maven/python-runtime/src/main/java/com/codename1/python/runtime/ExpatRun.java @@ -0,0 +1,702 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.python.runtime; + +import java.util.HashMap; + +/// The common path of `xml.parsers.expat`'s tokenizer, which CPython runs as +/// C. [#run] consumes complete tokens -- text with predefined and character +/// references, start and end tags with namespace processing, comments -- +/// and calls the parser's handlers itself. It stops, without side effects, +/// before the first token it does not take on (a declaration, a processing +/// instruction, CDATA, a general entity, input that is incomplete, anything +/// that is an error) and returns its position; the Python step then handles +/// that one token exactly as before, so errors and their positions stay the +/// Python module's. +/// +/// The parser's settings (`buffer_text`, `ordered_attributes`, +/// `specified_attributes`, `namespace_prefixes`, the separator) are read once +/// per call, as the C parser reads them once per parse; handlers are read at +/// every event, so a handler that replaces another takes effect at once. +final class ExpatRun { + private ExpatRun() { + } + + private static final AttrSite STATE = new AttrSite("_state"); + private static final StoreSite SET_STATE = new StoreSite("_state"); + private static final StoreSite SET_EV = new StoreSite("_ev"); + private static final AttrSite STACK = new AttrSite("_stack"); + private static final AttrSite NS = new AttrSite("_ns"); + private static final StoreSite SET_NS = new StoreSite("_ns"); + private static final AttrSite SEP = new AttrSite("_sep"); + private static final AttrSite TEXT = new AttrSite("_text"); + private static final AttrSite BUFFER_TEXT = new AttrSite("buffer_text"); + private static final AttrSite ORDERED = new AttrSite("ordered_attributes"); + private static final AttrSite SPECIFIED = new AttrSite("specified_attributes"); + private static final AttrSite NS_PREFIXES = new AttrSite("namespace_prefixes"); + private static final AttrSite ATTDEFAULTS = new AttrSite("_attdefaults"); + private static final AttrSite EXPANDING = new AttrSite("_expanding"); + private static final AttrSite FRAGMENT = new AttrSite("_fragment"); + private static final AttrSite H_CHARS = new AttrSite("CharacterDataHandler"); + private static final AttrSite H_START = new AttrSite("StartElementHandler"); + private static final AttrSite H_END = new AttrSite("EndElementHandler"); + private static final AttrSite H_COMMENT = new AttrSite("CommentHandler"); + private static final AttrSite H_START_NS = new AttrSite("StartNamespaceDeclHandler"); + private static final AttrSite H_END_NS = new AttrSite("EndNamespaceDeclHandler"); + + private static final String XML_NS = "http://www.w3.org/XML/1998/namespace"; + private static final String XMLNS_NS = "http://www.w3.org/2000/xmlns/"; + private static final String NL = "\n"; + + /// One call's view of the parser. + private static final class Ctx { + final Object p; + final PyList stack; + final PyList text; + final boolean buffered; + final boolean ordered; + final boolean prefixes; + /// The separator; null without namespace processing. + final String sep; + /// Whether no start tag can be taken (an odd separator or defaults + /// table): every one goes to the Python step. + final boolean noTags; + /// The DTD's attribute defaults, null when none apply. + final PyDict defaults; + Object ns; + int state; + /// Expanded names by qualified name, for the scope [#nameNs]. + final HashMap elemNames = new HashMap(); + final HashMap attrNames = new HashMap(); + Object nameNs; + /// The start tag [#scan] read. + String qname; + String[] an = new String[8]; + String[] av = new String[8]; + int na; + boolean selfClosing; + + Ctx(Object p) { + this.p = p; + Object st = STACK.get(p); + Object tx = TEXT.get(p); + this.stack = st instanceof PyList ? (PyList) st : null; + this.text = tx instanceof PyList ? (PyList) tx : null; + this.buffered = Py.isTrue(BUFFER_TEXT.get(p)); + this.ordered = Py.isTrue(ORDERED.get(p)); + this.prefixes = Py.isTrue(NS_PREFIXES.get(p)); + Object s = SEP.get(p); + this.sep = s instanceof String ? (String) s : null; + this.ns = NS.get(p); + this.state = (int) Typed.toLong(STATE.get(p)); + boolean odd = !isNone(s) && sep == null || sep != null && !(ns instanceof PyDict); + PyDict d = null; + if (!Py.isTrue(SPECIFIED.get(p))) { + Object o = ATTDEFAULTS.get(p); + if (o instanceof PyDict) { + d = ((PyDict) o).size() > 0 ? (PyDict) o : null; + } else { + odd = true; + } + } + this.defaults = d; + this.noTags = odd || stack == null; + } + + void setState(int s) { + state = s; + SET_STATE.set(p, Long.valueOf(s)); + } + + void setNs(Object n) { + ns = n; + SET_NS.set(p, n); + } + + void ev(int pos) { + SET_EV.set(p, Long.valueOf(pos)); + } + } + + static int run(Object p, String buf, int pos) { + Ctx c = new Ctx(p); + int n = buf.length(); + while (pos < n) { + int lt = buf.indexOf('<', pos); + if (lt != pos) { + if (lt < 0) { + return pos; + } + int r = text(c, buf, pos, lt); + if (r < lt) { + return r; + } + pos = lt; + continue; + } + char ch = pos + 1 < n ? buf.charAt(pos + 1) : '\0'; + int r; + if (ch == '/') { + r = endTag(c, buf, pos); + } else if (ch == '!') { + r = comment(c, buf, pos); + } else if (ch == '?') { + return pos; + } else { + r = startTag(c, buf, pos); + } + if (r < 0) { + return pos; + } + pos = r; + } + return pos; + } + + private static boolean isNone(Object o) { + return o == null || o == Py.NONE; //NOPMD CompareObjectsWithEquals - identity is meant + } + + // -- text -------------------------------------------------------------- + + /// Text in `[s, e)`: returns `e`, or the position the Python step must + /// take over at (nothing at or past it has been reported). + private static int text(Ctx c, String buf, int s, int e) { + if (c.state != 1) { + return s; + } + // One pass over the run: where its first reference is, and whether + // it holds "]]>" (an error the Python step reports). Every search is + // bounded by the run; one reaching the end of the buffer made a + // document's parse quadratic. + int firstAmp = -1; + for (int i = s; i < e; i++) { + char ch = buf.charAt(i); + if (ch == '&') { + if (firstAmp < 0) { + firstAmp = i; + } + } else if (ch == '>' && i - s >= 2 && buf.charAt(i - 1) == ']' && buf.charAt(i - 2) == ']') { + return s; + } + } + c.ev(s); + int at = s; + while (true) { + int amp = at == s ? firstAmp : find(buf, '&', at, e); + if (amp < 0) { + chars(c, buf.substring(at, e)); + return e; + } + if (amp > at) { + chars(c, buf.substring(at, amp)); + } + int semi = find(buf, ';', amp + 1, Math.min(e, amp + 12)); + if (semi < 0) { + return amp; + } + String v = reference(buf, amp + 1, semi); + if (v == null) { + return amp; + } + chars(c, v); + at = semi + 1; + } + } + + private static int find(String buf, char c, int s, int e) { + for (int i = s; i < e; i++) { + if (buf.charAt(i) == c) { + return i; + } + } + return -1; + } + + /// The text of the reference between `&` and `;`, or null for one the + /// Python step must see (a general entity, or a malformed reference). + private static String reference(String buf, int s, int e) { + if (s >= e) { + return null; + } + if (buf.charAt(s) != '#') { + switch (e - s) { + case 2: + if (buf.startsWith("lt", s)) { + return "<"; + } + if (buf.startsWith("gt", s)) { + return ">"; + } + return null; + case 3: + return buf.startsWith("amp", s) ? "&" : null; + case 4: + if (buf.startsWith("quot", s)) { + return "\""; + } + if (buf.startsWith("apos", s)) { + return "'"; + } + return null; + default: + return null; + } + } + int i = s + 1; + boolean hex = i < e && buf.charAt(i) == 'x'; + if (hex) { + i++; + } + if (i >= e || e - i > 8) { + return null; + } + int cp = 0; + for (; i < e; i++) { + int d = Character.digit(buf.charAt(i), hex ? 16 : 10); + if (d < 0 || buf.charAt(i) > 'f') { + return null; + } + cp = cp * (hex ? 16 : 10) + d; + } + if (cp == 0 || cp > 0x10FFFF || cp >= 0xD800 && cp <= 0xDFFF || cp == 0xFFFE || cp == 0xFFFF + || cp < 0x20 && cp != 9 && cp != 10 && cp != 13) { + return null; + } + if (cp < 0x10000) { + return String.valueOf((char) cp); + } + int v = cp - 0x10000; + return new String(new char[] {(char) (0xD800 + (v >> 10)), (char) (0xDC00 + (v & 0x3FF))}); + } + + + /// `_chars`: buffered, or one call per line and per line ending. + private static void chars(Ctx c, String s) { + if (s.length() == 0) { + return; + } + if (c.buffered) { + if (c.text != null) { + c.text.append(s); + } else { + Py.callMethod(TEXT.get(c.p), "append", s); + } + return; + } + Object h = H_CHARS.get(c.p); + if (isNone(h)) { + return; + } + int start = 0; + int len = s.length(); + while (true) { + int nl = s.indexOf('\n', start); + if (nl < 0) { + if (start < len) { + Py.call(h, start == 0 ? s : s.substring(start)); + } + return; + } + if (nl > start) { + Py.call(h, s.substring(start, nl)); + } + Py.call(h, NL); + start = nl + 1; + } + } + + /// `_flush`: hands buffered text to the handler. + private static void flush(Ctx c) { + PyList l = c.text; + if (l == null) { + Py.callMethod(c.p, "_flush"); + return; + } + int k = l.size(); + if (k == 0) { + return; + } + String data; + if (k == 1 && l.get(0) instanceof String) { + data = (String) l.get(0); + } else { + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < k; i++) { + sb.append(Typed.asStr(l.get(i))); + } + data = sb.toString(); + } + l.clear(); + Object h = H_CHARS.get(c.p); + if (!isNone(h)) { + Py.call(h, data); + } + } + + // -- comments ---------------------------------------------------------- + + private static int comment(Ctx c, String buf, int pos) { + if (!buf.startsWith("", pos + 4); + if (e < 0) { + return -1; + } + int bad = buf.indexOf("--", pos + 4); + if (bad < e || e - 1 >= pos + 4 && buf.charAt(e - 1) == '-') { + return -1; + } + c.ev(pos); + flush(c); + Object h = H_COMMENT.get(c.p); + if (!isNone(h)) { + Py.call(h, buf.substring(pos + 4, e)); + } + return e + 3; + } + + // -- tags -------------------------------------------------------------- + + private static int endTag(Ctx c, String buf, int pos) { + PyList st = c.stack; + if (st == null) { + return -1; + } + int n = buf.length(); + int i = pos + 2; + int e = XmlScan.name(buf, i, n); + if (e == i) { + return -1; + } + int j = e; + while (j < n && XmlScan.space(buf.charAt(j))) { + j++; + } + if (j >= n || buf.charAt(j) != '>') { + return -1; + } + int k = st.size(); + if (k == 0) { + return -1; + } + Object top = st.get(k - 1); + if (!(top instanceof PyTuple)) { + return -1; + } + Object q = ((PyTuple) top).get(0); + if (!(q instanceof String) || ((String) q).length() != e - i || !buf.startsWith((String) q, i)) { + return -1; + } + c.ev(pos); + closeTop(c); + return j + 1; + } + + /// `_close_top`. + private static void closeTop(Ctx c) { + PyList st = c.stack; + PyTuple top = (PyTuple) st.pop(-1); + flush(c); + Object h = H_END.get(c.p); + if (!isNone(h)) { + Py.call(h, top.get(1)); + } + Object declared = top.get(2); + if (Py.len(declared) > 0) { + h = H_END_NS.get(c.p); + if (!isNone(h)) { + if (declared instanceof PyList) { + PyList d = (PyList) declared; + for (int i = d.size() - 1; i >= 0; i--) { + Py.call(h, ((PyTuple) d.get(i)).get(0)); + } + } + } + } + Object parent = top.get(3); + if (parent != c.ns) { //NOPMD CompareObjectsWithEquals - identity is meant + c.setNs(parent); + } + if (st.size() == 0 && Py.len(EXPANDING.get(c.p)) == 0) { + Object frag = FRAGMENT.getOrMiss(c.p); + if (frag == Py.MISS || !Py.isTrue(frag)) { //NOPMD CompareObjectsWithEquals - identity is meant + c.setState(2); + } + } + } + + /// Reads `` at `pos` into the context, values + /// normalised as `_attr_value` would; -1 for anything off the common path + /// (see [XmlScan#scanStart], which this follows). + private static int scan(Ctx c, String s, int pos) { + int n = s.length(); + int i = pos + 1; + int e = XmlScan.name(s, i, n); + if (e == i) { + return -1; + } + c.qname = s.substring(i, e); + c.na = 0; + i = e; + while (true) { + int ws = i; + while (i < n && XmlScan.space(s.charAt(i))) { + i++; + } + if (i >= n) { + return -1; + } + char ch = s.charAt(i); + if (ch == '>' || ch == '/') { + c.selfClosing = ch == '/'; + if (c.selfClosing) { + if (i + 1 >= n || s.charAt(i + 1) != '>') { + return -1; + } + i++; + } + return i + 1; + } + if (i == ws) { + return -1; + } + int ne = XmlScan.name(s, i, n); + if (ne == i) { + return -1; + } + int ns = i; + i = ne; + while (i < n && XmlScan.space(s.charAt(i))) { + i++; + } + if (i >= n || s.charAt(i) != '=') { + return -1; + } + i++; + while (i < n && XmlScan.space(s.charAt(i))) { + i++; + } + if (i >= n) { + return -1; + } + char q = s.charAt(i); + if (q != '"' && q != '\'') { + return -1; + } + int vs = i + 1; + int ve = s.indexOf(q, vs); + if (ve < 0) { + return -1; + } + boolean norm = false; + for (int k = vs; k < ve; k++) { + char v = s.charAt(k); + if (v == '<' || v == '&') { + return -1; + } + if (v == '\t' || v == '\n' || v == '\r') { + norm = true; + } + } + int len = ne - ns; + for (int k = 0; k < c.na; k++) { + String o = c.an[k]; + if (o.length() == len && s.startsWith(o, ns)) { + return -1; + } + } + String val = s.substring(vs, ve); + if (norm) { + val = val.replace('\t', ' ').replace('\n', ' ').replace('\r', ' '); + } + if (c.na == c.an.length) { + String[] a = new String[c.na * 2]; + String[] b = new String[c.na * 2]; + System.arraycopy(c.an, 0, a, 0, c.na); + System.arraycopy(c.av, 0, b, 0, c.na); + c.an = a; + c.av = b; + } + c.an[c.na] = s.substring(ns, ne); + c.av[c.na] = val; + c.na++; + i = ve + 1; + } + } + + private static int startTag(Ctx c, String buf, int pos) { + if (c.noTags || c.state == 2) { + return -1; + } + int end = scan(c, buf, pos); + if (end < 0) { + return -1; + } + String qname = c.qname; + if (c.defaults != null && c.defaults.getOrNull(qname) != null) { + return -1; + } + Object parentNs = c.ns; + int k = c.na; + Object declared = PyTuple.EMPTY; + PyDict newNs = null; + String name; + if (c.sep != null) { + // Declarations first: they change the scope the names expand in. + PyList decl = null; + for (int i = 0; i < k; i++) { + String an = c.an[i]; + if (!an.startsWith("xmlns") || an.length() > 5 && an.charAt(5) != ':') { + continue; + } + String av = c.av[i]; + String prefix = an.length() > 5 ? an.substring(6) : null; + if ("xmlns".equals(prefix) || "xml".equals(prefix) && !XML_NS.equals(av) + || !"xml".equals(prefix) && (XML_NS.equals(av) || XMLNS_NS.equals(av)) + || prefix != null && av.length() == 0) { + return -1; + } + if (newNs == null) { + newNs = ((PyDict) parentNs).copy(); + decl = Py.list(); + } + newNs.setItem(prefix == null || prefix.length() == 0 ? "" : prefix, av); + decl.append(Py.tuple(prefix == null ? Py.NONE : prefix, av.length() == 0 ? Py.NONE : av)); + } + if (decl != null) { + declared = decl; + } + PyDict scope = newNs != null ? newNs : (PyDict) parentNs; + if (scope != c.nameNs) { //NOPMD CompareObjectsWithEquals - identity is meant + c.nameNs = scope; + c.elemNames.clear(); + c.attrNames.clear(); + } + name = c.elemNames.get(qname); + if (name == null) { + name = expand(scope, qname, true, c.sep, c.prefixes); + if (name == null) { + return -1; + } + c.elemNames.put(qname, name); + } + // Keep the attributes that are not declarations, expanded. + int keep = 0; + for (int i = 0; i < k; i++) { + String an = c.an[i]; + if (an.startsWith("xmlns") && (an.length() == 5 || an.charAt(5) == ':')) { + continue; + } + String en = c.attrNames.get(an); + if (en == null) { + en = expand(scope, an, false, c.sep, c.prefixes); + if (en == null) { + return -1; + } + c.attrNames.put(an, en); + } + for (int j = 0; j < keep; j++) { + if (c.an[j].equals(en)) { + return -1; + } + } + c.an[keep] = en; + c.av[keep] = c.av[i]; + keep++; + } + k = keep; + } else { + name = qname; + } + // Nothing below declines: the token is ours from here. + c.ev(pos); + if (newNs != null) { + c.setNs(newNs); + } + flush(c); + if (declared != PyTuple.EMPTY) { //NOPMD CompareObjectsWithEquals - identity is meant + Object h = H_START_NS.get(c.p); + if (!isNone(h)) { + PyList d = (PyList) declared; + for (int i = 0; i < d.size(); i++) { + PyTuple t = (PyTuple) d.get(i); + Py.call(h, t.get(0), t.get(1)); + } + } + } + if (c.state == 0) { + c.setState(1); + } + Object h = H_START.get(c.p); + if (!isNone(h)) { + Object attrs; + if (c.ordered) { + PyList l = Py.list(); + for (int i = 0; i < k; i++) { + l.append(c.an[i]); + l.append(c.av[i]); + } + attrs = l; + } else { + PyDict d = Py.dict(); + for (int i = 0; i < k; i++) { + d.setItem(c.an[i], c.av[i]); + } + attrs = d; + } + Py.call(h, name, attrs); + } + c.stack.append(Py.tuple(qname, name, declared, parentNs)); + if (c.selfClosing) { + c.ev(pos); + closeTop(c); + } + return end; + } + + /// `_expand_name`, or null where it would raise. + private static String expand(PyDict ns, String qname, boolean element, String sep, boolean prefixes) { + int colon = qname.indexOf(':'); + if (colon < 0) { + if (!element) { + return qname; + } + Object uri = ns.getOrNull(""); + if (!(uri instanceof String) || ((String) uri).length() == 0) { + return uri == null || uri instanceof String || isNone(uri) ? qname : null; + } + return (String) uri + sep + qname; + } + Object uri = ns.getOrNull(qname.substring(0, colon)); + if (!(uri instanceof String)) { + return null; + } + String local = qname.substring(colon + 1); + if (prefixes) { + return (String) uri + sep + local + sep + qname.substring(0, colon); + } + return (String) uri + sep + local; + } +} diff --git a/maven/python-runtime/src/main/java/com/codename1/python/runtime/Formatting.java b/maven/python-runtime/src/main/java/com/codename1/python/runtime/Formatting.java index f3de12fdce9..8ccb14fc964 100644 --- a/maven/python-runtime/src/main/java/com/codename1/python/runtime/Formatting.java +++ b/maven/python-runtime/src/main/java/com/codename1/python/runtime/Formatting.java @@ -121,7 +121,7 @@ static String format(Object v, String spec) { if (v instanceof PyInstance) { Object m = Py.typeOf(v).lookup("__format__"); if (m != null) { - return Py.strValue(Py.obj(m).call(new Object[] {v, Py.str(spec)}, Py.NO_KW), "__format__"); + return Py.strValue(Py.obj(m).call2(v, Py.str(spec)), "__format__"); } if (spec.length() == 0) { return Py.toStr(v); @@ -136,6 +136,19 @@ static String format(Object v, String spec) { } Spec p = Spec.parse(spec); if (Py.isInt(v) && !(v instanceof PyBool && p.type == 0)) { + if ((p.type == 0 || p.type == 'd' || p.type == 'x') && v instanceof Long + && ((Long) v).longValue() != Long.MIN_VALUE) { + // A machine int: its digits straight from the long, where + // formatInt would build a BigInteger for each one. + long l = ((Long) v).longValue(); + boolean neg = l < 0; + long a = neg ? -l : l; + String digits = p.type == 'x' ? Long.toHexString(a) : Long.toString(a); + if (p.grouping != 0) { + digits = group(digits, p.grouping, p.type == 'x' ? 4 : 3); + } + return pad(signOf(neg, p) + (p.type == 'x' && p.alt ? "0x" : ""), digits, p, '>'); + } if (p.type == 0 || "dboxXcn".indexOf(p.type) >= 0) { return formatInt(Py.intView(v), p); } @@ -487,30 +500,245 @@ private static String trimGeneral(String body, boolean alt) { // ---- printf style ---------------------------------------------------- + /// `"lit %s lit %d" % (a, b)` with a literal format and a literal tuple, + /// lowered by the transpiler: `lits` holds the text between the + /// conversions (one more than there are values), `convs` one of `s`, + /// `d` or `i` per value. The values arrive already evaluated, so the + /// order matches CPython, and nothing parses the format at run time. + public static String pct(String[] lits, String convs, Object a) { + return lits[0] + conv(convs.charAt(0), a) + lits[1]; + } + + public static String pct(String[] lits, String convs, Object a, Object b) { + return lits[0] + conv(convs.charAt(0), a) + lits[1] + conv(convs.charAt(1), b) + lits[2]; + } + + public static String pct(String[] lits, String convs, Object a, Object b, Object c) { + return lits[0] + conv(convs.charAt(0), a) + lits[1] + conv(convs.charAt(1), b) + lits[2] + + conv(convs.charAt(2), c) + lits[3]; + } + + public static String pct(String[] lits, String convs, Object a, Object b, Object c, Object d) { + return lits[0] + conv(convs.charAt(0), a) + lits[1] + conv(convs.charAt(1), b) + lits[2] + + conv(convs.charAt(2), c) + lits[3] + conv(convs.charAt(3), d) + lits[4]; + } + + /// One `%s`, `%d` or `%i` conversion of `v`, for the transpiler's + /// concatenation of a literal format whose values are mostly typed. + public static String conv1(char c, Object v) { + return conv(c, v); + } + + private static String conv(char c, Object v) { + if (c == 's') { + return v instanceof String ? (String) v : Py.toStr(v); + } + if (v instanceof Long) { + return Long.toString(((Long) v).longValue()); + } + // Anything else -- a bool, a big int, a float, a subclass -- as the + // general path formats it, with its errors. + return percent(c == 'd' ? "%d" : "%i", Py.tuple(v)); + } + + /// Appends `v` right-aligned in `width` columns, padded with zeros after the sign when + /// `zero` is set and with spaces before it otherwise, as `%0Nd` and `%Nd` do. + private static void padInt(StringBuilder sb, long v, int width, boolean zero) { + String digits = v < 0 ? Long.toString(v).substring(1) : Long.toString(v); + int len = digits.length() + (v < 0 ? 1 : 0); + if (!zero) { + for (int k = len; k < width; k++) { + sb.append(' '); + } + } + if (v < 0) { + sb.append('-'); + } + if (zero) { + for (int k = len; k < width; k++) { + sb.append('0'); + } + } + sb.append(digits); + } + + /// `fmt % args` when every conversion is a bare `%s`, `%d`, `%i` or `%%` of a str or an + /// int, as nearly every one is: formatted with nothing allocated but the result, which is + /// what CPython allocates. Null for anything else, which the general path then formats -- + /// or reports, with the message Python gives. + private static String percentSimple(String fmt, Object args) { + Object[] items = null; + int count; + if (args instanceof PyTuple) { + items = ((PyTuple) args).arr(); + count = items.length; + } else if (args instanceof Long || args instanceof String) { + count = 1; + } else { + return null; + } + // Local on purpose: ParparVM keeps a builder that does not escape on the stack, + // unlocked, where a shared static one is locked on every append. + // Sized from the arguments themselves: markdownify formats whole + // converted subtrees (`'%s%s%s' % (prefix, text, suffix)`), and a + // guess per argument grew -- and copied -- the buffer several times + // on every one of them. + int size = fmt.length(); + for (int k = 0; k < count; k++) { + Object v = items == null ? args : items[k]; + size += v instanceof String ? ((String) v).length() : 20; + } + StringBuilder sb = new StringBuilder(size); + int n = fmt.length(); + int ai = 0; + int i = 0; + while (i < n) { + int pct = fmt.indexOf('%', i); + if (pct < 0) { + sb.append(fmt, i, n); + break; + } + sb.append(fmt, i, pct); + if (pct + 1 >= n) { + return null; + } + char c = fmt.charAt(pct + 1); + i = pct + 2; + if (c == '%') { + sb.append('%'); + continue; + } + if (c != 's' && c != 'd' && c != 'i' || ai >= count) { + return null; + } + Object v = items == null ? args : items[ai]; + ai++; + if (v instanceof Long) { + // %s of an int is its str(), the same digits %d writes. + sb.append(((Long) v).longValue()); + } else if (c == 's' && v instanceof String) { + sb.append((String) v); + } else { + return null; + } + } + if (ai != count) { + return null; + } + return sb.toString(); + } + static String percent(String fmt, Object args) { + String simple = percentSimple(fmt, args); + if (simple != null) { + return simple; + } + return percent(fmt, args, false); + } + + /// `fmt % args` for a bytes format (PEP 461): the format and every + /// bytes-like value are latin-1 chars here, one char per byte, so the + /// str formatter does the work and the result is encoded back. + static PyBytes percentBytes(byte[] fmt, Object args) { + return new PyBytes(latin1Bytes(percent(Codecs.latin1(fmt, 0, fmt.length), args, true))); + } + + /// The chars of a latin-1 text as its bytes, one byte each. + private static byte[] latin1Bytes(String s) { + byte[] out = new byte[s.length()]; + for (int k = 0; k < out.length; k++) { + out[k] = (byte) s.charAt(k); + } + return out; + } + + /// The bytes `%s` and `%b` insert: a bytes-like value, or what its + /// `__bytes__` answers. A str is refused, as CPython refuses it. + private static String bytesArg(Object value) { + byte[] b = PyBytes.like(value); + if (b == null && !(value instanceof String)) { + Object m = Py.obj(value).getAttrOrNull("__bytes__"); + if (m != null) { + b = PyBytes.like(Py.call(m)); + } + } + if (b == null) { + throw Py.typeError("%b requires a bytes-like object, or an object that implements __bytes__, not '" + + Py.typeOf(value).name + "'"); + } + return Codecs.latin1(b, 0, b.length); + } + + private static String percent(String fmt, Object args, boolean bytesMode) { Object[] items; PyDict mapping = null; if (args instanceof PyTuple) { - items = ((PyTuple) args).items; + items = ((PyTuple) args).arr(); + } else if (args instanceof PyInstance && ((PyInstance) args).base instanceof PyTuple) { + // An instance of a tuple subclass (a namedtuple) is itself the argument tuple, + // as in CPython: its items fill the conversions, never its repr. + items = ((PyTuple) ((PyInstance) args).base).arr(); } else { items = new Object[] {args}; if (args instanceof PyDict) { mapping = (PyDict) args; } } - StringBuilder sb = new StringBuilder(); - int ai = 0; int n = fmt.length(); + StringBuilder sb = new StringBuilder(n + 16 * items.length); + int ai = 0; for (int i = 0; i < n; i++) { char c = fmt.charAt(i); if (c != '%') { - sb.append(c); + // The literal run up to the next %, in one append: each append + // takes the builder's lock. + int pct = fmt.indexOf('%', i); + int stop = pct < 0 ? n : pct; + sb.append(fmt, i, stop); + i = stop - 1; continue; } i++; if (i >= n) { throw Py.valueError("incomplete format"); } + // A bare %s, %d or %i of a str or an int, as nearly every one is: + // appended directly. The general path below builds a spec string + // for format() to parse again, and took ints through BigInteger. + char quick = fmt.charAt(i); + if ((quick == 's' || quick == 'd' || quick == 'i') && mapping == null && ai < items.length) { + Object v = items[ai]; + // In a bytes format %s takes no int, so only %d and %i come here. + if (v instanceof Long && !(bytesMode && quick == 's')) { + sb.append(((Long) v).longValue()); + ai++; + continue; + } + if (quick == 's' && v instanceof String && !bytesMode) { + sb.append((String) v); + ai++; + continue; + } + } + // %Nd and %0Nd of an int, the other common spelling (dates, ids): padded here + // rather than through a spec string format() would parse again. + if (mapping == null && ai < items.length && items[ai] instanceof Long) { + int j = i; + boolean zero = j < n && fmt.charAt(j) == '0'; + if (zero) { + j++; + } + int width = 0; + while (j < n && j - i < 4 && fmt.charAt(j) >= '0' && fmt.charAt(j) <= '9') { + width = width * 10 + fmt.charAt(j++) - '0'; + } + if (j < n && (fmt.charAt(j) == 'd' || fmt.charAt(j) == 'i')) { + padInt(sb, ((Long) items[ai]).longValue(), width, zero); + ai++; + i = j; + continue; + } + } Object value = null; if (fmt.charAt(i) == '(') { int close = fmt.indexOf(')', i); @@ -518,7 +746,8 @@ static String percent(String fmt, Object args) { if (mapping == null) { throw Py.typeError("format requires a mapping"); } - value = mapping.getItem(Py.str(key)); + // A bytes format names bytes keys: b"%(k)s" reads b"k". + value = mapping.getItem(bytesMode ? new PyBytes(latin1Bytes(key)) : Py.str(key)); i = close + 1; } StringBuilder spec = new StringBuilder(); @@ -577,6 +806,26 @@ static String percent(String fmt, Object args) { String align = left ? "<" : ""; // printf-style padding right-justifies text too, unlike format(). String textAlign = left ? "<" : ">"; + if (bytesMode && (conv == 's' || conv == 'b')) { + sb.append(format(Py.str(bytesArg(value)), textAlign + width + prec)); + continue; + } + if (bytesMode && (conv == 'r' || conv == 'a')) { + // %r is %a in a bytes format: repr() limited to ASCII. + sb.append(format(Py.call(Builtins.ASCII, value), textAlign + width + prec)); + continue; + } + if (bytesMode && conv == 'c') { + byte[] one = PyBytes.like(value); + if (one != null && one.length == 1) { + sb.append((char) (one[0] & 0xff)); + } else if (Py.isInt(value) && Py.asLong(value) >= 0 && Py.asLong(value) < 256) { + sb.append((char) Py.asLong(value)); + } else { + throw Py.typeError("%c requires an integer in range(256) or a single byte"); + } + continue; + } switch (conv) { case 's': sb.append(format(Py.str(Py.toStr(value)), textAlign + width + prec)); diff --git a/maven/python-runtime/src/main/java/com/codename1/python/runtime/Functools.java b/maven/python-runtime/src/main/java/com/codename1/python/runtime/Functools.java new file mode 100644 index 00000000000..5429da99f95 --- /dev/null +++ b/maven/python-runtime/src/main/java/com/codename1/python/runtime/Functools.java @@ -0,0 +1,316 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.python.runtime; + +/// `_cn1functools`: the parts of `functools` CPython implements in C. The +/// `lru_cache` decorator stays Python, as in CPython, and wraps the function +/// in [LruWrapper] -- the equivalent of C's `_lru_cache_wrapper`, which was a +/// Python closure here: an argument tuple, a `_make_key` call and a pop and +/// re-insert per hit, on functions such as charset_normalizer's per-character +/// `_char_info`. +final class Functools { + + private Functools() { + } + + static boolean provide(String name) { + if (!"_cn1functools".equals(name)) { + return false; + } + PyModule m = new PyModule("_cn1functools", new String[0]); + m.setAttr("_lru_cache_wrapper", PyBuiltin.positional("_lru_cache_wrapper", a -> { + if (a.length != 4) { + throw Py.typeError("_lru_cache_wrapper expected 4 arguments, got " + a.length); + } + if (!Builtins.isCallable(a[0])) { + throw Py.typeError("the first argument must be callable"); + } + long max; + if (a[1] == Py.NONE) { //NOPMD CompareObjectsWithEquals - identity is meant + max = -1; + } else { + max = Math.max(0, Py.index(a[1])); + } + return new LruWrapper(Py.obj(a[0]), max, Py.isTrue(a[2]), a[3]); + })); + PyModule.registerModule(m); + return true; + } + + /// The marker between positional and keyword arguments in a key. + private static final Object KW_MARK = new PyObject() { + @Override + public PyType type() { + return Py.OBJECT_TYPE; + } + }; + + static final PyType LRU_TYPE = lruType(); + + private static PyType lruType() { + PyType t = new PyType("_lru_cache_wrapper", new PyType[] {Py.OBJECT_TYPE}, (ty, a, k) -> { + throw Py.typeError("cannot create 'functools._lru_cache_wrapper' instances"); + }); + t.define("__module__", "functools"); + t.define("cache_info", PyBuiltin.method1(t, "cache_info", s -> ((LruWrapper) s).info())); + t.define("cache_clear", PyBuiltin.method1(t, "cache_clear", s -> { + ((LruWrapper) s).clear(); + return Py.NONE; + })); + t.define("__copy__", PyBuiltin.method1(t, "__copy__", s -> s)); + t.define("__deepcopy__", PyBuiltin.method2(t, "__deepcopy__", (s, memo) -> s)); + return t; + } + + /// A node of the bounded cache's recency list; the root's `next` is the + /// least recently used. + private static final class Link { + Link prev; + Link next; + Object key; + Object result; + } + + static final class LruWrapper extends PyObject { + private final PyObject fn; + /// -1 when unbounded. + private final long maxsize; + private final boolean typed; + private final Object infoType; + /// key to result when unbounded, key to [Link] when bounded. + private final PyDict cache = new PyDict(); + private final Link root = new Link(); + private long hits; + private long misses; + private PyDict attrs; + + LruWrapper(PyObject fn, long maxsize, boolean typed, Object infoType) { + this.fn = fn; + this.maxsize = maxsize; + this.typed = typed; + this.infoType = infoType; + root.prev = root; + root.next = root; + } + + @Override + public PyType type() { + return LRU_TYPE; + } + + Object info() { + return Py.obj(infoType).call(new Object[] {PyInt.of(hits), PyInt.of(misses), + maxsize < 0 ? Py.NONE : PyInt.of(maxsize), PyInt.of(cache.len())}, Py.NO_KW); + } + + void clear() { + cache.clear(); + root.prev = root; + root.next = root; + hits = 0; + misses = 0; + } + + /// CPython's `lru_cache_make_key`: a lone `int` or `str` argument is + /// its own key; otherwise the positional arguments, then a marker and + /// the keyword pairs, then (typed) every argument's type. + private Object key(Object[] a, String[] kw) { + int npos = a.length - kw.length; + if (kw.length == 0 && !typed) { + if (npos == 1 && (a[0] instanceof Long || a[0] instanceof String)) { + return a[0]; + } + return PyTuple.of(a.clone()); + } + int n = npos + (kw.length == 0 ? 0 : 1 + 2 * kw.length) + (typed ? a.length : 0); + Object[] k = new Object[n]; + System.arraycopy(a, 0, k, 0, npos); + int j = npos; + if (kw.length != 0) { + k[j++] = KW_MARK; + for (int i = 0; i < kw.length; i++) { + k[j++] = kw[i]; + k[j++] = a[npos + i]; + } + } + if (typed) { + for (Object v : a) { + k[j++] = Py.typeOf(v); + } + } + return PyTuple.of(k); + } + + private Object key1(Object a) { + if (!typed && (a instanceof Long || a instanceof String)) { + return a; + } + return typed ? PyTuple.of(a, Py.typeOf(a)) : PyTuple.of(a); + } + + @Override + public Object call(Object[] args, String[] kwNames) { + if (maxsize == 0) { + misses++; + return fn.call(args, kwNames); + } + Object k = key(args, kwNames); + Object hit = lookup(k); + if (hit != null) { + return hit; + } + misses++; + return store(k, fn.call(args, kwNames)); + } + + @Override + public Object call0() { + return call(Py.NO_ARGS, Py.NO_KW); + } + + @Override + public Object call1(Object a) { + if (maxsize == 0) { + misses++; + return fn.call1(a); + } + Object k = key1(a); + Object hit = lookup(k); + if (hit != null) { + return hit; + } + misses++; + return store(k, fn.call1(a)); + } + + @Override + public Object call2(Object a, Object b) { + if (maxsize == 0 || typed) { + return call(new Object[] {a, b}, Py.NO_KW); + } + Object k = Py.tuple(a, b); + Object hit = lookup(k); + if (hit != null) { + return hit; + } + misses++; + return store(k, fn.call2(a, b)); + } + + /// The cached result, counted as a hit, or null. + private Object lookup(Object k) { + // Hashed here rather than by the dict, whose message would name + // the key tuple: CPython reports only the unhashable argument. + long h = k instanceof Long || k instanceof String ? Py.keyHash(k, "") : Py.obj(k).hash(); + Object v = cache.getOrNullHashed(k, h); + if (v == null) { + return null; + } + hits++; + if (maxsize < 0) { + return v; + } + Link l = (Link) v; + if (root.prev != l) { //NOPMD CompareObjectsWithEquals - identity is meant + l.prev.next = l.next; + l.next.prev = l.prev; + l.prev = root.prev; + l.next = root; + root.prev.next = l; + root.prev = l; + } + return l.result; + } + + /// CPython's insertion: a call that cached its own key while it ran + /// keeps that entry; a full cache gives its oldest link to the new key. + private Object store(Object k, Object result) { + if (maxsize < 0) { + cache.setItem(k, result); + return result; + } + if (cache.getOrNull(k) != null) { + return result; + } + Link l; + if (cache.len() >= maxsize) { + l = root.next; + l.prev.next = l.next; + l.next.prev = l.prev; + cache.delItem(l.key); + } else { + l = new Link(); + } + l.key = k; + l.result = result; + l.prev = root.prev; + l.next = root; + root.prev.next = l; + root.prev = l; + cache.setItem(k, l); + return result; + } + + @Override + public Object bind(Object self) { + return new PyMethod(self, this); + } + + @Override + public Object getAttrOrNull(String name) { + if (attrs != null) { + Object v = attrs.getOrNull(name); + if (v != null) { + return v; + } + } + if ("__dict__".equals(name)) { + if (attrs == null) { + attrs = new PyDict(); + } + return attrs; + } + if ("__wrapped__".equals(name)) { + return fn; + } + return super.getAttrOrNull(name); + } + + @Override + public void setAttr(String name, Object value) { + if (attrs == null) { + attrs = new PyDict(); + } + attrs.setItem(name, value); + } + + @Override + public void delAttr(String name) { + if (attrs == null || !attrs.contains(name)) { + throw Py.attributeError("'functools._lru_cache_wrapper' object has no attribute '" + name + "'"); + } + attrs.delItem(name); + } + } +} diff --git a/maven/python-runtime/src/main/java/com/codename1/python/runtime/Gil.java b/maven/python-runtime/src/main/java/com/codename1/python/runtime/Gil.java index 5c4beccbbe9..0fabf78191e 100644 --- a/maven/python-runtime/src/main/java/com/codename1/python/runtime/Gil.java +++ b/maven/python-runtime/src/main/java/com/codename1/python/runtime/Gil.java @@ -119,18 +119,21 @@ public static void enter() { } private static void acquire(long me) { - if (OWNER.compareAndSet(0, me)) { - return; - } - WAITERS.incrementAndGet(); - try { - int attempt = 0; - while (!OWNER.compareAndSet(0, me)) { - pauseWaiter(HANDOFF.get() > 0 ? 0 : attempt++); + if (!OWNER.compareAndSet(0, me)) { + WAITERS.incrementAndGet(); + try { + int attempt = 0; + while (!OWNER.compareAndSet(0, me)) { + pauseWaiter(HANDOFF.get() > 0 ? 0 : attempt++); + } + } finally { + WAITERS.decrementAndGet(); } - } finally { - WAITERS.decrementAndGet(); } + // Per-thread interpreter state is switched here, once per hand-over, + // so that Python code reads it from a static rather than a ThreadLocal + // on every use. + Typed.adoptThread(); } /// One step aside for a thread waiting on something another thread diff --git a/maven/python-runtime/src/main/java/com/codename1/python/runtime/Hashing.java b/maven/python-runtime/src/main/java/com/codename1/python/runtime/Hashing.java index 59a7f94774d..191aff32248 100644 --- a/maven/python-runtime/src/main/java/com/codename1/python/runtime/Hashing.java +++ b/maven/python-runtime/src/main/java/com/codename1/python/runtime/Hashing.java @@ -116,6 +116,23 @@ static long ofDouble(double v, Object identity) { } /// The xxHash-based tuple hash of CPython 3.8+. + /// [#ofTuple(Object[])] read through the tuple itself: a fixed-size tuple + /// ([PyTuple] T2..T6) keeps its items in fields, and asking it for an array + /// first copied them into a new one for every hash -- a tuple used as a dict + /// key or a set member is hashed on every lookup. + static long ofTuple(PyTuple t) { + int n = t.size(); + long acc = XXPRIME_5; + for (int i = 0; i < n; i++) { + long lane = Py.hashOf(t.get(i)); + acc += lane * XXPRIME_2; + acc = (acc << 31) | (acc >>> 33); + acc *= XXPRIME_1; + } + acc += n ^ (XXPRIME_5 ^ 3527539L); + return acc == -1 ? 1546275796L : acc; + } + static long ofTuple(Object[] items) { long acc = XXPRIME_5; for (Object item : items) { diff --git a/maven/python-runtime/src/main/java/com/codename1/python/runtime/HeapqBisect.java b/maven/python-runtime/src/main/java/com/codename1/python/runtime/HeapqBisect.java new file mode 100644 index 00000000000..658c2afd8df --- /dev/null +++ b/maven/python-runtime/src/main/java/com/codename1/python/runtime/HeapqBisect.java @@ -0,0 +1,336 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.python.runtime; + +/// `_cn1heapq` and `_cn1bisect`: the heap and bisection primitives CPython +/// implements in C (`_heapq`, `_bisect`). `heapq.merge`, `nlargest` and +/// `nsmallest` stay Python, as they are in CPython. Each algorithm is the C +/// module's, so a heap of objects with a user `__lt__` sees the same +/// comparisons in the same order; and as there, a comparison that changes +/// the list's size is an error rather than a read past its end. +final class HeapqBisect { + + private HeapqBisect() { + } + + static boolean provide(String name) { + if ("_cn1heapq".equals(name)) { + PyModule.registerModule(heapq()); + return true; + } + if ("_cn1bisect".equals(name)) { + PyModule.registerModule(bisect()); + return true; + } + return false; + } + + private static PyList list(String fn, Object o) { + if (!(o instanceof PyList)) { + throw Py.typeError(fn + "() argument 1 must be list, not " + Py.typeOf(o).name); + } + return (PyList) o; + } + + private static PyException changed() { + return Py.runtimeError("list changed size during iteration"); + } + + /// `a < b` (or `b < a` for a max-heap) on two slots, checking that the + /// comparison left the list as long as it was. + private static boolean less(PyList h, int n, Object a, Object b) { + boolean r = Py.ltBool(a, b); + if (h.size != n) { + throw changed(); + } + return r; + } + + /// CPython's `siftdown`: moves the item at `pos` up towards `start`. + private static void up(PyList h, int start, int pos, boolean max) { + int n = h.size; + Object item = h.items[pos]; + while (pos > start) { + int parent = (pos - 1) >> 1; + Object p = h.items[parent]; + if (!(max ? less(h, n, p, item) : less(h, n, item, p))) { + break; + } + Object[] it = h.items; + it[pos] = it[parent]; + pos = parent; + } + h.items[pos] = item; + } + + /// CPython's `siftup`: the smaller child moves up to the leaf, then the + /// displaced item sifts back. + private static void down(PyList h, int pos, boolean max) { + int end = h.size; + int start = pos; + Object item = h.items[pos]; + int child = 2 * pos + 1; + while (child < end) { + int right = child + 1; + if (right < end) { + Object[] it = h.items; + boolean pickLeft = max ? less(h, end, it[right], it[child]) : less(h, end, it[child], it[right]); + if (!pickLeft) { + child = right; + } + } + Object[] it = h.items; + it[pos] = it[child]; + pos = child; + child = 2 * pos + 1; + } + h.items[pos] = item; + up(h, start, pos, max); + } + + private static Object push(String fn, Object heap, Object item, boolean max) { + PyList h = list(fn, heap); + h.append(item); + h.objects(); + up(h, 0, h.size - 1, max); + return Py.NONE; + } + + private static Object pop(String fn, Object heap, boolean max) { + PyList h = list(fn, heap); + if (h.size == 0) { + throw Py.indexError("index out of range"); + } + Object[] it = h.objects(); + int last = --h.size; + Object lastItem = it[last]; + it[last] = null; + if (last == 0) { + return lastItem; + } + Object top = it[0]; + it[0] = lastItem; + down(h, 0, max); + return top; + } + + private static Object replace(String fn, Object heap, Object item, boolean max) { + PyList h = list(fn, heap); + if (h.size == 0) { + throw Py.indexError("index out of range"); + } + Object[] it = h.objects(); + Object top = it[0]; + it[0] = item; + down(h, 0, max); + return top; + } + + private static Object pushPop(String fn, Object heap, Object item, boolean max) { + PyList h = list(fn, heap); + if (h.size == 0) { + return item; + } + Object[] it = h.objects(); + Object top = it[0]; + int n = h.size; + if (!(max ? less(h, n, item, top) : less(h, n, top, item))) { + return item; + } + if (h.size == 0) { + throw Py.indexError("index out of range"); + } + top = h.items[0]; + h.items[0] = item; + down(h, 0, max); + return top; + } + + private static Object heapify(String fn, Object heap, boolean max) { + PyList h = list(fn, heap); + h.objects(); + for (int i = h.size / 2 - 1; i >= 0; i--) { + down(h, i, max); + } + return Py.NONE; + } + + private static PyModule heapq() { + PyModule m = new PyModule("_cn1heapq", new String[0]); + m.setAttr("heappush", PyBuiltin.fixed2("heappush", (h, x) -> push("heappush", h, x, false))); + m.setAttr("heappop", PyBuiltin.fixed1("heappop", h -> pop("heappop", h, false))); + m.setAttr("heapreplace", PyBuiltin.fixed2("heapreplace", (h, x) -> replace("heapreplace", h, x, false))); + m.setAttr("heappushpop", PyBuiltin.fixed2("heappushpop", (h, x) -> pushPop("heappushpop", h, x, false))); + m.setAttr("heapify", PyBuiltin.fixed1("heapify", h -> heapify("heapify", h, false))); + m.setAttr("heappush_max", PyBuiltin.fixed2("heappush_max", (h, x) -> push("heappush_max", h, x, true))); + m.setAttr("heappop_max", PyBuiltin.fixed1("heappop_max", h -> pop("heappop_max", h, true))); + m.setAttr("heapreplace_max", PyBuiltin.fixed2("heapreplace_max", + (h, x) -> replace("heapreplace_max", h, x, true))); + m.setAttr("heappushpop_max", PyBuiltin.fixed2("heappushpop_max", + (h, x) -> pushPop("heappushpop_max", h, x, true))); + m.setAttr("heapify_max", PyBuiltin.fixed1("heapify_max", h -> heapify("heapify_max", h, true))); + return m; + } + + /// `x < a[i]` (right) or `a[i] < x` (left) over any sequence; a list is + /// read in place, bounds checked every step since `key` may shrink it. + private static long search(Object a, Object x, long lo, long hi, Object key, boolean right) { + if (lo < 0) { + throw Py.valueError("lo must be non-negative"); + } + PyObject k = key == Py.NONE ? null : Py.obj(key); //NOPMD CompareObjectsWithEquals - identity is meant + if (hi == -1) { + hi = a instanceof PyList ? ((PyList) a).size : Py.len(a); + } + PyList l = a instanceof PyList ? (PyList) a : null; + if (l != null && k == null && x instanceof Long && l.ints != null && hi <= l.size) { + // A list of small ints and an int probe: no comparison can run + // user code, so the search reads the unboxed array directly. + int[] v = l.ints; + long t = ((Long) x).longValue(); + int ilo = (int) lo; + int ihi = (int) hi; + while (ilo < ihi) { + int mid = (ilo + ihi) >>> 1; + if (right ? t < v[mid] : v[mid] < t) { + if (right) { + ihi = mid; + } else { + ilo = mid + 1; + } + } else if (right) { + ilo = mid + 1; + } else { + ihi = mid; + } + } + return ilo; + } + if (l != null && k == null && l.ints == null && l.floats == null) { + return searchObjects(l, x, lo, hi, right); + } + while (lo < hi) { + long mid = (lo + hi) >>> 1; + Object v; + if (l != null) { + if (mid >= l.size) { + throw Py.indexError("list index out of range"); + } + v = l.get((int) mid); + } else { + v = Py.getitem(a, mid); + } + if (k != null) { + v = k.call1(v); + } + if (right ? Py.ltBool(x, v) : Py.ltBool(v, x)) { + if (right) { + hi = mid; + } else { + lo = mid + 1; + } + } else if (right) { + lo = mid + 1; + } else { + hi = mid; + } + } + return lo; + } + + /// [#search] over a list of objects with no key: the array and length + /// stay in locals, and are read again only after a comparison that + /// could have run Python code. + private static long searchObjects(PyList l, Object x, long lo, long hi, boolean right) { + Object[] it = l.items; + int n = l.size; + boolean xl = x instanceof Long; + long t = xl ? ((Long) x).longValue() : 0; + int ilo = (int) lo; + int ihi = (int) Math.min(hi, Integer.MAX_VALUE); + while (ilo < ihi) { + int mid = (ilo + ihi) >>> 1; + if (mid >= n) { + throw Py.indexError("list index out of range"); + } + Object v = it[mid]; + boolean before; + if (xl && v instanceof Long) { + long e = ((Long) v).longValue(); + before = right ? t < e : e < t; + } else { + before = right ? Py.ltBool(x, v) : Py.ltBool(v, x); + if (l.ints != null || l.floats != null) { + l.objects(); + } + it = l.items; + n = l.size; + } + if (before == right) { + ihi = mid; + } else { + ilo = mid + 1; + } + } + return ilo; + } + + private static final String[] NAMES = {"a", "x", "lo", "hi", "key"}; + + private static PyBuiltin searcher(final String fn, final boolean right, final boolean insert) { + return new PyBuiltin(fn, (a, kw) -> { + Args args = new Args(fn, a, kw).check(4, NAMES); + Object seq = args.required(0, "a"); + Object x = args.required(1, "x"); + long lo = Py.index(args.get(2, "lo", PyInt.of(0))); + Object hiArg = args.get(3, "hi", Py.NONE); + long hi = hiArg == Py.NONE ? -1 : Py.index(hiArg); //NOPMD CompareObjectsWithEquals - identity is meant + Object key = args.get(-1, "key", Py.NONE); + return run(seq, x, lo, hi, key, right, insert); + }).with2((seq, x) -> run(seq, x, 0, -1, Py.NONE, right, insert)); + } + + private static Object run(Object seq, Object x, long lo, long hi, Object key, boolean right, boolean insert) { + if (!insert) { + return PyInt.of(search(seq, x, lo, hi, key, right)); + } + Object probe = key == Py.NONE ? x : Py.obj(key).call1(x); //NOPMD CompareObjectsWithEquals - identity is meant + long i = search(seq, probe, lo, hi, key, right); + if (seq.getClass() == PyList.class) { + ((PyList) seq).insert(i, x); + } else { + Py.callMethod(seq, "insert", PyInt.of(i), x); + } + return Py.NONE; + } + + private static PyModule bisect() { + PyModule m = new PyModule("_cn1bisect", new String[0]); + m.setAttr("bisect_left", searcher("bisect_left", false, false)); + m.setAttr("bisect_right", searcher("bisect_right", true, false)); + m.setAttr("insort_left", searcher("insort_left", false, true)); + m.setAttr("insort_right", searcher("insort_right", true, true)); + return m; + } +} diff --git a/maven/python-runtime/src/main/java/com/codename1/python/runtime/ItemWalk.java b/maven/python-runtime/src/main/java/com/codename1/python/runtime/ItemWalk.java new file mode 100644 index 00000000000..9ac0167f2b1 --- /dev/null +++ b/maven/python-runtime/src/main/java/com/codename1/python/runtime/ItemWalk.java @@ -0,0 +1,121 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.python.runtime; + +/// `for k, v in d.items()`, in a statement or a comprehension, without an +/// items view, an iterator or a tuple per entry. +/// +/// The generated code takes it only where the loop target is exactly two +/// names, so nothing can keep the pair: each step returns the walk itself, +/// and [Py#unpackNames] hands back [#current], which the generated code reads +/// at once, as it reads a tuple's own items. A plain dict is walked over its entry +/// arrays with the same size check its iterator makes. Anything else -- a dict +/// subclass, which may override `items`, or any object with an `items` method +/// -- has `items()` called as written, and each item unpacked as before. +public final class ItemWalk extends PyObject { + private final Object[] pair = new Object[2]; + /// The pair of the last step: [#pair], or a tuple's own items. + Object[] current; + private final PyDict dict; + private final int startSize; + private final PyObject it; + /// A dict that is a view of something else (an instance's `__dict__`), + /// walked through its iteration hooks as its own items() would be. + private final boolean view; + private int at; + + private ItemWalk(PyDict dict, PyObject it, boolean view) { + this.dict = dict; + this.it = it; + this.view = view; + this.startSize = dict != null ? dict.size : 0; + } + + /// The walk over `o.items()`. + public static ItemWalk of(Object o) { + if (o instanceof PyDict && o.getClass() == PyDict.class) { + return new ItemWalk((PyDict) o, null, false); + } + if (o instanceof PyDict && ((PyDict) o).walkAsView()) { + // As PyDict.iterate does: brought up to date first, then each + // step through syncStep and valueAt -- no items() lookup and + // no tuple per entry. + PyDict d = (PyDict) o; + d.sync(); + return new ItemWalk(d, null, true); + } + return new ItemWalk(null, Py.iter(Py.call(Py.getattr(o, "items"))), false); + } + + @Override + public PyType type() { + return Py.ITERATOR_TYPE; + } + + @Override + public Object iter() { + return this; + } + + @Override + public Object next() { + PyDict d = dict; + if (d == null) { + Object v = it.next(); + if (v == null) { + return null; + } + current = v instanceof PyTuple && ((PyTuple) v).arr().length == 2 ? ((PyTuple) v).arr() + : Py.unpack(v, 2); + return this; + } + if (view) { + Object[] ks = d.keys; + int u = d.used; + int j = at; + while (j < u && ks[j] == null) { + j++; + } + d.syncStep(j >= u); + } + if (d.size != startSize) { + throw Py.runtimeError("dictionary changed size during iteration"); + } + Object[] keys = d.keys; + int used = d.used; + int i = at; + while (i < used && keys[i] == null) { + i++; + } + if (i >= used) { + return null; + } + at = i + 1; + Object[] p = pair; + p[0] = keys[i]; + p[1] = view ? d.valueAt(i) : d.values[i]; + current = p; + return this; + } +} diff --git a/maven/python-runtime/src/main/java/com/codename1/python/runtime/Itertools.java b/maven/python-runtime/src/main/java/com/codename1/python/runtime/Itertools.java new file mode 100644 index 00000000000..4afd2c693ef --- /dev/null +++ b/maven/python-runtime/src/main/java/com/codename1/python/runtime/Itertools.java @@ -0,0 +1,1062 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.python.runtime; + +/// `_cn1itertools`: the `itertools` module, which CPython implements in C. +/// It was Python here -- a generator per iterator, `groupby` a class whose +/// grouper re-entered `_fetch` through attribute sites per item -- and +/// pdfplumber's word extraction spent a quarter of its time in it. Each +/// callable is a type, as in CPython (`chain.from_iterable` is an attribute +/// of one), and each algorithm is the C module's: the same items consumed, +/// in the same order, with the same errors. +final class Itertools { + + private Itertools() { + } + + static PyModule module() { + PyModule m = new PyModule("_cn1itertools", new String[0]); + m.setAttr("count", type("count", (t, a, k) -> { + Object[] v = kwArgs("count", a, k, 2, new String[] {"start", "step"}, + new Object[] {PyInt.of(0), PyInt.of(1)}); + return new Count(t, number(v[0]), number(v[1])); + })); + m.setAttr("cycle", type("cycle", (t, a, k) -> new Cycle(t, Py.iter(positional("cycle", a, k, 1, 1)[0])))); + m.setAttr("repeat", type("repeat", (t, a, k) -> { + Object[] v = kwArgs("repeat", a, k, 2, new String[] {"object", "times"}, new Object[] {null, Py.NONE}); + long times = v[1] == Py.NONE ? -1 : Math.max(0, Py.index(v[1])); //NOPMD CompareObjectsWithEquals - identity is meant + return new Repeat(t, v[0], times); + })); + m.setAttr("accumulate", type("accumulate", (t, a, k) -> { + Object[] v = kwArgs("accumulate", a, k, 2, new String[] {"iterable", "func", "initial"}, + new Object[] {null, Py.NONE, Py.NONE}); + return new Accumulate(t, Py.iter(v[0]), v[1] == Py.NONE ? null : Py.obj(v[1]), v[2]); //NOPMD CompareObjectsWithEquals - identity is meant + })); + m.setAttr("batched", type("batched", (t, a, k) -> { + Object[] v = kwArgs("batched", a, k, 2, new String[] {"iterable", "n", "strict"}, + new Object[] {null, null, Py.FALSE}); + long n = Py.index(v[1]); + if (n < 1) { + throw Py.valueError("n must be at least one"); + } + return new Batched(t, Py.iter(v[0]), (int) Math.min(n, Integer.MAX_VALUE - 8), Py.isTrue(v[2])); + })); + PyType chain = type("chain", (t, a, k) -> { + noKeywords("chain", k); + return new Chain(t, a, null); + }); + chain.define("from_iterable", new PyClassMethod(PyBuiltin.fixed2("from_iterable", + (cls, src) -> new Chain((PyType) cls, null, Py.iter(src))))); + m.setAttr("chain", chain); + m.setAttr("compress", type("compress", (t, a, k) -> { + Object[] v = kwArgs("compress", a, k, 2, new String[] {"data", "selectors"}, new Object[] {null, null}); + return new Compress(t, Py.iter(v[0]), Py.iter(v[1])); + })); + m.setAttr("dropwhile", type("dropwhile", (t, a, k) -> { + Object[] v = positional("dropwhile", a, k, 2, 2); + return new Predicate(t, Py.obj(v[0]), Py.iter(v[1]), Predicate.DROP); + })); + m.setAttr("takewhile", type("takewhile", (t, a, k) -> { + Object[] v = positional("takewhile", a, k, 2, 2); + return new Predicate(t, Py.obj(v[0]), Py.iter(v[1]), Predicate.TAKE); + })); + m.setAttr("filterfalse", type("filterfalse", (t, a, k) -> { + Object[] v = positional("filterfalse", a, k, 2, 2); + return new Predicate(t, v[0] == Py.NONE ? null : Py.obj(v[0]), Py.iter(v[1]), Predicate.FALSE); //NOPMD CompareObjectsWithEquals - identity is meant + })); + final PyType grouper = type("_grouper", (t, a, k) -> { + throw Py.typeError("cannot create '_grouper' instances"); + }); + m.setAttr("groupby", type("groupby", (t, a, k) -> { + Object[] v = kwArgs("groupby", a, k, 2, new String[] {"iterable", "key"}, new Object[] {null, Py.NONE}); + return new GroupBy(t, grouper, Py.iter(v[0]), v[1] == Py.NONE ? null : Py.obj(v[1])); //NOPMD CompareObjectsWithEquals - identity is meant + })); + m.setAttr("islice", type("islice", Itertools::islice)); + m.setAttr("pairwise", type("pairwise", (t, a, k) -> new Pairwise(t, Py.iter(positional("pairwise", a, k, 1, 1)[0])))); + m.setAttr("starmap", type("starmap", (t, a, k) -> { + Object[] v = positional("starmap", a, k, 2, 2); + return new Starmap(t, Py.obj(v[0]), Py.iter(v[1])); + })); + final PyType tee = type("_tee", (t, a, k) -> new Tee(t, new TeeData(Py.iter(positional("_tee", a, k, 1, 1)[0])), 0)); + tee.define("__copy__", PyBuiltin.method1(tee, "__copy__", s -> ((Tee) s).copy())); + m.setAttr("_tee", tee); + m.setAttr("tee", PyBuiltin.positional("tee", a -> { + positional("tee", a, Py.NO_KW, 1, 2); + long n = a.length > 1 ? Py.index(a[1]) : 2; + if (n < 0) { + throw Py.valueError("n must be >= 0"); + } + Object[] r = new Object[(int) n]; + if (n == 0) { + return PyTuple.EMPTY; + } + Tee first = a[0] instanceof Tee ? ((Tee) a[0]).copy() : new Tee(tee, new TeeData(Py.iter(a[0])), 0); + r[0] = first; + for (int i = 1; i < r.length; i++) { + r[i] = first.copy(); + } + return new PyTuple(r); + })); + m.setAttr("zip_longest", type("zip_longest", (t, a, k) -> { + Object fill = Py.NONE; + int npos = a.length - k.length; + for (int i = 0; i < k.length; i++) { + if (!"fillvalue".equals(k[i])) { + // CPython 3.14 names no argument here. + throw Py.typeError("zip_longest() got an unexpected keyword argument"); + } + fill = a[npos + i]; + } + PyObject[] its = new PyObject[npos]; + for (int i = 0; i < npos; i++) { + its[i] = Py.iter(a[i]); + } + return new ZipLongest(t, its, fill); + })); + m.setAttr("product", type("product", (t, a, k) -> { + long repeat = 1; + int npos = a.length - k.length; + if (k.length > 1) { + throw Py.typeError("product() takes at most 1 keyword argument (" + k.length + " given)"); + } + for (int i = 0; i < k.length; i++) { + if (!"repeat".equals(k[i])) { + throw Py.typeError("product() got an unexpected keyword argument '" + k[i] + "'"); + } + repeat = Py.index(a[npos + i]); + } + if (repeat < 0) { + throw Py.valueError("repeat argument cannot be negative"); + } + Object[][] given = new Object[npos][]; + for (int i = 0; i < npos; i++) { + given[i] = Py.toArray(a[i]).clone(); + } + Object[][] pools = new Object[(int) (npos * repeat)][]; + for (int i = 0; i < pools.length; i++) { + pools[i] = given[i % Math.max(1, npos)]; + } + return new Product(t, pools); + })); + m.setAttr("permutations", type("permutations", (t, a, k) -> { + Object[] v = kwArgs("permutations", a, k, 2, new String[] {"iterable", "r"}, new Object[] {null, Py.NONE}); + Object[] pool = Py.toArray(v[0]).clone(); + long r = v[1] == Py.NONE ? pool.length : Py.index(v[1]); //NOPMD CompareObjectsWithEquals - identity is meant + return new Combinatoric(t, pool, nonNegative(r), Combinatoric.PERMUTATIONS); + })); + m.setAttr("combinations", type("combinations", (t, a, k) -> { + Object[] v = kwArgs("combinations", a, k, 2, new String[] {"iterable", "r"}, new Object[] {null, null}); + return new Combinatoric(t, Py.toArray(v[0]).clone(), nonNegative(Py.index(v[1])), Combinatoric.COMBINATIONS); + })); + m.setAttr("combinations_with_replacement", type("combinations_with_replacement", (t, a, k) -> { + Object[] v = kwArgs("combinations_with_replacement", a, k, 2, new String[] {"iterable", "r"}, + new Object[] {null, null}); + return new Combinatoric(t, Py.toArray(v[0]).clone(), nonNegative(Py.index(v[1])), Combinatoric.REPLACEMENT); + })); + return m; + } + + // ---- types and arguments ------------------------------------------------- + + /// An itertools type: instances iterate themselves through `next()`, + /// and `__iter__`/`__next__` are there for code that names them. + private static PyType type(String name, PyType.Factory f) { + PyType t = new PyType(name, new PyType[] {Py.OBJECT_TYPE}, f); + t.define("__module__", "itertools"); + t.define("__iter__", PyBuiltin.method1(t, "__iter__", s -> s)); + t.define("__next__", PyBuiltin.method1(t, "__next__", s -> { + Object v = ((PyObject) s).next(); + if (v == null) { + throw Py.raise(Py.STOP_ITERATION); + } + return v; + })); + return t; + } + + private static void noKeywords(String fn, String[] kw) { + if (kw.length != 0) { + throw Py.typeError(fn + "() takes no keyword arguments"); + } + } + + /// Exactly `min`..`max` positional arguments and no keywords. + private static Object[] positional(String fn, Object[] a, String[] kw, int min, int max) { + noKeywords(fn, kw); + if (a.length < min || a.length > max) { + throw Py.typeError(fn + " expected " + (min == max ? "" : a.length < min ? "at least " : "at most ") + + (a.length < min ? min : max) + ((a.length < min ? min : max) == 1 ? " argument" : " arguments") + + ", got " + a.length); + } + return a; + } + + /// Up to `maxPos` positional arguments, then keywords by name; a null + /// default makes the parameter required. Names past `maxPos` are + /// keyword only. + private static Object[] kwArgs(String fn, Object[] a, String[] kw, int maxPos, String[] names, Object[] defaults) { + int npos = a.length - kw.length; + if (npos > maxPos && names.length > maxPos) { + // A function with keyword-only parameters words it as CPython's + // argument clinic does: batched's n is required, accumulate's + // func is not. + throw Py.typeError(fn + "() takes " + (defaults[maxPos - 1] == null ? "exactly " : "at most ") + maxPos + + " positional arguments (" + npos + " given)"); + } + Args args = new Args(fn, a, kw).check(maxPos, names); + Object[] r = new Object[names.length]; + for (int i = 0; i < names.length; i++) { + int pos = i < maxPos ? i : -1; + r[i] = defaults[i] == null ? args.required(pos, names[i]) : args.get(pos, names[i], defaults[i]); + } + return r; + } + + private static Object number(Object o) { + if (o instanceof String || o instanceof PyBytes || o instanceof PyList || o instanceof PyTuple + || o instanceof PyDict || o == Py.NONE) { //NOPMD CompareObjectsWithEquals - identity is meant + throw Py.typeError("a number is required"); + } + return o; + } + + private static int nonNegative(long r) { + if (r < 0) { + throw Py.valueError("r must be non-negative"); + } + return (int) Math.min(r, Integer.MAX_VALUE); + } + + /// A tuple of `src[idx[0..n)]`. + private static PyTuple pick(Object[] src, int[] idx, int n) { + Object[] r = new Object[n]; + for (int i = 0; i < n; i++) { + r[i] = src[idx[i]]; + } + return new PyTuple(r); + } + + /// The base of every iterator here: its type, and itself as its iterator. + private abstract static class It extends PyObject { + private final PyType t; + + It(PyType t) { + this.t = t; + } + + @Override + public final PyType type() { + return t; + } + + @Override + public final Object iter() { + return this; + } + } + + // ---- infinite ------------------------------------------------------------ + + private static final class Count extends It { + private Object n; + private final Object step; + + Count(PyType t, Object start, Object step) { + super(t); + this.n = start; + this.step = step; + } + + @Override + public Object next() { + Object r = n; + n = Py.add(r, step); + return r; + } + + @Override + public String repr() { + boolean unit = step instanceof Long && ((Long) step).longValue() == 1; + return "count(" + Py.toRepr(n) + (unit ? "" : ", " + Py.toRepr(step)) + ")"; + } + } + + private static final class Cycle extends It { + private PyObject it; + private Object[] saved = new Object[8]; + private int size; + private int pos; + + Cycle(PyType t, PyObject it) { + super(t); + this.it = it; + } + + @Override + public Object next() { + if (it != null) { + Object v = it.next(); + if (v != null) { + if (size == saved.length) { + Object[] g = new Object[size * 2]; + System.arraycopy(saved, 0, g, 0, size); + saved = g; + } + saved[size++] = v; + return v; + } + it = null; + } + if (size == 0) { + return null; + } + Object v = saved[pos]; + pos = pos + 1 == size ? 0 : pos + 1; + return v; + } + } + + private static final class Repeat extends It { + private final Object value; + /// Remaining, or -1 for forever. + private long times; + + Repeat(PyType t, Object value, long times) { + super(t); + this.value = value; + this.times = times; + } + + @Override + public Object next() { + if (times < 0) { + return value; + } + if (times == 0) { + return null; + } + times--; + return value; + } + + @Override + public String repr() { + return "repeat(" + Py.toRepr(value) + (times < 0 ? "" : ", " + times) + ")"; + } + } + + // ---- terminating on the shortest input ---------------------------------- + + private static final class Accumulate extends It { + private final PyObject it; + private final PyObject func; + private Object initial; + private Object total; + + Accumulate(PyType t, PyObject it, PyObject func, Object initial) { + super(t); + this.it = it; + this.func = func; + this.initial = initial; + } + + @Override + public Object next() { + if (initial != Py.NONE) { //NOPMD CompareObjectsWithEquals - identity is meant + total = initial; + initial = Py.NONE; + return total; + } + Object x = it.next(); + if (x == null) { + return null; + } + Object s = total; + total = s == null ? x : func == null ? Py.add(s, x) : func.call2(s, x); + return total; + } + } + + private static final class Batched extends It { + private PyObject it; + private final int n; + private final boolean strict; + + Batched(PyType t, PyObject it, int n, boolean strict) { + super(t); + this.it = it; + this.n = n; + this.strict = strict; + } + + @Override + public Object next() { + PyObject src = it; + if (src == null) { + return null; + } + Object[] b = new Object[Math.min(n, 64)]; + int k = 0; + while (k < n) { + Object v = src.next(); + if (v == null) { + it = null; + break; + } + if (k == b.length) { + Object[] g = new Object[(int) Math.min((long) n, (long) k * 2)]; + System.arraycopy(b, 0, g, 0, k); + b = g; + } + b[k++] = v; + } + if (k == 0) { + return null; + } + if (strict && k != n) { + throw Py.valueError("batched(): incomplete batch"); + } + if (k != b.length) { + Object[] e = new Object[k]; + System.arraycopy(b, 0, e, 0, k); + b = e; + } + return new PyTuple(b); + } + } + + private static final class Chain extends It { + private Object[] sources; + private PyObject sourceIt; + private int i; + private PyObject cur; + + Chain(PyType t, Object[] sources, PyObject sourceIt) { + super(t); + this.sources = sources; + this.sourceIt = sourceIt; + } + + @Override + public Object next() { + while (true) { + PyObject c = cur; + if (c != null) { + Object v = c.next(); + if (v != null) { + return v; + } + cur = null; + } + if (sources != null) { + if (i >= sources.length) { + sources = null; + return null; + } + cur = Py.iter(sources[i++]); + } else if (sourceIt != null) { + Object s = sourceIt.next(); + if (s == null) { + sourceIt = null; + return null; + } + cur = Py.iter(s); + } else { + return null; + } + } + } + } + + private static final class Compress extends It { + private final PyObject data; + private final PyObject selectors; + + Compress(PyType t, PyObject data, PyObject selectors) { + super(t); + this.data = data; + this.selectors = selectors; + } + + @Override + public Object next() { + while (true) { + Object d = data.next(); + if (d == null) { + return null; + } + Object s = selectors.next(); + if (s == null) { + return null; + } + if (Py.isTrue(s)) { + return d; + } + } + } + } + + /// dropwhile, takewhile and filterfalse: one predicate over one input. + private static final class Predicate extends It { + static final int DROP = 0; + static final int TAKE = 1; + static final int FALSE = 2; + private final PyObject fn; + private final PyObject it; + private final int kind; + /// dropwhile: still dropping. takewhile: stopped. + private boolean flag; + + Predicate(PyType t, PyObject fn, PyObject it, int kind) { + super(t); + this.fn = fn; + this.it = it; + this.kind = kind; + this.flag = kind == DROP; + } + + @Override + public Object next() { + if (kind == TAKE && flag) { + return null; + } + while (true) { + Object v = it.next(); + if (v == null) { + return null; + } + if (kind == DROP) { + if (!flag || !Py.isTrue(fn.call1(v))) { + flag = false; + return v; + } + } else if (kind == TAKE) { + if (Py.isTrue(fn.call1(v))) { + return v; + } + flag = true; + return null; + } else if (!Py.isTrue(fn == null ? v : fn.call1(v))) { + return v; + } + } + } + } + + /// groupby, as CPython's: the key of the current item and the item, a + /// target key, and the one grouper still allowed to read. + private static final class GroupBy extends It { + private final PyType grouperType; + private final PyObject it; + private final PyObject key; + Object currKey; + Object currValue; + private Object tgtKey; + Grouper currGrouper; + + GroupBy(PyType t, PyType grouperType, PyObject it, PyObject key) { + super(t); + this.grouperType = grouperType; + this.it = it; + this.key = key; + } + + /// Reads the next item and its key; false at the end. + boolean step() { + Object v = it.next(); + if (v == null) { + return false; + } + Object k = key == null ? v : key.call1(v); + currValue = v; + currKey = k; + return true; + } + + @Override + public Object next() { + currGrouper = null; + while (true) { + if (currKey != null) { + if (tgtKey == null || !Py.eqBool(tgtKey, currKey)) { + break; + } + } + if (!step()) { + return null; + } + } + tgtKey = currKey; + Grouper g = new Grouper(grouperType, this, tgtKey); + currGrouper = g; + return Py.tuple(currKey, g); + } + } + + private static final class Grouper extends It { + private final GroupBy parent; + private final Object tgtKey; + + Grouper(PyType t, GroupBy parent, Object tgtKey) { + super(t); + this.parent = parent; + this.tgtKey = tgtKey; + } + + @Override + public Object next() { + GroupBy p = parent; + if (p.currGrouper != this) { //NOPMD CompareObjectsWithEquals - identity is meant + return null; + } + if (p.currValue == null && !p.step()) { + return null; + } + if (!Py.eqBool(tgtKey, p.currKey)) { + return null; + } + Object r = p.currValue; + p.currValue = null; + p.currKey = null; + return r; + } + } + + private static Object islice(PyType t, Object[] a, String[] kw) { + positional("islice", a, kw, 2, 4); + long start = 0; + long stop; + long step = 1; + if (a.length == 2) { + stop = sliceIndex(a[1], -1, "Stop argument for islice() must be None or an integer: 0 <= x <= sys.maxsize."); + } else { + String m = "Indices for islice() must be None or an integer: 0 <= x <= sys.maxsize."; + start = sliceIndex(a[1], 0, m); + stop = sliceIndex(a[2], -1, m); + if (a.length == 4) { + step = a[3] == Py.NONE ? 1 : Py.typeOf(a[3]).lookup("__index__") == null ? 0 : Py.index(a[3]); //NOPMD CompareObjectsWithEquals - identity is meant + if (step < 1) { + throw Py.valueError("Step for islice() must be a positive integer or None."); + } + } + } + return new Islice(t, Py.iter(a[0]), start, stop, step); + } + + private static long sliceIndex(Object v, long none, String message) { + if (v == Py.NONE) { //NOPMD CompareObjectsWithEquals - identity is meant + return none; + } + if (Py.typeOf(v).lookup("__index__") == null) { + throw Py.valueError(message); + } + long r = Py.index(v); + if (r < 0) { + throw Py.valueError(message); + } + return r; + } + + private static final class Islice extends It { + private PyObject it; + private long next; + private final long stop; + private final long step; + private long cnt; + + Islice(PyType t, PyObject it, long start, long stop, long step) { + super(t); + this.it = it; + this.next = start; + this.stop = stop; + this.step = step; + } + + @Override + public Object next() { + PyObject src = it; + if (src == null) { + return null; + } + while (cnt < next) { + if (src.next() == null) { + it = null; + return null; + } + cnt++; + } + if (stop != -1 && cnt >= stop) { + it = null; + return null; + } + Object v = src.next(); + if (v == null) { + it = null; + return null; + } + cnt++; + long old = next; + next += step; + if (next < old || stop != -1 && next > stop) { + next = stop; + } + return v; + } + } + + private static final class Pairwise extends It { + private PyObject it; + private Object old; + + Pairwise(PyType t, PyObject it) { + super(t); + this.it = it; + } + + @Override + public Object next() { + PyObject src = it; + if (src == null) { + return null; + } + if (old == null) { + old = src.next(); + if (old == null) { + it = null; + return null; + } + } + Object n = src.next(); + if (n == null) { + it = null; + old = null; + return null; + } + PyTuple r = Py.tuple(old, n); + old = n; + return r; + } + } + + private static final class Starmap extends It { + private final PyObject fn; + private final PyObject it; + + Starmap(PyType t, PyObject fn, PyObject it) { + super(t); + this.fn = fn; + this.it = it; + } + + @Override + public Object next() { + Object row = it.next(); + if (row == null) { + return null; + } + Object[] a = Py.toArray(row); + switch (a.length) { + case 0: + return fn.call0(); + case 1: + return fn.call1(a[0]); + case 2: + return fn.call2(a[0], a[1]); + case 3: + return fn.call3(a[0], a[1], a[2]); + default: + return fn.call(a.clone(), Py.NO_KW); + } + } + } + + /// The values a set of tee iterators share: blocks of what was read, + /// each linked to the next, dropped once every iterator is past it. + private static final class TeeData { + static final int CELLS = 57; + final PyObject it; + final Object[] values = new Object[CELLS]; + int n; + TeeData next; + boolean running; + + TeeData(PyObject it) { + this.it = it; + } + + TeeData nextLink() { + if (next == null) { + next = new TeeData(it); + } + return next; + } + + Object get(int i) { + if (i < n) { + return values[i]; + } + if (running) { + throw Py.runtimeError("cannot re-enter the tee iterator"); + } + running = true; + Object v; + try { + v = it.next(); + } finally { + running = false; + } + if (v == null) { + return null; + } + values[n++] = v; + return v; + } + } + + private static final class Tee extends It { + private TeeData data; + private int index; + + Tee(PyType t, TeeData data, int index) { + super(t); + this.data = data; + this.index = index; + } + + Tee copy() { + return new Tee(type(), data, index); + } + + @Override + public Object next() { + if (index >= TeeData.CELLS) { + data = data.nextLink(); + index = 0; + } + Object v = data.get(index); + if (v != null) { + index++; + } + return v; + } + } + + private static final class ZipLongest extends It { + private final PyObject[] its; + private final Object fill; + private int active; + + ZipLongest(PyType t, PyObject[] its, Object fill) { + super(t); + this.its = its; + this.fill = fill; + this.active = its.length; + } + + @Override + public Object next() { + if (active == 0) { + return null; + } + Object[] r = new Object[its.length]; + for (int i = 0; i < its.length; i++) { + PyObject s = its[i]; + Object v; + if (s == null) { + v = fill; + } else { + v = s.next(); + if (v == null) { + active--; + if (active == 0) { + return null; + } + its[i] = null; + v = fill; + } + } + r[i] = v; + } + return new PyTuple(r); + } + } + + // ---- combinatoric -------------------------------------------------------- + + private static final class Product extends It { + private final Object[][] pools; + private final int[] indices; + private boolean started; + private boolean stopped; + + Product(PyType t, Object[][] pools) { + super(t); + this.pools = pools; + this.indices = new int[pools.length]; + } + + @Override + public Object next() { + if (stopped) { + return null; + } + int n = pools.length; + if (!started) { + started = true; + for (int i = 0; i < n; i++) { + if (pools[i].length == 0) { + stopped = true; + return null; + } + } + } else { + int i = n - 1; + while (i >= 0) { + indices[i]++; + if (indices[i] < pools[i].length) { + break; + } + indices[i] = 0; + i--; + } + if (i < 0) { + stopped = true; + return null; + } + } + Object[] r = new Object[n]; + for (int i = 0; i < n; i++) { + r[i] = pools[i][indices[i]]; + } + return new PyTuple(r); + } + } + + /// permutations, combinations and combinations_with_replacement, each the + /// documented equivalent's index walk. + private static final class Combinatoric extends It { + static final int PERMUTATIONS = 0; + static final int COMBINATIONS = 1; + static final int REPLACEMENT = 2; + private final Object[] pool; + private final int r; + private final int kind; + private final int[] indices; + private final int[] cycles; + private boolean started; + private boolean stopped; + + Combinatoric(PyType t, Object[] pool, int r, int kind) { + super(t); + this.pool = pool; + this.r = r; + this.kind = kind; + int n = pool.length; + if (kind == PERMUTATIONS) { + indices = new int[n]; + cycles = new int[Math.min(r, n)]; + for (int i = 0; i < n; i++) { + indices[i] = i; + } + for (int i = 0; i < cycles.length; i++) { + cycles[i] = n - i; + } + stopped = r > n; + } else if (kind == COMBINATIONS) { + indices = new int[Math.min(r, n)]; + cycles = null; + for (int i = 0; i < indices.length; i++) { + indices[i] = i; + } + stopped = r > n; + } else { + indices = new int[r]; + cycles = null; + stopped = n == 0 && r > 0; + } + } + + @Override + public Object next() { + if (stopped) { + return null; + } + if (!started) { + started = true; + return pick(pool, indices, r); + } + int n = pool.length; + if (kind == PERMUTATIONS) { + if (n == 0) { + stopped = true; + return null; + } + for (int i = r - 1; i >= 0; i--) { + cycles[i]--; + if (cycles[i] == 0) { + int first = indices[i]; + System.arraycopy(indices, i + 1, indices, i, n - i - 1); + indices[n - 1] = first; + cycles[i] = n - i; + } else { + int j = cycles[i]; + int tmp = indices[i]; + indices[i] = indices[n - j]; + indices[n - j] = tmp; + return pick(pool, indices, r); + } + } + stopped = true; + return null; + } + int i = r - 1; + if (kind == COMBINATIONS) { + while (i >= 0 && indices[i] == i + n - r) { + i--; + } + if (i < 0) { + stopped = true; + return null; + } + indices[i]++; + for (int j = i + 1; j < r; j++) { + indices[j] = indices[j - 1] + 1; + } + return pick(pool, indices, r); + } + while (i >= 0 && indices[i] == n - 1) { + i--; + } + if (i < 0) { + stopped = true; + return null; + } + int v = indices[i] + 1; + for (int j = i; j < r; j++) { + indices[j] = v; + } + return pick(pool, indices, r); + } + } +} diff --git a/maven/python-runtime/src/main/java/com/codename1/python/runtime/KeySite.java b/maven/python-runtime/src/main/java/com/codename1/python/runtime/KeySite.java new file mode 100644 index 00000000000..e21207ec8d7 --- /dev/null +++ b/maven/python-runtime/src/main/java/com/codename1/python/runtime/KeySite.java @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.python.runtime; + +/// The inline cache of one `d["key"]` read with a str literal key: the +/// layout ([PyDict.Layout]) last seen there and the slot of the key in it. +/// A dict on that layout answers with one identity compare and an array +/// load; anything else takes [Py#getitemS]. +public final class KeySite { + private final String key; + private PyDict.Layout layout; + private int slot; + + public KeySite(String key) { + this.key = key.intern(); + } + + /// One site per name of `names`, joined by newlines. + public static KeySite[] table(String names) { + String[] each = Py.names(names); + KeySite[] out = new KeySite[each.length]; + for (int i = 0; i < each.length; i++) { + out[i] = new KeySite(each[i]); + } + return out; + } + + public Object get(Object o) { + if (o instanceof PyDict) { + PyDict d = (PyDict) o; + PyDict.Layout l = d.layout; + if (l != null) { + if (l == layout) { //NOPMD CompareObjectsWithEquals - identity is meant + return d.values[slot]; + } + return miss(d, l); + } + } + return Py.getitemS(o, key); + } + + private Object miss(PyDict d, PyDict.Layout l) { + int e = l.slotOf(key); + if (e < 0 || d.type() != Py.DICT_TYPE) { //NOPMD CompareObjectsWithEquals - identity is meant + return Py.getitemS(d, key); + } + layout = l; + slot = e; + return d.values[e]; + } +} diff --git a/maven/python-runtime/src/main/java/com/codename1/python/runtime/MathFunctions.java b/maven/python-runtime/src/main/java/com/codename1/python/runtime/MathFunctions.java index b448acdf6f4..fbbcf29639e 100644 --- a/maven/python-runtime/src/main/java/com/codename1/python/runtime/MathFunctions.java +++ b/maven/python-runtime/src/main/java/com/codename1/python/runtime/MathFunctions.java @@ -463,10 +463,10 @@ static void install(final PyModule m) { fn(m, "erfc", Erf::erfc); fn(m, "gamma", MathFunctions::gamma, "expected a noninteger or positive integer, got %s"); fn(m, "lgamma", MathFunctions::lgamma, "expected a noninteger or positive integer, got %s"); - m.setAttr("frexp", PyBuiltin.positional("frexp", a -> { - double x = Py.asDouble(a[0]); + m.setAttr("frexp", PyBuiltin.fixed1("frexp", a0 -> { + double x = Py.asDouble(a0); if (x == 0 || Double.isNaN(x) || Double.isInfinite(x)) { - return new PyTuple(new Object[] {Py.ofFloat(x), PyInt.of(0)}); + return Py.tuple(Py.ofFloat(x), PyInt.of(0)); } int e = 0; double ax = Math.abs(x); @@ -484,14 +484,14 @@ static void install(final PyModule m) { } e += be - 1022; double mant = Double.longBitsToDouble((bits & 0x800fffffffffffffL) | (1022L << 52)); - return new PyTuple(new Object[] {Py.ofFloat(x < 0 ? -mant : mant), PyInt.of(e)}); + return Py.tuple(Py.ofFloat(x < 0 ? -mant : mant), PyInt.of(e)); })); - m.setAttr("ldexp", PyBuiltin.positional("ldexp", a -> { - if (!Py.isInt(a[1])) { + m.setAttr("ldexp", PyBuiltin.fixed2("ldexp", (a0, a1) -> { + if (!Py.isInt(a1)) { throw Py.typeError("Expected an int as second argument to ldexp."); } - double x = Py.asDouble(a[0]); - Object e = a[1]; + double x = Py.asDouble(a0); + Object e = a1; long n; com.codename1.util.BigInteger big = Py.intView(e).toBig(); if (big.bitLength() > 62) { @@ -505,26 +505,26 @@ static void install(final PyModule m) { } return Py.ofFloat(r); })); - m.setAttr("modf", PyBuiltin.positional("modf", a -> { - double x = Py.asDouble(a[0]); + m.setAttr("modf", PyBuiltin.fixed1("modf", a0 -> { + double x = Py.asDouble(a0); if (Double.isInfinite(x)) { - return new PyTuple(new Object[] {Py.ofFloat(x > 0 ? 0.0 : -0.0), Py.ofFloat(x)}); + return Py.tuple(Py.ofFloat(x > 0 ? 0.0 : -0.0), Py.ofFloat(x)); } double ip = x < 0 ? Math.ceil(x) : Math.floor(x); double fp = x - ip; if (fp == 0 && x < 0 || (x == 0 && 1 / x < 0)) { fp = -0.0; } - return new PyTuple(new Object[] {Py.ofFloat(fp), Py.ofFloat(ip)}); + return Py.tuple(Py.ofFloat(fp), Py.ofFloat(ip)); })); - m.setAttr("fma", PyBuiltin.positional("fma", a -> { + m.setAttr("fma", PyBuiltin.fixed3("fma", (a0, a1, a2) -> { // Not fused: device class libraries have no exact fma. - double r = Py.asDouble(a[0]) * Py.asDouble(a[1]) + Py.asDouble(a[2]); + double r = Py.asDouble(a0) * Py.asDouble(a1) + Py.asDouble(a2); return Py.ofFloat(r); })); - m.setAttr("remainder", PyBuiltin.positional("remainder", a -> { - double x = Py.asDouble(a[0]); - double y = Py.asDouble(a[1]); + m.setAttr("remainder", PyBuiltin.fixed2("remainder", (a0, a1) -> { + double x = Py.asDouble(a0); + double y = Py.asDouble(a1); double r = remainder(x, y); if (Double.isNaN(r) && !Double.isNaN(x) && !Double.isNaN(y)) { throw Py.valueError("math domain error"); @@ -555,9 +555,9 @@ static void install(final PyModule m) { return Py.ofFloat(y > x ? nextUp(x) : nextDown(x)); })); fn(m, "ulp", MathFunctions::ulp); - m.setAttr("dist", PyBuiltin.positional("dist", a -> { - Object[] p = Py.toArray(a[0]); - Object[] q = Py.toArray(a[1]); + m.setAttr("dist", PyBuiltin.fixed2("dist", (a0, a1) -> { + Object[] p = Py.toArray(a0); + Object[] q = Py.toArray(a1); if (p.length != q.length) { throw Py.valueError("both points must have the same number of dimensions"); } @@ -611,9 +611,9 @@ static void install(final PyModule m) { } return PyInt.of(r); })); - m.setAttr("sumprod", PyBuiltin.positional("sumprod", a -> { - Object[] p = Py.toArray(a[0]); - Object[] q = Py.toArray(a[1]); + m.setAttr("sumprod", PyBuiltin.fixed2("sumprod", (a0, a1) -> { + Object[] p = Py.toArray(a0); + Object[] q = Py.toArray(a1); if (p.length != q.length) { throw Py.valueError("Inputs are not the same length"); } diff --git a/maven/python-runtime/src/main/java/com/codename1/python/runtime/NativeModule.java b/maven/python-runtime/src/main/java/com/codename1/python/runtime/NativeModule.java index 3592d5f79ab..142d0225c57 100644 --- a/maven/python-runtime/src/main/java/com/codename1/python/runtime/NativeModule.java +++ b/maven/python-runtime/src/main/java/com/codename1/python/runtime/NativeModule.java @@ -160,6 +160,41 @@ public void install() { PyModule.registerModule(module); } + private static final java.util.Map REPLACED = + new java.util.HashMap(); + + /// Gives the Java that runs in place of a Python function the build was + /// told to replace (`replace=` in `cn1-python.properties`). `function` + /// is its dotted name, `pkg.module.function` or + /// `pkg.module.Class.method`. `body` receives the values of the + /// function's parameters in the order it declares them -- a `*args` + /// parameter as one tuple, a `**kwargs` parameter as one dict -- as + /// the runtime holds them, and what it returns is what the call + /// answers. + public static void replace(String function, PyBuiltin.Positional body) { + REPLACED.put(function, body); + } + + /// Runs the replacement of the function named by the first argument. + static Object replaced(Object[] a) { + String name = String.valueOf(a[0]); + PyBuiltin.Positional body = REPLACED.get(name); + if (body == null) { + throw notReplaced(name); + } + Object[] args = new Object[a.length - 1]; + System.arraycopy(a, 1, args, 0, args.length); + return body.call(args); + } + + /// The `NotImplementedError` of a replaced function whose Java was not + /// written yet. + public static RuntimeException notReplaced(String function) { + return Py.error(Py.NOT_IMPLEMENTED_ERROR, function + " is replaced by Java in this build" + + " (cn1-python.properties), and the Java is not written yet: fill in the class the build" + + " generated for its module under com.codename1.python.ext"); + } + /// The `NotImplementedError` a generated stub raises until it is filled /// in, naming what is missing. public static RuntimeException notImplemented(String what) { diff --git a/maven/python-runtime/src/main/java/com/codename1/python/runtime/NumPy.java b/maven/python-runtime/src/main/java/com/codename1/python/runtime/NumPy.java index 5a7d0cdefeb..28d1b98fada 100644 --- a/maven/python-runtime/src/main/java/com/codename1/python/runtime/NumPy.java +++ b/maven/python-runtime/src/main/java/com/codename1/python/runtime/NumPy.java @@ -39,13 +39,13 @@ private NumPy() { static PyModule module() { PyModule m = new PyModule("_cn1np", new String[0]); - m.setAttr("alloc", PyBuiltin.positional("alloc", a -> new NdBuf(kind(a[0]), (int) Py.asLong(a[1])))); - m.setAttr("kind", PyBuiltin.positional("kind", a -> String.valueOf(buf(a[0]).kind))); - m.setAttr("size", PyBuiltin.positional("size", a -> Py.of((long) buf(a[0]).size()))); - m.setAttr("fromflat", PyBuiltin.positional("fromflat", a -> fromFlat(kind(a[0]), a[1]))); - m.setAttr("item", PyBuiltin.positional("item", a -> buf(a[0]).item((int) Py.asLong(a[1])))); - m.setAttr("setitem", PyBuiltin.positional("setitem", a -> { - setScalar(buf(a[0]), (int) Py.asLong(a[1]), a[2]); + m.setAttr("alloc", PyBuiltin.fixed2("alloc", (a0, a1) -> new NdBuf(kind(a0), (int) Py.asLong(a1)))); + m.setAttr("kind", PyBuiltin.fixed1("kind", a0 -> String.valueOf(buf(a0).kind))); + m.setAttr("size", PyBuiltin.fixed1("size", a0 -> Py.of((long) buf(a0).size()))); + m.setAttr("fromflat", PyBuiltin.fixed2("fromflat", (a0, a1) -> fromFlat(kind(a0), a1))); + m.setAttr("item", PyBuiltin.fixed2("item", (a0, a1) -> buf(a0).item((int) Py.asLong(a1)))); + m.setAttr("setitem", PyBuiltin.fixed3("setitem", (a0, a1, a2) -> { + setScalar(buf(a0), (int) Py.asLong(a1), a2); return Py.NONE; })); m.setAttr("copy", PyBuiltin.positional("copy", a -> copy(kind(a[0]), ints(a[1]), buf(a[2]), off(a[3]), ints(a[4])))); @@ -70,15 +70,15 @@ static PyModule module() { (int) Py.asLong(a[3]), buf(a[4]), off(a[5]), ints(a[6]), buf(a[7]), off(a[8]), ints(a[9])))); m.setAttr("where", PyBuiltin.positional("where", a -> where(kind(a[0]), ints(a[1]), buf(a[2]), off(a[3]), ints(a[4]), buf(a[5]), off(a[6]), ints(a[7]), buf(a[8]), off(a[9]), ints(a[10])))); - m.setAttr("positions", PyBuiltin.positional("positions", a -> positions(ints(a[0]), off(a[1]), ints(a[2])))); - m.setAttr("compress", PyBuiltin.positional("compress", a -> compress(buf(a[0]), buf(a[1])))); - m.setAttr("gather", PyBuiltin.positional("gather", a -> gather(buf(a[0]), buf(a[1])))); - m.setAttr("scatter", PyBuiltin.positional("scatter", a -> { - scatter(buf(a[0]), buf(a[1]), buf(a[2])); + m.setAttr("positions", PyBuiltin.fixed3("positions", (a0, a1, a2) -> positions(ints(a0), off(a1), ints(a2)))); + m.setAttr("compress", PyBuiltin.fixed2("compress", (a0, a1) -> compress(buf(a0), buf(a1)))); + m.setAttr("gather", PyBuiltin.fixed2("gather", (a0, a1) -> gather(buf(a0), buf(a1)))); + m.setAttr("scatter", PyBuiltin.fixed3("scatter", (a0, a1, a2) -> { + scatter(buf(a0), buf(a1), buf(a2)); return Py.NONE; })); - m.setAttr("sortrows", PyBuiltin.positional("sortrows", a -> sortRows(buf(a[0]), (int) Py.asLong(a[1]), Py.isTrue(a[2])))); - m.setAttr("concat", PyBuiltin.positional("concat", a -> concat(kind(a[0]), a[1]))); + m.setAttr("sortrows", PyBuiltin.fixed3("sortrows", (a0, a1, a2) -> sortRows(buf(a0), (int) Py.asLong(a1), Py.isTrue(a2)))); + m.setAttr("concat", PyBuiltin.fixed2("concat", (a0, a1) -> concat(kind(a0), a1))); m.setAttr("arange", PyBuiltin.positional("arange", a -> arange(kind(a[0]), a[1], a[2], (int) Py.asLong(a[3])))); return m; } @@ -107,7 +107,7 @@ private static int off(Object o) { private static int[] ints(Object o) { Object[] items; if (o instanceof PyTuple) { - items = ((PyTuple) o).items; + items = ((PyTuple) o).arr(); } else if (o instanceof PyList) { items = ((PyList) o).toArray(); } else { @@ -145,7 +145,7 @@ private static void setScalar(NdBuf b, int i, Object v) { } private static NdBuf fromFlat(char kind, Object list) { - Object[] items = list instanceof PyList ? ((PyList) list).toArray() : ((PyTuple) list).items; + Object[] items = list instanceof PyList ? ((PyList) list).toArray() : ((PyTuple) list).arr(); NdBuf b = new NdBuf(kind, items.length); for (int i = 0; i < items.length; i++) { setScalar(b, i, items[i]); @@ -1014,7 +1014,7 @@ private static NdBuf arange(char kind, Object start, Object step, int n) { } private static NdBuf concat(char kind, Object parts) { - Object[] items = parts instanceof PyList ? ((PyList) parts).toArray() : ((PyTuple) parts).items; + Object[] items = parts instanceof PyList ? ((PyList) parts).toArray() : ((PyTuple) parts).arr(); int n = 0; for (Object o : items) { n += buf(o).size(); diff --git a/maven/python-runtime/src/main/java/com/codename1/python/runtime/Operator.java b/maven/python-runtime/src/main/java/com/codename1/python/runtime/Operator.java new file mode 100644 index 00000000000..ec27661102b --- /dev/null +++ b/maven/python-runtime/src/main/java/com/codename1/python/runtime/Operator.java @@ -0,0 +1,337 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.python.runtime; + +/// The `operator` module's functions and its three callable types, which +/// CPython implements in C (`_operator`). They were Python here: `itemgetter` +/// a class whose `__call__` tested `len(self._items)` on every call, and +/// `lt`, `add` and the rest each a `def` -- pdfplumber sorts characters with +/// one, and `sorted(key=itemgetter(0))` calls it per element. +final class Operator { + + private Operator() { + } + + static void install(PyModule m) { + m.setAttr("lt", PyBuiltin.fixed2("lt", Py::lt)); + m.setAttr("le", PyBuiltin.fixed2("le", Py::le)); + m.setAttr("eq", PyBuiltin.fixed2("eq", Py::eq)); + m.setAttr("ne", PyBuiltin.fixed2("ne", Py::ne)); + m.setAttr("ge", PyBuiltin.fixed2("ge", Py::ge)); + m.setAttr("gt", PyBuiltin.fixed2("gt", Py::gt)); + m.setAttr("not_", PyBuiltin.fixed1("not_", a -> Py.bool(!Py.isTrue(a)))); + m.setAttr("truth", PyBuiltin.fixed1("truth", a -> Py.bool(Py.isTrue(a)))); + m.setAttr("is_", PyBuiltin.fixed2("is_", (a, b) -> Py.bool(a == b))); //NOPMD CompareObjectsWithEquals - identity is meant + m.setAttr("is_not", PyBuiltin.fixed2("is_not", (a, b) -> Py.bool(a != b))); //NOPMD CompareObjectsWithEquals - identity is meant + m.setAttr("is_none", PyBuiltin.fixed1("is_none", a -> Py.bool(a == Py.NONE))); //NOPMD CompareObjectsWithEquals - identity is meant + m.setAttr("is_not_none", PyBuiltin.fixed1("is_not_none", a -> Py.bool(a != Py.NONE))); //NOPMD CompareObjectsWithEquals - identity is meant + m.setAttr("add", PyBuiltin.fixed2("add", Py::add)); + m.setAttr("sub", PyBuiltin.fixed2("sub", Py::sub)); + m.setAttr("mul", PyBuiltin.fixed2("mul", Py::mul)); + m.setAttr("truediv", PyBuiltin.fixed2("truediv", Py::truediv)); + m.setAttr("floordiv", PyBuiltin.fixed2("floordiv", Py::floordiv)); + m.setAttr("mod", PyBuiltin.fixed2("mod", Py::mod)); + m.setAttr("pow", PyBuiltin.fixed2("pow", Py::pow)); + m.setAttr("lshift", PyBuiltin.fixed2("lshift", Py::lshift)); + m.setAttr("rshift", PyBuiltin.fixed2("rshift", Py::rshift)); + m.setAttr("and_", PyBuiltin.fixed2("and_", Py::and)); + m.setAttr("or_", PyBuiltin.fixed2("or_", Py::or)); + m.setAttr("xor", PyBuiltin.fixed2("xor", Py::xor)); + m.setAttr("neg", PyBuiltin.fixed1("neg", Py::neg)); + m.setAttr("pos", PyBuiltin.fixed1("pos", Py::pos)); + PyBuiltin inv = PyBuiltin.fixed1("inv", Py::invert); + m.setAttr("inv", inv); + m.setAttr("invert", PyBuiltin.fixed1("invert", Py::invert)); + m.setAttr("contains", PyBuiltin.fixed2("contains", (a, b) -> Py.in(b, a))); + m.setAttr("getitem", PyBuiltin.fixed2("getitem", Py::getitem)); + m.setAttr("setitem", PyBuiltin.fixed3("setitem", (a, b, c) -> { + Py.setitem(a, b, c); + return Py.NONE; + })); + m.setAttr("itemgetter", ITEMGETTER); + m.setAttr("attrgetter", ATTRGETTER); + m.setAttr("methodcaller", METHODCALLER); + } + + private static PyType type(String name, PyType.Factory f) { + PyType t = new PyType(name, new PyType[] {Py.OBJECT_TYPE}, f); + t.define("__module__", "operator"); + return t; + } + + private static void noKeywords(String fn, String[] kw) { + if (kw.length != 0) { + throw Py.typeError(fn + "() takes no keyword arguments"); + } + } + + private static PyException arity(String fn, int n) { + return Py.typeError(fn + " expected 1 argument, got " + n); + } + + static final PyType ITEMGETTER = type("itemgetter", (t, a, k) -> { + noKeywords("itemgetter", k); + if (a.length == 0) { + throw Py.typeError("itemgetter expected 1 argument, got 0"); + } + return new ItemGetter(t, a.clone()); + }); + + static final PyType ATTRGETTER = type("attrgetter", (t, a, k) -> { + noKeywords("attrgetter", k); + if (a.length == 0) { + throw Py.typeError("attrgetter expected 1 argument, got 0"); + } + String[][] paths = new String[a.length][]; + for (int i = 0; i < a.length; i++) { + if (!(a[i] instanceof String)) { + throw Py.typeError("attribute name must be a string"); + } + paths[i] = split((String) a[i]); + } + return new AttrGetter(t, a.clone(), paths); + }); + + static final PyType METHODCALLER = type("methodcaller", (t, a, k) -> { + int npos = a.length - k.length; + if (npos < 1) { + throw Py.typeError("methodcaller needs at least one argument, the method name"); + } + if (!(a[0] instanceof String)) { + throw Py.typeError("method name must be a string"); + } + Object[] rest = new Object[a.length - 1]; + System.arraycopy(a, 1, rest, 0, rest.length); + return new MethodCaller(t, (String) a[0], rest, k.clone()); + }); + + /// A dotted attribute path, split once when the getter is made. + private static String[] split(String path) { + int n = 1; + for (int i = path.indexOf('.'); i >= 0; i = path.indexOf('.', i + 1)) { + n++; + } + String[] r = new String[n]; + int start = 0; + for (int i = 0; i < n - 1; i++) { + int dot = path.indexOf('.', start); + r[i] = path.substring(start, dot); + start = dot + 1; + } + r[n - 1] = start == 0 ? path : path.substring(start); + return r; + } + + private static String reprArgs(String name, Object[] args) { + StringBuilder b = new StringBuilder("operator.").append(name).append('('); + for (int i = 0; i < args.length; i++) { + if (i > 0) { + b.append(", "); + } + b.append(Py.toRepr(args[i])); + } + return b.append(')').toString(); + } + + /// The base of the three: a type of their own and a one-argument call. + private abstract static class Getter extends PyObject { + private final PyType type; + + Getter(PyType type) { + this.type = type; + } + + @Override + public PyType type() { + return type; + } + + abstract Object apply(Object obj); + + abstract String name(); + + @Override + public Object call1(Object a) { + return apply(a); + } + + @Override + public Object call(Object[] args, String[] kwNames) { + noKeywords(name(), kwNames); + if (args.length != 1) { + throw arity(name(), args.length); + } + return apply(args[0]); + } + } + + static final class ItemGetter extends Getter { + private final Object[] items; + private final Object single; + + ItemGetter(PyType t, Object[] items) { + super(t); + this.items = items; + this.single = items.length == 1 ? items[0] : null; + long[] h = null; + for (int i = 0; i < items.length; i++) { + if (items[i] instanceof String) { + if (h == null) { + h = new long[items.length]; + } + h[i] = Py.keyHash(items[i], "a dict key"); + } + } + this.strHashes = h; + } + + /// The hash of each str key, taken once: pdfplumber applies one getter + /// with four str keys to every char dict on a page. + private final long[] strHashes; + + private Object item(Object obj, int i) { + Object k = items[i]; + if (strHashes != null && k instanceof String && obj instanceof PyDict) { + PyDict d = (PyDict) obj; + if (d.type() == Py.DICT_TYPE) { //NOPMD CompareObjectsWithEquals - identity is meant + Object v = d.getStrHashed((String) k, strHashes[i]); + if (v != null) { + return v; + } + } + } + return Py.getitem(obj, k); + } + + @Override + String name() { + return "itemgetter"; + } + + @Override + Object apply(Object obj) { + if (single != null) { + return item(obj, 0); + } + Object[] out = new Object[items.length]; + for (int i = 0; i < out.length; i++) { + out[i] = item(obj, i); + } + return new PyTuple(out); + } + + @Override + public String repr() { + return reprArgs("itemgetter", items); + } + } + + static final class AttrGetter extends Getter { + private final Object[] names; + private final String[][] paths; + + AttrGetter(PyType t, Object[] names, String[][] paths) { + super(t); + this.names = names; + this.paths = paths; + } + + @Override + String name() { + return "attrgetter"; + } + + private static Object walk(Object obj, String[] path) { + Object v = obj; + for (String p : path) { + v = Py.getattr(v, p); + } + return v; + } + + @Override + Object apply(Object obj) { + if (paths.length == 1) { + return walk(obj, paths[0]); + } + Object[] out = new Object[paths.length]; + for (int i = 0; i < out.length; i++) { + out[i] = walk(obj, paths[i]); + } + return new PyTuple(out); + } + + @Override + public String repr() { + return reprArgs("attrgetter", names); + } + } + + static final class MethodCaller extends Getter { + private final String method; + private final Object[] args; + private final String[] kw; + + MethodCaller(PyType t, String method, Object[] args, String[] kw) { + super(t); + this.method = method; + this.args = args; + this.kw = kw; + } + + @Override + String name() { + return "methodcaller"; + } + + @Override + Object apply(Object obj) { + Object f = Py.getattr(obj, method); + if (kw.length == 0) { + switch (args.length) { + case 0: + return Py.obj(f).call0(); + case 1: + return Py.obj(f).call1(args[0]); + default: + break; + } + } + return Py.obj(f).call(args.clone(), kw); + } + + @Override + public String repr() { + StringBuilder b = new StringBuilder("operator.methodcaller(").append(Py.toRepr(method)); + int npos = args.length - kw.length; + for (int i = 0; i < npos; i++) { + b.append(", ").append(Py.toRepr(args[i])); + } + for (int i = 0; i < kw.length; i++) { + b.append(", ").append(kw[i]).append('=').append(Py.toRepr(args[npos + i])); + } + return b.append(')').toString(); + } + } +} diff --git a/maven/python-runtime/src/main/java/com/codename1/python/runtime/Py.java b/maven/python-runtime/src/main/java/com/codename1/python/runtime/Py.java index 4188fbf0eba..5106a45fd01 100644 --- a/maven/python-runtime/src/main/java/com/codename1/python/runtime/Py.java +++ b/maven/python-runtime/src/main/java/com/codename1/python/runtime/Py.java @@ -231,6 +231,15 @@ public static boolean isInt(Object o) { } public static PyType typeOf(Object o) { + // Asked first and answered here: isinstance, method lookup and every + // builtin's receiver check come through this, and going by way of + // obj() was a second call, frame and guard per ask. + if (o instanceof PyInstance) { + return ((PyInstance) o).cls; + } + if (o instanceof PyObject) { + return ((PyObject) o).type(); + } if (o instanceof Long) { return INT_TYPE; } @@ -287,6 +296,10 @@ public static long hashOf(Object o) { if (o instanceof String) { return o.hashCode(); } + if (o instanceof Double) { + // The boxed value is the float object: a NaN hashes by it. + return Hashing.ofDouble(((Double) o).doubleValue(), o); + } return obj(o).hash(); } @@ -307,6 +320,9 @@ static long keyHash(Object o, String role) { if (o instanceof String) { return o.hashCode(); } + if (o instanceof Double) { + return Hashing.ofDouble(((Double) o).doubleValue(), o); + } return keyHashSlow(o, role); } @@ -333,6 +349,118 @@ public static Object len(Object f, Object o) { return call(f, o); } + /// `ord(o)` where the name may still be rebound: the builtin's answer + /// with no dispatch through its function object when `f` is the builtin. + public static Object ord(Object f, Object o) { + if (f == Builtins.ORD) { //NOPMD CompareObjectsWithEquals - identity is meant + return Builtins.ord(o); + } + return call(f, o); + } + + /// `isinstance(o, t)` where the name may still be rebound: the builtin's + /// answer without its argument array when `f` is the builtin. + public static Object isinstance(Object f, Object o, Object t) { + if (f == Builtins.ISINSTANCE) { //NOPMD CompareObjectsWithEquals - identity is meant + return bool(isinstance(o, t)); + } + return call(f, o, t); + } + + /// `isinstance(o, (a, b))` with the tuple written out: the builtin checks + /// each type in turn without the tuple being built; anything else that + /// is bound to the name gets the tuple. + public static Object isinstanceAny(Object f, Object o, Object a, Object b) { + if (f == Builtins.ISINSTANCE) { //NOPMD CompareObjectsWithEquals - identity is meant + return bool(isinstance(o, a) || isinstance(o, b)); + } + return call(f, o, tuple(a, b)); + } + + public static Object isinstanceAny(Object f, Object o, Object a, Object b, Object c) { + if (f == Builtins.ISINSTANCE) { //NOPMD CompareObjectsWithEquals - identity is meant + return bool(isinstance(o, a) || isinstance(o, b) || isinstance(o, c)); + } + return call(f, o, tuple(a, b, c)); + } + + public static Object isinstanceAny(Object f, Object o, Object a, Object b, Object c, Object d) { + if (f == Builtins.ISINSTANCE) { //NOPMD CompareObjectsWithEquals - identity is meant + return bool(isinstance(o, a) || isinstance(o, b) || isinstance(o, c) || isinstance(o, d)); + } + return call(f, o, tuple(a, b, c, d)); + } + + public static Object isinstanceAny(Object fn, Object o, Object a, Object b, Object c, Object d, Object e) { + if (fn == Builtins.ISINSTANCE) { //NOPMD CompareObjectsWithEquals - identity is meant + return bool(isinstance(o, a) || isinstance(o, b) || isinstance(o, c) || isinstance(o, d) || isinstance(o, e)); + } + return call(fn, o, tuple(a, b, c, d, e)); + } + + public static Object isinstanceAny(Object fn, Object o, Object a, Object b, Object c, Object d, Object e, Object f) { + if (fn == Builtins.ISINSTANCE) { //NOPMD CompareObjectsWithEquals - identity is meant + return bool(isinstance(o, a) || isinstance(o, b) || isinstance(o, c) || isinstance(o, d) || isinstance(o, e) || isinstance(o, f)); + } + return call(fn, o, tuple(a, b, c, d, e, f)); + } + + public static Object isinstanceAny(Object fn, Object o, Object a, Object b, Object c, Object d, Object e, Object f, Object g) { + if (fn == Builtins.ISINSTANCE) { //NOPMD CompareObjectsWithEquals - identity is meant + return bool(isinstance(o, a) || isinstance(o, b) || isinstance(o, c) || isinstance(o, d) || isinstance(o, e) || isinstance(o, f) || isinstance(o, g)); + } + return call(fn, o, tuple(a, b, c, d, e, f, g)); + } + + public static Object isinstanceAny(Object fn, Object o, Object a, Object b, Object c, Object d, Object e, Object f, Object g, Object h) { + if (fn == Builtins.ISINSTANCE) { //NOPMD CompareObjectsWithEquals - identity is meant + return bool(isinstance(o, a) || isinstance(o, b) || isinstance(o, c) || isinstance(o, d) || isinstance(o, e) || isinstance(o, f) || isinstance(o, g) || isinstance(o, h)); + } + return call(fn, o, tuple(a, b, c, d, e, f, g, h)); + } + + /// `x in (a, b, ...)` with the tuple written out: each item is compared + /// in turn, identity first as a tuple's `__contains__` does, and no tuple + /// is built. + public static boolean inOf(Object x, Object a, Object b) { + return a == x || eqBool(a, x) || b == x || eqBool(b, x); //NOPMD CompareObjectsWithEquals - identity first, as a tuple compares + } + + public static boolean inOf(Object x, Object a, Object b, Object c) { + return a == x || eqBool(a, x) || b == x || eqBool(b, x) || c == x || eqBool(c, x); //NOPMD CompareObjectsWithEquals - identity first, as a tuple compares + } + + public static boolean inOf(Object x, Object a, Object b, Object c, Object d) { + return a == x || eqBool(a, x) || b == x || eqBool(b, x) || c == x || eqBool(c, x) || d == x || eqBool(d, x); //NOPMD CompareObjectsWithEquals - identity first, as a tuple compares + } + + public static boolean inOf(Object x, Object a, Object b, Object c, Object d, Object e) { + return a == x || eqBool(a, x) || b == x || eqBool(b, x) || c == x || eqBool(c, x) || d == x || eqBool(d, x) || e == x || eqBool(e, x); //NOPMD CompareObjectsWithEquals - identity first, as a tuple compares + } + + public static boolean inOf(Object x, Object a, Object b, Object c, Object d, Object e, Object f) { + return a == x || eqBool(a, x) || b == x || eqBool(b, x) || c == x || eqBool(c, x) || d == x || eqBool(d, x) || e == x || eqBool(e, x) || f == x || eqBool(f, x); //NOPMD CompareObjectsWithEquals - identity first, as a tuple compares + } + + public static boolean inOf(Object x, Object a, Object b, Object c, Object d, Object e, Object f, Object g) { + return a == x || eqBool(a, x) || b == x || eqBool(b, x) || c == x || eqBool(c, x) || d == x || eqBool(d, x) || e == x || eqBool(e, x) || f == x || eqBool(f, x) || g == x || eqBool(g, x); //NOPMD CompareObjectsWithEquals - identity first, as a tuple compares + } + + public static boolean inOf(Object x, Object a, Object b, Object c, Object d, Object e, Object f, Object g, Object h) { + return a == x || eqBool(a, x) || b == x || eqBool(b, x) || c == x || eqBool(c, x) || d == x || eqBool(d, x) || e == x || eqBool(e, x) || f == x || eqBool(f, x) || g == x || eqBool(g, x) || h == x || eqBool(h, x); //NOPMD CompareObjectsWithEquals - identity first, as a tuple compares + } + + /// `dict(o)`, as [#isinstance(Object, Object, Object)]: a copy of a dict + /// made straight from it. + public static Object dict1(Object f, Object o) { + if (f == DICT_TYPE && o instanceof PyDict) { //NOPMD CompareObjectsWithEquals - identity is meant + PyDict d = new PyDict(); + d.update(o); + return d; + } + return call(f, o); + } + public static int len(Object o) { if (o instanceof PyObject) { return ((PyObject) o).len(); @@ -421,9 +549,46 @@ public static Object wrap(Object o) { /// Instantiates exception type `t` with `msg` and wraps it for `throw`. public static PyException error(PyType t, String msg) { + if (t.plainException()) { + // What BaseException's __new__ and __init__ would do, without + // two lookups, two argument copies and two calls a raise. + PyInstance e = t.newInstance(); + e.setAttrDirect("args", new PyTuple(new Object[] {msg})); + return new PyException(e); + } return new PyException(t.call(new Object[] {str(msg)}, NO_KW)); } + /// A UnicodeDecodeError with its parts, as a codec raises it. + static PyException decodeError(String encoding, byte[] object, int start, int end, String reason) { + return new PyException(UNICODE_DECODE_ERROR.call(new Object[] {str(encoding), new PyBytes(object), + Long.valueOf(start), Long.valueOf(end), str(reason)}, NO_KW)); + } + + /// A UnicodeEncodeError with its parts; `start`/`end` count code points. + static PyException encodeError(String encoding, String object, int start, int end, String reason) { + return new PyException(UNICODE_ENCODE_ERROR.call(new Object[] {str(encoding), str(object), + Long.valueOf(start), Long.valueOf(end), str(reason)}, NO_KW)); + } + + /// What a translated library's `compile` is: it answers a code object + /// that names its file and mode and holds nothing to run, since running + /// one is `eval` or `exec`, which a build refuses wherever the program + /// reaches them. + public static final PyBuiltin UNCOMPILED = new PyBuiltin("compile", (args, kwNames) -> { + if (args.length < 3) { + throw typeError("compile() missing required argument 'mode'"); + } + String mode = toStr(args[2]); + if (!"exec".equals(mode) && !"eval".equals(mode) && !"single".equals(mode)) { + throw valueError("compile() mode must be 'exec', 'eval' or 'single'"); + } + PyModule code = new PyModule("code", new String[0]); + code.setAttr("co_filename", args[1]); + code.setAttr("co_name", str("")); + return code; + }); + public static PyException typeError(String m) { return error(TYPE_ERROR, m); } @@ -461,6 +626,14 @@ public static PyException unboundLocal(String name) { + "' where it is not associated with a value"); } + /// A closure's read of a free variable its enclosing function has not + /// bound (or has deleted): CPython raises NameError, not + /// UnboundLocalError, for it. + public static PyException unboundFree(String name) { + return error(NAME_ERROR, "cannot access free variable '" + name + + "' where it is not associated with a value in enclosing scope"); + } + public static PyException keyError(Object key) { return new PyException(KEY_ERROR.call(new Object[] {key}, NO_KW)); } @@ -555,13 +728,30 @@ public static boolean isTrue(Object o) { if (o instanceof String) { return ((String) o).length() != 0; } - return obj(o).isTrue(); + if (o instanceof PyList) { + return ((PyList) o).size != 0; + } + // An instance (a bs4 Tag in every `if node:`) asks its class once, + // without the trip through obj(). + if (o instanceof PyInstance) { + return ((PyInstance) o).isTrue(); + } + return (o instanceof PyObject ? (PyObject) o : obj(o)).isTrue(); } public static Object not(Object o) { return bool(!isTrue(o)); } + /// `a == lit` for a str literal: a str compares its text, anything else + /// (a str subclass, an object with its own `__eq__`) the generic way. + public static boolean eqStr(Object a, String lit) { + if (a instanceof String) { + return lit.equals(a); + } + return !(a instanceof Long) && a != Py.NONE && eqBool(a, lit); //NOPMD CompareObjectsWithEquals - identity is meant + } + public static boolean eqBool(Object a, Object b) { if (a instanceof Long && b instanceof Long) { return ((Long) a).longValue() == ((Long) b).longValue(); @@ -613,7 +803,7 @@ public static Object ne(Object a, Object b) { if (a instanceof PyInstance) { Object m = Py.typeOf(a).lookup("__ne__"); if (m != null) { - Object r = Py.obj(m).call(new Object[] {a, b}, NO_KW); + Object r = (m instanceof PyObject ? (PyObject) m : Py.obj(m)).call2(a, b); if (r != NOT_IMPLEMENTED) { return r; } @@ -781,9 +971,68 @@ public static boolean ltBool(Object a, Object b) { if (a instanceof String && b instanceof String) { return PyStr.compare((String) a, (String) b) < 0; } + if (a instanceof PyTuple && b instanceof PyTuple) { + // Two tuples (a heap's or a sort key's entries) compare + // element-wise here, without the boxed-bool round trip through + // PyTuple.lt. No Java subclass overrides the comparison (a struct + // sequence compares as a tuple, as in CPython), and a Python + // subclass is a PyInstance, which takes the long way below. + Object[] x = ((PyTuple) a).arr(); + Object[] y = ((PyTuple) b).arr(); + return seqCompare(x, x.length, y, y.length) < 0; + } return isTrue(lt(a, b)); } + public static boolean neBool(Object a, Object b) { + if (a instanceof Long && b instanceof Long) { + return ((Long) a).longValue() != ((Long) b).longValue(); + } + if (a instanceof String && b instanceof String) { + return !a.equals(b); + } + return isTrue(ne(a, b)); + } + + public static boolean leBool(Object a, Object b) { + if (a instanceof Long && b instanceof Long) { + return ((Long) a).longValue() <= ((Long) b).longValue(); + } + if (a instanceof Double && b instanceof Double) { + return ((Double) a).doubleValue() <= ((Double) b).doubleValue(); + } + if (a instanceof String && b instanceof String) { + return PyStr.compare((String) a, (String) b) <= 0; + } + return isTrue(le(a, b)); + } + + public static boolean gtBool(Object a, Object b) { + if (a instanceof Long && b instanceof Long) { + return ((Long) a).longValue() > ((Long) b).longValue(); + } + if (a instanceof Double && b instanceof Double) { + return ((Double) a).doubleValue() > ((Double) b).doubleValue(); + } + if (a instanceof String && b instanceof String) { + return PyStr.compare((String) a, (String) b) > 0; + } + return isTrue(gt(a, b)); + } + + public static boolean geBool(Object a, Object b) { + if (a instanceof Long && b instanceof Long) { + return ((Long) a).longValue() >= ((Long) b).longValue(); + } + if (a instanceof Double && b instanceof Double) { + return ((Double) a).doubleValue() >= ((Double) b).doubleValue(); + } + if (a instanceof String && b instanceof String) { + return PyStr.compare((String) a, (String) b) >= 0; + } + return isTrue(ge(a, b)); + } + private static PyException cmpError(String op, Object a, Object b) { return typeError("'" + op + "' not supported between instances of '" + Py.typeOf(a).name + "' and '" + Py.typeOf(b).name + "'"); @@ -805,11 +1054,26 @@ public static boolean identical(Object a, Object b) { } public static Object in(Object x, Object container) { - return bool(Py.obj(container).contains(x)); + return bool(contains(container, x)); + } + + /// `x in container` in a test: membership always answers a bool, so the + /// boxed result [#in] would make is never needed there. + public static boolean inBool(Object x, Object container) { + return contains(container, x); } public static Object notIn(Object x, Object container) { - return bool(!Py.obj(container).contains(x)); + return bool(!contains(container, x)); + } + + /// `x in container`; a str in a str is answered without the PyStr view + /// Py.obj would allocate for the container. + private static boolean contains(Object container, Object x) { + if (container instanceof String && x instanceof String) { + return ((String) container).indexOf((String) x) >= 0; + } + return Py.obj(container).contains(x); } // ---- arithmetic ------------------------------------------------------ @@ -887,6 +1151,10 @@ public static Object add(Object a, Object b) { if (r == null) { r = Py.obj(b).radd(a); if (r == null) { + if (a instanceof String && b instanceof PyInstance && ((PyInstance) b).base instanceof String) { + // a str subclass without __radd__ concatenates as the str it carries + return ((String) a).concat((String) ((PyInstance) b).base); + } if (a instanceof String && !(b instanceof String)) { throw typeError("can only concatenate str (not \"" + Py.typeOf(b).name + "\") to str"); } @@ -1057,6 +1325,13 @@ public static Object mod(Object a, Object b) { if (a instanceof String) { return Formatting.percent((String) a, b); } + if (a instanceof PyBytes) { + return Formatting.percentBytes(((PyBytes) a).value, b); + } + if (a instanceof PyByteArray) { + PyByteArray ba = (PyByteArray) a; + return new PyByteArray(Formatting.percentBytes(ba.bytes(), b).value); + } if (a instanceof Long) { long x = ((Long) a).longValue(); if (b instanceof Long) { @@ -1210,6 +1485,12 @@ public static Object xor(Object a, Object b) { } /// `a += b`: the in-place method when the type has one, else `a + b`. + /// Answers `r`; `a` was evaluated first. A lambda the transpiler expands in + /// place stores its arguments this way, ahead of its body. + public static Object seq(Object a, Object r) { + return r; + } + public static Object iadd(Object a, Object b) { Object r = a instanceof PyObject ? ((PyObject) a).iadd(b) : null; return r != null ? r : add(a, b); @@ -1306,6 +1587,83 @@ public static void setattr(Object o, String name, Object v) { Py.obj(o).setAttr(name, v); } + // ---- lookups that miss without raising ----------------------------------- + // + // `try: x += obj.attr / d[key]` with one `except AttributeError` / + // `except KeyError` is lowered by the parser into a probe, a branch and the + // original try (see Parser.missProbe): the probe answers MISS instead of + // raising, so the common miss builds no exception and unwinds nothing. + + /// A probe found nothing and ran no code while looking: re-reading is + /// pure, so [#unmissed] may evaluate the original expression again. + public static final Object MISS = new Object(); + + /// A probe that caught the error it stands for, raised by code that ran + /// (a `__getitem__`, a property): that exception is rethrown rather than + /// evaluating the code a second time. + static final class Miss { + final PyException error; + + Miss(PyException error) { + this.error = error; + } + } + + /// `d[key]` for the probe: [#MISS] when an exact dict lacks the key, a + /// [Miss] for a KeyError raised anywhere else. + public static Object getitemOrMiss(Object o, Object key) { + if (o instanceof PyDict && o.getClass() == PyDict.class) { + Object v = ((PyDict) o).getOrNull(key); + return v == null ? MISS : v; + } + try { + return getitem(o, key); + } catch (PyException e) { + if (e.matches(KEY_ERROR)) { + return new Miss(e); + } + throw e; + } + } + + /// Whether the probe missed AND the handler names the builtin it was + /// lowered for. A module that rebinds `KeyError` takes the original try, + /// where [#unmissed] raises the real error for its handler to match. + public static boolean isMiss(Object m, Object handlerType, Object builtin) { + return (m == MISS || m instanceof Miss) && handlerType == builtin; //NOPMD CompareObjectsWithEquals - identity is meant + } + + /// The probed value, or the error it stands for: a [Miss] rethrows its + /// exception; [#MISS] answers null and the caller re-reads. + public static Object unmissed(Object m) { + if (m instanceof Miss) { + throw ((Miss) m).error; + } + return m == MISS ? null : m; //NOPMD CompareObjectsWithEquals - identity is meant + } + + /// `getattr(obj, name, default)` over a probe. + public static Object orDefault(Object m, Object dflt) { + return m == MISS || m instanceof Miss ? dflt : m; //NOPMD CompareObjectsWithEquals - identity is meant + } + + /// `o["k"]` for a str literal key: an exact dict is probed directly by + /// the str's cached hash, without the sequence checks of [#getitem] or + /// its virtual `getItem`. A miss, a dict subclass and anything else take + /// the general path, so `__missing__` and `__getitem__` still apply. + public static Object getitemS(Object o, String key) { + if (o instanceof PyDict) { + PyDict d = (PyDict) o; + if (d.type() == DICT_TYPE) { //NOPMD CompareObjectsWithEquals - identity is meant + Object v = d.getStrHashed(key, key.hashCode()); + if (v != null) { + return v; + } + } + } + return getitem(o, key); + } + public static Object getitem(Object o, Object key) { if (o instanceof PyList) { PyList l = (PyList) o; @@ -1323,6 +1681,16 @@ public static Object getitem(Object o, Object key) { } return l.getItem(key); } + if (o instanceof String && key instanceof Long) { + // s[i] without the PyStr view Py.obj makes (an allocation per + // character a tokenizer reads). + String str = (String) o; + long i = ((Long) key).longValue(); + int len = str.length(); + if (i >= 0 && i < len && PyStr.surrogates(str) == 0) { + return Typed.ch(str.charAt((int) i)); + } + } return Py.obj(o).getItem(key); } @@ -1367,9 +1735,9 @@ public static Object getitem(Object o, long i) { return l.get((int) i); } } else if (o instanceof PyTuple) { - Object[] items = ((PyTuple) o).items; - if (i >= 0 && i < items.length) { - return items[(int) i]; + PyTuple t = (PyTuple) o; + if (i >= 0 && i < t.size()) { + return t.get((int) i); } } return Py.obj(o).getItem(Long.valueOf(i)); @@ -1388,12 +1756,67 @@ public static void setArgv(String program, String[] args) { /// `o[a:b:c]`, with NONE for a missing part. public static Object getslice(Object o, Object a, Object b, Object c) { + if (o instanceof String && c == NONE && (a instanceof Long || a == NONE) //NOPMD CompareObjectsWithEquals - identity is meant + && (b instanceof Long || b == NONE)) { //NOPMD CompareObjectsWithEquals - identity is meant + // s[a:b] of int bounds on a string without surrogate pairs, where a + // code point is a char: clamped as CPython clamps, and no PySlice. + String s = (String) o; + int n = s.length(); + if (PyStr.surrogates(s) == 0) { + int lo = a == NONE ? 0 : clampSlice(((Long) a).longValue(), n); //NOPMD CompareObjectsWithEquals - identity is meant + int hi = b == NONE ? n : clampSlice(((Long) b).longValue(), n); //NOPMD CompareObjectsWithEquals - identity is meant + return hi <= lo ? "" : lo == 0 && hi == n ? s : s.substring(lo, hi); + } + } if (o instanceof PyList) { return ((PyList) o).getSlice(a, b, c); } + if (o instanceof PyBytes && c == NONE //NOPMD CompareObjectsWithEquals - identity is meant + && (a instanceof Long || a == NONE) && (b instanceof Long || b == NONE)) { //NOPMD CompareObjectsWithEquals - identity is meant + // b[a:b] of int bounds: one block copy, without a PySlice or its index array. + byte[] v = ((PyBytes) o).value; + int n = v.length; + int lo = a == NONE ? 0 : clampSlice(((Long) a).longValue(), n); //NOPMD CompareObjectsWithEquals - identity is meant + int hi = b == NONE ? n : clampSlice(((Long) b).longValue(), n); //NOPMD CompareObjectsWithEquals - identity is meant + if (lo == 0 && hi == n) { + return o; // bytes are immutable: CPython hands back the same object + } + return PyBytes.range(v, lo, hi); + } return Py.obj(o).getItem(new PySlice(a, b, c)); } + /// The transpiler's lowering of `"lit %s" % (a,)`; see `Formatting.pct`. + /// One `%s`, `%d` or `%i` conversion of `v`, for the transpiler's + /// concatenation of a literal format whose values are mostly typed. + public static String pconv(char c, Object v) { + return Formatting.conv1(c, v); + } + + public static String pct(String[] lits, String convs, Object a) { + return Formatting.pct(lits, convs, a); + } + + public static String pct(String[] lits, String convs, Object a, Object b) { + return Formatting.pct(lits, convs, a, b); + } + + public static String pct(String[] lits, String convs, Object a, Object b, Object c) { + return Formatting.pct(lits, convs, a, b, c); + } + + public static String pct(String[] lits, String convs, Object a, Object b, Object c, Object d) { + return Formatting.pct(lits, convs, a, b, c, d); + } + + static int clampSlice(long v, int n) { + if (v < 0) { + v += n; + return v < 0 ? 0 : (int) v; + } + return v > n ? n : (int) v; + } + /// `o[a:b:c]` for a local whose previous list `old` nothing else can /// see any more: a list slice is copied into `old` rather than a new /// list. Anything else is an ordinary [#getslice(Object, Object, Object, Object)]. @@ -1464,7 +1887,7 @@ public static boolean isFloatAt(Object o, Object i) { return k >= 0 && l.isFloatAt(k); } if (o instanceof PyTuple) { - Object[] items = ((PyTuple) o).items; + Object[] items = ((PyTuple) o).arr(); int k = floatIndex(i, items.length); return k >= 0 && items[k] instanceof Double; } @@ -1477,7 +1900,7 @@ public static double floatAt(Object o, Object i) { PyList l = (PyList) o; return l.floatAt(floatIndex(i, l.size)); } - Object[] items = ((PyTuple) o).items; + Object[] items = ((PyTuple) o).arr(); return ((Double) items[floatIndex(i, items.length)]).doubleValue(); } @@ -1545,14 +1968,14 @@ private static double floatItemSlow(Object o, long k) { return v instanceof Double ? ((Double) v).doubleValue() : Double.NaN; } if (o instanceof PyTuple) { - Object[] items = ((PyTuple) o).items; + PyTuple t = (PyTuple) o; if (k < 0) { - k += items.length; + k += t.size(); } - if (k < 0 || k >= items.length) { + if (k < 0 || k >= t.size()) { return Double.NaN; } - Object v = items[(int) k]; + Object v = t.get((int) k); return v instanceof Double ? ((Double) v).doubleValue() : Double.NaN; } return Double.NaN; @@ -1658,42 +2081,145 @@ public static void setitem(Object o, Object key, Object v) { /// One-argument call; `len(x)` skips the argument array and the builtin. public static Object call(Object f, Object a) { + if (f instanceof PyFunction) { + // A Python function straight into its body: no view, no + // virtual call1. + PyFunction.Body1 b = ((PyFunction) f).body1; + if (b != null) { + return b.run(a); + } + } if (f == Builtins.LEN) { //NOPMD CompareObjectsWithEquals - identity is meant return Long.valueOf(len(a)); } - return Py.obj(f).call1(a); + return (f instanceof PyObject ? (PyObject) f : Py.obj(f)).call1(a); } public static Object call(Object f) { - return Py.obj(f).call0(); + return (f instanceof PyObject ? (PyObject) f : Py.obj(f)).call0(); } public static Object call(Object f, Object a, Object b) { - return Py.obj(f).call2(a, b); + if (f instanceof PyFunction) { + PyFunction.Body2 g = ((PyFunction) f).body2; + if (g != null) { + return g.run(a, b); + } + } + return (f instanceof PyObject ? (PyObject) f : Py.obj(f)).call2(a, b); } public static Object call(Object f, Object a, Object b, Object c) { - return Py.obj(f).call3(a, b, c); + return (f instanceof PyObject ? (PyObject) f : Py.obj(f)).call3(a, b, c); } public static Object call(Object f, Object a, Object b, Object c, Object d) { - return Py.obj(f).call4(a, b, c, d); + return (f instanceof PyObject ? (PyObject) f : Py.obj(f)).call4(a, b, c, d); } public static Object call(Object f, Object a, Object b, Object c, Object d, Object e) { - return Py.obj(f).call5(a, b, c, d, e); + return (f instanceof PyObject ? (PyObject) f : Py.obj(f)).call5(a, b, c, d, e); } public static Object call(Object f, Object a, Object b, Object c, Object d, Object e, Object g) { - return Py.obj(f).call6(a, b, c, d, e, g); + return (f instanceof PyObject ? (PyObject) f : Py.obj(f)).call6(a, b, c, d, e, g); + } + + public static Object call(Object fn, Object x0, Object x1, Object x2, Object x3, Object x4, Object x5, Object x6) { + return Py.obj(fn).call7(x0, x1, x2, x3, x4, x5, x6); + } + + public static Object call(Object fn, Object x0, Object x1, Object x2, Object x3, Object x4, Object x5, Object x6, Object x7) { + return Py.obj(fn).call8(x0, x1, x2, x3, x4, x5, x6, x7); + } + + public static Object call(Object fn, Object x0, Object x1, Object x2, Object x3, Object x4, Object x5, Object x6, Object x7, Object x8) { + return Py.obj(fn).call9(x0, x1, x2, x3, x4, x5, x6, x7, x8); + } + + public static Object call(Object fn, Object x0, Object x1, Object x2, Object x3, Object x4, Object x5, Object x6, Object x7, Object x8, Object x9) { + return Py.obj(fn).call10(x0, x1, x2, x3, x4, x5, x6, x7, x8, x9); + } + + public static Object call(Object fn, Object x0, Object x1, Object x2, Object x3, Object x4, Object x5, Object x6, Object x7, Object x8, Object x9, Object x10) { + return Py.obj(fn).call11(x0, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10); + } + + public static Object call(Object fn, Object x0, Object x1, Object x2, Object x3, Object x4, Object x5, Object x6, Object x7, Object x8, Object x9, Object x10, Object x11) { + return Py.obj(fn).call12(x0, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11); + } + + public static Object call(Object fn, Object x0, Object x1, Object x2, Object x3, Object x4, Object x5, Object x6, Object x7, Object x8, Object x9, Object x10, Object x11, Object x12) { + return Py.obj(fn).call13(x0, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12); + } + + public static Object call(Object fn, Object x0, Object x1, Object x2, Object x3, Object x4, Object x5, Object x6, Object x7, Object x8, Object x9, Object x10, Object x11, Object x12, Object x13) { + return Py.obj(fn).call14(x0, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13); } public static Object call(Object f, Object... args) { - return Py.obj(f).call(args, NO_KW); + return (f instanceof PyObject ? (PyObject) f : Py.obj(f)).call(args, NO_KW); + } + + /// [#callKw] of a fixed arity: no argument array at the call site. + public static Object callKwF(Object fn, String[] kwNames, Object a) { + return Py.obj(fn).callKwF(kwNames, a); + } + + public static Object callKwF(Object fn, String[] kwNames, Object a, Object b) { + return Py.obj(fn).callKwF(kwNames, a, b); + } + + public static Object callKwF(Object fn, String[] kwNames, Object a, Object b, Object c) { + return Py.obj(fn).callKwF(kwNames, a, b, c); + } + + public static Object callKwF(Object fn, String[] kwNames, Object a, Object b, Object c, Object d) { + return Py.obj(fn).callKwF(kwNames, a, b, c, d); + } + + public static Object callKwF(Object fn, String[] kwNames, Object a, Object b, Object c, Object d, Object e) { + return Py.obj(fn).callKwF(kwNames, a, b, c, d, e); + } + + public static Object callKwF(Object fn, String[] kwNames, Object a, Object b, Object c, Object d, Object e, Object f) { + return Py.obj(fn).callKwF(kwNames, a, b, c, d, e, f); + } + + public static Object callKwF(Object fn, String[] kwNames, Object a, Object b, Object c, Object d, Object e, Object f, Object g) { + return Py.obj(fn).callKwF(kwNames, a, b, c, d, e, f, g); + } + + public static Object callKwF(Object fn, String[] kwNames, Object a, Object b, Object c, Object d, Object e, Object f, Object g, Object h) { + return Py.obj(fn).callKwF(kwNames, a, b, c, d, e, f, g, h); + } + + public static Object callKwF(Object fn, String[] kwNames, Object a, Object b, Object c, Object d, Object e, Object f, Object g, Object h, Object i) { + return Py.obj(fn).callKwF(kwNames, a, b, c, d, e, f, g, h, i); + } + + public static Object callKwF(Object fn, String[] kwNames, Object a, Object b, Object c, Object d, Object e, Object f, Object g, Object h, Object i, Object j) { + return Py.obj(fn).callKwF(kwNames, a, b, c, d, e, f, g, h, i, j); + } + + public static Object callKwF(Object fn, String[] kwNames, Object a, Object b, Object c, Object d, Object e, Object f, Object g, Object h, Object i, Object j, Object k) { + return Py.obj(fn).callKwF(kwNames, a, b, c, d, e, f, g, h, i, j, k); + } + + public static Object callKwF(Object fn, String[] kwNames, Object a, Object b, Object c, Object d, Object e, Object f, Object g, Object h, Object i, Object j, Object k, Object l) { + return Py.obj(fn).callKwF(kwNames, a, b, c, d, e, f, g, h, i, j, k, l); + } + + public static Object callKwF(Object fn, String[] kwNames, Object a, Object b, Object c, Object d, Object e, Object f, Object g, Object h, Object i, Object j, Object k, Object l, Object m) { + return Py.obj(fn).callKwF(kwNames, a, b, c, d, e, f, g, h, i, j, k, l, m); + } + + public static Object callKwF(Object fn, String[] kwNames, Object a, Object b, Object c, Object d, Object e, Object f, Object g, Object h, Object i, Object j, Object k, Object l, Object m, Object n) { + return Py.obj(fn).callKwF(kwNames, a, b, c, d, e, f, g, h, i, j, k, l, m, n); } public static Object callKw(Object f, Object[] args, String[] kwNames) { - return Py.obj(f).call(args, kwNames); + return (f instanceof PyObject ? (PyObject) f : Py.obj(f)).call(args, kwNames); } /// `obj.name(args)`, without materialising the bound method when `name` @@ -1704,7 +2230,7 @@ public static Object callMethod(Object o, String name, Object... args) { if (inst.own(name) == null) { Object m = inst.cls.lookup(name); if (m instanceof PyFunction) { - return Py.obj(m).call(prepend(o, args), NO_KW); + return ((PyFunction) m).call(prepend(o, args), NO_KW); } } } else if (!(o instanceof PyType) && !(o instanceof PyModule) && !(o instanceof PySuper)) { @@ -1712,7 +2238,7 @@ public static Object callMethod(Object o, String name, Object... args) { // from the MRO after the class it was made for, never from there. Object m = Py.typeOf(o).lookup(name); if (m instanceof PyBuiltin) { - return Py.obj(m).call(prepend(o, args), NO_KW); + return ((PyBuiltin) m).call(prepend(o, args), NO_KW); } } return Py.obj(Py.obj(o).getAttr(name)).call(args, NO_KW); @@ -1722,6 +2248,104 @@ public static Object callMethod(Object o, String name, Object... args) { /// lists each argument; `kinds` says 0 = plain, 1 = star, 2 = double star, /// 3 = keyword (name in `names` at the same index). public static Object callSpread(Object f, Object[] parts, int[] kinds, String[] names) { + // `f(*args, **kwargs)` forwarding a tuple and an empty dict, the + // usual shape of a wrapper (pdfplumber's render_char over super()): + // the arguments go straight into a fixed-arity call, with nothing + // gathered into lists or arrays on the way. + int npos = spreadCount(parts, kinds); + if (npos >= 0 && npos <= 14) { + PyObject fo = Py.obj(f); + switch (npos) { + case 0: + return fo.call0(); + case 1: + return fo.call1(spreadAt(parts, kinds, 0)); + case 2: + return fo.call2(spreadAt(parts, kinds, 0), spreadAt(parts, kinds, 1)); + case 3: + return fo.call3(spreadAt(parts, kinds, 0), spreadAt(parts, kinds, 1), spreadAt(parts, kinds, 2)); + case 4: + return fo.call4(spreadAt(parts, kinds, 0), spreadAt(parts, kinds, 1), spreadAt(parts, kinds, 2), spreadAt(parts, kinds, 3)); + case 5: + return fo.call5(spreadAt(parts, kinds, 0), spreadAt(parts, kinds, 1), spreadAt(parts, kinds, 2), spreadAt(parts, kinds, 3), spreadAt(parts, kinds, 4)); + case 6: + return fo.call6(spreadAt(parts, kinds, 0), spreadAt(parts, kinds, 1), spreadAt(parts, kinds, 2), spreadAt(parts, kinds, 3), spreadAt(parts, kinds, 4), spreadAt(parts, kinds, 5)); + case 7: + return fo.call7(spreadAt(parts, kinds, 0), spreadAt(parts, kinds, 1), spreadAt(parts, kinds, 2), spreadAt(parts, kinds, 3), spreadAt(parts, kinds, 4), spreadAt(parts, kinds, 5), spreadAt(parts, kinds, 6)); + case 8: + return fo.call8(spreadAt(parts, kinds, 0), spreadAt(parts, kinds, 1), spreadAt(parts, kinds, 2), spreadAt(parts, kinds, 3), spreadAt(parts, kinds, 4), spreadAt(parts, kinds, 5), spreadAt(parts, kinds, 6), spreadAt(parts, kinds, 7)); + case 9: + return fo.call9(spreadAt(parts, kinds, 0), spreadAt(parts, kinds, 1), spreadAt(parts, kinds, 2), spreadAt(parts, kinds, 3), spreadAt(parts, kinds, 4), spreadAt(parts, kinds, 5), spreadAt(parts, kinds, 6), spreadAt(parts, kinds, 7), spreadAt(parts, kinds, 8)); + case 10: + return fo.call10(spreadAt(parts, kinds, 0), spreadAt(parts, kinds, 1), spreadAt(parts, kinds, 2), spreadAt(parts, kinds, 3), spreadAt(parts, kinds, 4), spreadAt(parts, kinds, 5), spreadAt(parts, kinds, 6), spreadAt(parts, kinds, 7), spreadAt(parts, kinds, 8), spreadAt(parts, kinds, 9)); + case 11: + return fo.call11(spreadAt(parts, kinds, 0), spreadAt(parts, kinds, 1), spreadAt(parts, kinds, 2), spreadAt(parts, kinds, 3), spreadAt(parts, kinds, 4), spreadAt(parts, kinds, 5), spreadAt(parts, kinds, 6), spreadAt(parts, kinds, 7), spreadAt(parts, kinds, 8), spreadAt(parts, kinds, 9), spreadAt(parts, kinds, 10)); + case 12: + return fo.call12(spreadAt(parts, kinds, 0), spreadAt(parts, kinds, 1), spreadAt(parts, kinds, 2), spreadAt(parts, kinds, 3), spreadAt(parts, kinds, 4), spreadAt(parts, kinds, 5), spreadAt(parts, kinds, 6), spreadAt(parts, kinds, 7), spreadAt(parts, kinds, 8), spreadAt(parts, kinds, 9), spreadAt(parts, kinds, 10), spreadAt(parts, kinds, 11)); + case 13: + return fo.call13(spreadAt(parts, kinds, 0), spreadAt(parts, kinds, 1), spreadAt(parts, kinds, 2), spreadAt(parts, kinds, 3), spreadAt(parts, kinds, 4), spreadAt(parts, kinds, 5), spreadAt(parts, kinds, 6), spreadAt(parts, kinds, 7), spreadAt(parts, kinds, 8), spreadAt(parts, kinds, 9), spreadAt(parts, kinds, 10), spreadAt(parts, kinds, 11), spreadAt(parts, kinds, 12)); + case 14: + return fo.call14(spreadAt(parts, kinds, 0), spreadAt(parts, kinds, 1), spreadAt(parts, kinds, 2), spreadAt(parts, kinds, 3), spreadAt(parts, kinds, 4), spreadAt(parts, kinds, 5), spreadAt(parts, kinds, 6), spreadAt(parts, kinds, 7), spreadAt(parts, kinds, 8), spreadAt(parts, kinds, 9), spreadAt(parts, kinds, 10), spreadAt(parts, kinds, 11), spreadAt(parts, kinds, 12), spreadAt(parts, kinds, 13)); + default: + break; + } + } + return callSpreadGeneral(f, parts, kinds, names); + } + + /// The positional count of a call whose parts are plain values, tuples + /// and lists spread with `*`, and empty plain dicts spread with `**`; + /// -1 for any other call. + private static int spreadCount(Object[] parts, int[] kinds) { + int n = 0; + for (int i = 0; i < parts.length; i++) { + Object p = parts[i]; + switch (kinds[i]) { + case 0: + n++; + break; + case 1: + if (p instanceof PyTuple) { + n += ((PyTuple) p).size(); + } else if (p != null && p.getClass() == PyList.class) { + n += ((PyList) p).size; + } else { + return -1; + } + break; + case 2: + if (p == null || p.getClass() != PyDict.class || ((PyDict) p).size != 0) { + return -1; + } + break; + default: + return -1; + } + } + return n; + } + + /// Positional argument `j` of a call [#spreadCount] accepted. + private static Object spreadAt(Object[] parts, int[] kinds, int j) { + for (int i = 0; i < parts.length; i++) { + Object p = parts[i]; + if (kinds[i] == 0) { + if (j == 0) { + return p; + } + j--; + } else if (kinds[i] == 1) { + int n = p instanceof PyTuple ? ((PyTuple) p).size() : ((PyList) p).size; + if (j < n) { + return p instanceof PyTuple ? ((PyTuple) p).get(j) : ((PyList) p).get(j); + } + j -= n; + } + } + throw new IllegalStateException(); + } + + private static Object callSpreadGeneral(Object f, Object[] parts, int[] kinds, String[] names) { List pos = new ArrayList(); List kwn = new ArrayList(); List kwv = new ArrayList(); @@ -1767,7 +2391,7 @@ public static Object callSpread(Object f, Object[] parts, int[] kinds, String[] for (int i = 0; i < kwv.size(); i++) { args[pos.size() + i] = kwv.get(i); } - return Py.obj(f).call(args, kwn.toArray(new String[kwn.size()])); + return (f instanceof PyObject ? (PyObject) f : Py.obj(f)).call(args, kwn.toArray(new String[kwn.size()])); } public static Object[] prepend(Object first, Object[] rest) { @@ -1791,6 +2415,45 @@ public static long index(Object o) { throw typeError("indices must be integers or slices, not " + Py.typeOf(o).name); } + /// The index in `seq[key]`. An int no `long` holds is past either end of + /// any sequence, and is an IndexError as every other such index is. + public static long subscript(Object key) { + if (key instanceof Long) { + return ((Long) key).longValue(); + } + if (key instanceof PyInt && ((PyInt) key).big != null) { + throw indexError("cannot fit 'int' into an index-sized integer"); + } + return index(key); + } + + /// No names: the parameter table of a function that takes none. + public static final String[] NO_NAMES = new String[0]; + + /// The names in `joined`, one a line: how generated code writes a table + /// of names down as one constant. + public static String[] names(String joined) { + int n = 1; + for (int i = 0; i < joined.length(); i++) { + if (joined.charAt(i) == '\n') { + n++; + } + } + String[] out = new String[n]; + int at = 0; + for (int i = 0; i < n; i++) { + int end = joined.indexOf('\n', at); + if (end < 0) { + end = joined.length(); + } + // Interned, as the literals they stand for were: names are + // compared by identity before they are compared by value. + out[i] = joined.substring(at, end).intern(); + at = end + 1; + } + return out; + } + // ---- iteration ------------------------------------------------------- public static PyObject iter(Object o) { @@ -1801,6 +2464,28 @@ public static PyObject iter(Object o) { throw typeError("iter() returned non-iterator of type '" + typeOf(r).name + "'"); } + /// `next(it)`, where `f` is what the name `next` holds where it is + /// called: the builtin goes straight to the iterator. + public static Object nextB(Object f, Object it) { + if (f == Builtins.NEXT && it instanceof PyObject) { //NOPMD CompareObjectsWithEquals - identity is meant + Object v = ((PyObject) it).next(); + if (v == null) { + throw Builtins.exhausted(it); + } + return v; + } + return call(f, it); + } + + /// `next(it, default)`. + public static Object nextB(Object f, Object it, Object dflt) { + if (f == Builtins.NEXT && it instanceof PyObject) { //NOPMD CompareObjectsWithEquals - identity is meant + Object v = ((PyObject) it).next(); + return v != null ? v : dflt; + } + return call(f, it, dflt); + } + /// The next item of iterator `it`, or null when it is exhausted. public static Object next(Object it) { return ((PyObject) it).next(); @@ -1809,7 +2494,7 @@ public static Object next(Object it) { /// Materialises any iterable. public static Object[] toArray(Object o) { if (o instanceof PyTuple) { - return ((PyTuple) o).items; + return ((PyTuple) o).arr(); } if (o instanceof PyList) { return ((PyList) o).toArray(); @@ -1820,9 +2505,27 @@ public static Object[] toArray(Object o) { } /// `a, b = value`: exactly `n` items or `ValueError`. + /// [#unpack] for generated code, answering an empty array when `o` is + /// a fixed-size tuple of exactly `n` items (n is at least one): the + /// caller then reads them from the tuple, and no array is made for it. + public static Object[] unpackT(Object o, int n) { + if (o instanceof PyTuple && ((PyTuple) o).elems == null && ((PyTuple) o).size() == n) { + return NO_ARGS; + } + return unpack(o, n); + } + + /// [#unpackNames] answering an empty array as [#unpackT] does. + public static Object[] unpackNamesT(Object o, int n) { + if (o instanceof PyTuple && ((PyTuple) o).elems == null && ((PyTuple) o).size() == n) { + return NO_ARGS; + } + return unpackNames(o, n); + } + public static Object[] unpack(Object o, int n) { if (o instanceof PyTuple) { - Object[] items = ((PyTuple) o).items; + Object[] items = ((PyTuple) o).arr(); if (items.length == n) { return items; } @@ -1857,11 +2560,15 @@ public static Object[] unpackNames(Object o, int n) { if (o instanceof PyTuple) { // A tuple never changes, and the generated code only reads the // array it gets back, at once: its own items need no copy. - Object[] items = ((PyTuple) o).items; + Object[] items = ((PyTuple) o).arr(); if (items.length == n) { return items; } } + if (o instanceof ItemWalk && n == 2) { + // Read at once, like a tuple's items (see ItemWalk). + return ((ItemWalk) o).current; + } return unpack(o, n); } @@ -1903,6 +2610,35 @@ public static PyTuple tuple(Object... items) { return PyTuple.of(items); } + // `(a, b)` to `(a, ..., f)`: one object each, its items in fields. A + // tuple of one keeps the varargs form, whose single Object[] argument + // would otherwise bind here. + + public static PyTuple tuple(Object a, Object b) { + return new PyTuple.T2(a, b); + } + + public static PyTuple tuple(Object a, Object b, Object c) { + return new PyTuple.T3(a, b, c); + } + + public static PyTuple tuple(Object a, Object b, Object c, Object d) { + return new PyTuple.T4(a, b, c, d); + } + + public static PyTuple tuple(Object a, Object b, Object c, Object d, Object e) { + return new PyTuple.T5(a, b, c, d, e); + } + + public static PyTuple tuple(Object a, Object b, Object c, Object d, Object e, Object f) { + return new PyTuple.T6(a, b, c, d, e, f); + } + + /// `{}`, without the empty varargs array or a sized table. + public static PyDict dict() { + return new PyDict(); + } + /// `{k0: v0, k1: v1, ...}` from alternating keys and values. public static PyDict dict(Object... kv) { PyDict d = new PyDict(kv.length / 2); @@ -1943,6 +2679,16 @@ public static Object format(Object v, String spec) { return str(Formatting.format(v, spec)); } + /// One formatted piece of an f-string, as the Java string the generated + /// builder appends: a str under the empty spec is itself (str.__format__ + /// with no spec is the identity, and an exact str cannot override it). + public static String fmt(Object v, String spec) { + if (v instanceof String && spec.length() == 0) { + return (String) v; + } + return Formatting.format(v, spec); + } + /// Joins the pieces of an f-string. public static String concat(Object... parts) { StringBuilder sb = new StringBuilder(); @@ -2050,9 +2796,39 @@ public static Object callerModule(Object made, PyModule caller) { private static final java.util.Set FACTORY_MODULES = new java.util.HashSet(java.util.Arrays.asList( "__main__", "collections", "typing", "enum", "dataclasses")); + /// `isinstance(o, t)` as a condition in typed code: the builtin's answer + /// as a Java boolean, with no bool to box and test. + public static boolean isinstanceB(Object f, Object o, Object t) { + if (f == Builtins.ISINSTANCE) { //NOPMD CompareObjectsWithEquals - identity is meant + if (o instanceof PyInstance && ((PyInstance) o).cls == t) { //NOPMD CompareObjectsWithEquals - identity is meant + return true; + } + return isinstance(o, t); + } + return isTrue(call(f, o, t)); + } + + /// `typing.cast(t, o)` where typed code holds the result as `t`'s + /// compiled class: `o` when it is None or passes `isinstance(o, t)`, + /// TypeError otherwise -- never a wrongly typed object. + public static Object castChecked(Object o, Object t) { + if (o == null || o == NONE) { //NOPMD CompareObjectsWithEquals - identity is meant + // The typed caller holds a nullable T, whose None is null. + return null; + } + if (isinstance(o, t)) { + return o; + } + throw typeError("cast() to " + toStr(t) + " got " + toStr(typeOf(o))); + } + public static boolean isinstance(Object o, Object t) { + if (t instanceof PyType) { + // The common case first: a class, not a tuple or a union. + return ((PyType) t).instanceCheck(o); + } if (t instanceof PyTuple) { - Object[] items = ((PyTuple) t).items; + Object[] items = ((PyTuple) t).arr(); for (Object item : items) { if (isinstance(o, item)) { return true; @@ -2067,7 +2843,13 @@ public static boolean isinstance(Object o, Object t) { return ((PyUnion) t).instanceCheck(o); } if (!(t instanceof PyType)) { - throw typeError("isinstance() arg 2 must be a type, a tuple of types, or a union"); + // Any object whose type defines __instancecheck__ may stand on + // the right (typing.Mapping and the other generic aliases). + Object check = typeOf(t).lookup("__instancecheck__"); + if (check == null) { + throw typeError("isinstance() arg 2 must be a type, a tuple of types, or a union"); + } + return isTrue(call(check, t, o)); } return ((PyType) t).instanceCheck(o); } @@ -2133,6 +2915,12 @@ public static void importStar(PyModule target, PyModule m) { // ---- modules --------------------------------------------------------- /// `import name`. + /// How many calls so far built an argument array because the callee had + /// no fixed-arity path for their shape; see `ArgArrays.fallback`. + public static long argArrayFallbacks() { + return ArgArrays.fallbacks; + } + public static PyModule importModule(String name) { return PyModule.load(name); } diff --git a/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyAes.java b/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyAes.java new file mode 100644 index 00000000000..61f1b70befc --- /dev/null +++ b/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyAes.java @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.python.runtime; + + +/// `_cn1aes`: the AES block cipher the `cryptography` package's +/// `hazmat.primitives.ciphers` is written over. It is the platform's own, +/// through `com.codename1.io.Util`, so every port supplies the cipher and +/// none is written here. Only unpadded CBC is exposed; ECB is built from it a +/// block at a time on the Python side, and padding is the caller's, as in the +/// real package. +final class PyAes { + private static final String CBC = "AES/CBC/NoPadding"; + + private PyAes() { + } + + /// The port's AES, `com.codename1.io.Util` on a client, installed by + /// Cn1Platform. A server's class library has no cipher, so there it stays + /// null and the module reports that rather than failing to compile. + interface Cipher { + byte[] apply(boolean encrypt, String transformation, byte[] key, byte[] iv, byte[] data); + } + + private static Cipher cipher; + + static void setCipher(Cipher c) { + cipher = c; + } + + private static byte[] run(boolean encrypt, Object[] a) { + Cipher c = cipher; + if (c == null) { + throw Py.error(Py.NOT_IMPLEMENTED_ERROR, "AES is not available on this target"); + } + return c.apply(encrypt, CBC, PyBytes.like(a[0]), PyBytes.like(a[1]), PyBytes.like(a[2])); + } + + static PyModule module() { + PyModule m = new PyModule("_cn1aes", new String[0]); + m.setAttr("cbc_encrypt", PyBuiltin.positional("cbc_encrypt", a -> + new PyBytes(run(true, a)))); + m.setAttr("cbc_decrypt", PyBuiltin.positional("cbc_decrypt", a -> + new PyBytes(run(false, a)))); + return m; + } +} diff --git a/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyBinascii.java b/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyBinascii.java new file mode 100644 index 00000000000..5a00d7ecaf5 --- /dev/null +++ b/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyBinascii.java @@ -0,0 +1,152 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.python.runtime; + +/// `_cn1binascii`: the loops of the bundled `binascii`, which CPython runs in +/// C. The Python module still checks its arguments and raises every error, so +/// these see only bytes and answer `None` where the Python code must report. +final class PyBinascii { + private static final String ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + private static final byte[] B64 = new byte[64]; + private static final int[] REV = new int[256]; + private static final int[] CRC = new int[256]; + + static { + java.util.Arrays.fill(REV, -1); + for (int k = 0; k < 64; k++) { + B64[k] = (byte) ALPHABET.charAt(k); + REV[B64[k]] = k; + } + for (int k = 0; k < 256; k++) { + int c = k; + for (int j = 0; j < 8; j++) { + c = (c & 1) != 0 ? 0xEDB88320 ^ (c >>> 1) : c >>> 1; + } + CRC[k] = c; + } + } + + private PyBinascii() { + } + + static PyModule module() { + PyModule m = new PyModule("_cn1binascii", new String[0]); + m.setAttr("b2a_base64", PyBuiltin.fixed2("b2a_base64", (a0, a1) -> new PyBytes(encode(((PyBytes) a0).value, Py.isTrue(a1))))); + m.setAttr("a2b_base64", PyBuiltin.fixed1("a2b_base64", a0 -> decode(((PyBytes) a0).value))); + m.setAttr("crc32", PyBuiltin.fixed2("crc32", (a0, a1) -> Long.valueOf(crc32(((PyBytes) a0).value, Py.asLong(a1))))); + m.setAttr("crc_hqx", PyBuiltin.fixed2("crc_hqx", (a0, a1) -> Long.valueOf(crcHqx(((PyBytes) a0).value, (int) Py.asLong(a1))))); + return m; + } + + static byte[] encode(byte[] d, boolean newline) { + int n = d.length; + byte[] out = new byte[(n + 2) / 3 * 4 + (newline ? 1 : 0)]; + int i = 0; + int o = 0; + while (i + 2 < n) { + int v = (d[i] & 0xff) << 16 | (d[i + 1] & 0xff) << 8 | d[i + 2] & 0xff; + out[o] = B64[v >> 18]; + out[o + 1] = B64[v >> 12 & 63]; + out[o + 2] = B64[v >> 6 & 63]; + out[o + 3] = B64[v & 63]; + o += 4; + i += 3; + } + int rest = n - i; + if (rest > 0) { + int v = (d[i] & 0xff) << 16 | (rest == 2 ? (d[i + 1] & 0xff) << 8 : 0); + out[o] = B64[v >> 18]; + out[o + 1] = B64[v >> 12 & 63]; + out[o + 2] = rest == 2 ? B64[v >> 6 & 63] : (byte) '='; + out[o + 3] = (byte) '='; + o += 4; + } + if (newline) { + out[o] = (byte) '\n'; + } + return out; + } + + /// The non-strict decode of the Python module, or `None` when the input + /// ends mid-quantum: the Python code then runs and raises its error. + static Object decode(byte[] d) { + byte[] out = new byte[d.length / 4 * 3 + 3]; + int o = 0; + int acc = 0; + int bits = 0; + int quad = 0; + int pads = 0; + for (byte b : d) { + int c = b & 0xff; + if (c == '=') { + if (quad >= 2) { + pads++; + if (quad + pads >= 4) { + acc = 0; + bits = 0; + quad = 0; + pads = 0; + } + } + continue; + } + int v = REV[c]; + if (v < 0) { + continue; + } + pads = 0; + acc = acc << 6 | v; + bits += 6; + quad = (quad + 1) & 3; + if (bits >= 8) { + bits -= 8; + out[o++] = (byte) (acc >> bits); + acc &= (1 << bits) - 1; + } + } + if (quad != 0) { + return Py.NONE; + } + return new PyBytes(java.util.Arrays.copyOf(out, o)); + } + + static long crc32(byte[] d, long start) { + int c = ~(int) start; + for (byte b : d) { + c = CRC[(c ^ b) & 0xff] ^ (c >>> 8); + } + return ~c & 0xFFFFFFFFL; + } + + static int crcHqx(byte[] d, int value) { + int c = value & 0xFFFF; + for (byte b : d) { + c ^= (b & 0xff) << 8; + for (int j = 0; j < 8; j++) { + c = (c & 0x8000) != 0 ? (c << 1 ^ 0x1021) & 0xFFFF : c << 1 & 0xFFFF; + } + } + return c; + } +} diff --git a/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyBuiltin.java b/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyBuiltin.java index be942d92b85..7baee8fe148 100644 --- a/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyBuiltin.java +++ b/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyBuiltin.java @@ -56,11 +56,29 @@ public interface Three { public final String name; final Impl impl; + /// Set on a builtin subclass's own `__bool__` (see BuiltinSubclass): + /// the instance's truth is its base value's. + boolean baseTruth; private One one; private Two two; + /// A two-argument path that takes the receiver still wrapped, asked + /// only where [#two] is absent: see [#withSelf2]. + private Two selfTwo; private Three three; + private Four four; + private Five five; + private Six six; + private Seven seven; /// The builtin type a [#method] belongs to; null for a function. private final PyType owner; + /// `__qualname__` where it is not the name: a method made for a class in Python. + private String qual; + + /// Names the class this is a method of, for `__qualname__`. + PyBuiltin qual(String qualifiedName) { + qual = qualifiedName; + return this; + } public PyBuiltin(String name, Impl impl) { this(name, impl, null); @@ -73,6 +91,13 @@ private PyBuiltin(String name, Impl impl, PyType owner) { } /// A builtin that rejects keyword arguments, as most C functions do. + /// Adds a two-argument path to a builtin whose general form takes an array, so + /// `f(a, b)` reaches it without packing the arguments. + PyBuiltin withTwo(Two f) { + two = f; + return this; + } + public static PyBuiltin positional(final String name, final Positional p) { return new PyBuiltin(name, new Impl() { @Override @@ -85,6 +110,103 @@ public Object call(Object[] args, String[] kwNames) { }); } + /// [#positional] for an implementation that reads its argument array and + /// keeps nothing of it once it returns (its elements, yes; the array, no). + /// Its usual call, of `n` arguments, is then lent an array ([ArgArrays]) + /// rather than handed a new one per call. Any other count goes through + /// the array form unchanged. Not for a method of a builtin type. + static PyBuiltin lending(final String name, final int n, final Positional p) { + PyBuiltin b = positional(name, p); + switch (n) { + case 1: + b.one = x0 -> lend(p, ArgArrays.take(1), x0, null, null, null, null, null, null); + break; + case 2: + b.two = (x0, x1) -> lend(p, ArgArrays.take(2), x0, x1, null, null, null, null, null); + break; + case 3: + b.three = (x0, x1, x2) -> lend(p, ArgArrays.take(3), x0, x1, x2, null, null, null, null); + break; + case 4: + b.four = (x0, x1, x2, x3) -> lend(p, ArgArrays.take(4), x0, x1, x2, x3, null, null, null); + break; + case 5: + b.five = (x0, x1, x2, x3, x4) -> lend(p, ArgArrays.take(5), x0, x1, x2, x3, x4, null, null); + break; + case 6: + b.six = (x0, x1, x2, x3, x4, x5) -> lend(p, ArgArrays.take(6), x0, x1, x2, x3, x4, x5, null); + break; + case 7: + b.seven = (x0, x1, x2, x3, x4, x5, x6) -> lend(p, ArgArrays.take(7), x0, x1, x2, x3, x4, x5, x6); + break; + default: + throw new IllegalArgumentException("lending() covers one to seven arguments: " + n); + } + return b; + } + + private static Object lend(Positional p, Object[] a, Object x0, Object x1, Object x2, Object x3, Object x4, + Object x5, Object x6) { + int n = a.length; + a[0] = x0; + if (n > 1) { + a[1] = x1; + } + if (n > 2) { + a[2] = x2; + } + if (n > 3) { + a[3] = x3; + } + if (n > 4) { + a[4] = x4; + } + if (n > 5) { + a[5] = x5; + } + if (n > 6) { + a[6] = x6; + } + Object r = p.call(a); + ArgArrays.give(a); + return r; + } + + /// A builtin of exactly `n` arguments, whose fixed-arity call runs + /// without an argument array. + private static PyBuiltin fixed(final String name, final int n, final Positional p) { + return positional(name, a -> { + // Too few is an error; extra arguments are ignored, as the array + // implementations these replaced ignored them (__exit__). + if (a.length < n) { + throw Py.typeError(name + " expected " + n + (n == 1 ? " argument" : " arguments") + ", got " + + a.length); + } + return p.call(a); + }); + } + + /// [#fixed] for one argument. + public static PyBuiltin fixed1(final String name, final One f) { + PyBuiltin b = fixed(name, 1, a -> f.call(a[0])); + b.one = f; + return b; + } + + /// [#fixed] for two arguments. + public static PyBuiltin fixed2(final String name, final Two f) { + PyBuiltin b = fixed(name, 2, a -> f.call(a[0], a[1])); + b.two = f; + return b; + } + + /// [#fixed] for three arguments. + public static PyBuiltin fixed3(final String name, final Three f) { + PyBuiltin b = fixed(name, 3, a -> f.call(a[0], a[1], a[2])); + b.three = f; + return b; + } + /// A builtin of exactly one argument: `len`, `ord`, `repr`. public static PyBuiltin unary(final String name, final One f) { PyBuiltin b = positional(name, a -> { @@ -110,6 +232,57 @@ public PyBuiltin with2(Two f) { return this; } + /// The array-free two-argument path of a [#methodKwSelf] builtin: `f` + /// receives the receiver as it was passed, wrapped or not. + PyBuiltin withSelf2(Two f) { + selfTwo = f; + return this; + } + + /// [One] for four arguments. + public interface Four { + Object call(Object a, Object b, Object c, Object d); + } + + /// [#with1] for four arguments. + public PyBuiltin with4(Four f) { + four = f; + return this; + } + + /// [One] for five arguments. + public interface Five { + Object call(Object a, Object b, Object c, Object d, Object e); + } + + /// [#with1] for five arguments. + public PyBuiltin with5(Five f) { + five = f; + return this; + } + + /// [One] for six arguments. + public interface Six { + Object call(Object a, Object b, Object c, Object d, Object e, Object f); + } + + /// [One] for seven arguments. + public interface Seven { + Object call(Object a, Object b, Object c, Object d, Object e, Object f, Object g); + } + + /// [#with1] for six arguments; not for methods of a builtin type. + public PyBuiltin with6(Six f) { + six = f; + return this; + } + + /// [#with1] for seven arguments; not for methods of a builtin type. + public PyBuiltin with7(Seven f) { + seven = f; + return this; + } + /// [#with1] for three arguments. public PyBuiltin with3(Three f) { three = f; @@ -131,6 +304,10 @@ public Object call1(Object a) { @Override public Object call2(Object a, Object b) { if (two == null) { + if (selfTwo != null) { + receiver(a); + return selfTwo.call(a, b); + } return super.call2(a, b); } if (owner == null) { @@ -152,6 +329,46 @@ public Object call3(Object a, Object b, Object c) { return result(a, s, three.call(s, b, c)); } + @Override + public Object call4(Object a, Object b, Object c, Object d) { + if (four == null) { + return super.call4(a, b, c, d); + } + if (owner == null) { + return four.call(a, b, c, d); + } + Object s = receiver(a); + return result(a, s, four.call(s, b, c, d)); + } + + @Override + public Object call5(Object a, Object b, Object c, Object d, Object e) { + if (five == null) { + return super.call5(a, b, c, d, e); + } + if (owner == null) { + return five.call(a, b, c, d, e); + } + Object s = receiver(a); + return result(a, s, five.call(s, b, c, d, e)); + } + + @Override + public Object call6(Object a, Object b, Object c, Object d, Object e, Object f) { + if (six == null || owner != null) { + return super.call6(a, b, c, d, e, f); + } + return six.call(a, b, c, d, e, f); + } + + @Override + public Object call7(Object a, Object b, Object c, Object d, Object e, Object f, Object g) { + if (seven == null || owner != null) { + return super.call7(a, b, c, d, e, f, g); + } + return seven.call(a, b, c, d, e, f, g); + } + /// [#checkReceiver] and [#unwrap] for the receiver of a fixed-arity /// method call: the value the implementation works on. private Object receiver(Object self) { @@ -193,6 +410,33 @@ public Object call(Object[] args, String[] kwNames) { return b; } + /// A method of builtin type `owner` taking the receiver and `n - 1` + /// arguments, whose fixed-arity call runs without an argument array. + private static PyBuiltin methodN(final PyType owner, final String name, final int n, final Positional p) { + return method(owner, name, a -> { + if (a.length < n) { + throw Py.typeError(name + "() takes " + (n == 1 ? "no arguments" : "exactly " + (n - 1) + + (n == 2 ? " argument" : " arguments")) + " (" + (a.length - 1) + " given)"); + } + return p.call(a); + }); + } + + /// [#methodN] for the receiver alone. + public static PyBuiltin method1(final PyType owner, final String name, final One f) { + return methodN(owner, name, 1, a -> f.call(a[0])).with1(f); + } + + /// [#methodN] for the receiver and one argument. + public static PyBuiltin method2(final PyType owner, final String name, final Two f) { + return methodN(owner, name, 2, a -> f.call(a[0], a[1])).with2(f); + } + + /// [#methodN] for the receiver and two arguments. + public static PyBuiltin method3(final PyType owner, final String name, final Three f) { + return methodN(owner, name, 3, a -> f.call(a[0], a[1], a[2])).with3(f); + } + /// [#method] for an implementation that takes keyword arguments. public static PyBuiltin methodKw(final PyType owner, final String name, final Impl p) { PyBuiltin b = new PyBuiltin(name, new Impl() { @@ -207,6 +451,30 @@ public Object call(Object[] args, String[] kwNames) { return b; } + /// [#methodKw] for an implementation that unwraps its receiver itself + /// with [#base]: no copy of the arguments per call. + static PyBuiltin methodKwSelf(final PyType owner, final String name, final Impl p) { + return new PyBuiltin(name, new Impl() { + @Override + public Object call(Object[] args, String[] kwNames) { + checkReceiver(owner, name, args); + return p.call(args, kwNames); + } + }, owner); + } + + /// The builtin value an instance of a subclass of builtin `owner` + /// extends, or `self` itself. + static Object base(PyType owner, Object self) { + if (owner != Py.OBJECT_TYPE && self instanceof PyInstance) { //NOPMD CompareObjectsWithEquals - identity is meant + Object b = ((PyInstance) self).base; + if (b != null) { + return b; + } + } + return self; + } + /// The arguments with an instance of a subclass of builtin `owner` /// replaced by the builtin value it extends, which is what the /// implementation works on. A method returning that value (a chained @@ -216,8 +484,7 @@ static Object[] unwrap(PyType owner, Object[] args) { if (owner != Py.OBJECT_TYPE && self instanceof PyInstance) { //NOPMD CompareObjectsWithEquals - identity is meant Object b = ((PyInstance) self).base; if (b != null) { - Object[] a = new Object[args.length]; - System.arraycopy(args, 0, a, 0, args.length); + Object[] a = args.clone(); a[0] = b; return a; } @@ -240,8 +507,38 @@ public PyType type() { return Py.BUILTIN_TYPE; } + /// Adds fixed-arity calls of one and two arguments to a builtin whose + /// general form parses an argument list: the usual call then builds no + /// array and no parser. Either may be null. + PyBuiltin withFixed(One f1, Two f2) { + one = f1; + two = f2; + return this; + } + + /// For a method whose implementation keeps nothing of its argument + /// array once it returns: the two-argument call (`list.__init__(self, + /// it)` from a subclass constructor) is lent an array ([ArgArrays]). + PyBuiltin lendingTwo() { + final Impl p = impl; + two = (x0, x1) -> { + Object[] a = ArgArrays.take(2); + a[0] = x0; + a[1] = x1; + Object r = p.call(a, Py.NO_KW); + ArgArrays.give(a); + return r; + }; + return this; + } + @Override public Object bind(Object self) { + if ("__new__".equals(name)) { + // Every __new__ is a static method: `self.__new__(cls)` reads + // the function as it is, with nothing bound. + return this; + } return new PyMethod(self, this); } @@ -252,6 +549,9 @@ public Object call(Object[] args, String[] kwNames) { @Override public Object getAttrOrNull(String attr) { + if ("__qualname__".equals(attr) && qual != null) { + return qual; + } if ("__name__".equals(attr) || "__qualname__".equals(attr)) { return name; } diff --git a/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyByteArray.java b/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyByteArray.java index 8e35cc9d276..5aa2dbe0c07 100644 --- a/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyByteArray.java +++ b/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyByteArray.java @@ -186,7 +186,7 @@ private static byte byteOf(Object v) { } private int index(Object key) { - long i = Py.index(key); + long i = Py.subscript(key); if (i < 0) { i += size; } @@ -317,24 +317,24 @@ static void install() { return toArray(Py.obj(Py.BYTES_TYPE.lookup(name)).call(mapped, kw)); })); } - t.define("append", PyBuiltin.method(t, "append", a -> { - PyByteArray b = self(a[0]); - b.insertAt(b.size, new byte[] {byteOf(a[1])}); + t.define("append", PyBuiltin.method2(t, "append", (a0, a1) -> { + PyByteArray b = self(a0); + b.insertAt(b.size, new byte[] {byteOf(a1)}); return Py.NONE; })); - t.define("extend", PyBuiltin.method(t, "extend", a -> { - PyByteArray b = self(a[0]); - byte[] src = PyBytes.like(a[1]); - b.insertAt(b.size, src != null ? src : PyBytes.fromInts(a[1])); + t.define("extend", PyBuiltin.method2(t, "extend", (a0, a1) -> { + PyByteArray b = self(a0); + byte[] src = PyBytes.like(a1); + b.insertAt(b.size, src != null ? src : PyBytes.fromInts(a1)); return Py.NONE; })); - t.define("insert", PyBuiltin.method(t, "insert", a -> { - PyByteArray b = self(a[0]); - long i = Py.index(a[1]); + t.define("insert", PyBuiltin.method3(t, "insert", (a0, a1, a2) -> { + PyByteArray b = self(a0); + long i = Py.index(a1); if (i < 0) { i = Math.max(0, i + b.size); } - b.insertAt((int) Math.min(i, b.size), new byte[] {byteOf(a[2])}); + b.insertAt((int) Math.min(i, b.size), new byte[] {byteOf(a2)}); return Py.NONE; })); t.define("pop", PyBuiltin.method(t, "pop", a -> { @@ -347,9 +347,9 @@ static void install() { b.removeRange(i, i + 1); return PyInt.of(v); })); - t.define("remove", PyBuiltin.method(t, "remove", a -> { - PyByteArray b = self(a[0]); - byte v = byteOf(a[1]); + t.define("remove", PyBuiltin.method2(t, "remove", (a0, a1) -> { + PyByteArray b = self(a0); + byte v = byteOf(a1); for (int i = 0; i < b.size; i++) { if (b.buf[i] == v) { b.removeRange(i, i + 1); @@ -358,12 +358,12 @@ static void install() { } throw Py.valueError("value not found in bytearray"); })); - t.define("clear", PyBuiltin.method(t, "clear", a -> { - self(a[0]).size = 0; + t.define("clear", PyBuiltin.method1(t, "clear", a0 -> { + self(a0).size = 0; return Py.NONE; })); - t.define("reverse", PyBuiltin.method(t, "reverse", a -> { - PyByteArray b = self(a[0]); + t.define("reverse", PyBuiltin.method1(t, "reverse", a0 -> { + PyByteArray b = self(a0); for (int i = 0, j = b.size - 1; i < j; i++, j--) { byte x = b.buf[i]; b.buf[i] = b.buf[j]; @@ -371,12 +371,22 @@ static void install() { } return Py.NONE; })); - t.define("copy", PyBuiltin.method(t, "copy", a -> new PyByteArray(self(a[0]).bytes()))); + t.define("copy", PyBuiltin.method1(t, "copy", a0 -> new PyByteArray(self(a0).bytes()))); t.define("maketrans", Py.BYTES_TYPE.lookup("maketrans")); - t.define("fromhex", new PyClassMethod(PyBuiltin.positional("fromhex", a -> { + t.define("fromhex", new PyClassMethod(PyBuiltin.fixed2("fromhex", (a0, a1) -> { Object b = Py.obj(Py.BYTES_TYPE.lookup("fromhex")).bind(Py.BYTES_TYPE); - return new PyByteArray(((PyBytes) Py.call(b, a[1])).value); + return new PyByteArray(((PyBytes) Py.call(b, a1)).value); }))); + t.unary = x -> { + if (x instanceof String || x instanceof PyStr) { + throw Py.typeError("string argument without an encoding"); + } + Object b = PyBytes.fromOne(Py.BYTES_TYPE, x); + if (!(b instanceof PyBytes)) { + throw Py.typeError("cannot convert '" + Py.typeOf(x).name + "' object to bytearray"); + } + return new PyByteArray(((PyBytes) b).bytes()); + }; t.factory = (type, args, kw) -> { if (args.length == 0) { return new PyByteArray(new byte[0]); diff --git a/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyBytes.java b/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyBytes.java index be27b9f28ea..ff47b8ea90e 100644 --- a/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyBytes.java +++ b/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyBytes.java @@ -25,12 +25,36 @@ /// Python's `bytes`, immutable. public final class PyBytes extends PyObject { + private static final String HEX_DIGITS = "0123456789abcdef"; + final byte[] value; public PyBytes(byte[] value) { this.value = value; } + /// The empty and the one-byte values, shared as CPython shares them: a + /// tokenizer's `s[j:j + 1]` (pdfminer's psparser, once per character) + /// otherwise allocates a byte array and a bytes object every time. + private static final PyBytes[] SMALL = new PyBytes[257]; + + /// `v[lo:hi]` as a new bytes, or the shared value for zero or one byte. + static PyBytes range(byte[] v, int lo, int hi) { + int n = hi <= lo ? 0 : hi - lo; + if (n <= 1) { + int k = n == 0 ? 256 : v[lo] & 0xff; + PyBytes b = SMALL[k]; + if (b == null) { + b = new PyBytes(n == 0 ? new byte[0] : new byte[] {v[lo]}); + SMALL[k] = b; + } + return b; + } + byte[] out = new byte[n]; + System.arraycopy(v, lo, out, 0, n); + return new PyBytes(out); + } + @Override public PyType type() { return Py.BYTES_TYPE; @@ -262,13 +286,17 @@ public Object getItem(Object key) { if (key instanceof PySlice) { int[] r = ((PySlice) key).indices(value.length); int n = PySlice.length(r); + if (r[2] == 1) { + // A plain slice is one block copy, not a checked store per element. + return range(value, r[0], r[0] + n); + } byte[] out = new byte[n]; for (int i = 0, j = r[0]; i < n; i++, j += r[2]) { out[i] = value[j]; } return new PyBytes(out); } - long i = Py.index(key); + long i = Py.subscript(key); if (i < 0) { i += value.length; } @@ -288,13 +316,41 @@ Object at(int i) { }; } + /// `v.hex()`: two digits a byte, straight from the table (the general + /// digit writer measures how many digits each value needs first). + /// Measured against ASCII bytes made a str by `new String(byte[])`: the + /// constructor's charset handling cost more than the appends. Measured again + /// against a byte table and `new String(out, 0, n, "ISO-8859-1")`: slower + /// still on ParparVM -- every store into the result was bounds checked and + /// the decode copied once more -- where the builder's appends are inlined. + static String hexOf(byte[] v) { + StringBuilder sb = new StringBuilder(v.length * 2); + for (byte x : v) { + sb.append(HEX_DIGITS.charAt(x >> 4 & 15)).append(HEX_DIGITS.charAt(x & 15)); + } + return sb.toString(); + } + static void install() { - Py.BYTES_TYPE.define("decode", PyBuiltin.methodKw(Py.BYTES_TYPE, "decode", (a, kw) -> { + final PyBuiltin decode = PyBuiltin.methodKw(Py.BYTES_TYPE, "decode", (a, kw) -> { + // `b.decode()` and `b.decode("utf-8")`, bound without Args. + if ((kw == null || kw.length == 0) && a.length <= 2 && a[0] instanceof PyBytes + && (a.length == 1 || a[1] instanceof String)) { + return Codecs.decodeKeep(((PyBytes) a[0]).value, a.length == 1 ? "utf-8" : (String) a[1], "strict"); + } Object[] p = Args.bind("decode", a, kw, new String[] {"self", "encoding", "errors"}, new Object[] {null, Py.str("utf-8"), Py.str("strict")}); - return Py.str(Codecs.decode(((PyBytes) p[0]).value, Py.toStr(p[1]), Py.toStr(p[2]))); - })); - Py.BYTES_TYPE.define("hex", PyBuiltin.methodKw(Py.BYTES_TYPE, "hex", (args, kw) -> { + return Py.str(Codecs.decodeKeep(((PyBytes) p[0]).value, Py.toStr(p[1]), Py.toStr(p[2]))); + }); + // `b.decode()` and `b.decode("utf-8")` once more, without an argument array: the + // method-call site hands a builtin its receiver and argument directly. + decode.with1(b -> b instanceof PyBytes ? Codecs.decodeKeep(((PyBytes) b).value, "utf-8", "strict") + : decode.impl.call(new Object[] {b}, Py.NO_KW)); + decode.with2((b, e) -> b instanceof PyBytes && e instanceof String + ? Codecs.decodeKeep(((PyBytes) b).value, (String) e, "strict") + : decode.impl.call(new Object[] {b, e}, Py.NO_KW)); + Py.BYTES_TYPE.define("decode", decode); + PyBuiltin hex = PyBuiltin.methodKw(Py.BYTES_TYPE, "hex", (args, kw) -> { Object[] p = Args.bind("hex", args, kw, new String[] {"self", "sep", "bytes_per_sep"}, new Object[] {null, Py.NONE, PyInt.of(1)}); byte[] v = self(p[0]).value; @@ -323,10 +379,14 @@ static void install() { PyStr.hex(sb, v[i] & 0xff, 2); } return Py.str(sb.toString()); - })); + }); + // `b.hex()`, as every hexdigest() asks it: no separator to bind, so no + // argument arrays and no defaults built per call. + hex.with1(b -> Py.str(hexOf(self(b).value))); + Py.BYTES_TYPE.define("hex", hex); installLatin1Delegates(); - Py.BYTES_TYPE.define("fromhex", new PyClassMethod(PyBuiltin.positional("fromhex", a -> { - String h = Py.toStr(a[1]); + Py.BYTES_TYPE.define("fromhex", new PyClassMethod(PyBuiltin.fixed2("fromhex", (a0, a1) -> { + String h = Py.toStr(a1); java.io.ByteArrayOutputStream out = new java.io.ByteArrayOutputStream(); int i = 0; while (i < h.length()) { @@ -346,28 +406,37 @@ static void install() { } return new PyBytes(out.toByteArray()); }))); - Py.BYTES_TYPE.define("upper", PyBuiltin.method(Py.BYTES_TYPE, "upper", a -> asciiCase((PyBytes) a[0], true))); - Py.BYTES_TYPE.define("lower", PyBuiltin.method(Py.BYTES_TYPE, "lower", a -> asciiCase((PyBytes) a[0], false))); - Py.BYTES_TYPE.define("isdigit", PyBuiltin.method(Py.BYTES_TYPE, "isdigit", - a -> Py.bool(allAscii((PyBytes) a[0], "0123456789")))); - Py.BYTES_TYPE.define("isalpha", PyBuiltin.method(Py.BYTES_TYPE, "isalpha", - a -> Py.bool(allAscii((PyBytes) a[0], LETTERS)))); - Py.BYTES_TYPE.define("isalnum", PyBuiltin.method(Py.BYTES_TYPE, "isalnum", - a -> Py.bool(allAscii((PyBytes) a[0], LETTERS + "0123456789")))); - Py.BYTES_TYPE.define("isspace", PyBuiltin.method(Py.BYTES_TYPE, "isspace", - a -> Py.bool(allAscii((PyBytes) a[0], " \t\n\r\u000b\f")))); + Py.BYTES_TYPE.define("upper", PyBuiltin.method1(Py.BYTES_TYPE, "upper", a0 -> asciiCase((PyBytes) a0, true))); + Py.BYTES_TYPE.define("lower", PyBuiltin.method1(Py.BYTES_TYPE, "lower", a0 -> asciiCase((PyBytes) a0, false))); + Py.BYTES_TYPE.define("isdigit", PyBuiltin.method1(Py.BYTES_TYPE, "isdigit", a0 -> Py.bool(allAscii((PyBytes) a0, "0123456789")))); + Py.BYTES_TYPE.define("isalpha", PyBuiltin.method1(Py.BYTES_TYPE, "isalpha", a0 -> Py.bool(allAscii((PyBytes) a0, LETTERS)))); + Py.BYTES_TYPE.define("isalnum", PyBuiltin.method1(Py.BYTES_TYPE, "isalnum", a0 -> Py.bool(allAscii((PyBytes) a0, LETTERS + "0123456789")))); + Py.BYTES_TYPE.define("isspace", PyBuiltin.method1(Py.BYTES_TYPE, "isspace", a0 -> Py.bool(allAscii((PyBytes) a0, " \t\n\r\u000b\f")))); installAsciiText(); - Py.BYTES_TYPE.factory = (t, args, kw) -> { - if (args.length == 0) { - return new PyBytes(new byte[0]); - } - Object x = args[0]; + Py.BYTES_TYPE.factory = (t, args, kw) -> args.length == 0 ? new PyBytes(new byte[0]) : fromOne(t, args[0]); + Py.BYTES_TYPE.unary = x -> fromOne(Py.BYTES_TYPE, x); + } + + /// `t(x)` for bytes or a subclass `t`. + static Object fromOne(PyType t, Object x) { + { if (x instanceof String) { return new PyBytes(Utf8.encode(((String) x))); } if (Py.isInt(x)) { return new PyBytes(new byte[(int) Py.asLong(x)]); } + if (x instanceof PyBytes && t == Py.BYTES_TYPE) { //NOPMD CompareObjectsWithEquals - identity is meant + // bytes(b) is b: it cannot change. Hashing and I/O code calls + // this on every buffer it is handed. + return x; + } + if (x instanceof PyByteArray) { + return new PyBytes(((PyByteArray) x).bytes()); + } + if (x instanceof PyMemoryView) { + return new PyBytes(((PyMemoryView) x).bytes().clone()); + } Object[] items = Py.toArray(x); byte[] r = new byte[items.length]; for (int i = 0; i < items.length; i++) { @@ -378,7 +447,7 @@ static void install() { r[i] = (byte) v; } return new PyBytes(r); - }; + } } private static boolean isUpper(int c) { @@ -443,17 +512,23 @@ private static void installAsciiText() { for (byte e : del) { drop[e & 0xff] = true; } - java.io.ByteArrayOutputStream out = new java.io.ByteArrayOutputStream(v.length); + byte[] out = new byte[v.length]; + int n = 0; for (byte el : v) { int c = el & 0xff; if (!drop[c]) { - out.write(table == null ? c : table[c] & 0xff); + out[n++] = table == null ? el : table[c]; } } - return new PyBytes(out.toByteArray()); + if (n != out.length) { + byte[] cut = new byte[n]; + System.arraycopy(out, 0, cut, 0, n); + out = cut; + } + return new PyBytes(out); })); - t.define("isascii", PyBuiltin.method(t, "isascii", a -> { - byte[] v = self(a[0]).value; + t.define("isascii", PyBuiltin.method1(t, "isascii", a0 -> { + byte[] v = self(a0).value; for (byte e : v) { if (e < 0) { return Py.FALSE; @@ -461,10 +536,10 @@ private static void installAsciiText() { } return Py.TRUE; })); - t.define("islower", PyBuiltin.method(t, "islower", a -> Py.bool(cased(self(a[0]).value, false)))); - t.define("isupper", PyBuiltin.method(t, "isupper", a -> Py.bool(cased(self(a[0]).value, true)))); - t.define("istitle", PyBuiltin.method(t, "istitle", a -> { - byte[] v = self(a[0]).value; + t.define("islower", PyBuiltin.method1(t, "islower", a0 -> Py.bool(cased(self(a0).value, false)))); + t.define("isupper", PyBuiltin.method1(t, "isupper", a0 -> Py.bool(cased(self(a0).value, true)))); + t.define("istitle", PyBuiltin.method1(t, "istitle", a0 -> { + byte[] v = self(a0).value; boolean cased = false; boolean prevCased = false; for (byte e : v) { @@ -487,8 +562,8 @@ private static void installAsciiText() { } return Py.bool(cased); })); - t.define("swapcase", PyBuiltin.method(t, "swapcase", a -> { - byte[] v = self(a[0]).value; + t.define("swapcase", PyBuiltin.method1(t, "swapcase", a0 -> { + byte[] v = self(a0).value; byte[] r = new byte[v.length]; for (int i = 0; i < v.length; i++) { int c = v[i] & 0xff; @@ -496,8 +571,8 @@ private static void installAsciiText() { } return new PyBytes(r); })); - t.define("capitalize", PyBuiltin.method(t, "capitalize", a -> { - byte[] v = self(a[0]).value; + t.define("capitalize", PyBuiltin.method1(t, "capitalize", a0 -> { + byte[] v = self(a0).value; byte[] r = new byte[v.length]; for (int i = 0; i < v.length; i++) { int c = v[i] & 0xff; @@ -509,8 +584,8 @@ private static void installAsciiText() { } return new PyBytes(r); })); - t.define("title", PyBuiltin.method(t, "title", a -> { - byte[] v = self(a[0]).value; + t.define("title", PyBuiltin.method1(t, "title", a0 -> { + byte[] v = self(a0).value; byte[] r = new byte[v.length]; boolean prevCased = false; for (int i = 0; i < v.length; i++) { @@ -556,7 +631,14 @@ private static boolean cased(byte[] v, boolean upper) { private static void installLatin1Delegates() { for (String e : LATIN1_DELEGATES) { final String name = e; + final int search = searchKind(name); Py.BYTES_TYPE.define(name, PyBuiltin.methodKw(Py.BYTES_TYPE, name, (args, kw) -> { + if (search != 0 && args.length >= 2 && args.length <= 4 && kw.length == 0) { + Object r = searched(search, args); + if (r != null) { + return r; + } + } Object[] mapped = new Object[args.length]; for (int k = 0; k < args.length; k++) { Object v = args[k]; @@ -572,14 +654,211 @@ private static void installLatin1Delegates() { } } + /// Which of the searches [#searched] answers `name` is, 0 for none of them. + private static int searchKind(String name) { + if ("startswith".equals(name)) { + return 1; + } + if ("endswith".equals(name)) { + return 2; + } + if ("find".equals(name)) { + return 3; + } + if ("rfind".equals(name)) { + return 4; + } + if ("count".equals(name)) { + return 5; + } + return 0; + } + + /// A search of one bytes value for another, with no range, done on the bytes + /// themselves; null for any other call, which goes the long way. That way maps + /// the whole receiver to text first, so testing how a file starts + /// (`data.startswith(b"%PDF-")`, and a type sniffer asks that a dozen times) + /// copied the file twice per question. + /// + /// The optional start and end are taken as slice bounds, the way CPython's + /// `ADJUST_INDICES` takes them. A tokenizer scans a buffer with + /// `data.find(b">>", pos)`; that form used to copy the whole buffer to text + /// on every call, which made scanning a file quadratic in its size. + private static Object searched(int kind, Object[] args) { + byte[] h = like(args[0]); + if (h == null) { + return null; + } + Object arg = args[1]; + int lo = 0; + int hi = h.length; + if (args.length > 2) { + long[] r = window(h.length, args); + if (r.length == 0) { + return null; + } + lo = (int) r[0]; + hi = (int) r[1]; + if (lo > h.length) { + // Past the end: nothing is found, not even an empty needle. + return kind <= 2 ? Py.FALSE : kind == 5 ? PyInt.of(0) : PyInt.of(-1); + } + } + if (kind >= 3 && arg instanceof Long) { + long v = ((Long) arg).longValue(); + if (v < 0 || v > 255) { + return null; + } + arg = new PyBytes(new byte[] {(byte) v}); + } + if (lo != 0 || hi != h.length) { + return searchedIn(kind, h, lo, hi, arg); + } + if (kind <= 2 && arg instanceof PyTuple) { + Object[] each = ((PyTuple) arg).arr(); + for (Object one : each) { + if (like(one) == null) { + return null; + } + } + for (Object one : each) { + byte[] n = like(one); + if (matchesAt(h, n, kind == 1 ? 0 : h.length - n.length)) { + return Py.TRUE; + } + } + return Py.FALSE; + } + byte[] n = like(arg); + if (n == null) { + return null; + } + if (kind == 1) { + return Py.bool(matchesAt(h, n, 0)); + } + if (kind == 2) { + return Py.bool(matchesAt(h, n, h.length - n.length)); + } + if (n.length == 0) { + return null; + } + if (kind == 3) { + for (int i = 0; i + n.length <= h.length; i++) { + if (h[i] == n[0] && matchesAt(h, n, i)) { + return PyInt.of(i); + } + } + return PyInt.of(-1); + } + if (kind == 4) { + for (int i = h.length - n.length; i >= 0; i--) { + if (h[i] == n[0] && matchesAt(h, n, i)) { + return PyInt.of(i); + } + } + return PyInt.of(-1); + } + int count = 0; + int i = 0; + while (i + n.length <= h.length) { + if (h[i] == n[0] && matchesAt(h, n, i)) { + count++; + i += n.length; + } else { + i++; + } + } + return PyInt.of(count); + } + + /// The start and end of a ranged search, clamped as slice bounds except that + /// a start past the end is kept so the caller can answer it; empty when + /// either is neither an int nor None. + private static final long[] NO_WINDOW = new long[0]; + + private static long[] window(int len, Object[] args) { + long lo = 0; + long hi = len; + Object a = args[2]; + if (a instanceof Long) { + lo = ((Long) a).longValue(); + if (lo < 0) { + lo = Math.max(0, lo + len); + } + } else if (a != Py.NONE) { //NOPMD CompareObjectsWithEquals - identity is meant + return NO_WINDOW; + } + if (args.length > 3) { + Object b = args[3]; + if (b instanceof Long) { + hi = ((Long) b).longValue(); + hi = hi < 0 ? Math.max(0, hi + len) : Math.min(hi, len); + } else if (b != Py.NONE) { //NOPMD CompareObjectsWithEquals - identity is meant + return NO_WINDOW; + } + } + return new long[] {lo, hi}; + } + + /// [#searched] over `h[lo:hi]`, `lo` at most the length; null for what it + /// leaves to the long way (a tuple of prefixes, an empty needle). + private static Object searchedIn(int kind, byte[] h, int lo, int hi, Object arg) { + byte[] n = like(arg); + if (n == null || n.length == 0) { + return null; + } + if (kind == 1) { + return Py.bool(hi - lo >= n.length && matchesAt(h, n, lo)); + } + if (kind == 2) { + return Py.bool(hi - lo >= n.length && matchesAt(h, n, hi - n.length)); + } + if (kind == 3) { + byte first = n[0]; + for (int i = lo; i + n.length <= hi; i++) { + if (h[i] == first && matchesAt(h, n, i)) { + return PyInt.of(i); + } + } + return PyInt.of(-1); + } + if (kind == 4) { + for (int i = hi - n.length; i >= lo; i--) { + if (h[i] == n[0] && matchesAt(h, n, i)) { + return PyInt.of(i); + } + } + return PyInt.of(-1); + } + int count = 0; + int i = lo; + while (i + n.length <= hi) { + if (h[i] == n[0] && matchesAt(h, n, i)) { + count++; + i += n.length; + } else { + i++; + } + } + return PyInt.of(count); + } + + private static boolean matchesAt(byte[] h, byte[] n, int at) { + if (at < 0 || at + n.length > h.length) { + return false; + } + for (int i = 0; i < n.length; i++) { + if (h[at + i] != n[i]) { + return false; + } + } + return true; + } + private static Object toLatin1(Object o) { byte[] v = like(o); if (v != null) { - char[] c = new char[v.length]; - for (int i = 0; i < v.length; i++) { - c[i] = (char) (v[i] & 0xff); - } - return new String(c); + return Codecs.latin1(v, 0, v.length); } if (o instanceof String) { throw Py.typeError("a bytes-like object is required, not 'str'"); diff --git a/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyCode.java b/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyCode.java index 154c45c88b0..205ce7dd78a 100644 --- a/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyCode.java +++ b/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyCode.java @@ -68,7 +68,7 @@ public Object getAttrOrNull(String attr) { case "co_argcount": return Py.of((long) f.positional); case "co_posonlyargcount": - return Py.of(0L); + return Py.of((long) f.positionalOnly); case "co_kwonlyargcount": return Py.of((long) f.kwOnly); case "co_varnames": diff --git a/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyCollections.java b/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyCollections.java new file mode 100644 index 00000000000..90c18ba239e --- /dev/null +++ b/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyCollections.java @@ -0,0 +1,198 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.python.runtime; + +/// `_cn1collections`: the parts of `collections` CPython runs in C +/// (`_collections`, `_tuplegetter`), which the Python module builds on. +/// A namedtuple's `__new__` took `*args, **kwargs` and filled a list field +/// by field on every construction (`urlparse` builds one per link), each +/// field read went through `property(itemgetter(i))`, and `defaultdict()` +/// bound `*args, **kwargs` to pass nothing on to `dict.__init__`. +final class PyCollections { + + private PyCollections() { + } + + static PyModule module() { + PyModule m = new PyModule("_cn1collections", new String[0]); + m.setAttr("tuplegetter", PyBuiltin.fixed2("tuplegetter", (i, doc) -> tupleGetter((int) Py.index(i)))); + m.setAttr("nt_new", PyBuiltin.fixed3("nt_new", (tn, names, defs) -> + ntNew(Py.toStr(tn), ((PyTuple) names).arr(), (PyDict) defs))); + m.setAttr("dd_init", new PyBuiltin("__init__", PyCollections::ddInit) + .with1(self -> ddInit(self, Py.NONE)).with2(PyCollections::ddInit)); + m.setAttr("dd_missing", PyBuiltin.fixed2("__missing__", PyCollections::missing)); + return m; + } + + /// The property a namedtuple field reads through: item `i` of the tuple. + private static PyProperty tupleGetter(final int i) { + return new PyProperty(PyBuiltin.fixed1("_tuplegetter", self -> item(self, i)), Py.NONE, Py.NONE); + } + + private static Object item(Object self, int i) { + if (self instanceof PyInstance) { + Object b = ((PyInstance) self).base; + if (b instanceof PyTuple) { + Object[] items = ((PyTuple) b).arr(); + if (i < items.length) { + return items[i]; + } + } + } + return Py.getitem(self, Long.valueOf(i)); + } + + /// The namedtuple instance of `cls` holding `vals`. + private static Object build(Object cls, Object[] vals) { + if (cls instanceof PyType && cls != Py.TUPLE_TYPE && ((PyType) cls).isSubtype(Py.TUPLE_TYPE)) { //NOPMD CompareObjectsWithEquals - identity is meant + PyInstance o = ((PyType) cls).newInstance(); + o.base = new PyTuple(vals); + return o; + } + return Py.obj(Py.getattr(Py.TUPLE_TYPE, "__new__")).call2(cls, new PyTuple(vals)); + } + + /// The `__new__` of a namedtuple with fields `names`: a call passing + /// every field positionally builds the tuple from its arguments, any + /// other binds as the generated `__new__(_cls, a, b=..., ...)` would. + private static PyBuiltin ntNew(final String tn, final Object[] names, final PyDict defs) { + final int n = names.length; + PyBuiltin b = new PyBuiltin("__new__", (args, kw) -> ntBind(tn, names, defs, args, kw)); + switch (n) { + case 0: + b.with1(c -> build(c, new Object[0])); + break; + case 1: + b.with2((c, x0) -> build(c, new Object[] {x0})); + break; + case 2: + b.with3((c, x0, x1) -> build(c, new Object[] {x0, x1})); + break; + case 3: + b.with4((c, x0, x1, x2) -> build(c, new Object[] {x0, x1, x2})); + break; + case 4: + b.with5((c, x0, x1, x2, x3) -> build(c, new Object[] {x0, x1, x2, x3})); + break; + case 5: + b.with6((c, x0, x1, x2, x3, x4) -> build(c, new Object[] {x0, x1, x2, x3, x4})); + break; + case 6: + b.with7((c, x0, x1, x2, x3, x4, x5) -> build(c, new Object[] {x0, x1, x2, x3, x4, x5})); + break; + default: + break; + } + return b; + } + + private static Object ntBind(String tn, Object[] names, PyDict defs, Object[] args, String[] kw) { + int npos = args.length - kw.length; + if (npos < 1) { + throw Py.typeError(tn + ".__new__(): not enough arguments"); + } + int n = names.length; + int given = npos - 1; + if (given > n) { + int d = defs.size(); + throw Py.typeError(tn + ".__new__() takes " + (d == 0 ? "" : "from " + (n - d + 1) + " to ") + (n + 1) + + " positional arguments but " + npos + " were given"); + } + Object[] vals = new Object[n]; + System.arraycopy(args, 1, vals, 0, given); + boolean[] used = new boolean[kw.length]; + for (int k = given; k < n; k++) { + String name = (String) names[k]; + int j = 0; + while (j < kw.length && !kw[j].equals(name)) { + j++; + } + if (j < kw.length) { + vals[k] = args[npos + j]; + used[j] = true; + continue; + } + Object d = defs.getOrNull(name); + if (d == null) { + throw Py.typeError(tn + ".__new__() missing 1 required positional argument: " + + Py.obj(name).repr()); + } + vals[k] = d; + } + for (int j = 0; j < kw.length; j++) { + if (!used[j]) { + for (Object f : names) { + if (kw[j].equals(f)) { + throw Py.typeError(tn + ".__new__() got multiple values for argument " + + Py.obj(kw[j]).repr()); + } + } + throw Py.typeError(tn + ".__new__() got an unexpected keyword argument " + Py.obj(kw[j]).repr()); + } + } + return build(args[0], vals); + } + + /// `defaultdict.__init__(self, default_factory=None, /, *args, **kwargs)`. + private static Object ddInit(Object[] args, String[] kw) { + int npos = args.length - kw.length; + if (npos < 1) { + throw Py.typeError("descriptor '__init__' of 'collections.defaultdict' object needs an argument"); + } + Object self = args[0]; + Object f = npos > 1 ? args[1] : Py.NONE; + int skip = npos > 1 ? 2 : 1; + if (args.length > skip) { + Object[] rest = new Object[args.length - skip + 1]; + rest[0] = self; + System.arraycopy(args, skip, rest, 1, args.length - skip); + checkFactory(f); + Py.obj(Py.DICT_TYPE.lookup("__init__")).call(rest, kw); + } + return ddInit(self, f); + } + + private static Object ddInit(Object self, Object f) { + checkFactory(f); + Py.setattr(self, "default_factory", f); + return Py.NONE; + } + + private static void checkFactory(Object f) { + if (f != Py.NONE && !Builtins.isCallable(f)) { //NOPMD CompareObjectsWithEquals - identity is meant + throw Py.typeError("first argument must be callable or None"); + } + } + + /// `defaultdict.__missing__(self, key)`. + private static Object missing(Object self, Object key) { + Object f = Py.getattr(self, "default_factory"); + if (f == Py.NONE) { //NOPMD CompareObjectsWithEquals - identity is meant + throw Py.keyError(key); + } + Object v = Py.obj(f).call0(); + Py.setitem(self, key, v); + return v; + } +} diff --git a/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyComplex.java b/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyComplex.java index fe11725a5e0..baa292305de 100644 --- a/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyComplex.java +++ b/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyComplex.java @@ -245,16 +245,20 @@ static double abs(PyComplex c) { static void install() { PyType t = Py.COMPLEX_TYPE; - t.define("conjugate", PyBuiltin.method(t, "conjugate", a -> { - PyComplex c = self(a[0]); + t.define("conjugate", PyBuiltin.method1(t, "conjugate", a0 -> { + PyComplex c = self(a0); return new PyComplex(c.real, -c.imag); })); - t.define("__abs__", PyBuiltin.method(t, "__abs__", a -> Py.ofFloat(abs(self(a[0]))))); - t.define("__complex__", PyBuiltin.method(t, "__complex__", a -> self(a[0]))); + t.define("__abs__", PyBuiltin.method1(t, "__abs__", a0 -> Py.ofFloat(abs(self(a0))))); + t.define("__complex__", PyBuiltin.method1(t, "__complex__", a0 -> self(a0))); t.factory = (type, args, kw) -> { Args p = new Args("complex", args, kw).check(2, "real", "imag"); Object re = p.get(0, "real", null); Object im = p.get(1, "imag", null); + Object text = Builtins.textBase(re); + if (text instanceof String && Py.typeOf(re).lookup("__complex__") == null) { + re = text; + } if (re instanceof String || re instanceof PyStr) { if (im != null) { throw Py.typeError("complex() argument 'real' must be a real number, not str"); @@ -292,7 +296,7 @@ private static PyComplex coerce(Object o, boolean first) { } Object m = Py.typeOf(o).lookup("__complex__"); if (m != null) { - Object r = Py.obj(m).call(new Object[] {o}, Py.NO_KW); + Object r = Py.obj(m).call1(o); if (r instanceof PyComplex) { return (PyComplex) r; } @@ -300,7 +304,7 @@ private static PyComplex coerce(Object o, boolean first) { } m = Py.typeOf(o).lookup("__float__"); if (m != null) { - return new PyComplex(Py.asDouble(Py.obj(m).call(new Object[] {o}, Py.NO_KW)), 0); + return new PyComplex(Py.asDouble(Py.obj(m).call1(o)), 0); } throw Py.typeError(first ? "complex() argument must be a string or a number, not " + Py.typeOf(o).name : "complex() argument 'imag' must be a real number, not " + Py.typeOf(o).name); diff --git a/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyDict.java b/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyDict.java index 2cd315599ed..d88dd746e9a 100644 --- a/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyDict.java +++ b/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyDict.java @@ -50,32 +50,307 @@ public class PyDict extends PyObject { private static final Object[] NO_OBJECTS = new Object[0]; private static final long[] NO_HASHES = new long[0]; + /// The shared key layout this dict's `keys`, `hashes` and `index` belong + /// to, or null when they are its own. While it is set the dict has no + /// deleted entry, `used == size == layout.n`, and those three arrays + /// must never be written: every write path calls [#unshare] first. + Layout layout; + /// An empty dict allocates no arrays until its first entry: keyword /// dicts, per-call dicts and the like are often never filled. public PyDict() { keys = NO_OBJECTS; values = NO_OBJECTS; hashes = NO_HASHES; + if (getClass() == PyDict.class) { + layout = Layout.ROOT; + } + } + + /// A hidden class, as JavaScript engines have them: the keys, hashes and + /// index table of every dict that received the same str keys in the same + /// order. pdfplumber turns each char of a page into a dict of the same + /// twenty keys; sharing the layout means each of those dicts holds only + /// its values, is built without hashing or probing a key, and a + /// `char["top"]` site ([KeySite]) finds the slot by one identity + /// compare. A layout is immutable once made. + static final class Layout { + /// The most keys a layout holds, the most layouts that follow one + /// (but the root, which every dict starts from: kwargs and module + /// dicts reach it before any record does), and the most layouts in + /// the program. Past any of them dicts keep their own arrays, as + /// before; the last bounds what a program of map-like dicts costs. + private static final int MAX_KEYS = 48; + private static final int MAX_NEXT = 64; + private static final int MAX_LAYOUTS = 8192; + private static int layouts; + + final Object[] keys; + final long[] hashes; + final int[] index; + final int n; + private String[] nextKey = NO_KEYS; + private Layout[] next = NO_LAYOUTS; + private static final String[] NO_KEYS = new String[0]; + private static final Layout[] NO_LAYOUTS = new Layout[0]; + /// Declared after the empty arrays its fields start from. + static final Layout ROOT = new Layout(NO_OBJECTS, NO_HASHES, null, 0); + private int nNext; + /// Keys one dict has added here that no layout follows yet. A step + /// is made a layout the second time a dict takes it, so a dict used + /// as a map (a word count) never builds a chain of layouts. + private String[] seen = NO_KEYS; + private int nSeen; + + private Layout(Object[] keys, long[] hashes, int[] index, int n) { + this.keys = keys; + this.hashes = hashes; + this.index = index; + this.n = n; + } + + /// The layout after adding `key` (absent here), or null when the dict + /// must take its own arrays. + Layout step(String key, long h) { + String[] nk = nextKey; + if (nk.length > 0) { + int mask = nk.length - 1; + int i = (int) h & mask; + String k; + while ((k = nk[i]) != null) { + if (k.equals(key)) { + return next[i]; + } + i = (i + 1) & mask; + } + } + if (n >= MAX_KEYS || nNext >= MAX_NEXT && n > 0 || layouts >= MAX_LAYOUTS) { + return null; + } + String[] sn = seen; + for (int i = 0; i < nSeen; i++) { + if (sn[i].equals(key)) { + sn[i] = sn[--nSeen]; + sn[nSeen] = null; + return extend(key, h); + } + } + if (sn.length == 0) { + seen = sn = new String[4]; + } + if (nSeen < sn.length) { + sn[nSeen++] = key; + } else { + sn[(int) (h & (sn.length - 1))] = key; + } + return null; + } + + private Layout extend(String key, long h) { + int m = n + 1; + Object[] k = new Object[m]; + long[] hs = new long[m]; + System.arraycopy(keys, 0, k, 0, n); + System.arraycopy(hashes, 0, hs, 0, n); + k[n] = key; + hs[n] = h; + int[] ix = null; + if (m > LINEAR) { + int t = 16; + while (m * 3 >= t * 2) { + t *= 2; + } + ix = newIndex(t); + int mask = t - 1; + for (int e = 0; e < m; e++) { + long sp = spread(hs[e]); + int i = (int) (sp & mask); + long perturb = sp & Long.MAX_VALUE; + while (ix[i] != EMPTY) { + perturb >>>= 5; + i = (int) ((i * 5L + perturb + 1) & mask); + } + ix[i] = e; + } + } + Layout l = new Layout(k, hs, ix, m); + layouts++; + if ((nNext + 1) * 2 > nextKey.length) { + String[] ok = nextKey; + Layout[] ol = next; + nextKey = new String[Math.max(4, ok.length * 2)]; + next = new Layout[nextKey.length]; + for (int i = 0; i < ok.length; i++) { + if (ok[i] != null) { + place(ok[i], ol[i]); + } + } + } + place(key, l); + nNext++; + return l; + } + + private void place(String key, Layout l) { + int mask = nextKey.length - 1; + int i = key.hashCode() & mask; + while (nextKey[i] != null) { + i = (i + 1) & mask; + } + nextKey[i] = key; + next[i] = l; + } + + /// The entry of str `key` in this layout, or -1. + int slotOf(String key) { + Object[] k = keys; + for (int e = 0; e < n; e++) { + Object x = k[e]; + if (key.equals(x)) { + return e; + } + } + return -1; + } + } + + /// Takes the next layout for a new str key: only the value is stored. + private void appendShared(Layout nl, Object value) { + int u = used; + Object[] v = values; + if (v.length <= u) { + Object[] nv = new Object[Math.max(4, u + (u >> 1) + 1)]; + System.arraycopy(v, 0, nv, 0, u); + values = v = nv; + } + v[u] = value; + keys = nl.keys; + hashes = nl.hashes; + index = nl.index; + layout = nl; + used = u + 1; + size = u + 1; + } + + /// Gives this dict its own copies of the shared arrays, before a write + /// no layout describes (a delete, a key that is not a str, a layout + /// past its limits). + void unshare() { + Layout l = layout; + if (l == null) { + return; + } + layout = null; + int cap = Math.max(4, values.length); + Object[] k = new Object[cap]; + long[] h = new long[cap]; + System.arraycopy(l.keys, 0, k, 0, l.n); + System.arraycopy(l.hashes, 0, h, 0, l.n); + keys = k; + hashes = h; + if (values.length < cap) { + Object[] nv = new Object[cap]; + System.arraycopy(values, 0, nv, 0, used); + values = nv; + } + index = l.index == null ? null : l.index.clone(); + if (index == null && cap > LINEAR) { + rebuildFor(cap); + } + } + + /// The index table for a dict of capacity `cap`, as grow() sizes it. + private void rebuildFor(int cap) { + int t = 16; + while (cap * 3 >= t * 2) { + t *= 2; + } + rebuild(t); } /// A dict sized for `n` entries, as a literal of that many pairs builds: /// its arrays are allocated once at that size rather than at the first /// growth's. public PyDict(int n) { - if (n > 0 && n <= LINEAR) { - keys = new Object[n]; - values = new Object[n]; - hashes = new long[n]; - } else { - // A larger literal grows as it is filled, index table included. + if (n <= 0) { keys = NO_OBJECTS; values = NO_OBJECTS; hashes = NO_HASHES; + if (getClass() == PyDict.class) { + layout = Layout.ROOT; + } + return; + } + if (getClass() == PyDict.class) { + keys = NO_OBJECTS; + hashes = NO_HASHES; + values = new Object[n]; + layout = Layout.ROOT; + return; + } + allocate(n); + } + + /// An empty dict about to be filled with `n` entries gets its arrays at + /// that size at once, rather than through every growth on the way. + void reserve(int n) { + if (layout != null) { + if (used == 0 && values.length < n) { + values = new Object[n]; + } + return; + } + if (used == 0 && keys.length < n) { + allocate(n); + } + } + + /// Takes `n` entries whose keys, hashes and index table are fresh copies + /// of ones an equal dict already built (an instance's `__dict__`, see + /// `PyInstance.InstanceDict`): no key is hashed or probed again. + void adopt(Object[] k, long[] h, int[] ix, Object[] v, int n) { + layout = null; + keys = k; + hashes = h; + index = ix; + values = v; + used = n; + size = n; + } + + /// The index table, or null while the entries are scanned. + int[] indexTable() { + return index; + } + + private void allocate(int n) { + layout = null; + keys = new Object[n]; + values = new Object[n]; + hashes = new long[n]; + if (n > LINEAR) { + // The index table at the size grow() would reach for n entries, once. + int t = 16; + while (n * 3 >= t * 2) { + t *= 2; + } + index = newIndex(t); } } /// The entry a slot from `find` names: without an index table the /// finders answer the entry itself. + /// The hash an index slot is taken from. A str's hash is Java's, whose + /// low bits are a poor mix (31 squared is 1 modulo 64, so in a table of + /// 64 slots a word's chars nearly cancel): words of one length collided + /// on most probes. A multiply carries every bit into the high ones, and + /// the fold brings them down to the slot bits. Hash values themselves, + /// which Python code sees, are unchanged. + static long spread(long h) { + long x = h * 0x9E3779B97F4A7C15L; + return x ^ (x >>> 29); + } + private int entry(int s) { return index == null ? s : index[s]; } @@ -151,8 +426,9 @@ private int findStr(String key, long h) { return -1; } int mask = index.length - 1; - int i = (int) (h & mask); - long perturb = h & Long.MAX_VALUE; + long m = spread(h); + int i = (int) (m & mask); + long perturb = m & Long.MAX_VALUE; int freeSlot = -1; while (true) { int e = index[i]; @@ -182,8 +458,9 @@ private int find(Object key, long h) { return scan(key, h); } int mask = index.length - 1; - int i = (int) (h & mask); - long perturb = h & Long.MAX_VALUE; + long m = spread(h); + int i = (int) (m & mask); + long perturb = m & Long.MAX_VALUE; int freeSlot = -1; while (true) { int e = index[i]; @@ -212,8 +489,20 @@ Object count(Object key, Object dflt, Object inc) { final int[] ix = index; final Object[] ks = keys; int e = entry(s); + Object cur = values[e]; + if (cur instanceof Long && inc instanceof Long) { + // Two ints: no Python code runs, so the slot stays put. + long a = (Long) cur; + long b = (Long) inc; + long c = a + b; + if (((a ^ c) & (b ^ c)) >= 0) { + Object r = Long.valueOf(c); + values[e] = r; + return r; + } + } Object stored = ks[e]; - Object r = Py.add(values[e], inc); + Object r = Py.add(cur, inc); if (index != ix || keys != ks || ix != null && ix[s] != e || ks[e] != stored) { //NOPMD CompareObjectsWithEquals - identity is meant // The addition ran Python code that changed the dict. s = find(key, h); @@ -247,8 +536,9 @@ private int findLong(long k, long h) { return -1; } int mask = index.length - 1; - int i = (int) (h & mask); - long perturb = h & Long.MAX_VALUE; + long m = spread(h); + int i = (int) (m & mask); + long perturb = m & Long.MAX_VALUE; int freeSlot = -1; while (true) { int e = index[i]; @@ -284,6 +574,10 @@ void setLong(long k, Object value) { values[entry(s)] = value; return; } + if (layout != null) { + unshare(); + s = findLong(k, h); + } if (used == keys.length) { grow(); s = findLong(k, h); @@ -302,6 +596,22 @@ void setLong(long k, Object value) { } /// `self[key]`, or `null` when absent. + /// [#getOrNull] with the key's hash already taken, by a caller that + /// had to hash it itself for its own error message (lru_cache). + Object getOrNullHashed(Object key, long h) { + sync(); + int s = find(key, h); + return s >= 0 ? values[entry(s)] : null; + } + + /// `self[key]` for a str key whose hash the caller took once, up front + /// (operator.itemgetter), or `null` when absent. + Object getStrHashed(String key, long h) { + sync(); + int s = findStr(key, h); + return s >= 0 ? values[entry(s)] : null; + } + public Object getOrNull(Object key) { sync(); int s = find(key, Py.keyHash(key, "a dict key")); @@ -318,13 +628,98 @@ public Object getItem(Object key) { if (v == null) { Object missing = type() == Py.DICT_TYPE ? null : type().lookup("__missing__"); //NOPMD CompareObjectsWithEquals - identity is meant if (missing != null) { - return Py.obj(missing).call(new Object[] {this, key}, Py.NO_KW); + return Py.obj(missing).call2(this, key); } throw Py.keyError(key); } return v; } + /// The keys of one dict display whose keys are distinct str constants, + /// resolved to their shared [Layout] on the display's first evaluation. + /// The transpiler makes one per such display, as a static field of the + /// module. + public static final class Literal { + final String[] keys; + Layout layout; + /// Set when the keys cannot share a layout (past its limits): the + /// display then builds its dict a pair at a time, as before. + boolean own; + + private Literal(String[] keys) { + this.keys = keys; + } + + /// The shape of a display's keys, joined by newlines (no key of a + /// shape contains one; the transpiler checks). + public static Literal of(String joined) { + String[] k = Py.names(joined); + for (int i = 0; i < k.length; i++) { + k[i] = k[i].intern(); + } + return new Literal(k); + } + } + + /// A dict display of str constant keys: `values` (a new array, in key + /// order, which the dict keeps as its own) under the keys' shared + /// layout. Measured on sqlite-utils, whose every Table and insert builds + /// a display of fifteen keys: one put per pair hashed each key and + /// probed the dict and the layout chain for it, 2.1x CPython's + /// BUILD_MAP; with the layout resolved once there is nothing to hash or + /// probe, and the dict is the array. + public static PyDict literal(Literal shape, Object[] values) { + Layout l = shape.layout; + if (l == null) { + l = shape.own ? null : resolve(shape); + if (l == null) { + PyDict d = new PyDict(values.length); + String[] k = shape.keys; + for (int i = 0; i < k.length; i++) { + d.setItem(k[i], values[i]); + } + return d; + } + } + PyDict d = new PyDict(); + d.values = values; + d.keys = l.keys; + d.hashes = l.hashes; + d.index = l.index; + d.layout = l; + d.used = l.n; + d.size = l.n; + return d; + } + + /// Walks the layout chain for a shape's keys, taking each step twice + /// when it has to: [Layout#step] makes a step a layout only the second + /// time a dict takes it. + private static Layout resolve(Literal shape) { + Layout l = Layout.ROOT; + for (String k : shape.keys) { + long h = Py.keyHash(k, "a dict key"); + Layout nl = l.step(k, h); + if (nl == null) { + nl = l.step(k, h); + } + if (nl == null) { + shape.own = true; + return null; + } + l = nl; + } + shape.layout = l; + return l; + } + + /// [#setItem] answering the dict: what a literal compiles to, one call per pair on a dict + /// made at its final size, so building one allocates no array of its pairs. + public PyDict put(Object key, Object value) { + setItem(key, value); + return this; + } + @Override public void setItem(Object key, Object value) { long h = Py.keyHash(key, "a dict key"); @@ -333,6 +728,17 @@ public void setItem(Object key, Object value) { values[entry(s)] = value; return; } + if (layout != null) { + if (key instanceof String) { + Layout nl = layout.step((String) key, h); + if (nl != null) { + appendShared(nl, value); + return; + } + } + unshare(); + s = find(key, h); + } if (used == keys.length) { grow(); s = find(key, h); @@ -392,8 +798,9 @@ private void rebuild(int n) { continue; } long h = hashes[e]; - int i = (int) (h & mask); - long perturb = h & Long.MAX_VALUE; + long m = spread(h); + int i = (int) (m & mask); + long perturb = m & Long.MAX_VALUE; while (index[i] != EMPTY) { perturb >>>= 5; i = (int) ((i * 5L + perturb + 1) & mask); @@ -404,10 +811,15 @@ private void rebuild(int n) { /// Removes `key`, returning its value or `null` when absent. public Object remove(Object key) { - int s = find(key, Py.keyHash(key, "a dict key")); + long h = Py.keyHash(key, "a dict key"); + int s = find(key, h); if (s < 0) { return null; } + if (layout != null) { + unshare(); + s = find(key, h); + } int e = entry(s); Object v = values[e]; if (index != null) { @@ -450,6 +862,17 @@ public long hash() { } public void clear() { + if (layout != null) { + // The shared arrays are not this dict's to null; its values are. + nullOut(values, used); + keys = NO_OBJECTS; + hashes = NO_HASHES; + index = null; + layout = Layout.ROOT; + used = 0; + size = 0; + return; + } if (keys.length <= KEEP_ON_CLEAR) { // A dict cleared and refilled, a cache or a window, keeps its // capacity as Java's HashMap does: refilling it would otherwise @@ -493,6 +916,49 @@ public void update(Object other) { } if (other instanceof PyDict) { PyDict d = (PyDict) other; + if (size == 0 && used == 0 && d.size == 0) { + return; + } + if (size == 0 && used == 0 && d.layout != null && layout != null && d.size > 0) { + // `dict(d)` and `d.copy()` of a dict on a shared layout: the + // copy takes the same layout and a copy of the values. + Object[] nv = new Object[d.used]; + System.arraycopy(d.values, 0, nv, 0, d.used); + keys = d.keys; + hashes = d.hashes; + index = d.index; + values = nv; + layout = d.layout; + used = d.used; + size = d.size; + return; + } + if (size == 0 && used == 0 && d.size <= LINEAR && getClass() == PyDict.class) { + // `dict(small)`, as every `self.attrib = dict(attrib)` is: the + // entries and their hashes copied once into arrays of the right + // size, rather than hashed again and grown on the way. + int cap = Math.max(4, d.size); + Object[] nk = new Object[cap]; + Object[] nv = new Object[cap]; + long[] nh = new long[cap]; + int w = 0; + for (int i = 0; i < d.used; i++) { + if (d.keys[i] != null) { + nk[w] = d.keys[i]; + nv[w] = d.values[i]; + nh[w] = d.hashes[i]; + w++; + } + } + keys = nk; + values = nv; + hashes = nh; + used = w; + size = w; + index = null; + layout = null; + return; + } for (int i = 0; i < d.used; i++) { if (d.keys[i] != null) { setItem(d.keys[i], d.values[i]); @@ -500,7 +966,33 @@ public void update(Object other) { } return; } - Object keysFn = Py.obj(other).getAttrOrNull("keys"); + if (other instanceof PyList) { + // Pairs read straight off the list, its length read each step; + // a list has no keys() to look up first, and the table is sized + // once for every pair rather than grown on the way. + PyList l = (PyList) other; + if (size == 0 && getClass() == PyDict.class) { + reserve(l.size); + } + for (int n = 0; n < l.size; n++) { + pairItem(l.get(n), n); + } + return; + } + if (other instanceof PyTuple || other instanceof PyGenerator || other instanceof Builtins.FilterIter + || other instanceof Builtins.MapIter) { + // None of these has keys(): no attribute lookup per dict() call. + updatePairs(other); + return; + } + Object keysFn; + if (!(other instanceof PyInstance)) { + // A builtin's attributes are its type's: no __getattr__ can run, + // so no handler (a setjmp per dict() call on ParparVM). + keysFn = Py.obj(other).getAttrOrNull("keys"); + } else { + keysFn = instanceKeys(other); + } if (keysFn != null) { Object it = Py.iter(Py.obj(keysFn).call(Py.NO_ARGS, Py.NO_KW)); for (Object k = Py.next(it); k != null; k = Py.next(it)) { @@ -508,16 +1000,94 @@ public void update(Object other) { } return; } + updatePairs(other); + } + + /// The pairs of an iterable with no keys(): a generator drained under + /// one handler (a setjmp per value otherwise), a filter or map stepped + /// by a direct call. + private void updatePairs(Object other) { Object it = Py.iter(other); + // dict(pairs) is usually built for more than the four entries a + // dict's first growth makes room for: two growths become one. + reserve(8); int n = 0; + if (it instanceof PyJavaIter) { + PyJavaIter j = (PyJavaIter) it; + PyJavaIter.Source s = j.liveSource(); + if (s instanceof Builtins.ZipSeq) { + ((Builtins.ZipSeq) s).drainInto(this); + j.finish(); + return; + } + } + if (it instanceof PyGenerator) { + PyGenerator g = (PyGenerator) it; + try { + for (Object pair = PyGenerator.loopNext(g); pair != null; pair = PyGenerator.loopNext(g), n++) { + pairItem(pair, n); + } + } catch (Throwable e) { + throw PyGenerator.loopEscape(g, e); + } + return; + } + if (it instanceof Builtins.FilterIter) { + Builtins.FilterIter f = (Builtins.FilterIter) it; + for (Object pair = f.next(); pair != null; pair = f.next(), n++) { + pairItem(pair, n); + } + return; + } for (Object pair = Py.next(it); pair != null; pair = Py.next(it), n++) { - Object[] kv = Py.toArray(pair); - if (kv.length != 2) { - throw Py.valueError("dictionary update sequence element #" + n + " has length " + kv.length - + "; 2 is required"); + pairItem(pair, n); + } + } + + private void pairItem(Object pair, int n) { + Object[] kv; + if (pair instanceof PyTuple && ((PyTuple) pair).size() == 2) { + PyTuple t = (PyTuple) pair; + setItem(t.get(0), t.get(1)); + return; + } + if (pair instanceof PyTuple) { + kv = ((PyTuple) pair).arr(); + } else if (pair instanceof PyList) { + kv = ((PyList) pair).toArray(); + } else { + Object it; + try { + it = Py.iter(pair); + } catch (PyException e) { + // CPython 3.14's wording for an element that is no sequence. + if (e.matches(Py.TYPE_ERROR)) { + throw Py.typeError("object is not iterable"); //NOPMD PreserveStackTrace - CPython raises a fresh TypeError here too + } + throw e; } - setItem(kv[0], kv[1]); + kv = Py.toArray(it); } + if (kv.length != 2) { + throw Py.valueError("dictionary update sequence element #" + n + " has length " + kv.length + + "; 2 is required"); + } + setItem(kv[0], kv[1]); + } + + private static Object instanceKeys(Object other) { + Object keysFn; + try { + keysFn = Py.obj(other).getAttrOrNull("keys"); + } catch (PyException e) { + // A __getattr__ that raises AttributeError means "no keys", and + // the argument is read as pairs (dict(pydantic_model)). + if (!e.matches(Py.ATTRIBUTE_ERROR)) { + throw e; + } + keysFn = null; + } + return keysFn; } /// The live keys in order. @@ -533,9 +1103,35 @@ public Object[] keyArray() { return r; } + /// Before each step of an iteration; `last` when the walk has no entry + /// left, where a change of size must still be found. A view can do less + /// than a full `sync` there, as long as what the step returns is current. + void syncStep(boolean last) { + sync(); + } + + /// [#sync] before an iteration, whose every step brings what it returns + /// up to date through [#syncStep] and [#valueAt]: a view need not + /// re-read every value first. + void syncForWalk() { + sync(); + } + + /// Whether a `for k, v in d.items()` may walk this dict through + /// [#sync], [#syncStep] and [#valueAt] instead of calling its items(): + /// true for a view whose items() is exactly that walk. + boolean walkAsView() { + return false; + } + + /// The value of live entry `e`, for an iteration step. + Object valueAt(int e) { + return values[e]; + } + /// Iterates over entries; `kind` 0 = keys, 1 = values, 2 = items. Object iterate(final int kind) { - sync(); + syncForWalk(); final int startSize = size; return new PyJavaIter(new PyJavaIter.Source() { int i; @@ -546,7 +1142,11 @@ public Object next() { // object behind it, so a store made through the object while // iterating is caught as one made through the dict is. A plain // dict's sync does nothing. - sync(); + int j = i; + while (j < used && keys[j] == null) { + j++; + } + syncStep(j >= used); if (size != startSize) { throw Py.runtimeError("dictionary changed size during iteration"); } @@ -561,9 +1161,9 @@ public Object next() { return keys[e]; } if (kind == 1) { - return values[e]; + return valueAt(e); } - return new PyTuple(new Object[] {keys[e], values[e]}); + return Py.tuple(keys[e], valueAt(e)); } }); } diff --git a/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyException.java b/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyException.java index 2bb73a504ab..2090272192a 100644 --- a/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyException.java +++ b/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyException.java @@ -42,15 +42,21 @@ public PyException(Object value) { // A raised exception has a traceback. The translated program has no // frame objects, so it is an empty `traceback` instance: what // `traceback.format_exception` reads to print the header. - if (value instanceof PyInstance && ((PyInstance) value).getAttrOrNull("__traceback__") == Py.NONE) { //NOPMD CompareObjectsWithEquals - identity is meant - ((PyInstance) value).setAttrDirect("__traceback__", new PyInstance(Py.TRACEBACK_TYPE)); + // Only the instance's own attribute is read: the class's is None, + // and a generic lookup on every raise cost more than the raise. + if (value instanceof PyInstance) { + PyInstance i = (PyInstance) value; + Object tb = i.own("__traceback__"); + if (tb == null || tb == Py.NONE) { //NOPMD CompareObjectsWithEquals - identity is meant + i.setAttrDirect("__traceback__", new PyInstance(Py.TRACEBACK_TYPE)); + } } } /// `isinstance(value, type)`, where `type` may be a tuple of types. public boolean matches(Object type) { if (type instanceof PyTuple) { - Object[] items = ((PyTuple) type).items; + Object[] items = ((PyTuple) type).arr(); for (Object item : items) { if (matches(item)) { return true; diff --git a/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyFunction.java b/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyFunction.java index 86f0dac6823..6c692db35a9 100644 --- a/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyFunction.java +++ b/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyFunction.java @@ -72,6 +72,38 @@ public interface Body6 { Object run(Object a, Object b, Object c, Object d, Object e, Object f); } + public interface Body7 { + Object run(Object a, Object b, Object c, Object d, Object e, Object f, Object g); + } + + public interface Body8 { + Object run(Object a, Object b, Object c, Object d, Object e, Object f, Object g, Object h); + } + + public interface Body9 { + Object run(Object a, Object b, Object c, Object d, Object e, Object f, Object g, Object h, Object i); + } + + public interface Body10 { + Object run(Object a, Object b, Object c, Object d, Object e, Object f, Object g, Object h, Object i, Object j); + } + + public interface Body11 { + Object run(Object a, Object b, Object c, Object d, Object e, Object f, Object g, Object h, Object i, Object j, Object k); + } + + public interface Body12 { + Object run(Object a, Object b, Object c, Object d, Object e, Object f, Object g, Object h, Object i, Object j, Object k, Object l); + } + + public interface Body13 { + Object run(Object a, Object b, Object c, Object d, Object e, Object f, Object g, Object h, Object i, Object j, Object k, Object l, Object m); + } + + public interface Body14 { + Object run(Object a, Object b, Object c, Object d, Object e, Object f, Object g, Object h, Object i, Object j, Object k, Object l, Object m, Object n); + } + /// A function whose body is one float expression of its parameters /// also has its value as a raw double: the arithmetic alone, for the /// parameter types the expression implies. It answers NaN for "not @@ -120,12 +152,20 @@ public interface PureL2 { final Object[] kwDefaults; final Body body; private Body0 body0; - private Body1 body1; - private Body2 body2; + Body1 body1; + Body2 body2; private Body3 body3; private Body4 body4; private Body5 body5; private Body6 body6; + private Body7 body7; + private Body8 body8; + private Body9 body9; + private Body10 body10; + private Body11 body11; + private Body12 body12; + private Body13 body13; + private Body14 body14; private PureD1 pure1; private PureD2 pure2; private PureD3 pure3; @@ -158,47 +198,136 @@ public PyFunction(String name, String[] params, int positional, boolean varArgs, public PyFunction(String name, String[] params, int positional, boolean varArgs, int kwOnly, boolean varKw, Object[] defaults, Object[] kwDefaults, Body0 b) { this(name, params, positional, varArgs, kwOnly, varKw, defaults, kwDefaults, (Object[] a) -> b.run()); - body0 = b; + if (kwOnly == 0) { + // A fixed-arity body is taken as N positional parameters by + // every fast path; with keyword-only ones it is reached + // through the bound array, or a call site bound at build time. + body0 = b; + } } public PyFunction(String name, String[] params, int positional, boolean varArgs, int kwOnly, boolean varKw, Object[] defaults, Object[] kwDefaults, Body1 b) { this(name, params, positional, varArgs, kwOnly, varKw, defaults, kwDefaults, (Object[] a) -> b.run(a[0])); - body1 = b; + if (kwOnly == 0) { + body1 = b; + } } public PyFunction(String name, String[] params, int positional, boolean varArgs, int kwOnly, boolean varKw, Object[] defaults, Object[] kwDefaults, Body2 b) { this(name, params, positional, varArgs, kwOnly, varKw, defaults, kwDefaults, (Object[] a) -> b.run(a[0], a[1])); - body2 = b; + if (kwOnly == 0) { + body2 = b; + } } public PyFunction(String name, String[] params, int positional, boolean varArgs, int kwOnly, boolean varKw, Object[] defaults, Object[] kwDefaults, Body3 b) { this(name, params, positional, varArgs, kwOnly, varKw, defaults, kwDefaults, (Object[] a) -> b.run(a[0], a[1], a[2])); - body3 = b; + if (kwOnly == 0) { + body3 = b; + } } public PyFunction(String name, String[] params, int positional, boolean varArgs, int kwOnly, boolean varKw, Object[] defaults, Object[] kwDefaults, Body4 b) { this(name, params, positional, varArgs, kwOnly, varKw, defaults, kwDefaults, (Object[] a) -> b.run(a[0], a[1], a[2], a[3])); - body4 = b; + if (kwOnly == 0) { + body4 = b; + } } public PyFunction(String name, String[] params, int positional, boolean varArgs, int kwOnly, boolean varKw, Object[] defaults, Object[] kwDefaults, Body5 b) { this(name, params, positional, varArgs, kwOnly, varKw, defaults, kwDefaults, (Object[] a) -> b.run(a[0], a[1], a[2], a[3], a[4])); - body5 = b; + if (kwOnly == 0) { + body5 = b; + } } public PyFunction(String name, String[] params, int positional, boolean varArgs, int kwOnly, boolean varKw, Object[] defaults, Object[] kwDefaults, Body6 b) { this(name, params, positional, varArgs, kwOnly, varKw, defaults, kwDefaults, (Object[] a) -> b.run(a[0], a[1], a[2], a[3], a[4], a[5])); - body6 = b; + if (kwOnly == 0) { + body6 = b; + } + } + + public PyFunction(String name, String[] params, int positional, boolean varArgs, int kwOnly, + boolean varKw, Object[] defaults, Object[] kwDefaults, Body7 b) { + this(name, params, positional, varArgs, kwOnly, varKw, defaults, kwDefaults, + (Object[] a) -> b.run(a[0], a[1], a[2], a[3], a[4], a[5], a[6])); + if (kwOnly == 0) { + body7 = b; + } + } + + public PyFunction(String name, String[] params, int positional, boolean varArgs, int kwOnly, + boolean varKw, Object[] defaults, Object[] kwDefaults, Body8 b) { + this(name, params, positional, varArgs, kwOnly, varKw, defaults, kwDefaults, + (Object[] a) -> b.run(a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7])); + if (kwOnly == 0) { + body8 = b; + } + } + + public PyFunction(String name, String[] params, int positional, boolean varArgs, int kwOnly, + boolean varKw, Object[] defaults, Object[] kwDefaults, Body9 b) { + this(name, params, positional, varArgs, kwOnly, varKw, defaults, kwDefaults, + (Object[] a) -> b.run(a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8])); + if (kwOnly == 0) { + body9 = b; + } + } + + public PyFunction(String name, String[] params, int positional, boolean varArgs, int kwOnly, + boolean varKw, Object[] defaults, Object[] kwDefaults, Body10 b) { + this(name, params, positional, varArgs, kwOnly, varKw, defaults, kwDefaults, + (Object[] a) -> b.run(a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9])); + if (kwOnly == 0) { + body10 = b; + } + } + + public PyFunction(String name, String[] params, int positional, boolean varArgs, int kwOnly, + boolean varKw, Object[] defaults, Object[] kwDefaults, Body11 b) { + this(name, params, positional, varArgs, kwOnly, varKw, defaults, kwDefaults, + (Object[] a) -> b.run(a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], a[10])); + if (kwOnly == 0) { + body11 = b; + } + } + + public PyFunction(String name, String[] params, int positional, boolean varArgs, int kwOnly, + boolean varKw, Object[] defaults, Object[] kwDefaults, Body12 b) { + this(name, params, positional, varArgs, kwOnly, varKw, defaults, kwDefaults, + (Object[] a) -> b.run(a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], a[10], a[11])); + if (kwOnly == 0) { + body12 = b; + } + } + + public PyFunction(String name, String[] params, int positional, boolean varArgs, int kwOnly, + boolean varKw, Object[] defaults, Object[] kwDefaults, Body13 b) { + this(name, params, positional, varArgs, kwOnly, varKw, defaults, kwDefaults, + (Object[] a) -> b.run(a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], a[10], a[11], a[12])); + if (kwOnly == 0) { + body13 = b; + } + } + + public PyFunction(String name, String[] params, int positional, boolean varArgs, int kwOnly, + boolean varKw, Object[] defaults, Object[] kwDefaults, Body14 b) { + this(name, params, positional, varArgs, kwOnly, varKw, defaults, kwDefaults, + (Object[] a) -> b.run(a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], a[10], a[11], a[12], a[13])); + if (kwOnly == 0) { + body14 = b; + } } @Override @@ -214,7 +343,9 @@ public Object call1(Object a) { if (body1 != null) { return body1.run(a); } - return widen(1) ? fill(1, a, null, null, null, null) : call(new Object[] {a}, Py.NO_KW); + return widen(1) ? fill(1, a, null, null, null, null) + : starOnly(1) ? star(1, a, null, null, null, null) + : slotsFit(1) ? slotsCall(1, a, null, null, null, null) : call(ArgArrays.fallback(new Object[] {a}), Py.NO_KW); } @Override @@ -222,7 +353,9 @@ public Object call2(Object a, Object b) { if (body2 != null) { return body2.run(a, b); } - return widen(2) ? fill(2, a, b, null, null, null) : call(new Object[] {a, b}, Py.NO_KW); + return widen(2) ? fill(2, a, b, null, null, null) + : starOnly(2) ? star(2, a, b, null, null, null) + : slotsFit(2) ? slotsCall(2, a, b, null, null, null) : call(ArgArrays.fallback(new Object[] {a, b}), Py.NO_KW); } @Override @@ -230,7 +363,9 @@ public Object call3(Object a, Object b, Object c) { if (body3 != null) { return body3.run(a, b, c); } - return widen(3) ? fill(3, a, b, c, null, null) : call(new Object[] {a, b, c}, Py.NO_KW); + return widen(3) ? fill(3, a, b, c, null, null) + : starOnly(3) ? star(3, a, b, c, null, null) + : slotsFit(3) ? slotsCall(3, a, b, c, null, null) : call(ArgArrays.fallback(new Object[] {a, b, c}), Py.NO_KW); } @Override @@ -238,7 +373,9 @@ public Object call4(Object a, Object b, Object c, Object d) { if (body4 != null) { return body4.run(a, b, c, d); } - return widen(4) ? fill(4, a, b, c, d, null) : call(new Object[] {a, b, c, d}, Py.NO_KW); + return widen(4) ? fill(4, a, b, c, d, null) + : starOnly(4) ? star(4, a, b, c, d, null) + : slotsFit(4) ? slotsCall(4, a, b, c, d, null) : call(ArgArrays.fallback(new Object[] {a, b, c, d}), Py.NO_KW); } @Override @@ -246,12 +383,141 @@ public Object call5(Object a, Object b, Object c, Object d, Object e) { if (body5 != null) { return body5.run(a, b, c, d, e); } - return widen(5) ? fill(5, a, b, c, d, e) : call(new Object[] {a, b, c, d, e}, Py.NO_KW); + return widen(5) ? fill(5, a, b, c, d, e) + : starOnly(5) ? star(5, a, b, c, d, e) + : slotsFit(5) ? slotsCall(5, a, b, c, d, e) : call(ArgArrays.fallback(new Object[] {a, b, c, d, e}), Py.NO_KW); } @Override public Object call6(Object a, Object b, Object c, Object d, Object e, Object f) { - return body6 != null ? body6.run(a, b, c, d, e, f) : call(new Object[] {a, b, c, d, e, f}, Py.NO_KW); + return body6 != null ? body6.run(a, b, c, d, e, f) : call(ArgArrays.fallback(new Object[] {a, b, c, d, e, f}), Py.NO_KW); + } + + @Override + public Object call7(Object a, Object b, Object c, Object d, Object e, Object f, Object g) { + return body7 != null ? body7.run(a, b, c, d, e, f, g) : call(ArgArrays.fallback(new Object[] {a, b, c, d, e, f, g}), Py.NO_KW); + } + + @Override + public Object call8(Object a, Object b, Object c, Object d, Object e, Object f, Object g, Object h) { + return body8 != null ? body8.run(a, b, c, d, e, f, g, h) : call(ArgArrays.fallback(new Object[] {a, b, c, d, e, f, g, h}), Py.NO_KW); + } + + @Override + public Object call9(Object a, Object b, Object c, Object d, Object e, Object f, Object g, Object h, Object i) { + return body9 != null ? body9.run(a, b, c, d, e, f, g, h, i) : call(ArgArrays.fallback(new Object[] {a, b, c, d, e, f, g, h, i}), Py.NO_KW); + } + + @Override + public Object call10(Object a, Object b, Object c, Object d, Object e, Object f, Object g, Object h, Object i, Object j) { + return body10 != null ? body10.run(a, b, c, d, e, f, g, h, i, j) : call(ArgArrays.fallback(new Object[] {a, b, c, d, e, f, g, h, i, j}), Py.NO_KW); + } + + @Override + public Object call11(Object a, Object b, Object c, Object d, Object e, Object f, Object g, Object h, Object i, Object j, Object k) { + return body11 != null ? body11.run(a, b, c, d, e, f, g, h, i, j, k) : call(ArgArrays.fallback(new Object[] {a, b, c, d, e, f, g, h, i, j, k}), Py.NO_KW); + } + + @Override + public Object call12(Object a, Object b, Object c, Object d, Object e, Object f, Object g, Object h, Object i, Object j, Object k, Object l) { + return body12 != null ? body12.run(a, b, c, d, e, f, g, h, i, j, k, l) : call(ArgArrays.fallback(new Object[] {a, b, c, d, e, f, g, h, i, j, k, l}), Py.NO_KW); + } + + @Override + public Object call13(Object a, Object b, Object c, Object d, Object e, Object f, Object g, Object h, Object i, Object j, Object k, Object l, Object m) { + return body13 != null ? body13.run(a, b, c, d, e, f, g, h, i, j, k, l, m) : call(ArgArrays.fallback(new Object[] {a, b, c, d, e, f, g, h, i, j, k, l, m}), Py.NO_KW); + } + + @Override + public Object call14(Object a, Object b, Object c, Object d, Object e, Object f, Object g, Object h, Object i, Object j, Object k, Object l, Object m, Object n) { + return body14 != null ? body14.run(a, b, c, d, e, f, g, h, i, j, k, l, m, n) : call(ArgArrays.fallback(new Object[] {a, b, c, d, e, f, g, h, i, j, k, l, m, n}), Py.NO_KW); + } + + /// Whether a positional call with `n` arguments binds as `f(*args)` does: + /// plain leading parameters and one `*args`, nothing keyword-only. + private boolean starOnly(int n) { + return varArgs && kwOnly == 0 && n >= positional; + } + + /// [#call] of `f(*args)` or `f(*args, **kwargs)` from a fixed-arity call + /// with no keywords: the leading arguments go to their slots and the rest + /// straight into the tuple, with no argument array built first and copied + /// out of. `**kwargs` gets an empty dict, the shared one when the function + /// never keeps it ([#kwShared]) -- a logger's `debug(msg, *args, **kwargs)` + /// is this shape and is called once per token by a parser that logs. + private Object star(int n, Object a, Object b, Object c, Object d, Object e) { + Object[] slots = spareSlots; + spareSlots = null; + if (slots == null) { + slots = new Object[positional + (varKw ? 2 : 1)]; + } + if (varKw) { + slots[positional + 1] = kwShared ? NO_KWARGS : new PyDict(); + } + int rest = n - positional; + Object[] items = rest == 0 ? null : new Object[rest]; + for (int i = 0; i < n; i++) { + Object v = i == 0 ? a : i == 1 ? b : i == 2 ? c : i == 3 ? d : e; + if (i < positional) { + slots[i] = v; + } else { + items[i - positional] = v; + } + } + slots[positional] = items == null ? PyTuple.EMPTY : new PyTuple(items); + Object r = body.run(slots); + spareSlots = clear(slots); + return r; + } + + /// Whether a positional call with `n` arguments binds as + /// `f(a, b=1, **kwargs)` does when no keyword is passed: plain parameters, + /// each one not given defaulted, and an empty `**kwargs`. + /// Whether a positional call of `n` arguments binds with no keyword + /// matching at all: the missing parameters all have defaults, a `*args` + /// gets nothing, and every keyword-only parameter has a default. That is + /// most of what reaches here -- `__init__(self, x, *, strict=False)`, + /// sqlite-utils' `insert(self, record, pk=DEFAULT, ... )` with a dozen + /// defaulted parameters, `table(self, name, **kwargs)` -- and building an + /// argument array to hand [#call] was a new array per call for each. + private boolean slotsFit(int n) { + if (n > positional || positional - defaults.length > n) { + return false; + } + for (int i = 0; i < kwOnly; i++) { + if (kwDefaults == null || kwDefaults[i] == null) { + return false; + } + } + return true; + } + + /// [#call] of a [#slotsFit] call: the slots are this function's spare + /// ones, laid out as [#bindArgs] lays them out and filled straight from + /// the arguments and the defaults. `**kwargs` is an empty dict -- the + /// shared one when the function never keeps it. + private Object slotsCall(int n, Object a, Object b, Object c, Object d, Object e) { + Object[] slots = spareSlots; + spareSlots = null; + if (slots == null) { + slots = new Object[positional + (varArgs ? 1 : 0) + kwOnly + (varKw ? 1 : 0)]; + } + for (int i = 0; i < positional; i++) { + slots[i] = pick(i, n, i == 0 ? a : i == 1 ? b : i == 2 ? c : i == 3 ? d : e); + } + int k = positional; + if (varArgs) { + slots[k++] = PyTuple.EMPTY; + } + for (int i = 0; i < kwOnly; i++) { + slots[k++] = kwDefaults[i]; + } + if (varKw) { + slots[k] = kwShared ? NO_KWARGS : new PyDict(); + } + Object r = body.run(slots); + spareSlots = clear(slots); + return r; } /// Whether a positional call with `n` arguments can go straight to the @@ -409,6 +675,23 @@ public static Object meta(Object fn, Object doc, Body0 annotations) { return fn; } + /// The annotations as the program [Annotations#build] runs, and the + /// module whose names it reads: what most functions have in place of a + /// thunk. + private String annotationTable; + private PyModule annotationModule; + + /// As [#meta(Object, Object, Body0)], the annotations a table. + public static Object meta(Object fn, Object doc, PyModule module, String annotations) { + if (fn instanceof PyFunction) { + PyFunction f = (PyFunction) fn; + f.doc = doc; + f.annotationTable = annotations; + f.annotationModule = module; + } + return fn; + } + /// One annotation's value: `value`'s result, or `fallback` when /// evaluating it raises (an annotation the runtime cannot express, such /// as a generic alias it does not model, never fails the definition). @@ -422,12 +705,37 @@ public static Object annotation(Body0 value, Object fallback) { int kindFlags; + /// `__module__`: the module the `def` ran in, null for a function made + /// by the runtime itself. + private Object module; + + /// Sets `__module__`, which pickle-free code still reads: `repr` of a + /// class built by a decorator, `functools.wraps`, registries keyed by + /// `f"{f.__module__}.{f.__qualname__}"`. Not `mod`: that is `%`. + public PyFunction inModule(Object m) { + module = m; + return this; + } + /// Sets `__qualname__` where it is not just the name. public PyFunction qual(String q) { qualname = q; return this; } + /// The bool this function answers whatever its one argument is, its + /// body being nothing but `return True` or `return False`; null for + /// any other. bs4's `Tag.__bool__`: a truth test of an instance reads + /// it (PyType#truthConst) rather than calling the function. + Object constant; + + /// Marks this function as one that only returns `value` (see + /// [#constant]). + public PyFunction constant(Object value) { + constant = value; + return this; + } + /// Marks a generator, coroutine or async generator function with the /// `co_flags` bit CPython gives it (0x20, 0x80, 0x200). public PyFunction kind(int flags) { @@ -435,6 +743,16 @@ public PyFunction kind(int flags) { return this; } + /// How many leading parameters are positional-only (before a `/`). + int positionalOnly; + + /// Marks the first `n` parameters positional-only: a keyword argument + /// with one of their names is refused, or goes to `**kwargs`. + public PyFunction positionalOnly(int n) { + positionalOnly = n; + return this; + } + private String qn() { return qualname != null ? qualname : name; } @@ -455,7 +773,7 @@ public Object getAttrOrNull(String attr) { case "__doc__": return doc != null ? doc : Py.NONE; case "__module__": - return Py.NONE; + return module != null ? module : Py.NONE; case "__dict__": if (attrs == null) { attrs = new PyDict(); @@ -477,8 +795,9 @@ public Object getAttrOrNull(String attr) { } case "__annotations__": PyDict d = new PyDict(); - if (annotationThunk != null) { - Object made = annotationThunk.run(); + if (annotationThunk != null || annotationTable != null) { + Object made = annotationTable != null + ? Annotations.build(annotationModule, annotationTable) : annotationThunk.run(); Object[] kv = made instanceof Object[] ? (Object[]) made : Py.NO_ARGS; for (int i = 0; i < kv.length; i += 2) { d.setItem(kv[i], kv[i + 1]); @@ -499,44 +818,780 @@ public void setAttr(String attr, Object value) { attrs.setItem(attr, value); } + /// `del f.name` of an attribute set on the function, as click does with + /// the `__click_params__` its decorators collect. + @Override + public void delAttr(String attr) { + if (attrs == null || !attrs.contains(attr)) { + throw Py.attributeError("'function' object has no attribute '" + attr + "'"); + } + attrs.delItem(attr); + } + @Override public Object call(Object[] args, String[] kwNames) { if (kwNames.length == 0 && !varArgs && kwOnly == 0 && !varKw && args.length == positional) { return body.run(args); } + if (varArgs && kwNames.length == 0 && kwOnly == 0 && args.length >= positional) { + // f(*args) (or f(*args, **kwargs)) called positionally: the slots + // are the leading arguments, one tuple of the rest and an empty + // dict, with none of bindArgs' keyword matching. + Object[] slots = spareSlots; + spareSlots = null; + if (slots == null) { + slots = new Object[positional + (varKw ? 2 : 1)]; + } + if (varKw) { + slots[positional + 1] = kwShared ? NO_KWARGS : new PyDict(); + } + System.arraycopy(args, 0, slots, 0, positional); + int rest = args.length - positional; + if (rest == 0) { + slots[positional] = PyTuple.EMPTY; + } else { + Object[] items = new Object[rest]; + System.arraycopy(args, positional, items, 0, rest); + slots[positional] = new PyTuple(items); + } + Object r = body.run(slots); + spareSlots = clear(slots); + return r; + } if (positional <= 6 && !varArgs && kwOnly == 0 && !varKw && args.length <= positional) { Object r = bindDirect(args, kwNames); if (r != UNBOUND) { //NOPMD CompareObjectsWithEquals - identity is meant return r; } } - return body.run(bindArgs(args, kwNames)); + // One slot array per function, reused: every generated body copies + // its slots into locals on entry (a generator into its fields when + // it is made), so the array is free once run returns. A nested call + // finds the spare taken and allocates its own; a throw just leaves + // it taken. Python code here runs on one thread at a time. + Object[] slots = spareSlots; + spareSlots = null; + if (slots == null) { + slots = new Object[positional + (varArgs ? 1 : 0) + kwOnly + (varKw ? 1 : 0)]; + } + Object r = body.run(bindArgs(slots, args, kwNames)); + spareSlots = clear(slots); + return r; + } + + /// True when a call of `n` arguments can bind in locals. + private boolean direct(int n) { + return positional <= 14 && !varArgs && kwOnly == 0 && !varKw && n <= positional; + } + + @Override + public Object callKwF(String[] kwNames, Object a) { + if (direct(1)) { + Object r = bindDirect(1, kwNames, a, null, null, null, null, null, null, null, null, null, null, null, null, null); + if (r != UNBOUND) { //NOPMD CompareObjectsWithEquals - identity is meant + return r; + } + } + if (planned(1)) { + Object r = bindPlanned(1, kwNames, a, null, null, null, null, null, null, null, null, null, null, null, null, null); + if (r != UNBOUND) { //NOPMD CompareObjectsWithEquals - identity is meant + return r; + } + } + return call(ArgArrays.fallback(new Object[] {a}), kwNames); + } + + @Override + public Object callKwF(String[] kwNames, Object a, Object b) { + if (direct(2)) { + Object r = bindDirect(2, kwNames, a, b, null, null, null, null, null, null, null, null, null, null, null, null); + if (r != UNBOUND) { //NOPMD CompareObjectsWithEquals - identity is meant + return r; + } + } + if (planned(2)) { + Object r = bindPlanned(2, kwNames, a, b, null, null, null, null, null, null, null, null, null, null, null, null); + if (r != UNBOUND) { //NOPMD CompareObjectsWithEquals - identity is meant + return r; + } + } + return call(ArgArrays.fallback(new Object[] {a, b}), kwNames); + } + + @Override + public Object callKwF(String[] kwNames, Object a, Object b, Object c) { + if (direct(3)) { + Object r = bindDirect(3, kwNames, a, b, c, null, null, null, null, null, null, null, null, null, null, null); + if (r != UNBOUND) { //NOPMD CompareObjectsWithEquals - identity is meant + return r; + } + } + if (planned(3)) { + Object r = bindPlanned(3, kwNames, a, b, c, null, null, null, null, null, null, null, null, null, null, null); + if (r != UNBOUND) { //NOPMD CompareObjectsWithEquals - identity is meant + return r; + } + } + return call(ArgArrays.fallback(new Object[] {a, b, c}), kwNames); } - /// A call to a function of at most six plain parameters, keywords + @Override + public Object callKwF(String[] kwNames, Object a, Object b, Object c, Object d) { + if (direct(4)) { + Object r = bindDirect(4, kwNames, a, b, c, d, null, null, null, null, null, null, null, null, null, null); + if (r != UNBOUND) { //NOPMD CompareObjectsWithEquals - identity is meant + return r; + } + } + if (planned(4)) { + Object r = bindPlanned(4, kwNames, a, b, c, d, null, null, null, null, null, null, null, null, null, null); + if (r != UNBOUND) { //NOPMD CompareObjectsWithEquals - identity is meant + return r; + } + } + return call(ArgArrays.fallback(new Object[] {a, b, c, d}), kwNames); + } + + @Override + public Object callKwF(String[] kwNames, Object a, Object b, Object c, Object d, Object e) { + if (direct(5)) { + Object r = bindDirect(5, kwNames, a, b, c, d, e, null, null, null, null, null, null, null, null, null); + if (r != UNBOUND) { //NOPMD CompareObjectsWithEquals - identity is meant + return r; + } + } + if (planned(5)) { + Object r = bindPlanned(5, kwNames, a, b, c, d, e, null, null, null, null, null, null, null, null, null); + if (r != UNBOUND) { //NOPMD CompareObjectsWithEquals - identity is meant + return r; + } + } + return call(ArgArrays.fallback(new Object[] {a, b, c, d, e}), kwNames); + } + + @Override + public Object callKwF(String[] kwNames, Object a, Object b, Object c, Object d, Object e, Object f) { + if (direct(6)) { + Object r = bindDirect(6, kwNames, a, b, c, d, e, f, null, null, null, null, null, null, null, null); + if (r != UNBOUND) { //NOPMD CompareObjectsWithEquals - identity is meant + return r; + } + } + if (planned(6)) { + Object r = bindPlanned(6, kwNames, a, b, c, d, e, f, null, null, null, null, null, null, null, null); + if (r != UNBOUND) { //NOPMD CompareObjectsWithEquals - identity is meant + return r; + } + } + return call(ArgArrays.fallback(new Object[] {a, b, c, d, e, f}), kwNames); + } + + @Override + public Object callKwF(String[] kwNames, Object a, Object b, Object c, Object d, Object e, Object f, Object g) { + if (direct(7)) { + Object r = bindDirect(7, kwNames, a, b, c, d, e, f, g, null, null, null, null, null, null, null); + if (r != UNBOUND) { //NOPMD CompareObjectsWithEquals - identity is meant + return r; + } + } + if (planned(7)) { + Object r = bindPlanned(7, kwNames, a, b, c, d, e, f, g, null, null, null, null, null, null, null); + if (r != UNBOUND) { //NOPMD CompareObjectsWithEquals - identity is meant + return r; + } + } + return call(ArgArrays.fallback(new Object[] {a, b, c, d, e, f, g}), kwNames); + } + + @Override + public Object callKwF(String[] kwNames, Object a, Object b, Object c, Object d, Object e, Object f, Object g, Object h) { + if (direct(8)) { + Object r = bindDirect(8, kwNames, a, b, c, d, e, f, g, h, null, null, null, null, null, null); + if (r != UNBOUND) { //NOPMD CompareObjectsWithEquals - identity is meant + return r; + } + } + if (planned(8)) { + Object r = bindPlanned(8, kwNames, a, b, c, d, e, f, g, h, null, null, null, null, null, null); + if (r != UNBOUND) { //NOPMD CompareObjectsWithEquals - identity is meant + return r; + } + } + return call(ArgArrays.fallback(new Object[] {a, b, c, d, e, f, g, h}), kwNames); + } + + @Override + public Object callKwF(String[] kwNames, Object a, Object b, Object c, Object d, Object e, Object f, Object g, Object h, Object i) { + if (direct(9)) { + Object r = bindDirect(9, kwNames, a, b, c, d, e, f, g, h, i, null, null, null, null, null); + if (r != UNBOUND) { //NOPMD CompareObjectsWithEquals - identity is meant + return r; + } + } + if (planned(9)) { + Object r = bindPlanned(9, kwNames, a, b, c, d, e, f, g, h, i, null, null, null, null, null); + if (r != UNBOUND) { //NOPMD CompareObjectsWithEquals - identity is meant + return r; + } + } + return call(ArgArrays.fallback(new Object[] {a, b, c, d, e, f, g, h, i}), kwNames); + } + + @Override + public Object callKwF(String[] kwNames, Object a, Object b, Object c, Object d, Object e, Object f, Object g, Object h, Object i, Object j) { + if (direct(10)) { + Object r = bindDirect(10, kwNames, a, b, c, d, e, f, g, h, i, j, null, null, null, null); + if (r != UNBOUND) { //NOPMD CompareObjectsWithEquals - identity is meant + return r; + } + } + if (planned(10)) { + Object r = bindPlanned(10, kwNames, a, b, c, d, e, f, g, h, i, j, null, null, null, null); + if (r != UNBOUND) { //NOPMD CompareObjectsWithEquals - identity is meant + return r; + } + } + return call(ArgArrays.fallback(new Object[] {a, b, c, d, e, f, g, h, i, j}), kwNames); + } + + @Override + public Object callKwF(String[] kwNames, Object a, Object b, Object c, Object d, Object e, Object f, Object g, Object h, Object i, Object j, Object k) { + if (direct(11)) { + Object r = bindDirect(11, kwNames, a, b, c, d, e, f, g, h, i, j, k, null, null, null); + if (r != UNBOUND) { //NOPMD CompareObjectsWithEquals - identity is meant + return r; + } + } + if (planned(11)) { + Object r = bindPlanned(11, kwNames, a, b, c, d, e, f, g, h, i, j, k, null, null, null); + if (r != UNBOUND) { //NOPMD CompareObjectsWithEquals - identity is meant + return r; + } + } + return call(ArgArrays.fallback(new Object[] {a, b, c, d, e, f, g, h, i, j, k}), kwNames); + } + + @Override + public Object callKwF(String[] kwNames, Object a, Object b, Object c, Object d, Object e, Object f, Object g, Object h, Object i, Object j, Object k, Object l) { + if (direct(12)) { + Object r = bindDirect(12, kwNames, a, b, c, d, e, f, g, h, i, j, k, l, null, null); + if (r != UNBOUND) { //NOPMD CompareObjectsWithEquals - identity is meant + return r; + } + } + if (planned(12)) { + Object r = bindPlanned(12, kwNames, a, b, c, d, e, f, g, h, i, j, k, l, null, null); + if (r != UNBOUND) { //NOPMD CompareObjectsWithEquals - identity is meant + return r; + } + } + return call(ArgArrays.fallback(new Object[] {a, b, c, d, e, f, g, h, i, j, k, l}), kwNames); + } + + @Override + public Object callKwF(String[] kwNames, Object a, Object b, Object c, Object d, Object e, Object f, Object g, Object h, Object i, Object j, Object k, Object l, Object m) { + if (direct(13)) { + Object r = bindDirect(13, kwNames, a, b, c, d, e, f, g, h, i, j, k, l, m, null); + if (r != UNBOUND) { //NOPMD CompareObjectsWithEquals - identity is meant + return r; + } + } + if (planned(13)) { + Object r = bindPlanned(13, kwNames, a, b, c, d, e, f, g, h, i, j, k, l, m, null); + if (r != UNBOUND) { //NOPMD CompareObjectsWithEquals - identity is meant + return r; + } + } + return call(ArgArrays.fallback(new Object[] {a, b, c, d, e, f, g, h, i, j, k, l, m}), kwNames); + } + + @Override + public Object callKwF(String[] kwNames, Object a, Object b, Object c, Object d, Object e, Object f, Object g, Object h, Object i, Object j, Object k, Object l, Object m, Object n) { + if (direct(14)) { + Object r = bindDirect(14, kwNames, a, b, c, d, e, f, g, h, i, j, k, l, m, n); + if (r != UNBOUND) { //NOPMD CompareObjectsWithEquals - identity is meant + return r; + } + } + if (planned(14)) { + Object r = bindPlanned(14, kwNames, a, b, c, d, e, f, g, h, i, j, k, l, m, n); + if (r != UNBOUND) { //NOPMD CompareObjectsWithEquals - identity is meant + return r; + } + } + return call(ArgArrays.fallback(new Object[] {a, b, c, d, e, f, g, h, i, j, k, l, m, n}), kwNames); + } + + /// True when a keyword call of `n` arguments can go through + /// [#bindPlanned]: no `*args` or `**kwargs` to collect into. + private boolean planned(int n) { + return !varArgs && (varKw || n <= positional + kwOnly); + } + + /// The slot of each name of the last keyword-name array [#bindPlanned] + /// matched, keyword-only parameters included. + private String[] plannedKw; + private int[] plannedSlots; + /// The positional count the plan above was made for, and whether a call + /// of that shape binds by the template alone: every keyword names a + /// distinct parameter past the positional arguments, and every + /// parameter without a default is given. + private int plannedPos = -1; + private boolean plannedSimple; + /// The parameters with their defaults in place and null where there is + /// none: a simple planned call copies it into the slots in one step, + /// where filling each default in turn was most of binding a call to a + /// function of many keyword-only parameters (hashlib.blake2b's twelve). + /// The default arrays are final and never handed out, so it never goes + /// stale. + private Object[] template; + + private Object[] template() { + Object[] t = template; + if (t == null) { + int total = positional + kwOnly; + int first = positional - defaults.length; + t = new Object[total]; + for (int p = 0; p < total; p++) { + t[p] = p < positional ? dflt(p, first) : kwDefaults == null ? null : kwDefaults[p - positional]; + } + template = t; + } + return t; + } + + /// Whether a call of `nPos` positional arguments and these keyword slots + /// binds by [#template] alone (see [#plannedSimple]). + private boolean simplePlan(int nPos, int[] kwSlots) { + int total = positional + kwOnly; + boolean[] given = new boolean[total]; + for (int i = 0; i < nPos; i++) { + given[i] = true; + } + for (int slot : kwSlots) { + if (slot < nPos || slot >= total || given[slot]) { + return false; + } + given[slot] = true; + } + Object[] t = template(); + for (int p = 0; p < total; p++) { + if (!given[p] && t[p] == null) { + return false; + } + } + return true; + } + + /// A keyword call of a function [#direct] cannot take -- more than six + /// parameters, or keyword-only ones: the `n` arguments go straight into + /// the reused slot array, defaults fill the rest, and the array body + /// runs. [#UNBOUND] before running anything when the call is not that + /// simple (an unknown, repeated or positional-only keyword, a missing + /// argument, a positional-only parameter named), and [#call] then binds + /// and reports it exactly as before. + private Object bindPlanned(int n, String[] kwNames, Object p0, Object p1, Object p2, Object p3, Object p4, Object p5, Object p6, Object p7, Object p8, Object p9, Object p10, Object p11, Object p12, Object p13) { + int nPos = n - kwNames.length; + if (nPos > positional) { + return UNBOUND; + } + int[] kwSlots; + if (kwNames == plannedKw) { //NOPMD CompareObjectsWithEquals - identity is meant + kwSlots = plannedSlots; + } else { + kwSlots = new int[kwNames.length]; + for (int i = 0; i < kwSlots.length; i++) { + int slot = slotOf(kwNames[i]); + if (slot < 0) { + for (int p = 0; p < kwOnly; p++) { + if (params[positional + p].equals(kwNames[i])) { + slot = positional + p; + break; + } + } + } + kwSlots[i] = slot; + } + plannedKw = kwNames; + plannedSlots = kwSlots; + plannedPos = -1; + } + if (plannedPos != nPos) { + plannedSimple = simplePlan(nPos, kwSlots); + plannedPos = nPos; + } + int total = positional + kwOnly; + Object[] slots = spareSlots; + spareSlots = null; + if (slots == null) { + slots = new Object[varKw ? total + 1 : total]; + } + if (plannedSimple) { + // Defaults in one copy, then the arguments over them; nothing left + // to check, the plan having proved every slot given or defaulted. + System.arraycopy(template, 0, slots, 0, total); + for (int i = 0; i < n; i++) { + slots[i < nPos ? i : kwSlots[i - nPos]] = arg(i, p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13); + } + if (varKw) { + slots[total] = kwShared ? NO_KWARGS : new PyDict(); + } + Object r = body.run(slots); + spareSlots = clear(slots); + return r; + } + // `**kwargs` (markitdown's `convert_a(self, el, text, **kwargs)`, + // called per link): a keyword no parameter takes goes into the dict + // in the slot after the keyword-only ones, where bindArgs puts it. + PyDict extra = null; + for (int i = 0; i < n; i++) { + int slot = i < nPos ? i : kwSlots[i - nPos]; + if (slot < 0 && varKw && i >= nPos) { + if (extra == null) { + extra = new PyDict(); + } + String k = kwNames[i - nPos]; + if (extra.getOrNull(k) != null) { + spareSlots = clear(slots); + return UNBOUND; + } + extra.setItem(k, arg(i, p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13)); + continue; + } + if (slot < 0 || slots[slot] != null) { + spareSlots = clear(slots); + return UNBOUND; + } + Object v; + switch (i) { + case 0: + v = p0; + break; + case 1: + v = p1; + break; + case 2: + v = p2; + break; + case 3: + v = p3; + break; + case 4: + v = p4; + break; + case 5: + v = p5; + break; + case 6: + v = p6; + break; + case 7: + v = p7; + break; + case 8: + v = p8; + break; + case 9: + v = p9; + break; + case 10: + v = p10; + break; + case 11: + v = p11; + break; + case 12: + v = p12; + break; + default: + v = p13; + break; + } + slots[slot] = v; + } + int first = positional - defaults.length; + for (int p = 0; p < total; p++) { + if (slots[p] == null) { + Object v = p < positional ? dflt(p, first) : kwDefaults == null ? null : kwDefaults[p - positional]; + if (v == null) { + spareSlots = clear(slots); + return UNBOUND; + } + slots[p] = v; + } + } + if (varKw) { + slots[total] = extra != null ? extra : kwShared ? NO_KWARGS : new PyDict(); + } + Object r = body.run(slots); + spareSlots = clear(slots); + return r; + } + + /// Argument `i` of `p0`..`p13`. + private static Object arg(int i, Object p0, Object p1, Object p2, Object p3, Object p4, Object p5, Object p6, Object p7, Object p8, Object p9, Object p10, Object p11, Object p12, Object p13) { + switch (i) { + case 0: + return p0; + case 1: + return p1; + case 2: + return p2; + case 3: + return p3; + case 4: + return p4; + case 5: + return p5; + case 6: + return p6; + case 7: + return p7; + case 8: + return p8; + case 9: + return p9; + case 10: + return p10; + case 11: + return p11; + case 12: + return p12; + default: + return p13; + } + } + + private Object[] spareSlots; + + /// Set when the body only ever passes its `**kwargs` on with `**` (a + /// logger's `debug(msg, *args, **kwargs)`): a call without keywords then + /// gets [#NO_KWARGS] rather than a new dict nobody can see, write or keep. + /// The transpiler proves this; see `Emitter.kwForwardOnly`. + private boolean kwShared; + + /// The empty `**kwargs` of a [#kwShared] function. Spreading it adds + /// nothing, and a callee that collects keywords builds its own dict. + static final PyDict NO_KWARGS = new PyDict(); + + /// Marks the function [#kwShared]. + public PyFunction kwShared() { + kwShared = true; + return this; + } + + /// The slot of each name of the last two keyword-name arrays + /// [#bindDirect] matched. Every call site hoists its array into a static, + /// so the same array arrives again and again: one identity check instead + /// of a string comparison per keyword and parameter. + private String[] directKw0; + private int[] directSlots0; + private String[] directKw1; + private int[] directSlots1; + + private int[] directSlots(String[] kwNames) { + if (kwNames == directKw0) { //NOPMD CompareObjectsWithEquals - identity is meant + return directSlots0; + } + if (kwNames == directKw1) { //NOPMD CompareObjectsWithEquals - identity is meant + return directSlots1; + } + int[] r = new int[kwNames.length]; + for (int i = 0; i < r.length; i++) { + r[i] = slotOf(kwNames[i]); + } + directKw1 = directKw0; + directSlots1 = directSlots0; + directKw0 = kwNames; + directSlots0 = r; + return r; + } + + /// The keyword-name arrays of the last few call sites that bound through + /// [#bindArgs], and the slot each of their names goes to (-1 for a name + /// that is no parameter). + private static final int SEEN = 4; + private String[][] seenKw; + private int[][] seenSlots; + private int seenNext; + private String[] pendingKw; + + /// Nulls, copied over a slot array to empty it: one bulk copy, where a + /// store per slot paid the collector's write barrier each. Up to 8 slots the + /// stores measured cheaper than the bulk barrier's setup. Never written. + private static final Object[] NULLS = new Object[64]; + + private static Object[] clear(Object[] a) { + if (a.length > 8 && a.length <= NULLS.length) { + System.arraycopy(NULLS, 0, a, 0, a.length); + return a; + } + for (int i = 0; i < a.length; i++) { + a[i] = null; + } + return a; + } + + /// A call to a function of at most 14 plain parameters, keywords /// included (`f(x, key=y)`, `f(**kw)`): the arguments are matched to /// parameters in locals and the fixed-arity body runs, so no second - /// array is bound. Null when the call is not that simple -- an unknown - /// or repeated keyword, a missing argument, no body of this arity -- - /// it answers [#UNBOUND] before running anything, and [#bindArgs] then - /// reports the call exactly as before. + /// array is bound. [#UNBOUND] when the call is not that simple -- an + /// unknown or repeated keyword, a missing argument, no body of this + /// arity -- before running anything, and [#bindArgs] then reports the + /// call exactly as before. private Object bindDirect(Object[] args, String[] kwNames) { - int nPos = args.length - kwNames.length; + int n = args.length; + return bindDirect(n, kwNames, n > 0 ? args[0] : null, n > 1 ? args[1] : null, n > 2 ? args[2] : null, n > 3 ? args[3] : null, n > 4 ? args[4] : null, n > 5 ? args[5] : null, n > 6 ? args[6] : null, n > 7 ? args[7] : null, n > 8 ? args[8] : null, n > 9 ? args[9] : null, n > 10 ? args[10] : null, n > 11 ? args[11] : null, n > 12 ? args[12] : null, n > 13 ? args[13] : null); + } + + /// [#bindDirect] for a function of at most four parameters called with + /// at most four arguments -- `self.match(i, _known_rules=True)` in bs4's + /// filter loop: four locals and one placement per argument instead of + /// the fourteen-way form. Answers exactly what the general form does. + private Object bindSmall(int n, String[] kwNames, Object p0, Object p1, Object p2, Object p3) { + int nPos = n - kwNames.length; + int[] kwSlots = kwNames.length == 0 ? null : directSlots(kwNames); + Object x0 = null; + Object x1 = null; + Object x2 = null; + Object x3 = null; + for (int i = 0; i < n; i++) { + int slot = i; + if (i >= nPos) { + slot = kwSlots[i - nPos]; + } + if (slot < 0 || slot >= positional) { + // Too many arguments or no such parameter: bindArgs reports it. + return UNBOUND; + } + Object v = i == 0 ? p0 : i == 1 ? p1 : i == 2 ? p2 : p3; + if (slot == 0) { + if (x0 != null) { + return UNBOUND; + } + x0 = v; + } else if (slot == 1) { + if (x1 != null) { + return UNBOUND; + } + x1 = v; + } else if (slot == 2) { + if (x2 != null) { + return UNBOUND; + } + x2 = v; + } else { + if (x3 != null) { + return UNBOUND; + } + x3 = v; + } + } + int first = positional - defaults.length; + if (positional >= 1 && x0 == null) { + x0 = dflt(0, first); + } + if (positional >= 2 && x1 == null) { + x1 = dflt(1, first); + } + if (positional >= 3 && x2 == null) { + x2 = dflt(2, first); + } + if (positional >= 4 && x3 == null) { + x3 = dflt(3, first); + } + if (positional > 0 && x0 == null || positional > 1 && x1 == null || positional > 2 && x2 == null + || positional > 3 && x3 == null) { + return UNBOUND; + } + switch (positional) { + case 0: + return body0 != null ? body0.run() : UNBOUND; + case 1: + return body1 != null ? body1.run(x0) : UNBOUND; + case 2: + return body2 != null ? body2.run(x0, x1) : UNBOUND; + case 3: + return body3 != null ? body3.run(x0, x1, x2) : UNBOUND; + default: + return body4 != null ? body4.run(x0, x1, x2, x3) : UNBOUND; + } + } + + /// [#bindDirect] over the `n` arguments `p0`..`p13` themselves. + private Object bindDirect(int n, String[] kwNames, Object p0, Object p1, Object p2, Object p3, Object p4, Object p5, Object p6, Object p7, Object p8, Object p9, Object p10, Object p11, Object p12, Object p13) { + if (positional <= 4 && n <= 4) { + return bindSmall(n, kwNames, p0, p1, p2, p3); + } + int nPos = n - kwNames.length; + int[] kwSlots = kwNames.length == 0 ? null : directSlots(kwNames); Object x0 = null; Object x1 = null; Object x2 = null; Object x3 = null; Object x4 = null; Object x5 = null; - for (int i = 0; i < args.length; i++) { + Object x6 = null; + Object x7 = null; + Object x8 = null; + Object x9 = null; + Object x10 = null; + Object x11 = null; + Object x12 = null; + Object x13 = null; + for (int i = 0; i < n; i++) { int slot = i; if (i >= nPos) { - slot = slotOf(kwNames[i - nPos]); + slot = kwSlots[i - nPos]; if (slot < 0) { return UNBOUND; } } - Object v = args[i]; + Object v; + switch (i) { + case 0: + v = p0; + break; + case 1: + v = p1; + break; + case 2: + v = p2; + break; + case 3: + v = p3; + break; + case 4: + v = p4; + break; + case 5: + v = p5; + break; + case 6: + v = p6; + break; + case 7: + v = p7; + break; + case 8: + v = p8; + break; + case 9: + v = p9; + break; + case 10: + v = p10; + break; + case 11: + v = p11; + break; + case 12: + v = p12; + break; + default: + v = p13; + break; + } switch (slot) { case 0: if (x0 != null) { @@ -568,12 +1623,60 @@ private Object bindDirect(Object[] args, String[] kwNames) { } x4 = v; break; - default: + case 5: if (x5 != null) { return UNBOUND; } x5 = v; break; + case 6: + if (x6 != null) { + return UNBOUND; + } + x6 = v; + break; + case 7: + if (x7 != null) { + return UNBOUND; + } + x7 = v; + break; + case 8: + if (x8 != null) { + return UNBOUND; + } + x8 = v; + break; + case 9: + if (x9 != null) { + return UNBOUND; + } + x9 = v; + break; + case 10: + if (x10 != null) { + return UNBOUND; + } + x10 = v; + break; + case 11: + if (x11 != null) { + return UNBOUND; + } + x11 = v; + break; + case 12: + if (x12 != null) { + return UNBOUND; + } + x12 = v; + break; + default: + if (x13 != null) { + return UNBOUND; + } + x13 = v; + break; } } int first = positional - defaults.length; @@ -583,8 +1686,19 @@ private Object bindDirect(Object[] args, String[] kwNames) { x3 = x3 != null || positional < 4 ? x3 : dflt(3, first); x4 = x4 != null || positional < 5 ? x4 : dflt(4, first); x5 = x5 != null || positional < 6 ? x5 : dflt(5, first); - if (positional > 0 && x0 == null || positional > 1 && x1 == null || positional > 2 && x2 == null - || positional > 3 && x3 == null || positional > 4 && x4 == null || positional > 5 && x5 == null) { + x6 = x6 != null || positional < 7 ? x6 : dflt(6, first); + x7 = x7 != null || positional < 8 ? x7 : dflt(7, first); + x8 = x8 != null || positional < 9 ? x8 : dflt(8, first); + x9 = x9 != null || positional < 10 ? x9 : dflt(9, first); + x10 = x10 != null || positional < 11 ? x10 : dflt(10, first); + x11 = x11 != null || positional < 12 ? x11 : dflt(11, first); + x12 = x12 != null || positional < 13 ? x12 : dflt(12, first); + x13 = x13 != null || positional < 14 ? x13 : dflt(13, first); + if (positional > 0 && x0 == null || positional > 1 && x1 == null || positional > 2 && x2 == null || + positional > 3 && x3 == null || positional > 4 && x4 == null || positional > 5 && x5 == null || + positional > 6 && x6 == null || positional > 7 && x7 == null || positional > 8 && x8 == null || + positional > 9 && x9 == null || positional > 10 && x10 == null || + positional > 11 && x11 == null || positional > 12 && x12 == null || positional > 13 && x13 == null) { return UNBOUND; } switch (positional) { @@ -600,8 +1714,24 @@ private Object bindDirect(Object[] args, String[] kwNames) { return body4 != null ? body4.run(x0, x1, x2, x3) : UNBOUND; case 5: return body5 != null ? body5.run(x0, x1, x2, x3, x4) : UNBOUND; - default: + case 6: return body6 != null ? body6.run(x0, x1, x2, x3, x4, x5) : UNBOUND; + case 7: + return body7 != null ? body7.run(x0, x1, x2, x3, x4, x5, x6) : UNBOUND; + case 8: + return body8 != null ? body8.run(x0, x1, x2, x3, x4, x5, x6, x7) : UNBOUND; + case 9: + return body9 != null ? body9.run(x0, x1, x2, x3, x4, x5, x6, x7, x8) : UNBOUND; + case 10: + return body10 != null ? body10.run(x0, x1, x2, x3, x4, x5, x6, x7, x8, x9) : UNBOUND; + case 11: + return body11 != null ? body11.run(x0, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10) : UNBOUND; + case 12: + return body12 != null ? body12.run(x0, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11) : UNBOUND; + case 13: + return body13 != null ? body13.run(x0, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12) : UNBOUND; + default: + return body14 != null ? body14.run(x0, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13) : UNBOUND; } } @@ -610,9 +1740,10 @@ private Object dflt(int i, int first) { return i >= first ? defaults[i - first] : null; } - /// The positional parameter named `k`, or -1. + /// The positional parameter named `k`, or -1. A positional-only one + /// cannot be named, so [#bindArgs] reports or collects that keyword. private int slotOf(String k) { - for (int p = 0; p < positional; p++) { + for (int p = positionalOnly; p < positional; p++) { if (params[p].equals(k)) { return p; } @@ -620,6 +1751,15 @@ private int slotOf(String k) { return -1; } + private boolean isPositionalOnly(String k) { + for (int p = 0; p < positionalOnly; p++) { + if (params[p].equals(k)) { + return true; + } + } + return false; + } + private static List add(List l, String n) { List r = l == null ? new ArrayList() : l; r.add(n); @@ -640,8 +1780,13 @@ private PyException missing(String kind, List names) { } Object[] bindArgs(Object[] args, String[] kwNames) { + return bindArgs(null, args, kwNames); + } + + /// Binds into `reuse` when given (all null), or into a new array. + private Object[] bindArgs(Object[] reuse, Object[] args, String[] kwNames) { int slots = positional + (varArgs ? 1 : 0) + kwOnly + (varKw ? 1 : 0); - Object[] out = new Object[slots]; + Object[] out = reuse != null ? reuse : new Object[slots]; int nPos = args.length - kwNames.length; int copy = Math.min(nPos, positional); System.arraycopy(args, 0, out, 0, copy); @@ -659,28 +1804,62 @@ Object[] bindArgs(Object[] args, String[] kwNames) { } else if (varArgs) { out[positional] = PyTuple.EMPTY; } - PyDict kw = varKw ? new PyDict() : null; + PyDict kw = varKw ? (kwShared && kwNames.length == 0 ? NO_KWARGS : new PyDict()) : null; int kwBase = positional + (varArgs ? 1 : 0); + List byKeyword = null; + // Which slot each keyword names is the same every time one call site + // calls: its names are one constant array. Matching them against the + // parameters by text again was most of what binding a keyword call cost. + int[] known = null; + if (kwNames.length > 0 && seenKw != null) { + for (int c = 0; c < SEEN; c++) { + if (seenKw[c] == kwNames) { //NOPMD CompareObjectsWithEquals - identity is meant + known = seenSlots[c]; + break; + } + } + } + // Learnt at the second sight of an array: one built for a single call + // (`f(**kw)`) never comes back, and must not push out those that do. + int[] learnt = null; + if (known == null && kwNames.length > 0) { + if (pendingKw == kwNames) { //NOPMD CompareObjectsWithEquals - identity is meant + learnt = new int[kwNames.length]; + } else { + pendingKw = kwNames; + } + } for (int i = 0; i < kwNames.length; i++) { String k = kwNames[i]; Object v = args[nPos + i]; int slot = -1; - for (int p = 0; p < positional; p++) { - if (params[p].equals(k)) { - slot = p; - break; - } - } - if (slot < 0) { - for (int p = 0; p < kwOnly; p++) { - if (params[kwBase + p].equals(k)) { - slot = kwBase + p; + if (known != null) { + slot = known[i]; + } else { + for (int p = positionalOnly; p < positional; p++) { + if (params[p].equals(k)) { + slot = p; break; } } + if (slot < 0) { + for (int p = 0; p < kwOnly; p++) { + if (params[kwBase + p].equals(k)) { + slot = kwBase + p; + break; + } + } + } + if (learnt != null) { + learnt[i] = slot; + } } if (slot < 0) { if (kw == null) { + if (isPositionalOnly(k)) { + byKeyword = add(byKeyword, k); + continue; + } throw Py.typeError(qn() + "() got an unexpected keyword argument '" + k + "'"); } kw.setItem(k, v); @@ -691,6 +1870,23 @@ Object[] bindArgs(Object[] args, String[] kwNames) { } out[slot] = v; } + if (byKeyword != null) { + StringBuilder sb = new StringBuilder(); + for (String n : byKeyword) { + sb.append(sb.length() == 0 ? "" : ", ").append(n); + } + throw Py.typeError(qn() + "() got some positional-only arguments passed as keyword arguments: '" + + sb + "'"); + } + if (learnt != null) { + if (seenKw == null) { + seenKw = new String[SEEN][]; + seenSlots = new int[SEEN][]; + } + seenKw[seenNext] = kwNames; + seenSlots[seenNext] = learnt; + seenNext = (seenNext + 1) % SEEN; + } int firstDefault = positional - defaults.length; List missing = null; for (int p = 0; p < positional; p++) { diff --git a/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyGenerator.java b/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyGenerator.java index ccb14463d49..753b9d0b59c 100644 --- a/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyGenerator.java +++ b/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyGenerator.java @@ -50,13 +50,27 @@ public abstract class PyGenerator extends PyObject { private final String name; private final boolean coroutine; private boolean running; - private Object sent = Py.NONE; - private PyException thrown; + // Protected so a generated body can test them before calling resumed(): + // a plain next() leaves both at rest, and the call was 12% of a drain. + protected Object sent = Py.NONE; + protected PyException thrown; private Object returned = Py.NONE; + /// The generator this body is resuming through [#nextFlat] or + /// [#delegateStepFlat], which run it without a handler of its own; null + /// between such calls. When the resumed body raises, the exception passes + /// that generator by, and the [#resume] that catches it finishes every + /// generator along this chain, as each would have finished itself. + private PyGenerator flat; + + /// [#flatResumable]'s answer, fixed at construction: the class and the + /// coroutine flag never change, and the question is asked once per value at + /// every level of a `yield from` chain. + private final boolean flatOk; protected PyGenerator(String name, boolean coroutine) { this.name = name; this.coroutine = coroutine; + this.flatOk = !coroutine && !(this instanceof Async) && !(this instanceof Awaiter) && !(this instanceof ASend); } /// Runs the body from `pc` to its next suspension or its end. @@ -67,11 +81,19 @@ protected PyGenerator(String name, boolean coroutine) { protected final Object resumed() { PyException t = thrown; Object s = sent; - thrown = null; - sent = Py.NONE; + // Stores only when something was sent or thrown in. A plain next() leaves + // both at their resting values, and each store is a barriered reference + // write -- two of them per value yielded, for nothing. if (t != null) { + thrown = null; + if (s != Py.NONE) { //NOPMD CompareObjectsWithEquals - identity is meant + sent = Py.NONE; + } throw t; } + if (s != Py.NONE) { //NOPMD CompareObjectsWithEquals - identity is meant + sent = Py.NONE; + } return s; } @@ -101,38 +123,200 @@ final Object resume(Object v, PyException t) { + (coroutine ? "coroutine" : "generator")); } } - sent = v; - thrown = t; + // The same as storing both unconditionally, minus the stores that would + // not change anything: resumed() puts both back to NONE/null, so a plain + // next() finds them there already. + if (sent != v) { //NOPMD CompareObjectsWithEquals - identity is meant + sent = v; + } + if (thrown != t) { //NOPMD CompareObjectsWithEquals - identity is meant + thrown = t; + } running = true; + // ONE handler and no finally: each catch clause, and the copy of the + // range a finally makes, is a try entry pushed on every resumption, + // and a generator resumes once per value. + Object r; try { - Object r = step(); - if (pc == -1) { - returned = r; - return null; + r = step(); + } catch (Throwable e) { + PyException re = escaped(e); + if (re != null) { + throw re; //NOPMD PreserveStackTrace - the Python cause is chained } - return r; - } catch (PyException e) { - pc = -1; - if (e.matches(Py.STOP_ITERATION)) { - // PEP 479: a StopIteration escaping the body would end the - // caller's loop silently. - Object err = Py.runtimeError((coroutine ? "coroutine" : "generator") + " raised StopIteration").value; - PyException re = Py.raise(err, e.value); - if (err instanceof PyInstance) { - ((PyInstance) err).setAttrDirect("__context__", e.value); + throw e; + } + running = false; + if (pc == -1) { + returned = r; + return null; + } + return r; + } + + /// What the body raising `e` does to this generator: it is finished, with + /// every generator it was resuming flat, and the exception to raise in its + /// place is returned -- PEP 479's RuntimeError for a StopIteration, else + /// null for `e` itself. + private PyException escaped(Throwable e) { + running = false; + pc = -1; + finishFlat(); + if (e instanceof PyException && ((PyException) e).matches(Py.STOP_ITERATION)) { + // PEP 479: a StopIteration escaping the body would end the + // caller's loop silently. + Object err = Py.runtimeError((coroutine ? "coroutine" : "generator") + " raised StopIteration").value; + PyException re = Py.raise(err, ((PyException) e).value); + if (err instanceof PyInstance) { + ((PyInstance) err).setAttrDirect("__context__", ((PyException) e).value); + } + return re; + } + return null; + } + + /// The next value of a `for` loop's iterator, for a loop the transpiler + /// has wrapped in ONE handler that calls [#loopEscape]. A plain generator + /// is stepped with no handler of its own -- the try [#resume] enters is a + /// setjmp on ParparVM, and measured at 5.5ns of the 17ns a value cost -- + /// and anything else is asked for next() as before. + public static Object loopNext(PyObject it) { + if (it instanceof PyGenerator) { + PyGenerator g = (PyGenerator) it; + // resumeFlat's common case written out here: the call between + // the two was 14% of a drain (neither is small enough to inline). + if (g.flatOk && !g.running && g.pc != -1 && g.thrown == null + && g.sent == Py.NONE) { //NOPMD CompareObjectsWithEquals - identity is meant + g.running = true; + Object r = g.step(); + g.running = false; + if (g.pc == -1) { + g.returned = r; + return null; } + return r; + } + if (g.flatOk) { + return g.resumeFlat(); + } + } + return it.next(); + } + + /// The loop handler of [#loopNext]: when the exception came out of the + /// generator's own body (it is still marked running) the generator is + /// finished exactly as [#resume]'s handler would have; an exception from + /// the loop body leaves it alone. Always throws; declared to return so a + /// call site can be written `throw loopEscape(...)`. + public static RuntimeException loopEscape(Object it, Throwable e) { + if (it instanceof PyGenerator && ((PyGenerator) it).running) { + PyException re = ((PyGenerator) it).escaped(e); + if (re != null) { throw re; //NOPMD PreserveStackTrace - the Python cause is chained } - throw e; - } catch (RuntimeException e) { - pc = -1; - throw e; - } catch (Error e) { - pc = -1; - throw e; - } finally { - running = false; } + throw PyGenerator.sneaky(e); + } + + @SuppressWarnings("unchecked") + private static T sneaky(Throwable e) throws T { + throw (T) e; + } + + /// Finishes the generators [#flat] left running when an exception + /// passed them by. + private void finishFlat() { + PyGenerator d = flat; + flat = null; + while (d != null && d.running) { + PyGenerator n = d.flat; + d.running = false; + d.pc = -1; + d.flat = null; + d = n; + } + } + + /// Whether [#resumeFlat] may drive `g`: a plain generator, not a + /// coroutine or one of the async adapters, which resume differently. + private static boolean flatResumable(PyGenerator g) { + return g.flatOk; + } + + /// `next()` without the handler [#resume] enters: a try costs a setjmp on + /// ParparVM, paid at every level of a pipeline for every value. Only + /// [#nextFlat] and [#delegateStepFlat] call this, and only from a body + /// with no except, finally or with around the call, so an exception + /// reaches the caller's own `resume`, whose handler finishes this one + /// (see [#flat]) and applies PEP 479 as this one's would have. + private Object resumeFlat() { + if (running || pc == -1) { + return resume(Py.NONE, null); + } + // As in resume: only the stores that change something. + if (sent != Py.NONE) { //NOPMD CompareObjectsWithEquals - identity is meant + sent = Py.NONE; + } + if (thrown != null) { + thrown = null; + } + running = true; + Object r = step(); + running = false; + if (pc == -1) { + returned = r; + return null; + } + return r; + } + + /// `it.next()` for a `for` loop in a generator body, outside any handler + /// (the transpiler emits it only there). + protected final Object nextFlat(PyObject it) { + if (it instanceof PyGenerator && flatResumable((PyGenerator) it)) { + PyGenerator g = (PyGenerator) it; + flat = g; + Object r = g.resumeFlat(); + flat = null; + return r; + } + return it.next(); + } + + /// `next(f, it)` for the desugared `try: x = next(it) except + /// StopIteration` in a body with no handler around it: [#nextFlat] for + /// the builtin `next` on a plain generator, answering + /// `Builtins.NEXT_STOP` when it is exhausted; anything else as + /// `Builtins.nextOrStop`. + protected final Object nextOrStopFlat(Object f, Object it) { + if (f == Builtins.NEXT && it instanceof PyGenerator //NOPMD CompareObjectsWithEquals - identity is meant + && flatResumable((PyGenerator) it)) { + PyGenerator g = (PyGenerator) it; + flat = g; + Object r = g.resumeFlat(); + flat = null; + return r == null ? Builtins.NEXT_STOP : r; + } + return Builtins.nextOrStop(f, it); + } + + /// [#delegateStep] for a `yield from` outside any handler: a plain + /// generator with nothing sent or thrown in is resumed flat. + protected final Object delegateStepFlat() { + PyObject d = delegate; + if (thrown == null && sent == Py.NONE && d instanceof PyGenerator //NOPMD CompareObjectsWithEquals - identity is meant + && flatResumable((PyGenerator) d)) { + PyGenerator g = (PyGenerator) d; + flat = g; + Object r = g.resumeFlat(); + flat = null; + if (r == null) { + delegate = null; + delegateResult = g.returned; + } + return r; + } + return delegateStep(); } /// The finished body's return value. @@ -425,32 +609,31 @@ protected Object step() { static void install() { PyType ag = Py.ASYNC_GENERATOR_TYPE; - ag.define("__aiter__", PyBuiltin.method(ag, "__aiter__", a -> a[0])); - ag.define("__anext__", PyBuiltin.method(ag, "__anext__", a -> new ASend(gen(a[0]), ASEND, Py.NONE))); - ag.define("asend", PyBuiltin.method(ag, "asend", a -> new ASend(gen(a[0]), ASEND, a[1]))); + ag.define("__aiter__", PyBuiltin.method1(ag, "__aiter__", a0 -> a0)); + ag.define("__anext__", PyBuiltin.method1(ag, "__anext__", a0 -> new ASend(gen(a0), ASEND, Py.NONE))); + ag.define("asend", PyBuiltin.method2(ag, "asend", (a0, a1) -> new ASend(gen(a0), ASEND, a1))); ag.define("athrow", PyBuiltin.method(ag, "athrow", a -> new ASend(gen(a[0]), ATHROW, a.length > 2 && a[2] != Py.NONE ? a[2] : a[1]))); - ag.define("aclose", PyBuiltin.method(ag, "aclose", a -> new ASend(gen(a[0]), ACLOSE, Py.NONE))); + ag.define("aclose", PyBuiltin.method1(ag, "aclose", a0 -> new ASend(gen(a0), ACLOSE, Py.NONE))); for (int i = 0; i < 2; i++) { PyType t = i == 0 ? Py.GENERATOR_TYPE : Py.COROUTINE_TYPE; t.define("send", PyBuiltin.method(t, "send", a -> gen(a[0]).send(a.length > 1 ? a[1] : Py.NONE))); t.define("throw", PyBuiltin.method(t, "throw", a -> gen(a[0]).throwIn(a.length > 2 && a[2] != Py.NONE ? a[2] : a[1]))); - t.define("close", PyBuiltin.method(t, "close", a -> { - gen(a[0]).close(); + t.define("close", PyBuiltin.method1(t, "close", a0 -> { + gen(a0).close(); return Py.NONE; })); } - Py.GENERATOR_TYPE.define("__iter__", PyBuiltin.method(Py.GENERATOR_TYPE, "__iter__", a -> a[0])); - Py.GENERATOR_TYPE.define("__next__", PyBuiltin.method(Py.GENERATOR_TYPE, "__next__", a -> { - Object r = gen(a[0]).resume(Py.NONE, null); + Py.GENERATOR_TYPE.define("__iter__", PyBuiltin.method1(Py.GENERATOR_TYPE, "__iter__", a0 -> a0)); + Py.GENERATOR_TYPE.define("__next__", PyBuiltin.method1(Py.GENERATOR_TYPE, "__next__", a0 -> { + Object r = gen(a0).resume(Py.NONE, null); if (r == null) { - throw stopIteration(gen(a[0]).returned); + throw stopIteration(gen(a0).returned); } return r; })); - Py.COROUTINE_TYPE.define("__await__", PyBuiltin.method(Py.COROUTINE_TYPE, "__await__", - a -> new Awaiter(gen(a[0])))); + Py.COROUTINE_TYPE.define("__await__", PyBuiltin.method1(Py.COROUTINE_TYPE, "__await__", a0 -> new Awaiter(gen(a0)))); } private static PyGenerator gen(Object o) { diff --git a/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyGenericAlias.java b/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyGenericAlias.java index e3e2be29efd..f417599d4f3 100644 --- a/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyGenericAlias.java +++ b/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyGenericAlias.java @@ -27,7 +27,17 @@ /// origin and the arguments where `typing.get_origin`/`get_args` read them, /// and calling it builds the origin. final class PyGenericAlias extends PyObject { - static final PyType TYPE = new PyType("types.GenericAlias", new PyType[] {Py.OBJECT_TYPE}, null); + /// `types.GenericAlias(origin, args)`, which `__class_getitem__ = + /// classmethod(GenericAlias)` relies on, as `collections.abc` does. + static final PyType TYPE = new PyType("types.GenericAlias", new PyType[] {Py.OBJECT_TYPE}, (t, a, kw) -> { + if (kw.length != 0 || a.length != 2) { + throw Py.typeError("GenericAlias expected 2 arguments, got " + (a.length - kw.length)); + } + if (!(a[0] instanceof PyType)) { + throw Py.typeError("GenericAlias() argument 1 must be a type"); + } + return new PyGenericAlias((PyType) a[0], a[1]); + }); final PyType origin; final PyTuple args; @@ -53,6 +63,11 @@ public Object getAttrOrNull(String attr) { if ("__parameters__".equals(attr)) { return new PyTuple(new Object[0]); } + if ("__mro_entries__".equals(attr)) { + // class C(Iterator[int]): the alias stands for its origin, as + // CPython's GenericAlias answers. + return PyBuiltin.positional("__mro_entries__", a -> PyTuple.of(origin)); + } return origin.getAttrOrNull(attr); } @@ -88,11 +103,11 @@ public long hash() { @Override public String repr() { StringBuilder b = new StringBuilder(PyUnion.typeRepr(origin)).append('['); - for (int i = 0; i < args.items.length; i++) { + for (int i = 0; i < args.arr().length; i++) { if (i > 0) { b.append(", "); } - b.append(PyUnion.typeRepr(args.items[i])); + b.append(PyUnion.typeRepr(args.arr()[i])); } return b.append(']').toString(); } diff --git a/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyHashlib.java b/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyHashlib.java new file mode 100644 index 00000000000..0512fcf3278 --- /dev/null +++ b/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyHashlib.java @@ -0,0 +1,126 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.python.runtime; + +import com.codename1.security.Hash; +import com.codename1.security.Pbkdf2; + +/// `_cn1hash`: `hashlib`'s hashes, which are Codename One's own +/// ([Hash]); this only names them the way Python does. Each hash object is +/// a `Hash` held in a `PyJavaObject`, and `digest` finishes a copy, so the +/// object can still be updated afterwards, as Python's can. +final class PyHashlib { + + /// `os.urandom`'s source, and so `secrets`' and `uuid`'s: the platform's secure + /// generator, which seeds itself and is safe to share between threads. + private static final java.security.SecureRandom RANDOM = new java.security.SecureRandom(); + + private PyHashlib() { + } + + private static Object newHash(Object nameO, Object size, Object key, Object salt, Object person) { + String name = Py.toStr(nameO); + Hash h; + if ("blake2b".equals(name)) { + h = Hash.blake2b((int) Py.asLong(size), PyBytes.like(key), PyBytes.like(salt), PyBytes.like(person)); + } else if ("blake2s".equals(name)) { + h = Hash.blake2s((int) Py.asLong(size), PyBytes.like(key), PyBytes.like(salt), PyBytes.like(person)); + } else { + String algorithm = algorithm(name); + if (algorithm == null) { + throw Py.error(Py.VALUE_ERROR, "unsupported hash type " + name); + } + h = Hash.create(algorithm); + } + return new PyJavaObject(h); + } + + static PyModule module() { + PyModule m = new PyModule("_cn1hash", new String[0]); + // hashlib.py always passes all five; no argument array is built for them. + m.setAttr("new", PyBuiltin.positional("new", a -> { + if (a.length != 5) { + throw Py.typeError("new expected 5 arguments, got " + a.length); + } + return newHash(a[0], a[1], a[2], a[3], a[4]); + }).with5(PyHashlib::newHash)); + m.setAttr("update", PyBuiltin.fixed2("update", (a0, a1) -> { + byte[] b = PyBytes.like(a1); + hash(a0).update(b, 0, b.length); + return Py.NONE; + })); + m.setAttr("copy", PyBuiltin.fixed1("copy", a0 -> new PyJavaObject(hash(a0).copy()))); + m.setAttr("digest", PyBuiltin.fixed1("digest", a0 -> new PyBytes(hash(a0).peekDigest()))); + // hexdigest() without the bytes object and the method call between. + m.setAttr("hexdigest", PyBuiltin.fixed1("hexdigest", a0 -> Py.str(PyBytes.hexOf(hash(a0).peekDigest())))); + m.setAttr("pbkdf2", PyBuiltin.positional("pbkdf2", a -> { + String algorithm = algorithm(Py.toStr(a[0])); + if (algorithm == null || Hash.SHA3_256.equals(algorithm)) { + throw Py.error(Py.VALUE_ERROR, "unsupported hash type " + Py.toStr(a[0])); + } + return new PyBytes(Pbkdf2.derive(algorithm, PyBytes.like(a[1]), PyBytes.like(a[2]), + (int) Py.asLong(a[3]), (int) Py.asLong(a[4]))); + })); + m.setAttr("urandom", PyBuiltin.fixed1("urandom", a0 -> { + long n = Py.asLong(a0); + if (n < 0 || n > Integer.MAX_VALUE) { + throw Py.error(Py.VALUE_ERROR, "negative argument not allowed"); + } + byte[] out = new byte[(int) n]; + RANDOM.nextBytes(out); + return new PyBytes(out); + })); + return m; + } + + /// The `Hash` name of a `hashlib` one, or null for one it does not have. + private static String algorithm(String name) { + switch (name) { + case "md5": + return Hash.MD5; + case "sha1": + return Hash.SHA1; + case "sha224": + return Hash.SHA224; + case "sha256": + return Hash.SHA256; + case "sha384": + return Hash.SHA384; + case "sha512": + return Hash.SHA512; + case "sha3_256": + return Hash.SHA3_256; + default: + return null; + } + } + + private static Hash hash(Object o) { + Object v = o instanceof PyJavaObject ? ((PyJavaObject) o).value : null; + if (v instanceof Hash) { + return (Hash) v; + } + throw Py.typeError("not a hash state"); + } +} diff --git a/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyImage.java b/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyImage.java index a0f5bfbdf5e..1ab0ce1ed0b 100644 --- a/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyImage.java +++ b/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyImage.java @@ -93,20 +93,20 @@ static PyModule module() { System.arraycopy(b, 0, r.d, 0, r.d.length); return wrap(r); })); - m.setAttr("size", PyBuiltin.positional("size", a -> { - PyImageData s = img(a[0]); - return new PyTuple(new Object[] {PyInt.of(s.w), PyInt.of(s.h)}); + m.setAttr("size", PyBuiltin.fixed1("size", a0 -> { + PyImageData s = img(a0); + return Py.tuple(PyInt.of(s.w), PyInt.of(s.h)); })); - m.setAttr("tobytes", PyBuiltin.positional("tobytes", a -> { - PyImageData s = img(a[0]); + m.setAttr("tobytes", PyBuiltin.fixed1("tobytes", a0 -> { + PyImageData s = img(a0); byte[] out = new byte[s.d.length]; System.arraycopy(s.d, 0, out, 0, out.length); return new PyBytes(out); })); - m.setAttr("getpixel", PyBuiltin.positional("getpixel", a -> { - PyImageData s = img(a[0]); - int x = i(a[1]); - int y = i(a[2]); + m.setAttr("getpixel", PyBuiltin.fixed3("getpixel", (a0, a1, a2) -> { + PyImageData s = img(a0); + int x = i(a1); + int y = i(a2); if (x < 0 || y < 0 || x >= s.w || y >= s.h) { throw Py.error(Py.INDEX_ERROR, "image index out of range"); } @@ -137,7 +137,7 @@ static PyModule module() { paste(img(a[0]), img(a[1]), i(a[2]), i(a[3]), a[4] == Py.NONE ? null : img(a[4])); //NOPMD CompareObjectsWithEquals - identity is meant return Py.NONE; })); - m.setAttr("transpose", PyBuiltin.positional("transpose", a -> wrap(transpose(img(a[0]), i(a[1]))))); + m.setAttr("transpose", PyBuiltin.fixed2("transpose", (a0, a1) -> wrap(transpose(img(a0), i(a1))))); m.setAttr("affine", PyBuiltin.positional("affine", a -> { Object[] c = Py.toArray(a[3]); double[] k = new double[6]; @@ -155,23 +155,23 @@ static PyModule module() { return wrap(requireEngine().resample(img(a[0]), i(a[1]), i(a[2]), box, a.length > 4 ? i(a[4]) : FILTER_BILINEAR, a.length > 5 && Py.isTrue(a[5]))); })); - m.setAttr("palette", PyBuiltin.positional("palette", a -> wrap(palette(img(a[0]), bytes(a[1]))))); + m.setAttr("palette", PyBuiltin.fixed2("palette", (a0, a1) -> wrap(palette(img(a0), bytes(a1))))); m.setAttr("scatter", PyBuiltin.positional("scatter", a -> { scatter(img(a[0]), img(a[1]), i(a[2]), i(a[3]), i(a[4]), i(a[5])); return Py.NONE; })); - m.setAttr("convert", PyBuiltin.positional("convert", a -> wrap(convert(img(a[0]), i(a[1]))))); - m.setAttr("band", PyBuiltin.positional("band", a -> { - PyImageData s = img(a[0]); - int b = i(a[1]); + m.setAttr("convert", PyBuiltin.fixed2("convert", (a0, a1) -> wrap(convert(img(a0), i(a1))))); + m.setAttr("band", PyBuiltin.fixed2("band", (a0, a1) -> { + PyImageData s = img(a0); + int b = i(a1); PyImageData r = new PyImageData(s.w, s.h, 1); for (int p = 0, n = s.w * s.h; p < n; p++) { r.d[p] = s.d[p * s.bands + b]; } return wrap(r); })); - m.setAttr("merge", PyBuiltin.positional("merge", a -> { - Object[] parts = Py.toArray(a[0]); + m.setAttr("merge", PyBuiltin.fixed1("merge", a0 -> { + Object[] parts = Py.toArray(a0); PyImageData first = img(parts[0]); PyImageData r = new PyImageData(first.w, first.h, parts.length); for (int b = 0; b < parts.length; b++) { @@ -185,10 +185,10 @@ static PyModule module() { } return wrap(r); })); - m.setAttr("getbbox", PyBuiltin.positional("getbbox", a -> getbbox(img(a[0]), Py.isTrue(a[1])))); - m.setAttr("point", PyBuiltin.positional("point", a -> { - PyImageData s = img(a[0]); - byte[] lut = bytes(a[1]); + m.setAttr("getbbox", PyBuiltin.fixed2("getbbox", (a0, a1) -> getbbox(img(a0), Py.isTrue(a1)))); + m.setAttr("point", PyBuiltin.fixed2("point", (a0, a1) -> { + PyImageData s = img(a0); + byte[] lut = bytes(a1); PyImageData r = new PyImageData(s.w, s.h, s.bands); for (int p = 0; p < s.d.length; p += s.bands) { for (int b = 0; b < s.bands; b++) { @@ -197,9 +197,9 @@ static PyModule module() { } return wrap(r); })); - m.setAttr("boxblur", PyBuiltin.positional("boxblur", a -> { - PyImageData s = img(a[0]); - int r = i(a[1]); + m.setAttr("boxblur", PyBuiltin.fixed2("boxblur", (a0, a1) -> { + PyImageData s = img(a0); + int r = i(a1); PyImageData t = blurRows(s, r); PyImageData u = blurRows(transpose(t, 5), r); return wrap(transpose(u, 5)); @@ -208,11 +208,11 @@ static PyModule module() { new PyBytes(requireEngine().pngUnfilter(bytes(a[0]), i(a[1]), i(a[2]), i(a[3]))))); m.setAttr("png_expand", PyBuiltin.positional("png_expand", a -> wrap(requireEngine().pngExpand(bytes(a[0]), i(a[1]), i(a[2]), i(a[3]), i(a[4]))))); - m.setAttr("jpeg_decode", PyBuiltin.positional("jpeg_decode", a -> wrap(requireEngine().jpegDecode(bytes(a[0]))))); + m.setAttr("jpeg_decode", PyBuiltin.fixed1("jpeg_decode", a0 -> wrap(requireEngine().jpegDecode(bytes(a0))))); m.setAttr("jpeg_encode", PyBuiltin.positional("jpeg_encode", a -> new PyBytes(requireEngine().jpegEncode(img(a[0]), (float) Py.asDouble(a[1]))))); - m.setAttr("png_rows", PyBuiltin.positional("png_rows", a -> { - PyImageData s = img(a[0]); + m.setAttr("png_rows", PyBuiltin.fixed1("png_rows", a0 -> { + PyImageData s = img(a0); int row = s.w * s.bands; byte[] out = new byte[(row + 1) * s.h]; for (int y = 0; y < s.h; y++) { @@ -230,19 +230,19 @@ static PyModule module() { new PyJavaObject(requireEngine().defaultFont(Py.asDouble(a[0]))))); m.setAttr("ft_variant", PyBuiltin.positional("ft_variant", a -> new PyJavaObject(requireEngine().deriveFont(ft(a[0]), Py.asDouble(a[1]))))); - m.setAttr("ft_name", PyBuiltin.positional("ft_name", a -> { - String[] n = requireEngine().fontName(ft(a[0])); - return new PyTuple(new Object[] {new PyStr(n[0]), new PyStr(n[1])}); + m.setAttr("ft_name", PyBuiltin.fixed1("ft_name", a0 -> { + String[] n = requireEngine().fontName(ft(a0)); + return Py.tuple(new PyStr(n[0]), new PyStr(n[1])); })); - m.setAttr("ft_metrics", PyBuiltin.positional("ft_metrics", a -> { - int[] mt = requireEngine().fontMetrics(ft(a[0])); - return new PyTuple(new Object[] {PyInt.of(mt[0]), PyInt.of(mt[1])}); + m.setAttr("ft_metrics", PyBuiltin.fixed1("ft_metrics", a0 -> { + int[] mt = requireEngine().fontMetrics(ft(a0)); + return Py.tuple(PyInt.of(mt[0]), PyInt.of(mt[1])); })); m.setAttr("ft_length", PyBuiltin.positional("ft_length", a -> PyInt.of(requireEngine().textLength(ft(a[0]), Py.toStr(a[1]))))); - m.setAttr("ft_bbox", PyBuiltin.positional("ft_bbox", a -> { - int[] b = requireEngine().textBox(ft(a[0]), Py.toStr(a[1]), anchor(a[2])); - return new PyTuple(new Object[] {PyInt.of(b[0]), PyInt.of(b[1]), PyInt.of(b[2]), PyInt.of(b[3])}); + m.setAttr("ft_bbox", PyBuiltin.fixed3("ft_bbox", (a0, a1, a2) -> { + int[] b = requireEngine().textBox(ft(a0), Py.toStr(a1), anchor(a2)); + return Py.tuple(PyInt.of(b[0]), PyInt.of(b[1]), PyInt.of(b[2]), PyInt.of(b[3])); })); m.setAttr("ft_mask", PyBuiltin.positional("ft_mask", a -> { PyImageEngine e = requireEngine(); @@ -250,8 +250,8 @@ static PyModule module() { String text = Py.toStr(a[1]); String anchor = anchor(a[2]); int[] b = e.textBox(f, text, anchor); - return new PyTuple(new Object[] {wrap(e.textMask(f, text, anchor, Py.isTrue(a[3]))), PyInt.of(b[2]), - PyInt.of(b[3])}); + return Py.tuple(wrap(e.textMask(f, text, anchor, Py.isTrue(a[3]))), PyInt.of(b[2]), + PyInt.of(b[3])); })); m.setAttr("exact", PyBuiltin.positional("exact", a -> { PyImageEngine e = engine; @@ -496,7 +496,7 @@ private static Object getbbox(PyImageData s, boolean alphaOnly) { if (x1 < 0) { return Py.NONE; } - return new PyTuple(new Object[] {PyInt.of(x0), PyInt.of(y0), PyInt.of(x1 + 1), PyInt.of(y1 + 1)}); + return Py.tuple(PyInt.of(x0), PyInt.of(y0), PyInt.of(x1 + 1), PyInt.of(y1 + 1)); } /// One horizontal pass of Pillow's box blur for an integer radius. diff --git a/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyInstance.java b/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyInstance.java index 5402c513b6d..df613c2c8f0 100644 --- a/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyInstance.java +++ b/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyInstance.java @@ -62,6 +62,21 @@ public class PyInstance extends PyObject { /// `o.__dict__ is o.__dict__` as in CPython. Null until then. private InstanceDict dictView; + /// The instance's one `__dict__` view, made on first use. + final PyDict dictView() { + InstanceDict d = dictView; + if (d == null) { + d = new InstanceDict(this); + dictView = d; + } + return d; + } + + /// The view if one was made: what [AttrSite] compares a read with. + final Object dictViewOrNull() { + return dictView; + } + /// The shape, the empty one for null. final Shape shape() { return shape == null ? Shape.EMPTY : shape; @@ -94,6 +109,60 @@ protected Object getField(int i) { return null; } + /// Every field into `d[0..fieldNames().length)`, as getField answers + /// each; generated classes write them in one pass. + protected void copyFields(Object[] d) { + int n = fieldNames().length; + for (int i = 0; i < n; i++) { + d[i] = getField(i); + } + } + + /// The state half of `copy.copy` and `copy.deepcopy` (`_cn1copy`): every + /// attribute of this instance into `y`, a fresh instance of the same + /// class that `copy` just made, each value passed through `deep` (with + /// `memo`) when it is not null. CPython copies an instance by reducing + /// it to `__dict__` and storing every key back with `setattr`; here the + /// fields move by index through the methods the transpiler generates per + /// class ([#copyFields], [#setField]), and the attributes held beside + /// them in the shape move with it, so no attribute is looked up by name. + void copyStateInto(PyInstance y, Object memo, Object deep) { + int nf = fieldNames().length; + if (nf > 0) { + Object[] d = new Object[nf]; + copyFields(d); + for (int i = 0; i < nf; i++) { + Object v = d[i]; + if (v != null) { + y.setField(i, deep == null ? v : Py.call(deep, v, memo)); + } + } + } + Shape sh = shape; + int n = sh == null ? 0 : sh.size(); + if (n == 0) { + return; + } + Object[] src = slots; + if (y.shape == null && y.getClass() == getClass() && y.cls == cls) { //NOPMD CompareObjectsWithEquals - identity is meant + Object[] out = new Object[src.length]; + for (int i = 0; i < n; i++) { + Object v = src[i]; + out[i] = deep == null || v == FIELD_HERE ? v : Py.call(deep, v, memo); //NOPMD CompareObjectsWithEquals - identity is meant + } + y.slots = out; + y.shape = sh; + y.extra = extra; + return; + } + for (int i = 0; i < n; i++) { + Object v = src[i]; + if (v != FIELD_HERE) { //NOPMD CompareObjectsWithEquals - identity is meant + y.store(sh.names[i], deep == null ? v : Py.call(deep, v, memo)); + } + } + } + /// Stores field `i`; null unsets it. protected void setField(int i, Object value) { } @@ -105,6 +174,10 @@ protected String[] fieldNames() { private static final String[] NO_NAMES = new String[0]; + /// The slot value of a field's name in the shape: the name marks where + /// the attribute was first set (see [#store]), its value is the field. + static final Object FIELD_HERE = new Object(); + /// The instance attribute `name`, or null. Object own(String name) { int f = fieldIndex(name); @@ -115,16 +188,56 @@ Object own(String name) { } } int i = shape == null ? -1 : shape.indexOf(name); - return i < 0 ? null : slots[i]; + Object v = i < 0 ? null : slots[i]; + return v == FIELD_HERE ? null : v; //NOPMD CompareObjectsWithEquals - identity is meant + } + + /// The field index of each of `names` in this instance's class, -1 for + /// one it keeps elsewhere: for a caller that reads the same attributes of + /// many instances, through [#ownAt] and [#storeAt], without matching a + /// name each time. + int[] fieldIndexes(String[] names) { + int[] out = new int[names.length]; + for (int i = 0; i < names.length; i++) { + out[i] = fieldIndex(names[i]); + } + return out; + } + + /// [#own] with the field index already known (see [#fieldIndexes]). + Object ownAt(int f, String name) { + if (f >= 0) { + Object v = getField(f); + if (v != null || !extra) { + return v; + } + } + return own(name); + } + + /// [#store] with the field index already known (see [#fieldIndexes]). + void storeAt(int f, String name, Object value) { + if (f >= 0 && (!extra || getField(f) != null)) { + setField(f, value); + return; + } + store(name, value); } /// Stores `name`, adding it to the shape if the instance lacks it. void store(String name, Object value) { int f = fieldIndex(name); - // A field first set after some other attribute would list before - // it; such a late attribute is kept in the shape instead, which - // remembers the order. - if (f >= 0 && (!extra || getField(f) != null)) { + if (f >= 0) { + // A field first set after some other attribute would list before + // it: the shape takes its name, which keeps the order, and the + // value stays in the field, where compiled code reads and stores + // it. Kept in the shape instead, a subclass that sets one + // attribute of its own before calling the compiled __init__ had + // every compiled access to its fields go the generic way. + // An unset field has no marker: deleting one drops it. + if (extra && getField(f) == null) { + append(shape().with(name), FIELD_HERE); + } setField(f, value); return; } @@ -137,6 +250,12 @@ void store(String name, Object value) { throw Py.attributeError("'" + cls.name + "' object has no attribute '" + name + "' and no __dict__ for setting new attributes"); } + Object hook = cls.newAttrHook(); + if (hook != null && Py.isTrue(Py.obj(hook).call3(this, name, value))) { + // The class kept the value elsewhere (pydantic's extras) or + // raised: a model refuses a name that is not a field. + return; + } append(shape().with(name), value); } } @@ -146,17 +265,52 @@ void store(String name, Object value) { void append(Shape next, Object value) { int n = shape().size(); if (slots == null) { - slots = new Object[4]; + slots = new Object[cls.slotHint]; } else if (n == slots.length) { - Object[] grown = new Object[n < 4 ? 4 : n * 2]; + int size = n < 4 ? 4 : n * 2; + Object[] grown = new Object[size]; System.arraycopy(slots, 0, grown, 0, n); slots = grown; + if (size > cls.slotHint) { + cls.slotHint = size; + } } slots[n] = value; shape = next; extra = true; } + /// How many of the shape's names are fields listed at that place (see + /// [#store]). + int fieldMarkers() { + Object[] sl = slots; + int n = shape == null ? 0 : shape.size(); + int c = 0; + for (int i = 0; i < n; i++) { + if (sl[i] == FIELD_HERE) { //NOPMD CompareObjectsWithEquals - identity is meant + c++; + } + } + return c; + } + + /// Which of the `n` fields have a marker in the shape, or null when none + /// has. + boolean[] markedFields(int n) { + Object[] sl = slots; + int size = shape == null ? 0 : shape.size(); + boolean[] out = null; + for (int i = 0; i < size; i++) { + if (sl[i] == FIELD_HERE) { //NOPMD CompareObjectsWithEquals - identity is meant + if (out == null) { + out = new boolean[n]; + } + out[fieldIndex(shape.names[i])] = true; + } + } + return out; + } + /// The attribute names: the set fields, then the rest in the order they /// were first assigned. String[] attributeNames() { @@ -165,8 +319,10 @@ String[] attributeNames() { return shape().names; } List out = new ArrayList(); + boolean[] marked = markedFields(f.length); for (int i = 0; i < f.length; i++) { - if (getField(i) != null) { + // A field whose name the shape holds lists at that place. + if (getField(i) != null && (marked == null || !marked[i])) { out.add(f[i]); } } @@ -185,7 +341,7 @@ public Object getAttrOrNull(String name) { // type and never comes here. An AttributeError it raises falls back // to __getattr__, as CPython's slot does. try { - return Py.obj(cls.lookup("__getattribute__")).call(new Object[] {this, name}, Py.NO_KW); + return Py.obj(cls.lookup("__getattribute__")).call2(this, name); } catch (PyException e) { if (!e.matches(Py.ATTRIBUTE_ERROR)) { throw e; @@ -194,7 +350,7 @@ public Object getAttrOrNull(String name) { if (ga == null) { return null; } - return Py.obj(ga).call(new Object[] {this, name}, Py.NO_KW); + return Py.obj(ga).call2(this, name); } } Object v = genericAttrOrNull(name); @@ -203,7 +359,7 @@ public Object getAttrOrNull(String name) { } Object ga = cls.lookup("__getattr__"); if (ga != null) { - return Py.obj(ga).call(new Object[] {this, name}, Py.NO_KW); + return Py.obj(ga).call2(this, name); } return null; } @@ -222,7 +378,7 @@ Object genericAttrOrNull(String name) { PyType dt = ((PyInstance) clsAttr).cls; get = dt.lookup("__get__"); if (get != null && (dt.lookup("__set__") != null || dt.lookup("__delete__") != null)) { - return Py.obj(get).call(new Object[] {clsAttr, this, cls}, Py.NO_KW); + return Py.obj(get).call3(clsAttr, this, cls); } } Object v = own(name); @@ -230,7 +386,7 @@ Object genericAttrOrNull(String name) { return v; } if (get != null) { - return Py.obj(get).call(new Object[] {clsAttr, this, cls}, Py.NO_KW); + return Py.obj(get).call3(clsAttr, this, cls); } if ("__dict__".equals(name)) { // A live view: its stores and deletes reach the instance, and it @@ -243,10 +399,7 @@ Object genericAttrOrNull(String name) { } // One view per instance, refilled from the instance before // every read, so a view fetched earlier sees later writes. - if (dictView == null) { - dictView = new InstanceDict(this); - } - return dictView; + return dictView(); } if ("__class__".equals(name)) { return cls; @@ -263,7 +416,7 @@ public void setAttr(String name, Object value) { // a property or another data descriptor owns, as in CPython. Object sa = cls.lookup("__setattr__"); if (sa != null && !(sa instanceof PyBuiltin)) { - Py.obj(sa).call(new Object[] {this, name, value}, Py.NO_KW); + Py.obj(sa).call3(this, name, value); return; } setAttrObject(name, value); @@ -272,6 +425,23 @@ public void setAttr(String name, Object value) { /// `object.__setattr__(self, name, value)`: data descriptors, then the /// plain store, never an overriding `__setattr__`. public void setAttrObject(String name, Object value) { + if ("__dict__".equals(name) && value instanceof PyDict && cls.slotNames() == null + && cls.lookup("__dict__") == null) { + // Replacing the dict (pydantic's construct does): the attributes + // become the dict's. They are copied, not aliased, so a later + // store into the old dict object no longer reaches the instance. + for (String n : attributeNames()) { + delAttrDirect(n); + } + PyDict d = (PyDict) value; + for (Object k : d.keyArray()) { + if (!(k instanceof String)) { + throw Py.typeError("attribute name must be string"); + } + store((String) k, d.getItem(k)); + } + return; + } Object clsAttr = cls.lookup(name); if (clsAttr instanceof PyProperty) { ((PyProperty) clsAttr).set(this, value); @@ -280,7 +450,7 @@ public void setAttrObject(String name, Object value) { if (clsAttr instanceof PyInstance) { Object set = ((PyInstance) clsAttr).cls.lookup("__set__"); if (set != null) { - Py.obj(set).call(new Object[] {clsAttr, this, value}, Py.NO_KW); + Py.obj(set).call3(clsAttr, this, value); return; } } @@ -296,14 +466,14 @@ public void setAttrDirect(String name, Object value) { public void delAttr(String name) { Object da = cls.lookup("__delattr__"); if (da != null && !(da instanceof PyBuiltin)) { - Py.obj(da).call(new Object[] {this, name}, Py.NO_KW); + Py.obj(da).call2(this, name); return; } Object clsAttr = cls.lookup(name); if (clsAttr instanceof PyInstance) { Object del = ((PyInstance) clsAttr).cls.lookup("__delete__"); if (del != null) { - Py.obj(del).call(new Object[] {clsAttr, this}, Py.NO_KW); + Py.obj(del).call2(clsAttr, this); return; } } @@ -318,7 +488,10 @@ void delAttrDirect(String name) { setField(f, null); // Set again, it is the newest attribute: see store. extra = true; - return; + if (shape == null || shape.indexOf(name) < 0) { + return; + } + // Its place in the shape goes too. } } int at = shape().indexOf(name); @@ -344,13 +517,13 @@ protected final Object dunder(String name, Object arg) { if (m == null) { return null; } - Object r = Py.obj(m).call(new Object[] {this, arg}, Py.NO_KW); + Object r = (m instanceof PyObject ? (PyObject) m : Py.obj(m)).call2(this, arg); return r == Py.NOT_IMPLEMENTED ? null : r; //NOPMD CompareObjectsWithEquals - identity is meant } private Object dunder0(String name) { Object m = cls.lookup(name); - return m == null ? null : Py.obj(m).call(new Object[] {this}, Py.NO_KW); + return m == null ? null : (m instanceof PyObject ? (PyObject) m : Py.obj(m)).call1(this); } @Override @@ -359,7 +532,7 @@ public String repr() { if (r != null) { return Py.strValue(r, "__repr__"); } - return "<" + cls.name + " object at 0x" + Integer.toHexString(System.identityHashCode(this)) + ">"; + return "<" + cls.fullName() + " object at 0x" + Integer.toHexString(System.identityHashCode(this)) + ">"; } @Override @@ -373,16 +546,25 @@ public String str() { @Override public boolean isTrue() { - Object m = cls.lookup("__bool__"); + PyType t = cls; + if (t.truthVersion != PyType.version) { + t.truthMethods(); + } + if (t.truthBase && base != null) { + return Py.isTrue(base); + } + if (t.truthConst != null) { + return t.truthConst == Py.TRUE; //NOPMD CompareObjectsWithEquals - identity is meant + } + Object m = t.truthBool; if (m != null) { - Object r = Py.obj(m).call(new Object[] {this}, Py.NO_KW); + Object r = (m instanceof PyObject ? (PyObject) m : Py.obj(m)).call1(this); if (!(r instanceof PyBool)) { throw Py.typeError("__bool__ should return bool, returned " + Py.typeOf(r).name); } return r == Py.TRUE; //NOPMD CompareObjectsWithEquals - identity is meant } - m = cls.lookup("__len__"); - if (m != null) { + if (t.truthLen != null) { return len() != 0; } return true; @@ -394,7 +576,43 @@ public Object call(Object[] args, String[] kwNames) { if (m == null) { return super.call(args, kwNames); } - return Py.obj(m).call(Py.prepend(this, args), kwNames); + return (m instanceof PyObject ? (PyObject) m : Py.obj(m)).call(Py.prepend(this, args), kwNames); + } + + // Fixed-arity calls hand `self` and the arguments on without building an + // argument array and then a second one with `self` prepended. + + private Object callable() { + Object m = cls.lookup("__call__"); + if (m == null) { + throw Py.typeError("'" + type().name + "' object is not callable"); + } + return m; + } + + @Override + public Object call0() { + return Py.obj(callable()).call1(this); + } + + @Override + public Object call1(Object a) { + return Py.obj(callable()).call2(this, a); + } + + @Override + public Object call2(Object a, Object b) { + return Py.obj(callable()).call3(this, a, b); + } + + @Override + public Object call3(Object a, Object b, Object c) { + return Py.obj(callable()).call4(this, a, b, c); + } + + @Override + public Object call4(Object a, Object b, Object c, Object d) { + return Py.obj(callable()).call5(this, a, b, c, d); } @Override @@ -548,6 +766,13 @@ public Object ge(Object o) { @Override public long hash() { + PyType t = cls; + if (t.truthVersion != PyType.version) { + t.truthMethods(); + } + if (t.hashBase && base != null) { + return Py.hashOf(base); + } Object m = cls.lookup("__hash__"); if (m == Py.NONE) { //NOPMD CompareObjectsWithEquals - identity is meant throw Py.typeError("unhashable type: '" + cls.name + "'"); @@ -558,21 +783,20 @@ public long hash() { } return System.identityHashCode(this); } - return Py.asLong(Py.obj(m).call(new Object[] {this}, Py.NO_KW)); + return Py.asLong((m instanceof PyObject ? (PyObject) m : Py.obj(m)).call1(this)); } @Override public Object getItem(Object key) { if (base instanceof PyDict) { - Object m = cls.lookup("__getitem__"); - if (m instanceof PyBuiltin) { + if (cls.hasBuiltinGetitem()) { Object v = ((PyDict) base).getOrNull(key); if (v != null) { return v; } - Object missing = cls.lookup("__missing__"); + Object missing = cls.missingMethod(); if (missing != null) { - return Py.obj(missing).call(new Object[] {this, key}, Py.NO_KW); + return Py.obj(missing).call2(this, key); } } } @@ -587,7 +811,7 @@ public void setItem(Object key, Object value) { super.setItem(key, value); return; } - Py.obj(m).call(new Object[] {this, key, value}, Py.NO_KW); + (m instanceof PyObject ? (PyObject) m : Py.obj(m)).call3(this, key, value); } @Override @@ -597,11 +821,18 @@ public void delItem(Object key) { super.delItem(key); return; } - Py.obj(m).call(new Object[] {this, key}, Py.NO_KW); + (m instanceof PyObject ? (PyObject) m : Py.obj(m)).call2(this, key); } @Override public int len() { + PyType t = cls; + if (t.truthVersion != PyType.version) { + t.truthMethods(); + } + if (t.lenBase && base != null) { + return Py.len(base); + } Object r = dunder0("__len__"); if (r == null) { return super.len(); @@ -617,7 +848,7 @@ public int len() { public boolean contains(Object x) { Object m = cls.lookup("__contains__"); if (m != null) { - return Py.isTrue(Py.obj(m).call(new Object[] {this, x}, Py.NO_KW)); + return Py.isTrue((m instanceof PyObject ? (PyObject) m : Py.obj(m)).call2(this, x)); } return super.contains(x); } @@ -641,7 +872,7 @@ public Object next() { return super.next(); } try { - return Py.obj(m).call(new Object[] {this}, Py.NO_KW); + return (m instanceof PyObject ? (PyObject) m : Py.obj(m)).call1(this); } catch (PyException e) { if (e.matches(Py.STOP_ITERATION)) { return null; @@ -681,6 +912,13 @@ private static final class InstanceDict extends PyDict { private long seenFields; private boolean seen; + /// Where each entry's value lives, by entry index, while the keys are + /// as the last refill laid them out: a field index, or `~j` for slot + /// `j`. An iteration step reads its value from there with no name + /// lookup; null when the layout is not known. + private int[] src; + private int srcLen; + // No "dictionary keys changed during iteration" check: CPython 3.14 // does not raise it for an instance's __dict__ either (deleting one // attribute and adding another while iterating runs on, as @@ -699,31 +937,33 @@ void sync() { syncing = true; try { String[] fields = self.fieldNames(); - long mask = 0; boolean small = fields.length <= 64; - for (int i = 0; small && i < fields.length; i++) { - if (self.getField(i) != null) { - mask |= 1L << i; - } - } + long mask = small ? fieldMask(fields.length) : 0; // A net, not the mechanism: every write through this dict // clears `seen`, but a path that changes the instance without // moving its shape or set fields would otherwise go unseen. PyDict other0 = self.nonStrKeys; - int expected = Long.bitCount(mask) + self.shape().size() + (other0 == null ? 0 : other0.size); + int expected = Long.bitCount(mask) + self.shape().size() - self.fieldMarkers() + + (other0 == null ? 0 : other0.size); if (small && seen && seenShape == self.shape && seenFields == mask //NOPMD CompareObjectsWithEquals - identity is meant - && size == expected && refreshValues(fields, mask)) { + && size == expected && (keysOnly || refreshValues(fields, mask))) { return; } seenShape = self.shape; seenFields = mask; seen = small; - String[] names = self.attributeNames(); PyDict other = self.nonStrKeys; - if (sameKeys(names, other)) { + if (size == 0 && other == null && small && fromTemplate(mask)) { + return; + } + // A dict with no entries yet (the first read of this + // instance's __dict__) cannot hold the same keys already. + String[] names = size == 0 ? null : self.attributeNames(); + if (names != null && sameKeys(names, other)) { // The same keys in the same order: the values are // brought up to date in place, so an iteration in // progress over this dict is not disturbed. + src = null; int n = 0; for (int i = 0; i < used && n < names.length; i++) { if (keys[i] != null) { @@ -733,8 +973,9 @@ void sync() { return; } super.clear(); - for (String e : names) { - super.setItem(e, self.own(e)); + refill(fields, other == null ? 0 : other.size); + if (other == null && small) { + keepTemplate(mask); } if (other != null) { for (int i = 0; i < other.used; i++) { @@ -755,7 +996,214 @@ void sync() { /// the shape, the set fields and the size, which fix the keys; the /// name check is a cheap safety net against a path that changes the /// keys without moving any of those, never the expected case. + /// Fills the emptied dict with the set fields and then the shape's + /// slots, the order attributeNames lists them in, by index: what + /// `own(name)` answers for each name, without looking a name up. + private void refill(String[] fields, int others) { + String[] shapeNames = self.shape().names; + Object[] sl = self.slots; + int n = shapeNames.length; + reserve(fields.length + n + others); + int[] map = new int[fields.length + n]; + int w = 0; + boolean[] marked = self.markedFields(fields.length); + for (int i = 0; i < fields.length; i++) { + Object v = self.getField(i); + if (v != null && (marked == null || !marked[i])) { + super.setItem(fields[i], v); + map[w++] = i; + } + } + for (int j = 0; j < n; j++) { + Object v = sl == null || j >= sl.length ? null : sl[j]; + if (v == FIELD_HERE) { //NOPMD CompareObjectsWithEquals - identity is meant + // A field listed where it was first set (see store). + int f = self.fieldIndex(shapeNames[j]); + super.setItem(shapeNames[j], self.getField(f)); + map[w++] = f; + continue; + } + super.setItem(shapeNames[j], v); + map[w++] = ~j; + } + src = used == w ? map : null; + srcLen = w; + } + + /// Fills this empty dict from the class's template when the instance + /// has the shape, the set fields and the field markers it was built + /// for: the keys, hashes and index table are copied, and only the + /// values are read. [#snap] holds the fields, from [#fieldMask]. + private boolean fromTemplate(long mask) { + PyType c = self.cls; + Shape sh = self.shape; + if (c.dictTplKeys == null || c.dictTplShape != sh || c.dictTplMask != mask) { //NOPMD CompareObjectsWithEquals - identity is meant + return false; + } + Object[] sl = self.slots; + boolean[] marks = c.dictTplMarks; + for (int j = 0; j < marks.length; j++) { + if ((sl[j] == FIELD_HERE) != marks[j]) { //NOPMD CompareObjectsWithEquals - identity is meant + return false; + } + } + int[] map = c.dictTplMap; + int n = map.length; + Object[] k = new Object[n]; + long[] h = new long[n]; + Object[] v = new Object[n]; + System.arraycopy(c.dictTplKeys, 0, k, 0, n); + System.arraycopy(c.dictTplHashes, 0, h, 0, n); + int[] ix = null; + int[] tix = c.dictTplIndex; + if (tix != null) { + ix = new int[tix.length]; + System.arraycopy(tix, 0, ix, 0, tix.length); + } + Object[] d = snap; + for (int i = 0; i < n; i++) { + int s = map[i]; + v[i] = s >= 0 ? d[s] : sl[~s]; + } + adopt(k, h, ix, v, n); + src = map; + srcLen = n; + return true; + } + + /// Records what [#refill] just built as the class's template, when + /// the entries are exactly the ones its value map names. + private void keepTemplate(long mask) { + int[] map = src; + if (map == null || srcLen != used || used != size) { + return; + } + int n = used; + PyType c = self.cls; + int sn = self.shape == null ? 0 : self.shape.size(); + boolean[] marks = new boolean[sn]; + for (int j = 0; j < sn; j++) { + marks[j] = self.slots[j] == FIELD_HERE; //NOPMD CompareObjectsWithEquals - identity is meant + } + Object[] k = new Object[n]; + long[] h = new long[n]; + int[] m = new int[n]; + System.arraycopy(keys, 0, k, 0, n); + System.arraycopy(hashes, 0, h, 0, n); + System.arraycopy(map, 0, m, 0, n); + int[] ix = indexTable(); + int[] tix = null; + if (ix != null) { + tix = new int[ix.length]; + System.arraycopy(ix, 0, tix, 0, ix.length); + } + c.dictTplShape = self.shape; + c.dictTplMask = mask; + c.dictTplMarks = marks; + c.dictTplKeys = k; + c.dictTplHashes = h; + c.dictTplIndex = tix; + c.dictTplMap = m; + } + + /// Which of the instance's first `n` (at most 64) fields are set. + /// The fields as [#fieldMask] last read them, in one copyFields call. + private Object[] snap = new Object[0]; + + /// Which of the `n` fields are set, from a fresh [#snap]. + private long fieldMask(int n) { + Object[] d = snap; + if (d.length < n) { + d = new Object[n]; + snap = d; + } + self.copyFields(d); + long mask = 0; + for (int i = 0; i < n; i++) { + if (d[i] != null) { + mask |= 1L << i; + } + } + return mask; + } + + // Iterating an instance's __dict__ used to sync the whole dict on + // every step, quadratic in the attributes. While the keys are as last + // read (same shape, same set fields), a step re-reads only the value + // it returns. + /// Set while [#syncForWalk] runs: the keys are checked, the values + /// are left to each step's [#valueAt]. + private boolean keysOnly; + + @Override + void syncForWalk() { + keysOnly = true; + try { + sync(); + } finally { + keysOnly = false; + } + } + + @Override + void syncStep(boolean last) { + // The set fields are compared (every field read) only at the end + // of the walk: per step that made iterating quadratic in the + // attributes -- pdfplumber's dict(map(..., obj.__dict__.items())) + // spent 6x CPython's time here. A step reads its value from the + // instance anyway (valueAt); an attribute added or removed in the + // middle changes the size, which the last step still reports. + if (!seen || seenShape != self.shape //NOPMD CompareObjectsWithEquals - identity is meant + || last && fieldMask(self.fieldNames().length) != seenFields) { + sync(); + } + } + + @Override + boolean walkAsView() { + return true; + } + + @Override + Object valueAt(int e) { + int[] m = src; + if (m != null && e < srcLen) { + int s = m[e]; + Object v; + if (s >= 0) { + v = self.getField(s); + } else { + Object[] sl = self.slots; + v = sl != null && ~s < sl.length ? sl[~s] : null; + } + if (v != null) { + values[e] = v; + } + return values[e]; + } + Object k = keys[e]; + if (k instanceof String) { + Object v = self.own((String) k); + if (v != null) { + values[e] = v; + } + } + return values[e]; + } + private boolean refreshValues(String[] fieldNames, long mask) { + int[] m = src; + Object[] sl0 = self.slots; + if (m != null && srcLen == used) { + // The order refill recorded; the caller has matched the shape + // and the set fields, which fix it. + Object[] d = snap; + for (int i = 0; i < used; i++) { + int s = m[i]; + values[i] = s >= 0 ? d[s] : sl0[~s]; + } + return true; + } int fieldCount = fieldNames.length; String[] shapeNames = self.shape().names; int f = 0; @@ -772,9 +1220,10 @@ private boolean refreshValues(String[] fieldNames, long mask) { if (!fieldNames[f].equals(keys[i])) { return false; } - values[i] = self.getField(f++); + // Read by the fieldMask the caller has just taken. + values[i] = snap[f++]; } else if (sl != null && slot < sl.length && slot < shapeNames.length) { - if (!shapeNames[slot].equals(keys[i])) { + if (!shapeNames[slot].equals(keys[i]) || sl[slot] == FIELD_HERE) { //NOPMD CompareObjectsWithEquals - identity is meant return false; } values[i] = sl[slot++]; @@ -837,6 +1286,7 @@ public void setItem(Object key, Object value) { // The write may restore a shape the stamp already holds (del // d['b'] then c.b = 9), so the next sync must not trust it. seen = false; + src = null; } @Override @@ -858,6 +1308,7 @@ public void delItem(Object key) { /// Removes `key` from what the dict stands for. private void forget(Object key) { seen = false; + src = null; if (isStr(key)) { self.delAttrDirect(Py.toStr(key)); } else if (self.nonStrKeys != null) { diff --git a/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyInt.java b/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyInt.java index a09b3b3c973..056899fb675 100644 --- a/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyInt.java +++ b/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyInt.java @@ -36,6 +36,13 @@ public class PyInt extends PyObject { private static final PyInt[] CACHE = new PyInt[CACHE_HIGH - CACHE_LOW + 1]; private static final BigInteger LONG_MIN = BigInteger.valueOf(Long.MIN_VALUE); private static final BigInteger LONG_MAX = BigInteger.valueOf(Long.MAX_VALUE); + private static final Long[] BOXED = new Long[1024]; + + static { + for (int i = 0; i < BOXED.length; i++) { + BOXED[i] = Long.valueOf(i); + } + } static { for (int i = 0; i < CACHE.length; i++) { @@ -57,9 +64,16 @@ private PyInt(BigInteger big) { } public static Object of(long v) { + // Long.valueOf caches -128..127 only; iterating bytes and building + // code point lists produce 0..255 all the time, and every one of + // those above 127 was a new object. + if (v >= 0 && v < BOXED.length) { + return BOXED[(int) v]; + } return Long.valueOf(v); } + public static Object of(BigInteger b) { if (b.compareTo(LONG_MIN) >= 0 && b.compareTo(LONG_MAX) <= 0) { return of(b.longValue()); @@ -77,6 +91,29 @@ static PyInt view(long v) { /// Parses an integer literal or `int(str, base)` text. public static Object parse(String s, int base) { + return parse(s, base, s); + } + + /// [#parse], naming `orig` (what int() was given: a str or bytes) as + /// CPython does, by its repr, in a failure. + public static Object parse(String s, int base, Object orig) { + int len = s.length(); + if (base == 10 && len > 0 && len <= 18) { + // The common case, ASCII digits with an optional minus, read + // without the copies and per-digit lookups below. + int k = s.charAt(0) == '-' && len > 1 ? 1 : 0; + long v = 0; + for (; k < len; k++) { + int d = s.charAt(k) - '0'; + if (d < 0 || d > 9) { + break; + } + v = v * 10 + d; + } + if (k == len) { + return of(s.charAt(0) == '-' ? -v : v); + } + } String t = s.trim().replace("_", ""); boolean neg = false; if (t.startsWith("-") || t.startsWith("+")) { @@ -85,13 +122,15 @@ public static Object parse(String s, int base) { } if (base == 0 || base == 16 || base == 8 || base == 2) { String lower = t.length() > 1 ? t.substring(0, 2) : ""; - if ("0x".equals(lower) || "0X".equals(lower)) { + // A prefix is only read as one when it names the base asked for + // (or base 0): int("0B47", 16) is 0xB47, not a binary literal. + if (("0x".equals(lower) || "0X".equals(lower)) && (base == 0 || base == 16)) { base = 16; t = t.substring(2); - } else if ("0o".equals(lower) || "0O".equals(lower)) { + } else if (("0o".equals(lower) || "0O".equals(lower)) && (base == 0 || base == 8)) { base = 8; t = t.substring(2); - } else if ("0b".equals(lower) || "0B".equals(lower)) { + } else if (("0b".equals(lower) || "0B".equals(lower)) && (base == 0 || base == 2)) { base = 2; t = t.substring(2); } else if (base == 0) { @@ -99,11 +138,11 @@ public static Object parse(String s, int base) { } } if (t.length() == 0) { - throw Py.valueError("invalid literal for int() with base " + base + ": '" + s + "'"); + throw Py.valueError("invalid literal for int() with base " + base + ": " + Py.toRepr(orig)); } for (int i = 0; i < t.length(); i++) { if (Character.digit(t.charAt(i), base) < 0) { - throw Py.valueError("invalid literal for int() with base " + base + ": '" + s + "'"); + throw Py.valueError("invalid literal for int() with base " + base + ": " + Py.toRepr(orig)); } } if (t.length() <= 12 || base == 10 && t.length() <= 18) { diff --git a/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyJavaIter.java b/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyJavaIter.java index 387608edcb1..d092aff2904 100644 --- a/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyJavaIter.java +++ b/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyJavaIter.java @@ -60,4 +60,16 @@ public Object next() { } return v; } + + /// The source, while it has values left; null once it ran out. For a + /// consumer that drains a source it knows without stepping it value by + /// value (`dict(zip(keys, row))`), which then calls [#finish]. + Source liveSource() { + return done ? null : source; + } + + /// Marks this iterator exhausted, after its source was drained directly. + void finish() { + done = true; + } } diff --git a/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyJson.java b/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyJson.java new file mode 100644 index 00000000000..efba0867ec2 --- /dev/null +++ b/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyJson.java @@ -0,0 +1,762 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.python.runtime; + +import com.codename1.io.JSONParser; +import com.codename1.io.JSONValueFactory; +import com.codename1.util.BigInteger; +import java.io.IOException; + +/// `_cn1json`: `json.loads` on Codename One's strict JSON reader. +/// +/// CPython decodes JSON in C (`_json.scanstring`, `scan_once`); run as +/// transpiled Python the decoder dispatched generically on every character. +/// Here [JSONParser#parseStrict(String, JSONValueFactory)] walks the text and +/// this factory builds the Python values directly: a `dict` per object (a +/// repeated key keeps its first position and its last value, as CPython's +/// does), a `list` per array, `int` and `float`, and `NaN`/`Infinity`. +/// +/// `loads` answers [#FAILED] for anything the reader refuses, and `json.py` +/// then decodes the text again in Python, which raises `JSONDecodeError` with +/// CPython's own message and position. A malformed document is the rare case, +/// so it pays for being parsed twice and the messages stay exactly CPython's. +final class PyJson { + /// What `loads` answers when the reader refused the document. + static final Object FAILED = new PyList(); + + private PyJson() { + } + + static PyModule module() { + PyModule m = new PyModule("_cn1json", new String[0]); + m.setAttr("FAILED", FAILED); + // loads(s, strict, object_hook, object_pairs_hook) + m.setAttr("loads", PyBuiltin.positional("loads", a -> { + Values f = Values.take(Py.isTrue(a[1]), a[2] == Py.NONE ? null : a[2], + a[3] == Py.NONE ? null : a[3]); + Object r = parse(Py.toStr(a[0]), f); + Values.give(f); + return r; + })); + // dumps(o, ensure_ascii, check_circular, allow_nan, sort_keys, indent, + // item_separator, key_separator, skipkeys, other) + // options(ensure_ascii, check_circular, allow_nan, sort_keys, indent, + // item_separator, key_separator, skipkeys, other): an encoder's + // settings, made once when the encoder is, so that encode() passes two + // values per call rather than ten. + m.setAttr("options", PyBuiltin.positional("options", a -> new PyJavaObject(new Options(Py.isTrue(a[0]), + Py.isTrue(a[1]), Py.isTrue(a[2]), Py.isTrue(a[3]), a[4] == Py.NONE ? null : Py.toStr(a[4]), + Py.toStr(a[5]), Py.toStr(a[6]), Py.isTrue(a[7]), a[8])))); + m.setAttr("encode", PyBuiltin.fixed2("encode", (o, opts) -> { + Object v = opts instanceof PyJavaObject ? ((PyJavaObject) opts).value : opts; + if (!(v instanceof Options)) { + throw Py.typeError("encode() needs the value options() made"); + } + Options p = (Options) v; + Encoder e = Encoder.take(p.ascii, p.circular, p.allowNan, p.sortKeys, p.indent, p.itemSep, p.keySep, + p.skipKeys, p.other); + e.value(o, 0); + String r = new String(e.buf, 0, e.len); + Encoder.give(e); + return r; + })); + m.setAttr("dumps", PyBuiltin.positional("dumps", a -> { + Encoder e = Encoder.take(Py.isTrue(a[1]), Py.isTrue(a[2]), Py.isTrue(a[3]), Py.isTrue(a[4]), + a[5] == Py.NONE ? null : Py.toStr(a[5]), Py.toStr(a[6]), Py.toStr(a[7]), Py.isTrue(a[8]), a[9]); + e.value(a[0], 0); + String r = new String(e.buf, 0, e.len); + Encoder.give(e); + return r; + })); + return m; + } + + /// The parse, apart so that its handler is set up only by this call and not by every + /// frame around it. + private static Object parse(String text, Values f) { + try { + return JSONParser.parseStrict(text, f); + } catch (IOException err) { + return FAILED; + } + } + + /// `json.dumps` for the builtin types, as CPython's C encoder + /// (`c_make_encoder`) writes them: one buffer, no list of fragments. + /// + /// Only an exact `str`, `int`, `float`, `bool`, `None`, `list`, `tuple` + /// and `dict` is written here. Anything else -- a subclass of one of them, + /// an object `default` converts, a dict whose keys must be sorted but are + /// not all strings -- is handed to `other`, json.py's own encoder, for + /// that one value, with the containers open around it so a cycle through + /// it is still reported. What `isinstance` and `default` decide therefore + /// stays in Python, exactly as CPython decides it. + /// The settings of one json.JSONEncoder, as [Encoder] takes them. + private static final class Options { + final boolean ascii; + final boolean circular; + final boolean allowNan; + final boolean sortKeys; + final String indent; + final String itemSep; + final String keySep; + final boolean skipKeys; + final Object other; + + Options(boolean ascii, boolean circular, boolean allowNan, boolean sortKeys, String indent, String itemSep, + String keySep, boolean skipKeys, Object other) { + this.ascii = ascii; + this.circular = circular; + this.allowNan = allowNan; + this.sortKeys = sortKeys; + this.indent = indent; + this.itemSep = itemSep; + this.keySep = keySep; + this.skipKeys = skipKeys; + this.other = other; + } + } + + private static final class Encoder { + /// The output, written straight into an array: a native StringBuilder + /// append takes the builder's owner lock and the thread's identity + /// each call, and an encoder appends several times per value. + char[] buf = new char[256]; + int len; + private boolean ascii; + private boolean circular; + private boolean allowNan; + private boolean sortKeys; + private String indent; + private String itemSep; + private String keySep; + private boolean skipKeys; + private Object other; + private final java.util.ArrayList markers = new java.util.ArrayList(); + + /// One encoder kept between calls, with its buffer, so a dumps allocates only its + /// result, as CPython's does. A call takes it and gives it back when done; a dumps + /// made while one is running (from a default function) finds none and makes its own, + /// and one that raises simply does not give it back, so no handler is needed for it. + private static Encoder spare; + + static Encoder take(boolean ascii, boolean circular, boolean allowNan, boolean sortKeys, String indent, + String itemSep, String keySep, boolean skipKeys, Object other) { + Encoder e = spare; + if (e == null) { + return new Encoder(ascii, circular, allowNan, sortKeys, indent, itemSep, keySep, skipKeys, other); + } + spare = null; + e.set(ascii, circular, allowNan, sortKeys, indent, itemSep, keySep, skipKeys, other); + e.len = 0; + e.markers.clear(); + return e; + } + + static void give(Encoder e) { + if (e.buf.length > 4096) { + // One large document must not stay held for the life of the program. + e.buf = new char[256]; + } + e.other = null; + spare = e; + } + + Encoder(boolean ascii, boolean circular, boolean allowNan, boolean sortKeys, String indent, String itemSep, + String keySep, boolean skipKeys, Object other) { + set(ascii, circular, allowNan, sortKeys, indent, itemSep, keySep, skipKeys, other); + } + + private void set(boolean ascii, boolean circular, boolean allowNan, boolean sortKeys, String indent, + String itemSep, String keySep, boolean skipKeys, Object other) { + this.ascii = ascii; + this.circular = circular; + this.allowNan = allowNan; + this.sortKeys = sortKeys; + this.indent = indent; + this.itemSep = itemSep; + this.keySep = keySep; + this.skipKeys = skipKeys; + this.other = other; + } + + + private void room(int n) { + if (len + n > buf.length) { + char[] b = new char[Math.max(buf.length * 2, len + n)]; + System.arraycopy(buf, 0, b, 0, len); + buf = b; + } + } + + private void put(char c) { + if (len == buf.length) { + room(1); + } + buf[len++] = c; + } + + private void put(String s) { + int n = s.length(); + room(n); + s.getChars(0, n, buf, len); + len += n; + } + + private void putLong(long v) { + if (v >= 0 && v < 10) { + put((char) ('0' + v)); + return; + } + if (v == Long.MIN_VALUE) { + put("-9223372036854775808"); + return; + } + room(20); + if (v < 0) { + buf[len++] = '-'; + v = -v; + } + int start = len; + while (v > 0) { + buf[len++] = (char) ('0' + v % 10); + v /= 10; + } + for (int i = start, j = len - 1; i < j; i++, j--) { + char t = buf[i]; + buf[i] = buf[j]; + buf[j] = t; + } + } + + private static final char[] HEX = "0123456789abcdef".toCharArray(); + + /// A JSON string literal, as json's encoder writes one: copied in one + /// block, then escaped in place from the first character that needs it. + private void quote(String s) { + int n = s.length(); + room(n + 2); + buf[len++] = '"'; + s.getChars(0, n, buf, len); + int limit = ascii ? 0x7f : 0x10000; + int i = len; + int end = len + n; + while (i < end) { + char c = buf[i]; + if (c < 0x20 || c == '"' || c == '\\' || c >= limit) { + break; + } + i++; + } + if (i == end) { + len = end; + buf[len++] = '"'; + return; + } + // Escaped in place, from the back: one pass counts how much longer the + // escapes make the text, a second walks it from its end and writes each + // character, or its escape, at its final position. Nothing is read from + // the string again -- a character read from a string is a call that asks + // which form the string is in -- and no second buffer is copied through. + int extra = 0; + for (int k = i; k < end; k++) { + char c = buf[k]; + if (c < 0x20 || c == '"' || c == '\\' || c >= limit) { + extra += c == '"' || c == '\\' || c == '\n' || c == '\r' || c == '\t' || c == '\b' + || c == '\f' ? 1 : 5; + } + } + len = end; + room(extra + 1); + char[] o = buf; + int d = end + extra; + for (int k = end - 1; k >= i; k--) { + char c = o[k]; + if (c >= 0x20 && c != '"' && c != '\\' && c < limit) { + o[--d] = c; + continue; + } + switch (c) { + case '"': + o[--d] = '"'; + break; + case '\\': + o[--d] = '\\'; + break; + case '\n': + o[--d] = 'n'; + break; + case '\r': + o[--d] = 'r'; + break; + case '\t': + o[--d] = 't'; + break; + case '\b': + o[--d] = 'b'; + break; + case '\f': + o[--d] = 'f'; + break; + default: + o[--d] = HEX[c & 15]; + o[--d] = HEX[c >> 4 & 15]; + o[--d] = HEX[c >> 8 & 15]; + o[--d] = HEX[c >> 12 & 15]; + o[--d] = 'u'; + } + o[--d] = '\\'; + } + len = end + extra; + o[len++] = '"'; + } + + void value(Object o, int level) { + if (o instanceof String) { + quote((String) o); + } else if (o == Py.NONE) { //NOPMD CompareObjectsWithEquals - singleton + put("null"); + } else if (o == Py.TRUE) { //NOPMD CompareObjectsWithEquals - singleton + put("true"); + } else if (o == Py.FALSE) { //NOPMD CompareObjectsWithEquals - singleton + put("false"); + } else if (o instanceof Long) { + putLong(((Long) o).longValue()); + } else if (o instanceof Double) { + floatText(((Double) o).doubleValue()); + } else if (o instanceof PyInt && o.getClass() == PyInt.class) { + put(((PyInt) o).repr()); + } else if (o instanceof PyList && Py.typeOf(o) == Py.LIST_TYPE) { //NOPMD CompareObjectsWithEquals + PyList l = (PyList) o; + int n = l.size(); + sequence(o, n, l, null, level); + } else if (o instanceof PyTuple && Py.typeOf(o) == Py.TUPLE_TYPE) { //NOPMD CompareObjectsWithEquals + PyTuple t = (PyTuple) o; + sequence(o, t.size(), null, t, level); + } else if (o instanceof PyDict && Py.typeOf(o) == Py.DICT_TYPE) { //NOPMD CompareObjectsWithEquals + dict((PyDict) o, level); + } else { + delegate(o, level); + } + } + + private void delegate(Object o, int level) { + put(Py.toStr(Py.call(other, o, new PyList(markers.toArray()), Py.of((long) level)))); + } + + private void floatText(double d) { + String text; + if (Double.isNaN(d)) { + text = "NaN"; + } else if (d == Double.POSITIVE_INFINITY) { + text = "Infinity"; + } else if (d == Double.NEGATIVE_INFINITY) { + text = "-Infinity"; + } else { + put(PyFloat.repr(d)); + return; + } + if (!allowNan) { + throw Py.valueError("Out of range float values are not JSON compliant: " + PyFloat.repr(d)); + } + put(text); + } + + private void mark(Object o) { + if (!circular) { + return; + } + for (int i = markers.size() - 1; i >= 0; i--) { + if (markers.get(i) == o) { //NOPMD CompareObjectsWithEquals - identity is meant + throw Py.valueError("Circular reference detected"); + } + } + markers.add(o); + } + + private void unmark() { + if (circular) { + markers.remove(markers.size() - 1); + } + } + + private void newline(int level) { + if (indent != null) { + put('\n'); + for (int i = 0; i < level; i++) { + put(indent); + } + } + } + + private void sequence(Object o, int n, PyList l, PyTuple t, int level) { + mark(o); + if (n == 0) { + put("[]"); + } else { + put('['); + for (int i = 0; i < n; i++) { + if (i > 0) { + put(itemSep); + } + newline(level + 1); + value(l != null ? l.get(i) : t.get(i), level + 1); + } + newline(level); + put(']'); + } + unmark(); + } + + private void dict(PyDict d, int level) { + int used = d.used; + Object[] keys = d.keys; + Object[] values = d.values; + int[] order = null; + if (sortKeys && d.size() > 1) { + order = sortedStringKeys(keys, used); + if (order == null) { + delegate(d, level); + return; + } + } + mark(d); + if (d.size() == 0) { + put("{}"); + unmark(); + return; + } + put('{'); + boolean first = true; + int count = order != null ? order.length : used; + for (int j = 0; j < count; j++) { + int i = order != null ? order[j] : j; + Object k = keys[i]; + if (k == null) { + continue; + } + String key = key(k); + if (key == null) { + continue; + } + if (!first) { + put(itemSep); + } + first = false; + newline(level + 1); + quote(key); + put(keySep); + value(values[i], level + 1); + } + newline(level); + put('}'); + unmark(); + } + + /// The entry indices in key order when every key is a str, else null: + /// sorting mixed keys is Python's comparison to make, and raises there. + private static int[] sortedStringKeys(Object[] keys, int used) { + int n = 0; + for (int i = 0; i < used; i++) { + if (keys[i] != null) { + if (!(keys[i] instanceof String)) { + return null; + } + n++; + } + } + if (n <= 32) { + // The usual object: a handful of keys, ordered in the array + // that is answered, with no boxed indices and no comparator. + int[] out = new int[n]; + int w = 0; + for (int i = 0; i < used; i++) { + if (keys[i] == null) { + continue; + } + String key = (String) keys[i]; + int at = w++; + while (at > 0 && codePointCompare((String) keys[out[at - 1]], key) > 0) { + out[at] = out[at - 1]; + at--; + } + out[at] = i; + } + return out; + } + Integer[] idx = new Integer[n]; + n = 0; + for (int i = 0; i < used; i++) { + if (keys[i] != null) { + idx[n++] = Integer.valueOf(i); + } + } + final Object[] k = keys; + java.util.Arrays.sort(idx, new java.util.Comparator() { + @Override + public int compare(Integer a, Integer b) { + return codePointCompare((String) k[a.intValue()], (String) k[b.intValue()]); + } + }); + int[] out = new int[n]; + for (int i = 0; i < n; i++) { + out[i] = idx[i].intValue(); + } + return out; + } + + /// Python orders str by code point; String.compareTo orders UTF-16 + /// units, which differ for a supplementary character against U+E000 + /// to U+FFFF. + private static int codePointCompare(String a, String b) { + int n = Math.min(a.length(), b.length()); + for (int i = 0; i < n; i++) { + char x = a.charAt(i); + char y = b.charAt(i); + if (x != y) { + boolean sx = x >= 0xD800 && x < 0xE000; + boolean sy = y >= 0xD800 && y < 0xE000; + if (sx != sy) { + return sx ? 1 : -1; + } + return x - y; + } + } + return a.length() - b.length(); + } + + private String key(Object k) { + if (k instanceof String) { + return (String) k; + } + if (k instanceof Double) { + int mark = len; + floatText(((Double) k).doubleValue()); + String t = new String(buf, mark, len - mark); + len = mark; + return t; + } + if (k == Py.TRUE) { //NOPMD CompareObjectsWithEquals - singleton + return "true"; + } + if (k == Py.FALSE) { //NOPMD CompareObjectsWithEquals - singleton + return "false"; + } + if (k == Py.NONE) { //NOPMD CompareObjectsWithEquals - singleton + return "null"; + } + if (k instanceof Long || k instanceof PyInt && k.getClass() == PyInt.class) { + return k instanceof Long ? k.toString() : ((PyInt) k).repr(); + } + PyType kt = Py.typeOf(k); + if (kt.isSubtype(Py.STR_TYPE) || kt.isSubtype(Py.INT_TYPE) || kt.isSubtype(Py.FLOAT_TYPE)) { + return Py.toStr(Py.call(other, k, Py.NONE, Py.of(-1L))); + } + if (skipKeys) { + return null; + } + throw Py.typeError("keys must be str, int, float, bool or None, not " + kt.name); + } + } + + /// Builds Python values for the reader. + private static final class Values extends JSONValueFactory { + private boolean strict; + private Object objectHook; + private Object pairsHook; + + Values(boolean strict, Object objectHook, Object pairsHook) { + this.strict = strict; + this.objectHook = objectHook; + this.pairsHook = pairsHook; + } + + /// One builder kept between calls, as [Encoder#take] keeps an encoder: a hook that + /// calls loads while one is running finds none and makes its own. + private static Values spare; + + static Values take(boolean strict, Object objectHook, Object pairsHook) { + Values v = spare; + if (v == null) { + return new Values(strict, objectHook, pairsHook); + } + spare = null; + v.strict = strict; + v.objectHook = objectHook; + v.pairsHook = pairsHook; + v.top = 0; + v.depth = 0; + return v; + } + + static void give(Values v) { + if (v.stack.length > 1024) { + v.stack = new Object[64]; + } else { + // What the last document held must not stay reachable from here. + java.util.Arrays.fill(v.stack, 0, v.stack.length, null); + } + v.objectHook = null; + v.pairsHook = null; + spare = v; + } + + /// Members and elements of the containers being read, innermost last. + /// A container is built once, at its final size, when it closes: an + /// object's dict then allocates its arrays once instead of growing + /// from four entries to eight to sixteen, and a list holds exactly its + /// elements. + private Object[] stack = new Object[64]; + private int top; + /// One frame per open container, reused: where its entries start. + private Frame[] frames = new Frame[16]; + private int depth; + + private static final class Frame { + int start; + } + + private Frame open() { + if (depth == frames.length) { + Frame[] f = new Frame[depth * 2]; + System.arraycopy(frames, 0, f, 0, depth); + frames = f; + } + Frame f = frames[depth]; + if (f == null) { + f = new Frame(); + frames[depth] = f; + } + depth++; + f.start = top; + return f; + } + + private void push(Object o) { + if (top == stack.length) { + Object[] g = new Object[top * 2]; + System.arraycopy(stack, 0, g, 0, top); + stack = g; + } + stack[top++] = o; + } + + @Override + public Object newObject() { + return open(); + } + + @Override + public void put(Object object, String key, Object value) { + push(key); + push(value); + } + + @Override + public Object endObject(Object object) { + int start = ((Frame) object).start; + int n = (top - start) >> 1; + Object result; + if (pairsHook != null) { + Object[] pairs = new Object[n]; + for (int i = 0; i < n; i++) { + pairs[i] = Py.tuple(stack[start + 2 * i], stack[start + 2 * i + 1]); + } + result = new PyList(pairs); + } else { + PyDict d = new PyDict(n); + for (int i = start; i < top; i += 2) { + d.setItem(stack[i], stack[i + 1]); + } + result = d; + } + close(start); + if (pairsHook != null) { + return Py.call(pairsHook, result); + } + return objectHook != null ? Py.call(objectHook, result) : result; + } + + private void close(int start) { + for (int i = start; i < top; i++) { + stack[i] = null; + } + top = start; + depth--; + } + + @Override + public Object newArray() { + return open(); + } + + @Override + public void add(Object array, Object value) { + push(value); + } + + @Override + public Object endArray(Object array) { + int start = ((Frame) array).start; + Object[] items = new Object[top - start]; + System.arraycopy(stack, start, items, 0, items.length); + close(start); + return PyList.of(items); + } + + @Override + public Object integer(long value) { + return Py.of(value); + } + + @Override + public Object bigInteger(String digits) { + return PyInt.of(new BigInteger(digits)); + } + + @Override + public Object decimal(double value) { + return Py.ofFloat(value); + } + + @Override + public Object bool(boolean value) { + return Py.bool(value); + } + + @Override + public Object nullValue() { + return Py.NONE; + } + + @Override + public boolean allowNonFinite() { + return true; + } + + @Override + public boolean allowControlCharacters() { + return !strict; + } + } +} diff --git a/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyList.java b/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyList.java index 21479f1eb4e..29316181bea 100644 --- a/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyList.java +++ b/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyList.java @@ -184,7 +184,10 @@ private void appendInt(int v) { private void appendObject(Object v) { if (size == items.length) { - Object[] n = new Object[size * 2 + 4]; + // 8 first, as CPython's list starts an unsized fill: a list + // built from a filter or a generator of a dozen items then + // allocates twice rather than three times. + Object[] n = new Object[size + (size >> 1) + 8]; System.arraycopy(items, 0, n, 0, size); items = n; } @@ -217,12 +220,59 @@ public void extend(Object iterable) { size += n; return; } + if (o.ints == null && o.floats == null && ints == null && floats == null) { + // Objects into objects: one copy, as CPython's list_extend + // does, not an append (and a storage check) per element. + // The source array and length are read first, so + // x.extend(x) copies what x held before. + Object[] src = o.items; + Object[] dst = items; + if (size + n > dst.length) { + Object[] g = new Object[Math.max(4, size == 0 ? n : size + n + (size >> 1))]; + System.arraycopy(dst, 0, g, 0, size); + items = g; + dst = g; + } + System.arraycopy(src, 0, dst, size, n); + size += n; + return; + } for (int i = 0; i < n; i++) { append(o.get(i)); } return; } Object it = Py.iter(iterable); + if (it instanceof PyGenerator) { + // A generator drained under ONE handler, as a transpiled for + // loop drains it: next() enters a try per value, a setjmp on + // ParparVM. + PyGenerator g = (PyGenerator) it; + try { + for (Object v = PyGenerator.loopNext(g); v != null; v = PyGenerator.loopNext(g)) { + append(v); + } + } catch (Throwable e) { + throw PyGenerator.loopEscape(g, e); + } + return; + } + if (it instanceof Builtins.FilterIter) { + // Both classes are final: next() is a direct call, not a + // virtual one through Py.next per item. + Builtins.FilterIter f = (Builtins.FilterIter) it; + for (Object v = f.next(); v != null; v = f.next()) { + append(v); + } + return; + } + if (it instanceof Builtins.MapIter) { + Builtins.MapIter m = (Builtins.MapIter) it; + for (Object v = m.next(); v != null; v = m.next()) { + append(v); + } + return; + } for (Object v = Py.next(it); v != null; v = Py.next(it)) { append(v); } @@ -468,7 +518,7 @@ public Object rmul(Object o) { } private int checkIndex(Object key) { - long i = Py.index(key); + long i = Py.subscript(key); if (i < 0) { i += size; } @@ -496,6 +546,11 @@ public Object getItem(Object key) { int[] r = ((PySlice) key).indices(size); int n = PySlice.length(r); Object[] out = new Object[n]; + if (r[2] == 1) { + // A plain slice is one block copy, not a checked store per element. + System.arraycopy(items, r[0], out, 0, n); + return new PyList(out); + } for (int i = 0, j = r[0]; i < n; i++, j += r[2]) { out[i] = items[j]; } @@ -851,35 +906,158 @@ Object at(int i) { }; } - /// `list.sort(key=None, reverse=False)`: a stable merge sort. + /// `list.sort(key=None, reverse=False)`: a stable merge sort. The order + /// is an int array, and keys that are all ints compare as longs. public void sort(Object key, boolean reverse) { + boolean none = key == null || key == Py.NONE; //NOPMD CompareObjectsWithEquals - identity is meant + if (none && ints != null) { + // Unboxed ints: equal ones cannot be told apart, so stability is + // moot and the array sorts in place, never boxed. + java.util.Arrays.sort(ints, 0, size); + if (reverse) { + int[] l = ints; + for (int i = 0, j = size - 1; i < j; i++, j--) { + int t = l[i]; + l[i] = l[j]; + l[j] = t; + } + } + return; + } objects(); + PyObject kf = none ? null : Py.obj(key); Object[] keys = new Object[size]; + boolean longs = true; + boolean strs = true; for (int i = 0; i < size; i++) { - keys[i] = key == null || key == Py.NONE ? items[i] : Py.obj(key).call(new Object[] {items[i]}, Py.NO_KW); //NOPMD CompareObjectsWithEquals - identity is meant + Object k = none ? items[i] : kf.call1(items[i]); + keys[i] = k; + longs &= k instanceof Long; + strs &= k instanceof String; + } + if (longs && size > 1 && packable(keys)) { + sortPacked(keys, reverse); + return; + } + long[] lk = null; + Object[] tie = keys; + if (longs) { + lk = new long[size]; + for (int i = 0; i < size; i++) { + lk[i] = (Long) keys[i]; + } + tie = null; + } else if (!strs) { + lk = new long[size]; + if (!tupleFirsts(keys, lk)) { + lk = null; + } } - Integer[] order = new Integer[size]; + int[] order = new int[size]; for (int i = 0; i < size; i++) { - order[i] = Integer.valueOf(i); + order[i] = i; } - Integer[] tmp = new Integer[size]; - mergeSort(order, tmp, keys, 0, size, reverse); + mergeSort(order, new int[size], tie, lk, strs && size > 0, 0, size, reverse); Object[] out = new Object[Math.max(4, size)]; for (int i = 0; i < size; i++) { - out[i] = items[order[i].intValue()]; + out[i] = items[order[i]]; + } + items = out; + } + + /// When every key is a tuple whose first item is an int, those ints, so + /// that most comparisons are settled without touching the tuples (as + /// CPython's unsafe_tuple_compare does), written into `r`; false when + /// some key is not such a tuple. + private static boolean tupleFirsts(Object[] keys, long[] r) { + for (int i = 0; i < keys.length; i++) { + if (!(keys[i] instanceof PyTuple)) { + return false; + } + Object[] t = ((PyTuple) keys[i]).arr(); + if (t.length == 0 || !(t[0] instanceof Long)) { + return false; + } + r[i] = ((Long) t[0]).longValue(); + } + return true; + } + + private static boolean packable(Object[] keys) { + for (Object k : keys) { + long v = ((Long) k).longValue(); + if (v != (int) v) { + return false; + } + } + return true; + } + + /// Int keys that fit in 32 bits: each packed above its index into one + /// long, so a primitive merge sort orders by key and breaks ties by + /// position -- stable, with no index indirection or boxed compare. + /// Reversed, the key is complemented, which keeps equal keys in their + /// original order as Python's reverse=True does. + private void sortPacked(Object[] keys, boolean reverse) { + int n = size; + long[] p = new long[n]; + for (int i = 0; i < n; i++) { + int k = (int) ((Long) keys[i]).longValue(); + p[i] = ((long) (reverse ? ~k : k) << 32) | i; + } + mergeLongs(p, new long[n], 0, n); + Object[] src = items; + Object[] out = new Object[Math.max(4, n)]; + for (int i = 0; i < n; i++) { + out[i] = src[(int) p[i]]; } items = out; } - private static void mergeSort(Integer[] a, Integer[] tmp, Object[] keys, int lo, int hi, boolean rev) { + private static void mergeLongs(long[] a, long[] tmp, int lo, int hi) { + if (hi - lo <= 12) { + for (int i = lo + 1; i < hi; i++) { + long v = a[i]; + int j = i - 1; + while (j >= lo && a[j] > v) { + a[j + 1] = a[j]; + j--; + } + a[j + 1] = v; + } + return; + } + int mid = (lo + hi) >>> 1; + mergeLongs(a, tmp, lo, mid); + mergeLongs(a, tmp, mid, hi); + if (a[mid - 1] < a[mid]) { + return; + } + int i = lo; + int j = mid; + int k = lo; + while (i < mid && j < hi) { + tmp[k++] = a[j] < a[i] ? a[j++] : a[i++]; + } + while (i < mid) { + tmp[k++] = a[i++]; + } + while (j < hi) { + tmp[k++] = a[j++]; + } + System.arraycopy(tmp, lo, a, lo, hi - lo); + } + + private static void mergeSort(int[] a, int[] tmp, Object[] keys, long[] lk, boolean strs, int lo, int hi, + boolean rev) { if (hi - lo < 2) { return; } if (hi - lo <= 8) { for (int i = lo + 1; i < hi; i++) { - Integer v = a[i]; + int v = a[i]; int j = i - 1; - while (j >= lo && before(keys[v.intValue()], keys[a[j].intValue()], rev)) { + while (j >= lo && before(keys, lk, strs, v, a[j], rev)) { a[j + 1] = a[j]; j--; } @@ -888,13 +1066,17 @@ private static void mergeSort(Integer[] a, Integer[] tmp, Object[] keys, int lo, return; } int mid = (lo + hi) >>> 1; - mergeSort(a, tmp, keys, lo, mid, rev); - mergeSort(a, tmp, keys, mid, hi, rev); + mergeSort(a, tmp, keys, lk, strs, lo, mid, rev); + mergeSort(a, tmp, keys, lk, strs, mid, hi, rev); + if (!before(keys, lk, strs, a[mid], a[mid - 1], rev)) { + // Already in order: the two runs need no merge. + return; + } int i = lo; int j = mid; int k = lo; while (i < mid && j < hi) { - if (before(keys[a[j].intValue()], keys[a[i].intValue()], rev)) { + if (before(keys, lk, strs, a[j], a[i], rev)) { tmp[k++] = a[j++]; } else { tmp[k++] = a[i++]; @@ -909,6 +1091,26 @@ private static void mergeSort(Integer[] a, Integer[] tmp, Object[] keys, int lo, System.arraycopy(tmp, lo, a, lo, hi - lo); } + private static boolean before(Object[] keys, long[] lk, boolean strs, int x, int y, boolean rev) { + if (lk != null) { + long a = lk[x]; + long b = lk[y]; + if (a != b) { + return rev ? b < a : a < b; + } + // Equal ints never move; equal first items of two tuples leave + // the rest of the tuples to decide. + return keys != null && before(keys[x], keys[y], rev); + } + if (strs) { + // Every key a str, checked once up front as CPython's + // unsafe_latin_compare is: no comparison can run user code. + int c = PyStr.compare((String) keys[x], (String) keys[y]); + return rev ? c > 0 : c < 0; + } + return before(keys[x], keys[y], rev); + } + /// Whether `x` must move before `y`: `x < y`, or `y < x` reversed. Equal /// keys never move, which keeps the sort stable in both directions. private static boolean before(Object x, Object y, boolean rev) { diff --git a/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyMatch.java b/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyMatch.java index 2ea7dadd35b..435feb89427 100644 --- a/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyMatch.java +++ b/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyMatch.java @@ -48,7 +48,7 @@ public static Object match(Object pattern, Object subject) { private static Object[] parts(Object pattern) { if (pattern instanceof PyTuple) { - return ((PyTuple) pattern).items; + return ((PyTuple) pattern).arr(); } throw Py.runtimeError("internal error: bad pattern"); } diff --git a/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyMemoryView.java b/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyMemoryView.java index 34d59a2e77e..aed1c99f080 100644 --- a/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyMemoryView.java +++ b/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyMemoryView.java @@ -108,7 +108,7 @@ public Object getItem(Object key) { } private int index(Object key) { - long i = Py.index(key); + long i = Py.subscript(key); if (i < 0) { i += length; } @@ -202,28 +202,28 @@ private static PyMemoryView self(Object o) { static void install() { PyType t = Py.MEMORYVIEW_TYPE; - t.define("tobytes", PyBuiltin.method(t, "tobytes", a -> new PyBytes(self(a[0]).bytes()))); - t.define("tolist", PyBuiltin.method(t, "tolist", a -> { - byte[] b = self(a[0]).bytes(); + t.define("tobytes", PyBuiltin.method1(t, "tobytes", a0 -> new PyBytes(self(a0).bytes()))); + t.define("tolist", PyBuiltin.method1(t, "tolist", a0 -> { + byte[] b = self(a0).bytes(); Object[] r = new Object[b.length]; for (int i = 0; i < b.length; i++) { r[i] = PyInt.of(b[i] & 0xff); } return new PyList(r); })); - t.define("hex", PyBuiltin.method(t, "hex", a -> Py.call(Py.BYTES_TYPE.lookup("hex"), - new PyBytes(self(a[0]).bytes())))); - t.define("release", PyBuiltin.method(t, "release", a -> { - self(a[0]).released = true; + t.define("hex", PyBuiltin.method1(t, "hex", a0 -> Py.call(Py.BYTES_TYPE.lookup("hex"), + new PyBytes(self(a0).bytes())))); + t.define("release", PyBuiltin.method1(t, "release", a0 -> { + self(a0).released = true; return Py.NONE; })); - t.define("toreadonly", PyBuiltin.method(t, "toreadonly", a -> { - PyMemoryView m = self(a[0]); + t.define("toreadonly", PyBuiltin.method1(t, "toreadonly", a0 -> { + PyMemoryView m = self(a0); return new PyMemoryView(new PyBytes(m.bytes()), 0, 1, m.length); })); - t.define("__enter__", PyBuiltin.method(t, "__enter__", a -> self(a[0]))); - t.define("__exit__", PyBuiltin.method(t, "__exit__", a -> { - self(a[0]).released = true; + t.define("__enter__", PyBuiltin.method1(t, "__enter__", a0 -> self(a0))); + t.define("__exit__", PyBuiltin.method1(t, "__exit__", a0 -> { + self(a0).released = true; return Py.FALSE; })); t.factory = (type, args, kw) -> { diff --git a/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyMethod.java b/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyMethod.java index 51d6d0a0378..81ecdef9fef 100644 --- a/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyMethod.java +++ b/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyMethod.java @@ -38,6 +38,71 @@ public PyType type() { return Py.METHOD_TYPE; } + @Override + public Object callKwF(String[] kwNames, Object a) { + return Py.obj(func).callKwF(kwNames, self, a); + } + + @Override + public Object callKwF(String[] kwNames, Object a, Object b) { + return Py.obj(func).callKwF(kwNames, self, a, b); + } + + @Override + public Object callKwF(String[] kwNames, Object a, Object b, Object c) { + return Py.obj(func).callKwF(kwNames, self, a, b, c); + } + + @Override + public Object callKwF(String[] kwNames, Object a, Object b, Object c, Object d) { + return Py.obj(func).callKwF(kwNames, self, a, b, c, d); + } + + @Override + public Object callKwF(String[] kwNames, Object a, Object b, Object c, Object d, Object e) { + return Py.obj(func).callKwF(kwNames, self, a, b, c, d, e); + } + + @Override + public Object callKwF(String[] kwNames, Object a, Object b, Object c, Object d, Object e, Object f) { + return Py.obj(func).callKwF(kwNames, self, a, b, c, d, e, f); + } + + @Override + public Object callKwF(String[] kwNames, Object a, Object b, Object c, Object d, Object e, Object f, Object g) { + return Py.obj(func).callKwF(kwNames, self, a, b, c, d, e, f, g); + } + + @Override + public Object callKwF(String[] kwNames, Object a, Object b, Object c, Object d, Object e, Object f, Object g, Object h) { + return Py.obj(func).callKwF(kwNames, self, a, b, c, d, e, f, g, h); + } + + @Override + public Object callKwF(String[] kwNames, Object a, Object b, Object c, Object d, Object e, Object f, Object g, Object h, Object i) { + return Py.obj(func).callKwF(kwNames, self, a, b, c, d, e, f, g, h, i); + } + + @Override + public Object callKwF(String[] kwNames, Object a, Object b, Object c, Object d, Object e, Object f, Object g, Object h, Object i, Object j) { + return Py.obj(func).callKwF(kwNames, self, a, b, c, d, e, f, g, h, i, j); + } + + @Override + public Object callKwF(String[] kwNames, Object a, Object b, Object c, Object d, Object e, Object f, Object g, Object h, Object i, Object j, Object k) { + return Py.obj(func).callKwF(kwNames, self, a, b, c, d, e, f, g, h, i, j, k); + } + + @Override + public Object callKwF(String[] kwNames, Object a, Object b, Object c, Object d, Object e, Object f, Object g, Object h, Object i, Object j, Object k, Object l) { + return Py.obj(func).callKwF(kwNames, self, a, b, c, d, e, f, g, h, i, j, k, l); + } + + @Override + public Object callKwF(String[] kwNames, Object a, Object b, Object c, Object d, Object e, Object f, Object g, Object h, Object i, Object j, Object k, Object l, Object m) { + return Py.obj(func).callKwF(kwNames, self, a, b, c, d, e, f, g, h, i, j, k, l, m); + } + @Override public Object call(Object[] args, String[] kwNames) { return Py.obj(func).call(Py.prepend(self, args), kwNames); @@ -73,6 +138,46 @@ public Object call5(Object a, Object b, Object c, Object d, Object e) { return Py.obj(func).call6(self, a, b, c, d, e); } + @Override + public Object call6(Object a, Object b, Object c, Object d, Object e, Object f) { + return Py.obj(func).call7(self, a, b, c, d, e, f); + } + + @Override + public Object call7(Object a, Object b, Object c, Object d, Object e, Object f, Object g) { + return Py.obj(func).call8(self, a, b, c, d, e, f, g); + } + + @Override + public Object call8(Object a, Object b, Object c, Object d, Object e, Object f, Object g, Object h) { + return Py.obj(func).call9(self, a, b, c, d, e, f, g, h); + } + + @Override + public Object call9(Object a, Object b, Object c, Object d, Object e, Object f, Object g, Object h, Object i) { + return Py.obj(func).call10(self, a, b, c, d, e, f, g, h, i); + } + + @Override + public Object call10(Object a, Object b, Object c, Object d, Object e, Object f, Object g, Object h, Object i, Object j) { + return Py.obj(func).call11(self, a, b, c, d, e, f, g, h, i, j); + } + + @Override + public Object call11(Object a, Object b, Object c, Object d, Object e, Object f, Object g, Object h, Object i, Object j, Object k) { + return Py.obj(func).call12(self, a, b, c, d, e, f, g, h, i, j, k); + } + + @Override + public Object call12(Object a, Object b, Object c, Object d, Object e, Object f, Object g, Object h, Object i, Object j, Object k, Object l) { + return Py.obj(func).call13(self, a, b, c, d, e, f, g, h, i, j, k, l); + } + + @Override + public Object call13(Object a, Object b, Object c, Object d, Object e, Object f, Object g, Object h, Object i, Object j, Object k, Object l, Object m) { + return Py.obj(func).call14(self, a, b, c, d, e, f, g, h, i, j, k, l, m); + } + @Override public Object getAttrOrNull(String name) { if ("__self__".equals(name)) { diff --git a/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyModule.java b/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyModule.java index ed652258e5b..89d4915a775 100644 --- a/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyModule.java +++ b/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyModule.java @@ -46,11 +46,85 @@ public interface Loader { /// `sys.modules`: every module as it starts loading. A program may read /// and change it, but importing goes by the loaded table alone. static final PyDict SYS_MODULES = new PyDict(); + /// The modules whose bodies are running, innermost last; the main module + /// is not on it, since `load` never runs it. + private static final java.util.ArrayList EXECUTING = new java.util.ArrayList(); public final String name; public final Object[] slots; private final String[] slotNames; + private static final int SCANNED = 6; + private HashMap slotIndex; private Map extra; + /// Bumped on every change to `extra`, so a call site that cached a name + /// stored there can tell its value is still the module's. Names in + /// `slots` need no stamp: a site that cached one re-reads the slot. + int extraStamp; + + /// The loaded module whose translated class is `javaClass` or encloses + /// it (a function body may be a nested or a lambda class), or null. The + /// longest matching module class wins, so `a.b` is never taken for `a`. + static PyModule ofClass(String javaClass) { + int dot = javaClass.lastIndexOf('.'); + String simple = javaClass.substring(dot + 1); + PyModule best = null; + int bestLength = -1; + for (PyModule m : LOADED.values()) { + String c = className(m.name); + if (c.length() > bestLength && (simple.equals(c) || simple.startsWith(c + "$"))) { + best = m; + bestLength = c.length(); + } + } + return best; + } + + /// The module whose body is running innermost -- the main module when no + /// import is under way -- or null. + static PyModule executing() { + String n = EXECUTING.isEmpty() ? "__main__" : EXECUTING.get(EXECUTING.size() - 1); + return LOADED.get(n); + } + + /// The loaded module whose class, or a class nested in it, a native + /// ParparVM stack frame names. Such a frame carries the translated C name, + /// in which every `.` and `$` of the Java name is a `_` + /// (`com_..._py_anyio_2e_core` for `py_anyio$2ecore`), so the module + /// classes are compared in that form, the longest match winning. + static PyModule ofNativeClass(String cName) { + PyModule best = null; + int bestLength = -1; + for (PyModule m : LOADED.values()) { + String c = "_" + className(m.name).replace('$', '_'); + int at = cName.lastIndexOf(c); + while (at >= 0) { + int end = at + c.length(); + if (end == cName.length() || cName.charAt(end) == '_') { + if (c.length() > bestLength) { + best = m; + bestLength = c.length(); + } + break; + } + at = cName.lastIndexOf(c, at - 1); + } + } + return best; + } + + /// `PythonTranspiler.className`, which names a module's class. + private static String className(String module) { + StringBuilder sb = new StringBuilder("py_"); + for (int i = 0; i < module.length(); i++) { + char c = module.charAt(i); + if (c < 128 && (Character.isLetterOrDigit(c) || c == '_')) { + sb.append(c); + } else { + sb.append('$').append(Integer.toHexString(c)); + } + } + return sb.toString(); + } public PyModule(String name, String[] slotNames) { this.name = name; @@ -63,6 +137,35 @@ public static void register(String name, Loader loader) { LOADERS.put(name, loader); } + /// The modules of a generated registry: `exec(i)` runs the body of the + /// i-th name. + public interface Group { + void exec(int index); + } + + /// Registers the modules `names` lists, one a line, as the ones `group` + /// runs by position. Nothing of a module is touched until it is imported: + /// a program is built with every module it could import and imports a + /// fraction of them. + public static void register(String names, final Group group) { + int at = 0; + int index = 0; + while (at <= names.length()) { + int end = names.indexOf('\n', at); + if (end < 0) { + end = names.length(); + } + final int position = index++; + LOADERS.put(names.substring(at, end), new Loader() { + @Override + public void exec(PyModule m) { + group.exec(position); + } + }); + at = end + 1; + } + } + /// Registers an already populated module (runtime-provided modules). public static void registerModule(PyModule m) { LOADED.put(m.name, m); @@ -77,6 +180,15 @@ static PyModule find(String name) { return m; } + /// Whether `name` can be imported: compiled into the program, already + /// loaded, or provided by the runtime itself. + public static boolean available(String name) { + if (LOADED.containsKey(name) || LOADERS.containsKey(name)) { + return true; + } + return StdModules.provide(name) && LOADED.containsKey(name); + } + /// `import name`: runs the module body once, parents first. public static PyModule load(String name) { PyModule m = LOADED.get(name); @@ -101,7 +213,12 @@ public static PyModule load(String name) { } throw Py.error(Py.MODULE_NOT_FOUND_ERROR, "No module named '" + name + "'"); } - l.exec(null); + EXECUTING.add(name); + try { + l.exec(null); + } finally { + EXECUTING.remove(EXECUTING.size() - 1); + } m = LOADED.get(name); if (m == null) { throw Py.error(Py.IMPORT_ERROR, "module '" + name + "' did not initialise"); @@ -130,13 +247,39 @@ public PyType type() { return Py.MODULE_TYPE; } + /// The slot of `n`, or -1 when the name lives in `extra`; for call + /// sites that cache where a name is (`AttrSite`). + int slotIndexOf(String n) { + return slotOf(n); + } + + /// `n` as stored in `extra`, or null. + Object extraOrNull(String n) { + return extra == null ? null : extra.get(n); + } + private int slotOf(String n) { - for (int i = 0; i < slotNames.length; i++) { - if (slotNames[i].equals(n)) { - return i; + if (slotNames.length <= SCANNED) { + for (int i = 0; i < slotNames.length; i++) { + if (slotNames[i].equals(n)) { + return i; + } + } + return -1; + } + // Built by the first read by name: `json.dumps` and every other + // `module.attr` comes here, and a scan compared the name with each + // global of the module in turn. + HashMap ix = slotIndex; + if (ix == null) { + ix = new HashMap(); + for (int i = slotNames.length - 1; i >= 0; i--) { + ix.put(slotNames[i], Integer.valueOf(i)); } + slotIndex = ix; } - return -1; + Integer at = ix.get(n); + return at == null ? -1 : at.intValue(); } /// A global the generated code reads that was never assigned: the @@ -152,6 +295,14 @@ public Object unbound(int slot) { @Override public Object getAttrOrNull(String n) { + Object v = getGlobal(n); + return v != null ? v : moduleGetattr(n); + } + + /// A name the module defines, as its own code reads a global: never + /// through the module's `__getattr__`, which serves only attribute + /// access from outside. + public Object getGlobal(String n) { int s = slotOf(n); if (s >= 0 && slots[s] != null) { return slots[s]; @@ -166,13 +317,34 @@ public Object getAttrOrNull(String n) { return Py.str(name); } if ("__dict__".equals(n)) { - // A snapshot, as globals() is: reading names through it works, - // writing through it does not reach the module. + // As globals(): writes through it reach the module. return globals(); } return null; } + /// PEP 562: a name the module does not define goes to the module's own + /// `__getattr__`, when it has one -- how packages load submodules and + /// exports lazily. Its AttributeError means "no such name". + private Object moduleGetattr(String n) { + if ("__getattr__".equals(n)) { + return null; + } + int s = slotOf("__getattr__"); + Object hook = s >= 0 ? slots[s] : extra == null ? null : extra.get("__getattr__"); + if (hook == null) { + return null; + } + try { + return Py.call(hook, Py.str(n)); + } catch (PyException e) { + if (e.matches(Py.ATTRIBUTE_ERROR)) { + return null; + } + throw e; + } + } + @Override public void setAttr(String n, Object value) { int s = slotOf(n); @@ -184,6 +356,7 @@ public void setAttr(String n, Object value) { extra = new LinkedHashMap(); } extra.put(n, value); + extraStamp++; } @Override @@ -196,11 +369,17 @@ public void delAttr(String n) { if (extra == null || extra.remove(n) == null) { throw Py.attributeError("module '" + name + "' has no attribute '" + n + "'"); } + extraStamp++; } /// `globals()`: a snapshot, since the slots are not a dict. + /// `globals()` (and a module's `__dict__`, and `locals()` at module + /// level): a dict of the module's names whose writes reach the module, + /// so `globals()[name] = value` defines `name` -- the idiom libraries + /// export generated names with. Reads see the names as they were when + /// it was made, plus what was written through it. public PyDict globals() { - PyDict d = new PyDict(); + PyDict d = new Globals(this); d.setItem(Py.str("__name__"), Py.str(name)); for (int i = 0; i < slots.length; i++) { if (slots[i] != null) { @@ -212,13 +391,41 @@ public PyDict globals() { d.setItem(Py.str(e.getKey()), e.getValue()); } } + ((Globals) d).filled = true; return d; } + /// A module's globals dict, writing through to the module. + private static final class Globals extends PyDict { + private final PyModule module; + private boolean filled; + + Globals(PyModule module) { + this.module = module; + } + + @Override + public void setItem(Object key, Object value) { + super.setItem(key, value); + if (filled && key instanceof String) { + module.setAttr(Py.toStr(key), value); + } + } + + @Override + public Object remove(Object key) { + Object v = super.remove(key); + if (v != null && key instanceof String && module.getAttrOrNull(Py.toStr(key)) != null) { + module.delAttr(Py.toStr(key)); + } + return v; + } + } + /// The names `from m import *` copies: `__all__` when defined, else every /// public global. public String[] exportedNames() { - Object all = getAttrOrNull("__all__"); + Object all = getGlobal("__all__"); if (all != null) { Object[] items = Py.toArray(all); String[] r = new String[items.length]; diff --git a/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyObject.java b/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyObject.java index 0d110d70aec..70e97dcde67 100644 --- a/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyObject.java +++ b/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyObject.java @@ -111,28 +111,121 @@ public Object call0() { return call(Py.NO_ARGS, Py.NO_KW); } + // Keyword calls of a fixed arity: `kwNames` names the trailing arguments, + // as in [#call]. The transpiler emits these for every keyword call of at + // most 14 arguments, so the call site builds no argument array; a + // function binds them in locals, anything else gets the array here. + + public Object callKwF(String[] kwNames, Object a) { + return call(ArgArrays.fallback(new Object[] {a}), kwNames); + } + + public Object callKwF(String[] kwNames, Object a, Object b) { + return call(ArgArrays.fallback(new Object[] {a, b}), kwNames); + } + + public Object callKwF(String[] kwNames, Object a, Object b, Object c) { + return call(ArgArrays.fallback(new Object[] {a, b, c}), kwNames); + } + + public Object callKwF(String[] kwNames, Object a, Object b, Object c, Object d) { + return call(ArgArrays.fallback(new Object[] {a, b, c, d}), kwNames); + } + + public Object callKwF(String[] kwNames, Object a, Object b, Object c, Object d, Object e) { + return call(ArgArrays.fallback(new Object[] {a, b, c, d, e}), kwNames); + } + + public Object callKwF(String[] kwNames, Object a, Object b, Object c, Object d, Object e, Object f) { + return call(ArgArrays.fallback(new Object[] {a, b, c, d, e, f}), kwNames); + } + + public Object callKwF(String[] kwNames, Object a, Object b, Object c, Object d, Object e, Object f, Object g) { + return call(ArgArrays.fallback(new Object[] {a, b, c, d, e, f, g}), kwNames); + } + + public Object callKwF(String[] kwNames, Object a, Object b, Object c, Object d, Object e, Object f, Object g, Object h) { + return call(ArgArrays.fallback(new Object[] {a, b, c, d, e, f, g, h}), kwNames); + } + + public Object callKwF(String[] kwNames, Object a, Object b, Object c, Object d, Object e, Object f, Object g, Object h, Object i) { + return call(ArgArrays.fallback(new Object[] {a, b, c, d, e, f, g, h, i}), kwNames); + } + + public Object callKwF(String[] kwNames, Object a, Object b, Object c, Object d, Object e, Object f, Object g, Object h, Object i, Object j) { + return call(ArgArrays.fallback(new Object[] {a, b, c, d, e, f, g, h, i, j}), kwNames); + } + + public Object callKwF(String[] kwNames, Object a, Object b, Object c, Object d, Object e, Object f, Object g, Object h, Object i, Object j, Object k) { + return call(ArgArrays.fallback(new Object[] {a, b, c, d, e, f, g, h, i, j, k}), kwNames); + } + + public Object callKwF(String[] kwNames, Object a, Object b, Object c, Object d, Object e, Object f, Object g, Object h, Object i, Object j, Object k, Object l) { + return call(ArgArrays.fallback(new Object[] {a, b, c, d, e, f, g, h, i, j, k, l}), kwNames); + } + + public Object callKwF(String[] kwNames, Object a, Object b, Object c, Object d, Object e, Object f, Object g, Object h, Object i, Object j, Object k, Object l, Object m) { + return call(ArgArrays.fallback(new Object[] {a, b, c, d, e, f, g, h, i, j, k, l, m}), kwNames); + } + + public Object callKwF(String[] kwNames, Object a, Object b, Object c, Object d, Object e, Object f, Object g, Object h, Object i, Object j, Object k, Object l, Object m, Object n) { + return call(ArgArrays.fallback(new Object[] {a, b, c, d, e, f, g, h, i, j, k, l, m, n}), kwNames); + } + public Object call1(Object a) { - return call(new Object[] {a}, Py.NO_KW); + return call(ArgArrays.fallback(new Object[] {a}), Py.NO_KW); } public Object call2(Object a, Object b) { - return call(new Object[] {a, b}, Py.NO_KW); + return call(ArgArrays.fallback(new Object[] {a, b}), Py.NO_KW); } public Object call3(Object a, Object b, Object c) { - return call(new Object[] {a, b, c}, Py.NO_KW); + return call(ArgArrays.fallback(new Object[] {a, b, c}), Py.NO_KW); } public Object call4(Object a, Object b, Object c, Object d) { - return call(new Object[] {a, b, c, d}, Py.NO_KW); + return call(ArgArrays.fallback(new Object[] {a, b, c, d}), Py.NO_KW); } public Object call5(Object a, Object b, Object c, Object d, Object e) { - return call(new Object[] {a, b, c, d, e}, Py.NO_KW); + return call(ArgArrays.fallback(new Object[] {a, b, c, d, e}), Py.NO_KW); } public Object call6(Object a, Object b, Object c, Object d, Object e, Object f) { - return call(new Object[] {a, b, c, d, e, f}, Py.NO_KW); + return call(ArgArrays.fallback(new Object[] {a, b, c, d, e, f}), Py.NO_KW); + } + + public Object call7(Object a, Object b, Object c, Object d, Object e, Object f, Object g) { + return call(ArgArrays.fallback(new Object[] {a, b, c, d, e, f, g}), Py.NO_KW); + } + + public Object call8(Object a, Object b, Object c, Object d, Object e, Object f, Object g, Object h) { + return call(ArgArrays.fallback(new Object[] {a, b, c, d, e, f, g, h}), Py.NO_KW); + } + + public Object call9(Object a, Object b, Object c, Object d, Object e, Object f, Object g, Object h, Object i) { + return call(ArgArrays.fallback(new Object[] {a, b, c, d, e, f, g, h, i}), Py.NO_KW); + } + + public Object call10(Object a, Object b, Object c, Object d, Object e, Object f, Object g, Object h, Object i, Object j) { + return call(ArgArrays.fallback(new Object[] {a, b, c, d, e, f, g, h, i, j}), Py.NO_KW); + } + + public Object call11(Object a, Object b, Object c, Object d, Object e, Object f, Object g, Object h, Object i, Object j, Object k) { + return call(ArgArrays.fallback(new Object[] {a, b, c, d, e, f, g, h, i, j, k}), Py.NO_KW); + } + + public Object call12(Object a, Object b, Object c, Object d, Object e, Object f, Object g, Object h, Object i, Object j, Object k, Object l) { + return call(ArgArrays.fallback(new Object[] {a, b, c, d, e, f, g, h, i, j, k, l}), Py.NO_KW); + } + + public Object call13(Object a, Object b, Object c, Object d, Object e, Object f, Object g, Object h, Object i, Object j, Object k, Object l, Object m) { + return call(ArgArrays.fallback(new Object[] {a, b, c, d, e, f, g, h, i, j, k, l, m}), Py.NO_KW); + } + + public Object call14(Object a, Object b, Object c, Object d, Object e, Object f, Object g, Object h, Object i, Object j, Object k, Object l, Object m, Object n) { + return call(ArgArrays.fallback(new Object[] {a, b, c, d, e, f, g, h, i, j, k, l, m, n}), Py.NO_KW); } // ---- numbers --------------------------------------------------------- diff --git a/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyObjects.java b/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyObjects.java new file mode 100644 index 00000000000..dc8bfdba0f1 --- /dev/null +++ b/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyObjects.java @@ -0,0 +1,97 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.python.runtime; + +/// `_cn1obj`: an instance made with all of its attributes in one call. +/// +/// `make(cls, "a\nb\nc", va, vb, vc)` (the names one a line) answers what `object.__new__(cls)` +/// followed by `o.a = va; o.b = vb; o.c = vc` does. The standard library +/// builds value objects that way where it has already validated their +/// fields -- datetime above all: a `datetime` sets ten attributes, and set +/// one at a time each store walked a shape transition and grew the slot +/// array, which with the collector it fed was most of +/// `datetime.now(timezone.utc)` (measured against CPython, whose datetime is +/// one C allocation). +/// +/// The names are a constant of the calling module, so the shape they make +/// is looked up by that string's identity. A class whose instances are not +/// plain -- a compiled layout, a builtin base -- gets the attributes stored +/// one by one, through `setattr`, exactly as the Python would. +final class PyObjects { + private static final int CACHE = 16; + private static final String[] KEYS = new String[CACHE]; + private static final Shape[] SHAPES = new Shape[CACHE]; + private static final String[][] NAMES = new String[CACHE][]; + + private PyObjects() { + } + + static PyModule module() { + PyModule m = new PyModule("_cn1obj", new String[0]); + m.setAttr("make", PyBuiltin.positional("make", PyObjects::make)); + return m; + } + + private static Object make(Object[] a) { + if (a.length < 2 || !(a[0] instanceof PyType) || !(a[1] instanceof String)) { + throw Py.error(Py.TYPE_ERROR, "make(cls, names, *values)"); + } + return build((PyType) a[0], (String) a[1], a, 2); + } + + /// The instance of `cls` with the attributes `key` names (one a line) + /// set to `a[from]`, `a[from + 1]` and on. + static PyInstance build(PyType cls, String key, Object[] a, int from) { + int slot = (System.identityHashCode(key) & 0x7fffffff) % CACHE; + if (KEYS[slot] != key) { //NOPMD CompareObjectsWithEquals - the cache is keyed by identity + String[] names = Py.names(key); + Shape s = Shape.EMPTY; + for (int i = 0; i < names.length; i++) { + names[i] = names[i].intern(); + s = s.with(names[i]); + } + NAMES[slot] = names; + SHAPES[slot] = s; + KEYS[slot] = key; + } + String[] names = NAMES[slot]; + int n = names.length; + if (a.length != n + from) { + throw Py.error(Py.TYPE_ERROR, "make() takes " + n + " values, got " + (a.length - from)); + } + PyInstance o = cls.newInstance(); + if (o.getClass() == PyInstance.class && o.base == null && o.shape == null) { //NOPMD CompareObjectsWithEquals - exactly the plain instance class + Object[] slots = new Object[n]; + System.arraycopy(a, from, slots, 0, n); + o.slots = slots; + o.shape = SHAPES[slot]; + o.extra = true; + return o; + } + for (int i = 0; i < n; i++) { + Py.setattr(o, names[i], a[i + from]); + } + return o; + } +} diff --git a/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyPackageData.java b/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyPackageData.java new file mode 100644 index 00000000000..a916a36f521 --- /dev/null +++ b/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyPackageData.java @@ -0,0 +1,176 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.python.runtime; + +import java.io.DataInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/// The data files the application's Python packages ship beside their +/// modules -- a JSON table, a font, a CMap -- read-only under `/cn1python/`, +/// where every module's `__file__` points. +/// +/// The build packs them into one resource at the root of the application, +/// `/cn1python.dat`, because device resources are flat: a package's own +/// directory tree would not survive. The format is a count followed by that +/// many entries, each a UTF path relative to the root, a length and the +/// bytes (`java.io.DataOutputStream`). It is read once, on the first access +/// under the root; an application without package data has no resource and +/// an empty tree. +public final class PyPackageData { + /// Must match `Emitter.PACKAGE_DATA_ROOT`. + public static final String ROOT = "/cn1python/"; + /// The resource the build writes. + public static final String RESOURCE = "/cn1python.dat"; + + private static Map files; + private static Map> dirs; + + private PyPackageData() { + } + + /// Whether `path` is under the package data root. + public static boolean covers(String path) { + return path.startsWith(ROOT) || ROOT.substring(0, ROOT.length() - 1).equals(path); + } + + private static String key(String path) { + String k = path.length() <= ROOT.length() ? "" : path.substring(ROOT.length()); + while (k.endsWith("/")) { + k = k.substring(0, k.length() - 1); + } + return k; + } + + /// The archive is an application resource. In an application it comes from + /// the port's resource lookup: on ParparVM `Class.getResourceAsStream` reads + /// the host file system (a translated command-line program's search path), + /// not the bundle, so a shipped iOS or macOS app never found its own + /// archive and every package that reads a data file failed. A server or a + /// command-line program has no `Display`, and keeps the class lookup. + private static InputStream open() { + java.util.function.Function o = opener; + if (o != null) { + InputStream in = o.apply(RESOURCE); + if (in != null) { + return in; + } + } + return PyPackageData.class.getResourceAsStream(RESOURCE); + } + + /// How a client application opens a resource, installed by Cn1Platform. + /// Not named here: a server's class library has no Display, and naming it + /// in this class stopped a Python command-line tool from compiling. + private static java.util.function.Function opener; + + static void setOpener(java.util.function.Function o) { + opener = o; + } + + private static synchronized void load() { + if (files != null) { + return; + } + Map f = new LinkedHashMap(); + Map> d = new HashMap>(); + d.put("", new ArrayList()); + InputStream in = open(); + if (in != null) { + try (DataInputStream data = new DataInputStream(in)) { + int count = data.readInt(); + for (int i = 0; i < count; i++) { + String path = data.readUTF(); + byte[] bytes = new byte[data.readInt()]; + data.readFully(bytes); + f.put(path, bytes); + } + } catch (IOException e) { + RuntimeException corrupt = Py.error(Py.OS_ERROR, "corrupt " + RESOURCE + ": " + e.getMessage()); + corrupt.initCause(e); + throw corrupt; + } + } + // Indexed outside the try: its implicit catch (Throwable) would cover + // the casts of d.get, which ParparVM does not check. + for (String path : f.keySet()) { + String child = path; + while (true) { + int slash = child.lastIndexOf('/'); + String parent = slash < 0 ? "" : child.substring(0, slash); + String name = child.substring(slash + 1); + List list = d.get(parent); + boolean known = list != null; + if (!known) { + list = new ArrayList(); + d.put(parent, list); + } + if (!list.contains(name)) { + list.add(name); + } + // The root is always listed, so a walk ends there. + if (known) { + break; + } + child = parent; + } + } + dirs = d; + files = f; + } + + /// The bytes of the file at `path`, or null when there is none. + public static byte[] read(String path) { + load(); + return files.get(key(path)); + } + + public static boolean exists(String path) { + load(); + String k = key(path); + return files.containsKey(k) || dirs.containsKey(k); + } + + public static boolean isDirectory(String path) { + load(); + return dirs.containsKey(key(path)); + } + + /// The names in directory `path`, or null when it is not one. + public static String[] list(String path) { + load(); + List l = dirs.get(key(path)); + return l == null ? null : l.toArray(new String[l.size()]); + } + + public static long size(String path) { + byte[] b = read(path); + return b == null ? 0 : b.length; + } +} diff --git a/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyProperty.java b/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyProperty.java index 584dd8b1c4c..a250b73e404 100644 --- a/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyProperty.java +++ b/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyProperty.java @@ -52,21 +52,21 @@ Object get(Object self) { if (fget == null || fget == Py.NONE) { //NOPMD CompareObjectsWithEquals - identity is meant throw Py.attributeError("property has no getter"); } - return Py.obj(fget).call(new Object[] {self}, Py.NO_KW); + return Py.obj(fget).call1(self); } void delete(Object self) { if (fdel == null || fdel == Py.NONE) { //NOPMD CompareObjectsWithEquals - identity is meant throw Py.attributeError("property has no deleter"); } - Py.obj(fdel).call(new Object[] {self}, Py.NO_KW); + Py.obj(fdel).call1(self); } void set(Object self, Object value) { if (fset == null || fset == Py.NONE) { //NOPMD CompareObjectsWithEquals - identity is meant throw Py.attributeError("property has no setter"); } - Py.obj(fset).call(new Object[] {self, value}, Py.NO_KW); + Py.obj(fset).call2(self, value); } @Override diff --git a/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyRange.java b/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyRange.java index a2d9aafbe69..b0dfa480a72 100644 --- a/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyRange.java +++ b/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyRange.java @@ -112,18 +112,43 @@ public boolean isTrue() { @Override public Object iter() { - final long n = length(); - return new PyJavaIter(new PyJavaIter.Source() { - long i; - - @Override - public Object next() { - if (i >= n) { - return null; - } - return PyInt.of(start + step * i++); + return new Iter(start, step, length()); + } + + /// The range's own iterator: one final class whose next() is the counter itself. + /// It was a PyJavaIter over an anonymous Source -- two virtual calls and a done + /// flag per value, in the most common loop a Python program writes. + static final class Iter extends PyObject { + private long cur; + private final long step; + private long left; + + Iter(long start, long step, long n) { + this.cur = start; + this.step = step; + this.left = n; + } + + @Override + public PyType type() { + return Py.ITERATOR_TYPE; + } + + @Override + public Object iter() { + return this; + } + + @Override + public Object next() { + if (left <= 0) { + return null; } - }); + left--; + long v = cur; + cur = v + step; + return PyInt.of(v); + } } @Override @@ -133,6 +158,9 @@ public Object getItem(Object key) { int[] r = ((PySlice) key).indices((int) n); return new PyRange(start + r[0] * step, start + r[1] * step, step * r[2]); } + if (key instanceof PyInt && ((PyInt) key).big != null) { + throw Py.indexError("range object index out of range"); + } long i = Py.index(key); if (i < 0) { i += n; @@ -145,10 +173,12 @@ public Object getItem(Object key) { @Override public boolean contains(Object x) { - if (!(Py.isInt(x)) || Py.intView(x).isBig()) { + // A Long is read directly (intView allocates above its cache); a bool, a + // big int or anything else takes the general path. + if (!(x instanceof Long)) { return super.contains(x); } - long v = Py.intView(x).value; + long v = ((Long) x).longValue(); if (step > 0 ? v < start || v >= stop : v > start || v <= stop) { return false; } diff --git a/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyServer.java b/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyServer.java index 980dc502826..2b7d7d119cf 100644 --- a/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyServer.java +++ b/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyServer.java @@ -96,21 +96,21 @@ public interface WebSocketSink { public static Object openWebSocket(Object webSockets, String target, String[] headers, final WebSocketSink sink) { Object[] req = request("GET", target, headers, null); - PyBuiltin send = PyBuiltin.positional("send", a -> { - String kind = Py.toStr(a[0]); + PyBuiltin send = PyBuiltin.fixed3("send", (a0, a1, a2) -> { + String kind = Py.toStr(a0); if ("accept".equals(kind)) { - sink.accept(a[1] == Py.NONE ? null : Py.toStr(a[1]), strings(a[2])); //NOPMD CompareObjectsWithEquals - identity is meant + sink.accept(a1 == Py.NONE ? null : Py.toStr(a1), strings(a2)); //NOPMD CompareObjectsWithEquals - identity is meant } else if ("text".equals(kind)) { - sink.text(Py.toStr(a[1])); + sink.text(Py.toStr(a1)); } else if ("bytes".equals(kind)) { - sink.binary(PyBytes.like(a[1])); + sink.binary(PyBytes.like(a1)); } else if ("deny".equals(kind)) { - Object detail = a[2]; + Object detail = a2; Object[] parts = detail instanceof PyList ? ((PyList) detail).toArray() : null; - sink.deny((int) Py.asLong(a[1]), parts == null ? new String[0] : strings(parts[0]), + sink.deny((int) Py.asLong(a1), parts == null ? new String[0] : strings(parts[0]), parts == null ? new byte[0] : PyBytes.like(parts[1])); } else { - sink.close((int) Py.asLong(a[1]), a[2] == Py.NONE ? "" : Py.toStr(a[2])); //NOPMD CompareObjectsWithEquals - identity is meant + sink.close((int) Py.asLong(a1), a2 == Py.NONE ? "" : Py.toStr(a2)); //NOPMD CompareObjectsWithEquals - identity is meant } return Py.NONE; }); @@ -171,7 +171,7 @@ public static Object[] request(String method, String target, String[] headers, b String query = q < 0 ? "" : target.substring(q + 1); PyList hs = new PyList(headers.length / 2); for (int i = 0; i + 1 < headers.length; i += 2) { - hs.append(new PyTuple(new Object[] {headers[i], headers[i + 1]})); + hs.append(Py.tuple(headers[i], headers[i + 1])); } return new Object[] {method, path, query, hs, new PyBytes(body == null ? new byte[0] : body)}; } @@ -195,7 +195,7 @@ private static Response call0(Object dispatch, Object[] request) { Object after = t.size() == 4 && t.get(3) != Py.NONE ? t.get(3) : null; //NOPMD CompareObjectsWithEquals - identity is meant Object hl = t.get(1); Object[] pairs = hl instanceof PyList ? ((PyList) hl).toArray() - : hl instanceof PyTuple ? ((PyTuple) hl).items : null; + : hl instanceof PyTuple ? ((PyTuple) hl).arr() : null; if (pairs == null) { throw Py.typeError("dispatch headers must be a list of (name, value) pairs"); } diff --git a/maven/python-runtime/src/main/java/com/codename1/python/runtime/PySet.java b/maven/python-runtime/src/main/java/com/codename1/python/runtime/PySet.java index e23e4743808..2f9cb4d88b0 100644 --- a/maven/python-runtime/src/main/java/com/codename1/python/runtime/PySet.java +++ b/maven/python-runtime/src/main/java/com/codename1/python/runtime/PySet.java @@ -43,8 +43,8 @@ public PyType type() { }; final boolean frozen; - private Object[] keys = new Object[MINSIZE]; - private long[] hashes = new long[MINSIZE]; + private Object[] keys; + private long[] hashes; private int mask = MINSIZE - 1; /// Active plus dummy entries. private int fill; @@ -55,13 +55,34 @@ public PyType type() { public PySet(boolean frozen) { this.frozen = frozen; + keys = new Object[MINSIZE]; + hashes = new long[MINSIZE]; } public PySet() { this(false); } + /// A copy of `src`'s table, for [#of] where [#merge] would build that + /// same table: nothing allocated but the two copies. + private PySet(boolean frozen, PySet src) { + this.frozen = frozen; + keys = src.keys.clone(); + hashes = src.hashes.clone(); + fill = src.used; + used = src.used; + } + public static PySet of(Object iterable, boolean frozen) { + if (iterable instanceof PySet) { + PySet o = (PySet) iterable; + // merge into a fresh table copies slot for slot exactly when + // the source is minimal, has no dummies and needs no resize; + // markdownify copies its parent tags so for every tag. + if (o.mask == MINSIZE - 1 && o.fill == o.used && (long) o.used * 5 < (long) o.mask * 3) { + return new PySet(frozen, o); + } + } PySet s = new PySet(frozen); s.update(iterable); return s; @@ -287,7 +308,30 @@ void update(Object iterable) { } return; } + if (iterable instanceof PyList && iterable.getClass() == PyList.class) { //NOPMD CompareObjectsWithEquals - exactly list: a subclass may override __iter__ + // set(names) over a plain list, sqlite-utils' check of every + // query's columns: indexed, as the list's own iterator reads it + // (live, so an __eq__ that changes the list ends it the same way). + PyList l = (PyList) iterable; + for (int i = 0; i < l.size(); i++) { + Object v = l.get(i); + insert(v, hashOf(v)); + } + return; + } Object it = Py.iter(iterable); + if (it instanceof PyGenerator) { + // Stepped under one handler (see PyList.extend). + PyGenerator g = (PyGenerator) it; + try { + for (Object v = PyGenerator.loopNext(g); v != null; v = PyGenerator.loopNext(g)) { + insert(v, hashOf(v)); + } + } catch (Throwable e) { + throw PyGenerator.loopEscape(g, e); + } + return; + } for (Object v = Py.next(it); v != null; v = Py.next(it)) { insert(v, hashOf(v)); } @@ -308,6 +352,16 @@ public static PySet ofConstants(Object... items) { return s; } + /// The frozenset constant CPython folds `x in {"a", "b"}` to; the + /// transpiler makes it once per module. + public static PySet frozenConstants(Object... items) { + PySet s = new PySet(true); + for (Object item : items) { + s.addRaw(item); + } + return s; + } + private void merge(PySet other) { if (other == this || other.used == 0) { //NOPMD CompareObjectsWithEquals - identity is meant return; diff --git a/maven/python-runtime/src/main/java/com/codename1/python/runtime/PySlice.java b/maven/python-runtime/src/main/java/com/codename1/python/runtime/PySlice.java index 4df657f0a80..01d6e5adc97 100644 --- a/maven/python-runtime/src/main/java/com/codename1/python/runtime/PySlice.java +++ b/maven/python-runtime/src/main/java/com/codename1/python/runtime/PySlice.java @@ -49,11 +49,11 @@ public int[] indices(int length) { int lo; int hi; if (st > 0) { - lo = start == Py.NONE ? 0 : clamp(Py.index(start), length, 0, length); //NOPMD CompareObjectsWithEquals - identity is meant - hi = stop == Py.NONE ? length : clamp(Py.index(stop), length, 0, length); //NOPMD CompareObjectsWithEquals - identity is meant + lo = start == Py.NONE ? 0 : clamp(edge(start), length, 0, length); //NOPMD CompareObjectsWithEquals - identity is meant + hi = stop == Py.NONE ? length : clamp(edge(stop), length, 0, length); //NOPMD CompareObjectsWithEquals - identity is meant } else { - lo = start == Py.NONE ? length - 1 : clamp(Py.index(start), length, -1, length - 1); //NOPMD CompareObjectsWithEquals - identity is meant - hi = stop == Py.NONE ? -1 : clamp(Py.index(stop), length, -1, length - 1); //NOPMD CompareObjectsWithEquals - identity is meant + lo = start == Py.NONE ? length - 1 : clamp(edge(start), length, -1, length - 1); //NOPMD CompareObjectsWithEquals - identity is meant + hi = stop == Py.NONE ? -1 : clamp(edge(stop), length, -1, length - 1); //NOPMD CompareObjectsWithEquals - identity is meant } return new int[] {lo, hi, st}; } @@ -70,17 +70,17 @@ static int step(Object step) { /// The first index a slice selects, as in [#indices(int)]. static int lower(Object start, Object stop, int st, int length) { if (st > 0) { - return start == Py.NONE ? 0 : clamp(Py.index(start), length, 0, length); //NOPMD CompareObjectsWithEquals - identity is meant + return start == Py.NONE ? 0 : clamp(edge(start), length, 0, length); //NOPMD CompareObjectsWithEquals - identity is meant } - return start == Py.NONE ? length - 1 : clamp(Py.index(start), length, -1, length - 1); //NOPMD CompareObjectsWithEquals - identity is meant + return start == Py.NONE ? length - 1 : clamp(edge(start), length, -1, length - 1); //NOPMD CompareObjectsWithEquals - identity is meant } /// The bound a slice stops at, as in [#indices(int)]. static int upper(Object stop, int st, int length) { if (st > 0) { - return stop == Py.NONE ? length : clamp(Py.index(stop), length, 0, length); //NOPMD CompareObjectsWithEquals - identity is meant + return stop == Py.NONE ? length : clamp(edge(stop), length, 0, length); //NOPMD CompareObjectsWithEquals - identity is meant } - return stop == Py.NONE ? -1 : clamp(Py.index(stop), length, -1, length - 1); //NOPMD CompareObjectsWithEquals - identity is meant + return stop == Py.NONE ? -1 : clamp(edge(stop), length, -1, length - 1); //NOPMD CompareObjectsWithEquals - identity is meant } /// The number of indices from `lo` towards `hi` by `st`. @@ -91,6 +91,16 @@ static int count(int lo, int hi, int st) { return lo > hi ? (lo - hi - st - 1) / -st : 0; } + /// A start or stop as a `long`. One no `long` holds is beyond either end + /// of any sequence, which is all a slice asks of it; the stand-in leaves + /// room for the length that `clamp` adds to a negative one. + private static long edge(Object o) { + if (o instanceof PyInt && ((PyInt) o).big != null) { + return ((PyInt) o).big.signum() < 0 ? Long.MIN_VALUE / 2 : Long.MAX_VALUE / 2; + } + return Py.index(o); + } + private static int clamp(long v, int length, int min, int max) { if (v < 0) { v += length; @@ -133,7 +143,7 @@ public Object getAttrOrNull(String name) { throw Py.valueError("length should not be negative"); } int[] r = indices((int) n); - return new PyTuple(new Object[] {Py.of((long) r[0]), Py.of((long) r[1]), Py.of((long) r[2])}); + return Py.tuple(Py.of((long) r[0]), Py.of((long) r[1]), Py.of((long) r[2])); }); } return super.getAttrOrNull(name); diff --git a/maven/python-runtime/src/main/java/com/codename1/python/runtime/PySql.java b/maven/python-runtime/src/main/java/com/codename1/python/runtime/PySql.java index ea0662a4a38..d144c91f444 100644 --- a/maven/python-runtime/src/main/java/com/codename1/python/runtime/PySql.java +++ b/maven/python-runtime/src/main/java/com/codename1/python/runtime/PySql.java @@ -23,6 +23,8 @@ */ package com.codename1.python.runtime; +import java.util.function.Function; + import java.io.IOException; import java.util.ArrayList; import java.util.List; @@ -66,6 +68,90 @@ public abstract static class Connection { /// filled for an `INSERT`, `UPDATE`, `DELETE` or `REPLACE`. public abstract Result run(String sql, Object[] params, boolean query) throws IOException; + /// How many SQL functions are running a statement of their own, + /// one inside another: what a statement run at that depth may reuse + /// is its own. Python runs one thread at a time, so this is static. + static int nesting; + + private String statusMessage; + + /// [#run(String, Object[], boolean)] for a caller on a hot path: the + /// result, or null when the statement failed, the reason then being + /// [#statusMessage()]. A port whose engine reports a status overrides + /// it to run with no exception handler on the way; this one wraps + /// the throwing method. + public Result runStatus(String sql, Object[] params, boolean query) { + try { + return run(sql, params, query); + } catch (IOException e) { + return failStatus(e.getMessage()); + } + } + + /// Why the last [#runStatus(String, Object[], boolean)] answered null. + public String statusMessage() { + return statusMessage; + } + + /// Records why a statement failed, for [#statusMessage()]; answers null. + protected final Result failStatus(String message) { + statusMessage = String.valueOf(message); + return null; + } + + /// The row lists of this connection's cursors that still have rows to + /// read, by identity, while [#holdRead(boolean)] is on for them. + private Object[] pending = new Object[4]; + private int pendingCount; + + /// A cursor was handed `rows`, one or more: while it works + /// through them the connection may keep its read lock (see + /// [#holdRead(boolean)]), as CPython's does under a pending statement. + public final void pending(Object rows) { + for (int i = 0; i < pendingCount; i++) { + if (pending[i] == rows) { //NOPMD CompareObjectsWithEquals - identity is meant + return; + } + } + if (pendingCount == pending.length) { + // A cursor left part read never says it is done: the oldest + // slot is most likely one, and goes, so it is not kept alive. + System.arraycopy(pending, 1, pending, 0, pendingCount - 1); + pendingCount--; + } + pending[pendingCount++] = rows; + // Every time, not only on the first: the engine lets go by itself + // before a statement the lock would be in the way of. + holdRead(true); + } + + /// The cursor that was handed `rows` read the last of them, or moved on. + public final void drained(Object rows) { + for (int i = 0; i < pendingCount; i++) { + if (pending[i] == rows) { //NOPMD CompareObjectsWithEquals - identity is meant + pending[i] = pending[--pendingCount]; + pending[pendingCount] = null; + if (pendingCount == 0) { + holdRead(false); + } + return; + } + } + } + + /// Whether any cursor's rows are pending: the caller skips the lookup + /// when none are. + public final boolean anyPending() { + return pendingCount > 0; + } + + /// Keeps the engine's read lock between statements, or lets it go. Only + /// ever a saving -- the rows are read already -- so an engine with no + /// such lock, or no way to keep it, leaves this as it is. + protected void holdRead(boolean on) { + // Nothing to keep by default. + } + public abstract void begin() throws IOException; public abstract void commit() throws IOException; @@ -73,12 +159,20 @@ public abstract static class Connection { public abstract void rollback() throws IOException; public abstract void close() throws IOException; + + /// Registers the scalar SQL function `name` of `nargs` arguments (-1 + /// for any number); a later registration of the same name and count + /// replaces it. Answers false where the engine cannot call back into + /// the application, which is the default. + public boolean createFunction(String name, int nargs, Function body) throws IOException { + return false; + } } /// What a statement produced. Values are null, `Long`, `Double`, /// `String` or `byte[]`, as SQLite stored them. public static final class Result { - public String[] columns = new String[0]; + public String[] columns = NO_COLUMNS; public final List rows = new ArrayList(); public long changes = -1; public long lastRowId = -1; @@ -87,6 +181,17 @@ public static final class Result { /// "datetime", "datetimetz" or "time" -- or null; null altogether when /// the engine reports none (SQLite). public String[] types; + + /// Empties it for another statement, keeping the row list's storage. + public void clear() { + columns = NO_COLUMNS; + rows.clear(); + changes = -1; + lastRowId = -1; + types = null; + } + + private static final String[] NO_COLUMNS = new String[0]; } /// The value a SQLite engine that cannot report storage classes most diff --git a/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyStaticMethod.java b/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyStaticMethod.java index 197c3afeda5..b339626c3c5 100644 --- a/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyStaticMethod.java +++ b/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyStaticMethod.java @@ -46,6 +46,16 @@ public Object call(Object[] args, String[] kwNames) { return Py.obj(func).call(args, kwNames); } + @Override + public Object call1(Object a) { + return Py.obj(func).call1(a); + } + + @Override + public Object call2(Object a, Object b) { + return Py.obj(func).call2(a, b); + } + @Override public Object getAttrOrNull(String attr) { if ("__func__".equals(attr) || "__wrapped__".equals(attr)) { diff --git a/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyStr.java b/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyStr.java index e47410f08cc..51d9d64862e 100644 --- a/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyStr.java +++ b/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyStr.java @@ -58,13 +58,16 @@ public PyType type() { return Py.STR_TYPE; } - /// The last long string whose surrogates were counted. Indexing a long - /// string in a loop would otherwise rescan it on every access; one entry - /// covers that loop. The holder is immutable, so a reader on another - /// thread sees either the old pair or the new one, never a mix. + /// A long string's surrogate pair count, cached so that indexing or + /// slicing it in a loop does not rescan it on every access. The holder + /// is immutable, so a reader on another thread sees either the old entry + /// or the new one, never a mix. private static final class Count { final String s; final int n; + /// The UTF-16 offsets at which the pairs start, ascending; built the + /// first time the string is indexed by code point. + int[] at; Count(String s, int n) { this.s = s; @@ -72,34 +75,87 @@ private static final class Count { } } - private static Count lastCount = new Count("", 0); - - /// High surrogates in `s`: zero for every string without a supplementary - /// character. + /// Direct mapped by identity hash. A parser works on several long + /// strings at once -- its buffer, the text a match holds, the slice it + /// is building -- and a cache of one or two entries evicted one of them + /// on every access, which still cost MarkItDown a tenth of its time. + /// + /// Two tables, by length: the many short slices a parser makes must not + /// evict the page it is walking, whose rescan is what costs. And the slot + /// is the identity hash MIXED: on ParparVM it is the object's address, + /// whose low bits are allocation alignment, so masking it directly put + /// every string in a few slots and the page was rescanned on every + /// regex call. + private static final Count[] COUNTS = new Count[256]; + private static final Count[] LONG_COUNTS = new Count[64]; + private static final int LONG = 1024; + /// Strings up to this long are counted, never cached: a Latin-1 one -- + /// nearly all of them -- answers from its storage flag, and any other is + /// one vector scan, cheaper than hashing its identity into a table. Kept + /// short: a 256-char table of non-Latin-1 text indexed per character + /// (pdfminer's PDFDocEncoding[o]) was a full scan per index. + private static final int SHORT = 32; + + private static int slot(String s, int size) { + int h = System.identityHashCode(s); + h ^= (h >>> 16); + h *= 0x45d9f3b; + h ^= (h >>> 16); + return h & (size - 1); + } + + /// Surrogate pairs in `s`, each one code point of two chars: zero for + /// every string without a supplementary character. A lone surrogate is + /// not a pair; it is one char and one code point. static int surrogates(String s) { int len = s.length(); - if (len > 32) { - Count c = lastCount; - if (c.s == s) { //NOPMD CompareObjectsWithEquals - identity is meant - return c.n; - } - } - int n = 0; - for (int i = 0; i < len; i++) { - char c = s.charAt(i); - if (c >= '\uD800' && c <= '\uDBFF') { - n++; - } + if (len <= SHORT) { + // codePointCount counts a pair as one code point, as scan does, and + // answers a Latin-1 string -- nearly every short one -- from its + // storage without reading a char, on ParparVM and on a JDK alike. + return len - s.codePointCount(0, len); } - if (len > 32) { - lastCount = new Count(s, n); + Count[] table = len >= LONG ? LONG_COUNTS : COUNTS; + int slot = slot(s, table.length); + Count c = table[slot]; + if (c != null && c.s == s) { //NOPMD CompareObjectsWithEquals - identity is meant + return c.n; } + int n = len - s.codePointCount(0, len); + table[slot] = new Count(s, n); return n; } + /// The pair count of `s` if the cache holds it, else -1. Never scans: + /// for `len`, where a miss costs the same scan a lookup would have + /// saved and a Latin-1 string answers without one. + static int cachedSurrogates(String s) { + int len = s.length(); + if (len <= SHORT) { + return -1; + } + Count[] table = len >= LONG ? LONG_COUNTS : COUNTS; + Count c = table[slot(s, table.length)]; + return c != null && c.s == s ? c.n : -1; //NOPMD CompareObjectsWithEquals - identity is meant + } + + /// Records the pair count of `s` that its maker already knows (a + /// decoder), so `len` and indexing do not scan for it. + static void knownSurrogates(String s, int n) { + int len = s.length(); + if (len > SHORT) { + Count[] table = len >= LONG ? LONG_COUNTS : COUNTS; + table[slot(s, table.length)] = new Count(s, n); + } + } + /// Length in code points; a lone surrogate counts as one, as in Python. + /// The pair count of the last long string is kept, so indexing or slicing + /// one in a loop does not rescan it each time: `html.parser` walks a + /// page that way, and a page with one non-Latin-1 character went + /// quadratic through `String.codePointCount`. public static int codePoints(String s) { - return s.codePointCount(0, s.length()); + return s.length() - surrogates(s); } public int codePoints() { @@ -111,11 +167,59 @@ static int offset(String s, int cp) { if (surrogates(s) == 0) { return cp; } - int off = 0; - for (int i = 0; i < cp; i++) { - off += pairAt(s, off) ? 2 : 1; + int[] at = pairOffsets(s); + if (at.length == 0) { + int off = 0; + for (int i = 0; i < cp; i++) { + off += pairAt(s, off) ? 2 : 1; + } + return off; + } + // Pair k starts at code point at[k] - k, a strictly increasing + // sequence; the offset is cp plus the pairs that start before it. + int lo = 0; + int hi = at.length; + while (lo < hi) { + int mid = (lo + hi) >>> 1; + if (at[mid] - mid < cp) { + lo = mid + 1; + } else { + hi = mid; + } + } + return cp + lo; + } + + /// The pair offsets of a cached string, or an empty array for a short + /// one, which is walked instead (a string with pairs has at least one). Walking a long one per index made every loop over + /// it quadratic: bs4 compiles a pattern of all 2,000 HTML entities, a + /// few of them outside the BMP, and `re._parser` reads it one character + /// at a time -- 120 ms of a cold page conversion. + private static final int[] NO_PAIRS = new int[0]; + + private static int[] pairOffsets(String s) { + int len = s.length(); + if (len <= SHORT) { + return NO_PAIRS; + } + Count[] table = len >= LONG ? LONG_COUNTS : COUNTS; + Count c = table[slot(s, table.length)]; + if (c == null || c.s != s) { //NOPMD CompareObjectsWithEquals - identity is meant + return NO_PAIRS; + } + int[] at = c.at; + if (at == null) { + at = new int[c.n]; + int k = 0; + for (int i = 0; i + 1 < len && k < at.length; i++) { + if (pairAt(s, i)) { + at[k++] = i; + i++; + } + } + c.at = at; } - return off; + return at; } /// Whether a surrogate pair, one code point, starts at offset `i`; a @@ -134,13 +238,29 @@ static int cpIndex(String s, int off) { if (surrogates(s) == 0) { return off; } - int cp = 0; - for (int i = 0; i < off; i++) { - if (i == 0 || !pairAt(s, i - 1)) { - cp++; + int[] at = pairOffsets(s); + if (at.length == 0) { + int cp = 0; + for (int i = 0; i < off; i++) { + if (i == 0 || !pairAt(s, i - 1)) { + cp++; + } } + return cp; } - return cp; + // Every pair whose low half lies before `off` was one code point + // of two chars. + int lo = 0; + int hi = at.length; + while (lo < hi) { + int mid = (lo + hi) >>> 1; + if (at[mid] + 1 < off) { + lo = mid + 1; + } else { + hi = mid; + } + } + return off - lo; } int cpIndex(int off) { @@ -187,9 +307,26 @@ public String repr() { /// quote and no double quote. public static String repr(String s) { char q = s.indexOf('\'') >= 0 && s.indexOf('"') < 0 ? '"' : '\''; - StringBuilder sb = new StringBuilder(s.length() + 2); - sb.append(q); - for (int i = 0; i < s.length(); i++) { + final int len = s.length(); + int i = plainRun(s, 0, len, q); + String qs = q == '"' ? "\"" : "'"; + if (i == len) { + // Nothing to escape, the usual case: one concatenation. + return qs + s + qs; + } + // Plain text is copied a run at a time: each append is a call that + // takes the builder's lock. + StringBuilder sb = new StringBuilder(len + 8); + sb.append(q).append(s, 0, i); + for (; i < len; i++) { + int run = plainRun(s, i, len, q); + if (run > i) { + sb.append(s, i, run); + i = run; + if (i == len) { + break; + } + } char c = s.charAt(i); if (c == q || c == '\\') { sb.append('\\').append(c); @@ -207,6 +344,19 @@ public static String repr(String s) { // A lone surrogate is not printable. sb.append('\\').append('u'); hex(sb, c, 4); + } else if (c > 0xff) { + int cp = pairAt(s, i) ? Character.codePointAt(s, i) : c; + int n = Character.charCount(cp); + if (printable(cp)) { + sb.append(s, i, i + n); + } else if (cp < 0x10000) { + sb.append('\\').append('u'); + hex(sb, cp, 4); + } else { + sb.append('\\').append('U'); + hex(sb, cp, 8); + } + i += n - 1; } else { sb.append(c); } @@ -215,12 +365,47 @@ public static String repr(String s) { return sb.toString(); } + /// The end of the run from `i` that repr() copies as it is: printable + /// ASCII other than the quote and backslash, and printable Latin-1. + private static int plainRun(String s, int i, int len, char q) { + while (i < len) { + char c = s.charAt(i); + if (c >= 0x20 && c < 0x7f ? c == q || c == '\\' : c <= 0xa0 || c > 0xff || c == 0xad) { + return i; + } + i++; + } + return len; + } + + /// str.isprintable() for one code point: the C0 and C1 controls, DEL, + /// NBSP and the soft hyphen are not; above Latin-1, separators, + /// controls, format characters, private use and unassigned code points + /// are escaped by repr(). + static boolean isPrintable(int cp) { + if (cp < 0x20 || cp >= 0x7f && cp <= 0xa0 || cp == 0xad) { + return false; + } + return cp <= 0xff || printable(cp); + } + + /// From CPython's own tables (`UnicodeTables.PRINTABLE`): the device's + /// java.lang.Character has no categories above Latin-1, so asking it + /// escaped every emoji and CJK character in repr() on iOS. + private static boolean printable(int cp) { + return Unicode.printable(cp); + } + static void hex(StringBuilder sb, int v, int digits) { - String h = Integer.toHexString(v); - for (int i = h.length(); i < digits; i++) { - sb.append('0'); + // Digit by digit: this runs once per byte of every bytes.hex() and hexdigest(), + // and a string per byte was the largest source of character arrays in a run. + int n = 1; + while (n < 8 && v >>> (4 * n) != 0) { + n++; + } + for (int i = Math.max(n, digits) - 1; i >= 0; i--) { + sb.append(i >= 8 ? '0' : "0123456789abcdef".charAt(v >>> (4 * i) & 15)); } - sb.append(h); } @Override @@ -338,7 +523,7 @@ public Object getItem(Object key) { } return sb.toString(); } - long i = Py.index(key); + long i = Py.subscript(key); if (i < 0) { i += n; } diff --git a/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyStruct.java b/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyStruct.java new file mode 100644 index 00000000000..104c4f2ec6d --- /dev/null +++ b/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyStruct.java @@ -0,0 +1,191 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.python.runtime; + +/// `_cn1struct`: packing and unpacking for the bundled `struct`, which +/// CPython does in C. The Python module parses the format and raises every +/// error; a call here answers `None` whenever the Python code has to run -- +/// a value out of range, a buffer that is not bytes, a half float -- so it +/// never decides an error itself. +final class PyStruct { + private PyStruct() { + } + + /// One parsed format: per item its code, offset and size. + static final class Plan extends PyObject { + final char[] codes; + final int[] offs; + final int[] sizes; + final boolean little; + + Plan(String codes, Object offs, Object sizes, boolean little) { + this.codes = codes.toCharArray(); + int n = this.codes.length; + this.offs = new int[n]; + this.sizes = new int[n]; + for (int k = 0; k < n; k++) { + this.offs[k] = (int) Py.asLong(Py.getitem(offs, Long.valueOf(k))); + this.sizes[k] = (int) Py.asLong(Py.getitem(sizes, Long.valueOf(k))); + } + this.little = little; + } + + @Override + public PyType type() { + return Py.OBJECT_TYPE; + } + } + + static PyModule module() { + PyModule m = new PyModule("_cn1struct", new String[0]); + m.setAttr("plan", PyBuiltin.positional("plan", + a -> new Plan(Typed.asStr(a[0]), a[1], a[2], Py.isTrue(a[3])))); + m.setAttr("unpack", PyBuiltin.fixed3("unpack", (a0, a1, a2) -> unpack(a0, a1, (int) Py.asLong(a2)))); + m.setAttr("pack", PyBuiltin.fixed3("pack", (a0, a1, a2) -> pack(a0, (int) Py.asLong(a1), a2))); + return m; + } + + private static boolean signed(char c) { + return c == 'b' || c == 'h' || c == 'i' || c == 'l' || c == 'q' || c == 'n'; + } + + private static boolean integer(char c) { + return "bBhHiIlLqQnNP".indexOf(c) >= 0; + } + + private static long read(byte[] b, int o, int size, boolean little) { + long v = 0; + if (little) { + for (int k = size - 1; k >= 0; k--) { + v = v << 8 | b[o + k] & 0xff; + } + } else { + for (int k = 0; k < size; k++) { + v = v << 8 | b[o + k] & 0xff; + } + } + return v; + } + + private static void write(byte[] b, int o, int size, boolean little, long v) { + for (int k = 0; k < size; k++) { + int at = little ? o + k : o + size - 1 - k; + b[at] = (byte) (v >>> (8 * k)); + } + } + + static Object unpack(Object planObj, Object buf, int offset) { + if (!(planObj instanceof Plan) || offset < 0) { + return Py.NONE; + } + Plan p = (Plan) planObj; + byte[] b; + if (buf instanceof PyBytes) { + b = ((PyBytes) buf).value; + } else if (buf instanceof PyByteArray) { + b = ((PyByteArray) buf).buf; + } else { + return Py.NONE; + } + int n = p.codes.length; + Object[] out = new Object[n]; + for (int k = 0; k < n; k++) { + char c = p.codes[k]; + int o = offset + p.offs[k]; + int size = p.sizes[k]; + if (integer(c)) { + long v = read(b, o, size, p.little); + if (size < 8 && signed(c)) { + int shift = 64 - 8 * size; + v = v << shift >> shift; + } else if (size == 8 && !signed(c) && v < 0) { + return Py.NONE; + } + out[k] = Long.valueOf(v); + } else if (c == '?') { + out[k] = b[o] != 0 ? Py.TRUE : Py.FALSE; + } else if (c == 'd') { + out[k] = Double.valueOf(Double.longBitsToDouble(read(b, o, 8, p.little))); + } else if (c == 'f') { + out[k] = Double.valueOf(Float.intBitsToFloat((int) read(b, o, 4, p.little))); + } else if (c == 'c' || c == 's') { + out[k] = new PyBytes(java.util.Arrays.copyOfRange(b, o, o + size)); + } else { + return Py.NONE; + } + } + return new PyTuple(out); + } + + static Object pack(Object planObj, int total, Object args) { + if (!(planObj instanceof Plan) || !(args instanceof PyTuple)) { + return Py.NONE; + } + Plan p = (Plan) planObj; + PyTuple t = (PyTuple) args; + int n = p.codes.length; + if (t.size() != n) { + return Py.NONE; + } + byte[] out = new byte[total]; + for (int k = 0; k < n; k++) { + char c = p.codes[k]; + int o = p.offs[k]; + int size = p.sizes[k]; + Object v = t.get(k); + if (integer(c)) { + if (!(v instanceof Long)) { + return Py.NONE; + } + long x = ((Long) v).longValue(); + boolean s = signed(c); + if (size < 8) { + long lo = s ? -(1L << (8 * size - 1)) : 0; + long hi = s ? (1L << (8 * size - 1)) - 1 : (1L << (8 * size)) - 1; + if (x < lo || x > hi) { + return Py.NONE; + } + } else if (!s && x < 0) { + return Py.NONE; + } + write(out, o, size, p.little, x); + } else if (c == 'd' && v instanceof Double) { + write(out, o, 8, p.little, Double.doubleToRawLongBits(((Double) v).doubleValue())); + } else if (c == 'f' && v instanceof Double) { + double d = ((Double) v).doubleValue(); + float f = (float) d; + if (Float.isInfinite(f) && !Double.isInfinite(d)) { + return Py.NONE; + } + write(out, o, 4, p.little, Float.floatToRawIntBits(f) & 0xFFFFFFFFL); + } else if (c == 's' && v instanceof PyBytes) { + byte[] src = ((PyBytes) v).value; + System.arraycopy(src, 0, out, o, Math.min(src.length, size)); + } else { + return Py.NONE; + } + } + return new PyBytes(out); + } +} diff --git a/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyStructSeq.java b/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyStructSeq.java new file mode 100644 index 00000000000..57febdc76b0 --- /dev/null +++ b/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyStructSeq.java @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.python.runtime; + +/// A tuple whose items also answer to names, as CPython's struct sequences +/// do (`sys.version_info.major`). It is a tuple in every other respect. +final class PyStructSeq extends PyTuple { + private final String[] names; + + PyStructSeq(String[] names, Object... items) { + super(items); + this.names = names; + } + + @Override + public Object getAttrOrNull(String name) { + for (int i = 0; i < names.length; i++) { + if (names[i].equals(name)) { + return get(i); + } + } + return super.getAttrOrNull(name); + } +} diff --git a/maven/python-runtime/src/main/java/com/codename1/python/runtime/PySuper.java b/maven/python-runtime/src/main/java/com/codename1/python/runtime/PySuper.java index e69f814d926..c149b512c8a 100644 --- a/maven/python-runtime/src/main/java/com/codename1/python/runtime/PySuper.java +++ b/maven/python-runtime/src/main/java/com/codename1/python/runtime/PySuper.java @@ -44,6 +44,16 @@ public PyType type() { @Override public Object getAttrOrNull(String name) { PyType start = self instanceof PyType && ((PyType) self).isSubtype(cls) ? (PyType) self : Py.typeOf(self); + switch (name) { + case "__thisclass__": + return cls; + case "__self__": + return self; + case "__self_class__": + return start; + default: + break; + } PyType[] mro = start.mro; int i = 0; while (i < mro.length && mro[i] != cls) { //NOPMD CompareObjectsWithEquals - identity is meant diff --git a/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyTuple.java b/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyTuple.java index b4fe03489a1..a78790461a8 100644 --- a/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyTuple.java +++ b/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyTuple.java @@ -24,54 +24,64 @@ package com.codename1.python.runtime; /// Python's `tuple`. -public final class PyTuple extends PyObject { +public class PyTuple extends PyObject { public static final PyTuple EMPTY = new PyTuple(new Object[0]); - final Object[] items; + /// The items; null in a fixed-size tuple ([T2] to [T6]) until [#arr] + /// is first asked for them. + Object[] elems; /// Wraps `items` without copying; the caller must not keep mutating it. public PyTuple(Object[] items) { - this.items = items; + this.elems = items; } public static PyTuple of(Object... items) { return items.length == 0 ? EMPTY : new PyTuple(items); } + /// The items as an array, which the caller must not change. A + /// fixed-size tuple makes it on the first call; hot paths read + /// [#get] and [#size] instead. + Object[] arr() { + return elems; + } + @Override public PyType type() { return Py.TUPLE_TYPE; } public Object get(int i) { - return items[i]; + return elems[i]; } public int size() { - return items.length; + return elems.length; } @Override public int len() { - return items.length; + return size(); } @Override public boolean isTrue() { - return items.length != 0; + return size() != 0; } @Override public String repr() { - if (items.length == 1) { - return "(" + Py.toRepr(items[0]) + ",)"; + if (size() == 1) { + return "(" + Py.toRepr(get(0)) + ",)"; } - return Py.joinRepr("(", items, items.length, ")"); + Object[] a = arr(); + return Py.joinRepr("(", a, a.length, ")"); } @Override public long hash() { - return Hashing.ofTuple(items); + return Hashing.ofTuple(this); } @Override @@ -79,8 +89,19 @@ public Object eq(Object o) { if (!(o instanceof PyTuple)) { return null; } - Object[] b = ((PyTuple) o).items; - return Py.bool(Py.seqEquals(items, items.length, b, b.length)); + PyTuple t = (PyTuple) o; + int n = size(); + if (t.size() != n) { + return Py.FALSE; + } + for (int i = 0; i < n; i++) { + Object x = get(i); + Object y = t.get(i); + if (x != y && !Py.eqBool(x, y)) { //NOPMD CompareObjectsWithEquals - identity is meant + return Py.FALSE; + } + } + return Py.TRUE; } @Override @@ -104,8 +125,9 @@ public Object ge(Object o) { } private int cmp(Object o) { - Object[] b = ((PyTuple) o).items; - return Py.seqCompare(items, items.length, b, b.length); + Object[] a = arr(); + Object[] b = ((PyTuple) o).arr(); + return Py.seqCompare(a, a.length, b, b.length); } @Override @@ -113,10 +135,11 @@ public Object add(Object o) { if (!(o instanceof PyTuple)) { return null; } - Object[] b = ((PyTuple) o).items; - Object[] r = new Object[items.length + b.length]; - System.arraycopy(items, 0, r, 0, items.length); - System.arraycopy(b, 0, r, items.length, b.length); + Object[] a = arr(); + Object[] b = ((PyTuple) o).arr(); + Object[] r = new Object[a.length + b.length]; + System.arraycopy(a, 0, r, 0, a.length); + System.arraycopy(b, 0, r, a.length, b.length); return new PyTuple(r); } @@ -125,10 +148,11 @@ public Object mul(Object o) { if (!(Py.isInt(o))) { return null; } + Object[] a = arr(); long n = Math.max(0, Py.asLong(o)); - Object[] r = new Object[(int) (items.length * n)]; + Object[] r = new Object[(int) (a.length * n)]; for (int i = 0; i < n; i++) { - System.arraycopy(items, 0, r, i * items.length, items.length); + System.arraycopy(a, 0, r, i * a.length, a.length); } return new PyTuple(r); } @@ -140,32 +164,288 @@ public Object rmul(Object o) { @Override public Object getItem(Object key) { + int n = size(); if (key instanceof PySlice) { - int[] r = ((PySlice) key).indices(items.length); - int n = PySlice.length(r); - Object[] out = new Object[n]; - for (int i = 0, j = r[0]; i < n; i++, j += r[2]) { - out[i] = items[j]; + Object[] a = arr(); + int[] r = ((PySlice) key).indices(n); + int m = PySlice.length(r); + Object[] out = new Object[m]; + if (r[2] == 1) { + // A plain slice is one block copy, not a checked store per element. + System.arraycopy(a, r[0], out, 0, m); + return new PyTuple(out); + } + for (int i = 0, j = r[0]; i < m; i++, j += r[2]) { + out[i] = a[j]; } return new PyTuple(out); } - long i = Py.index(key); + long i = Py.subscript(key); if (i < 0) { - i += items.length; + i += n; } - if (i < 0 || i >= items.length) { + if (i < 0 || i >= n) { throw Py.indexError("tuple index out of range"); } - return items[(int) i]; + return get((int) i); + } + + /// By index, identity first as CPython's tuple compares: the inherited + /// loop made an iterator and a `next` call per item for every `x in t`. + @Override + public boolean contains(Object x) { + int n = size(); + for (int i = 0; i < n; i++) { + Object v = get(i); + if (v == x || Py.eqBool(v, x)) { //NOPMD CompareObjectsWithEquals - identity is meant + return true; + } + } + return false; } @Override public Object iter() { - return new PyIter(items.length) { + return new PyIter(size()) { @Override Object at(int i) { - return items[i]; + return get(i); } }; } + + /// A tuple of 2 held in fields: one object where a wrapped array is two. + static final class T2 extends PyTuple { + private final Object a; + private final Object b; + + T2(Object a, Object b) { + super(null); + this.a = a; + this.b = b; + } + + @Override + public Object get(int i) { + switch (i) { + case 0: + return a; + case 1: + return b; + default: + throw new ArrayIndexOutOfBoundsException(i); + } + } + + @Override + public int size() { + return 2; + } + + @Override + Object[] arr() { + Object[] r = elems; + if (r == null) { + r = new Object[] {a, b}; + elems = r; + } + return r; + } + } + + /// A tuple of 3 held in fields: one object where a wrapped array is two. + static final class T3 extends PyTuple { + private final Object a; + private final Object b; + private final Object c; + + T3(Object a, Object b, Object c) { + super(null); + this.a = a; + this.b = b; + this.c = c; + } + + @Override + public Object get(int i) { + switch (i) { + case 0: + return a; + case 1: + return b; + case 2: + return c; + default: + throw new ArrayIndexOutOfBoundsException(i); + } + } + + @Override + public int size() { + return 3; + } + + @Override + Object[] arr() { + Object[] r = elems; + if (r == null) { + r = new Object[] {a, b, c}; + elems = r; + } + return r; + } + } + + /// A tuple of 4 held in fields: one object where a wrapped array is two. + static final class T4 extends PyTuple { + private final Object a; + private final Object b; + private final Object c; + private final Object d; + + T4(Object a, Object b, Object c, Object d) { + super(null); + this.a = a; + this.b = b; + this.c = c; + this.d = d; + } + + @Override + public Object get(int i) { + switch (i) { + case 0: + return a; + case 1: + return b; + case 2: + return c; + case 3: + return d; + default: + throw new ArrayIndexOutOfBoundsException(i); + } + } + + @Override + public int size() { + return 4; + } + + @Override + Object[] arr() { + Object[] r = elems; + if (r == null) { + r = new Object[] {a, b, c, d}; + elems = r; + } + return r; + } + } + + /// A tuple of 5 held in fields: one object where a wrapped array is two. + static final class T5 extends PyTuple { + private final Object a; + private final Object b; + private final Object c; + private final Object d; + private final Object e; + + T5(Object a, Object b, Object c, Object d, Object e) { + super(null); + this.a = a; + this.b = b; + this.c = c; + this.d = d; + this.e = e; + } + + @Override + public Object get(int i) { + switch (i) { + case 0: + return a; + case 1: + return b; + case 2: + return c; + case 3: + return d; + case 4: + return e; + default: + throw new ArrayIndexOutOfBoundsException(i); + } + } + + @Override + public int size() { + return 5; + } + + @Override + Object[] arr() { + Object[] r = elems; + if (r == null) { + r = new Object[] {a, b, c, d, e}; + elems = r; + } + return r; + } + } + + /// A tuple of 6 held in fields: one object where a wrapped array is two. + static final class T6 extends PyTuple { + private final Object a; + private final Object b; + private final Object c; + private final Object d; + private final Object e; + private final Object f; + + T6(Object a, Object b, Object c, Object d, Object e, Object f) { + super(null); + this.a = a; + this.b = b; + this.c = c; + this.d = d; + this.e = e; + this.f = f; + } + + @Override + public Object get(int i) { + switch (i) { + case 0: + return a; + case 1: + return b; + case 2: + return c; + case 3: + return d; + case 4: + return e; + case 5: + return f; + default: + throw new ArrayIndexOutOfBoundsException(i); + } + } + + @Override + public int size() { + return 6; + } + + @Override + Object[] arr() { + Object[] r = elems; + if (r == null) { + r = new Object[] {a, b, c, d, e, f}; + elems = r; + } + return r; + } + } } diff --git a/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyType.java b/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyType.java index c1d9561157e..462e209e7ed 100644 --- a/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyType.java +++ b/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyType.java @@ -24,6 +24,7 @@ package com.codename1.python.runtime; import java.util.ArrayList; +import java.util.Arrays; import java.util.LinkedHashMap; import java.util.HashSet; import java.util.List; @@ -50,6 +51,11 @@ interface Unary { Object create(Object x); } + /// [Unary] for two positional arguments: `int(s, 16)`, `str(b, "utf-8")`. + interface Binary { + Object create(Object x, Object y); + } + public String name; public final PyType[] bases; final PyType[] mro; @@ -73,12 +79,29 @@ public PyType type() { return Py.OBJECT_TYPE; } }; + private boolean plainException; + private int plainExceptionVersion = -1; + + /// Whether constructing this exception type from a message only makes an + /// instance and sets `args`: BaseException's `__new__` and `__init__` + /// both apply. `Py.error` builds those without the call protocol. + boolean plainException() { + if (plainExceptionVersion != version) { + plainException = factory == null && isSubtype(Py.BASE_EXCEPTION) + && lookup("__new__") == Builtins.BASE_EXCEPTION_NEW //NOPMD CompareObjectsWithEquals - identity is meant + && lookup("__init__") == Builtins.BASE_EXCEPTION_INIT; //NOPMD CompareObjectsWithEquals - identity is meant + plainExceptionVersion = version; + } + return plainException; + } + private Map lookupCache; private int lookupVersion = -1; Factory factory; /// Set only on the builtin type itself, never inherited: a subclass of /// `str` constructs through `__new__`/`__init__` as usual. Unary unary; + Binary binary; /// The builtin type whose storage instances of this class extend, or `null`. final PyType solidBase; /// The class's metaclass: `type`, or a subclass of it (null while `type` @@ -88,6 +111,27 @@ public PyType type() { /// The direct subclasses, for `type.__subclasses__()`; null until one exists. private List subclasses; + /// `abc` state of a class whose metaclass is [Abc#META]: the classes + /// `register` made virtual subclasses, and the abstract names that make + /// constructing it a TypeError (null when there are none). + List abcRegistry; + String[] abstractNames; + + /// The direct subclasses, never null. + List subclassList() { + return subclasses == null ? java.util.Collections.emptyList() : subclasses; + } + + /// A number of its own, for the hashed caches of the store sites + /// ([StoreSite]). Python code runs on one thread at a time. + final int id = nextTypeId(); + + private static int typeIds; + + private static int nextTypeId() { + return ++typeIds; + } + PyType(String name, PyType[] bases, Factory factory) { this.name = name; this.bases = bases; @@ -117,6 +161,10 @@ public interface Layout { } private Layout layout; + /// The compiled class whose layout a class built at run time borrows + /// (see [#borrowLayout]), or null. + private PyType layoutFrom; + private boolean layoutDecided; private String[] compiledMethods; private String[] layoutFields; /// Set once a method the generated code calls directly may no longer be @@ -140,18 +188,247 @@ public PyType layout(Layout l, String[] methods, String[] fields) { return this; } + /// Set for a frozen dataclass: generated code stores none of its fields + /// directly (the transpiler gives it a layout only then), so the + /// `__setattr__` and `__delattr__` the decorator adds after the class is + /// built decide every store, as in CPython. + private boolean storesThroughSetattr; + + public PyType storesThroughSetattr() { + storesThroughSetattr = true; + return this; + } + + /// The compiled class after the builtin base of a class confirmed by + /// [#builtinBased], or null. + private PyType compiledParent; + + /// Whether a compiled class whose first base is the builtin type + /// `builtin` (`class NavigableString(str, PageElement)`) may take its + /// layout, with `parent` (or null) its one other base and its compiled + /// parent: the MRO is this class, the builtin, then the parent's chain, + /// so a name the builtin binds comes before the chain's. Typed code + /// resolves every name in the chain, so none of its names may be one + /// the builtin binds. + public boolean builtinBased(PyType builtin, PyType parent) { + if (bases.length == 0 || bases[0] != builtin || solidBase != builtin //NOPMD CompareObjectsWithEquals - identity is meant + || customMeta()) { + return false; + } + int seen = 0; + for (int i = 1; i < bases.length; i++) { + if (bases[i] == parent) { //NOPMD CompareObjectsWithEquals - identity is meant + seen++; + } else if (!fieldlessGeneric(bases[i])) { + return false; + } + } + if (parent == null) { + return true; + } + if (seen != 1 || !parent.hasLayout()) { + return false; + } + // Below an enum, EnumType copies these from the nearest enum (or the + // mixin, for __hash__) onto the class when it is made (enum._finish), + // so the builtin's own never answers for them. The compiler exempts + // the same names (Layouts.ENUM_COPIED); the metaclass is not set on + // this class yet, so the parent says whether EnumType makes it. + boolean enumCopies = EnumMeta.governs(parent); + for (PyType m : parent.mro) { + if (m == Py.OBJECT_TYPE) { //NOPMD CompareObjectsWithEquals - identity is meant + continue; + } + for (String k : m.dict.keySet()) { + if (builtin.dict.containsKey(k) && !CLASS_METADATA.contains(k) + && !(enumCopies && ENUM_COPIED.contains(k))) { + return false; + } + } + } + compiledParent = parent; + return true; + } + + /// Whether a compiled class deriving from builtin exceptions may take + /// its layout: its bases are still `parent` (when not null, a compiled + /// class with its layout) followed by the builtin exception types named + /// `builtins`, in that order. An exception instance is a plain + /// [PyInstance] whose `args` and the rest live in its attribute table, + /// so the layout needs nothing of the builtins but that they are the + /// builtins: `except` and `isinstance` walk the type's own MRO, which + /// keeps every one of them. + public boolean exceptionBased(PyType parent, String[] builtins) { + int off = parent != null ? 1 : 0; + if (customMeta() || bases.length != off + builtins.length) { + return false; + } + if (parent != null && (bases[0] != parent || !parent.hasLayout())) { //NOPMD CompareObjectsWithEquals - identity is meant + return false; + } + for (int i = 0; i < builtins.length; i++) { + PyType b = bases[off + i]; + if (!Py.EXCEPTION_TYPES.contains(b) || !b.name.equals(builtins[i])) { + return false; + } + } + return true; + } + + /// Whether `t` is `typing.Generic`, compiled with no field: as a base + /// it gives an instance nothing. + private static boolean fieldlessGeneric(PyType t) { + return "Generic".equals(t.name) && t.layout != null && (t.layoutFields == null || t.layoutFields.length == 0); + } + + /// Names every class body binds, which say nothing of its instances. + private static final Set CLASS_METADATA = new HashSet(Arrays.asList( + "__module__", "__qualname__", "__doc__", "__dict__", "__weakref__", "__annotations__", + "__firstlineno__", "__static_attributes__", "__slots__", "__orig_bases__", "__parameters__")); + + /// The names `enum._finish` sets on every class EnumType makes. + private static final Set ENUM_COPIED = new HashSet(Arrays.asList( + "__repr__", "__str__", "__format__", "__hash__")); + /// The compiled class this one's layout extends, or null. private PyType layoutParent() { - return bases.length == 1 && bases[0].layout != null ? bases[0] : null; + if (layoutFrom != null) { + return layoutFrom; + } + if (compiledParent != null) { + return compiledParent; + } + // neutralExtraBases recorded the compiled parent when it was not + // the first base; otherwise that is the first base. + return bases.length >= 1 && bases[0].layout != null ? bases[0] : null; + } + + /// Whether a compiled class with bases besides its compiled parent + /// (`parent`, or null when it has none) may take its layout: the MRO + /// is this class, then `parent`'s MRO but `object`, then the rest, and + /// nothing in the rest -- `typing.Generic`, a method-only mixin -- + /// has a field or a builtin base, hooks attribute access, declares + /// slots, binds `__init__` or `__new__` or a special method typed code + /// acts on, or binds a name that is one of the layout's `fields`. Every + /// field and compiled method then resolves in the compiled chain first, + /// as typed code assumes. pdfminer's `LTContainer(LTComponent, + /// Generic[T])` and `LTChar(LTComponent, LTText)`, and every class + /// below them, had plain instances without this. + public boolean neutralExtraBases(PyType parent, String[] fields) { + PyType[] chain = parent != null ? parent.mro : new PyType[0]; + // The compiled parent may be any base, not only the first: a + // method-only mixin listed before it (pptx's + // `LayoutPlaceholder(_InheritsDimensions, Shape)`) is judged below + // like every other class outside the compiled chain, and the + // compiler resolved its methods through this same MRO. + if (parent != null && (!isBase(parent) || !parent.hasLayout())) { + return false; + } + // The compiled chain keeps its order in this MRO, though C3 may put + // a class of an extra base between two of its classes (a diamond). + int prev = 0; + for (PyType c : chain) { + int at = indexIn(mro, c); + if (at <= prev) { + return false; + } + prev = at; + } + for (int i = 1; i < mro.length; i++) { + PyType m = mro[i]; + if (m == Py.OBJECT_TYPE || indexIn(chain, m) >= 0) { //NOPMD CompareObjectsWithEquals - identity is meant + continue; + } + if (Py.EXCEPTION_TYPES.contains(m) && exceptionChain(chain)) { + // A builtin exception beside a chain over one: an exception + // instance keeps its state in its attribute table whatever + // its builtin, so it adds nothing to the layout + // (Layouts.mergeExtrasOrdered admits the same). + continue; + } + if (m.solidBase != null) { + return false; + } + // A compiled extra base's fields are copied into this layout. + if (m.layout != null && m.layoutFields != null) { + for (String f : m.layoutFields) { + if (!contains(fields, f)) { + return false; + } + } + } + for (Map.Entry e : m.dict.entrySet()) { + String k = e.getKey(); + Object v = e.getValue(); + if ("__setattr__".equals(k) || "__getattribute__".equals(k) || "__delattr__".equals(k) + || "__getattr__".equals(k) || "__slots__".equals(k) && !emptySlots(v) || contains(fields, k)) { + return false; + } + if (CLASS_METADATA.contains(k)) { + continue; + } + // A name a class before this one in the MRO binds never + // reaches it. Otherwise construction must not run it, and + // a special method typed code acts on is taken only from a + // compiled class, whose names the subclass's typed code + // already resolves through the MRO (Layouts.mergeExtras). + boolean shadowed = false; + for (int j = 0; j < i && !shadowed; j++) { + shadowed = mro[j].dict.containsKey(k); + } + // A compiled extra base's __init__ is allowed: the compiler + // (Layouts.mergeExtrasOrdered) binds no def of its own for + // it, so construction runs the MRO's, as here. + if (!shadowed && ("__init__".equals(k) && v instanceof PyFunction && !Abc.isAbstract(v) && m.layout == null + || "__new__".equals(k) || specialMethod(k, v) && m.layout == null && !Abc.isAbstract(v))) { + return false; + } + } + } + if (parent != null) { + compiledParent = parent; + } + return true; + } + + /// Whether a builtin exception type is in `chain`. + private static boolean exceptionChain(PyType[] chain) { + for (PyType c : chain) { + if (Py.EXCEPTION_TYPES.contains(c)) { + return true; + } + } + return false; + } + + private boolean isBase(PyType t) { + for (PyType b : bases) { + if (b == t) { //NOPMD CompareObjectsWithEquals - identity is meant + return true; + } + } + return false; + } + + private static int indexIn(PyType[] a, PyType t) { + for (int i = 0; i < a.length; i++) { + if (a[i] == t) { //NOPMD CompareObjectsWithEquals - identity is meant + return i; + } + } + return -1; } /// Whether the class has a compiled layout. public boolean hasLayout() { - return layout != null; + return layout != null && layoutFrom == null; } /// A new, uninitialised instance. public PyInstance newInstance() { + if (!layoutDecided && layout == null) { + borrowLayout(); + } PyInstance o = layout != null ? layout.create(this) : new PyInstance(this); if (solidBase != null && BuiltinSubclass.mutable(solidBase)) { // Filled by the builtin's __init__ (or the subclass's, through super()). @@ -160,15 +437,151 @@ public PyInstance newInstance() { return o; } + /// Lets a class built at run time -- a subclass in another module of a + /// class the transpiler compiled -- make its instances with that class's + /// layout, so the compiled methods it inherits read their fields as + /// fields. Without it every one of pdfminer's parsers, all subclasses of + /// `psparser.PSBaseParser` defined in other modules, ran the compiled + /// tokenizer on a plain instance, every field through a megamorphic + /// site. Decided at the first instance, when the class namespace is + /// complete, and only when nothing in the MRO outside the compiled + /// chain can change what a field read or store means: no attribute + /// hooks or `__slots__`, and nothing but a function or a constant bound + /// to a field's name, and no method that overrides a compiled one or is + /// a special method (see the loop); later changes go through + /// [#changed] as for a compiled class. + private void borrowLayout() { + layoutDecided = true; + if (solidBase != null || customMeta() && !EnumMeta.governs(this)) { + return; + } + PyType a = null; + for (int i = 1; i < mro.length && a == null; i++) { + if (mro[i].layout != null && mro[i].layoutFrom == null) { + a = mro[i]; + } + } + if (a == null) { + return; + } + boolean beforeA = true; + boolean overrides = false; + for (PyType m : mro) { + if (m == a) { //NOPMD CompareObjectsWithEquals - identity is meant + beforeA = false; + } + if (m == Py.OBJECT_TYPE || m.layout != null && m.layoutFrom == null && a.isSubtype(m)) { //NOPMD CompareObjectsWithEquals - identity is meant + continue; + } + for (Map.Entry e : m.dict.entrySet()) { + String k = e.getKey(); + if ("__setattr__".equals(k) || "__getattribute__".equals(k) || "__delattr__".equals(k) + || "__slots__".equals(k) && !emptySlots(e.getValue())) { + return; + } + if (fieldOf(a, k) && !plainClassValue(e.getValue())) { + return; + } + if (beforeA && specialMethod(k, e.getValue())) { + // Typed code assumes the compiled class's comparison and + // truth; a special method the compiled class lacks, or + // overrides, would be skipped without a word. Such a + // class keeps ordinary instances, which no typed entry + // admits, so every operation goes the generic way. + return; + } + // An override of a compiled method is honoured instead: the + // class is marked patched, so every compiled call of a method + // -- the generic dispatch (`m_`), a typed method's bridge + // (`pt_`) and its virtual slot (`tv_`) -- asks the class + // first and goes the generic way, which finds the override. + // `label()` of the base calling `self.kind()` must answer the + // subclass's kind. The fields stay compiled: bs4's + // BeautifulSoupHTMLParser overrides the handle_* hooks of + // HTMLParser, whose tokenizer it runs millions of times. + overrides |= beforeA && methodOf(a, k); + } + } + layout = a.layout; + layoutFrom = a; + patched |= overrides; + LAYOUTS.add(this); + } + + /// A special method other than `__init__` that typed code may act on + /// in place of calling it: comparison, truth, hashing, length, + /// iteration, operators. The ones it never acts on -- it reaches them + /// through the generic dispatch, which finds an override -- are left + /// out (`NEUTRAL_SPECIALS`): `__repr__` on pdfminer's LTChar and + /// `__getstate__` on bs4's BeautifulSoup kept both on plain instances. + private static boolean specialMethod(String name, Object v) { + return v instanceof PyFunction && name.startsWith("__") && name.endsWith("__") && !"__init__".equals(name) + && !NEUTRAL_SPECIALS.contains(name); + } + + private static final Set NEUTRAL_SPECIALS = new HashSet(); + + static { + String[] n = {"__repr__", "__str__", "__format__", "__getstate__", "__setstate__", "__reduce__", + "__reduce_ex__", "__copy__", "__deepcopy__", "__init_subclass__", "__class_getitem__", "__sizeof__", + "__dir__", "__enter__", "__exit__"}; + for (String s : n) { + NEUTRAL_SPECIALS.add(s); + } + } + + /// `__slots__ = ()`, as `typing.Generic` declares: no slot descriptor. + private static boolean emptySlots(Object v) { + return v instanceof PyTuple && ((PyTuple) v).size() == 0; + } + + private static boolean fieldOf(PyType a, String name) { + for (PyType u = a; u != null; u = u.layoutParent()) { + if (contains(u.layoutFields, name)) { + return true; + } + } + return false; + } + + private static boolean methodOf(PyType a, String name) { + for (PyType u = a; u != null; u = u.layoutParent()) { + if (contains(u.compiledMethods, name)) { + return true; + } + } + return false; + } + + /// A class attribute that is not a descriptor: an instance attribute of + /// the same name, which a field holds, takes precedence over it. + private static boolean plainClassValue(Object v) { + return v == null || v == Py.NONE || v instanceof PyFunction || v instanceof String || v instanceof Long //NOPMD CompareObjectsWithEquals - identity is meant + || v instanceof Double || v instanceof Boolean || v instanceof PyTuple || v instanceof PyStr; + } + /// Invalidates direct calls to `attr` and refuses what a compiled field /// cannot honour, once the class namespace of `this` changes. + /// Set for good once anything writes or deletes an attribute of this + /// compiled class, or of a class above it, after the class was built. + /// Generated code folds a class constant only while this is clear: the + /// transpiler proves over the whole program that no instance ever holds + /// the name, and this answers for the class objects, which a computed + /// `setattr(cls, k, v)` can reach without the build telling which. + public boolean classWritten; + private void changed(String attr, Object value) { for (int i = 0; i < LAYOUTS.size(); i++) { //NOPMD ForLoopCanBeForeach - indexed: a for-each allocates an iterator PyType t = LAYOUTS.get(i); if (!t.isSubtype(this)) { continue; } - if ("__setattr__".equals(attr) || "__getattribute__".equals(attr) || "__delattr__".equals(attr) + t.classWritten = true; + boolean hooks = "__setattr__".equals(attr) || "__delattr__".equals(attr); + if (hooks && t.storesThroughSetattr) { + continue; + } + if (hooks || "__getattribute__".equals(attr) || value instanceof PyProperty && contains(t.layoutFields, attr)) { // Generated code stores and reads the fields of these // instances directly. The transpiler leaves a field to the @@ -251,11 +664,11 @@ static Object[] mroEntries(Object[] bases) { out.add(bases[j]); } } - Object entries = Py.obj(hook).call(new Object[] {PyTuple.of(bases)}, Py.NO_KW); + Object entries = Py.obj(hook).call1(PyTuple.of(bases)); if (!(entries instanceof PyTuple)) { throw Py.typeError("__mro_entries__ must return a tuple"); } - Object[] items = ((PyTuple) entries).items; + Object[] items = ((PyTuple) entries).arr(); for (Object item : items) { if (!out.contains(item)) { out.add(item); @@ -274,6 +687,22 @@ static Object[] mroEntries(Object[] bases) { /// The only attributes an instance may hold, when every class in the /// MRO declares `__slots__` and none of them names `__dict__`; null when /// instances have a `__dict__`. + private Object newAttrHook; + private boolean newAttrHookKnown; + + /// `__cn1_new_attr__(self, name, value)` of the class, asked before an + /// instance gains an attribute it has never had; it answers true when it + /// kept the value itself. What a bundled library binds in place of a + /// `__setattr__` that only polices new names (pydantic's BaseModel): a + /// class binding `__setattr__` has no layout. Read once per class. + Object newAttrHook() { + if (!newAttrHookKnown) { + newAttrHook = lookup("__cn1_new_attr__"); + newAttrHookKnown = true; + } + return newAttrHook; + } + Set slotNames() { if (!slotsKnown) { slotNames = computeSlots(); @@ -321,7 +750,9 @@ public PyType type() { /// Whether the metaclass is a class the application defines. private boolean customMeta() { - return meta != null && meta != Py.TYPE_TYPE; //NOPMD CompareObjectsWithEquals - identity is meant + // abc's ABCMeta is done by the runtime (Abc), so its classes keep the + // fast construction paths, which check abstractNames themselves. + return meta != null && meta != Py.TYPE_TYPE && meta != Abc.META; //NOPMD CompareObjectsWithEquals - identity is meant } /// The metaclass's own dunder `name`, or null when the metaclass is @@ -337,22 +768,94 @@ private Object metaDunder(String name) { /// `isinstance(o, this)`, through the metaclass's `__instancecheck__` /// when it defines one (what `abc.ABCMeta` registration needs). boolean instanceCheck(Object o) { + if (protocolState() != PROTO_NONE) { + return protocolCheck(o, Py.typeOf(o).isSubtype(this)); + } if (Py.typeOf(o).isSubtype(this)) { return true; } + if (Abc.governs(this)) { + return Abc.subclassCheck(this, Py.typeOf(o)); + } Object m = metaDunder("__instancecheck__"); - return m != null && Py.isTrue(Py.obj(m).call(new Object[] {this, o}, Py.NO_KW)); + return m != null && Py.isTrue(Py.obj(m).call2(this, o)); } /// `issubclass(c, this)`, through the metaclass's `__subclasscheck__`. boolean subclassCheck(PyType c) { + if (protocolState() != PROTO_NONE) { + String data = protocolState() == PROTO_RUNTIME && !c.isSubtype(this) ? protocolData() : null; + if (data != null) { + throw Py.typeError("Protocols with non-method members don't support issubclass(). " + + "Non-method members: " + data + "."); + } + return protocolCheck(c, c.isSubtype(this)); + } + if (Abc.governs(this)) { + return Abc.subclassCheck(this, c); + } Object m = metaDunder("__subclasscheck__"); if (m != null) { - return Py.isTrue(Py.obj(m).call(new Object[] {this, c}, Py.NO_KW)); + return Py.isTrue(Py.obj(m).call2(this, c)); } return c.isSubtype(this); } + private static final int PROTO_NONE = 0; + private static final int PROTO_RUNTIME = 1; + private static final int PROTO_STATIC = 2; + + /// The protocol state of this class and the class version it was read + /// at: `typing.runtime_checkable` marks a class after it is built. + private int protoState; + private int protoAt = -1; + + /// Whether this class is a `typing.Protocol` of its own (`_is_protocol` + /// in its own namespace, as CPython keeps it), and whether it is + /// runtime checkable. A protocol the transpiler wrote no structural + /// check for (ProtocolChecks) is held nominally. + private int protocolState() { + if (protoAt != version) { + Object p = dict.get("_is_protocol"); + int st = PROTO_NONE; + if (p != null && Py.isTrue(p) && dict.get("__cn1_protocol_check__") != null) { + Object r = dict.get("_is_runtime_protocol"); + st = r != null && Py.isTrue(r) ? PROTO_RUNTIME : PROTO_STATIC; + } + protoState = st; + protoAt = version; + } + return protoState; + } + + /// `isinstance`/`issubclass` against a protocol: CPython refuses one + /// that is not runtime checkable before anything else, then accepts a + /// nominal subclass, then checks the members by their literal names + /// through the check the transpiler generated for the class body. + private boolean protocolCheck(Object o, boolean nominal) { + if (protocolState() == PROTO_STATIC) { + throw Py.typeError("Instance and class checks can only be used with @runtime_checkable protocols"); + } + if (nominal) { + return true; + } + return Py.isTrue(Py.call(getAttr("__cn1_protocol_check__"), o)); + } + + /// The quoted names of the non-method members this protocol and those + /// above it declare, or null when there are none. + private String protocolData() { + StringBuilder b = null; + for (PyType t : mro) { + Object d = t.dict.get("__cn1_protocol_data__"); + if (d != null) { + b = b == null ? new StringBuilder() : b.append(", "); + b.append(Py.toStr(d)); + } + } + return b == null ? null : b.toString(); + } + // ---- class creation ---------------------------------------------------- /// Class namespaces handed to a metaclass whose class object already @@ -415,7 +918,76 @@ public static Object finish(PyType k, String[] kwNames, Object[] kwValues) { k.created(kn, kv); return k; } - return callMeta(w, k, kn, kv); + if (w == Abc.META) { //NOPMD CompareObjectsWithEquals - identity is meant + // What ABCMeta.__new__ did, without a reflective metaclass call: + // type.__new__ (created), then the abstract names. + k.meta = w; + k.created(kn, kv); + Abc.init(k); + return k; + } + if (w == EnumMeta.META) { //NOPMD CompareObjectsWithEquals - identity is meant + // What EnumType.__new__ did, without a reflective metaclass + // call: type.__new__ (created), then the members. + k.meta = w; + Object boundary = boundaryOf(kn, kv); + k.created(withoutBoundary(kn), withoutBoundary(kn, kv)); + EnumMeta.init(k, boundary); + return k; + } + if (!k.hasLayout()) { + return callMeta(w, k, kn, kv); + } + // A compiled class: its fields and methods were laid out from the + // body as written, and generated code names the class object it + // built. A metaclass `__new__`/`__init__` may add to the namespace, + // but replacing the class, or rebinding or adding a name the layout + // compiled, would leave compiled code reading another class than the + // one Python sees; that is refused rather than run unsoundly. + Object[] keys = k.dict.keySet().toArray(); + Object[] before = new Object[keys.length]; + for (int i = 0; i < keys.length; i++) { + before[i] = k.dict.get(keys[i]); + } + Object made = callMeta(w, k, kn, kv); + if (made != k) { //NOPMD CompareObjectsWithEquals - identity is meant + throw Py.typeError("metaclass " + w.name + " replaced the compiled class " + k.name); + } + for (int i = 0; i < keys.length; i++) { + if (k.dict.get(keys[i]) != before[i]) { //NOPMD CompareObjectsWithEquals - identity is meant + throw Py.typeError("metaclass " + w.name + " rebound " + keys[i] + " of the compiled class " + k.name); + } + } + for (Object key : k.dict.keySet().toArray()) { + if (k.layoutNames(key) && !containsKey(keys, key)) { + throw Py.typeError("metaclass " + w.name + " added " + key + ", a compiled name of " + k.name); + } + } + return k; + } + + private static boolean containsKey(Object[] keys, Object key) { + for (Object x : keys) { + if (x.equals(key)) { + return true; + } + } + return false; + } + + /// Whether `name` is one of the compiled methods or fields of the + /// layout. + private boolean layoutNames(Object name) { + for (String[] a : new String[][] {compiledMethods, layoutFields}) { + if (a != null) { + for (String x : a) { + if (x.equals(name)) { + return true; + } + } + } + } + return false; } private static void addKw(List names, List values, String n, Object v) { @@ -524,10 +1096,54 @@ static Object typeNew(Object[] args, String[] kw) { version++; k.meta = winner(mcs, k.bases); k.implicitClassMethods(); + if (k.meta.isSubtype(EnumMeta.META)) { + // EnumType(name, bases, ns, boundary=...): the functional API. + Object boundary = boundaryOf(kn, kv); + k.created(withoutBoundary(kn), withoutBoundary(kn, kv)); + EnumMeta.init(k, boundary); + return k; + } k.created(kn, kv); + if (k.meta.isSubtype(Abc.META)) { + // A Python metaclass deriving from abc.ABCMeta calling + // super().__new__. + Abc.init(k); + } return k; } + /// The `boundary=` keyword of an enum class statement, or None. + private static Object boundaryOf(String[] kn, Object[] kv) { + for (int i = 0; i < kn.length; i++) { + if ("boundary".equals(kn[i])) { + return kv[i]; + } + } + return Py.NONE; + } + + /// The keyword names without `boundary`, which EnumType consumes. + private static String[] withoutBoundary(String[] kn) { + List out = new ArrayList(); + for (String n : kn) { + if (!"boundary".equals(n)) { + out.add(n); + } + } + return out.toArray(new String[out.size()]); + } + + /// The keyword values matching [#withoutBoundary]. + private static Object[] withoutBoundary(String[] kn, Object[] kv) { + List out = new ArrayList(); + for (int i = 0; i < kn.length; i++) { + if (!"boundary".equals(kn[i])) { + out.add(kv[i]); + } + } + return out.toArray(); + } + /// `__init_subclass__` and `__class_getitem__` are class methods even /// when written as plain functions. private void implicitClassMethods() { @@ -550,7 +1166,7 @@ private void created(String[] kn, Object[] kv) { if (v instanceof PyInstance) { Object sn = ((PyInstance) v).cls.lookup("__set_name__"); if (sn != null) { - Py.obj(sn).call(new Object[] {v, this, e.getKey()}, Py.NO_KW); + Py.obj(sn).call3(v, this, e.getKey()); } } } @@ -573,12 +1189,15 @@ private void created(String[] kn, Object[] kv) { public Object getItem(Object key) { Object m = metaDunder("__getitem__"); if (m != null) { - return Py.obj(m).call(new Object[] {this, key}, Py.NO_KW); + return Py.obj(m).call2(this, key); + } + if (EnumMeta.governs(this)) { + return EnumMeta.getItem(this, key); } Object cg = lookup("__class_getitem__"); if (cg != null) { Object f = cg instanceof PyClassMethod ? ((PyClassMethod) cg).func : cg; - return Py.obj(f).call(new Object[] {this, key}, Py.NO_KW); + return Py.obj(f).call2(this, key); } if (factory != null) { return new PyGenericAlias(this, key); @@ -590,7 +1209,10 @@ public Object getItem(Object key) { public Object iter() { Object m = metaDunder("__iter__"); if (m != null) { - return Py.obj(m).call(new Object[] {this}, Py.NO_KW); + return Py.obj(m).call1(this); + } + if (EnumMeta.governs(this)) { + return EnumMeta.iterOf(this); } return super.iter(); } @@ -599,7 +1221,10 @@ public Object iter() { public int len() { Object m = metaDunder("__len__"); if (m != null) { - return (int) Py.asLong(Py.obj(m).call(new Object[] {this}, Py.NO_KW)); + return (int) Py.asLong(Py.obj(m).call1(this)); + } + if (EnumMeta.governs(this)) { + return EnumMeta.len(this); } return super.len(); } @@ -608,7 +1233,10 @@ public int len() { public boolean contains(Object x) { Object m = metaDunder("__contains__"); if (m != null) { - return Py.isTrue(Py.obj(m).call(new Object[] {this, x}, Py.NO_KW)); + return Py.isTrue(Py.obj(m).call2(this, x)); + } + if (EnumMeta.governs(this)) { + return EnumMeta.contains(this, x); } return super.contains(x); } @@ -617,7 +1245,10 @@ public boolean contains(Object x) { public boolean isTrue() { Object m = metaDunder("__bool__"); if (m != null) { - return Py.isTrue(Py.obj(m).call(new Object[] {this}, Py.NO_KW)); + return Py.isTrue(Py.obj(m).call1(this)); + } + if (EnumMeta.governs(this)) { + return true; } m = metaDunder("__len__"); return m == null || len() != 0; @@ -627,7 +1258,7 @@ public boolean isTrue() { public String str() { Object m = metaDunder("__str__"); if (m != null) { - return Py.strValue(Py.obj(m).call(new Object[] {this}, Py.NO_KW), "__str__"); + return Py.strValue(Py.obj(m).call1(this), "__str__"); } return repr(); } @@ -669,6 +1300,28 @@ boolean hasCustomGetattribute() { return customGetattribute; } + /// Whether `__getitem__` is the builtin one (a dict subclass that does + /// not override it), and the class's `__missing__` (null for none), kept + /// against [#version] as [#hasCustomGetattribute()] is: a subscript of a + /// `defaultdict` asked both of the whole MRO on every read. + private boolean builtinGetitem; + private Object missing; + private int getitemVersion = -1; + + boolean hasBuiltinGetitem() { + if (getitemVersion != version) { + builtinGetitem = lookup("__getitem__") instanceof PyBuiltin; + missing = lookup("__missing__"); + getitemVersion = version; + } + return builtinGetitem; + } + + /// `__missing__`, valid after [#hasBuiltinGetitem()] answered. + Object missingMethod() { + return missing; + } + /// `issubclass(self, other)`. public boolean isSubtype(PyType other) { for (PyType e : mro) { @@ -714,7 +1367,9 @@ public Object getAttrOrNull(String attr) { } Object v = lookup(attr); if (v == null) { - if (customMeta()) { + // ABCMeta's register is found here too, though Abc.META keeps + // the fast construction paths customMeta() guards. + if (meta != null && meta != Py.TYPE_TYPE) { //NOPMD CompareObjectsWithEquals - identity is meant Object mv = metaAttr(attr); if (mv != null) { return mv; @@ -748,7 +1403,7 @@ public Object getAttrOrNull(String attr) { if (v instanceof PyInstance) { Object get = ((PyInstance) v).cls.lookup("__get__"); if (get != null) { - return Py.obj(get).call(new Object[] {v, Py.NONE, this}, Py.NO_KW); + return Py.obj(get).call3(v, Py.NONE, this); } } return v; @@ -760,7 +1415,7 @@ private Object metaAttr(String attr) { Object m = meta.lookup(attr); if (m == null) { Object ga = metaDunder("__getattr__"); - return ga == null ? null : Py.obj(ga).call(new Object[] {this, attr}, Py.NO_KW); + return ga == null ? null : Py.obj(ga).call2(this, attr); } if (m instanceof PyProperty) { return ((PyProperty) m).get(this); @@ -778,7 +1433,11 @@ private Object metaAttr(String attr) { public void setAttr(String attr, Object value) { Object sa = metaDunder("__setattr__"); if (sa != null) { - Py.obj(sa).call(new Object[] {this, attr, value}, Py.NO_KW); + Py.obj(sa).call3(this, attr, value); + return; + } + if (EnumMeta.governs(this)) { + EnumMeta.setAttr(this, attr, value); return; } setAttrDirect(attr, value); @@ -786,6 +1445,22 @@ public void setAttr(String attr, Object value) { /// `type.__setattr__(cls, attr, value)`. public void setAttrDirect(String attr, Object value) { + if (customMeta()) { + // A data descriptor of the metaclass (a property with a setter) + // decides the store, as type.__setattr__ does in CPython. + Object ma = meta.lookup(attr); + if (ma instanceof PyProperty) { + ((PyProperty) ma).set(this, value); + return; + } + if (ma instanceof PyInstance) { + Object set = ((PyInstance) ma).cls.lookup("__set__"); + if (set != null) { + Py.obj(set).call3(ma, this, value); + return; + } + } + } if ("__name__".equals(attr)) { if (!(value instanceof String) && !(value instanceof PyStr)) { throw Py.typeError("can only assign string to " + name + ".__name__, not '" @@ -804,7 +1479,7 @@ public void setAttrDirect(String attr, Object value) { public void delAttr(String attr) { Object da = metaDunder("__delattr__"); if (da != null) { - Py.obj(da).call(new Object[] {this, attr}, Py.NO_KW); + Py.obj(da).call2(this, attr); return; } delAttrDirect(attr); @@ -828,15 +1503,32 @@ public Object call(Object[] args, String[] kwNames) { if (mc != null) { return Py.obj(mc).call(Py.prepend(this, args), kwNames); } + if (EnumMeta.governs(this)) { + return EnumMeta.call(this, args, kwNames); + } return construct(args, kwNames); } /// `type.__call__(cls, *args)`: `__new__`, then `__init__`. Object construct(Object[] args, String[] kwNames) { + if (abstractNames != null) { + throw Abc.instantiationError(this); + } if (factory != null) { // A builtin type builds and initialises its own instances. return factory.create(this, args, kwNames); } + if (kwNames.length == 0 && this != Py.OS_ERROR && plainException()) { //NOPMD CompareObjectsWithEquals - identity is meant + // An exception class that overrides neither: what __new__ and + // __init__ would do between them, once, without the receiver + // prepended to two argument arrays (raise ValueError(...) in a + // parser's loop). + PyInstance e = newInstance(); + Object[] rest = new Object[args.length]; + System.arraycopy(args, 0, rest, 0, rest.length); + e.setAttrDirect("args", rest.length == 0 ? PyTuple.EMPTY : new PyTuple(rest)); + return e; + } Object newFn = lookup("__new__"); Object obj; if (newFn != null && newFn != Builtins.OBJECT_NEW) { //NOPMD CompareObjectsWithEquals - identity is meant @@ -862,19 +1554,337 @@ Object construct(Object[] args, String[] kwNames) { /// The `__init__` of a plain class (no `__new__`, no builtin base), the /// case a positional constructor call takes without an argument array. - private Object plainInit() { - if (factory != null || this == Py.TYPE_TYPE || customMeta()) { //NOPMD CompareObjectsWithEquals - identity is meant + Object plainInit() { + Object init = plainInitAny(); + return init instanceof PyFunction ? init : null; + } + + /// The `__init__` of a plain class whatever it is, or null for a class that + /// is not plain. + private Object plainInitAny() { + if (plainInitVersion == version) { + return plainInitCache; + } + Object r = resolvePlainInit(); + plainInitCache = r; + plainInitVersion = version; + return r; + } + + /// [#plainInitAny()]'s answer, valid while [#plainInitVersion] equals + /// [#version]; any class change re-resolves it. + private Object plainInitCache; + private int plainInitVersion = -1; + + /// `__bool__` of this type, else its `__len__` (one of them null), for + /// truth tests of instances; good while [#truthVersion] is [#version]. + Object truthBool; + /// [#truthBool] is a builtin subclass's own `__bool__`: an instance's + /// truth is its base value's. + boolean truthBase; + /// `__len__` / `__hash__` are the builtin's own (a subclass of str, + /// tuple, int... that does not override them): an instance's answer is + /// its base value's, asked without the builtin call and the view of the + /// value it made. Kept with the truth methods, against the version. + boolean lenBase; + boolean hashBase; + + /// How many extra attribute slots this class's instances have grown to, + /// the most seen: a new instance's first slot array is that long, so an + /// `__init__` that sets a dozen names allocates once rather than at 4, 8 + /// and 16. Only a size hint -- any value is correct. + /// The last `__dict__` an instance of this class built from scratch: + /// the shape and set fields it was built for, the shape slots holding a + /// field marker, and copies of its keys, hashes, index table and value + /// sources (see `PyInstance.InstanceDict`). + Shape dictTplShape; + long dictTplMask; + boolean[] dictTplMarks; + Object[] dictTplKeys; + long[] dictTplHashes; + int[] dictTplIndex; + int[] dictTplMap; + + int slotHint = 4; + Object truthLen; + /// What [#truthBool] always answers, when it is a function whose body + /// only returns a bool (PyFunction#constant); null otherwise. + Object truthConst; + int truthVersion = -1; + + /// Refreshes [#truthBool] and [#truthLen] after any type changed. + void truthMethods() { + truthBool = lookup("__bool__"); + truthLen = truthBool == null ? lookup("__len__") : null; + truthConst = truthBool instanceof PyFunction ? ((PyFunction) truthBool).constant : null; + // A builtin's own __bool__, or (str, list, dict: no __bool__) its + // own __len__, both answer the truth of the value an instance wraps. + // A Python override is a function, never a builtin. + truthBase = truthBool instanceof PyBuiltin ? ((PyBuiltin) truthBool).baseTruth + : truthBool == null && truthLen instanceof PyBuiltin; + lenBase = lookup("__len__") instanceof PyBuiltin; + hashBase = lookup("__hash__") instanceof PyBuiltin; + truthVersion = version; + } + + private Object resolvePlainInit() { + if (factory != null || this == Py.TYPE_TYPE || customMeta() || abstractNames != null) { //NOPMD CompareObjectsWithEquals - identity is meant return null; } Object newFn = lookup("__new__"); if (newFn != null && newFn != Builtins.OBJECT_NEW) { //NOPMD CompareObjectsWithEquals - identity is meant return null; } + return lookup("__init__"); + } + + // Keyword constructor calls of a plain class (`Tag(parser, builder, + // name, attrs=a)`): `__init__` gets the new instance and the arguments as + // parameters, with no argument array and none with the instance + // prepended. Anything else -- a builtin, a `__new__`, a metaclass -- goes + // the generic way. + + @Override + public Object callKwF(String[] kwNames, Object a) { + Object init = plainInitAny(); + if (init instanceof PyFunction) { + PyInstance o = newInstance(); + initReturned(((PyFunction) init).callKwF(kwNames, o, a)); + return o; + } + return super.callKwF(kwNames, a); + } + + @Override + public Object callKwF(String[] kwNames, Object a, Object b) { + Object init = plainInitAny(); + if (init instanceof PyFunction) { + PyInstance o = newInstance(); + initReturned(((PyFunction) init).callKwF(kwNames, o, a, b)); + return o; + } + return super.callKwF(kwNames, a, b); + } + + @Override + public Object callKwF(String[] kwNames, Object a, Object b, Object c) { + Object init = plainInitAny(); + if (init instanceof PyFunction) { + PyInstance o = newInstance(); + initReturned(((PyFunction) init).callKwF(kwNames, o, a, b, c)); + return o; + } + return super.callKwF(kwNames, a, b, c); + } + + @Override + public Object callKwF(String[] kwNames, Object a, Object b, Object c, Object d) { + Object init = plainInitAny(); + if (init instanceof PyFunction) { + PyInstance o = newInstance(); + initReturned(((PyFunction) init).callKwF(kwNames, o, a, b, c, d)); + return o; + } + return super.callKwF(kwNames, a, b, c, d); + } + + @Override + public Object callKwF(String[] kwNames, Object a, Object b, Object c, Object d, Object e) { + Object init = plainInitAny(); + if (init instanceof PyFunction) { + PyInstance o = newInstance(); + initReturned(((PyFunction) init).callKwF(kwNames, o, a, b, c, d, e)); + return o; + } + return super.callKwF(kwNames, a, b, c, d, e); + } + + @Override + public Object callKwF(String[] kwNames, Object a, Object b, Object c, Object d, Object e, Object f) { + Object init = plainInitAny(); + if (init instanceof PyFunction) { + PyInstance o = newInstance(); + initReturned(((PyFunction) init).callKwF(kwNames, o, a, b, c, d, e, f)); + return o; + } + return super.callKwF(kwNames, a, b, c, d, e, f); + } + + @Override + public Object callKwF(String[] kwNames, Object a, Object b, Object c, Object d, Object e, Object f, Object g) { + Object init = plainInitAny(); + if (init instanceof PyFunction) { + PyInstance o = newInstance(); + initReturned(((PyFunction) init).callKwF(kwNames, o, a, b, c, d, e, f, g)); + return o; + } + return super.callKwF(kwNames, a, b, c, d, e, f, g); + } + + @Override + public Object callKwF(String[] kwNames, Object a, Object b, Object c, Object d, Object e, Object f, Object g, Object h) { + Object init = plainInitAny(); + if (init instanceof PyFunction) { + PyInstance o = newInstance(); + initReturned(((PyFunction) init).callKwF(kwNames, o, a, b, c, d, e, f, g, h)); + return o; + } + return super.callKwF(kwNames, a, b, c, d, e, f, g, h); + } + + @Override + public Object callKwF(String[] kwNames, Object a, Object b, Object c, Object d, Object e, Object f, Object g, Object h, Object i) { + Object init = plainInitAny(); + if (init instanceof PyFunction) { + PyInstance o = newInstance(); + initReturned(((PyFunction) init).callKwF(kwNames, o, a, b, c, d, e, f, g, h, i)); + return o; + } + return super.callKwF(kwNames, a, b, c, d, e, f, g, h, i); + } + + @Override + public Object callKwF(String[] kwNames, Object a, Object b, Object c, Object d, Object e, Object f, Object g, Object h, Object i, Object j) { + Object init = plainInitAny(); + if (init instanceof PyFunction) { + PyInstance o = newInstance(); + initReturned(((PyFunction) init).callKwF(kwNames, o, a, b, c, d, e, f, g, h, i, j)); + return o; + } + return super.callKwF(kwNames, a, b, c, d, e, f, g, h, i, j); + } + + @Override + public Object callKwF(String[] kwNames, Object a, Object b, Object c, Object d, Object e, Object f, Object g, Object h, Object i, Object j, Object k) { + Object init = plainInitAny(); + if (init instanceof PyFunction) { + PyInstance o = newInstance(); + initReturned(((PyFunction) init).callKwF(kwNames, o, a, b, c, d, e, f, g, h, i, j, k)); + return o; + } + return super.callKwF(kwNames, a, b, c, d, e, f, g, h, i, j, k); + } + + @Override + public Object callKwF(String[] kwNames, Object a, Object b, Object c, Object d, Object e, Object f, Object g, Object h, Object i, Object j, Object k, Object l) { + Object init = plainInitAny(); + if (init instanceof PyFunction) { + PyInstance o = newInstance(); + initReturned(((PyFunction) init).callKwF(kwNames, o, a, b, c, d, e, f, g, h, i, j, k, l)); + return o; + } + return super.callKwF(kwNames, a, b, c, d, e, f, g, h, i, j, k, l); + } + + @Override + public Object callKwF(String[] kwNames, Object a, Object b, Object c, Object d, Object e, Object f, Object g, Object h, Object i, Object j, Object k, Object l, Object m) { + Object init = plainInitAny(); + if (init instanceof PyFunction) { + PyInstance o = newInstance(); + initReturned(((PyFunction) init).callKwF(kwNames, o, a, b, c, d, e, f, g, h, i, j, k, l, m)); + return o; + } + return super.callKwF(kwNames, a, b, c, d, e, f, g, h, i, j, k, l, m); + } + + /// A positional constructor call of a plain class without an argument + /// array: `__init__` is a function, or the one a dataclass generated. Null + /// when the class is neither, and the caller builds the array after all. + private Object positionalNew(int n, Object a, Object b, Object c, Object d, Object e, Object f6, + Object g7) { + Object init = plainInitAny(); + if (init instanceof PyFunction) { + PyFunction f = (PyFunction) init; + PyInstance o = newInstance(); + switch (n) { + case 0: + initReturned(f.call1(o)); + break; + case 1: + initReturned(f.call2(o, a)); + break; + case 2: + initReturned(f.call3(o, a, b)); + break; + case 3: + initReturned(f.call4(o, a, b, c)); + break; + case 4: + initReturned(f.call5(o, a, b, c, d)); + break; + case 5: + initReturned(f.call6(o, a, b, c, d, e)); + break; + case 6: + initReturned(f.call7(o, a, b, c, d, e, f6)); + break; + default: + initReturned(f.call8(o, a, b, c, d, e, f6, g7)); + break; + } + return o; + } + return constructFixed(n, a, b, c, d, e, f6, g7); + } + + /// [#construct] for a call of `n` positional arguments: `__new__` and + /// `__init__` called at their arity, where construct prepends the + /// receiver to an argument array for each. A namedtuple (`urlparse`), a + /// str subclass (bs4's NavigableString) and a list subclass are built + /// this way per element. Null for a call this does not cover, which + /// then goes through construct exactly as before. + private Object constructFixed(int n, Object a, Object b, Object c, Object d, Object e, Object f6, + Object g7) { + if (factory != null || this == Py.TYPE_TYPE || this == Py.OS_ERROR || plainException() //NOPMD CompareObjectsWithEquals - identity is meant + || abstractNames != null || metaDunder("__call__") != null || EnumMeta.governs(this)) { + return null; + } + Object newFn = lookup("__new__"); + Object obj; + if (newFn != null && newFn != Builtins.OBJECT_NEW) { //NOPMD CompareObjectsWithEquals - identity is meant + Object fn = newFn instanceof PyStaticMethod ? ((PyStaticMethod) newFn).func : newFn; + obj = callWith(Py.obj(fn), this, n, a, b, c, d, e, f6, g7); + if (!Py.typeOf(obj).isSubtype(this)) { + return obj; + } + } else { + obj = newInstance(); + } Object init = lookup("__init__"); - return init instanceof PyFunction ? init : null; + if (init != null && init != Builtins.OBJECT_INIT) { //NOPMD CompareObjectsWithEquals - identity is meant + initReturned(callWith(Py.obj(init), obj, n, a, b, c, d, e, f6, g7)); + } else if (n > 0 && newFn == Builtins.OBJECT_NEW) { //NOPMD CompareObjectsWithEquals - identity is meant + throw Py.typeError(name + "() takes no arguments"); + } + return obj; + } + + /// `f(first, a, ...)` with the `n` arguments after `first`. + private static Object callWith(PyObject f, Object first, int n, Object a, Object b, Object c, Object d, Object e, + Object f6, Object g7) { + switch (n) { + case 0: + return f.call1(first); + case 1: + return f.call2(first, a); + case 2: + return f.call3(first, a, b); + case 3: + return f.call4(first, a, b, c); + case 4: + return f.call5(first, a, b, c, d); + case 5: + return f.call6(first, a, b, c, d, e); + case 6: + return f.call7(first, a, b, c, d, e, f6); + default: + return f.call8(first, a, b, c, d, e, f6, g7); + } } - private static void initReturned(Object r) { + /// What a call of a class does with its `__init__`'s result; public for + /// the constructor calls the transpiler binds at build time. + public static void initReturned(Object r) { if (r != Py.NONE) { //NOPMD CompareObjectsWithEquals - identity is meant throw Py.typeError("__init__() should return None, not '" + Py.typeOf(r).name + "'"); } @@ -882,13 +1892,8 @@ private static void initReturned(Object r) { @Override public Object call0() { - Object init = plainInit(); - if (init == null) { - return super.call0(); - } - PyInstance o = newInstance(); - initReturned(((PyFunction) init).call1(o)); - return o; + Object o = positionalNew(0, null, null, null, null, null, null, null); + return o != null ? o : super.call0(); } @Override @@ -896,50 +1901,71 @@ public Object call1(Object a) { if (unary != null) { return unary.create(a); } - Object init = plainInit(); - if (init == null) { - return super.call1(a); - } - PyInstance o = newInstance(); - initReturned(((PyFunction) init).call2(o, a)); - return o; + Object o = positionalNew(1, a, null, null, null, null, null, null); + return o != null ? o : super.call1(a); } @Override public Object call2(Object a, Object b) { - Object init = plainInit(); - if (init == null) { - return super.call2(a, b); + if (binary != null) { + return binary.create(a, b); } - PyInstance o = newInstance(); - initReturned(((PyFunction) init).call3(o, a, b)); - return o; + Object o = positionalNew(2, a, b, null, null, null, null, null); + return o != null ? o : super.call2(a, b); } @Override public Object call3(Object a, Object b, Object c) { - Object init = plainInit(); - if (init == null) { - return super.call3(a, b, c); - } - PyInstance o = newInstance(); - initReturned(((PyFunction) init).call4(o, a, b, c)); - return o; + Object o = positionalNew(3, a, b, c, null, null, null, null); + return o != null ? o : super.call3(a, b, c); + } + + @Override + public Object call4(Object a, Object b, Object c, Object d) { + Object o = positionalNew(4, a, b, c, d, null, null, null); + return o != null ? o : super.call4(a, b, c, d); + } + + @Override + public Object call5(Object a, Object b, Object c, Object d, Object e) { + Object o = positionalNew(5, a, b, c, d, e, null, null); + return o != null ? o : super.call5(a, b, c, d, e); + } + + @Override + public Object call6(Object a, Object b, Object c, Object d, Object e, Object f) { + Object o = positionalNew(6, a, b, c, d, e, f, null); + return o != null ? o : super.call6(a, b, c, d, e, f); + } + + @Override + public Object call7(Object a, Object b, Object c, Object d, Object e, Object f, Object g) { + Object o = positionalNew(7, a, b, c, d, e, f, g); + return o != null ? o : super.call7(a, b, c, d, e, f, g); } @Override public String repr() { Object m = metaDunder("__repr__"); if (m != null) { - return Py.strValue(Py.obj(m).call(new Object[] {this}, Py.NO_KW), "__repr__"); + return Py.strValue(Py.obj(m).call1(this), "__repr__"); + } + if (EnumMeta.governs(this)) { + return EnumMeta.repr(this); } + return ""; + } + + /// `module.qualname` as `repr` shows a class and its instances; a + /// builtin type's module is left out. + String fullName() { Object q = dict.get("__qualname__"); String qual = q instanceof String ? (String) q : name; Object mod = dict.get("__module__"); if (mod instanceof String && !"builtins".equals(mod)) { - return ""; + return mod + "." + qual; } - return ""; + return qual; } @Override diff --git a/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyUnion.java b/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyUnion.java index 3837b4f860e..20ec33f1540 100644 --- a/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyUnion.java +++ b/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyUnion.java @@ -49,7 +49,7 @@ static Object of(Object a, Object b) { private static void add(List out, Object t) { if (t instanceof PyUnion) { - for (Object o : ((PyUnion) t).args.items) { + for (Object o : ((PyUnion) t).args.arr()) { add(out, o); } return; @@ -85,7 +85,7 @@ static String typeRepr(Object t) { } boolean instanceCheck(Object o) { - for (Object t : args.items) { + for (Object t : args.arr()) { if (Py.isinstance(o, t)) { return true; } @@ -127,8 +127,8 @@ public Object eq(Object o) { if (!(o instanceof PyUnion)) { return null; } - Object[] mine = args.items; - Object[] theirs = ((PyUnion) o).args.items; + Object[] mine = args.arr(); + Object[] theirs = ((PyUnion) o).args.arr(); if (mine.length != theirs.length) { return Py.FALSE; } @@ -150,7 +150,7 @@ public Object eq(Object o) { @Override public long hash() { long h = 0; - for (Object t : args.items) { + for (Object t : args.arr()) { h ^= Py.hashOf(t); } return h; @@ -159,11 +159,11 @@ public long hash() { @Override public String repr() { StringBuilder b = new StringBuilder(); - for (int i = 0; i < args.items.length; i++) { + for (int i = 0; i < args.arr().length; i++) { if (i > 0) { b.append(" | "); } - b.append(typeRepr(args.items[i])); + b.append(typeRepr(args.arr()[i])); } return b.toString(); } diff --git a/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyZlib.java b/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyZlib.java index dea201179fd..561dafb9d6a 100644 --- a/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyZlib.java +++ b/maven/python-runtime/src/main/java/com/codename1/python/runtime/PyZlib.java @@ -65,19 +65,19 @@ static PyModule module() { } return new PyJavaObject(z); })); - m.setAttr("deflate", PyBuiltin.positional("deflate", a -> { - ZStream z = stream(a[0]); - byte[] in = PyBytes.like(a[1]); - int flush = (int) Py.asLong(a[2]); + m.setAttr("deflate", PyBuiltin.fixed3("deflate", (a0, a1, a2) -> { + ZStream z = stream(a0); + byte[] in = PyBytes.like(a1); + int flush = (int) Py.asLong(a2); return new PyBytes(deflate(z, in, flush)); })); - m.setAttr("inflate_new", PyBuiltin.positional("inflate_new", a -> { + m.setAttr("inflate_new", PyBuiltin.fixed2("inflate_new", (a0, a1) -> { ZStream z = new ZStream(); - int err = z.inflateInit((int) Py.asLong(a[0])); + int err = z.inflateInit((int) Py.asLong(a0)); if (err != JZlib.Z_OK) { throw Py.error(Py.VALUE_ERROR, "Invalid initialization option"); } - return new PyJavaObject(new InflateState(z, a[1] == Py.NONE ? null : PyBytes.like(a[1]))); //NOPMD CompareObjectsWithEquals - identity is meant + return new PyJavaObject(new InflateState(z, a1 == Py.NONE ? null : PyBytes.like(a1))); //NOPMD CompareObjectsWithEquals - identity is meant })); m.setAttr("inflate", PyBuiltin.positional("inflate", a -> { InflateState s = inflateState(a[0]); @@ -85,8 +85,8 @@ static PyModule module() { long max = Py.asLong(a[2]); return s.inflate(in, max <= 0 ? Long.MAX_VALUE : max, Py.isTrue(a[3])); })); - m.setAttr("end", PyBuiltin.positional("end", a -> { - Object v = a[0] instanceof PyJavaObject ? ((PyJavaObject) a[0]).value : null; + m.setAttr("end", PyBuiltin.fixed1("end", a0 -> { + Object v = a0 instanceof PyJavaObject ? ((PyJavaObject) a0).value : null; if (v instanceof ZStream) { ((ZStream) v).deflateEnd(); } else if (v instanceof InflateState) { @@ -94,17 +94,17 @@ static PyModule module() { } return Py.NONE; })); - m.setAttr("crc32", PyBuiltin.positional("crc32", a -> { - byte[] b = PyBytes.like(a[0]); + m.setAttr("crc32", PyBuiltin.fixed2("crc32", (a0, a1) -> { + byte[] b = PyBytes.like(a0); CRC32 c = new CRC32(); - c.reset(Py.asLong(a[1]) & 0xffffffffL); + c.reset(Py.asLong(a1) & 0xffffffffL); c.update(b, 0, b.length); return PyInt.of(c.getValue() & 0xffffffffL); })); - m.setAttr("adler32", PyBuiltin.positional("adler32", a -> { - byte[] b = PyBytes.like(a[0]); + m.setAttr("adler32", PyBuiltin.fixed2("adler32", (a0, a1) -> { + byte[] b = PyBytes.like(a0); Adler32 c = new Adler32(); - c.reset(Py.asLong(a[1]) & 0xffffffffL); + c.reset(Py.asLong(a1) & 0xffffffffL); c.update(b, 0, b.length); return PyInt.of(c.getValue() & 0xffffffffL); })); @@ -160,17 +160,27 @@ static final class InflateState { /// Inflates `in`, producing at most `max` bytes; answers /// `(output, bytes of in consumed, end of stream reached)`. Object inflate(byte[] in, long max, boolean finish) { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - byte[] buf = new byte[CHUNK]; + // Straight into one array, sized from the input and doubled when + // full: no chunk buffer and no stream copying it twice per call. + long guess = Math.max(256L, (long) in.length * 4); + byte[] out = new byte[(int) Math.min(Math.min(guess, max), Integer.MAX_VALUE - 8)]; + int size = 0; z.setInput(in, 0, in.length, false); boolean eof = false; while (true) { - long room = max - out.size(); + long room = max - size; if (room <= 0) { break; } - int len = (int) Math.min(buf.length, room); - z.setOutput(buf, 0, len); + if (size == out.length) { + long grown = Math.min(Math.min((long) out.length * 2, max), Integer.MAX_VALUE - 8); + if (grown <= out.length) { + break; + } + out = java.util.Arrays.copyOf(out, (int) grown); + } + int len = (int) Math.min(out.length - size, room); + z.setOutput(out, size, len); int err = z.inflate(finish ? JZlib.Z_FINISH : JZlib.Z_NO_FLUSH); if (err == JZlib.Z_NEED_DICT) { if (dict == null || z.inflateSetDictionary(dict, dict.length) != JZlib.Z_OK) { @@ -179,13 +189,20 @@ Object inflate(byte[] in, long max, boolean finish) { continue; } int produced = len - z.availOut; - out.write(buf, 0, produced); + size += produced; if (err == JZlib.Z_STREAM_END) { eof = true; break; } if (err == JZlib.Z_BUF_ERROR) { - break; + // With Z_FINISH, zlib answers Z_BUF_ERROR whenever the + // output buffer fills before the stream ends, so it only + // means "stuck" when this pass produced nothing. Stopping + // on the first one truncated any output above one buffer. + if (produced == 0) { + break; + } + continue; } if (err != JZlib.Z_OK) { throw Py.error(Py.OS_ERROR, "Error " + err + " while decompressing data" + detail(z)); @@ -194,8 +211,11 @@ Object inflate(byte[] in, long max, boolean finish) { break; } } + if (size != out.length) { + out = java.util.Arrays.copyOf(out, size); + } int consumed = in.length - z.availIn; - return new PyTuple(new Object[] {new PyBytes(out.toByteArray()), PyInt.of(consumed), Py.bool(eof)}); + return Py.tuple(new PyBytes(out), PyInt.of(consumed), Py.bool(eof)); } } } diff --git a/maven/python-runtime/src/main/java/com/codename1/python/runtime/Regex.java b/maven/python-runtime/src/main/java/com/codename1/python/runtime/Regex.java index d43b9256b21..c086b5f1bd1 100644 --- a/maven/python-runtime/src/main/java/com/codename1/python/runtime/Regex.java +++ b/maven/python-runtime/src/main/java/com/codename1/python/runtime/Regex.java @@ -97,10 +97,18 @@ static final class Op { /// AT: the assertion. LOOK: behind, negative, width. int at; boolean behind; + /// A LOOK whose program is single-char tests and then MATCH (`(? scratch = - new java.util.concurrent.atomic.AtomicReference(); + /// allocated. A plain field: Python runs under the [Gil], one thread + /// at a time, and a run never releases it. Taken (left null) for the + /// run, so a run nested in another builds its own. + Scratch scratch; + /// 1 for a str pattern, 2 for bytes, 0 until [RegexMatch] first asks. + int kind; + /// Compiled replacement templates by text, as sre caches them; at + /// most [RegexMatch#TEMPLATES]. + java.util.HashMap templates; + /// The same for bytes replacements, keyed by their Latin-1 text. + java.util.HashMap byteTemplates; @Override public PyType type() { @@ -143,6 +183,13 @@ private static final class Scratch { final Ints stack = new Ints(); final Ints trail = new Ints(); int[] regs = NO_INTS; + /// [Prog#need]: whether the scan below is for this hold's text (a + /// scratch is held over one text, from [#acquire] to [#release]), + /// the offset it began at, and the first needed char at or after it, + /// -1 for none. A loop over one text scans it once. + boolean needValid; + int needFrom; + int needAt; } static PyModule module() { @@ -154,12 +201,259 @@ static PyModule module() { p.marks = (int) Py.index(a[2]); p.prefix = Py.isTrue(a[3]) ? Py.toStr(a[3]) : null; p.anchored = Py.isTrue(a[4]); + p.first = firstOps(p.ops); + if (p.first != null) { + p.firstAscii = new boolean[128]; + for (Op op : p.first) { + if (op.k == AT) { + p.firstAt = true; + continue; + } + for (int c = 0; c < 128; c++) { + p.firstAscii[c] |= one(op, c); + } + } + } + p.solo = solo(p); + p.need = need(p.ops, p.first); + if (p.need != null) { + p.needAscii = new boolean[128]; + for (int c = 0; c < 128; c++) { + p.needAscii[c] = one(p.need, c); + } + } return p; })); m.setAttr("run", new RunFn()); + m.setAttr("match", new MatchFn()); + m.setAttr("pattern_match", patternMethod("match", 0)); + m.setAttr("pattern_fullmatch", patternMethod("fullmatch", 1)); + m.setAttr("pattern_search", patternMethod("search", 2)); + // The module's own callers (re/__init__.py) pass every argument, so each + // entry also has its array-free form for exactly that many. + m.setAttr("iter", PyBuiltin.positional("iter", a -> RegexMatch.search(prog(a[0]), a[1], a[2], a[3], + a[4], (int) Py.index(a[5]), 2, (int) Py.index(a[6]))) + .with7((a0, a1, a2, a3, a4, a5, a6) -> RegexMatch.search(prog(a0), a1, a2, a3, a4, + (int) Py.index(a5), 2, (int) Py.index(a6)))); + m.setAttr("set_hooks", PyBuiltin.fixed3("set_hooks", (a0, a1, a2) -> { + RegexMatch.expandHook = a0; + RegexMatch.templateHook = a1; + RegexMatch.subHook = a2; + return Py.NONE; + })); + m.setAttr("sub", PyBuiltin.positional("sub", a -> RegexMatch.sub(prog(a[0]), a[1], a[2], a[3], + a[4], Py.isTrue(a[5]))) + .with6((a0, a1, a2, a3, a4, a5) -> RegexMatch.sub(prog(a0), a1, a2, a3, a4, Py.isTrue(a5)))); + m.setAttr("Match", RegexMatch.TYPE); + m.setAttr("subn", PyBuiltin.positional("subn", a -> subn(prog(a[0]), Py.toStr(a[1]), + (PyList) a[2], (int) Py.index(a[3]))) + .with4((a0, a1, a2, a3) -> subn(prog(a0), Py.toStr(a1), (PyList) a2, (int) Py.index(a3)))); + m.setAttr("split", PyBuiltin.fixed3("split", (a0, a1, a2) -> split(prog(a0), Py.toStr(a1), + (int) Py.index(a2)))); + m.setAttr("findall", PyBuiltin.positional("findall", a -> findall(prog(a[0]), Py.toStr(a[1]), + (int) Py.index(a[2]), (int) Py.index(a[3]))) + .with4((a0, a1, a2, a3) -> findall(prog(a0), Py.toStr(a1), (int) Py.index(a2), (int) Py.index(a3)))); return m; } + /// See `Prog.solo`. + private static Op solo(Prog p) { + Op[] ops = p.ops; + if (ops == null || ops.length != 2 || ops[1].k != MATCH || p.groups != 0 || p.marks != 0 || p.first == null || p.firstAt) { + return null; + } + Op op = ops[0]; + if (op.k == CHAR || op.k == SET) { + return op; + } + if (op.k == REPEAT_ONE && op.lo >= 1 && op.one != null && (op.one.k == CHAR || op.one.k == SET)) { + return op; + } + return null; + } + + /// See `Prog.need`: the first CHAR or SET test (alone, or as a repeat + /// of at least one) that MATCH cannot be reached without, and that the + /// first-character skip does not already ask for. + private static Op need(Op[] ops, Op[] first) { + for (int pc = 0; pc < ops.length; pc++) { + Op op = ops[pc]; + Op test = op.k == CHAR || op.k == SET ? op + : (op.k == REPEAT_ONE || op.k == MIN_REPEAT_ONE) && op.lo >= 1 ? op.one : null; + if (test == null || test.k != CHAR && test.k != SET || isFirst(first, test)) { + continue; + } + int r = reachesMatch(ops, pc); + if (r < 0) { + return null; + } + if (r == 0) { + return test; + } + } + return null; + } + + private static boolean isFirst(Op[] first, Op test) { + if (first != null) { + for (Op f : first) { + if (f == test) { //NOPMD CompareObjectsWithEquals - the same op of this program + return true; + } + } + } + return false; + } + + /// Whether MATCH is reachable from the start without passing `avoid`: + /// 1 yes, 0 no, -1 when the program has an op whose flow is not + /// modelled here. + private static int reachesMatch(Op[] ops, int avoid) { + boolean[] seen = new boolean[ops.length]; + int[] work = new int[2 * ops.length + 2]; + int n = 0; + work[n++] = 0; + while (n > 0) { + int pc = work[--n]; + if (pc < 0 || pc >= ops.length) { + return -1; + } + if (pc == avoid || seen[pc]) { + continue; + } + seen[pc] = true; + Op op = ops[pc]; + switch (op.k) { + case MATCH: + return 1; + case SPLIT: + work[n++] = op.a; + work[n++] = op.b; + break; + case JMP: + work[n++] = op.a; + break; + case PROGRESS: + case GROUPREF_EXISTS: + work[n++] = op.b; + work[n++] = pc + 1; + break; + case CHAR: + case CHARI: + case ANY: + case ANYALL: + case SET: + case AT: + case SAVE: + case MARK: + case BACKREF: + case LOOK: + case ATOMIC: + case REPEAT_ONE: + case MIN_REPEAT_ONE: + work[n++] = pc + 1; + break; + default: + return -1; + } + } + return 0; + } + + /// Whether a char of [Prog#need] is at or after `start` and before + /// `endpos`; the scan is kept in `sc` for the next run over the text. + private static boolean needed(Op op, boolean[] f, Scratch sc, String text, int start, int endpos) { + if (!sc.needValid || start < sc.needFrom || sc.needAt >= 0 && start > sc.needAt) { + int at = -1; + int len = text.length(); + if (op.k == CHAR && op.c < 0x10000) { + at = text.indexOf(op.c, start); + } else { + for (int i = start; i < len; i++) { + char c = text.charAt(i); + if (c < 128 ? f[c] : one(op, c)) { + at = i; + break; + } + } + } + sc.needValid = true; + sc.needFrom = start; + sc.needAt = at; + } + return sc.needAt >= 0 && sc.needAt < endpos; + } + + /// See `Prog.first`. + private static Op[] firstOps(Op[] ops) { + java.util.ArrayList out = new java.util.ArrayList(); + boolean[] seen = new boolean[ops.length]; + int[] work = new int[ops.length + 1]; + int n = 0; + work[n++] = 0; + while (n > 0) { + int pc = work[--n]; + while (true) { + if (pc < 0 || pc >= ops.length) { + return null; + } + if (seen[pc]) { + break; + } + seen[pc] = true; + Op op = ops[pc]; + if (op.k == CHAR || op.k == CHARI || op.k == ANY || op.k == ANYALL || op.k == SET) { + out.add(op); + break; + } + if (op.k == AT) { + // Zero width: a match starting here needs the assertion + // to hold here. markdownify's `(\s|^)...` escapes have + // one, and ran the program at every offset without it. + out.add(op); + break; + } + if (op.k == REPEAT_ONE || op.k == MIN_REPEAT_ONE) { + out.add(op.one); + if (op.lo >= 1) { + break; + } + // Optional: a match begins with the item or with whatever + // follows it. markdownify's `[\t \r\n]*[\r\n][\t \r\n]*` + // ran the program at every offset without this, where sre + // skips to the next whitespace. + pc++; + continue; + } + if (op.k == SAVE || op.k == LOOK) { + // A lookaround is zero width too: whatever follows it must + // still match from the same offset, so its first set is + // a necessary condition. `(?= 0 ? known : PyStr.surrogates(s); + if (pairs == 0) { cps = null; } else { - cps = new int[n]; + cps = new int[s.length() - pairs]; int i = 0; int j = 0; while (i < s.length()) { @@ -371,12 +681,57 @@ private static boolean inRanges(int[] ranges, int o) { return false; } + private static boolean simpleLook(Op[] sub) { + if (sub == null) { + return false; + } + int n = sub.length; + if (n < 2 || sub[n - 1].k != MATCH) { + return false; + } + for (int i = 0; i < n - 1; i++) { + int k = sub[i].k; + if (k != CHAR && k != CHARI && k != ANY && k != ANYALL && k != SET) { + return false; + } + } + return true; + } + + /// A simple LOOK's own tests (see `Op.simple`), before the negation. + private static boolean lookHit(Op op, Text t, int pos, int endpos) { + Op[] sub = op.sub; + if (sub == null) { + return false; + } + int n = sub.length - 1; + int from = op.behind ? pos - n : pos; + if (from < 0 || from + n > (op.behind ? pos : endpos)) { + return false; + } + for (int q = 0; q < n; q++) { + if (!one(sub[q], t.at(from + q))) { + return false; + } + } + return true; + } + private static boolean one(Op op, int c) { switch (op.k) { case CHAR: return c == op.c; case CHARI: - return c == op.c || c == op.c2 || TypeMethods.mapCase(str(c), 0).equals(op.lower); + if (c == op.c || c == op.c2) { + return true; + } + if (c < 128) { + // An ASCII char lowers to one ASCII char, which equals the + // pattern's lower case form only when that form is this + // one code point; no strings are made to find out. + return (c >= 'A' && c <= 'Z' ? c + 32 : c) == op.c; + } + return TypeMethods.mapCase(str(c), 0).equals(op.lower); case ANY: return c != '\n'; case ANYALL: @@ -384,6 +739,87 @@ private static boolean one(Op op, int c) { default: break; } + if (c < 128) { + return table(op)[c]; + } + return set(op, c); + } + + /// The ASCII answers of a SET-like op (see [Op#full]), or null for one + /// of the kinds [#one] answers directly. + private static boolean[] table(Op op) { + switch (op.k) { + case CHAR: + case CHARI: + case ANY: + case ANYALL: + case AT: + return null; + default: + break; + } + boolean[] f = op.full; + if (f == null) { + f = new boolean[128]; + for (int i = 0; i < 128; i++) { + f[i] = set(op, i); + } + op.full = f; + } + return f; + } + + /// How far from `pos` (up to `limit`) the chars all match `op`. + private static int span(Op op, Text t, int pos, int limit) { + int j = pos; + boolean[] f = t.cps == null ? table(op) : null; + if (f != null) { + // The common case, a \s+ or [^<]*: the string read directly, an + // ASCII char answered by one load. + String s = t.s; + while (j < limit) { + char c = s.charAt(j); + if (c < 128 ? !f[c] : !set(op, c)) { + break; + } + j++; + } + return j; + } + if (t.cps == null) { + // The kinds with no table, on the string itself: `.*` is a search + // for the next line end and a repeated literal a run of one char. + String s = t.s; + if (op.k == ANYALL) { + return limit; + } + if (op.k == ANY) { + if (limit == s.length()) { + int nl = s.indexOf('\n', j); + return nl < 0 ? limit : nl; + } + // A bounded repeat is walked: a search would read on to a line + // end that may be the whole text away, once per attempt. + while (j < limit && s.charAt(j) != '\n') { + j++; + } + return j; + } + if (op.k == CHAR) { + int c = op.c; + while (j < limit && s.charAt(j) == c) { + j++; + } + return j; + } + } + while (j < limit && one(op, t.at(j))) { + j++; + } + return j; + } + + private static boolean set(Op op, int c) { boolean r = c < 128 ? op.ascii[c] : java.util.Arrays.binarySearch(op.chars, c) >= 0; if (!r && op.ranges.length > 0) { r = inRanges(op.ranges, c); @@ -439,6 +875,13 @@ private static boolean at(int kind, Text t, int pos, int endpos, boolean unicode /// `_cn1re.run(prog, text, pos, endpos, mode, forbid)`. Called once per /// match attempt with all six arguments, so it takes them directly /// rather than as the argument array a [PyBuiltin] would build. + private static Prog prog(Object o) { + if (!(o instanceof Prog)) { + throw Py.typeError("_cn1re needs a compiled program"); + } + return (Prog) o; + } + private static final class RunFn extends PyObject { @Override public PyType type() { @@ -476,6 +919,78 @@ public String repr() { } } + /// `_cn1re.match(prog, pattern, string, pos, endpos, mode)`: see [RegexMatch]. + /// `self._prog` of a `re.Pattern`, read through one cached site. + private static final AttrSite PROG = new AttrSite("_prog"); + + /// `re.Pattern.match`/`fullmatch`/`search` themselves, stored on the + /// class: `pattern.match(s)` is then one call into Java with the pattern + /// prepended, with no Python frame between, as sre's methods are C. + private static PyBuiltin patternMethod(final String name, final int mode) { + return new PyBuiltin(name, (a, kw) -> { + Object string = null; + Object pos = 0L; + Object end = Py.NONE; + int np = a.length - kw.length; + if (np < 1 || np > 4) { + throw Py.typeError("Pattern." + name + "() takes from 1 to 3 positional arguments but " + + (np - 1) + " were given"); + } + if (np > 1) { + string = a[1]; + } + if (np > 2) { + pos = a[2]; + } + if (np > 3) { + end = a[3]; + } + for (int i = 0; i < kw.length; i++) { + Object v = a[np + i]; + if ("string".equals(kw[i]) && np <= 1) { + string = v; + } else if ("pos".equals(kw[i]) && np <= 2) { + pos = v; + } else if ("endpos".equals(kw[i]) && np <= 3) { + end = v; + } else { + throw Py.typeError("Pattern." + name + "() got an unexpected keyword argument '" + kw[i] + "'"); + } + } + if (string == null) { + throw Py.typeError("Pattern." + name + "() missing required argument 'string' (pos 1)"); + } + return RegexMatch.match(PROG.get(a[0]), a[0], string, pos, end, mode); + }).with2((self, string) -> RegexMatch.match(PROG.get(self), self, string, 0L, Py.NONE, mode)) + .with3((self, string, pos) -> RegexMatch.match(PROG.get(self), self, string, pos, Py.NONE, mode)) + .with4((self, string, pos, end) -> RegexMatch.match(PROG.get(self), self, string, pos, end, mode)); + } + + private static final class MatchFn extends PyObject { + @Override + public PyType type() { + return Py.BUILTIN_TYPE; + } + + @Override + public Object call6(Object prog, Object pattern, Object string, Object pos, Object endpos, Object mode) { + return RegexMatch.match(prog, pattern, string, pos, endpos, (int) Py.index(mode)); + } + + @Override + public Object call(Object[] args, String[] kwNames) { + if (args.length != 6 || kwNames.length != 0) { + throw Py.typeError("_cn1re.match() takes exactly 6 positional arguments"); + } + return call6(args[0], args[1], args[2], args[3], args[4], args[5]); + } + + @Override + public String repr() { + return ""; + } + } + // ---- the machine ----------------------------------------------------- /// A growable int stack: the trail holds (register, old value) pairs and @@ -483,31 +998,80 @@ public String repr() { private static final class Ints { int[] a = NO_INTS; int n; + /// What a lookaround or atomic group run from this stack's exec works + /// in: its copy of the registers and its own two stacks, kept here + /// rather than allocated per attempt. A lookbehind in a searched + /// pattern is tried at every position. The inner run is over before + /// the outer one goes on, so one set per nesting level serves all of + /// them; a nested one hangs off the inner stack the same way. + private int[] subRegs = NO_INTS; + private Ints subStack; + private Ints subTrail; + + int[] inner(int[] regs) { + int[] r = subRegs; + if (r.length != regs.length) { + r = new int[regs.length]; + subRegs = r; + } + System.arraycopy(regs, 0, r, 0, regs.length); + return r; + } + + Ints subStack() { + Ints x = subStack; + if (x == null) { + x = new Ints(); + subStack = x; + } + return x; + } + + Ints subTrail() { + Ints x = subTrail; + if (x == null) { + x = new Ints(); + subTrail = x; + } + return x; + } - void push(int v) { - if (n == a.length) { - int[] b = new int[n == 0 ? 24 : n * 2]; + /// The array with room for `need` entries in all; grown when short. + int[] room(int need) { + int[] b = a; + if (need > b.length) { + int cap = b.length == 0 ? 24 : b.length * 2; + b = new int[cap < need ? need : cap]; System.arraycopy(a, 0, b, 0, n); a = b; } - a[n++] = v; + return b; } } private static final int FRAME = 6; + // A choice frame is six ints and a trail entry two, written at once after + // one capacity check: one call per push made these the engine's hottest + // lines, several per character a repeat gives back. private static void choice(Ints st, int kind, int x, int y, int z, int w, int v) { - st.push(kind); - st.push(x); - st.push(y); - st.push(z); - st.push(w); - st.push(v); + int n = st.n; + int[] a = st.room(n + FRAME); + a[n] = kind; + a[n + 1] = x; + a[n + 2] = y; + a[n + 3] = z; + a[n + 4] = w; + a[n + 5] = v; + st.n = n + FRAME; } - private static void log(Ints trail, int[] regs, int n) { - trail.push(n); - trail.push(regs[n]); + private static void log(Ints trail, int[] regs, int r) { + int n = trail.n; + int[] a = trail.room(n + 2); + a[n] = r; + a[n + 1] = regs[r]; + trail.n = n + 2; } /// Runs `prog` from `start`; the end position, or -1. @@ -552,10 +1116,18 @@ private static int exec(Op[] prog, Text t, int start, int endpos, int[] regs, bo continue; case SAVE: { int n = op.a; - log(trail, regs, n); + // With no choice point open nothing can restore a + // register, so the old value is not kept: markdownify's + // `^(\n*)((?:.*[^\n])?)(\n*)$` logged six per child. + boolean undo = stack.n != 0; + if (undo) { + log(trail, regs, n); + } regs[n] = pos; if ((n & 1) != 0) { - log(trail, regs, li); + if (undo) { + log(trail, regs, li); + } regs[li] = n >> 1; } pc++; @@ -563,10 +1135,7 @@ private static int exec(Op[] prog, Text t, int start, int endpos, int[] regs, bo } case REPEAT_ONE: { int limit = op.hi < 0 ? endpos : Math.min(endpos, pos + op.hi); - int j = pos; - while (j < limit && one(op.one, t.at(j))) { - j++; - } + int j = span(op.one, t, pos, limit); if (j - pos < op.lo) { ok = false; break; @@ -612,7 +1181,9 @@ private static int exec(Op[] prog, Text t, int start, int endpos, int[] regs, bo return pos; case MARK: { int n = li + 1 + op.a; - log(trail, regs, n); + if (stack.n != 0) { + log(trail, regs, n); + } regs[n] = pos; pc++; continue; @@ -640,13 +1211,21 @@ private static int exec(Op[] prog, Text t, int start, int endpos, int[] regs, bo pc = regs[2 * op.a] >= 0 && regs[2 * op.a + 1] >= 0 ? pc + 1 : op.b; continue; case LOOK: { - int[] inner = copy(regs); + if (op.simple) { + if (lookHit(op, t, pos, endpos) != op.neg) { + pc++; + continue; + } + ok = false; + break; + } + int[] inner = stack.inner(regs); int end; if (op.behind) { int s = pos - op.width; - end = s < 0 ? -1 : exec(op.sub, t, s, pos, inner, true, -1, li, new Ints(), new Ints()); + end = s < 0 ? -1 : exec(op.sub, t, s, pos, inner, true, -1, li, stack.subStack(), stack.subTrail()); } else { - end = exec(op.sub, t, pos, endpos, inner, false, -1, li, new Ints(), new Ints()); + end = exec(op.sub, t, pos, endpos, inner, false, -1, li, stack.subStack(), stack.subTrail()); } if (op.neg) { if (end < 0) { @@ -660,18 +1239,18 @@ private static int exec(Op[] prog, Text t, int start, int endpos, int[] regs, bo ok = false; break; } - adopt(regs, inner, trail); + adopt(regs, inner, stack.n != 0 ? trail : null); pc++; continue; } case ATOMIC: { - int[] inner = copy(regs); - int end = exec(op.sub, t, pos, endpos, inner, false, -1, li, new Ints(), new Ints()); + int[] inner = stack.inner(regs); + int end = exec(op.sub, t, pos, endpos, inner, false, -1, li, stack.subStack(), stack.subTrail()); if (end < 0) { ok = false; break; } - adopt(regs, inner, trail); + adopt(regs, inner, stack.n != 0 ? trail : null); pos = end; pc++; continue; @@ -763,16 +1342,13 @@ private static String slice(Text t, int a, int n) { return sb.toString(); } - private static int[] copy(int[] regs) { - int[] r = new int[regs.length]; - System.arraycopy(regs, 0, r, 0, regs.length); - return r; - } - + /// `trail` is null when no choice point could restore the registers. private static void adopt(int[] regs, int[] inner, Ints trail) { for (int n = 0; n < regs.length; n++) { if (regs[n] != inner[n]) { - log(trail, regs, n); + if (trail != null) { + log(trail, regs, n); + } regs[n] = inner[n]; } } @@ -808,25 +1384,412 @@ private static int find(Text t, String prefix, int start, int endpos) { return -1; } + /// The first position at or after `start` whose character one of + /// `first` matches, or -1: every match consumes a character first. + private static int skip(Op[] first, Prog p, Text t, int start, int endpos) { + if (first.length == 1 && t.cps == null && first[0].k == CHAR && endpos == t.s.length()) { + return t.s.indexOf(first[0].c, start); + } + if (t.cps == null) { + // One merged table for every class the match can begin with, + // and the assertions (`(\s|^)`) asked only where it says no. + boolean[] f = p.firstAscii; + boolean ats = p.firstAt; + String s = t.s; + for (int i = start; i <= endpos; i++) { + if (i < endpos) { + char c = s.charAt(i); + if (c < 128 ? f[c] : anyFirst(first, c)) { + return i; + } + } else if (!ats) { + return -1; + } + if (ats) { + for (Op op : first) { + if (op.k == AT && at(op.at, t, i, endpos, op.unicode)) { + return i; + } + } + } + } + return -1; + } + for (int i = start; i <= endpos; i++) { + int c = i < endpos ? t.at(i) : -1; + for (Op op : first) { + if (op.k == AT) { + if (at(op.at, t, i, endpos, op.unicode)) { + return i; + } + } else if (c >= 0 && (op.k == CHAR ? c == op.c : one(op, c))) { + return i; + } + } + } + return -1; + } + + /// Whether a char-consuming op of `first` matches the non-ASCII `c`. + private static boolean anyFirst(Op[] first, int c) { + for (Op op : first) { + if (op.k != AT && one(op, c)) { + return true; + } + } + return false; + } + /// `_engine.run`: mode 0 matches, 1 fully matches, 2 searches. The /// group registers then `lastindex`, or `NO_MATCH`. static int[] run(Prog p, String text, int pos, int endpos, int mode, int forbid) { - Scratch sc = p.scratch.getAndSet(null); - if (sc == null) { - sc = new Scratch(); - } + return run(p, text, -1, pos, endpos, mode, forbid); + } + + /// [#run] for a text whose surrogate pair count the caller already took. + static int[] run(Prog p, String text, int pairs, int pos, int endpos, int mode, int forbid) { + Scratch sc = acquire(p); try { + sc.text.reset(text, pairs); return run(p, sc, text, pos, endpos, mode, forbid); } finally { - sc.text.s = null; - sc.text.cps = null; - p.scratch.set(sc); + release(p, sc); + } + } + + /// The pattern's scratch, held by one loop over one text: a loop that + /// runs once per match keeps it, so the text is prepared once. + private static Scratch acquire(Prog p) { + Scratch sc = p.scratch; + p.scratch = null; + return sc == null ? new Scratch() : sc; + } + + private static void release(Prog p, Scratch sc) { + sc.text.s = null; + sc.text.cps = null; + sc.needValid = false; + p.scratch = sc; + } + + /// `pattern.subn(template, text, count)` with the loop in Java: `template` + /// is a list of literal strings and group numbers, as re's + /// `_compile_template` makes it. No Match object is made per match -- + /// the Python loop made one, and a generator step, for each. + static Object subn(Prog p, String text, PyList template, int count) { + Scratch sc = acquire(p); + try { + // Counted once here; the runs below find the text already set. + Text tx = sc.text; + tx.reset(text); + int n = tx.cps == null ? text.length() : tx.cps.length; + int[] regs = count >= 0 ? run(p, sc, text, 0, n, 2, -1, true) : NO_MATCH; + if (regs.length == 0) { + return Py.tuple(text, Long.valueOf(0)); + } + return subnLoop(p, sc, text, n, regs, template, count); + } finally { + release(p, sc); + } + } + + /// The replacing loop, outside the caller's try/finally: javac parks a + /// value returned from inside a try in a spare local, and when that slot + /// is the builder's the translator rightly keeps the builder on the + /// heap, where every append takes its lock. + private static Object subnLoop(Prog p, Scratch sc, String text, int n, int[] first, PyList template, int count) { + int[] regs = first; + // Made once, after the first match, and never reassigned: ParparVM + // keeps a builder on the stack only when its local holds nothing + // else and only StringBuilder methods receive it (no helper), and one + // on the heap pays a lock on every append. A builder also keeps a + // Latin-1 text Latin-1, which a char array would widen. Without + // surrogates a code point index is the char index, so the pieces are + // appended straight from the text instead of as substrings. + StringBuilder out = new StringBuilder(text.length() + 16); + boolean plain = n == text.length(); + int parts = template.size(); + int last = 0; + int done = 0; + while (true) { + int s = regs[0]; + int e = regs[1]; + if (plain) { + out.append(text, last, s); + } else { + out.append(cut(sc.text, last, s)); + } + for (int k = 0; k < parts; k++) { + Object part = template.get(k); + if (part instanceof String) { + out.append((String) part); + } else { + int g = (int) Py.index(part); + int gs = regs[2 * g]; + int ge = regs[2 * g + 1]; + if (gs >= 0 && ge >= 0) { + if (plain) { + out.append(text, gs, ge); + } else { + out.append(cut(sc.text, gs, ge)); + } + } + } + } + last = e; + done++; + if (e > n || count != 0 && done >= count) { + break; + } + regs = run(p, sc, text, e, n, 2, s == e ? e : -1, true); + if (regs.length == 0) { + break; + } + } + if (plain) { + out.append(text, last, n); + } else { + out.append(cut(sc.text, last, n)); + } + return Py.tuple(out.toString(), Long.valueOf(done)); + } + + /// `pattern.subn(fn, text, count)` for a callable `fn`, with the loop in + /// Java: one Match per match handed to `fn`, as sre does, and no generator + /// step, piece list or join around it. markdownify indents every quoted + /// line through `re_line_with_content.sub(fn, text)`. As in sre, `fn` + /// answering None adds nothing, and anything but a str is a TypeError. + static Object subCall(Prog p, Object pattern, String text, Object fn, int count) { + return subCall(p, pattern, null, text, fn, count); + } + + /// [#subCall] over a bytes subject's Latin-1 `text`: the callable gets + /// bytes matches and returns bytes. + static Object subCall(Prog p, Object pattern, PyBytes subject, String text, Object fn, int count) { + Scratch sc = acquire(p); + try { + // Counted once here; the runs below find the text already set. + Text tx = sc.text; + tx.reset(text); + int n = tx.cps == null ? text.length() : tx.cps.length; + int[] regs = count >= 0 ? run(p, sc, text, 0, n, 2, -1) : new int[0]; + if (regs.length == 0) { + return Py.tuple(text, Long.valueOf(0)); + } + return subCallLoop(p, sc, pattern, subject, text, n, regs, fn, count); + } finally { + release(p, sc); + } + } + + /// The replacing loop, outside the caller's try/finally: javac parks a + /// value returned from inside a try in a spare local, and when that slot + /// is the builder's the translator rightly keeps the builder on the + /// heap, where every append takes its lock. + private static Object subCallLoop(Prog p, Scratch sc, Object pattern, PyBytes subject, String text, int n, int[] first, + Object fn, int count) { + int[] regs = first; + StringBuilder out = new StringBuilder(text.length() + 16); + boolean plain = n == text.length(); + PyObject f = Py.obj(fn); + int last = 0; + int done = 0; + while (true) { + int s = regs[0]; + int e = regs[1]; + if (plain) { + out.append(text, last, s); + } else { + out.append(cut(sc.text, last, s)); + } + // The callable may run this same pattern; it then builds its + // own scratch, since this one is taken. + Object r = f.call1(new RegexMatch(pattern, subject != null ? subject : text, text, subject != null, 0, n, + p.groups, regs)); + if (subject != null) { + if (!(r instanceof PyBytes)) { + throw Py.typeError("expected a bytes-like object, " + Py.typeOf(r).name + " found"); + } + byte[] v = ((PyBytes) r).value; + out.append(Codecs.latin1(v, 0, v.length)); + } else if (r instanceof String) { + out.append((String) r); + } else if (r != Py.NONE) { //NOPMD CompareObjectsWithEquals - None is a singleton + throw Py.typeError("expected str instance, " + Py.typeOf(r).name + " found"); + } + last = e; + done++; + if (e > n || count != 0 && done >= count) { + break; + } + regs = run(p, sc, text, e, n, 2, s == e ? e : -1); + if (regs.length == 0) { + break; + } + } + if (plain) { + out.append(text, last, n); + } else { + out.append(cut(sc.text, last, n)); + } + return Py.tuple(out.toString(), Long.valueOf(done)); + } + + /// `pattern.findall(text, pos, endpos)` with the loop in Java: the whole + /// match, the one group, or a tuple of groups, an unmatched group as "". + static Object findall(Prog p, String text, int pos, int endpos) { + Scratch sc = acquire(p); + try { + PyList out = Py.list(); + int at = pos; + int forbid = -1; + while (at <= endpos) { + int[] regs = run(p, sc, text, at, endpos, 2, forbid, true); + if (regs.length == 0) { + break; + } + if (p.groups == 0) { + out.append(cut(sc.text, regs[0], regs[1])); + } else if (p.groups == 1) { + out.append(group(sc.text, regs, 1)); + } else { + Object[] g = new Object[p.groups]; + for (int k = 0; k < g.length; k++) { + g[k] = group(sc.text, regs, k + 1); + } + out.append(Py.tuple(g)); + } + int s = regs[0]; + int e = regs[1]; + forbid = s == e ? e : -1; + at = e; + } + return out; + } finally { + release(p, sc); + } + } + + /// `pattern.split(text, maxsplit)` for a str, with the loop in Java as + /// sre's is C: no generator step and no Match per piece. An unmatched + /// group is None here, where findall makes it "". + static Object split(Prog p, String text, int maxsplit) { + PyList out = Py.list(); + if (maxsplit < 0) { + out.append(text); + return out; + } + Scratch sc = acquire(p); + try { + Text t = sc.text; + t.reset(text); + int endpos = t.cps == null ? text.length() : t.cps.length; + int at = 0; + int last = 0; + int forbid = -1; + int n = 0; + while (at <= endpos && (maxsplit == 0 || n < maxsplit)) { + int[] regs = run(p, sc, text, at, endpos, 2, forbid, true); + if (regs.length == 0) { + break; + } + int st = regs[0]; + int e = regs[1]; + out.append(cut(t, last, st)); + for (int k = 1; k <= p.groups; k++) { + int gs = regs[2 * k]; + int ge = regs[2 * k + 1]; + out.append(gs < 0 || ge < 0 ? Py.NONE : cut(t, gs, ge)); + } + last = e; + forbid = st == e ? e : -1; + at = e; + n++; + } + out.append(cut(t, last, endpos)); + return out; + } finally { + release(p, sc); + } + } + + /// A search for a [Prog#solo] program over a text with no surrogate + /// pair. Every match is non-empty, so the caller's `forbid` (an empty + /// match not to repeat) never rejects one. + private static int[] solo(Op op, Op[] first, Prog p, Scratch sc, Text t, int pos, int endpos, boolean keep) { + int start = pos; + int end = -1; + while (start < endpos) { + start = skip(first, p, t, start, endpos); + if (start < 0 || start >= endpos) { + return NO_MATCH; + } + if (op.k != REPEAT_ONE) { + end = start + 1; + break; + } + int limit = op.hi < 0 ? endpos : Math.min(endpos, start + op.hi); + int j = span(op.one, t, start, limit); + if (j - start >= op.lo) { + end = j; + break; + } + // Every later start inside this run has a shorter one. + start = j > start ? j : start + 1; } + if (end < 0) { + return NO_MATCH; + } + int[] regs; + if (keep) { + if (sc.regs.length != 3) { + sc.regs = new int[3]; + } + regs = sc.regs; + } else { + regs = new int[3]; + } + regs[0] = start; + regs[1] = end; + regs[2] = -1; + return regs; + } + + private static String group(Text t, int[] regs, int g) { + int s = regs[2 * g]; + int e = regs[2 * g + 1]; + return s < 0 || e < 0 ? "" : cut(t, s, e); + } + + /// Code points `from` to `to` of the run's text. The text was measured + /// when it was set (`cps` is null when it has no surrogate pair), so a + /// piece is a plain substring; PyStr.substr counted the pairs again for + /// every piece. + private static String cut(Text t, int from, int to) { + return t.cps == null ? t.s.substring(from, to) : PyStr.substr(t.s, from, to); } private static int[] run(Prog p, Scratch sc, String text, int pos, int endpos, int mode, int forbid) { + return run(p, sc, text, pos, endpos, mode, forbid, false); + } + + /// The run itself. With `keep` the registers are answered in the + /// scratch's own array, valid until the next run: a loop that reads + /// them before running again (sub, split, findall) made one array per + /// match. Its last slot is then not `lastindex`. + private static int[] run(Prog p, Scratch sc, String text, int pos, int endpos, int mode, int forbid, + boolean keep) { Text t = sc.text; t.reset(text); + Op needOp = p.need; + if (mode == 2 && needOp != null && t.cps == null && !needed(needOp, p.needAscii, sc, text, pos, endpos)) { + return NO_MATCH; + } + Op solo = p.solo; + Op[] first = p.first; + if (mode == 2 && solo != null && first != null && t.cps == null) { + return solo(solo, first, p, sc, t, pos, endpos, keep); + } int size = 2 * (p.groups + 1); boolean full = mode == 1; int start = pos; @@ -844,12 +1807,20 @@ private static int[] run(Prog p, Scratch sc, String text, int pos, int endpos, i return NO_MATCH; } start = found; + } else if (mode == 2 && p.first != null) { + start = skip(p.first, p, t, start, endpos); + if (start < 0) { + return NO_MATCH; + } } java.util.Arrays.fill(regs, -1); int end = exec(p.ops, t, start, endpos, regs, full, forbid, size, stack, trail); if (end >= 0) { regs[0] = start; regs[1] = end; + if (keep) { + return regs; + } int[] out = new int[size + 1]; System.arraycopy(regs, 0, out, 0, size + 1); return out; diff --git a/maven/python-runtime/src/main/java/com/codename1/python/runtime/RegexMatch.java b/maven/python-runtime/src/main/java/com/codename1/python/runtime/RegexMatch.java new file mode 100644 index 00000000000..b097ae4f1d6 --- /dev/null +++ b/maven/python-runtime/src/main/java/com/codename1/python/runtime/RegexMatch.java @@ -0,0 +1,475 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.python.runtime; + +/// `re.Match`, and the one call `Pattern.match`, `search` and `fullmatch` +/// make: `_cn1re.match(prog, pattern, string, pos, endpos, mode)`. sre does +/// both in C. As Python they were five frames per call (`match`, `_run`, +/// `_check`, the engine wrapper, the program lookup), a list of boxed +/// registers, and a Match whose constructor walked `groupindex` and whose +/// `group(1)` went through two isinstance checks: three to five times +/// CPython's cost for a call that matches three characters. +final class RegexMatch extends PyObject { + static final PyType TYPE = new PyType("Match", new PyType[] {Py.OBJECT_TYPE}, null); + + private final Object pattern; + private final Object string; + private final String text; + private final boolean bytes; + private final int pos; + private final int endpos; + private final int groups; + /// Two per group, group 0 first, then `lastindex` (0 for none). + private final int[] regs; + + RegexMatch(Object pattern, Object string, String text, boolean bytes, int pos, int endpos, + int groups, int[] regs) { + this.pattern = pattern; + this.string = string; + this.text = text; + this.bytes = bytes; + this.pos = pos; + this.endpos = endpos; + this.groups = groups; + this.regs = regs; + } + + @Override + public PyType type() { + return TYPE; + } + + /// `_cn1re.match`: None or a Match. `endpos` may be None. + static Object match(Object progObj, Object pattern, Object string, Object posObj, Object endObj, + int mode) { + if (!(progObj instanceof Regex.Prog)) { + throw Py.typeError("_cn1re.match() needs a compiled program"); + } + Regex.Prog p = (Regex.Prog) progObj; + return search(p, pattern, string, posObj, endObj, -1, mode, -1); + } + + /// The shared body of a match and of one step of `finditer`: `at` is where + /// the attempt starts (-1 for `pos`), `forbid` an end an empty match may + /// not have. + static Object search(Regex.Prog p, Object pattern, Object string, Object posObj, Object endObj, + int at, int mode, int forbid) { + Object subject = subject(string); + boolean isBytes = checkKind(p, pattern, subject); + String text = isBytes ? latin1((PyBytes) subject) : (String) subject; + // Counted once: the run below is handed the count rather than + // taking it again (a decoded bytes text is Latin-1, without pairs). + int pairs = isBytes ? 0 : PyStr.surrogates(text); + int n = text.length() - pairs; + long pos = Py.index(posObj); + long endpos = endObj == Py.NONE ? n : Py.index(endObj); //NOPMD CompareObjectsWithEquals - None is a singleton + if (endpos > n) { + endpos = n; + } + if (endpos < 0) { + endpos = 0; + } + if (pos < 0) { + pos = 0; + } + if (pos > endpos) { + return Py.NONE; + } + int start = at < 0 ? (int) pos : at; + if (start > endpos) { + return Py.NONE; + } + int[] regs = Regex.run(p, text, pairs, start, (int) endpos, mode, forbid); + if (regs.length == 0) { + return Py.NONE; + } + return new RegexMatch(pattern, string, text, isBytes, (int) pos, (int) endpos, p.groups, regs); + } + + /// The str or bytes a subject is: a str or bytes subclass (bs4's + /// NavigableString) by its value, a bytearray or memoryview by a copy of + /// its bytes, as sre's `getstring` reads any buffer. Anything else is + /// answered as it is, for the kind check to name. + private static Object subject(Object string) { + if (string instanceof String || string instanceof PyBytes) { + return string; + } + if (string instanceof PyInstance) { + Object base = ((PyInstance) string).base; + if (base instanceof String || base instanceof PyBytes) { + return base; + } + } + if (string instanceof PyByteArray || string instanceof PyMemoryView) { + return new PyBytes(PyBytes.like(string)); + } + return string; + } + + /// True for bytes. A str pattern takes only str and a bytes one only + /// bytes, as sre's `getstring` insists; which one a program is was fixed + /// when it was compiled, so the pattern is asked once. + private static boolean checkKind(Regex.Prog p, Object pattern, Object string) { + int kind = p.kind; + if (kind == 0) { + kind = Py.getattr(pattern, "pattern") instanceof String ? 1 : 2; + p.kind = kind; + } + if (kind == 1) { + if (!(string instanceof String)) { + if (string instanceof PyBytes) { + throw Py.typeError("cannot use a string pattern on a bytes-like object"); + } + throw Py.typeError("expected string or bytes-like object, got '" + + Py.typeOf(string).name + "'"); + } + return false; + } + if (string instanceof String) { + throw Py.typeError("cannot use a bytes pattern on a string-like object"); + } + if (!(string instanceof PyBytes)) { + throw Py.typeError("expected string or bytes-like object, got '" + + Py.typeOf(string).name + "'"); + } + return true; + } + + /// The last bytes object decoded and its text. A tokenizer (pdfminer's) + /// searches one buffer from position after position; decoding all of it + /// on every call made a PDF slower than the Python wrapper was. Bytes are + /// immutable, so identity is enough. Python runs under the [Gil]. + private static PyBytes lastBytes; + private static String lastText; + + private static String latin1(PyBytes b) { + if (b == lastBytes) { //NOPMD CompareObjectsWithEquals - identity is meant + return lastText; + } + byte[] v = b.value; + String t = Codecs.latin1(v, 0, v.length); + if (v.length <= 64) { + // A short subject costs less to convert than to remember, and + // remembering it would evict the long one: psparser alternates + // `NONSPC.search(self.buf, i)` with subs over each hex token, and + // every token converted the whole buffer again. + return t; + } + lastBytes = b; + lastText = t; + return t; + } + + // ---- groups ------------------------------------------------------------ + + private int index(Object g) { + if (g instanceof Long) { + long i = ((Long) g).longValue(); + if (i >= 0 && i <= groups) { + return (int) i; + } + } else if (g instanceof String) { + Object idx = groupindex().getOrNull(g); + if (idx != null) { + return (int) Py.index(idx); + } + } else if (Py.isInt(g)) { + long i = Py.asLong(g); + if (i >= 0 && i <= groups) { + return (int) i; + } + } + throw Py.indexError("no such group"); + } + + private PyDict groupindex() { + Object d = Py.getattr(pattern, "groupindex"); + if (!(d instanceof PyDict)) { + throw Py.typeError("Pattern.groupindex is not a dict"); + } + return (PyDict) d; + } + + private Object get(int idx, Object dflt) { + int s = regs[2 * idx]; + int e = regs[2 * idx + 1]; + if (s < 0 || e < 0) { + return dflt; + } + if (bytes) { + // Cut from the latin-1 text, one char per byte, never from + // `string`: that is the subject as given, a bytearray or a bytes + // subclass as often as a bytes. + byte[] out = new byte[e - s]; + for (int k = 0; k < out.length; k++) { + out[k] = (byte) text.charAt(s + k); + } + return new PyBytes(out); + } + return PyStr.substr(text, s, e); + } + + private Object group(Object[] a) { + if (a.length == 1) { + return get(0, Py.NONE); + } + if (a.length == 2) { + return get(index(a[1]), Py.NONE); + } + Object[] out = new Object[a.length - 1]; + for (int i = 1; i < a.length; i++) { + out[i - 1] = get(index(a[i]), Py.NONE); + } + return new PyTuple(out); + } + + private Object groupsTuple(Object dflt) { + Object[] out = new Object[groups]; + for (int i = 0; i < groups; i++) { + out[i] = get(i + 1, dflt); + } + return new PyTuple(out); + } + + private Object span(int i) { + return Py.tuple(Py.of(regs[2 * i]), Py.of(regs[2 * i + 1])); + } + + private Object lastgroup() { + int last = regs[regs.length - 1]; + if (last <= 0) { + return Py.NONE; + } + PyDict gi = groupindex(); + Object found = Py.NONE; + for (Object k : gi.keyArray()) { + Object v = gi.getOrNull(k); + if (v != null && Py.index(v) == last) { + found = k; + } + } + return found; + } + + @Override + public Object getAttrOrNull(String name) { + switch (name) { + case "re": + return pattern; + case "string": + return string; + case "pos": + return Py.of(pos); + case "endpos": + return Py.of(endpos); + case "lastindex": { + int last = regs[regs.length - 1]; + return last > 0 ? Py.of(last) : Py.NONE; + } + case "lastgroup": + return lastgroup(); + case "regs": { + Object[] out = new Object[groups + 1]; + for (int i = 0; i <= groups; i++) { + out[i] = span(i); + } + return new PyTuple(out); + } + default: + return super.getAttrOrNull(name); + } + } + + @Override + public Object getItem(Object key) { + return get(index(key), Py.NONE); + } + + @Override + public String repr() { + return ""; + } + + /// `expand` needs the template compiler of `re`, which registers it here + /// when it is imported. Python runs under the [Gil], one thread at a time. + static Object expandHook; + /// `re._compile_template` and `Pattern._subn`, registered with it. + static Object templateHook; + static Object subHook; + static final int TEMPLATES = 64; + + /// `Pattern.sub` (`withCount` false) and `subn`: a str template over a + /// str runs entirely here; anything else (a callable, bytes) goes to + /// the general loop in Python. + static Object sub(Regex.Prog p, Object pattern, Object repl, Object string, Object countObj, + boolean withCount) { + if (repl instanceof String && string instanceof String && !checkKind(p, pattern, string)) { + java.util.HashMap cache = p.templates; + if (cache == null) { + cache = new java.util.HashMap(); + p.templates = cache; + } + PyList template = cache.get(repl); + if (template == null) { + if (templateHook == null) { + throw Py.runtimeError("re is not initialised"); + } + Object t = Py.obj(templateHook).call2(pattern, repl); + if (!(t instanceof PyList)) { + throw Py.typeError("re._compile_template did not return a list"); + } + template = (PyList) t; + if (cache.size() < TEMPLATES) { + cache.put((String) repl, template); + } + } + Object r = Regex.subn(p, (String) string, template, (int) Py.index(countObj)); + return withCount ? r : ((PyTuple) r).arr()[0]; + } + if (string instanceof String && !(repl instanceof String) && Builtins.isCallable(repl) + && !checkKind(p, pattern, string)) { + Object r = Regex.subCall(p, pattern, (String) string, repl, (int) Py.index(countObj)); + return withCount ? r : ((PyTuple) r).arr()[0]; + } + if (string instanceof PyBytes && checkKind(p, pattern, string)) { + // A bytes subject runs here too, over its Latin-1 text, as a + // bytes search does: pdfminer subs every hex string it reads. + String text = latin1((PyBytes) string); + Object r = null; + if (repl instanceof PyBytes) { + java.util.HashMap cache = p.byteTemplates; + if (cache == null) { + cache = new java.util.HashMap(); + p.byteTemplates = cache; + } + String key = latin1((PyBytes) repl); + PyList template = cache.get(key); + if (template == null && templateHook != null) { + template = textTemplate(Py.obj(templateHook).call2(pattern, repl)); + if (template != null && cache.size() < TEMPLATES) { + cache.put(key, template); + } + } + if (template != null) { + r = Regex.subn(p, text, template, (int) Py.index(countObj)); + } + } else if (Builtins.isCallable(repl)) { + r = Regex.subCall(p, pattern, (PyBytes) string, text, repl, (int) Py.index(countObj)); + } + if (r != null) { + Object[] items = ((PyTuple) r).arr(); + PyBytes out = new PyBytes(latin1Encode((String) items[0])); + return withCount ? Py.tuple(out, items[1]) : out; + } + } + if (subHook == null) { + throw Py.runtimeError("re is not initialised"); + } + Object r = Py.obj(subHook).call4(pattern, repl, string, countObj); + return withCount ? r : Py.obj(r).getItem(Long.valueOf(0)); + } + + /// A bytes template from `re._compile_template` with its literal parts + /// as Latin-1 text, the form [Regex#subn] takes; null for a part of + /// another kind, which the Python loop handles instead. + private static PyList textTemplate(Object t) { + if (!(t instanceof PyList)) { + return null; + } + PyList src = (PyList) t; + PyList out = Py.list(); + int n = src.size(); + for (int i = 0; i < n; i++) { + Object part = src.get(i); + if (part instanceof PyBytes) { + byte[] v = ((PyBytes) part).value; + out.append(Codecs.latin1(v, 0, v.length)); + } else if (part instanceof Long) { + out.append(part); + } else { + return null; + } + } + return out; + } + + /// The bytes of a text whose chars are all below 256 (a bytes subject's + /// Latin-1 text, with bytes put into it). + static byte[] latin1Encode(String s) { + int n = s.length(); + byte[] b = new byte[n]; + for (int i = 0; i < n; i++) { + b[i] = (byte) s.charAt(i); + } + return b; + } + + private static RegexMatch self(Object o) { + return (RegexMatch) o; + } + + static { + PyType t = TYPE; + t.define("group", PyBuiltin.method(t, "group", a -> self(a[0]).group(a)) + .with1(m -> self(m).get(0, Py.NONE)) + .with2((m, g) -> self(m).get(self(m).index(g), Py.NONE))); + t.define("__getitem__", PyBuiltin.method2(t, "__getitem__", (a0, a1) -> self(a0).getItem(a1)) + .with2((m, g) -> self(m).getItem(g))); + t.define("groups", PyBuiltin.method(t, "groups", + a -> self(a[0]).groupsTuple(a.length > 1 ? a[1] : Py.NONE)) + .with1(m -> self(m).groupsTuple(Py.NONE))); + t.define("groupdict", PyBuiltin.method(t, "groupdict", a -> { + RegexMatch m = self(a[0]); + Object dflt = a.length > 1 ? a[1] : Py.NONE; + PyDict gi = m.groupindex(); + PyDict out = new PyDict(); + for (Object k : gi.keyArray()) { + out.setItem(k, m.get((int) Py.index(gi.getOrNull(k)), dflt)); + } + return out; + })); + t.define("start", PyBuiltin.method(t, "start", + a -> Py.of(self(a[0]).regs[2 * (a.length > 1 ? self(a[0]).index(a[1]) : 0)])) + .with1(m -> Py.of(self(m).regs[0])) + .with2((m, g) -> Py.of(self(m).regs[2 * self(m).index(g)]))); + t.define("end", PyBuiltin.method(t, "end", + a -> Py.of(self(a[0]).regs[2 * (a.length > 1 ? self(a[0]).index(a[1]) : 0) + 1])) + .with1(m -> Py.of(self(m).regs[1])) + .with2((m, g) -> Py.of(self(m).regs[2 * self(m).index(g) + 1]))); + t.define("span", PyBuiltin.method(t, "span", + a -> self(a[0]).span(a.length > 1 ? self(a[0]).index(a[1]) : 0)) + .with1(m -> self(m).span(0)) + .with2((m, g) -> self(m).span(self(m).index(g)))); + t.define("expand", PyBuiltin.method2(t, "expand", (a0, a1) -> { + if (expandHook == null) { + throw Py.runtimeError("re is not initialised"); + } + return Py.obj(expandHook).call2(a0, a1); + })); + t.define("__copy__", PyBuiltin.method1(t, "__copy__", a0 -> a0)); + t.define("__deepcopy__", PyBuiltin.method1(t, "__deepcopy__", a0 -> a0)); + t.define("__class_getitem__", new PyClassMethod(PyBuiltin.fixed2("__class_getitem__", (a0, a1) -> new PyGenericAlias((PyType) a0, a1)))); + t.define("__module__", "re"); + } +} diff --git a/maven/python-runtime/src/main/java/com/codename1/python/runtime/Shape.java b/maven/python-runtime/src/main/java/com/codename1/python/runtime/Shape.java index 482e1c91926..159677f4470 100644 --- a/maven/python-runtime/src/main/java/com/codename1/python/runtime/Shape.java +++ b/maven/python-runtime/src/main/java/com/codename1/python/runtime/Shape.java @@ -33,10 +33,27 @@ /// object. That identity is what an `AttrSite` compares. final class Shape { static final Shape EMPTY = new Shape(new String[0]); + private static final int LINEAR = 6; final String[] names; private Shape[] next = new Shape[0]; + /// The transitions by the name each adds, once there are more than a scan + /// finds quickly. The empty shape is every class's starting point, so it + /// collects the first attribute of each class in the program: scanning that + /// list was paid by the first assignment of every instance made. + private java.util.HashMap byName; + + /// A number of its own, for the hashed caches of the store sites + /// ([StoreSite]). Python code runs on one thread at a time. + final int id = nextId(); + + private static int ids; + + private static int nextId() { + return ++ids; + } + private Shape(String[] names) { this.names = names; } @@ -63,12 +80,37 @@ int indexOf(String name) { /// This shape extended by `name`. Shape with(String name) { + String ln = lastName; + if (ln == name) { //NOPMD CompareObjectsWithEquals - identity is meant + return lastNext; + } + Shape r = find(name); + lastNext = r; + lastName = name; + return r; + } + + /// The last transition [#with] answered: most shapes are left by one name + /// only, the attribute every instance of one class sets next. Written + /// next before name, and read name first, so a stale pair is never + /// handed out on one thread; Python code here runs on one at a time. + private String lastName; + private Shape lastNext; + + private Shape find(String name) { Shape[] t = next; - for (Shape e : t) { - String last = e.names[names.length]; - if (last == name || last.equals(name)) { //NOPMD CompareObjectsWithEquals - identity is meant + if (byName != null) { + Shape e = byName.get(name); + if (e != null) { return e; } + } else { + for (Shape e : t) { + String last = e.names[names.length]; + if (last == name || last.equals(name)) { //NOPMD CompareObjectsWithEquals - identity is meant + return e; + } + } } String[] n = new String[names.length + 1]; System.arraycopy(names, 0, n, 0, names.length); @@ -78,6 +120,14 @@ Shape with(String name) { System.arraycopy(t, 0, grown, 0, t.length); grown[t.length] = s; next = grown; + if (byName != null) { + byName.put(name, s); + } else if (grown.length > LINEAR) { + byName = new java.util.HashMap(); + for (Shape e : grown) { + byName.put(e.names[names.length], e); + } + } return s; } } diff --git a/maven/python-runtime/src/main/java/com/codename1/python/runtime/StdModules.java b/maven/python-runtime/src/main/java/com/codename1/python/runtime/StdModules.java index ca893e833e8..61bd456cb77 100644 --- a/maven/python-runtime/src/main/java/com/codename1/python/runtime/StdModules.java +++ b/maven/python-runtime/src/main/java/com/codename1/python/runtime/StdModules.java @@ -49,6 +49,18 @@ static boolean provide(String name) { PyModule.registerModule(atexit()); return true; } + if ("_cn1imp".equals(name)) { + PyModule.registerModule(imp()); + return true; + } + if ("_cn1xml".equals(name)) { + PyModule.registerModule(XmlScan.module()); + return true; + } + if ("_cn1json".equals(name)) { + PyModule.registerModule(PyJson.module()); + return true; + } if ("_cn1re".equals(name)) { PyModule.registerModule(Regex.module()); return true; @@ -98,10 +110,66 @@ static boolean provide(String name) { PyModule.registerModule(thread()); return true; } + if ("_cn1obj".equals(name)) { + PyModule.registerModule(PyObjects.module()); + return true; + } + if ("_cn1hash".equals(name)) { + PyModule.registerModule(PyHashlib.module()); + return true; + } + if ("_cn1binascii".equals(name)) { + PyModule.registerModule(PyBinascii.module()); + return true; + } + if ("_cn1struct".equals(name)) { + PyModule.registerModule(PyStruct.module()); + return true; + } + if ("_cn1url".equals(name)) { + PyModule.registerModule(urlModule()); + return true; + } + if (Functools.provide(name)) { + return true; + } + if (HeapqBisect.provide(name)) { + return true; + } + if ("_cn1copy".equals(name)) { + PyModule m = new PyModule("_cn1copy", new String[0]); + m.setAttr("copy_state", PyBuiltin.positional("copy_state", a -> { + if (a.length != 4) { + throw Py.typeError("copy_state() takes 4 arguments"); + } + if (a[0] instanceof PyInstance && a[1] instanceof PyInstance) { + ((PyInstance) a[0]).copyStateInto((PyInstance) a[1], a[2], a[3] == Py.NONE ? null : a[3]); //NOPMD CompareObjectsWithEquals - None is a singleton + } + return Py.NONE; + })); + PyModule.registerModule(m); + return true; + } + if ("_cn1itertools".equals(name)) { + PyModule.registerModule(Itertools.module()); + return true; + } + if ("_cn1collections".equals(name)) { + PyModule.registerModule(PyCollections.module()); + return true; + } + if ("_cn1op".equals(name)) { + PyModule.registerModule(operatorModule()); + return true; + } if ("_cn1zlib".equals(name)) { PyModule.registerModule(PyZlib.module()); return true; } + if ("_cn1aes".equals(name)) { + PyModule.registerModule(PyAes.module()); + return true; + } if ("_cn1image".equals(name)) { PyModule.registerModule(PyImage.module()); return true; @@ -208,6 +276,115 @@ static String traceback(Throwable e) { return b.toString(); } + /// `sys._getframe(depth)`: the Python frame `depth` calls above the one + /// that asked, found on the Java stack as a traceback is. It holds what + /// libraries read of a frame -- `f_globals` (a snapshot of its module's + /// globals, as `globals()` is), `f_lineno`, `f_code.co_filename`, + /// `co_name` and `f_back` -- and no locals: a translated function keeps + /// them in Java variables. Without the build's line mapping there are no + /// Python frames, and every depth raises ValueError as one past the + /// outermost does in CPython. + static Object frame(int depth) { + StackTraceElement[] st = new Throwable().getStackTrace(); + java.util.List frames = new java.util.ArrayList(); + StackTraceElement previous = null; + for (StackTraceElement f : st) { + StackTraceElement callee = previous; + previous = f; + if (!pythonFrame(f)) { + continue; + } + String mn = f.getMethodName(); + if (mn != null && mn.startsWith("lambda$") && callee != null + && f.getClassName().equals(callee.getClassName()) + && !String.valueOf(callee.getMethodName()).startsWith("lambda$")) { + continue; + } + frames.add(f); + } + if (frames.isEmpty() && depth >= 0) { + PyModule running = PyModule.executing(); + if (running != null) { + return moduleFrame(running); + } + } + if (depth < 0 || depth >= frames.size()) { + throw Py.valueError("call stack is not deep enough"); + } + return frameObject(frames, depth); + } + + /// The frame `_getframe` answers where the trace has no Python frames at + /// all: a native ParparVM build records no frames for most methods, so + /// nothing says which function is running. Libraries read + /// `sys._getframe(n).f_globals` while a module body is running -- anyio's + /// lazy importer and `namedtuple`'s module lookup do -- to find the module + /// that called them, so the frame is that body's: the innermost module + /// being imported, at every depth. A call made later, from a function, + /// therefore sees the globals of whatever is importing (usually the main + /// module) and not its caller's; there is no line and no `f_back`. + private static Object moduleFrame(PyModule m) { + PyModule frame = new PyModule("frame", new String[0]); + PyModule code = new PyModule("code", new String[0]); + Object file = m.getAttrOrNull("__file__"); + code.setAttr("co_filename", file != null ? file : Py.str(m.name)); + code.setAttr("co_name", Py.str("")); + frame.setAttr("f_code", code); + frame.setAttr("f_lineno", PyInt.of(0)); + frame.setAttr("f_globals", m.getAttrOrNull("__dict__")); + frame.setAttr("f_locals", new PyDict()); + frame.setAttr("f_back", Py.NONE); + return frame; + } + + /// Whether `f` runs a module's Python code. On the JVM the build's line + /// mapping names the `.py` source; a native ParparVM trace carries no + /// source files (it names each frame `.java`), so there the + /// frame is Python when its class is a loaded module's class or one nested + /// in it (`PyModule.ofNativeClass`) -- which is what `f_globals`, the + /// attribute libraries read, needs. + private static boolean pythonFrame(StackTraceElement f) { + String file = f.getFileName(); + if (file != null && file.endsWith(".py")) { + return f.getLineNumber() > 0; + } + return file != null && file.endsWith(".java") && owner(f) != null; + } + + /// The module whose code `f` runs, on either kind of trace. + private static PyModule owner(StackTraceElement f) { + String cls = f.getClassName(); + if (cls == null) { + return null; + } + String file = f.getFileName(); + if (file != null && file.endsWith(".py")) { + return PyModule.ofClass(cls); + } + return cls.indexOf('.') < 0 ? PyModule.ofNativeClass(cls) : null; + } + + private static Object frameObject(java.util.List frames, int i) { + if (i >= frames.size()) { + return Py.NONE; + } + StackTraceElement f = frames.get(i); + PyModule owner = owner(f); + PyModule frame = new PyModule("frame", new String[0]); + PyModule code = new PyModule("code", new String[0]); + String file = f.getFileName(); + Object moduleFile = owner == null || file == null || file.endsWith(".py") ? null : owner.getAttrOrNull("__file__"); + code.setAttr("co_filename", moduleFile != null ? moduleFile : Py.str(file)); + String mn = f.getMethodName(); + code.setAttr("co_name", Py.str(mn == null || mn.startsWith("lambda$") || "exec".equals(mn) ? "" : mn)); + frame.setAttr("f_code", code); + frame.setAttr("f_lineno", PyInt.of(f.getLineNumber())); + frame.setAttr("f_globals", owner == null ? new PyDict() : owner.getAttrOrNull("__dict__")); + frame.setAttr("f_locals", new PyDict()); + frame.setAttr("f_back", i + 1 < frames.size() ? frameObject(frames, i + 1) : Py.NONE); + return frame; + } + public static void runExitHandlers() { while (!EXIT_CALLS.isEmpty()) { int last = EXIT_CALLS.size() - 1; @@ -246,9 +423,9 @@ private static PyModule gc() { })); m.setAttr("isenabled", PyBuiltin.positional("isenabled", a -> Py.bool(gcEnabled))); m.setAttr("get_count", PyBuiltin.positional("get_count", - a -> new PyTuple(new Object[] {PyInt.of(0), PyInt.of(0), PyInt.of(0)}))); + a -> Py.tuple(PyInt.of(0), PyInt.of(0), PyInt.of(0)))); m.setAttr("get_threshold", PyBuiltin.positional("get_threshold", - a -> new PyTuple(new Object[] {PyInt.of(700), PyInt.of(10), PyInt.of(10)}))); + a -> Py.tuple(PyInt.of(700), PyInt.of(10), PyInt.of(10)))); m.setAttr("set_threshold", new PyBuiltin("set_threshold", (args, kwNames) -> Py.NONE)); m.setAttr("freeze", PyBuiltin.positional("freeze", a -> Py.NONE)); m.setAttr("unfreeze", PyBuiltin.positional("unfreeze", a -> Py.NONE)); @@ -257,6 +434,17 @@ private static PyModule gc() { return m; } + /// `importlib`'s hooks into the module registry. Every module of a + /// translated program is compiled in and registered by name before + /// `__main__` runs, so importing by a name computed at run time is a + /// lookup, not a search of a path. + private static PyModule imp() { + PyModule m = new PyModule("_cn1imp", new String[0]); + m.setAttr("load", PyBuiltin.fixed1("load", a0 -> PyModule.load(Py.toStr(a0)))); + m.setAttr("available", PyBuiltin.fixed1("available", a0 -> PyModule.available(Py.toStr(a0)) ? Py.TRUE : Py.FALSE)); + return m; + } + private static PyModule atexit() { PyModule m = new PyModule("atexit", new String[0]); m.setAttr("register", new PyBuiltin("register", (args, kwNames) -> { @@ -272,9 +460,9 @@ private static PyModule atexit() { EXIT_KW.add(kwNames); return args[0]; })); - m.setAttr("unregister", PyBuiltin.positional("unregister", a -> { + m.setAttr("unregister", PyBuiltin.fixed1("unregister", a0 -> { for (int i = EXIT_CALLS.size() - 1; i >= 0; i--) { - if (Py.isTrue(Py.eq(EXIT_CALLS.get(i)[0], a[0]))) { + if (Py.isTrue(Py.eq(EXIT_CALLS.get(i)[0], a0))) { EXIT_CALLS.remove(i); EXIT_KW.remove(i); } @@ -308,8 +496,7 @@ private static PyModule weakref() { } m.setAttr("ref", t); m.setAttr("ReferenceType", t); - m.setAttr("referenceable", PyBuiltin.positional("referenceable", - a -> Py.bool(PyWeakRef.referenceable(a[0])))); + m.setAttr("referenceable", PyBuiltin.fixed1("referenceable", a0 -> Py.bool(PyWeakRef.referenceable(a0)))); return m; } @@ -328,6 +515,42 @@ private static int utcOffset(double t) { /// repeats when daylight time ends. static int utcOffset(java.util.TimeZone z, double t) { long ms = (long) Math.floor(t * 1000); + long second = ms >= 0 ? ms / 1000 : -((999 - ms) / 1000); + // The answer is the same for every instant of one second, and code + // that stamps things asks many times within one: an archive writer + // calls localtime(time()) for each entry. The calendar below asks the + // platform for the zone's rules three times over, which on a desktop + // reads the zone file each time. + OffsetAnswer last = lastOffset; + String id = z.getID(); + if (id == null) { + return utcOffsetOf(z, ms); + } + if (last != null && last.second == second && last.zone.equals(id)) { + return last.offset; + } + int offset = utcOffsetOf(z, ms); + lastOffset = new OffsetAnswer(id, second, offset); + return offset; + } + + /// The last answer of [#utcOffset], published whole so a second thread + /// reads either the old one or the new one. + private static final class OffsetAnswer { + final String zone; + final long second; + final int offset; + + OffsetAnswer(String zone, long second, int offset) { + this.zone = zone; + this.second = second; + this.offset = offset; + } + } + + private static OffsetAnswer lastOffset; + + private static int utcOffsetOf(java.util.TimeZone z, long ms) { java.util.Calendar c = java.util.Calendar.getInstance(z); c.setTime(new java.util.Date(ms)); long days = daysFromCivil(c.get(java.util.Calendar.YEAR), c.get(java.util.Calendar.MONTH) + 1, @@ -362,6 +585,64 @@ private static void fs(PyModule m, String name, final FsOp op) { })); } + /// Puts the read-only package data tree (`PyPackageData`) in front of the + /// file system's primitives: a path under `/cn1python/` is answered from + /// the application's bundled package data, and writing there fails as on + /// a read-only file system. + private static void packageData(PyModule m) { + final String[] reads = {"read", "exists", "isdir", "listdir", "size", "mtime"}; + final String[] writes = {"write", "mkdir", "remove", "rename"}; + for (final String name : reads) { + final Object next = m.getAttrOrNull(name); + m.setAttr(name, PyBuiltin.positional(name, a -> { + String path = Py.toStr(a[0]); + if (!PyPackageData.covers(path)) { + return Py.obj(next).call(a, Py.NO_KW); + } + if ("exists".equals(name)) { + return Py.bool(PyPackageData.exists(path)); + } + if ("isdir".equals(name)) { + return Py.bool(PyPackageData.isDirectory(path)); + } + if ("listdir".equals(name)) { + String[] names = PyPackageData.list(path); + if (names == null) { + throw Py.error(Py.OS_ERROR, "Not a directory: " + path); + } + Object[] r = new Object[names.length]; + for (int i = 0; i < names.length; i++) { + r[i] = Py.str(names[i]); + } + return new PyList(r); + } + if ("mtime".equals(name)) { + // The bundle records no times. The Unix epoch made + // zipfile refuse to archive a bundled file at all (ZIP + // headers start in 1980), so every entry is dated + // 1980-01-02 UTC: still 1980 in local time in every + // time zone, where 1980-01-01 is 1979 west of Greenwich. + return Py.ofFloat(315619200); + } + byte[] b = PyPackageData.read(path); + if (b == null) { + throw Py.error(Py.OS_ERROR, "No such file or directory: " + path); + } + return "size".equals(name) ? PyInt.of(b.length) : new PyBytes(b); + })); + } + for (final String name : writes) { + final Object next = m.getAttrOrNull(name); + m.setAttr(name, PyBuiltin.positional(name, a -> { + if (PyPackageData.covers(Py.toStr(a[0])) + || "rename".equals(name) && PyPackageData.covers(Py.toStr(a[1]))) { + throw Py.error(Py.OS_ERROR, "Read-only file system: " + Py.toStr(a[0])); + } + return Py.obj(next).call(a, Py.NO_KW); + })); + } + } + /// `_cn1fs`: the primitives `io` and `os` are written over. Paths are /// absolute; the Python side resolves them against the working /// directory and turns a missing file into the right exception. @@ -414,6 +695,7 @@ private static PyModule fileSystem() { }); fs(m, "size", (fs, a) -> PyInt.of(fs.size(Py.toStr(a[0])))); fs(m, "mtime", (fs, a) -> Py.ofFloat(fs.lastModified(Py.toStr(a[0])) / 1000.0)); + packageData(m); // The process environment, for os.environ. ParparVM's System.getenv() // map is empty (it cannot enumerate the environment), so `getenv` reads // one variable by name as well; the JVM answers both. @@ -429,8 +711,8 @@ private static PyModule fileSystem() { } return d; })); - m.setAttr("getenv", PyBuiltin.positional("getenv", a -> { - String v = System.getenv(Py.toStr(a[0])); + m.setAttr("getenv", PyBuiltin.fixed1("getenv", a0 -> { + String v = System.getenv(Py.toStr(a0)); return v == null ? Py.NONE : Py.str(v); })); return m; @@ -453,8 +735,8 @@ private static PyModule sql(String moduleName, boolean server) { PyModule m = new PyModule(moduleName, new String[0]); if (server) { m.setAttr("available", PyBuiltin.positional("available", a -> Py.bool(PyDb.get() != null))); - m.setAttr("dialect", PyBuiltin.positional("dialect", a -> { - PySql.Connection c = sqlConnection(a[0]); + m.setAttr("dialect", PyBuiltin.fixed1("dialect", a0 -> { + PySql.Connection c = sqlConnection(a0); return Py.str(c instanceof PyDb.Connection ? ((PyDb.Connection) c).dialect() : "sqlite"); })); } @@ -481,7 +763,20 @@ private static PyModule sql(String moduleName, boolean server) { throw Py.error(Py.OS_ERROR, String.valueOf(e.getMessage())); //NOPMD PreserveStackTrace - a Python exception has no Java cause } })); - m.setAttr("run", PyBuiltin.positional("run", a -> { + // plain(values): the values as a tuple when every one is None or an exact int, float, + // str or bytes -- what binds with no adapter -- else None. One call for the check + // sqlite3's execute makes on each value. + m.setAttr("plain", PyBuiltin.lending("plain", 1, a -> { + Object[] vs = Py.toArray(a[0]); + for (Object v : vs) { + if (!(v == Py.NONE || v instanceof Long || v instanceof Double || v instanceof String //NOPMD CompareObjectsWithEquals - None is a singleton + || v instanceof PyBytes)) { + return Py.NONE; + } + } + return a[0] instanceof PyTuple ? a[0] : new PyTuple(vs); + })); + m.setAttr("run", PyBuiltin.lending("run", 4, a -> { PySql.Connection c = sqlConnection(a[0]); Object[] ps = Py.toArray(a[2]); Object[] params = new Object[ps.length]; @@ -497,23 +792,12 @@ private static PyModule sql(String moduleName, boolean server) { } catch (java.io.IOException e) { throw Py.error(Py.OS_ERROR, String.valueOf(e.getMessage())); //NOPMD PreserveStackTrace - a Python exception has no Java cause } - Object[] cols = new Object[r.columns.length]; - for (int i = 0; i < cols.length; i++) { - cols[i] = Py.str(r.columns[i]); - } - Object[] rows = new Object[r.rows.size()]; - for (int i = 0; i < rows.length; i++) { - Object[] values = r.rows.get(i); - Object[] t = new Object[values.length]; - for (int k = 0; k < values.length; k++) { - t[k] = sqlValue(values[k]); - } - rows[i] = new PyTuple(t); - } + Object[] cols = sqlColumns(r); + Object[] rows = sqlRows(r); if (!server) { // sqlite3 (_cn1sql): SQLite reports no column types. - return new PyTuple(new Object[] {new PyTuple(cols), new PyList(rows), PyInt.of(r.changes), - PyInt.of(r.lastRowId)}); + return Py.tuple(new PyTuple(cols), new PyList(rows), PyInt.of(r.changes), + PyInt.of(r.lastRowId)); } // _cn1db adds each column's kind (PySql.Result.types) for _cn1dbapi. Object[] kinds = new Object[cols.length]; @@ -521,9 +805,54 @@ private static PyModule sql(String moduleName, boolean server) { kinds[i] = r.types != null && i < r.types.length && r.types[i] != null ? Py.str(r.types[i]) : Py.NONE; } - return new PyTuple(new Object[] {new PyTuple(cols), new PyList(rows), PyInt.of(r.changes), - PyInt.of(r.lastRowId), new PyTuple(kinds)}); + return Py.tuple(new PyTuple(cols), new PyList(rows), PyInt.of(r.changes), + PyInt.of(r.lastRowId), new PyTuple(kinds)); + })); + // pending(handle, rows) / drained(handle, rows): a cursor was handed rows it + // has yet to read, or is done with them (PySql.Connection.pending). + m.setAttr("pending", PyBuiltin.positional("pending", a -> { + PySql.Connection c = SQL.get(Long.valueOf(Py.asLong(a[0]))); + if (c != null) { + c.pending(a[1]); + } + return Py.NONE; + })); + m.setAttr("drained", PyBuiltin.positional("drained", a -> { + PySql.Connection c = SQL.get(Long.valueOf(Py.asLong(a[0]))); + if (c != null && c.anyPending()) { + c.drained(a[1]); + } + return Py.NONE; + })); + m.setAttr("create_function", PyBuiltin.positional("create_function", a -> { + PySql.Connection c = sqlConnection(a[0]); + Object body = a[3]; + boolean made; + try { + made = c.createFunction(Py.toStr(a[1]), (int) Py.asLong(a[2]), args -> { + Object[] values = new Object[args.length]; + for (int i = 0; i < args.length; i++) { + values[i] = sqlValue(args[i]); + } + // A statement the function runs is one level down: it gets results of its own. + PySql.Connection.nesting++; + try { + return sqlParam(Py.callKw(body, values, new String[0]), 0); + } catch (RuntimeException e) { + // CPython's words for it, whatever the port's engine would say. + throw new IllegalStateException("user-defined function raised exception"); //NOPMD PreserveStackTrace - only the message reaches SQLite + } finally { + PySql.Connection.nesting--; + } + }); + } catch (java.io.IOException e) { + throw Py.error(Py.OS_ERROR, String.valueOf(e.getMessage())); //NOPMD PreserveStackTrace - a Python exception has no Java cause + } + return Py.bool(made); })); + if (!server) { + sqliteFastPath(m); + } sqlControl(m, "begin", 0); sqlControl(m, "commit", 1); sqlControl(m, "rollback", 2); @@ -531,8 +860,483 @@ private static PyModule sql(String moduleName, boolean server) { return m; } + private static Object[] sqlColumns(PySql.Result r) { + Object[] cols = new Object[r.columns.length]; + for (int i = 0; i < cols.length; i++) { + cols[i] = Py.str(r.columns[i]); + } + return cols; + } + + private static Object[] sqlRows(PySql.Result r) { + Object[] rows = new Object[r.rows.size()]; + for (int i = 0; i < rows.length; i++) { + // Converted in place: the result is this call's own, and nothing else reads it. + Object[] values = r.rows.get(i); + for (int k = 0; k < values.length; k++) { + values[k] = sqlValue(values[k]); + } + rows[i] = new PyTuple(values); + } + return rows; + } + + /// What `sqlite3`'s `Cursor.execute` worked out about one SQL text, for + /// `_cn1sql.execute`: the scanned statement, how many `?` it binds, and the + /// flags `_run` reads. Only a text that is one statement with bare `?` + /// placeholders, no transaction control and no DDL gets one. + private static final class SqlitePlan { + final String stmt; + final int params; + final boolean query; + final boolean dml; + final boolean inserts; + final boolean queryWord; + /// The last description built, and the column names it was built + /// from: a statement answers the same columns every time. + Object[] columns; + PyTuple description; + + SqlitePlan(String stmt, int params, boolean query, boolean dml, boolean inserts, boolean queryWord) { + this.stmt = stmt; + this.params = params; + this.query = query; + this.dml = dml; + this.inserts = inserts; + this.queryWord = queryWord; + } + } + + private static final java.util.Map SQLITE_PLANS = new java.util.HashMap(); + /// Well past what one pass of a program runs. A library that writes values or + /// generated names into its SQL (sqlite-utils does) makes hundreds of texts that + /// are each seen once, and a bound they reach empties the cache of the statements + /// that do repeat; at 256 that happened several times a second. + private static final int SQLITE_PLANS_MAX = 2048; + /// Set by `_cn1sql.setup`: the `adapters` dict, the five keys whose + /// presence means a storage value is adapted, `str`, and the legacy + /// transaction-control value. + private static PyDict sqliteAdapters; + private static Object[] sqliteAdapterKeys; + private static Object sqliteStr; + private static long sqliteLegacy; + private static int sqliteAdaptersSize = -1; + private static boolean sqlitePlainFree; + + private static boolean sqlWordStart(char c) { + return c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c == '_'; + } + + private static boolean sqlWordPart(char c) { + return sqlWordStart(c) || c >= '0' && c <= '9'; + } + + /// Whether the word of `sql` in `[from, to)` is `word`, which is upper case, + /// whatever case it is written in. + private static boolean sqlWordIs(String sql, int from, int to, String word) { + return to - from == word.length() && sql.regionMatches(true, from, word, 0, word.length()); + } + + /// `sqlite3._scan_text` for a statement in ASCII, which is nearly every one: + /// the first statement of `sql` with each placeholder written `?`, the + /// placeholders in order (None for a bare `?`, an int for `?NNN`, the name + /// for `:name`, `@name` and `$name`), what follows the statement's `;`, and + /// `trigger` as it was passed. The module scanned a character at a time in + /// Python, for every text it had not seen, and a library that writes names + /// and values into its SQL shows it hundreds of new texts a second. + /// + /// Answers None for a text with a character outside ASCII: what Python + /// calls a letter or a digit there is the module's to decide, and it does. + private static Object sqliteScan(String sql, boolean trigger) { + int n = sql.length(); + for (int k = 0; k < n; k++) { + if (sql.charAt(k) > 127) { + return Py.NONE; + } + } + StringBuilder out = null; + PyList params = new PyList(); + int start = 0; + int depth = 0; + int i = 0; + while (i < n) { + char c = sql.charAt(i); + if (c == '\'' || c == '"' || c == '`' || c == '[') { + char close = c == '[' ? ']' : c; + int j = i + 1; + while (j < n) { + if (sql.charAt(j) == close) { + if (close != ']' && j + 1 < n && sql.charAt(j + 1) == close) { + j += 2; + continue; + } + break; + } + j++; + } + i = j + 1; + } else if (c == '-' && sql.startsWith("--", i)) { + int j = sql.indexOf('\n', i); + i = j < 0 ? n : j + 1; + } else if (c == '/' && sql.startsWith("/*", i)) { + int j = sql.indexOf("*/", i + 2); + i = j < 0 ? n : j + 2; + } else if (sqlWordStart(c)) { + int j = i; + while (j < n && sqlWordPart(sql.charAt(j))) { + j++; + } + if (trigger) { + if (sqlWordIs(sql, i, j, "BEGIN") || sqlWordIs(sql, i, j, "CASE")) { + depth++; + } else if (sqlWordIs(sql, i, j, "END")) { + depth--; + } + } + i = j; + } else if (c == '?') { + int j = i + 1; + while (j < n && sql.charAt(j) >= '0' && sql.charAt(j) <= '9') { + j++; + } + if (j - i > 18) { + // A number past a long: Python's int reads it. + return Py.NONE; + } + if (out == null) { + out = new StringBuilder(n); + } + out.append(sql.substring(start, i)).append('?'); + params.append(j > i + 1 ? PyInt.of(Long.parseLong(sql.substring(i + 1, j))) : Py.NONE); + start = j; + i = j; + } else if ((c == ':' || c == '@' || c == '$') && i + 1 < n && sqlWordStart(sql.charAt(i + 1))) { + int j = i + 1; + while (j < n && sqlWordPart(sql.charAt(j))) { + j++; + } + if (out == null) { + out = new StringBuilder(n); + } + out.append(sql.substring(start, i)).append('?'); + params.append(sql.substring(i + 1, j)); + start = j; + i = j; + } else if (c == ';' && depth <= 0) { + String stmt = out == null ? sql.substring(start, i) : out.append(sql.substring(start, i)).toString(); + return Py.tuple(stmt, params, sql.substring(i + 1), trigger ? Py.TRUE : Py.FALSE); + } else { + i++; + } + } + String stmt = out == null ? (start == 0 ? sql : sql.substring(start)) : out.append(sql.substring(start, n)).toString(); + return new PyTuple(new Object[] {stmt, params, "", trigger ? Py.TRUE : Py.FALSE}); + } + + /// `Cursor.execute` for the call nearly every application makes, in one + /// builtin: a planned statement, a list or tuple of plain values, no + /// conversion. It applies the legacy implicit `BEGIN`, runs the statement + /// and sets what `_run` sets. Anything else answers None, before touching + /// anything, and the Python path handles it with every check and error. + private static void sqliteFastPath(PyModule m) { + m.setAttr("setup", PyBuiltin.positional("setup", a -> { + sqliteAdapters = (PyDict) a[0]; + sqliteAdapterKeys = Py.toArray(a[1]); + sqliteStr = a[2]; + sqliteLegacy = Py.asLong(a[3]); + sqliteAdaptersSize = -1; + return Py.NONE; + })); + m.setAttr("scan", PyBuiltin.fixed2("scan", (a0, a1) -> sqliteScan(Py.toStr(a0), Py.isTrue(a1)))); + m.setAttr("plan", PyBuiltin.lending("plan", 7, a -> { + if (SQLITE_PLANS.size() >= SQLITE_PLANS_MAX) { + SQLITE_PLANS.clear(); + } + SQLITE_PLANS.put(Py.toStr(a[0]), new SqlitePlan(Py.toStr(a[1]), (int) Py.asLong(a[2]), Py.isTrue(a[3]), + Py.isTrue(a[4]), Py.isTrue(a[5]), Py.isTrue(a[6]))); + return Py.NONE; + })); + // fetchone(cursor): the next row of an open cursor with no row factory, or None for + // anything else -- the end included -- which the Python fetchone then answers. + // Fixed arity, so the call from the sqlite3 module builds no argument array. + m.setAttr("fetchone", PyBuiltin.unary("fetchone", StdModules::sqliteFetchOneOrNone)); + m.setAttr("execute", PyBuiltin.positional("execute", a -> { + if (a.length != 3) { + throw Py.typeError("execute() takes exactly 3 arguments (" + a.length + " given)"); + } + return sqliteExecuteOrNone(a[0], a[1], a[2]); + }).with3(StdModules::sqliteExecuteOrNone)); + } + + /// The parameter arrays the fast path binds from, one per count. Python + /// runs one thread at a time and the engine reads the values while binding, + /// before any SQL function could call back into another execute, so one + /// array per count is all that is ever in use. + private static Object[][] sqliteBoundArrays = new Object[8][]; + + private static Object[] sqliteBound(int count) { + if (count >= sqliteBoundArrays.length) { + Object[][] grown = new Object[count + 8][]; + System.arraycopy(sqliteBoundArrays, 0, grown, 0, sqliteBoundArrays.length); + sqliteBoundArrays = grown; + } + Object[] a = sqliteBoundArrays[count]; + if (a == null) { + a = new Object[count]; + sqliteBoundArrays[count] = a; + } + return a; + } + + /// The attributes the fast path reads and writes, and their field indexes + /// in the last cursor and connection classes seen: resolved once per + /// class rather than matched by name on every call. + private static final String[] CURSOR_ATTRS = {"_closed", "connection", "_rows", "_pos", "description", "rowcount", "lastrowid", "row_factory"}; + private static final String[] CONN_ATTRS = {"detect_types", "_autocommit", "in_transaction", "_isolation_level", "_handle", "_closed", "text_factory", "total_changes", "row_factory"}; + private static final int C_CLOSED = 0; + private static final int C_CONNECTION = 1; + private static final int C_ROWS = 2; + private static final int C_POS = 3; + private static final int C_DESCRIPTION = 4; + private static final int C_ROWCOUNT = 5; + private static final int C_LASTROWID = 6; + private static final int C_ROW_FACTORY = 7; + private static final int K_DETECT_TYPES = 0; + private static final int K_AUTOCOMMIT = 1; + private static final int K_IN_TRANSACTION = 2; + private static final int K_ISOLATION_LEVEL = 3; + private static final int K_HANDLE = 4; + private static final int K_CLOSED = 5; + private static final int K_TEXT_FACTORY = 6; + private static final int K_TOTAL_CHANGES = 7; + private static final int K_ROW_FACTORY = 8; + + private static Class cursorClass; + private static int[] cursorFields; + private static Class connClass; + private static int[] connFields; + + private static int[] cursorFields(PyInstance cursor) { + if (cursor.getClass() != cursorClass) { + cursorFields = cursor.fieldIndexes(CURSOR_ATTRS); + cursorClass = cursor.getClass(); + } + return cursorFields; + } + + private static int[] connFields(PyInstance conn) { + if (conn.getClass() != connClass) { + connFields = conn.fieldIndexes(CONN_ATTRS); + connClass = conn.getClass(); + } + return connFields; + } + + private static boolean sqlitePlainFree() { + PyDict d = sqliteAdapters; + if (d == null) { + return false; + } + int n = d.size(); + if (n != sqliteAdaptersSize) { + boolean free = true; + for (Object k : sqliteAdapterKeys) { + if (d.getOrNull(k) != null) { + free = false; + break; + } + } + sqlitePlainFree = free; + sqliteAdaptersSize = n; + } + return sqlitePlainFree; + } + + private static boolean isFalse(Object v) { + return v == Py.FALSE; //NOPMD CompareObjectsWithEquals - False is a singleton + } + + /// The implicit BEGIN, once per transaction: null, or why it failed. + private static String sqliteBegin(PySql.Connection c) { + try { + c.begin(); + return null; + } catch (java.io.IOException e) { + return String.valueOf(e.getMessage()); + } + } + + private static Object sqliteFetchOneOrNone(Object cursor) { + Object answer = sqliteFetchOne(cursor); + return answer == null ? Py.NONE : answer; + } + + private static Object sqliteExecuteOrNone(Object cursor, Object sql, Object parameters) { + Object answer = sqliteExecute(cursor, sql, parameters); + return answer == null ? Py.NONE : answer; + } + + private static Object sqliteExecute(Object cursorObj, Object sqlObj, Object parameters) { + if (!(cursorObj instanceof PyInstance) || !(sqlObj instanceof String) + || !(parameters instanceof PyTuple || parameters instanceof PyList)) { + return null; + } + SqlitePlan plan = SQLITE_PLANS.get(sqlObj); + if (plan == null || !sqlitePlainFree()) { + return null; + } + PyInstance cursor = (PyInstance) cursorObj; + int[] cf = cursorFields(cursor); + if (!isFalse(cursor.ownAt(cf[C_CLOSED], "_closed")) || !(cursor.ownAt(cf[C_CONNECTION], "connection") instanceof PyInstance)) { + return null; + } + PyInstance conn = (PyInstance) cursor.ownAt(cf[C_CONNECTION], "connection"); + int[] kf = connFields(conn); + Object detect = conn.ownAt(kf[K_DETECT_TYPES], "detect_types"); + Object autocommit = conn.ownAt(kf[K_AUTOCOMMIT], "_autocommit"); + Object inTransaction = conn.ownAt(kf[K_IN_TRANSACTION], "in_transaction"); + Object isolation = conn.ownAt(kf[K_ISOLATION_LEVEL], "_isolation_level"); + Object handle = conn.ownAt(kf[K_HANDLE], "_handle"); + if (!isFalse(conn.ownAt(kf[K_CLOSED], "_closed")) || !(detect instanceof Long) || ((Long) detect).longValue() != 0 + || conn.ownAt(kf[K_TEXT_FACTORY], "text_factory") != sqliteStr || inTransaction == null || isolation == null //NOPMD CompareObjectsWithEquals - the str type itself + || !(handle instanceof Long)) { + return null; + } + // Read in place, a list's storage included: nothing here keeps or changes it. + // A small tuple keeps its items in fields, and arr() would allocate an + // array to copy them into; get(i) reads them where they are. + PyTuple tuple = null; + Object[] values = null; + int count; + if (parameters instanceof PyTuple) { + tuple = (PyTuple) parameters; + count = tuple.size(); + } else { + PyList list = (PyList) parameters; + // A list of only ints or only floats keeps them unboxed, and `items` is unused. + values = list.ints == null && list.floats == null ? list.items : list.toArray(); + count = list.size; + } + if (count != plan.params) { + return null; + } + Object[] bound = sqliteBound(count); + for (int i = 0; i < count; i++) { + Object v = tuple != null ? tuple.get(i) : values[i]; + if (v == Py.NONE) { //NOPMD CompareObjectsWithEquals - None is a singleton + bound[i] = null; + } else if (v instanceof Long || v instanceof Double || v instanceof String) { + bound[i] = v; + } else if (v instanceof PyBytes) { + bound[i] = sqlParam(v, i); + } else { + return null; + } + } + PySql.Connection c = SQL.get((Long) handle); + if (c == null) { + return null; + } + // Everything checked: from here on the call is this one's to finish. + cursor.storeAt(cf[C_POS], "_pos", PyInt.of(0)); + if (c.anyPending()) { + // The rows this cursor was working through, if it was: done with now. + c.drained(cursor.ownAt(cf[C_ROWS], "_rows")); + } + // No handler from here down: a failure comes back as the engine's message, which the + // caller raises. A frame with a handler pays for it on every call, thrown or not. + if (plan.dml && autocommit instanceof Long && ((Long) autocommit).longValue() == sqliteLegacy + && isolation != Py.NONE && isFalse(inTransaction)) { //NOPMD CompareObjectsWithEquals - None is a singleton + String failed = sqliteBegin(c); + if (failed != null) { + cursor.storeAt(cf[C_ROWS], "_rows", PyTuple.EMPTY); + return failed; + } + conn.storeAt(kf[K_IN_TRANSACTION], "in_transaction", Py.TRUE); + } + PySql.Result r = c.runStatus(plan.stmt, bound, plan.query); + if (r == null) { + cursor.storeAt(cf[C_ROWS], "_rows", PyTuple.EMPTY); + return c.statusMessage(); + } + if (plan.dml) { + Object total = conn.ownAt(kf[K_TOTAL_CHANGES], "total_changes"); + long add = Math.max(r.changes, 0); + Object sum; + if (total instanceof Long && ((Long) total).longValue() < Long.MAX_VALUE - add) { + // The count is an int in practice: add it without the generic arithmetic. + sum = add == 0 ? total : PyInt.of(((Long) total).longValue() + add); + } else { + sum = Py.add(total, PyInt.of(add)); + } + conn.storeAt(kf[K_TOTAL_CHANGES], "total_changes", sum); + } + if (r.columns.length > 0) { + Object[] rows = sqlRows(r); + cursor.storeAt(cf[C_DESCRIPTION], "description", sqliteDescription(plan, r.columns)); + PyList list = new PyList(rows); + cursor.storeAt(cf[C_ROWS], "_rows", list); + if (rows.length > 0) { + c.pending(list); + } + cursor.storeAt(cf[C_ROWCOUNT], "rowcount", PyInt.of(plan.queryWord ? -1 : rows.length)); + } else { + // Only ever read, by the sqlite3 module as well: one shared empty tuple. + cursor.storeAt(cf[C_ROWS], "_rows", PyTuple.EMPTY); + cursor.storeAt(cf[C_DESCRIPTION], "description", Py.NONE); + cursor.storeAt(cf[C_ROWCOUNT], "rowcount", PyInt.of(plan.dml ? r.changes : -1)); + } + if (plan.inserts) { + cursor.storeAt(cf[C_LASTROWID], "lastrowid", PyInt.of(r.lastRowId)); + } + return cursor; + } + + private static Object sqliteFetchOne(Object cursorObj) { + if (!(cursorObj instanceof PyInstance)) { + return null; + } + PyInstance cursor = (PyInstance) cursorObj; + int[] cf = cursorFields(cursor); + Object rows = cursor.ownAt(cf[C_ROWS], "_rows"); + Object pos = cursor.ownAt(cf[C_POS], "_pos"); + if (!(rows instanceof PyList) || !(pos instanceof Long) || !isFalse(cursor.ownAt(cf[C_CLOSED], "_closed")) + || cursor.ownAt(cf[C_ROW_FACTORY], "row_factory") != Py.NONE //NOPMD CompareObjectsWithEquals - None is a singleton + || !(cursor.ownAt(cf[C_CONNECTION], "connection") instanceof PyInstance)) { + return null; + } + PyList list = (PyList) rows; + if (list.ints != null || list.floats != null) { + return null; + } + long p = ((Long) pos).longValue(); + PyInstance conn = (PyInstance) cursor.ownAt(cf[C_CONNECTION], "connection"); + int[] kf = connFields(conn); + if (p < 0 || p >= list.size || !isFalse(conn.ownAt(kf[K_CLOSED], "_closed")) + || conn.ownAt(kf[K_ROW_FACTORY], "row_factory") != Py.NONE) { //NOPMD CompareObjectsWithEquals - None is a singleton + return null; + } + cursor.storeAt(cf[C_POS], "_pos", PyInt.of(p + 1)); + return list.items[(int) p]; + } + + private static PyTuple sqliteDescription(SqlitePlan plan, String[] columns) { + if (plan.description != null && java.util.Arrays.equals(plan.columns, columns)) { + return plan.description; + } + Object[] items = new Object[columns.length]; + for (int i = 0; i < items.length; i++) { + items[i] = new PyTuple(new Object[] {Py.str(columns[i]), Py.NONE, Py.NONE, Py.NONE, Py.NONE, Py.NONE, + Py.NONE}); + } + PyTuple d = new PyTuple(items); + plan.columns = columns.clone(); + plan.description = d; + return d; + } + private static void sqlControl(PyModule m, String name, int op) { - m.setAttr(name, PyBuiltin.positional(name, a -> { + m.setAttr(name, PyBuiltin.lending(name, 1, a -> { PySql.Connection c = sqlConnection(a[0]); try { if (op == 0) { @@ -657,7 +1461,7 @@ private static PyModule thread() { PyModule m = new PyModule("_thread", new String[0]); m.setAttr("start_new_thread", PyBuiltin.positional("start_new_thread", a -> { final Object fn = a[0]; - final Object[] args = a.length > 1 && a[1] instanceof PyTuple ? ((PyTuple) a[1]).items : new Object[0]; + final Object[] args = a.length > 1 && a[1] instanceof PyTuple ? ((PyTuple) a[1]).arr() : new Object[0]; Thread t = new Thread(() -> { Gil.enter(); try { @@ -676,15 +1480,15 @@ private static PyModule thread() { return Py.NONE; })); m.setAttr("allocate_lock", PyBuiltin.positional("allocate_lock", a -> new PyJavaObject(new PyLock()))); - m.setAttr("lock_acquire", PyBuiltin.positional("lock_acquire", a -> { - double timeout = a[2] == Py.NONE ? -1 : Py.asDouble(a[2]); //NOPMD CompareObjectsWithEquals - identity is meant - return Py.bool(lock(a[0]).acquire(Py.isTrue(a[1]), timeout < 0 ? -1 : (long) (timeout * 1000))); + m.setAttr("lock_acquire", PyBuiltin.fixed3("lock_acquire", (a0, a1, a2) -> { + double timeout = a2 == Py.NONE ? -1 : Py.asDouble(a2); //NOPMD CompareObjectsWithEquals - identity is meant + return Py.bool(lock(a0).acquire(Py.isTrue(a1), timeout < 0 ? -1 : (long) (timeout * 1000))); })); - m.setAttr("lock_release", PyBuiltin.positional("lock_release", a -> { - lock(a[0]).release(); + m.setAttr("lock_release", PyBuiltin.fixed1("lock_release", a0 -> { + lock(a0).release(); return Py.NONE; })); - m.setAttr("lock_locked", PyBuiltin.positional("lock_locked", a -> Py.bool(lock(a[0]).locked()))); + m.setAttr("lock_locked", PyBuiltin.fixed1("lock_locked", a0 -> Py.bool(lock(a0).locked()))); m.setAttr("get_ident", PyBuiltin.positional("get_ident", a -> PyInt.of(threadIdent()))); return m; } @@ -732,10 +1536,10 @@ private static PyModule http() { } Object[] pairs = new Object[r.headers.length / 2]; for (int i = 0; i < pairs.length; i++) { - pairs[i] = new PyTuple(new Object[] {Py.str(r.headers[2 * i]), Py.str(r.headers[2 * i + 1])}); + pairs[i] = Py.tuple(Py.str(r.headers[2 * i]), Py.str(r.headers[2 * i + 1])); } - return new PyTuple(new Object[] {PyInt.of(r.status), Py.str(r.reason), Py.str(r.url), new PyList(pairs), - new PyBytes(r.body)}); + return Py.tuple(PyInt.of(r.status), Py.str(r.reason), Py.str(r.url), new PyList(pairs), + new PyBytes(r.body)); })); return m; } @@ -767,10 +1571,8 @@ private static PyModule math() { fn1(m, "fabs", Math::abs); fn1(m, "degrees", Math::toDegrees); fn1(m, "radians", Math::toRadians); - m.setAttr("atan2", PyBuiltin.positional("atan2", - a -> Py.ofFloat(com.codename1.util.MathUtil.atan2(Py.asDouble(a[0]), Py.asDouble(a[1]))))); - m.setAttr("pow", PyBuiltin.positional("pow", - a -> Py.ofFloat(com.codename1.util.MathUtil.pow(Py.asDouble(a[0]), Py.asDouble(a[1]))))); + m.setAttr("atan2", PyBuiltin.fixed2("atan2", (a0, a1) -> Py.ofFloat(com.codename1.util.MathUtil.atan2(Py.asDouble(a0), Py.asDouble(a1))))); + m.setAttr("pow", PyBuiltin.fixed2("pow", (a0, a1) -> Py.ofFloat(com.codename1.util.MathUtil.pow(Py.asDouble(a0), Py.asDouble(a1))))); m.setAttr("hypot", PyBuiltin.positional("hypot", a -> { double s = 0; for (int i = 0; i < a.length; i++) { @@ -791,25 +1593,24 @@ private static PyModule math() { return Py.ofFloat(r); })); fn1(m, "log10", PyMath::log10); - m.setAttr("log2", PyBuiltin.positional("log2", - a -> Py.ofFloat(com.codename1.util.MathUtil.log(Py.asDouble(a[0])) / com.codename1.util.MathUtil.log(2)))); - m.setAttr("floor", PyBuiltin.positional("floor", a -> a[0] instanceof PyInt ? a[0] - : Builtins.toInt(Py.ofFloat(Math.floor(Py.asDouble(a[0])))))); - m.setAttr("ceil", PyBuiltin.positional("ceil", a -> a[0] instanceof PyInt ? a[0] - : Builtins.toInt(Py.ofFloat(Math.ceil(Py.asDouble(a[0])))))); - m.setAttr("trunc", PyBuiltin.positional("trunc", a -> Builtins.toInt(a[0]))); - m.setAttr("isnan", PyBuiltin.positional("isnan", a -> Py.bool(Double.isNaN(Py.asDouble(a[0]))))); - m.setAttr("isinf", PyBuiltin.positional("isinf", a -> Py.bool(Double.isInfinite(Py.asDouble(a[0]))))); - m.setAttr("isfinite", PyBuiltin.positional("isfinite", a -> { - double d = Py.asDouble(a[0]); + m.setAttr("log2", PyBuiltin.fixed1("log2", a0 -> Py.ofFloat(com.codename1.util.MathUtil.log(Py.asDouble(a0)) / com.codename1.util.MathUtil.log(2)))); + m.setAttr("floor", PyBuiltin.fixed1("floor", a0 -> a0 instanceof PyInt ? a0 + : Builtins.toInt(Py.ofFloat(Math.floor(Py.asDouble(a0)))))); + m.setAttr("ceil", PyBuiltin.fixed1("ceil", a0 -> a0 instanceof PyInt ? a0 + : Builtins.toInt(Py.ofFloat(Math.ceil(Py.asDouble(a0)))))); + m.setAttr("trunc", PyBuiltin.fixed1("trunc", a0 -> Builtins.toInt(a0))); + m.setAttr("isnan", PyBuiltin.fixed1("isnan", a0 -> Py.bool(Double.isNaN(Py.asDouble(a0))))); + m.setAttr("isinf", PyBuiltin.fixed1("isinf", a0 -> Py.bool(Double.isInfinite(Py.asDouble(a0))))); + m.setAttr("isfinite", PyBuiltin.fixed1("isfinite", a0 -> { + double d = Py.asDouble(a0); return Py.bool(!Double.isNaN(d) && !Double.isInfinite(d)); })); - m.setAttr("copysign", PyBuiltin.positional("copysign", a -> { - double x = Math.abs(Py.asDouble(a[0])); - double s = Py.asDouble(a[1]); + m.setAttr("copysign", PyBuiltin.fixed2("copysign", (a0, a1) -> { + double x = Math.abs(Py.asDouble(a0)); + double s = Py.asDouble(a1); return Py.ofFloat(s < 0 || s == 0 && 1 / s < 0 ? -x : x); })); - m.setAttr("fmod", PyBuiltin.positional("fmod", a -> Py.ofFloat(PyMath.fmod(Py.asDouble(a[0]), Py.asDouble(a[1]))))); + m.setAttr("fmod", PyBuiltin.fixed2("fmod", (a0, a1) -> Py.ofFloat(PyMath.fmod(Py.asDouble(a0), Py.asDouble(a1))))); m.setAttr("gcd", PyBuiltin.positional("gcd", a -> { com.codename1.util.BigInteger g = com.codename1.util.BigInteger.ZERO; for (int i = 0; i < a.length; i++) { @@ -817,8 +1618,8 @@ private static PyModule math() { } return PyInt.of(g); })); - m.setAttr("factorial", PyBuiltin.positional("factorial", a -> { - long n = Py.asLong(a[0]); + m.setAttr("factorial", PyBuiltin.fixed1("factorial", a0 -> { + long n = Py.asLong(a0); if (n < 0) { throw Py.valueError("factorial() not defined for negative values"); } @@ -828,8 +1629,8 @@ private static PyModule math() { } return r; })); - m.setAttr("isqrt", PyBuiltin.positional("isqrt", a -> { - com.codename1.util.BigInteger n = Py.intView(Builtins.toInt(a[0])).toBig(); + m.setAttr("isqrt", PyBuiltin.fixed1("isqrt", a0 -> { + com.codename1.util.BigInteger n = Py.intView(Builtins.toInt(a0)).toBig(); if (n.signum() < 0) { throw Py.valueError("isqrt() argument must be nonnegative"); } @@ -845,18 +1646,18 @@ private static PyModule math() { x = y; } })); - m.setAttr("fsum", PyBuiltin.positional("fsum", a -> Py.obj(Builtins.SUM).call(new Object[] {a[0], Py.ofFloat(0)}, Py.NO_KW))); - m.setAttr("prod", PyBuiltin.positional("prod", a -> { + m.setAttr("fsum", PyBuiltin.fixed1("fsum", a0 -> Py.obj(Builtins.SUM).call2(a0, Py.ofFloat(0)))); + m.setAttr("prod", PyBuiltin.fixed1("prod", a0 -> { Object r = PyInt.of(1); - Object it = Py.iter(a[0]); + Object it = Py.iter(a0); for (Object v = Py.next(it); v != null; v = Py.next(it)) { r = Py.mul(r, v); } return r; })); - m.setAttr("comb", PyBuiltin.positional("comb", a -> { - long n = Py.asLong(a[0]); - long k = Py.asLong(a[1]); + m.setAttr("comb", PyBuiltin.fixed2("comb", (a0, a1) -> { + long n = Py.asLong(a0); + long k = Py.asLong(a1); if (k < 0 || k > n) { return PyInt.of(0); } @@ -888,7 +1689,19 @@ private static PyModule sys() { m.setAttr("platform", Py.str("codenameone")); m.setAttr("byteorder", Py.str("little")); m.setAttr("version", Py.str("3.13.0 (Codename One)")); - m.setAttr("version_info", PyTuple.of(PyInt.of(3), PyInt.of(13), PyInt.of(0), Py.str("final"), PyInt.of(0))); + m.setAttr("version_info", new PyStructSeq(new String[] {"major", "minor", "micro", "releaselevel", "serial"}, + PyInt.of(3), PyInt.of(13), PyInt.of(0), Py.str("final"), PyInt.of(0))); + // sys.implementation: libraries read its name and cache_tag (None + // means "no bytecode cache"). A namespace with attributes is all they + // need, so an unregistered module object carries them. + PyModule impl = new PyModule("sys.implementation", new String[0]); + impl.setAttr("name", Py.str("codenameone")); + impl.setAttr("cache_tag", Py.NONE); + impl.setAttr("version", m.getAttrOrNull("version_info")); + impl.setAttr("hexversion", PyInt.of(0x030D00F0L)); + m.setAttr("implementation", impl); + m.setAttr("_getframe", PyBuiltin.positional("_getframe", + a -> frame(a.length == 0 ? 0 : (int) Py.asLong(a[0])))); Object[] argv = new Object[Py.argv.length]; for (int i = 0; i < argv.length; i++) { argv[i] = Py.argv[i]; @@ -904,8 +1717,18 @@ private static PyModule sys() { m.setAttr("float_info", PyTuple.of(Py.ofFloat(Double.MAX_VALUE), PyInt.of(1024), PyInt.of(308), Py.ofFloat(Double.MIN_NORMAL), PyInt.of(-1021), PyInt.of(-307), PyInt.of(15), PyInt.of(53), Py.ofFloat(Math.ulp(1.0)), PyInt.of(2), PyInt.of(1))); - m.setAttr("getrecursionlimit", PyBuiltin.positional("getrecursionlimit", a -> PyInt.of(1000))); - m.setAttr("setrecursionlimit", PyBuiltin.positional("setrecursionlimit", a -> Py.NONE)); + // The limit is recorded and reported but never enforced: Python calls + // are Java calls, the thread's stack is the real limit, and running + // out of it raises RecursionError. Counting depth on every call would + // tax every program for the sake of the few that lower the limit on + // purpose -- a test that sets it to 200 to provoke a fallback sees + // the deep input processed in full instead. + final Object[] limit = {PyInt.of(1000)}; + m.setAttr("getrecursionlimit", PyBuiltin.positional("getrecursionlimit", a -> limit[0])); + m.setAttr("setrecursionlimit", PyBuiltin.fixed1("setrecursionlimit", a0 -> { + limit[0] = a0; + return Py.NONE; + })); m.setAttr("exception", PyBuiltin.positional("exception", a -> Py.handling())); m.setAttr("exc_info", PyBuiltin.positional("exc_info", a -> { Object e = Py.handling(); @@ -914,7 +1737,7 @@ private static PyModule sys() { } return PyTuple.of(Py.typeOf(e), e, Py.NONE); })); - m.setAttr("intern", PyBuiltin.positional("intern", a -> a[0])); + m.setAttr("intern", PyBuiltin.fixed1("intern", a0 -> a0)); m.setAttr("exit", PyBuiltin.positional("exit", a -> { throw new PyException(Py.SYSTEM_EXIT.call(a, Py.NO_KW)); })); @@ -922,9 +1745,9 @@ private static PyModule sys() { @Override public Object getAttrOrNull(String name) { if ("write".equals(name)) { - return PyBuiltin.positional("write", a -> { - Builtins.writeOut(Py.toStr(a[0])); - return PyInt.of(Py.len(a[0])); + return PyBuiltin.fixed1("write", a0 -> { + Builtins.writeOut(Py.toStr(a0)); + return PyInt.of(Py.len(a0)); }); } if ("flush".equals(name)) { @@ -946,9 +1769,9 @@ public Object getAttrOrNull(String name) { @Override public Object getAttrOrNull(String name) { if ("write".equals(name)) { - return PyBuiltin.positional("write", a -> { - System.err.print(Py.toStr(a[0])); - return PyInt.of(Py.len(a[0])); + return PyBuiltin.fixed1("write", a0 -> { + System.err.print(Py.toStr(a0)); + return PyInt.of(Py.len(a0)); }); } if ("flush".equals(name)) { @@ -1233,11 +2056,68 @@ static Object redirectedStdout() { return so == null || so == originalStdout || so == Py.NONE ? null : so; //NOPMD CompareObjectsWithEquals - identity is meant } + /// (year, month, day, hour, minute, second, microsecond) of a count of + /// seconds since the epoch, by the same civil-from-days algorithm as + /// time.py's _civil_from_days. + private static PyTuple civilFields(long secs, int us) { + return new PyTuple(civilValues(secs, us, 7)); + } + + /// [#civilFields]'s seven values at the start of an array of `size`. + private static Object[] civilValues(long secs, int us, int size) { + long days = Math.floorDiv(secs, 86400L); + int rem = (int) Math.floorMod(secs, 86400L); + long z = days + 719468L; + long era = Math.floorDiv(z, 146097L); + long doe = z - era * 146097L; + long yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365; + long doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + long mp = (5 * doy + 2) / 153; + long d = doy - (153 * mp + 2) / 5 + 1; + long mo = mp < 10 ? mp + 3 : mp - 9; + long y = yoe + era * 400 + (mo <= 2 ? 1 : 0); + Object[] v = new Object[size]; + v[0] = PyInt.of(y); + v[1] = PyInt.of(mo); + v[2] = PyInt.of(d); + v[3] = PyInt.of(rem / 3600); + v[4] = PyInt.of(rem / 60 % 60); + v[5] = PyInt.of(rem % 60); + v[6] = PyInt.of(us); + return v; + } + private static PyModule time() { PyModule m = new PyModule("_time", new String[0]); - m.setAttr("utcoffset", PyBuiltin.positional("utcoffset", a -> PyInt.of(utcOffset(Py.asDouble(a[0]))))); + m.setAttr("utcoffset", PyBuiltin.fixed1("utcoffset", a0 -> PyInt.of(utcOffset(Py.asDouble(a0))))); m.setAttr("tzname", PyBuiltin.positional("tzname", a -> Py.str(java.util.TimeZone.getDefault().getID()))); m.setAttr("time", PyBuiltin.positional("time", a -> Py.ofFloat(System.currentTimeMillis() / 1000.0))); + // now(tz) for a fixed whole-second offset, made whole here: the + // fields of the clock at that offset, then tz, fold 0 and the unset + // hash, stored under the names datetime passes (see _cn1obj). + m.setAttr("now_datetime", PyBuiltin.positional("now_datetime", a -> { + long ms = System.currentTimeMillis(); + long secs = Math.floorDiv(ms, 1000L) + Py.asLong(a[2]); + Object[] v = civilValues(secs, (int) Math.floorMod(ms, 1000L) * 1000, 10); + v[7] = a[3]; + v[8] = PyInt.of(0); + v[9] = PyInt.of(-1); + return PyObjects.build((PyType) a[0], (String) a[1], v, 0); + })); + // fromtimestamp's calendar fields in one call, the 7-tuple _fields + // answers: the Python divmods and civil-date arithmetic were most of + // datetime.now(timezone.utc), 7x CPython once the checks went. + m.setAttr("float_fields", PyBuiltin.fixed2("float_fields", (a0, a1) -> { + double t = Py.asDouble(a0); + double fl = Math.floor(t); + long secs = (long) fl; + long us = (long) Math.rint((t - fl) * 1000000.0); + if (us >= 1000000L) { + secs++; + us -= 1000000L; + } + return civilFields(secs + Py.asLong(a1), (int) us); + })); m.setAttr("time_ns", PyBuiltin.positional("time_ns", a -> PyInt.of(System.currentTimeMillis() * 1000000L))); m.setAttr("perf_counter", PyBuiltin.positional("perf_counter", a -> Py.ofFloat(System.nanoTime() / 1e9))); m.setAttr("perf_counter_ns", PyBuiltin.positional("perf_counter_ns", a -> PyInt.of(System.nanoTime()))); @@ -1260,4 +2140,184 @@ private static PyModule time() { })); return m; } + + /// `_cn1op`: the loops of `operator.itemgetter` and `attrgetter` with + /// several keys, which CPython runs in C; the Python ones made a + /// generator for every call, and `pdfplumber` sorts by one per char. + /// `typing.cast`, which answers its second argument. A Java builtin so + /// that generated code can tell it by identity: a `cast(T, v)` whose `T` is + /// a plain type expression then skips evaluating `T` -- a subscription + /// such as `List[Rule]`, a cache lookup in typing, built to be thrown away + /// (bs4 does that for every tag it parses). Anything else bound to the + /// name is called as written. + public static final PyBuiltin CAST = PyBuiltin.fixed2("cast", (typ, val) -> val); + + private static PyModule operatorModule() { + PyModule m = new PyModule("_cn1op", new String[0]); + m.setAttr("cast", CAST); + // `abc.ABCMeta.__instancecheck__`: its `__subclasscheck__` with the + // instance's type, which is what `issubclass` already hands it from + // here. In Python it would be `type(instance)` of anything, which the + // transpiler must take for any class at all (Infer#classOf). + m.setAttr("subclass_check_of_type", PyBuiltin.fixed2("subclass_check_of_type", + (cls, instance) -> Py.callMethod(cls, "__subclasscheck__", Py.typeOf(instance)))); + // `abc.ABCMeta`, a builtin metaclass the runtime implements (Abc). + m.setAttr("ABCMeta", Abc.META); + // `enum.EnumType`, a builtin metaclass the runtime implements + // (EnumMeta), with the hooks enum.py installs and the define its + // member construction uses in place of a computed setattr. + m.setAttr("EnumType", EnumMeta.META); + m.setAttr("enum_install", PyBuiltin.fixed1("enum_install", EnumMeta::install)); + Operator.install(m); + m.setAttr("getitems", PyBuiltin.fixed2("getitems", (obj, keys) -> { + Object[] k = ((PyTuple) keys).arr(); + Object[] out = new Object[k.length]; + for (int i = 0; i < k.length; i++) { + out[i] = Py.getitem(obj, k[i]); + } + return new PyTuple(out); + })); + m.setAttr("getattrs", PyBuiltin.fixed2("getattrs", (obj, names) -> { + Object[] k = ((PyTuple) names).arr(); + Object[] out = new Object[k.length]; + for (int i = 0; i < k.length; i++) { + Object v = obj; + String path = Typed.asStr(k[i]); + int start = 0; + while (true) { + int dot = path.indexOf('.', start); + if (dot < 0) { + v = Py.getattr(v, path.substring(start)); + break; + } + v = Py.getattr(v, path.substring(start, dot)); + start = dot + 1; + } + out[i] = v; + } + return new PyTuple(out); + })); + return m; + } + + private static final String HEX = "0123456789ABCDEF"; + + /// `_cn1url.quote(data, safe)`: percent-encodes a str (as UTF-8) or a + /// bytes-like object, keeping the always-safe ASCII set plus `safe`. + /// Answers None for anything it does not handle -- a lone surrogate, + /// which strict UTF-8 refuses, or an unexpected type -- so the Python + /// code raises exactly as before. + private static PyModule urlModule() { + PyModule m = new PyModule("_cn1url", new String[0]); + m.setAttr("quote", PyBuiltin.fixed2("quote", (data, safe) -> { + boolean[] keep = new boolean[128]; + for (int c = 'A'; c <= 'Z'; c++) { + keep[c] = true; + keep[c + 32] = true; + } + for (int c = '0'; c <= '9'; c++) { + keep[c] = true; + } + keep['_'] = true; + keep['.'] = true; + keep['-'] = true; + keep['~'] = true; + if (safe instanceof String) { + String sf = (String) safe; + for (int i = 0; i < sf.length(); i++) { + char c = sf.charAt(i); + if (c < 128) { + keep[c] = true; + } + } + } else if (safe instanceof PyBytes) { + for (byte b : ((PyBytes) safe).value) { + if (b >= 0) { + keep[b] = true; + } + } + } else { + return Py.NONE; + } + byte[] bytes; + int n; + if (data instanceof String) { + String str = (String) data; + boolean plain = true; + for (int i = 0; i < str.length(); i++) { + char c = str.charAt(i); + if (c >= 128 || !keep[c]) { + plain = false; + break; + } + } + if (plain) { + return str; + } + bytes = utf8(str); + if (bytes == NOT_UTF8) { + return Py.NONE; + } + n = bytes.length; + } else if (data instanceof PyBytes) { + bytes = ((PyBytes) data).value; + n = bytes.length; + } else if (data instanceof PyByteArray) { + bytes = ((PyByteArray) data).buf; + n = ((PyByteArray) data).size; + } else { + return Py.NONE; + } + StringBuilder sb = new StringBuilder(n + 16); + for (int i = 0; i < n; i++) { + int b = bytes[i] & 0xff; + if (b < 128 && keep[b]) { + sb.append((char) b); + } else { + sb.append('%').append(HEX.charAt(b >> 4)).append(HEX.charAt(b & 15)); + } + } + return sb.toString(); + })); + return m; + } + + /// What `utf8` answers for a lone surrogate. An empty string never gets + /// there (it is all safe characters), so a zero-length array is free. + private static final byte[] NOT_UTF8 = new byte[0]; + + /// Strict UTF-8, or `NOT_UTF8` for a lone surrogate. + private static byte[] utf8(String s) { + java.io.ByteArrayOutputStream out = new java.io.ByteArrayOutputStream(s.length() + 8); + for (int i = 0; i < s.length(); i++) { + int c = s.charAt(i); + if (c >= 0xD800 && c <= 0xDFFF) { + if (c > 0xDBFF || i + 1 >= s.length()) { + return NOT_UTF8; + } + int d = s.charAt(i + 1); + if (d < 0xDC00 || d > 0xDFFF) { + return NOT_UTF8; + } + c = 0x10000 + ((c - 0xD800) << 10) + (d - 0xDC00); + i++; + } + if (c < 0x80) { + out.write(c); + } else if (c < 0x800) { + out.write(0xC0 | (c >> 6)); + out.write(0x80 | (c & 63)); + } else if (c < 0x10000) { + out.write(0xE0 | (c >> 12)); + out.write(0x80 | ((c >> 6) & 63)); + out.write(0x80 | (c & 63)); + } else { + out.write(0xF0 | (c >> 18)); + out.write(0x80 | ((c >> 12) & 63)); + out.write(0x80 | ((c >> 6) & 63)); + out.write(0x80 | (c & 63)); + } + } + return out.toByteArray(); + } } diff --git a/maven/python-runtime/src/main/java/com/codename1/python/runtime/StoreSite.java b/maven/python-runtime/src/main/java/com/codename1/python/runtime/StoreSite.java new file mode 100644 index 00000000000..4552c8e64ad --- /dev/null +++ b/maven/python-runtime/src/main/java/com/codename1/python/runtime/StoreSite.java @@ -0,0 +1,315 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.python.runtime; + +/// An inline cache for one attribute store, `obj.name = v`, in generated +/// code: what [AttrSite] is for a read. A store has a site of its own, never +/// one it shares with a read, so neither carries the other's entries. +/// +/// It remembers up to sixteen receiver layouts: the slot when the +/// instance already has the attribute, or the shape transition when the +/// store adds it. Everything it does not model -- a property, a descriptor +/// with `__set__`, a `__setattr__` written in Python -- goes the generic +/// way. +public final class StoreSite { + /// How many layouts a site remembers. More than a read site does, because a store + /// that adds an attribute takes two of them -- the transition, and the slot on the + /// shape it leads to -- and the stores that add attributes are those of an + /// `__init__`, which a base class shares with every subclass: at four, the + /// constructor of a class with three subclasses forgot one of them at every call + /// and stored by name instead. The first four are also held in fields, for the + /// test [#set] makes inline; the rest are found by the scan in [#setSlow]. + private static final int WAYS = 16; + private static final int INLINE = 4; + + private final String name; + + // Stores: a slot hit when the instance already has the attribute, or a + // shape transition when the store adds it. + private int setVersion = -1; + private int setUsed; + private PyType[] setTypes; + private Shape[] setShapes; + private int[] setSlots; + private Shape[] setTos; + + /// Once the sixteen are taken: every further layout, by a hash of its + /// class and shape, one entry a slot. A store in an `__init__` that a base + /// class shares with hundreds of subclasses (python-pptx's element class per + /// XML tag) evicted round robin and missed on every call, paying two class + /// lookups by name and a generic store each time. + private static final int HASHED = 256; + private PyType[] hTypes; + private Shape[] hShapes; + private int[] hSlots; + private Shape[] hTos; + + private static int hash(PyType t, Shape s) { + return (t.id * 0x9E3779B1 + (s == null ? 0 : s.id) * 0x85EBCA6B) >>> 24; + } + + private PyType st0; + private PyType st1; + private PyType st2; + private PyType st3; + private Shape ss0; + private Shape ss1; + private Shape ss2; + private Shape ss3; + private int si0; + private int si1; + private int si2; + private int si3; + private Shape sto0; + private Shape sto1; + private Shape sto2; + private Shape sto3; + + /// A site for each name of `names`, one a line: the sites of a module, + /// which generated code holds as one table. + public static StoreSite[] table(String names) { + String[] each = Py.names(names); + StoreSite[] out = new StoreSite[each.length]; + for (int i = 0; i < each.length; i++) { + out[i] = new StoreSite(each[i]); + } + return out; + } + + public StoreSite(String name) { + this.name = name; + } + + /// A data descriptor written in Python: every store goes through its + /// `__set__` (or `__delete__`), never straight into the instance. + private static boolean storesThroughSet(Object clsAttr) { + if (!(clsAttr instanceof PyInstance)) { + return false; + } + PyType t = ((PyInstance) clsAttr).cls; + return t.lookup("__set__") != null || t.lookup("__delete__") != null; + } + + + public void set(Object o, Object v) { + if (o instanceof PyInstance) { + PyInstance i = (PyInstance) o; + if (setVersion == PyType.version) { + PyType t = i.cls; + Shape s = i.shape; + if (ss0 == s && st0 == t) { //NOPMD CompareObjectsWithEquals - identity is meant + if (sto0 == null) { + i.slots[si0] = v; + } else { + // A new attribute: the transition is cached too. + i.append(sto0, v); + } + return; + } + if (ss1 == s && st1 == t) { //NOPMD CompareObjectsWithEquals - identity is meant + if (sto1 == null) { + i.slots[si1] = v; + } else { + // A new attribute: the transition is cached too. + i.append(sto1, v); + } + return; + } + if (ss2 == s && st2 == t) { //NOPMD CompareObjectsWithEquals - identity is meant + if (sto2 == null) { + i.slots[si2] = v; + } else { + // A new attribute: the transition is cached too. + i.append(sto2, v); + } + return; + } + if (ss3 == s && st3 == t) { //NOPMD CompareObjectsWithEquals - identity is meant + if (sto3 == null) { + i.slots[si3] = v; + } else { + // A new attribute: the transition is cached too. + i.append(sto3, v); + } + return; + } + } + if (fieldSetType == i.cls && fieldSetVersion == PyType.version) { //NOPMD CompareObjectsWithEquals - identity is meant + if (i.extra && i.getField(fieldSetIndex) == null) { + // A field first set after another attribute: its name + // joins the shape as a marker (PyInstance.store). An + // unset field never has one, as deleting it drops it. + Shape from = i.shape; + Shape to; + if (from == markFrom && from != null) { //NOPMD CompareObjectsWithEquals - identity is meant + to = markTo; + } else { + to = i.shape().with(name); + markFrom = from; + markTo = to; + } + i.append(to, PyInstance.FIELD_HERE); + } + i.setField(fieldSetIndex, v); + return; + } + setSlow(i, v); + return; + } + Py.obj(o).setAttr(name, v); + } + + /// The one class whose compiled field this site last stored, as + /// `PyInstance.store` would store it: no property, descriptor or + /// `__setattr__` in the way, and the field not displaced into the shape. + private PyType fieldSetType; + private int fieldSetIndex; + private int fieldSetVersion = -1; + /// The last marker transition: the shape before and after. + private Shape markFrom; + private Shape markTo; + + private void setSlow(PyInstance i, Object v) { + if (setVersion == PyType.version) { + PyType t = i.cls; + Shape s = i.shape; + if (hTypes != null) { + int h = hash(t, s); + if (hTypes[h] == t && hShapes[h] == s) { //NOPMD CompareObjectsWithEquals - identity is meant + Shape to = hTos[h]; + if (to == null) { + i.slots[hSlots[h]] = v; + } else { + i.append(to, v); + } + return; + } + } + for (int k = 0; k < setUsed; k++) { + if (setTypes[k] == t && setShapes[k] == s) { //NOPMD CompareObjectsWithEquals - identity is meant + Shape to = setTos[k]; + if (to == null) { + i.slots[setSlots[k]] = v; + } else { + i.append(to, v); + } + return; + } + } + } else { + setVersion = PyType.version; + setUsed = 0; + st0 = st1 = st2 = st3 = null; + hTypes = null; + } + fillSet(i, v); + } + + private void addSet(PyType t, Shape shape, int slot, Shape to) { + int k; + if (setUsed < WAYS) { + k = setUsed++; + } else { + if (hTypes == null) { + hTypes = new PyType[HASHED]; + hShapes = new Shape[HASHED]; + hSlots = new int[HASHED]; + hTos = new Shape[HASHED]; + } + int h = hash(t, shape); + hTypes[h] = t; + hShapes[h] = shape; + hSlots[h] = slot; + hTos[h] = to; + return; + } + if (setTypes == null) { + setTypes = new PyType[INLINE]; + setShapes = new Shape[INLINE]; + setSlots = new int[INLINE]; + setTos = new Shape[INLINE]; + } else if (k == setTypes.length) { + // Nearly every site sees one class or two; only one that has filled the + // small table pays for the large one. + PyType[] types = new PyType[WAYS]; + Shape[] shapes = new Shape[WAYS]; + int[] slots = new int[WAYS]; + Shape[] tos = new Shape[WAYS]; + System.arraycopy(setTypes, 0, types, 0, k); + System.arraycopy(setShapes, 0, shapes, 0, k); + System.arraycopy(setSlots, 0, slots, 0, k); + System.arraycopy(setTos, 0, tos, 0, k); + setTypes = types; + setShapes = shapes; + setSlots = slots; + setTos = tos; + } + setTypes[k] = t; + setShapes[k] = shape; + setSlots[k] = slot; + setTos[k] = to; + if (k == 0) { + st0 = t; ss0 = shape; si0 = slot; sto0 = to; + } else if (k == 1) { + st1 = t; ss1 = shape; si1 = slot; sto1 = to; + } else if (k == 2) { + st2 = t; ss2 = shape; si2 = slot; sto2 = to; + } else if (k == 3) { + st3 = t; ss3 = shape; si3 = slot; sto3 = to; + } + } + + private void fillSet(PyInstance i, Object v) { + PyType cls = i.cls; + Object clsAttr = cls.lookup(name); + Object sa = cls.lookup("__setattr__"); + int field = i.fieldIndex(name); + boolean plain = !(clsAttr instanceof PyProperty) && !storesThroughSet(clsAttr) + && (sa == null || sa instanceof PyBuiltin) + && field < 0; + Shape before = i.shape; + int version = PyType.version; + i.setAttr(name, v); + if (field >= 0 && !(clsAttr instanceof PyProperty) && !storesThroughSet(clsAttr) + && (sa == null || sa instanceof PyBuiltin) && version == PyType.version) { + fieldSetType = cls; + fieldSetIndex = field; + fieldSetVersion = version; + return; + } + if (!plain || setVersion != PyType.version) { + return; + } + Shape after = i.shape; + if (before == after) { //NOPMD CompareObjectsWithEquals - identity is meant + addSet(cls, before, after == null ? -1 : after.indexOf(name), null); + } else { + // Adding the attribute moved the instance to a new shape. Remember + // both the transition (the next new instance) and the slot on the + // new shape (the next store to an instance already initialised). + addSet(cls, before, 0, after); + addSet(cls, after, after.indexOf(name), null); + } + } +} diff --git a/maven/python-runtime/src/main/java/com/codename1/python/runtime/StrFormat.java b/maven/python-runtime/src/main/java/com/codename1/python/runtime/StrFormat.java index 7d081afff32..c521721bc2c 100644 --- a/maven/python-runtime/src/main/java/com/codename1/python/runtime/StrFormat.java +++ b/maven/python-runtime/src/main/java/com/codename1/python/runtime/StrFormat.java @@ -47,7 +47,17 @@ static String format(String fmt, Object[] pos, Object named) { throw Py.valueError("Single '}' encountered in format string"); } if (c != '{') { - sb.append(c); + // Literal text to the next brace in one append. + int j = i + 1; + while (j < n) { + char d = fmt.charAt(j); + if (d == '{' || d == '}') { + break; + } + j++; + } + sb.append(fmt, i, j); + i = j - 1; continue; } if (i + 1 < n && fmt.charAt(i + 1) == '{') { @@ -69,6 +79,17 @@ static String format(String fmt, Object[] pos, Object named) { if (depth != 0) { throw Py.valueError("expected '}' before end of string"); } + if (j == i + 2) { + // `{}`, the common field: no substrings, and a str argument + // appended as it is (str.__format__ with an empty spec). + if (manual) { + throw Py.valueError("cannot switch from manual field specification to automatic field numbering"); + } + Object v = posArg(pos, auto++); + sb.append(v instanceof String ? (String) v : Formatting.format(v, "")); + i = j - 1; + continue; + } String field = fmt.substring(i + 1, j - 1); i = j - 1; String spec = ""; @@ -95,9 +116,16 @@ static String format(String fmt, Object[] pos, Object named) { } v = posArg(pos, auto++); } else if (Character.isDigit(head.charAt(0))) { + if (auto > 0) { + throw Py.valueError("cannot switch from automatic field numbering to manual field specification"); + } manual = true; v = posArg(pos, Integer.parseInt(head)); } else { + if (named == null) { + // No keywords were passed: the lookup a dict would fail. + throw Py.keyError(Py.str(head)); + } v = Py.obj(named).getItem(Py.str(head)); } while (end < field.length()) { @@ -127,7 +155,7 @@ static String format(String fmt, Object[] pos, Object named) { } else if (conv == 's') { v = Py.str(Py.toStr(v)); } else if (conv == 'a') { - v = Py.obj(Builtins.ASCII).call(new Object[] {v}, Py.NO_KW); + v = Py.obj(Builtins.ASCII).call1(v); } sb.append(Formatting.format(v, spec)); } diff --git a/maven/python-runtime/src/main/java/com/codename1/python/runtime/TypeMethods.java b/maven/python-runtime/src/main/java/com/codename1/python/runtime/TypeMethods.java index 2eec40bf9c8..e837ae3cb45 100644 --- a/maven/python-runtime/src/main/java/com/codename1/python/runtime/TypeMethods.java +++ b/maven/python-runtime/src/main/java/com/codename1/python/runtime/TypeMethods.java @@ -36,6 +36,60 @@ private static void def(PyType t, String name, PyBuiltin.Positional p) { t.define(name, PyBuiltin.method(t, name, p)); } + // Methods of a fixed arity take their receiver and arguments as Java + // parameters: a call through an attribute site builds no argument array. + // The array form stays for calls made with a spread or through + // PyObject.call, and checks the count it was given. + + private static void def1(PyType t, String name, PyBuiltin.One f) { + t.define(name, PyBuiltin.method(t, name, a -> { + arity(name, a, 1); + return f.call(a[0]); + }).with1(f)); + } + + private static void def2(PyType t, String name, PyBuiltin.Two f) { + t.define(name, PyBuiltin.method(t, name, a -> { + arity(name, a, 2); + return f.call(a[0], a[1]); + }).with2(f)); + } + + private static void def3(PyType t, String name, PyBuiltin.Three f) { + t.define(name, PyBuiltin.method(t, name, a -> { + arity(name, a, 3); + return f.call(a[0], a[1], a[2]); + }).with3(f)); + } + + /// A method with optional trailing arguments: `p` takes every call, and + /// `f1`..`f3` (each may be null) the calls of that many values, receiver + /// included, without an array. + private static void defOpt(PyType t, String name, PyBuiltin.Positional p, PyBuiltin.One f1, + PyBuiltin.Two f2, PyBuiltin.Three f3) { + PyBuiltin b = PyBuiltin.method(t, name, p); + if (f1 != null) { + b.with1(f1); + } + if (f2 != null) { + b.with2(f2); + } + if (f3 != null) { + b.with3(f3); + } + t.define(name, b); + } + + /// `a` holds the receiver and `n - 1` arguments. + static void arity(String name, Object[] a, int n) { + // Extra arguments are ignored, as the array implementations these + // replaced ignored them. + if (a.length < n) { + throw Py.typeError(name + "() takes " + (n == 1 ? "no arguments" : "exactly " + (n - 1) + + (n == 2 ? " argument" : " arguments")) + " (" + (a.length - 1) + " given)"); + } + } + private static void defKw(PyType t, String name, PyBuiltin.Impl p) { t.define(name, PyBuiltin.methodKw(t, name, p)); } @@ -82,31 +136,54 @@ static String asciiLower(String s) { return sb == null ? s : sb.toString(); } + /// `s` mapped by `m` when every char of it is Latin-1 and maps to one + /// Latin-1 char (null otherwise): the string itself when nothing + /// changes, else one byte array wrapped as a compact string. Never a + /// StringBuilder, whose native append takes the builder lock per char, + /// nor a char[], which a Latin-1 result does not need. + private static String mapLatin1(String s, Unicode.Mapping m) { + final short[] lat = m.latin1; + final int n = s.length(); + int i = 0; + while (i < n) { + char c = s.charAt(i); + if (c >= 256) { + return null; + } + if (lat[c] != c) { + break; + } + i++; + } + if (i == n) { + return s; + } + byte[] out = new byte[n]; + for (int k = 0; k < i; k++) { + out[k] = (byte) s.charAt(k); + } + while (i < n) { + char c = s.charAt(i); + if (c >= 256) { + return null; + } + int d = lat[c]; + if (d < 0) { + return null; + } + out[i] = (byte) d; + i++; + } + return Codecs.latin1(out, 0, n); + } + /// Unicode case mapping per character, which (unlike /// `String.toLowerCase()`) does not depend on the device locale. static String mapCase(String s, int mode) { - if (mode <= 1) { - // ASCII: one array, and the string itself when nothing changes. - int n = s.length(); - char[] out = null; - int i = 0; - for (; i < n; i++) { - char c = s.charAt(i); - if (c >= 128) { - break; - } - char r = mode == 1 ? (c >= 'a' && c <= 'z' ? (char) (c - 32) : c) - : (c >= 'A' && c <= 'Z' ? (char) (c + 32) : c); - if (r != c && out == null) { - out = new char[n]; - s.getChars(0, i, out, 0); - } - if (out != null) { - out[i] = r; - } - } - if (i == n) { - return out == null ? s : new String(out); + if (mode <= 1 || mode == 4) { + String r = mapLatin1(s, mode == 0 ? Unicode.LOWER_MAP : mode == 1 ? Unicode.UPPER_MAP : Unicode.FOLD_MAP); + if (r != null) { + return r; } } StringBuilder sb = new StringBuilder(s.length()); @@ -231,7 +308,7 @@ public Object next() { } } - private static boolean isSpace(char c) { + static boolean isSpace(char c) { if (c > ' ' && c < '\u0085') { return false; } @@ -240,7 +317,7 @@ private static boolean isSpace(char c) { || Unicode.is(c, Unicode.SPACE); } - private static String strip(String v, Object chars, boolean left, boolean right) { + static String strip(String v, Object chars, boolean left, boolean right) { int a = 0; int b = v.length(); String cs = chars == null || chars == Py.NONE ? null : strArg(chars, "strip"); //NOPMD CompareObjectsWithEquals - identity is meant @@ -255,42 +332,51 @@ private static String strip(String v, Object chars, boolean left, boolean right) static PyList split(String v, Object sepO, long max) { if (sepO == null || sepO == Py.NONE) { //NOPMD CompareObjectsWithEquals - identity is meant - // Counted first, so the list is one array of the right size. + // One pass over a copy of the chars, the word bounds kept in + // pairs; the printable ASCII test is inline, the rest calls out. int n = v.length(); + char[] cs = new char[n]; + v.getChars(0, n, cs, 0); + int[] bounds = new int[16]; int count = 0; - for (int i = 0; i < n;) { - while (i < n && isSpace(v.charAt(i))) { - i++; - } - if (i >= n) { - break; - } - count++; - if (max >= 0 && count > max) { - break; - } - while (i < n && !isSpace(v.charAt(i))) { - i++; - } - } - Object[] parts = new Object[count]; - int k = 0; int i = 0; - while (k < count) { - while (isSpace(v.charAt(i))) { + while (i < n) { + char c = cs[i]; + if ((c <= ' ' || c >= '\u0085') && isSpace(c)) { i++; + continue; } - if (max >= 0 && k == max) { - parts[k++] = strip(v.substring(i), null, false, true); + if (max >= 0 && count == max) { break; } - int j = i; - while (j < n && !isSpace(v.charAt(j))) { + int j = i + 1; + while (j < n) { + char d = cs[j]; + if ((d <= ' ' || d >= '\u0085') && isSpace(d)) { + break; + } j++; } - parts[k++] = v.substring(i, j); + if (2 * count + 2 > bounds.length) { + int[] g = new int[bounds.length * 2]; + System.arraycopy(bounds, 0, g, 0, bounds.length); + bounds = g; + } + bounds[2 * count] = i; + bounds[2 * count + 1] = j; + count++; i = j; } + boolean rest = i < n; + Object[] parts = new Object[count + (rest ? 1 : 0)]; + for (int k = 0; k < count; k++) { + parts[k] = v.substring(bounds[2 * k], bounds[2 * k + 1]); + } + if (rest) { + // `max` reached: the remainder as it is, trailing + // whitespace kept, as CPython keeps it. + parts[count] = v.substring(i); + } return new PyList(parts); } PyList out = new PyList(); @@ -326,7 +412,7 @@ private static PyList rsplit(String v, Object sepO, long max) { break; } if (rev.size() >= max) { - rev.append(Py.str(strip(v.substring(0, j), null, true, false))); + rev.append(Py.str(v.substring(0, j))); // leading whitespace kept, as in CPython break; } int i = j; @@ -355,41 +441,274 @@ private static PyList rsplit(String v, Object sepO, long max) { /// Resolves the optional `start, end` arguments of find/count/startswith /// to UTF-16 offsets. - private static int[] range(String self, Object[] a, int from) { - int n = PyStr.codePoints(self); - int[] r = new PySlice(a.length > from ? a[from] : Py.NONE, a.length > from + 1 ? a[from + 1] : Py.NONE, - Py.NONE).indices(n); - return new int[] {PyStr.offset(self, r[0]), PyStr.offset(self, Math.max(r[0], r[1]))}; + /// + /// Packed as `lo << 32 | hi` so that a call allocates nothing: a tokenizer + /// calls `find(c, pos, end)` once per token. Bounds that are ints (or + /// absent) on a string without surrogate pairs -- nearly every call -- are + /// clamped here as slice indices clamp; anything else goes through + /// [PySlice], which also raises for a bound that is not an index. + /// `str.count(sub, start, end)`, counted in place: `_markupbase` + /// counts the newlines of a window of the whole document on every + /// tag, and a substring per call copied that window each time. + private static Object count(Object a0, Object a1, Object a2, Object a3) { + String self = s(a0); + String sub = strArg(a1, "count"); + long r = range(self, a2, a3); + int lo = lo(r); + int hi = hi(r); + if (hi < lo) { + return PyInt.of(0); + } + int m = sub.length(); + if (m == 0) { + return PyInt.of(self.codePointCount(lo, hi) + 1); + } + int n = 0; + if (m == 1) { + // Bounded by hand: indexOf would run on past `end` to the next + // match, the whole rest of a document with no newline in it. + char c = sub.charAt(0); + for (int i = lo; i < hi; i++) { + if (self.charAt(i) == c) { + n++; + } + } + return PyInt.of(n); + } + for (int i = indexIn(self, sub, lo, hi); i >= 0; i = indexIn(self, sub, i + m, hi)) { + n++; + } + return PyInt.of(n); + } + + /// `str.replace(old, new, count)`; `a3` null when no count was passed. + private static Object replace(Object a0, Object a1, Object a2, Object a3) { + String v = s(a0); + String old = strArg(a1, "replace"); + String nw = strArg(a2, "replace"); + long count = a3 != null ? Py.asLong(a3) : -1; + if (count < 0) { + if (old.length() == 0) { + StringBuilder sb = new StringBuilder(nw); + for (int i = 0; i < v.length(); i++) { + sb.append(v.charAt(i)).append(nw); + } + return Py.str(sb.toString()); + } + return Py.str(v.replace(old, nw)); + } + StringBuilder sb = new StringBuilder(); + int i = 0; + for (long k = 0; k < count; k++) { + int j = v.indexOf(old, i); + if (j < 0) { + break; + } + sb.append(v, i, j).append(nw); + i = j + old.length(); + if (old.length() == 0) { + if (i < v.length()) { + sb.append(v.charAt(i)); + } + i++; + } + } + if (i <= v.length()) { + sb.append(v.substring(Math.min(i, v.length()))); + } + return Py.str(sb.toString()); + } + + private static Object setdefault(Object a0, Object a1, Object a2) { + PyDict self = d(a0); + Object v = self.getOrNull(a1); + if (v == null) { + v = a2; + self.setItem(a1, v); + } + return v; + } + + private static long range(String self, Object[] a, int from) { + return range(self, a.length > from ? a[from] : Py.NONE, a.length > from + 1 ? a[from + 1] : Py.NONE); + } + + private static long range(String self, Object b0, Object b1) { + boolean plain = PyStr.surrogates(self) == 0; + int n = plain ? self.length() : PyStr.codePoints(self); + long lo = b0 == Py.NONE ? 0 : bound(b0, n); //NOPMD CompareObjectsWithEquals - identity is meant + long hi = b1 == Py.NONE ? n : Math.min(n, bound(b1, n)); //NOPMD CompareObjectsWithEquals - identity is meant + if (lo > hi) { + // A start past the end matches nothing, the empty string + // included: "abc".find("", 5) is -1 where "abc"[5:] is "". + return NOWHERE; + } + return plain ? pack((int) lo, (int) hi) : pack(PyStr.offset(self, (int) lo), PyStr.offset(self, (int) hi)); + } + + /// A window no needle is in, whatever its length: `hi - lo` is negative. + private static final long NOWHERE = pack(1, 0); + + /// A start or end argument counted from the end when negative and held + /// at zero below it. It is not held at `n` above it: only the end is. + private static long bound(Object b, int n) { + long v; + if (b instanceof Long) { + v = ((Long) b).longValue(); + } else if (b instanceof PyInt && ((PyInt) b).big != null) { + // An int no long holds is past either end of any string. + return ((PyInt) b).big.signum() < 0 ? 0 : Long.MAX_VALUE; + } else if (Py.isInt(b) || b instanceof PyInstance) { + v = Py.index(b); + } else { + // str.find and its kin word this as a slice bound does. + throw Py.typeError("slice indices must be integers or None or have an __index__ method"); + } + if (v < 0) { + v += n; + return v < 0 ? 0 : v; + } + return v; + } + + private static long pack(int lo, int hi) { + return ((long) lo << 32) | (hi & 0xFFFFFFFFL); + } + + private static int lo(long r) { + return (int) (r >>> 32); + } + + private static int hi(long r) { + return (int) r; + } + + /// `find`/`rfind` over the whole string, as a code point index. + static int findWhole(String v, String sub, boolean last) { + int i = last ? v.lastIndexOf(sub) : v.indexOf(sub); + return i < 0 ? -1 : PyStr.cpIndex(v, i); + } + + /// The answer of `find` (-1 for a miss) or `index` (which raises). + private static Object found(int i, boolean raise) { + if (i < 0 && raise) { + throw Py.valueError("substring not found"); + } + return PyInt.of(i); } private static int find(String self, Object[] a, boolean last) { - String sub = strArg(a[1], "find"); - int[] r = range(self, a, 2); + return findIn(self, strArg(a[1], "find"), range(self, a, 2), last); + } + + /// `self.find(sub, b0, b1)` and its `rfind`, for typed code: the bounds + /// as Python passed them, `None` for one left out. + static int findIn(String self, String sub, Object b0, Object b1, boolean last) { + return findIn(self, sub, range(self, b0, b1), last); + } + + /// `self.startswith(c, b0, b1)` and its `endswith`, for typed code. + static boolean affixIn(String self, String c, Object b0, Object b1, boolean start) { + long r = range(self, b0, b1); + return affixAt(self, lo(r), hi(r), c, start); + } + + /// `self.find(sub, start)` and its `rfind`, the start an int that fits a + /// `long`. + static int findFrom(String self, String sub, long start, boolean last) { + if (PyStr.surrogates(self) != 0) { + return findIn(self, sub, Long.valueOf(start), Py.NONE, last); + } + int n = self.length(); + long lo = start < 0 ? Math.max(0, start + n) : start; + return lo > n ? -1 : findIn(self, sub, pack((int) lo, n), last); + } + + /// `self.startswith(c, start)` and its `endswith`, likewise. + static boolean affixFrom(String self, String c, long start, boolean isStart) { + if (PyStr.surrogates(self) != 0) { + return affixIn(self, c, Long.valueOf(start), Py.NONE, isStart); + } + int n = self.length(); + long lo = start < 0 ? Math.max(0, start + n) : start; + return lo <= n && affixAt(self, (int) lo, n, c, isStart); + } + + /// Whether `v` is not empty and every char of it is of a class in `mask`. + static boolean allOf(String v, int mask) { + return all(v, mask); + } + + private static int findIn(String self, String sub, long r, boolean last) { String v = self; - if (r[1] - r[0] < sub.length()) { + if (hi(r) - lo(r) < sub.length()) { return -1; } - int i = last ? v.lastIndexOf(sub, r[1] - sub.length()) : v.indexOf(sub, r[0]); - if (i < r[0] || i + sub.length() > r[1]) { - return -1; + int i = last ? lastIndexIn(v, sub, lo(r), hi(r)) : indexIn(v, sub, lo(r), hi(r)); + return i < 0 ? -1 : PyStr.cpIndex(self, i); + } + + /// `sub` in `v[lo:hi]` (UTF-16 offsets), searching only that window as + /// CPython does. `indexOf(sub, lo)` runs on to the end of `v` when the + /// window has no hit, so a tokenizer calling `find(c, pos, end)` once per + /// token over one large buffer was quadratic. + static int indexIn(String v, String sub, int lo, int hi) { + int m = sub.length(); + int last = hi - m; + if (m == 0) { + return lo <= hi ? lo : -1; + } + if (hi == v.length()) { + // The window runs to the end: the native search is the same answer. + return v.indexOf(sub, lo); } - return PyStr.cpIndex(self, i); + char first = sub.charAt(0); + for (int i = lo; i <= last; i++) { + if (v.charAt(i) == first && (m == 1 || v.regionMatches(i + 1, sub, 1, m - 1))) { + return i; + } + } + return -1; + } + + /// The last `sub` in `v[lo:hi]`; never looks before `lo`. + static int lastIndexIn(String v, String sub, int lo, int hi) { + int m = sub.length(); + if (m == 0) { + return lo <= hi ? hi : -1; + } + if (lo == 0) { + // The window starts at 0: the native search is the same answer. + return v.lastIndexOf(sub, hi - m); + } + char first = sub.charAt(0); + for (int i = hi - m; i >= lo; i--) { + if (v.charAt(i) == first && (m == 1 || v.regionMatches(i + 1, sub, 1, m - 1))) { + return i; + } + } + return -1; } private static boolean affix(String self, Object[] a, boolean start) { - // Compared in place: no substring, and no offsets resolved unless - // a start or end was given. + return affix(self, a[1], a.length > 2 ? a[2] : null, a.length > 3 ? a[3] : Py.NONE, start); + } + + /// `self.startswith(c, b0, b1)` or `endswith`; `b0` null when neither + /// bound was passed. Compared in place: no substring, and no offsets + /// resolved unless a bound was given. + private static boolean affix(String self, Object c, Object b0, Object b1, boolean start) { int lo = 0; int hi = self.length(); - if (a.length > 2) { - int[] r = range(self, a, 2); - lo = r[0]; - hi = r[1]; + if (b0 != null) { + long r = range(self, b0, b1); + lo = lo(r); + hi = hi(r); } - if (!(a[1] instanceof PyTuple)) { - return affixAt(self, lo, hi, strArg(a[1], start ? "startswith" : "endswith"), start); + if (!(c instanceof PyTuple)) { + return affixAt(self, lo, hi, strArg(c, start ? "startswith" : "endswith"), start); } - for (Object cand : ((PyTuple) a[1]).items) { + for (Object cand : ((PyTuple) c).arr()) { if (affixAt(self, lo, hi, strArg(cand, start ? "startswith" : "endswith"), start)) { return true; } @@ -403,12 +722,16 @@ private static boolean affixAt(String self, int lo, int hi, String c, boolean st } private static Object pad(Object[] a, int mode) { - String v = s(a[0]); - int width = (int) Py.asLong(a[1]); - String fill = a.length > 2 ? strArg(a[2], "fill") : " "; - int n = PyStr.codePoints((String) a[0]); + return pad(a[0], a[1], a.length > 2 ? a[2] : null, mode); + } + + private static Object pad(Object a0, Object a1, Object a2, int mode) { + String v = s(a0); + int width = (int) Py.asLong(a1); + String fill = a2 != null ? strArg(a2, "fill") : " "; + int n = PyStr.codePoints(v); if (width <= n) { - return a[0]; + return a0; } int total = width - n; int left = mode == 0 ? 0 : mode == 1 ? total : total / 2 + (total & width & 1); @@ -477,46 +800,79 @@ private static boolean cased(String v, int want, int against) { return seen; } + /// An instance of a str subclass joins as the str it carries, as in CPython + /// (bs4's NavigableString is one). + private static Object joinItem(Object v) { + if (v instanceof PyInstance && ((PyInstance) v).base instanceof String) { + return ((PyInstance) v).base; + } + return v; + } + /// `sep.join(items)`; a list is read in place, without an iterator. - static Object join(String sep, Object items) { + /// Every path ends in the varargs String.join, which on ParparVM copies + /// Latin-1 parts straight into one allocation: a str subclass item + /// (bs4's NavigableString) is unwrapped to its value first, and an + /// iterable is gathered into an array. A StringBuilder here took the + /// builder lock twice per item. + static String join(String sep, Object items) { if (items instanceof PyList) { PyList l = (PyList) items; int n = l.size; - if (n == 1 && l.get(0) instanceof String) { - return l.get(0); - } - // String.join, which ParparVM builds in one allocation that the - // parts' bytes are copied straight into. - String[] parts = new String[n]; - for (int i = 0; i < n; i++) { - Object v = l.get(i); - if (!(v instanceof String)) { - throw Py.typeError("sequence item " + i + ": expected str instance, " + Py.typeOf(v).name + " found"); - } - parts[i] = (String) v; + Object only = n == 1 ? l.get(0) : null; + if (only instanceof String) { + return (String) only; } - return String.join(sep, parts); - } - Object it = Py.iter(items); - StringBuilder sb = new StringBuilder(); - boolean first = true; - int i = 0; - for (Object v = Py.next(it); v != null; v = Py.next(it), i++) { - if (!(v instanceof String)) { - throw Py.typeError("sequence item " + i + ": expected str instance, " + Py.typeOf(v).name + " found"); + if (n > 0 && (l.ints != null || l.floats != null)) { + // Unboxed numbers: the first item is already the error. + joinPart(l.get(0), 0); } - if (!first) { - sb.append(sep); + return joinArray(sep, l.items, n); + } + // The whole iterable first, then the type checks, as CPython's + // PySequence_Fast does: a bad item leaves the iterator exhausted. + Object[] raw = Py.toArray(items); + int n = raw.length; + if (n == 1 && raw[0] instanceof String) { + return (String) raw[0]; + } + return joinArray(sep, raw, n); + } + + /// The first `n` of `src` joined; read straight from the array, the + /// String test in line and the call only for a str subclass or an error. + private static String joinArray(String sep, Object[] src, int n) { + String[] parts = new String[n]; + for (int i = 0; i < n; i++) { + Object v = src[i]; + if (v instanceof String) { + parts[i] = (String) v; + } else if (v instanceof PyInstance && ((PyInstance) v).base instanceof String) { + parts[i] = (String) ((PyInstance) v).base; + } else { + parts[i] = joinPart(v, i); } - first = false; - sb.append(((String) v)); } - return Py.str(sb.toString()); + return String.join(sep, parts); } + private static String joinPart(Object v, int i) { + if (v instanceof String) { + return (String) v; + } + Object b = joinItem(v); + if (!(b instanceof String)) { + throw Py.typeError("sequence item " + i + ": expected str instance, " + Py.typeOf(b).name + " found"); + } + return (String) b; + } + + // A local builder on purpose: ParparVM keeps one that does not escape + // on the stack, unlocked; a shared static one is locked on every append. + private static void installStr() { PyType t = Py.STR_TYPE; - def(t, "join", a -> join(s(a[0]), a[1])); + def2(t, "join", (a0, a1) -> join(s(a0), a1)); defKw(t, "split", (args, kw) -> { Args a = new Args("split", args, kw).check(3, "sep", "maxsplit"); return split(s(args[0]), a.get(1, "sep", Py.NONE), Py.asLong(a.get(2, "maxsplit", PyInt.of(-1)))); @@ -552,103 +908,81 @@ private static void installStr() { } return out; }); - def(t, "strip", a -> Py.str(strip(s(a[0]), a.length > 1 ? a[1] : null, true, true))); - def(t, "lstrip", a -> Py.str(strip(s(a[0]), a.length > 1 ? a[1] : null, true, false))); - def(t, "rstrip", a -> Py.str(strip(s(a[0]), a.length > 1 ? a[1] : null, false, true))); - def(t, "replace", a -> { - String v = s(a[0]); - String old = strArg(a[1], "replace"); - String nw = strArg(a[2], "replace"); - long count = a.length > 3 ? Py.asLong(a[3]) : -1; - if (count < 0) { - if (old.length() == 0) { - StringBuilder sb = new StringBuilder(nw); - for (int i = 0; i < v.length(); i++) { - sb.append(v.charAt(i)).append(nw); - } - return Py.str(sb.toString()); - } - return Py.str(v.replace(old, nw)); + defOpt(t, "strip", a -> Py.str(strip(s(a[0]), a.length > 1 ? a[1] : null, true, true)), + a0 -> Py.str(strip(s(a0), null, true, true)), (a0, a1) -> Py.str(strip(s(a0), a1, true, true)), null); + defOpt(t, "lstrip", a -> Py.str(strip(s(a[0]), a.length > 1 ? a[1] : null, true, false)), + a0 -> Py.str(strip(s(a0), null, true, false)), (a0, a1) -> Py.str(strip(s(a0), a1, true, false)), null); + defOpt(t, "rstrip", a -> Py.str(strip(s(a[0]), a.length > 1 ? a[1] : null, false, true)), + a0 -> Py.str(strip(s(a0), null, false, true)), (a0, a1) -> Py.str(strip(s(a0), a1, false, true)), null); + t.define("replace", PyBuiltin.method(t, "replace", a -> { + if (a.length < 3) { + throw Py.typeError("replace() takes at least 2 arguments (" + (a.length - 1) + " given)"); } - StringBuilder sb = new StringBuilder(); - int i = 0; - for (long k = 0; k < count; k++) { - int j = v.indexOf(old, i); - if (j < 0) { - break; - } - sb.append(v, i, j).append(nw); - i = j + old.length(); - if (old.length() == 0) { - if (i < v.length()) { - sb.append(v.charAt(i)); - } - i++; - } - } - if (i <= v.length()) { - sb.append(v.substring(Math.min(i, v.length()))); - } - return Py.str(sb.toString()); - }); - def(t, "startswith", a -> Py.bool(affix(s(a[0]), a, true))); - def(t, "endswith", a -> Py.bool(affix(s(a[0]), a, false))); - def(t, "find", a -> PyInt.of(find(s(a[0]), a, false))); - def(t, "rfind", a -> PyInt.of(find(s(a[0]), a, true))); - def(t, "index", a -> { - int i = find(s(a[0]), a, false); - if (i < 0) { - throw Py.valueError("substring not found"); - } - return PyInt.of(i); - }); - def(t, "rindex", a -> { - int i = find(s(a[0]), a, true); - if (i < 0) { - throw Py.valueError("substring not found"); - } - return PyInt.of(i); - }); - def(t, "count", a -> { - String self = s(a[0]); - String sub = strArg(a[1], "count"); - int[] r = range(self, a, 2); - String v = self.substring(r[0], r[1]); - if (sub.length() == 0) { - return PyInt.of(PyStr.codePoints(v) + 1); - } - int n = 0; - for (int i = v.indexOf(sub); i >= 0; i = v.indexOf(sub, i + sub.length())) { - n++; + return replace(a[0], a[1], a[2], a.length > 3 ? a[3] : null); + }).with3((a0, a1, a2) -> replace(a0, a1, a2, null)).with4(TypeMethods::replace)); + // The search family runs without an argument array for every + // arity it takes: these are called per token by every parser. + for (int k = 0; k < 2; k++) { + final boolean st = k == 0; + t.define(st ? "startswith" : "endswith", PyBuiltin.method(t, st ? "startswith" : "endswith", + a -> Py.bool(affix(s(a[0]), a, st))) + .with2((a0, a1) -> Py.bool(affix(s(a0), a1, null, Py.NONE, st))) + .with3((a0, a1, a2) -> Py.bool(affix(s(a0), a1, a2, Py.NONE, st))) + .with4((a0, a1, a2, a3) -> Py.bool(affix(s(a0), a1, a2, a3, st)))); + } + for (int k = 0; k < 4; k++) { + final boolean last = (k & 1) != 0; + final boolean raise = k >= 2; + String nm = (last ? "r" : "") + (raise ? "index" : "find"); + t.define(nm, PyBuiltin.method(t, nm, a -> found(find(s(a[0]), a, last), raise)) + .with2((a0, a1) -> found(findIn(s(a0), strArg(a1, "find"), Py.NONE, Py.NONE, last), raise)) + .with3((a0, a1, a2) -> found(findIn(s(a0), strArg(a1, "find"), a2, Py.NONE, last), raise)) + .with4((a0, a1, a2, a3) -> found(findIn(s(a0), strArg(a1, "find"), a2, a3, last), raise))); + } + t.define("count", PyBuiltin.method(t, "count", a -> { + if (a.length < 2 || a.length > 4) { + throw Py.typeError("count() takes from 1 to 3 arguments (" + (a.length - 1) + " given)"); } - return PyInt.of(n); - }); - def(t, "upper", a -> Py.str(mapCase(s(a[0]), 1))); - def(t, "lower", a -> Py.str(mapCase(s(a[0]), 0))); - def(t, "casefold", a -> Py.str(mapCase(s(a[0]), 4))); - def(t, "swapcase", a -> Py.str(mapCase(s(a[0]), 2))); - def(t, "title", a -> Py.str(mapCase(s(a[0]), 3))); - def(t, "capitalize", a -> { - String v = s(a[0]); + return count(a[0], a[1], a.length > 2 ? a[2] : Py.NONE, a.length > 3 ? a[3] : Py.NONE); + }).with2((a0, a1) -> count(a0, a1, Py.NONE, Py.NONE)).with3((a0, a1, a2) -> count(a0, a1, a2, Py.NONE)) + .with4(TypeMethods::count)); + def1(t, "upper", a0 -> Py.str(mapCase(s(a0), 1))); + def1(t, "lower", a0 -> Py.str(mapCase(s(a0), 0))); + def1(t, "casefold", a0 -> Py.str(mapCase(s(a0), 4))); + def1(t, "swapcase", a0 -> Py.str(mapCase(s(a0), 2))); + def1(t, "title", a0 -> Py.str(mapCase(s(a0), 3))); + def1(t, "capitalize", a0 -> { + String v = s(a0); if (v.length() == 0) { - return a[0]; + return a0; } StringBuilder first = new StringBuilder(); Unicode.TITLE_MAP.append(first, v.charAt(0)); return Py.str(first.append(mapCase(v.substring(1), 0)).toString()); }); - def(t, "isdigit", a -> Py.bool(all(s(a[0]), Unicode.DIGIT))); - def(t, "isdecimal", a -> Py.bool(all(s(a[0]), Unicode.DECIMAL))); - def(t, "isnumeric", a -> Py.bool(all(s(a[0]), Unicode.NUMERIC))); - def(t, "isalpha", a -> Py.bool(all(s(a[0]), Unicode.ALPHA))); - def(t, "isalnum", a -> Py.bool(all(s(a[0]), + def1(t, "isdigit", a0 -> Py.bool(all(s(a0), Unicode.DIGIT))); + def1(t, "isdecimal", a0 -> Py.bool(all(s(a0), Unicode.DECIMAL))); + def1(t, "isnumeric", a0 -> Py.bool(all(s(a0), Unicode.NUMERIC))); + def1(t, "isalpha", a0 -> Py.bool(all(s(a0), Unicode.ALPHA))); + def1(t, "isalnum", a0 -> Py.bool(all(s(a0), Unicode.ALPHA | Unicode.DECIMAL | Unicode.DIGIT | Unicode.NUMERIC))); - def(t, "isspace", a -> Py.bool(all(s(a[0]), Unicode.SPACE))); - def(t, "isupper", a -> Py.bool(cased(s(a[0]), Unicode.UPPER, Unicode.LOWER))); - def(t, "islower", a -> Py.bool(cased(s(a[0]), Unicode.LOWER, Unicode.UPPER))); - def(t, "istitle", a -> Py.bool(isTitle(s(a[0])))); - def(t, "isascii", a -> { - String v = s(a[0]); + def1(t, "isspace", a0 -> Py.bool(all(s(a0), Unicode.SPACE))); + def1(t, "isupper", a0 -> Py.bool(cased(s(a0), Unicode.UPPER, Unicode.LOWER))); + def1(t, "islower", a0 -> Py.bool(cased(s(a0), Unicode.LOWER, Unicode.UPPER))); + def1(t, "istitle", a0 -> Py.bool(isTitle(s(a0)))); + def1(t, "isprintable", a0 -> { + String v = s(a0); + for (int i = 0; i < v.length(); ) { + int cp = v.codePointAt(i); + if (!PyStr.isPrintable(cp)) { + return Py.FALSE; + } + i += Character.charCount(cp); + } + return Py.TRUE; + }); + def1(t, "isascii", a0 -> { + String v = s(a0); for (int i = 0; i < v.length(); i++) { if (v.charAt(i) > 127) { return Py.FALSE; @@ -656,8 +990,8 @@ private static void installStr() { } return Py.TRUE; }); - def(t, "isidentifier", a -> { - String v = s(a[0]); + def1(t, "isidentifier", a0 -> { + String v = s(a0); if (v.length() == 0 || !(Unicode.is(v.charAt(0), Unicode.ALPHA) || v.charAt(0) == '_')) { return Py.FALSE; } @@ -668,14 +1002,14 @@ private static void installStr() { } return Py.TRUE; }); - def(t, "ljust", a -> pad(a, 0)); - def(t, "rjust", a -> pad(a, 1)); - def(t, "center", a -> pad(a, 2)); - def(t, "zfill", a -> { - String v = s(a[0]); - int width = (int) Py.asLong(a[1]); + defOpt(t, "ljust", a -> pad(a, 0), null, (a0, a1) -> pad(a0, a1, null, 0), (a0, a1, a2) -> pad(a0, a1, a2, 0)); + defOpt(t, "rjust", a -> pad(a, 1), null, (a0, a1) -> pad(a0, a1, null, 1), (a0, a1, a2) -> pad(a0, a1, a2, 1)); + defOpt(t, "center", a -> pad(a, 2), null, (a0, a1) -> pad(a0, a1, null, 2), (a0, a1, a2) -> pad(a0, a1, a2, 2)); + def2(t, "zfill", (a0, a1) -> { + String v = s(a0); + int width = (int) Py.asLong(a1); if (v.length() >= width) { - return a[0]; + return a0; } String sign = v.length() > 0 && (v.charAt(0) == '-' || v.charAt(0) == '+') ? v.substring(0, 1) : ""; StringBuilder sb = new StringBuilder(sign); @@ -684,33 +1018,33 @@ private static void installStr() { } return Py.str(sb.append(v.substring(sign.length())).toString()); }); - def(t, "partition", a -> { - String v = s(a[0]); - String sep = strArg(a[1], "partition"); + def2(t, "partition", (a0, a1) -> { + String v = s(a0); + String sep = strArg(a1, "partition"); int i = v.indexOf(sep); if (i < 0) { - return PyTuple.of(a[0], Py.EMPTY_STR, Py.EMPTY_STR); + return PyTuple.of(a0, Py.EMPTY_STR, Py.EMPTY_STR); } - return PyTuple.of(Py.str(v.substring(0, i)), a[1], Py.str(v.substring(i + sep.length()))); + return PyTuple.of(Py.str(v.substring(0, i)), a1, Py.str(v.substring(i + sep.length()))); }); - def(t, "rpartition", a -> { - String v = s(a[0]); - String sep = strArg(a[1], "rpartition"); + def2(t, "rpartition", (a0, a1) -> { + String v = s(a0); + String sep = strArg(a1, "rpartition"); int i = v.lastIndexOf(sep); if (i < 0) { - return PyTuple.of(Py.EMPTY_STR, Py.EMPTY_STR, a[0]); + return PyTuple.of(Py.EMPTY_STR, Py.EMPTY_STR, a0); } - return PyTuple.of(Py.str(v.substring(0, i)), a[1], Py.str(v.substring(i + sep.length()))); + return PyTuple.of(Py.str(v.substring(0, i)), a1, Py.str(v.substring(i + sep.length()))); }); - def(t, "removeprefix", a -> { - String v = s(a[0]); - String p = strArg(a[1], "removeprefix"); - return v.startsWith(p) ? Py.str(v.substring(p.length())) : a[0]; + def2(t, "removeprefix", (a0, a1) -> { + String v = s(a0); + String p = strArg(a1, "removeprefix"); + return v.startsWith(p) ? Py.str(v.substring(p.length())) : a0; }); - def(t, "removesuffix", a -> { - String v = s(a[0]); - String p = strArg(a[1], "removesuffix"); - return p.length() > 0 && v.endsWith(p) ? Py.str(v.substring(0, v.length() - p.length())) : a[0]; + def2(t, "removesuffix", (a0, a1) -> { + String v = s(a0); + String p = strArg(a1, "removesuffix"); + return p.length() > 0 && v.endsWith(p) ? Py.str(v.substring(0, v.length() - p.length())) : a0; }); def(t, "expandtabs", a -> { String v = s(a[0]); @@ -732,24 +1066,72 @@ private static void installStr() { } return Py.str(sb.toString()); }); - defKw(t, "format", (args, kw) -> { + PyBuiltin format = PyBuiltin.methodKw(t, "format", (args, kw) -> { Object[] pos = new Object[args.length - kw.length - 1]; System.arraycopy(args, 1, pos, 0, pos.length); - PyDict named = new PyDict(); + PyDict named = kw.length == 0 ? null : new PyDict(); for (int i = 0; i < kw.length; i++) { named.setItem(Py.str(kw[i]), args[args.length - kw.length + i]); } return Py.str(StrFormat.format(s(args[0]), pos, named)); }); - def(t, "format_map", a -> Py.str(StrFormat.format(s(a[0]), Py.NO_ARGS, a[1]))); - defKw(t, "encode", (a, kw) -> { + // The positional calls, with no argument array per call: StrFormat + // reads its arguments and keeps none of them, so they are lent. + format.with1(a0 -> Py.str(StrFormat.format(s(a0), Py.NO_ARGS, null))); + format.with2((a0, a1) -> { + Object[] p = ArgArrays.take(1); + p[0] = a1; + String r = StrFormat.format(s(a0), p, null); + ArgArrays.give(p); + return Py.str(r); + }); + format.with3((a0, a1, a2) -> { + Object[] p = ArgArrays.take(2); + p[0] = a1; + p[1] = a2; + String r = StrFormat.format(s(a0), p, null); + ArgArrays.give(p); + return Py.str(r); + }); + format.with4((a0, a1, a2, a3) -> { + Object[] p = ArgArrays.take(3); + p[0] = a1; + p[1] = a2; + p[2] = a3; + String r = StrFormat.format(s(a0), p, null); + ArgArrays.give(p); + return Py.str(r); + }); + format.with5((a0, a1, a2, a3, a4) -> { + Object[] p = ArgArrays.take(4); + p[0] = a1; + p[1] = a2; + p[2] = a3; + p[3] = a4; + String r = StrFormat.format(s(a0), p, null); + ArgArrays.give(p); + return Py.str(r); + }); + t.define("format", format); + def2(t, "format_map", (a0, a1) -> Py.str(StrFormat.format(s(a0), Py.NO_ARGS, a1))); + final PyBuiltin encode = PyBuiltin.methodKw(t, "encode", (a, kw) -> { + // `s.encode()` and `s.encode("utf-8")`, bound without Args. + if ((kw == null || kw.length == 0) && a.length <= 2 && a[0] instanceof String + && (a.length == 1 || a[1] instanceof String)) { + return new PyBytes(Codecs.encodeShared((String) a[0], a.length == 1 ? "utf-8" : (String) a[1], "strict")); + } Object[] p = Args.bind("encode", a, kw, new String[] {"self", "encoding", "errors"}, new Object[] {null, Py.str("utf-8"), Py.str("strict")}); - return new PyBytes(Codecs.encode(s(p[0]), Py.toStr(p[1]), Py.toStr(p[2]))); + return new PyBytes(Codecs.encodeShared(s(p[0]), Py.toStr(p[1]), Py.toStr(p[2]))); }); - def(t, "__len__", a -> PyInt.of(Py.len(a[0]))); - def(t, "__contains__", a -> Py.bool(Py.obj(a[0]).contains(a[1]))); - def(t, "__getitem__", a -> Py.obj(a[0]).getItem(a[1])); + // The same two calls without an argument array, for the method-call site. + encode.with1(o -> new PyBytes(Codecs.encodeShared(s(o), "utf-8", "strict"))); + encode.with2((o, e) -> e instanceof String ? new PyBytes(Codecs.encodeShared(s(o), (String) e, "strict")) + : encode.impl.call(new Object[] {o, e}, Py.NO_KW)); + t.define("encode", encode); + def1(t, "__len__", a0 -> PyInt.of(Py.len(a0))); + def2(t, "__contains__", (a0, a1) -> Py.bool(Py.obj(a0).contains(a1))); + def2(t, "__getitem__", (a0, a1) -> Py.obj(a0).getItem(a1)); t.define("maketrans", new PyStaticMethod(PyBuiltin.positional("maketrans", a -> { PyDict d = new PyDict(); if (a.length == 1) { @@ -774,8 +1156,8 @@ private static void installStr() { } return d; }))); - def(t, "translate", a -> { - String v = s(a[0]); + def2(t, "translate", (a0, a1) -> { + String v = s(a0); StringBuilder sb = new StringBuilder(); for (int i = 0; i < v.length(); i++) { int cp = v.codePointAt(i); @@ -783,14 +1165,26 @@ private static void installStr() { i++; } Object r; - try { - r = Py.obj(a[1]).getItem(PyInt.of(cp)); - } catch (PyException e) { - if (!e.matches(Py.LOOKUP_ERROR)) { - throw e; + if (a1 instanceof PyDict && a1.getClass() == PyDict.class) { + // The usual table, from str.maketrans: most characters are not in + // it, and asking getItem raised a KeyError -- a filled-in stack + // trace -- for each of them. A dict subclass may define __missing__, + // so only the exact type is looked up directly. + r = ((PyDict) a1).getOrNull(PyInt.of(cp)); + if (r == null) { + sb.appendCodePoint(cp); + continue; + } + } else { + try { + r = Py.obj(a1).getItem(PyInt.of(cp)); + } catch (PyException e) { + if (!e.matches(Py.LOOKUP_ERROR)) { + throw e; + } + sb.appendCodePoint(cp); + continue; } - sb.appendCodePoint(cp); - continue; } if (r == Py.NONE) { //NOPMD CompareObjectsWithEquals - identity is meant continue; @@ -816,29 +1210,30 @@ private static PyList l(Object o) { private static void installList() { PyType t = Py.LIST_TYPE; - def(t, "append", a -> { - l(a[0]).append(a[1]); + def2(t, "append", (a0, a1) -> { + l(a0).append(a1); return Py.NONE; }); - def(t, "extend", a -> { - l(a[0]).extend(a[1]); + def2(t, "extend", (a0, a1) -> { + l(a0).extend(a1); return Py.NONE; }); - def(t, "insert", a -> { - l(a[0]).insert(Py.index(a[1]), a[2]); + def3(t, "insert", (a0, a1, a2) -> { + l(a0).insert(Py.index(a1), a2); return Py.NONE; }); - def(t, "pop", a -> l(a[0]).pop(a.length > 1 ? Py.index(a[1]) : -1)); - def(t, "remove", a -> { - l(a[0]).remove(a[1]); + defOpt(t, "pop", a -> l(a[0]).pop(a.length > 1 ? Py.index(a[1]) : -1), + a0 -> l(a0).pop(-1), (a0, a1) -> l(a0).pop(Py.index(a1)), null); + def2(t, "remove", (a0, a1) -> { + l(a0).remove(a1); return Py.NONE; }); - def(t, "index", a -> PyInt.of(l(a[0]).index(a[1]))); - def(t, "count", a -> { - PyList self = l(a[0]); + def2(t, "index", (a0, a1) -> PyInt.of(l(a0).index(a1))); + def2(t, "count", (a0, a1) -> { + PyList self = l(a0); int n = 0; for (int i = 0; i < self.size; i++) { - if (Py.eqBool(self.get(i), a[1])) { + if (Py.eqBool(self.get(i), a1)) { n++; } } @@ -850,48 +1245,48 @@ private static void installList() { l(args[0]).sort(a.kw("key"), rev != null && Py.isTrue(rev)); return Py.NONE; }); - def(t, "reverse", a -> { - l(a[0]).reverse(); + def1(t, "reverse", a0 -> { + l(a0).reverse(); return Py.NONE; }); - def(t, "clear", a -> { - l(a[0]).clear(); + def1(t, "clear", a0 -> { + l(a0).clear(); return Py.NONE; }); - def(t, "copy", a -> new PyList(l(a[0]).toArray())); - def(t, "__len__", a -> PyInt.of(Py.len(a[0]))); - def(t, "__getitem__", a -> Py.obj(a[0]).getItem(a[1])); - def(t, "__setitem__", a -> { - Py.obj(a[0]).setItem(a[1], a[2]); + def1(t, "copy", a0 -> new PyList(l(a0).toArray())); + def1(t, "__len__", a0 -> PyInt.of(Py.len(a0))); + def2(t, "__getitem__", (a0, a1) -> Py.obj(a0).getItem(a1)); + def3(t, "__setitem__", (a0, a1, a2) -> { + Py.obj(a0).setItem(a1, a2); return Py.NONE; }); - def(t, "__contains__", a -> Py.bool(Py.obj(a[0]).contains(a[1]))); - def(t, "__iter__", a -> Py.iter(a[0])); + def2(t, "__contains__", (a0, a1) -> Py.bool(Py.obj(a0).contains(a1))); + def1(t, "__iter__", a0 -> Py.iter(a0)); } private static void installTuple() { PyType t = Py.TUPLE_TYPE; - def(t, "count", a -> { - Object[] items = ((PyTuple) a[0]).items; + def2(t, "count", (a0, a1) -> { + Object[] items = ((PyTuple) a0).arr(); int n = 0; for (Object item : items) { - if (Py.eqBool(item, a[1])) { + if (Py.eqBool(item, a1)) { n++; } } return PyInt.of(n); }); - def(t, "index", a -> { - Object[] items = ((PyTuple) a[0]).items; + def2(t, "index", (a0, a1) -> { + Object[] items = ((PyTuple) a0).arr(); for (int i = 0; i < items.length; i++) { - if (Py.eqBool(items[i], a[1])) { + if (Py.eqBool(items[i], a1)) { return PyInt.of(i); } } throw Py.valueError("tuple.index(x): x not in tuple"); }); - def(t, "__len__", a -> PyInt.of(Py.len(a[0]))); - def(t, "__getitem__", a -> Py.obj(a[0]).getItem(a[1])); + def1(t, "__len__", a0 -> PyInt.of(Py.len(a0))); + def2(t, "__getitem__", (a0, a1) -> Py.obj(a0).getItem(a1)); } // ---- dict ------------------------------------------------------------ @@ -907,14 +1302,20 @@ private static PyDict d(Object o) { private static void installDict() { PyType t = Py.DICT_TYPE; - def(t, "get", a -> { + defOpt(t, "get", a -> { Object v = d(a[0]).getOrNull(a[1]); return v != null ? v : a.length > 2 ? a[2] : Py.NONE; + }, null, (a0, a1) -> { + Object v = d(a0).getOrNull(a1); + return v != null ? v : Py.NONE; + }, (a0, a1, a2) -> { + Object v = d(a0).getOrNull(a1); + return v != null ? v : a2; }); - def(t, "keys", a -> new PyDictView(d(a[0]), 0)); - def(t, "values", a -> new PyDictView(d(a[0]), 1)); - def(t, "items", a -> new PyDictView(d(a[0]), 2)); - def(t, "pop", a -> { + def1(t, "keys", a0 -> new PyDictView(d(a0), 0)); + def1(t, "values", a0 -> new PyDictView(d(a0), 1)); + def1(t, "items", a0 -> new PyDictView(d(a0), 2)); + defOpt(t, "pop", a -> { Object v = d(a[0]).remove(a[1]); if (v == null) { if (a.length > 2) { @@ -923,6 +1324,15 @@ private static void installDict() { throw Py.keyError(a[1]); } return v; + }, null, (a0, a1) -> { + Object v = d(a0).remove(a1); + if (v == null) { + throw Py.keyError(a1); + } + return v; + }, (a0, a1, a2) -> { + Object v = d(a0).remove(a1); + return v != null ? v : a2; }); def(t, "popitem", a -> { PyDict self = d(a[0]); @@ -938,15 +1348,8 @@ private static void installDict() { } throw Py.error(Py.KEY_ERROR, "popitem(): dictionary is empty"); }); - def(t, "setdefault", a -> { - PyDict self = d(a[0]); - Object v = self.getOrNull(a[1]); - if (v == null) { - v = a.length > 2 ? a[2] : Py.NONE; - self.setItem(a[1], v); - } - return v; - }); + defOpt(t, "setdefault", a -> setdefault(a[0], a[1], a.length > 2 ? a[2] : Py.NONE), null, + (a0, a1) -> setdefault(a0, a1, Py.NONE), TypeMethods::setdefault); defKw(t, "update", (args, kw) -> { PyDict self = d(args[0]); int npos = args.length - kw.length; @@ -958,11 +1361,11 @@ private static void installDict() { } return Py.NONE; }); - def(t, "clear", a -> { - d(a[0]).clear(); + def1(t, "clear", a0 -> { + d(a0).clear(); return Py.NONE; }); - def(t, "copy", a -> d(a[0]).copy()); + def1(t, "copy", a0 -> d(a0).copy()); t.define("fromkeys", new PyClassMethod(PyBuiltin.positional("fromkeys", a -> { PyDict r = new PyDict(); Object v = a.length > 2 ? a[2] : Py.NONE; @@ -972,14 +1375,14 @@ private static void installDict() { } return r; }))); - def(t, "__getitem__", a -> Py.obj(a[0]).getItem(a[1])); - def(t, "__setitem__", a -> { - Py.obj(a[0]).setItem(a[1], a[2]); + def2(t, "__getitem__", (a0, a1) -> Py.obj(a0).getItem(a1)); + def3(t, "__setitem__", (a0, a1, a2) -> { + Py.obj(a0).setItem(a1, a2); return Py.NONE; }); - def(t, "__contains__", a -> Py.bool(Py.obj(a[0]).contains(a[1]))); - def(t, "__len__", a -> PyInt.of(Py.len(a[0]))); - def(t, "__iter__", a -> Py.iter(a[0])); + def2(t, "__contains__", (a0, a1) -> Py.bool(Py.obj(a0).contains(a1))); + def1(t, "__len__", a0 -> PyInt.of(Py.len(a0))); + def1(t, "__iter__", a0 -> Py.iter(a0)); } // ---- set ------------------------------------------------------------- @@ -1016,34 +1419,34 @@ private static void installSet() { } return r; }); - def(t, "symmetric_difference", a -> st(a[0]).symmetricDifference(a[1])); - def(t, "issubset", a -> Py.bool(st(a[0]).isSubset(a[1]))); - def(t, "issuperset", a -> Py.bool(PySet.of(a[1], true).isSubset(a[0]))); - def(t, "isdisjoint", a -> Py.bool(st(a[0]).intersection(a[1]).len() == 0)); - def(t, "copy", a -> st(a[0]).copyAs(st(a[0]).frozen)); - def(t, "__contains__", a -> Py.bool(Py.obj(a[0]).contains(a[1]))); - def(t, "__len__", a -> PyInt.of(Py.len(a[0]))); + def2(t, "symmetric_difference", (a0, a1) -> st(a0).symmetricDifference(a1)); + def2(t, "issubset", (a0, a1) -> Py.bool(st(a0).isSubset(a1))); + def2(t, "issuperset", (a0, a1) -> Py.bool(PySet.of(a1, true).isSubset(a0))); + def2(t, "isdisjoint", (a0, a1) -> Py.bool(st(a0).intersection(a1).len() == 0)); + def1(t, "copy", a0 -> st(a0).copyAs(st(a0).frozen)); + def2(t, "__contains__", (a0, a1) -> Py.bool(Py.obj(a0).contains(a1))); + def1(t, "__len__", a0 -> PyInt.of(Py.len(a0))); } PyType t = Py.SET_TYPE; - def(t, "add", a -> { - st(a[0]).addItem(a[1]); + def2(t, "add", (a0, a1) -> { + st(a0).addItem(a1); return Py.NONE; }); - def(t, "discard", a -> { - st(a[0]).discard(a[1]); + def2(t, "discard", (a0, a1) -> { + st(a0).discard(a1); return Py.NONE; }); - def(t, "remove", a -> { - if (!st(a[0]).discard(a[1])) { - throw Py.keyError(a[1]); + def2(t, "remove", (a0, a1) -> { + if (!st(a0).discard(a1)) { + throw Py.keyError(a1); } return Py.NONE; }); - def(t, "pop", a -> { - return st(a[0]).pop(); + def1(t, "pop", a0 -> { + return st(a0).pop(); }); - def(t, "clear", a -> { - st(a[0]).clear(); + def1(t, "clear", a0 -> { + st(a0).clear(); return Py.NONE; }); def(t, "update", a -> { @@ -1056,19 +1459,19 @@ private static void installSet() { } return Py.NONE; }); - def(t, "intersection_update", a -> { - PySet self = st(a[0]); - self.replaceWith(self.intersection(a[1])); + def2(t, "intersection_update", (a0, a1) -> { + PySet self = st(a0); + self.replaceWith(self.intersection(a1)); return Py.NONE; }); - def(t, "symmetric_difference_update", a -> { - PySet self = st(a[0]); - self.replaceWith(self.symmetricDifference(a[1])); + def2(t, "symmetric_difference_update", (a0, a1) -> { + PySet self = st(a0); + self.replaceWith(self.symmetricDifference(a1)); return Py.NONE; }); - def(t, "difference_update", a -> { - PySet self = st(a[0]); - Object it = Py.iter(a[1]); + def2(t, "difference_update", (a0, a1) -> { + PySet self = st(a0); + Object it = Py.iter(a1); for (Object v = Py.next(it); v != null; v = Py.next(it)) { self.discard(v); } @@ -1149,7 +1552,7 @@ private static void installNumbers() { Object cls = args[0]; return cls == Py.INT_TYPE ? PyInt.of(v) : Py.call(cls, PyInt.of(v)); //NOPMD CompareObjectsWithEquals - identity is meant }))); - def(Py.INT_TYPE, "as_integer_ratio", a -> new PyTuple(new Object[] {a[0], PyInt.of(1)})); + def(Py.INT_TYPE, "as_integer_ratio", a -> Py.tuple(a[0], PyInt.of(1))); def(Py.INT_TYPE, "is_integer", a -> Py.TRUE); def(Py.INT_TYPE, "bit_count", a -> PyInt.of(Py.intView(a[0]).toBig().abs().bitCount())); def(Py.INT_TYPE, "conjugate", a -> a[0]); @@ -1194,7 +1597,7 @@ private static Object floatRatio(double v) { } exp -= 1075; if (mant == 0) { - return new PyTuple(new Object[] {PyInt.of(0), PyInt.of(1)}); + return Py.tuple(PyInt.of(0), PyInt.of(1)); } while ((mant & 1) == 0 && exp < 0) { mant >>= 1; @@ -1204,8 +1607,8 @@ private static Object floatRatio(double v) { mant = -mant; } if (exp >= 0) { - return new PyTuple(new Object[] {PyInt.of(BigInteger.valueOf(mant).shiftLeft(exp)), PyInt.of(1)}); + return Py.tuple(PyInt.of(BigInteger.valueOf(mant).shiftLeft(exp)), PyInt.of(1)); } - return new PyTuple(new Object[] {PyInt.of(mant), PyInt.of(BigInteger.valueOf(1).shiftLeft(-exp))}); + return Py.tuple(PyInt.of(mant), PyInt.of(BigInteger.valueOf(1).shiftLeft(-exp))); } } diff --git a/maven/python-runtime/src/main/java/com/codename1/python/runtime/Typed.java b/maven/python-runtime/src/main/java/com/codename1/python/runtime/Typed.java index 73fbcde892f..3061e36736e 100644 --- a/maven/python-runtime/src/main/java/com/codename1/python/runtime/Typed.java +++ b/maven/python-runtime/src/main/java/com/codename1/python/runtime/Typed.java @@ -61,12 +61,36 @@ public static PyList nzl(PyList l) { return l; } + /// `o`, a new instance of a compiled class extending the builtin `t`, + /// given what `t.__new__` makes of the constructor's arguments: their + /// value, or for a mutable builtin an empty one when the class has an + /// `__init__` of its own to fill it (see `PyType.newInstance`). + public static T withBase(T o, PyType t, boolean ownInit, Object... args) { + o.base = t.factory.create(t, BuiltinSubclass.mutable(t) && ownInit ? Py.NO_ARGS : args, Py.NO_KW); + return o; + } + + /// Whether `o` is one of `types`, and has its compiled layout. + public static boolean laidOut(Object o, PyType... types) { + for (PyType t : types) { + if (o == t) { //NOPMD CompareObjectsWithEquals - identity is meant + return t.hasLayout(); + } + } + return false; + } + public static Object box(Object o) { return o == null ? Py.NONE : o; } public static PyException mismatch(Object o) { - return Py.runtimeError("internal error: typed code received a value of type '" + Py.typeOf(o).name + "'"); + // Reached when a value arrives by a path the compiler could not + // see by name -- a computed setattr, a write through __dict__, a + // method found with a computed getattr -- and is not of the type + // every path it did see gives. Raised where the value is read. + return Py.typeError("a value of type '" + Py.typeOf(o).name + + "' reached compiled code through a computed attribute name, where every named use holds another type"); } public static boolean asBool(Object o) { @@ -111,19 +135,11 @@ public static String ch(int cp) { /// `len(s)`: code points, which Java's UTF-16 length overcounts by one /// per surrogate pair. public static long slen(String s) { - int n = s.length(); - long r = n; - for (int i = 0; i < n; i++) { - char c = s.charAt(i); - if (c >= 0xD800 && c < 0xDC00 && i + 1 < n) { - char d = s.charAt(i + 1); - if (d >= 0xDC00 && d < 0xE000) { - r--; - i++; - } - } - } - return r; + // codePointCount counts a lone surrogate as one, as Python does, and + // on ParparVM answers a Latin-1 string without reading it; a wide + // string a decoder made has its count in PyStr's cache. + int pairs = PyStr.cachedSurrogates(s); + return pairs >= 0 ? s.length() - pairs : s.codePointCount(0, s.length()); } /// Int `o` modulo 2^64: its low 64 bits, as two's complement keeps them. @@ -147,15 +163,34 @@ private static final class Returned { int size; } + /// Each thread's own stack, looked up only when the GIL changes hands. private static final ThreadLocal RETURNED = new ThreadLocal(); - private static Returned returned() { + /// The stack of the thread that holds the GIL. One thread runs Python at + /// a time, so the stack is a static that [Gil] points at the new owner's + /// as it takes the lock: a `try` and a big-int return were each a + /// ThreadLocal lookup, which was a tenth of a loop that catches. Code that + /// runs Python without ever taking the lock shares the first stack, which + /// is right for the one thread such a program has. + private static Returned current = new Returned(); + + /// Points [#current] at the calling thread's stack: [Gil] calls it on + /// every acquisition, while it holds the lock. + static void adoptThread() { Returned r = RETURNED.get(); if (r == null) { - r = new Returned(); + r = current.size == 0 && !adopted ? current : new Returned(); + adopted = true; RETURNED.set(r); } - return r; + current = r; + } + + /// Whether some thread has claimed the initial stack as its own. + private static boolean adopted; + + private static Returned returned() { + return current; } /// Returns int `o` from a typed function whose result is a `long`: the @@ -193,17 +228,13 @@ public static Object take() { /// How many results are waiting to be taken: kept at the start of a /// `try`, for `untake`. public static int taken() { - Returned r = RETURNED.get(); - return r == null ? 0 : r.size; + return current.size; } /// Drops the results an exception left untaken, back to `mark`: one /// raised between a call returning a marker and its caller taking it. public static void untake(int mark) { - Returned r = RETURNED.get(); - if (r == null) { - return; - } + Returned r = current; while (r.size > mark) { r.items[--r.size] = null; } @@ -221,6 +252,7 @@ public static double asFloat(Object o) { throw mismatch(o); } + public static String asStr(Object o) { if (o instanceof String) { return (String) o; @@ -287,6 +319,17 @@ public static boolean ge(Object a, Object b) { return Py.isTrue(Py.ge(a, b)); } + /// `x in c`, without the view a str container would otherwise allocate. + public static boolean in(Object x, Object c) { + if (c instanceof String && x instanceof String) { + return ((String) c).indexOf((String) x) >= 0; + } + if (c instanceof PyDict) { + return ((PyDict) c).contains(x); + } + return Py.obj(c).contains(x); + } + public static boolean eq(Object a, Object b) { if (a instanceof Long && b instanceof Long) { return ((Long) a).longValue() == ((Long) b).longValue(); @@ -312,6 +355,22 @@ public static double mod(double a, double b) { } /// `a / b` of two ints. + /// `x ** y` for two floats the transpiler proved has a real answer (an + /// integral exponent, or a base that cannot be negative). The cases Python + /// raises on, a zero base to a negative power and an overflow, go through + /// the boxed operator so they raise as it does. + public static double pow(double x, double y) { + double r = Py.powd(x, y); + if (!Double.isNaN(r) && !Double.isInfinite(r)) { + return r; + } + Object o = Py.pow(Double.valueOf(x), Double.valueOf(y)); + if (o instanceof Double) { + return ((Double) o).doubleValue(); + } + throw Py.error(Py.TYPE_ERROR, "float ** float answered a complex"); + } + public static double truediv(Object a, Object b) { return Py.asDouble(Py.truediv(a, b)); } @@ -382,6 +441,38 @@ public static void setF(PyList l, Object i, double v) { l.setItem(i, Double.valueOf(v)); } + /// `x % k` for `k` above zero: Python's remainder, which takes the + /// divisor's sign. + public static long imod(long x, long k) { + long r = x % k; + return r < 0 ? r + k : r; + } + + /// `x % y`: Python's remainder, which takes the divisor's sign; a zero + /// divisor raises ZeroDivisionError. + public static long lmod(long x, long y) { + if (y == 0) { + throw Py.zeroDivision("integer modulo by zero"); + } + long r = x % y; + return r != 0 && (r ^ y) < 0 ? r + y : r; + } + + /// `l[k]` with the index as a long. + public static Object at(PyList l, long k) { + nzl(l); + if (k >= 0 && k < l.size && l.floats == null) { + int[] n = l.ints; + return n != null ? Long.valueOf(n[(int) k]) : l.items[(int) k]; + } + return get(l, Long.valueOf(k)); + } + + /// `len(l)` as a Java long; a missing list raises as `len` does. + public static long llen(PyList l) { + return l != null ? l.size : Py.len(Py.NONE); + } + public static Object len(PyList l) { return Long.valueOf(nzl(l).size); } @@ -443,6 +534,13 @@ public static PyList rangeList(Object start, Object stop, Object step) { } /// `list(l)`, a shallow copy. + /// `list(x)` of any iterable, for typed code that knows nothing of `x`. + public static PyList listOf(Object iterable) { + PyList r = new PyList(); + r.extend(iterable); + return r; + } + public static PyList copy(PyList l) { return iterable(l).getSlice(Py.NONE, Py.NONE, Py.NONE); } @@ -453,6 +551,47 @@ public static Object append(PyList l, Object v) { } /// `l.extend(other)` for two lists. + /// `min(a, b)` where `f` is what the name `min` holds: the first of + /// the smallest, compared as the builtin compares (`b < a`), with no + /// argument array. + public static Object min2(Object f, Object a, Object b) { + if (f != Builtins.MIN) { //NOPMD CompareObjectsWithEquals - identity is meant + return Py.call(f, a, b); + } + if (a instanceof Long && b instanceof Long) { + return ((Long) b).longValue() < ((Long) a).longValue() ? b : a; + } + return Py.isTrue(Py.lt(b, a)) ? b : a; + } + + /// `max(a, b)`, as [#min2]: the first of the largest (`b > a`). + public static Object max2(Object f, Object a, Object b) { + if (f != Builtins.MAX) { //NOPMD CompareObjectsWithEquals - identity is meant + return Py.call(f, a, b); + } + if (a instanceof Long && b instanceof Long) { + return ((Long) b).longValue() > ((Long) a).longValue() ? b : a; + } + return Py.isTrue(Py.gt(b, a)) ? b : a; + } + + /// `l.extend([a, b])`: appended in order, no list made for them. + public static Object extend2(PyList l, Object a, Object b) { + PyList n = nzl(l); + n.append(a); + n.append(b); + return Py.NONE; + } + + /// `l.extend([a, b, c])`, as [#extend2]. + public static Object extend3(PyList l, Object a, Object b, Object c) { + PyList n = nzl(l); + n.append(a); + n.append(b); + n.append(c); + return Py.NONE; + } + public static Object extend(PyList l, PyList other) { nzl(l).extend(nzl(other)); return Py.NONE; @@ -471,6 +610,98 @@ public static Object dget(AttrSite site, Object m, long k) { } /// `m[k] = v` for an int key. + /// `s.split()` / `s.split(sep)` on a str: a fresh list of strs. + public static PyList split(String s, Object sep) { + return TypeMethods.split(s, sep, -1); + } + + /// `d[k]` on a dict the transpiler followed from a display: a plain + /// `PyDict`, so a key that is not there raises KeyError, as the generic + /// read does. + public static Object dgetv(Object d, Object k) { + // Checked: a dict a guarded field guesses may be anything, and a + // cast does not fail on ParparVM. + Object v = d instanceof PyDict ? ((PyDict) d).getOrNull(k) : null; + return v != null ? v : Py.getitem(d, k); + } + + /// `d.get(k, def)` on a plain `PyDict`: no attribute lookup, no call. + public static Object dgetd(Object d, Object k, Object def) { + if (!(d instanceof PyDict)) { + return Py.call(Py.getattr(d, "get"), k, def); + } + Object v = ((PyDict) d).getOrNull(k); + return v != null ? v : def; + } + + /// Where the next word of `s.split()` starts at or after `a`: + /// `s.length()` when there is none. With [#wordEnd], a loop over the + /// words that makes no list. + public static int wordStart(String s, int a) { + int n = s.length(); + while (a < n) { + char c = s.charAt(a); + if ((c <= ' ' || c >= '\u0085') && TypeMethods.isSpace(c)) { + a++; + } else { + break; + } + } + return a; + } + + /// Where the word of `s.split()` starting at `a` ends. + public static int wordEnd(String s, int a) { + int n = s.length(); + int b = a + 1; + while (b < n) { + char c = s.charAt(b); + if ((c <= ' ' || c >= '\u0085') && TypeMethods.isSpace(c)) { + break; + } + b++; + } + return b; + } + + /// The separator of `s.split(sep)` in a loop over the pieces. + public static String splitSep(String sep) { + if (sep.isEmpty()) { + throw Py.valueError("empty separator"); + } + return sep; + } + + /// `d[k]` probed on a plain dict: the value, or [Py#MISS] -- never a + /// [Py.Miss], since a plain dict raises no KeyError of its own. + /// A probe of a value typed a dict that is not one: its answer, with a + /// KeyError folded to [Py#MISS] as a plain dict's miss is. + private static Object probeOf(Object r) { + return r instanceof Py.Miss ? Py.MISS : r; + } + + public static Object dprobe(Object d, long k) { + if (!(d instanceof PyDict)) { + return probeOf(Py.getitemOrMiss(d, Long.valueOf(k))); + } + Object v = ((PyDict) d).getLong(k); + return v != null ? v : Py.MISS; + } + + public static Object dprobe(Object d, Object k) { + if (!(d instanceof PyDict)) { + return probeOf(Py.getitemOrMiss(d, k)); + } + Object v = ((PyDict) d).getOrNull(k); + return v != null ? v : Py.MISS; + } + + /// Whether `o` is a plain dict, of no subclass: what a typed function + /// taking a dict the transpiler followed may be entered with. + public static boolean isDict(Object o) { + return o != null && o.getClass() == PyDict.class; + } + public static void dset(Object m, long k, Object v) { if (m instanceof PyDict) { ((PyDict) m).setLong(k, v); @@ -479,6 +710,23 @@ public static void dset(Object m, long k, Object v) { Py.setitem(m, Long.valueOf(k), v); } + /// `set(o)` without the type's constructor dispatch, unless the name + /// was rebound at run time. + /// `set()`: an empty set, unless the name `set` was rebound. + public static Object set(Object f) { + if (f == Py.SET_TYPE) { //NOPMD CompareObjectsWithEquals - identity is meant + return new PySet(); + } + return Py.call(f); + } + + public static Object set(Object f, Object o) { + if (f == Py.SET_TYPE) { //NOPMD CompareObjectsWithEquals - identity is meant + return PySet.of(o, false); + } + return Py.call(f, o); + } + public static long len(Object f, Object o) { if (f == Builtins.LEN) { //NOPMD CompareObjectsWithEquals - identity is meant if (o instanceof PyDict) { @@ -532,6 +780,236 @@ public static T none(Object ignored) { } /// An expression statement whose value is dropped. + /// A typed function's read of a local that not every path binds: null + /// is unbound, as no Python value is. + /// The object half of a typed int local before it is first bound: a read + /// that may come first checks for it with [#boundInt]. + public static final Object UNBOUND = new Object(); + + /// The object half of a typed field no constructor is known to set, + /// until something is stored in it: the field is absent. Typed code + /// tests the object half against null, which this is not, so only the + /// slow path ever meets it (see [#present]). + public static final Object UNSET = new Object(); + + /// The object half `b` of field `attr` of `recv` as a value: `b` itself, + /// or, when the field was never set, what reading the attribute + /// generically answers -- a class attribute, `__getattr__`, or + /// AttributeError. + public static Object present(Object b, Object recv, String attr) { + return b != UNSET ? b : Py.getattr(recv, attr); + } + + + + + + + /// The object half `big` of int local `name`, raising UnboundLocalError + /// while the local has never been bound. + public static Object boundInt(Object big, String name) { + if (big == UNBOUND) { + throw Py.unboundLocal(name); + } + return big; + } + + public static T local(T v, String name) { + if (v == null) { + throw Py.unboundLocal(name); + } + return v; + } + public static void drop(Object ignored) { } + + /// `s.strip()`, `lstrip()` and `rstrip()` with no argument, on a str + /// the transpiler knows is one. + public static String strip(String s, boolean left, boolean right) { + return TypeMethods.strip(s, null, left, right); + } + + /// `s.strip(chars)` and its one-sided forms. + public static String strip(String s, String chars, boolean left, boolean right) { + return TypeMethods.strip(s, chars, left, right); + } + + /// `s.find(sub)` and `s.rfind(sub)` over the whole string. + public static long find(String s, String sub, boolean last) { + return TypeMethods.findWhole(s, sub, last); + } + + /// `s[i]` of a str: the one character there, counted in code points + /// and from the end when negative. + /// How many surrogate pairs `s` holds, for [#sat(String, long, int)]. + public static int surr(String s) { + return PyStr.surrogates(s); + } + + /// [#sat(String, long)] with the pair count of `s` already known: a + /// local bound once and read by index in a loop (html.parser's + /// `rawdata[k]`) counts them once per binding, not once per read. + public static String sat(String s, long i, int surrogates) { + if (surrogates == 0 && i >= 0 && i < s.length()) { + return ch(s.charAt((int) i)); + } + return asStr(Py.getitem(s, Long.valueOf(i))); + } + + /// `s[i] in t`: the char searched for in place when `s` holds no + /// surrogate pair, so no one-char string is made or looked up. + public static boolean inAt(String t, String s, long i, int surrogates) { + if (surrogates == 0 && i >= 0 && i < s.length()) { + return t.indexOf(s.charAt((int) i)) >= 0; + } + return t.indexOf(sat(s, i, surrogates)) >= 0; + } + + /// `s[i] == c` for a one-char str `c` that is not half of a pair. + public static boolean charIs(String s, long i, int surrogates, char c) { + if (surrogates == 0 && i >= 0 && i < s.length()) { + return s.charAt((int) i) == c; + } + return sat(s, i, surrogates).equals(String.valueOf(c)); + } + + public static String sat(String s, long i) { + if (i >= 0 && i < s.length() && PyStr.surrogates(s) == 0) { + return ch(s.charAt((int) i)); + } + return asStr(Py.getitem(s, Long.valueOf(i))); + } + + /// `s.find(sub, start, end)` and `s.rfind(sub, start, end)`; a bound left + /// out is `Py.NONE`. + public static long find(String s, String sub, Object start, Object end, boolean last) { + return TypeMethods.findIn(s, sub, start, end, last); + } + + /// `s.startswith(sub, start, end)` and `s.endswith(sub, start, end)`. + public static boolean affix(String s, String sub, Object start, Object end, boolean startsWith) { + return TypeMethods.affixIn(s, sub, start, end, startsWith); + } + + /// `s.find(sub, start)` and `s.rfind(sub, start)`. + public static long find(String s, String sub, long start, boolean last) { + return TypeMethods.findFrom(s, sub, start, last); + } + + /// `s.startswith(sub, start)` and `s.endswith(sub, start)`. + public static boolean affix(String s, String sub, long start, boolean startsWith) { + return TypeMethods.affixFrom(s, sub, start, startsWith); + } + + /// `s.isspace()` and the other tests of every character, by name. + public static boolean isAll(String s, int kind) { + switch (kind) { + case 0: + return TypeMethods.allOf(s, Unicode.SPACE); + case 1: + return TypeMethods.allOf(s, Unicode.DIGIT); + case 2: + return TypeMethods.allOf(s, Unicode.DECIMAL); + case 3: + return TypeMethods.allOf(s, Unicode.NUMERIC); + case 4: + return TypeMethods.allOf(s, Unicode.ALPHA); + default: + return TypeMethods.allOf(s, Unicode.ALPHA | Unicode.DECIMAL | Unicode.DIGIT | Unicode.NUMERIC); + } + } + + /// `s.replace(old, new)` with no count. + public static String replace(String v, String old, String nw) { + if (old.length() == 0) { + StringBuilder sb = new StringBuilder(nw); + for (int i = 0; i < v.length(); i++) { + sb.append(v.charAt(i)).append(nw); + } + return sb.toString(); + } + return v.replace(old, nw); + } + + /// `s.count(sub)` over the whole string. + public static long count(String v, String sub) { + if (sub.length() == 0) { + return PyStr.codePoints(v) + 1; + } + long n = 0; + for (int i = v.indexOf(sub); i >= 0; i = v.indexOf(sub, i + sub.length())) { + n++; + } + return n; + } + + /// `s.lower()` (mode 0) and `s.upper()` (mode 1). + public static String mapCase(String s, int mode) { + return TypeMethods.mapCase(s, mode); + } + + /// `sep.join(items)`. + public static String join(String sep, Object items) { + return TypeMethods.join(sep, items); + } + + /// `s[a:b:c]` on a str the transpiler knows is one. + public static String slice(String s, Object a, Object b, Object c) { + Object r = Py.getslice(s, a, b, c); + return r instanceof String ? (String) r : String.valueOf(r); + } + + /// `s[a:b]` with int bounds held as longs: `aw` / `bw`, when not + /// null, is the bound's real value (a big int, a bool) and `a` / `b` + /// are ignored. + public static String sliceL(String s, long a, Object aw, long b, Object bw) { + int n = s.length(); + if (aw != null || bw != null || PyStr.surrogates(s) != 0) { + // A big int or bool bound, or a string whose code points are not + // its chars: the generic slice. + return slice(s, aw != null ? aw : Long.valueOf(a), bw != null ? bw : b == Long.MAX_VALUE ? Py.NONE + : Long.valueOf(b), Py.NONE); + } + int i = Py.clampSlice(a, n); + int j = b == Long.MAX_VALUE ? n : Py.clampSlice(b, n); + return j <= i ? "" : i == 0 && j == n ? s : s.substring(i, j); + } + + /// `s.encode(enc, errors)` on a str; a null encoding or handler is the + /// default. The result may share its array with the bytes `s` was + /// decoded from (see `Codecs.encodeShared`). + public static Object encode(String s, String enc, String errors) { + return new PyBytes(Codecs.encodeShared(s, enc == null ? "utf-8" : enc, errors == null ? "strict" : errors)); + } + + /// `b.decode(enc, errors)` on a value the transpiler typed as bytes; a + /// null encoding or handler is the default. Anything else (only a + /// rebinding the inference cannot see) takes the method call. + public static String decode(Object b, String enc, String errors) { + String e = enc == null ? "utf-8" : enc; + String h = errors == null ? "strict" : errors; + if (b instanceof PyBytes) { + return Codecs.decodeKeep(((PyBytes) b).value, e, h); + } + return Py.toStr(Py.callMethod(b, "decode", e, h)); + } + + /// `b[i]` on a value the transpiler typed as bytes: the byte as an int. + public static long bat(Object b, long i) { + if (b instanceof PyBytes) { + byte[] v = ((PyBytes) b).value; + long k = i < 0 ? i + v.length : i; + if (k >= 0 && k < v.length) { + return v[(int) k] & 0xff; + } + } + return toLong(Py.getitem(b, Long.valueOf(i))); + } + + /// `fmt % args` for a str format and a tuple of values. + public static String format(String fmt, Object args) { + Object r = Py.mod(fmt, args); + return r instanceof String ? (String) r : Py.toStr(r); + } } diff --git a/maven/python-runtime/src/main/java/com/codename1/python/runtime/Unicode.java b/maven/python-runtime/src/main/java/com/codename1/python/runtime/Unicode.java index 48591f28af5..727c0a4b6a5 100644 --- a/maven/python-runtime/src/main/java/com/codename1/python/runtime/Unicode.java +++ b/maven/python-runtime/src/main/java/com/codename1/python/runtime/Unicode.java @@ -68,6 +68,37 @@ static boolean is(char c, int mask) { return (FLAGS[c] & mask) != 0; } + /// `str.isprintable()` of one code point, on every plane. A holder class, + /// so a program that never calls repr() on non-Latin-1 text never decodes + /// the table. + static boolean printable(int cp) { + int[] e = Printable.EDGES; + int lo = 0; + int hi = e.length; + // The number of edges at or below cp: odd means inside a printable run. + while (lo < hi) { + int mid = (lo + hi) >>> 1; + if (e[mid] <= cp) { + lo = mid + 1; + } else { + hi = mid; + } + } + return (lo & 1) != 0; + } + + private static final class Printable { + static final int[] EDGES; + + static { + String s = join(UnicodeTables.PRINTABLE); + EDGES = new int[s.length() / 2]; + for (int i = 0; i < EDGES.length; i++) { + EDGES[i] = s.charAt(2 * i) << 16 | s.charAt(2 * i + 1); + } + } + } + private static String join(String[] parts) { StringBuilder sb = new StringBuilder(); for (String p : parts) { @@ -81,6 +112,9 @@ private static String join(String[] parts) { static final class Mapping { private final char[] keys; private final String[] values; + /// What each Latin-1 char maps to when that is one Latin-1 char, + /// else -1 (sharp s upper-cases to two, y-diaeresis to U+0178). + final short[] latin1 = new short[256]; Mapping(String[] table) { String t = join(table); @@ -96,6 +130,10 @@ static final class Mapping { values[k] = t.substring(i + 2, i + 2 + t.charAt(i + 1)); k++; } + for (int c = 0; c < 256; c++) { + String v = get((char) c); + latin1[c] = v == null ? (short) c : v.length() == 1 && v.charAt(0) < 256 ? (short) v.charAt(0) : -1; + } } /// What `c` maps to, or null when it maps to itself. diff --git a/maven/python-runtime/src/main/java/com/codename1/python/runtime/UnicodeTables.java b/maven/python-runtime/src/main/java/com/codename1/python/runtime/UnicodeTables.java index 4bfe8a4976d..050ed512ca2 100644 --- a/maven/python-runtime/src/main/java/com/codename1/python/runtime/UnicodeTables.java +++ b/maven/python-runtime/src/main/java/com/codename1/python/runtime/UnicodeTables.java @@ -23,12 +23,17 @@ */ package com.codename1.python.runtime; +/// The tables are generated from the Unicode Character Database, licensed under +/// the Unicode License v3 (text in maven/python-runtime/third-party/unicode/LICENSE.txt). +/// /// Generated by `maven/python-runtime/tools/gen_unicode_tables.py` from /// the Unicode 15.1.0 data of CPython 3.13; do not edit by hand. /// /// `FLAGS` is runs of (first char, property bits) over the Basic /// Multilingual Plane; each mapping table is entries of (char, length, -/// mapped chars), in char order. [Unicode] decodes them. +/// mapped chars), in char order. `PRINTABLE` is the code points, over +/// every plane, where `str.isprintable()` changes, two chars each. +/// [Unicode] decodes them. final class UnicodeTables { private UnicodeTables() { } @@ -37,6 +42,10 @@ private UnicodeTables() { "\u0000\u0000\u0009@\u000e\u0000\u001c@!\u000008:\u0000A\u0085[\u0000a\u0086{\u0000\u0085@\u0086\u0000\u00a0@\u00a1\u0000\u00aa\u0086\u00ab\u0000\u00b20\u00b4\u0000\u00b5\u0086\u00b6\u0000\u00b90\u00ba\u0086\u00bb\u0000\u00bc \u00bf\u0000\u00c0\u0085\u00d7\u0000\u00d8\u0085\u00df\u0086\u00f7\u0000\u00f8\u0086\u0100\u0085\u0101\u0086\u0102\u0085\u0103\u0086\u0104\u0085\u0105\u0086\u0106\u0085\u0107\u0086\u0108\u0085\u0109\u0086\u010a\u0085\u010b\u0086\u010c\u0085\u010d\u0086\u010e\u0085\u010f\u0086\u0110\u0085\u0111\u0086\u0112\u0085\u0113\u0086\u0114\u0085\u0115\u0086\u0116\u0085\u0117\u0086\u0118\u0085\u0119\u0086\u011a\u0085\u011b\u0086\u011c\u0085\u011d\u0086\u011e\u0085\u011f\u0086\u0120\u0085\u0121\u0086\u0122\u0085\u0123\u0086\u0124\u0085\u0125\u0086\u0126\u0085\u0127\u0086\u0128\u0085\u0129\u0086\u012a\u0085\u012b\u0086\u012c\u0085\u012d\u0086\u012e\u0085\u012f\u0086\u0130\u0085\u0131\u0086\u0132\u0085\u0133\u0086\u0134\u0085\u0135\u0086\u0136\u0085\u0137\u0086\u0139\u0085\u013a\u0086\u013b\u0085\u013c\u0086\u013d\u0085\u013e\u0086\u013f\u0085\u0140\u0086\u0141\u0085\u0142\u0086\u0143\u0085\u0144\u0086\u0145\u0085\u0146\u0086\u0147\u0085\u0148\u0086\u014a\u0085\u014b\u0086\u014c\u0085\u014d\u0086\u014e\u0085\u014f\u0086\u0150\u0085\u0151\u0086\u0152\u0085\u0153\u0086\u0154\u0085\u0155\u0086\u0156\u0085\u0157\u0086\u0158\u0085\u0159\u0086\u015a\u0085\u015b\u0086\u015c\u0085\u015d\u0086\u015e\u0085\u015f\u0086\u0160\u0085\u0161\u0086\u0162\u0085\u0163\u0086\u0164\u0085\u0165\u0086\u0166\u0085\u0167\u0086\u0168\u0085\u0169\u0086\u016a\u0085\u016b\u0086\u016c\u0085\u016d\u0086\u016e\u0085\u016f\u0086\u0170\u0085\u0171\u0086\u0172\u0085\u0173\u0086\u0174\u0085\u0175\u0086\u0176\u0085\u0177\u0086\u0178\u0085\u017a\u0086\u017b\u0085\u017c\u0086\u017d\u0085\u017e\u0086\u0181\u0085\u0183\u0086\u0184\u0085\u0185\u0086\u0186\u0085\u0188\u0086\u0189\u0085\u018c\u0086\u018e\u0085\u0192\u0086\u0193\u0085\u0195\u0086\u0196\u0085\u0199\u0086\u019c\u0085\u019e\u0086\u019f\u0085\u01a1\u0086\u01a2\u0085\u01a3\u0086\u01a4\u0085\u01a5\u0086\u01a6\u0085\u01a8\u0086\u01a9\u0085\u01aa\u0086\u01ac\u0085\u01ad\u0086\u01ae\u0085\u01b0\u0086\u01b1\u0085\u01b4\u0086\u01b5\u0085\u01b6\u0086\u01b7\u0085\u01b9\u0086\u01bb\u0004\u01bc\u0085\u01bd\u0086\u01c0\u0004\u01c4\u0085\u01c5\u0084\u01c6\u0086\u01c7\u0085\u01c8\u0084\u01c9\u0086\u01ca\u0085\u01cb\u0084\u01cc\u0086\u01cd\u0085\u01ce\u0086\u01cf\u0085\u01d0\u0086\u01d1\u0085\u01d2\u0086\u01d3\u0085\u01d4\u0086\u01d5\u0085\u01d6\u0086\u01d7\u0085\u01d8\u0086\u01d9\u0085\u01da\u0086\u01db\u0085\u01dc\u0086\u01de\u0085\u01df\u0086\u01e0\u0085\u01e1\u0086\u01e2\u0085\u01e3\u0086\u01e4\u0085\u01e5\u0086\u01e6\u0085\u01e7\u0086\u01e8\u0085\u01e9\u0086\u01ea\u0085\u01eb\u0086\u01ec\u0085\u01ed\u0086\u01ee\u0085\u01ef\u0086\u01f1\u0085\u01f2\u0084\u01f3\u0086\u01f4\u0085\u01f5\u0086\u01f6\u0085\u01f9\u0086\u01fa\u0085\u01fb\u0086\u01fc\u0085\u01fd\u0086\u01fe\u0085\u01ff\u0086\u0200\u0085\u0201\u0086\u0202\u0085\u0203\u0086\u0204\u0085\u0205\u0086\u0206\u0085\u0207\u0086\u0208\u0085\u0209\u0086\u020a\u0085\u020b\u0086\u020c\u0085\u020d\u0086\u020e\u0085\u020f\u0086\u0210\u0085\u0211\u0086\u0212\u0085\u0213\u0086\u0214\u0085\u0215\u0086\u0216\u0085\u0217\u0086\u0218\u0085\u0219\u0086\u021a\u0085\u021b\u0086\u021c\u0085\u021d\u0086\u021e\u0085\u021f\u0086\u0220\u0085\u0221\u0086\u0222\u0085\u0223\u0086\u0224\u0085\u0225\u0086\u0226\u0085\u0227\u0086\u0228\u0085\u0229\u0086\u022a\u0085\u022b\u0086\u022c\u0085\u022d\u0086\u022e\u0085\u022f\u0086\u0230\u0085\u0231\u0086\u0232\u0085\u0233\u0086\u023a\u0085\u023c\u0086\u023d\u0085\u023f\u0086\u0241\u0085\u0242\u0086\u0243\u0085\u0247\u0086\u0248\u0085\u0249\u0086\u024a\u0085\u024b\u0086\u024c\u0085\u024d\u0086\u024e\u0085\u024f\u0086\u0294\u0004\u0295\u0086\u02b9\u0004\u02c0\u0086\u02c2\u0000\u02c6\u0004\u02d2\u0000\u02e0\u0086\u02e5\u0000\u02ec\u0004\u02ed\u0000\u02ee\u0004\u02ef\u0000\u0345\u0082\u0346\u0000\u0370\u0085\u0371\u0086\u0372\u0085\u0373\u0086\u0374\u0004\u0375\u0000\u0376\u0085\u0377\u0086\u0378\u0000\u037a\u0086\u037e\u0000\u037f\u0085\u0380\u0000\u0386\u0085\u0387\u0000\u0388\u0085\u038b\u0000\u038c\u0085\u038d\u0000\u038e\u0085\u0390\u0086\u0391\u0085\u03a2\u0000\u03a3\u0085\u03ac\u0086\u03cf\u0085\u03d0\u0086\u03d2\u0085\u03d5\u0086\u03d8\u0085\u03d9\u0086\u03da\u0085\u03db\u0086\u03dc\u0085\u03dd\u0086\u03de\u0085\u03df\u0086\u03e0\u0085\u03e1\u0086\u03e2\u0085\u03e3\u0086\u03e4\u0085\u03e5\u0086\u03e6\u0085\u03e7\u0086\u03e8\u0085\u03e9\u0086\u03ea\u0085\u03eb\u0086\u03ec\u0085\u03ed\u0086\u03ee\u0085\u03ef\u0086\u03f4\u0085\u03f5\u0086\u03f6\u0000\u03f7\u0085\u03f8\u0086\u03f9\u0085\u03fb\u0086\u03fd\u0085\u0430\u0086\u0460\u0085\u0461\u0086\u0462\u0085\u0463\u0086\u0464\u0085\u0465\u0086\u0466\u0085\u0467\u0086\u0468\u0085\u0469\u0086\u046a\u0085\u046b\u0086\u046c\u0085\u046d\u0086\u046e\u0085\u046f\u0086\u0470\u0085\u0471\u0086\u0472\u0085\u0473\u0086\u0474\u0085\u0475\u0086\u0476\u0085\u0477\u0086\u0478\u0085\u0479\u0086\u047a\u0085\u047b\u0086\u047c\u0085\u047d\u0086\u047e\u0085\u047f\u0086\u0480\u0085\u0481\u0086\u0482\u0000\u048a\u0085\u048b\u0086\u048c\u0085\u048d\u0086\u048e\u0085\u048f\u0086\u0490\u0085\u0491\u0086\u0492\u0085\u0493\u0086\u0494\u0085\u0495\u0086\u0496\u0085\u0497\u0086\u0498\u0085\u0499\u0086\u049a\u0085\u049b\u0086\u049c\u0085\u049d\u0086\u049e\u0085\u049f\u0086\u04a0\u0085\u04a1\u0086\u04a2\u0085\u04a3\u0086\u04a4\u0085\u04a5\u0086\u04a6\u0085\u04a7\u0086\u04a8\u0085\u04a9\u0086\u04aa\u0085\u04ab\u0086\u04ac\u0085\u04ad\u0086\u04ae\u0085\u04af\u0086\u04b0\u0085\u04b1\u0086\u04b2\u0085\u04b3\u0086\u04b4\u0085\u04b5\u0086\u04b6\u0085\u04b7\u0086\u04b8\u0085\u04b9\u0086\u04ba\u0085\u04bb\u0086\u04bc\u0085\u04bd\u0086\u04be\u0085\u04bf\u0086\u04c0\u0085\u04c2\u0086\u04c3\u0085\u04c4\u0086\u04c5\u0085\u04c6\u0086\u04c7\u0085\u04c8\u0086\u04c9\u0085\u04ca\u0086\u04cb\u0085\u04cc\u0086\u04cd\u0085\u04ce\u0086\u04d0\u0085\u04d1\u0086\u04d2\u0085\u04d3\u0086\u04d4\u0085\u04d5\u0086\u04d6\u0085\u04d7\u0086\u04d8\u0085\u04d9\u0086\u04da\u0085\u04db\u0086\u04dc\u0085\u04dd\u0086\u04de\u0085\u04df\u0086\u04e0\u0085\u04e1\u0086\u04e2\u0085\u04e3\u0086\u04e4\u0085\u04e5\u0086\u04e6\u0085\u04e7\u0086\u04e8\u0085\u04e9\u0086\u04ea\u0085\u04eb\u0086\u04ec\u0085\u04ed\u0086\u04ee\u0085\u04ef\u0086\u04f0\u0085\u04f1\u0086\u04f2\u0085\u04f3\u0086\u04f4\u0085\u04f5\u0086\u04f6\u0085\u04f7\u0086\u04f8\u0085\u04f9\u0086\u04fa\u0085\u04fb\u0086\u04fc\u0085\u04fd\u0086\u04fe\u0085\u04ff\u0086\u0500\u0085\u0501\u0086\u0502\u0085\u0503\u0086\u0504\u0085\u0505\u0086\u0506\u0085\u0507\u0086\u0508\u0085\u0509\u0086\u050a\u0085\u050b\u0086\u050c\u0085\u050d\u0086\u050e\u0085\u050f\u0086\u0510\u0085\u0511\u0086\u0512\u0085\u0513\u0086\u0514\u0085\u0515\u0086\u0516\u0085\u0517\u0086\u0518\u0085\u0519\u0086\u051a\u0085\u051b\u0086\u051c\u0085\u051d\u0086\u051e\u0085\u051f\u0086\u0520\u0085\u0521\u0086\u0522\u0085\u0523\u0086\u0524\u0085\u0525\u0086\u0526\u0085\u0527\u0086\u0528\u0085\u0529\u0086\u052a\u0085\u052b\u0086\u052c\u0085\u052d\u0086\u052e\u0085\u052f\u0086\u0530\u0000\u0531\u0085\u0557\u0000\u0559\u0004\u055a\u0000\u0560\u0086\u0589\u0000\u05d0\u0004\u05eb\u0000\u05ef\u0004\u05f3\u0000\u0620\u0004\u064b\u0000\u06608\u066a\u0000\u066e\u0004\u0670\u0000\u0671\u0004\u06d4\u0000\u06d5\u0004\u06d6\u0000\u06e5\u0004\u06e7\u0000\u06ee\u0004\u06f08\u06fa\u0004\u06fd\u0000\u06ff\u0004\u0700\u0000\u0710\u0004\u0711\u0000\u0712\u0004\u0730\u0000\u074d\u0004\u07a6\u0000\u07b1\u0004\u07b2\u0000\u07c08\u07ca\u0004\u07eb\u0000\u07f4\u0004\u07f6\u0000\u07fa\u0004\u07fb\u0000\u0800\u0004\u0816\u0000\u081a\u0004\u081b\u0000\u0824\u0004\u0825\u0000\u0828\u0004\u0829\u0000\u0840\u0004\u0859\u0000\u0860\u0004\u086b\u0000\u0870\u0004\u0888\u0000\u0889\u0004\u088f\u0000\u08a0\u0004\u08ca\u0000\u0904\u0004\u093a\u0000\u093d\u0004\u093e\u0000\u0950\u0004\u0951\u0000\u0958\u0004\u0962\u0000\u09668\u0970\u0000\u0971\u0004\u0981\u0000\u0985\u0004\u098d\u0000\u098f\u0004\u0991\u0000\u0993\u0004\u09a9\u0000\u09aa\u0004\u09b1\u0000\u09b2\u0004\u09b3\u0000\u09b6\u0004\u09ba\u0000\u09bd\u0004\u09be\u0000\u09ce\u0004\u09cf\u0000\u09dc\u0004\u09de\u0000\u09df\u0004\u09e2\u0000\u09e68\u09f0\u0004\u09f2\u0000\u09f4 \u09fa\u0000\u09fc\u0004\u09fd\u0000\u0a05\u0004\u0a0b\u0000\u0a0f\u0004\u0a11\u0000\u0a13\u0004\u0a29\u0000\u0a2a\u0004\u0a31\u0000\u0a32\u0004\u0a34\u0000\u0a35\u0004\u0a37\u0000\u0a38\u0004\u0a3a\u0000\u0a59\u0004\u0a5d\u0000\u0a5e\u0004\u0a5f\u0000\u0a668\u0a70\u0000\u0a72\u0004\u0a75\u0000\u0a85\u0004\u0a8e\u0000\u0a8f\u0004\u0a92\u0000\u0a93\u0004\u0aa9\u0000\u0aaa\u0004\u0ab1\u0000\u0ab2\u0004\u0ab4\u0000\u0ab5\u0004\u0aba\u0000\u0abd\u0004\u0abe\u0000\u0ad0\u0004\u0ad1\u0000\u0ae0\u0004\u0ae2\u0000\u0ae68\u0af0\u0000\u0af9\u0004\u0afa\u0000\u0b05\u0004\u0b0d\u0000\u0b0f\u0004\u0b11\u0000\u0b13\u0004\u0b29\u0000\u0b2a\u0004\u0b31\u0000\u0b32\u0004\u0b34\u0000\u0b35\u0004\u0b3a\u0000\u0b3d\u0004\u0b3e\u0000\u0b5c\u0004\u0b5e\u0000\u0b5f\u0004\u0b62\u0000\u0b668\u0b70\u0000\u0b71\u0004\u0b72 \u0b78\u0000\u0b83\u0004\u0b84\u0000\u0b85\u0004\u0b8b\u0000\u0b8e\u0004\u0b91\u0000\u0b92\u0004\u0b96\u0000\u0b99\u0004\u0b9b\u0000\u0b9c\u0004\u0b9d\u0000\u0b9e\u0004\u0ba0\u0000\u0ba3\u0004\u0ba5\u0000\u0ba8\u0004\u0bab\u0000\u0bae\u0004\u0bba\u0000\u0bd0\u0004\u0bd1\u0000\u0be68\u0bf0 \u0bf3\u0000\u0c05\u0004\u0c0d\u0000\u0c0e\u0004\u0c11\u0000\u0c12\u0004\u0c29\u0000\u0c2a\u0004\u0c3a\u0000\u0c3d\u0004\u0c3e\u0000\u0c58\u0004\u0c5b\u0000\u0c5d\u0004\u0c5e\u0000\u0c60\u0004\u0c62\u0000\u0c668\u0c70\u0000\u0c78 \u0c7f\u0000\u0c80\u0004\u0c81\u0000\u0c85\u0004\u0c8d\u0000\u0c8e\u0004\u0c91\u0000\u0c92\u0004\u0ca9\u0000\u0caa\u0004\u0cb4\u0000\u0cb5\u0004\u0cba\u0000\u0cbd\u0004\u0cbe\u0000\u0cdd\u0004\u0cdf\u0000\u0ce0\u0004\u0ce2\u0000\u0ce68\u0cf0\u0000\u0cf1\u0004\u0cf3\u0000\u0d04\u0004\u0d0d\u0000\u0d0e\u0004\u0d11\u0000\u0d12\u0004\u0d3b\u0000\u0d3d\u0004\u0d3e\u0000\u0d4e\u0004\u0d4f\u0000\u0d54\u0004\u0d57\u0000\u0d58 \u0d5f\u0004\u0d62\u0000\u0d668\u0d70 \u0d79\u0000\u0d7a\u0004\u0d80\u0000\u0d85\u0004\u0d97\u0000\u0d9a\u0004\u0db2\u0000\u0db3\u0004\u0dbc\u0000\u0dbd\u0004\u0dbe\u0000\u0dc0\u0004\u0dc7\u0000\u0de68\u0df0\u0000\u0e01\u0004\u0e31\u0000\u0e32\u0004\u0e34\u0000\u0e40\u0004\u0e47\u0000\u0e508\u0e5a\u0000\u0e81\u0004\u0e83\u0000\u0e84\u0004\u0e85\u0000\u0e86\u0004\u0e8b\u0000\u0e8c\u0004\u0ea4\u0000\u0ea5\u0004\u0ea6\u0000\u0ea7\u0004\u0eb1\u0000\u0eb2\u0004\u0eb4\u0000\u0ebd\u0004\u0ebe\u0000\u0ec0\u0004\u0ec5\u0000\u0ec6\u0004\u0ec7\u0000\u0ed08\u0eda\u0000\u0edc\u0004\u0ee0\u0000\u0f00\u0004\u0f01\u0000\u0f208\u0f2a \u0f34\u0000\u0f40\u0004\u0f48\u0000\u0f49\u0004\u0f6d\u0000\u0f88\u0004\u0f8d\u0000\u1000\u0004\u102b\u0000\u103f\u0004\u10408\u104a\u0000\u1050\u0004\u1056\u0000\u105a\u0004\u105e\u0000\u1061\u0004\u1062\u0000\u1065\u0004\u1067\u0000\u106e\u0004\u1071\u0000\u1075\u0004\u1082\u0000\u108e\u0004\u108f\u0000\u10908\u109a\u0000\u10a0\u0085\u10c6\u0000\u10c7\u0085\u10c8\u0000\u10cd\u0085\u10ce\u0000\u10d0\u0086\u10fb\u0000\u10fc\u0086\u1100\u0004\u1249\u0000\u124a\u0004\u124e\u0000\u1250\u0004\u1257\u0000\u1258\u0004\u1259\u0000\u125a\u0004\u125e\u0000\u1260\u0004\u1289\u0000\u128a\u0004\u128e\u0000\u1290\u0004\u12b1\u0000\u12b2\u0004\u12b6\u0000\u12b8\u0004\u12bf\u0000\u12c0\u0004\u12c1\u0000\u12c2\u0004\u12c6\u0000\u12c8\u0004\u12d7\u0000\u12d8\u0004\u1311\u0000\u1312\u0004\u1316\u0000\u1318\u0004\u135b\u0000\u13690\u1372 \u137d\u0000\u1380\u0004\u1390\u0000\u13a0\u0085\u13f6\u0000\u13f8\u0086\u13fe\u0000\u1401\u0004\u166d\u0000\u166f\u0004\u1680@\u1681\u0004\u169b\u0000\u16a0\u0004\u16eb\u0000\u16ee \u16f1\u0004\u16f9\u0000\u1700\u0004\u1712\u0000\u171f\u0004\u1732\u0000\u1740\u0004\u1752\u0000\u1760\u0004\u176d\u0000\u176e\u0004\u1771\u0000\u1780\u0004\u17b4\u0000\u17d7\u0004\u17d8\u0000\u17dc\u0004\u17dd\u0000\u17e08\u17ea\u0000\u17f0 \u17fa\u0000\u18108\u181a\u0000\u1820\u0004\u1879\u0000\u1880\u0004\u1885\u0000\u1887\u0004\u18a9\u0000\u18aa\u0004\u18ab\u0000\u18b0\u0004\u18f6\u0000\u1900\u0004\u191f\u0000\u19468\u1950\u0004\u196e\u0000\u1970\u0004\u1975\u0000\u1980\u0004\u19ac\u0000\u19b0\u0004\u19ca\u0000\u19d08\u19da0\u19db\u0000\u1a00\u0004\u1a17\u0000\u1a20\u0004\u1a55\u0000\u1a808\u1a8a\u0000\u1a908\u1a9a\u0000\u1aa7\u0004\u1aa8\u0000\u1b05\u0004\u1b34\u0000\u1b45\u0004\u1b4d\u0000\u1b508\u1b5a\u0000\u1b83\u0004\u1ba1\u0000\u1bae\u0004\u1bb08\u1bba\u0004\u1be6\u0000\u1c00\u0004\u1c24\u0000\u1c408\u1c4a\u0000\u1c4d\u0004\u1c508\u1c5a\u0004\u1c7e\u0000\u1c80\u0086\u1c89\u0000\u1c90\u0085\u1cbb\u0000\u1cbd\u0085\u1cc0\u0000\u1ce9\u0004\u1ced\u0000\u1cee\u0004\u1cf4\u0000\u1cf5\u0004\u1cf7\u0000\u1cfa\u0004\u1cfb\u0000\u1d00\u0086\u1dc0\u0000\u1e00\u0085\u1e01\u0086\u1e02\u0085\u1e03\u0086\u1e04\u0085\u1e05\u0086\u1e06\u0085\u1e07\u0086\u1e08\u0085\u1e09\u0086\u1e0a\u0085\u1e0b\u0086\u1e0c\u0085\u1e0d\u0086\u1e0e\u0085\u1e0f\u0086\u1e10\u0085\u1e11\u0086\u1e12\u0085\u1e13\u0086\u1e14\u0085\u1e15\u0086\u1e16\u0085\u1e17\u0086\u1e18\u0085\u1e19\u0086\u1e1a\u0085\u1e1b\u0086\u1e1c\u0085\u1e1d\u0086\u1e1e\u0085\u1e1f\u0086\u1e20\u0085\u1e21\u0086\u1e22\u0085\u1e23\u0086\u1e24\u0085\u1e25\u0086\u1e26\u0085\u1e27\u0086\u1e28\u0085\u1e29\u0086\u1e2a\u0085\u1e2b\u0086\u1e2c\u0085\u1e2d\u0086\u1e2e\u0085\u1e2f\u0086\u1e30\u0085\u1e31\u0086\u1e32\u0085\u1e33\u0086\u1e34\u0085\u1e35\u0086\u1e36\u0085\u1e37\u0086\u1e38\u0085\u1e39\u0086\u1e3a\u0085\u1e3b\u0086\u1e3c\u0085\u1e3d\u0086\u1e3e\u0085\u1e3f\u0086\u1e40\u0085\u1e41\u0086\u1e42\u0085\u1e43\u0086\u1e44\u0085\u1e45\u0086\u1e46\u0085\u1e47\u0086\u1e48\u0085\u1e49\u0086\u1e4a\u0085\u1e4b\u0086\u1e4c\u0085\u1e4d\u0086\u1e4e\u0085\u1e4f\u0086\u1e50\u0085\u1e51\u0086\u1e52\u0085\u1e53\u0086\u1e54\u0085\u1e55\u0086\u1e56\u0085\u1e57\u0086\u1e58\u0085\u1e59\u0086\u1e5a\u0085\u1e5b\u0086\u1e5c\u0085\u1e5d\u0086\u1e5e\u0085\u1e5f\u0086\u1e60\u0085\u1e61\u0086\u1e62\u0085\u1e63\u0086\u1e64\u0085\u1e65\u0086\u1e66\u0085\u1e67\u0086\u1e68\u0085\u1e69\u0086\u1e6a\u0085\u1e6b\u0086\u1e6c\u0085\u1e6d\u0086\u1e6e\u0085\u1e6f\u0086\u1e70\u0085\u1e71\u0086\u1e72\u0085\u1e73\u0086\u1e74\u0085\u1e75\u0086\u1e76\u0085\u1e77\u0086\u1e78\u0085\u1e79\u0086\u1e7a\u0085\u1e7b\u0086\u1e7c\u0085\u1e7d\u0086\u1e7e\u0085\u1e7f\u0086\u1e80\u0085\u1e81\u0086\u1e82\u0085\u1e83\u0086\u1e84\u0085\u1e85\u0086\u1e86\u0085\u1e87\u0086\u1e88\u0085\u1e89\u0086\u1e8a\u0085\u1e8b\u0086\u1e8c\u0085\u1e8d\u0086\u1e8e\u0085\u1e8f\u0086\u1e90\u0085\u1e91\u0086\u1e92\u0085\u1e93\u0086\u1e94\u0085\u1e95\u0086\u1e9e\u0085\u1e9f\u0086\u1ea0\u0085\u1ea1\u0086\u1ea2\u0085\u1ea3\u0086\u1ea4\u0085\u1ea5\u0086\u1ea6\u0085\u1ea7\u0086\u1ea8\u0085\u1ea9\u0086\u1eaa\u0085\u1eab\u0086\u1eac\u0085\u1ead\u0086\u1eae\u0085\u1eaf\u0086\u1eb0\u0085\u1eb1\u0086\u1eb2\u0085\u1eb3\u0086\u1eb4\u0085\u1eb5\u0086\u1eb6\u0085\u1eb7\u0086\u1eb8\u0085\u1eb9\u0086\u1eba\u0085\u1ebb\u0086\u1ebc\u0085\u1ebd\u0086\u1ebe\u0085\u1ebf\u0086\u1ec0\u0085\u1ec1\u0086\u1ec2\u0085\u1ec3\u0086\u1ec4\u0085\u1ec5\u0086\u1ec6\u0085\u1ec7\u0086\u1ec8\u0085\u1ec9\u0086\u1eca\u0085\u1ecb\u0086\u1ecc\u0085\u1ecd\u0086\u1ece\u0085\u1ecf\u0086\u1ed0\u0085\u1ed1\u0086\u1ed2\u0085\u1ed3\u0086\u1ed4\u0085\u1ed5\u0086\u1ed6\u0085\u1ed7\u0086\u1ed8\u0085\u1ed9\u0086\u1eda\u0085\u1edb\u0086\u1edc\u0085\u1edd\u0086\u1ede\u0085\u1edf\u0086\u1ee0\u0085\u1ee1\u0086\u1ee2\u0085\u1ee3\u0086\u1ee4\u0085\u1ee5\u0086\u1ee6\u0085\u1ee7\u0086\u1ee8\u0085\u1ee9\u0086\u1eea\u0085\u1eeb\u0086\u1eec\u0085\u1eed\u0086\u1eee\u0085\u1eef\u0086\u1ef0\u0085\u1ef1\u0086\u1ef2\u0085\u1ef3\u0086\u1ef4\u0085\u1ef5\u0086\u1ef6\u0085\u1ef7\u0086\u1ef8\u0085\u1ef9\u0086\u1efa\u0085\u1efb\u0086\u1efc\u0085\u1efd\u0086\u1efe\u0085\u1eff\u0086\u1f08\u0085\u1f10\u0086\u1f16\u0000\u1f18\u0085\u1f1e\u0000\u1f20\u0086\u1f28\u0085\u1f30\u0086\u1f38\u0085\u1f40\u0086\u1f46\u0000\u1f48\u0085\u1f4e\u0000\u1f50\u0086\u1f58\u0000\u1f59\u0085\u1f5a\u0000\u1f5b\u0085\u1f5c\u0000\u1f5d\u0085\u1f5e\u0000\u1f5f\u0085\u1f60\u0086\u1f68\u0085\u1f70\u0086\u1f7e\u0000\u1f80\u0086\u1f88\u0084\u1f90\u0086\u1f98\u0084\u1fa0\u0086\u1fa8\u0084\u1fb0\u0086\u1fb5\u0000\u1fb6\u0086\u1fb8\u0085\u1fbc\u0084\u1fbd\u0000\u1fbe\u0086\u1fbf\u0000\u1fc2\u0086\u1fc5\u0000\u1fc6\u0086\u1fc8\u0085\u1fcc\u0084\u1fcd\u0000\u1fd0\u0086\u1fd4\u0000\u1fd6\u0086\u1fd8\u0085\u1fdc\u0000\u1fe0\u0086\u1fe8\u0085\u1fed\u0000\u1ff2\u0086\u1ff5\u0000\u1ff6\u0086\u1ff8\u0085\u1ffc\u0084\u1ffd\u0000\u2000@\u200b\u0000\u2028@\u202a\u0000\u202f@\u2030\u0000\u205f@\u2060\u0000\u20700\u2071\u0086\u2072\u0000\u20740\u207a\u0000\u207f\u0086\u20800\u208a\u0000\u2090\u0086\u209d\u0000\u2102\u0085\u2103\u0000\u2107\u0085\u2108\u0000\u210a\u0086\u210b\u0085\u210e\u0086\u2110\u0085\u2113\u0086\u2114\u0000\u2115\u0085\u2116\u0000\u2119\u0085\u211e\u0000\u2124\u0085\u2125\u0000\u2126\u0085\u2127\u0000\u2128\u0085\u2129\u0000\u212a\u0085\u212e\u0000\u212f\u0086\u2130\u0085\u2134\u0086\u2135\u0004\u2139\u0086\u213a\u0000\u213c\u0086\u213e\u0085\u2140\u0000\u2145\u0085\u2146\u0086\u214a\u0000\u214e\u0086\u214f\u0000\u2150 \u2160\u00a1\u2170\u00a2\u2180 \u2183\u0085\u2184\u0086\u2185 \u218a\u0000\u24600\u2469 \u24740\u247d \u24880\u2491 \u249c\u0000\u24b6\u0081\u24d0\u0082\u24ea0\u24eb \u24f50\u24fe \u24ff0\u2500\u0000\u27760\u277f \u27800\u2789 \u278a0\u2793 \u2794\u0000\u2c00\u0085\u2c30\u0086\u2c60\u0085\u2c61\u0086\u2c62\u0085\u2c65\u0086\u2c67\u0085\u2c68\u0086\u2c69\u0085\u2c6a\u0086\u2c6b\u0085\u2c6c\u0086\u2c6d\u0085\u2c71\u0086\u2c72\u0085\u2c73\u0086\u2c75\u0085\u2c76\u0086\u2c7e\u0085\u2c81\u0086\u2c82\u0085\u2c83\u0086\u2c84\u0085\u2c85\u0086\u2c86\u0085\u2c87\u0086\u2c88\u0085\u2c89\u0086\u2c8a\u0085\u2c8b\u0086\u2c8c\u0085\u2c8d\u0086\u2c8e\u0085\u2c8f\u0086\u2c90\u0085\u2c91\u0086\u2c92\u0085\u2c93\u0086\u2c94\u0085\u2c95\u0086\u2c96\u0085\u2c97\u0086\u2c98\u0085\u2c99\u0086\u2c9a\u0085\u2c9b\u0086\u2c9c\u0085\u2c9d\u0086\u2c9e\u0085\u2c9f\u0086\u2ca0\u0085\u2ca1\u0086\u2ca2\u0085\u2ca3\u0086\u2ca4\u0085\u2ca5\u0086\u2ca6\u0085\u2ca7\u0086\u2ca8\u0085\u2ca9\u0086\u2caa\u0085\u2cab\u0086\u2cac\u0085\u2cad\u0086\u2cae\u0085\u2caf\u0086\u2cb0\u0085\u2cb1\u0086\u2cb2\u0085\u2cb3\u0086\u2cb4\u0085\u2cb5\u0086\u2cb6\u0085\u2cb7\u0086\u2cb8\u0085\u2cb9\u0086\u2cba\u0085\u2cbb\u0086\u2cbc\u0085\u2cbd\u0086\u2cbe\u0085\u2cbf\u0086\u2cc0\u0085\u2cc1\u0086\u2cc2\u0085\u2cc3\u0086\u2cc4\u0085\u2cc5\u0086\u2cc6\u0085\u2cc7\u0086\u2cc8\u0085\u2cc9\u0086\u2cca\u0085\u2ccb\u0086\u2ccc\u0085\u2ccd\u0086\u2cce\u0085\u2ccf\u0086\u2cd0\u0085\u2cd1\u0086\u2cd2\u0085\u2cd3\u0086\u2cd4\u0085\u2cd5\u0086\u2cd6\u0085\u2cd7\u0086\u2cd8\u0085\u2cd9\u0086\u2cda\u0085\u2cdb\u0086\u2cdc\u0085\u2cdd\u0086\u2cde\u0085\u2cdf\u0086\u2ce0\u0085\u2ce1\u0086\u2ce2\u0085\u2ce3\u0086\u2ce5\u0000\u2ceb\u0085\u2cec\u0086\u2ced\u0085\u2cee\u0086\u2cef\u0000\u2cf2\u0085\u2cf3\u0086\u2cf4\u0000\u2cfd \u2cfe\u0000\u2d00\u0086\u2d26\u0000\u2d27\u0086\u2d28\u0000\u2d2d\u0086\u2d2e\u0000\u2d30\u0004\u2d68\u0000\u2d6f\u0004\u2d70\u0000\u2d80\u0004\u2d97\u0000\u2da0\u0004\u2da7\u0000\u2da8\u0004\u2daf\u0000\u2db0\u0004\u2db7\u0000\u2db8\u0004\u2dbf\u0000\u2dc0\u0004\u2dc7\u0000\u2dc8\u0004\u2dcf\u0000\u2dd0\u0004\u2dd7\u0000\u2dd8\u0004\u2ddf\u0000\u2e2f\u0004\u2e30\u0000\u3000@\u3001\u0000\u3005\u0004\u3007 \u3008\u0000\u3021 \u302a\u0000\u3031\u0004\u3036\u0000\u3038 \u303b\u0004\u303d\u0000\u3041\u0004\u3097\u0000\u309d\u0004\u30a0\u0000\u30a1\u0004\u30fb\u0000\u30fc\u0004\u3100\u0000\u3105\u0004\u3130\u0000\u3131\u0004\u318f\u0000\u3192 \u3196\u0000\u31a0\u0004\u31c0\u0000\u31f0\u0004\u3200\u0000\u3220 \u322a\u0000\u3248 \u3250\u0000\u3251 \u3260\u0000\u3280 \u328a\u0000\u32b1 \u32c0\u0000\u3400\u0004\u3405$\u3406\u0004\u3483$\u3484\u0004\u382a$\u382b\u0004\u3b4d$\u3b4e\u0004\u4dc0\u0000\u4e00$\u4e01\u0004\u4e03$\u4e04\u0004\u4e07$\u4e08\u0004\u4e09$\u4e0a\u0004\u4e24$\u4e25\u0004\u4e5d$\u4e5e\u0004\u4e8c$\u4e8d\u0004\u4e94$\u4e95\u0004\u4e96$\u4e97\u0004\u4eac$\u4ead\u0004\u4ebf$\u4ec1\u0004\u4edf$\u4ee0\u0004\u4ee8$\u4ee9\u0004\u4f0d$\u4f0e\u0004\u4f70$\u4f71\u0004\u4fe9$\u4fea\u0004\u5006$\u5007\u0004\u5104$\u5105\u0004\u5146$\u5147\u0004\u5169$\u516a\u0004\u516b$\u516c\u0004\u516d$\u516e\u0004\u5341$\u5342\u0004\u5343$\u5346\u0004\u534c$\u534d\u0004\u53c1$\u53c5\u0004\u56db$\u56dc\u0004\u58f1$\u58f2\u0004\u58f9$\u58fa\u0004\u5e7a$\u5e7b\u0004\u5efe$\u5f00\u0004\u5f0c$\u5f0f\u0004\u5f10$\u5f11\u0004\u62d0$\u62d1\u0004\u62fe$\u62ff\u0004\u634c$\u634d\u0004\u67d2$\u67d3\u0004\u6d1e$\u6d1f\u0004\u6f06$\u6f07\u0004\u7396$\u7397\u0004\u767e$\u767f\u0004\u7695$\u7696\u0004\u79ed$\u79ee\u0004\u8086$\u8087\u0004\u842c$\u842d\u0004\u8cae$\u8caf\u0004\u8cb3$\u8cb4\u0004\u8d30$\u8d31\u0004\u920e$\u920f\u0004\u94a9$\u94aa\u0004\u9621$\u9622\u0004\u9646$\u9647\u0004\u964c$\u964d\u0004\u9678$\u9679\u0004\u96f6$\u96f7\u0004\ua48d\u0000\ua4d0\u0004\ua4fe\u0000\ua500\u0004\ua60d\u0000\ua610\u0004\ua6208\ua62a\u0004\ua62c\u0000\ua640\u0085\ua641\u0086\ua642\u0085\ua643\u0086\ua644\u0085\ua645\u0086\ua646\u0085\ua647\u0086\ua648\u0085\ua649\u0086\ua64a\u0085\ua64b\u0086\ua64c\u0085\ua64d\u0086\ua64e\u0085\ua64f\u0086\ua650\u0085\ua651\u0086\ua652\u0085\ua653\u0086\ua654\u0085\ua655\u0086\ua656\u0085\ua657\u0086\ua658\u0085\ua659\u0086\ua65a\u0085\ua65b\u0086\ua65c\u0085\ua65d\u0086\ua65e\u0085\ua65f\u0086\ua660\u0085\ua661\u0086\ua662\u0085\ua663\u0086\ua664\u0085\ua665\u0086\ua666\u0085\ua667\u0086\ua668\u0085\ua669\u0086\ua66a\u0085\ua66b\u0086\ua66c\u0085\ua66d\u0086\ua66e\u0004\ua66f\u0000\ua67f\u0004\ua680\u0085\ua681\u0086\ua682\u0085\ua683\u0086\ua684\u0085\ua685\u0086\ua686\u0085\ua687\u0086\ua688\u0085\ua689\u0086\ua68a\u0085\ua68b\u0086\ua68c\u0085\ua68d\u0086\ua68e\u0085\ua68f\u0086\ua690\u0085\ua691\u0086\ua692\u0085\ua693\u0086\ua694\u0085\ua695\u0086\ua696\u0085\ua697\u0086\ua698\u0085\ua699\u0086\ua69a\u0085\ua69b\u0086\ua69e\u0000\ua6a0\u0004\ua6e6 \ua6f0\u0000\ua717\u0004\ua720\u0000\ua722\u0085\ua723\u0086\ua724\u0085\ua725\u0086\ua726\u0085\ua727\u0086\ua728\u0085\ua729\u0086\ua72a\u0085\ua72b\u0086\ua72c\u0085\ua72d\u0086\ua72e\u0085\ua72f\u0086\ua732\u0085\ua733\u0086\ua734\u0085\ua735\u0086\ua736\u0085\ua737\u0086\ua738\u0085\ua739\u0086\ua73a\u0085\ua73b\u0086\ua73c\u0085\ua73d\u0086\ua73e\u0085\ua73f\u0086\ua740\u0085\ua741\u0086\ua742\u0085\ua743\u0086\ua744\u0085\ua745\u0086\ua746\u0085\ua747\u0086\ua748\u0085\ua749\u0086\ua74a\u0085\ua74b\u0086\ua74c\u0085\ua74d\u0086\ua74e\u0085\ua74f\u0086\ua750\u0085\ua751\u0086\ua752\u0085\ua753\u0086\ua754\u0085\ua755\u0086\ua756\u0085\ua757\u0086\ua758\u0085\ua759\u0086\ua75a\u0085\ua75b\u0086\ua75c\u0085\ua75d\u0086\ua75e\u0085\ua75f\u0086\ua760\u0085\ua761\u0086\ua762\u0085\ua763\u0086\ua764\u0085\ua765\u0086\ua766\u0085\ua767\u0086\ua768\u0085\ua769\u0086\ua76a\u0085\ua76b\u0086\ua76c\u0085\ua76d\u0086\ua76e\u0085\ua76f\u0086\ua779\u0085\ua77a\u0086\ua77b\u0085\ua77c\u0086\ua77d\u0085\ua77f\u0086\ua780\u0085\ua781\u0086\ua782\u0085\ua783\u0086\ua784\u0085\ua785\u0086\ua786\u0085\ua787\u0086\ua788\u0004\ua789\u0000\ua78b\u0085\ua78c\u0086\ua78d\u0085\ua78e\u0086\ua78f\u0004\ua790\u0085\ua791\u0086\ua792\u0085\ua793\u0086\ua796\u0085\ua797\u0086\ua798\u0085\ua799\u0086\ua79a\u0085\ua79b\u0086\ua79c\u0085\ua79d\u0086\ua79e\u0085\ua79f\u0086\ua7a0\u0085\ua7a1\u0086\ua7a2\u0085\ua7a3\u0086\ua7a4\u0085\ua7a5\u0086\ua7a6\u0085\ua7a7\u0086\ua7a8\u0085\ua7a9\u0086\ua7aa\u0085\ua7af\u0086\ua7b0\u0085\ua7b5\u0086\ua7b6\u0085\ua7b7\u0086\ua7b8\u0085\ua7b9\u0086\ua7ba\u0085\ua7bb\u0086\ua7bc\u0085\ua7bd\u0086\ua7be\u0085\ua7bf\u0086\ua7c0\u0085\ua7c1\u0086\ua7c2\u0085\ua7c3\u0086\ua7c4\u0085\ua7c8\u0086\ua7c9\u0085\ua7ca\u0086\ua7cb\u0000\ua7d0\u0085\ua7d1\u0086\ua7d2\u0000\ua7d3\u0086\ua7d4\u0000\ua7d5\u0086\ua7d6\u0085\ua7d7\u0086\ua7d8\u0085\ua7d9\u0086\ua7da\u0000\ua7f2\u0086\ua7f5\u0085\ua7f6\u0086\ua7f7\u0004\ua7f8\u0086\ua7fb\u0004\ua802\u0000\ua803\u0004\ua806\u0000\ua807\u0004\ua80b\u0000\ua80c\u0004\ua823\u0000\ua830 \ua836\u0000\ua840\u0004\ua874\u0000\ua882\u0004\ua8b4\u0000\ua8d08\ua8da\u0000\ua8f2\u0004\ua8f8\u0000\ua8fb\u0004\ua8fc\u0000\ua8fd\u0004\ua8ff\u0000\ua9008\ua90a\u0004\ua926\u0000\ua930\u0004\ua947\u0000\ua960\u0004\ua97d\u0000\ua984\u0004\ua9b3\u0000\ua9cf\u0004\ua9d08\ua9da\u0000\ua9e0\u0004\ua9e5\u0000\ua9e6\u0004\ua9f08\ua9fa\u0004\ua9ff\u0000\uaa00\u0004\uaa29\u0000\uaa40\u0004\uaa43\u0000\uaa44\u0004\uaa4c\u0000\uaa508\uaa5a\u0000\uaa60\u0004\uaa77\u0000\uaa7a\u0004\uaa7b\u0000\uaa7e\u0004\uaab0\u0000\uaab1\u0004\uaab2\u0000\uaab5\u0004\uaab7\u0000\uaab9\u0004\uaabe\u0000\uaac0\u0004\uaac1\u0000\uaac2\u0004\uaac3\u0000\uaadb\u0004\uaade\u0000\uaae0\u0004\uaaeb\u0000\uaaf2\u0004\uaaf5\u0000\uab01\u0004\uab07\u0000\uab09\u0004\uab0f\u0000\uab11\u0004\uab17\u0000\uab20\u0004\uab27\u0000\uab28\u0004\uab2f\u0000\uab30\u0086\uab5b\u0000\uab5c\u0086\uab6a\u0000\uab70\u0086\uabc0\u0004\uabe3\u0000\uabf08\uabfa\u0000\uac00\u0004\ud7a4\u0000\ud7b0\u0004\ud7c7\u0000\ud7cb\u0004\ud7fc\u0000\uf900\u0004\uf96b$\uf96c\u0004\uf973$\uf974\u0004\uf978$\uf979\u0004\uf9b2$\uf9b3\u0004\uf9d1$\uf9d2\u0004\uf9d3$\uf9d4\u0004\uf9fd$\uf9fe\u0004\ufa6e\u0000\ufa70\u0004\ufada\u0000\ufb00\u0086\ufb07\u0000\ufb13\u0086\ufb18\u0000\ufb1d\u0004\ufb1e\u0000\ufb1f\u0004\ufb29\u0000\ufb2a\u0004\ufb37\u0000\ufb38\u0004\ufb3d\u0000\ufb3e\u0004\ufb3f\u0000\ufb40\u0004\ufb42\u0000\ufb43\u0004\ufb45\u0000\ufb46\u0004\ufbb2\u0000\ufbd3\u0004\ufd3e\u0000\ufd50\u0004\ufd90\u0000\ufd92\u0004\ufdc8\u0000\ufdf0\u0004\ufdfc\u0000\ufe70\u0004\ufe75\u0000\ufe76\u0004\ufefd\u0000\uff108\uff1a\u0000\uff21\u0085\uff3b\u0000\uff41\u0086\uff5b\u0000\uff66\u0004\uffbf\u0000\uffc2\u0004\uffc8\u0000\uffca\u0004\uffd0\u0000\uffd2\u0004\uffd8\u0000\uffda\u0004\uffdd\u0000", }; + static final String[] PRINTABLE = { + "\u0000 \u0000\u007f\u0000\u00a1\u0000\u00ad\u0000\u00ae\u0000\u0378\u0000\u037a\u0000\u0380\u0000\u0384\u0000\u038b\u0000\u038c\u0000\u038d\u0000\u038e\u0000\u03a2\u0000\u03a3\u0000\u0530\u0000\u0531\u0000\u0557\u0000\u0559\u0000\u058b\u0000\u058d\u0000\u0590\u0000\u0591\u0000\u05c8\u0000\u05d0\u0000\u05eb\u0000\u05ef\u0000\u05f5\u0000\u0606\u0000\u061c\u0000\u061d\u0000\u06dd\u0000\u06de\u0000\u070e\u0000\u0710\u0000\u074b\u0000\u074d\u0000\u07b2\u0000\u07c0\u0000\u07fb\u0000\u07fd\u0000\u082e\u0000\u0830\u0000\u083f\u0000\u0840\u0000\u085c\u0000\u085e\u0000\u085f\u0000\u0860\u0000\u086b\u0000\u0870\u0000\u088f\u0000\u0898\u0000\u08e2\u0000\u08e3\u0000\u0984\u0000\u0985\u0000\u098d\u0000\u098f\u0000\u0991\u0000\u0993\u0000\u09a9\u0000\u09aa\u0000\u09b1\u0000\u09b2\u0000\u09b3\u0000\u09b6\u0000\u09ba\u0000\u09bc\u0000\u09c5\u0000\u09c7\u0000\u09c9\u0000\u09cb\u0000\u09cf\u0000\u09d7\u0000\u09d8\u0000\u09dc\u0000\u09de\u0000\u09df\u0000\u09e4\u0000\u09e6\u0000\u09ff\u0000\u0a01\u0000\u0a04\u0000\u0a05\u0000\u0a0b\u0000\u0a0f\u0000\u0a11\u0000\u0a13\u0000\u0a29\u0000\u0a2a\u0000\u0a31\u0000\u0a32\u0000\u0a34\u0000\u0a35\u0000\u0a37\u0000\u0a38\u0000\u0a3a\u0000\u0a3c\u0000\u0a3d\u0000\u0a3e\u0000\u0a43\u0000\u0a47\u0000\u0a49\u0000\u0a4b\u0000\u0a4e\u0000\u0a51\u0000\u0a52\u0000\u0a59\u0000\u0a5d\u0000\u0a5e\u0000\u0a5f\u0000\u0a66\u0000\u0a77\u0000\u0a81\u0000\u0a84\u0000\u0a85\u0000\u0a8e\u0000\u0a8f\u0000\u0a92\u0000\u0a93\u0000\u0aa9\u0000\u0aaa\u0000\u0ab1\u0000\u0ab2\u0000\u0ab4\u0000\u0ab5\u0000\u0aba\u0000\u0abc\u0000\u0ac6\u0000\u0ac7\u0000\u0aca\u0000\u0acb\u0000\u0ace\u0000\u0ad0\u0000\u0ad1\u0000\u0ae0\u0000\u0ae4\u0000\u0ae6\u0000\u0af2\u0000\u0af9\u0000\u0b00\u0000\u0b01\u0000\u0b04\u0000\u0b05\u0000\u0b0d\u0000\u0b0f\u0000\u0b11\u0000\u0b13\u0000\u0b29\u0000\u0b2a\u0000\u0b31\u0000\u0b32\u0000\u0b34\u0000\u0b35\u0000\u0b3a\u0000\u0b3c\u0000\u0b45\u0000\u0b47\u0000\u0b49\u0000\u0b4b\u0000\u0b4e\u0000\u0b55\u0000\u0b58\u0000\u0b5c\u0000\u0b5e\u0000\u0b5f\u0000\u0b64\u0000\u0b66\u0000\u0b78\u0000\u0b82\u0000\u0b84\u0000\u0b85\u0000\u0b8b\u0000\u0b8e\u0000\u0b91\u0000\u0b92\u0000\u0b96\u0000\u0b99\u0000\u0b9b\u0000\u0b9c\u0000\u0b9d\u0000\u0b9e\u0000\u0ba0\u0000\u0ba3\u0000\u0ba5\u0000\u0ba8\u0000\u0bab\u0000\u0bae\u0000\u0bba\u0000\u0bbe\u0000\u0bc3\u0000\u0bc6\u0000\u0bc9\u0000\u0bca\u0000\u0bce\u0000\u0bd0\u0000\u0bd1\u0000\u0bd7\u0000\u0bd8\u0000\u0be6\u0000\u0bfb\u0000\u0c00\u0000\u0c0d\u0000\u0c0e\u0000\u0c11\u0000\u0c12\u0000\u0c29\u0000\u0c2a\u0000\u0c3a\u0000\u0c3c\u0000\u0c45\u0000\u0c46\u0000\u0c49\u0000\u0c4a\u0000\u0c4e\u0000\u0c55\u0000\u0c57\u0000\u0c58\u0000\u0c5b\u0000\u0c5d\u0000\u0c5e\u0000\u0c60\u0000\u0c64\u0000\u0c66\u0000\u0c70\u0000\u0c77\u0000\u0c8d\u0000\u0c8e\u0000\u0c91\u0000\u0c92\u0000\u0ca9\u0000\u0caa\u0000\u0cb4\u0000\u0cb5\u0000\u0cba\u0000\u0cbc\u0000\u0cc5\u0000\u0cc6\u0000\u0cc9\u0000\u0cca\u0000\u0cce\u0000\u0cd5\u0000\u0cd7\u0000\u0cdd\u0000\u0cdf\u0000\u0ce0\u0000\u0ce4\u0000\u0ce6\u0000\u0cf0\u0000\u0cf1\u0000\u0cf4\u0000\u0d00\u0000\u0d0d\u0000\u0d0e\u0000\u0d11\u0000\u0d12\u0000\u0d45\u0000\u0d46\u0000\u0d49\u0000\u0d4a\u0000\u0d50\u0000\u0d54\u0000\u0d64\u0000\u0d66\u0000\u0d80\u0000\u0d81\u0000\u0d84\u0000\u0d85\u0000\u0d97\u0000\u0d9a\u0000\u0db2\u0000\u0db3\u0000\u0dbc\u0000\u0dbd\u0000\u0dbe\u0000\u0dc0\u0000\u0dc7\u0000\u0dca\u0000\u0dcb\u0000\u0dcf\u0000\u0dd5\u0000\u0dd6\u0000\u0dd7\u0000\u0dd8\u0000\u0de0\u0000\u0de6\u0000\u0df0\u0000\u0df2\u0000\u0df5\u0000\u0e01\u0000\u0e3b\u0000\u0e3f\u0000\u0e5c\u0000\u0e81\u0000\u0e83\u0000\u0e84\u0000\u0e85\u0000\u0e86\u0000\u0e8b\u0000\u0e8c\u0000\u0ea4\u0000\u0ea5\u0000\u0ea6\u0000\u0ea7\u0000\u0ebe\u0000\u0ec0\u0000\u0ec5\u0000\u0ec6\u0000\u0ec7\u0000\u0ec8\u0000\u0ecf\u0000\u0ed0\u0000\u0eda\u0000\u0edc\u0000\u0ee0\u0000\u0f00\u0000\u0f48\u0000\u0f49\u0000\u0f6d\u0000\u0f71\u0000\u0f98\u0000\u0f99\u0000\u0fbd\u0000\u0fbe\u0000\u0fcd\u0000\u0fce\u0000\u0fdb\u0000\u1000\u0000\u10c6\u0000\u10c7\u0000\u10c8\u0000\u10cd\u0000\u10ce\u0000\u10d0\u0000\u1249\u0000\u124a\u0000\u124e\u0000\u1250\u0000\u1257\u0000\u1258\u0000\u1259\u0000\u125a\u0000\u125e\u0000\u1260\u0000\u1289\u0000\u128a\u0000\u128e\u0000\u1290\u0000\u12b1\u0000\u12b2\u0000\u12b6\u0000\u12b8\u0000\u12bf\u0000\u12c0\u0000\u12c1\u0000\u12c2\u0000\u12c6\u0000\u12c8\u0000\u12d7\u0000\u12d8\u0000\u1311\u0000\u1312\u0000\u1316\u0000\u1318\u0000\u135b\u0000\u135d\u0000\u137d\u0000\u1380\u0000\u139a\u0000\u13a0\u0000\u13f6\u0000\u13f8\u0000\u13fe\u0000\u1400\u0000\u1680\u0000\u1681\u0000\u169d\u0000\u16a0\u0000\u16f9\u0000\u1700\u0000\u1716\u0000\u171f\u0000\u1737\u0000\u1740\u0000\u1754\u0000\u1760\u0000\u176d\u0000\u176e\u0000\u1771\u0000\u1772\u0000\u1774\u0000\u1780\u0000\u17de\u0000\u17e0\u0000\u17ea\u0000\u17f0\u0000\u17fa\u0000\u1800\u0000\u180e\u0000\u180f\u0000\u181a\u0000\u1820\u0000\u1879\u0000\u1880\u0000\u18ab\u0000\u18b0\u0000\u18f6\u0000\u1900\u0000\u191f\u0000\u1920\u0000\u192c\u0000\u1930\u0000\u193c\u0000\u1940\u0000\u1941\u0000\u1944\u0000\u196e\u0000\u1970\u0000\u1975\u0000\u1980\u0000\u19ac\u0000\u19b0\u0000\u19ca\u0000\u19d0\u0000\u19db\u0000\u19de\u0000\u1a1c\u0000\u1a1e\u0000\u1a5f\u0000\u1a60\u0000\u1a7d\u0000\u1a7f\u0000\u1a8a\u0000\u1a90\u0000\u1a9a\u0000\u1aa0\u0000\u1aae\u0000\u1ab0\u0000\u1acf\u0000\u1b00\u0000\u1b4d\u0000\u1b50\u0000\u1b7f\u0000\u1b80\u0000\u1bf4\u0000\u1bfc\u0000\u1c38\u0000\u1c3b\u0000\u1c4a\u0000\u1c4d\u0000\u1c89\u0000\u1c90\u0000\u1cbb\u0000\u1cbd\u0000\u1cc8\u0000\u1cd0\u0000\u1cfb\u0000\u1d00\u0000\u1f16\u0000\u1f18\u0000\u1f1e\u0000\u1f20\u0000\u1f46\u0000\u1f48\u0000\u1f4e\u0000\u1f50\u0000\u1f58\u0000\u1f59\u0000\u1f5a\u0000\u1f5b\u0000\u1f5c\u0000\u1f5d\u0000\u1f5e\u0000\u1f5f\u0000\u1f7e\u0000\u1f80\u0000\u1fb5\u0000\u1fb6\u0000\u1fc5\u0000\u1fc6\u0000\u1fd4\u0000\u1fd6\u0000\u1fdc\u0000\u1fdd\u0000\u1ff0\u0000\u1ff2\u0000\u1ff5\u0000\u1ff6\u0000\u1fff\u0000\u2010\u0000\u2028\u0000\u2030\u0000\u205f\u0000\u2070\u0000\u2072\u0000\u2074\u0000\u208f\u0000\u2090\u0000\u209d\u0000\u20a0\u0000\u20c1\u0000\u20d0\u0000\u20f1\u0000\u2100\u0000\u218c\u0000\u2190\u0000\u2427\u0000\u2440\u0000\u244b\u0000\u2460\u0000\u2b74\u0000\u2b76\u0000\u2b96\u0000\u2b97\u0000\u2cf4\u0000\u2cf9\u0000\u2d26\u0000\u2d27\u0000\u2d28\u0000\u2d2d\u0000\u2d2e\u0000\u2d30\u0000\u2d68\u0000\u2d6f\u0000\u2d71\u0000\u2d7f\u0000\u2d97\u0000\u2da0\u0000\u2da7\u0000\u2da8\u0000\u2daf\u0000\u2db0\u0000\u2db7\u0000\u2db8\u0000\u2dbf\u0000\u2dc0\u0000\u2dc7\u0000\u2dc8\u0000\u2dcf\u0000\u2dd0\u0000\u2dd7\u0000\u2dd8\u0000\u2ddf\u0000\u2de0\u0000\u2e5e\u0000\u2e80\u0000\u2e9a\u0000\u2e9b\u0000\u2ef4\u0000\u2f00\u0000\u2fd6\u0000\u2ff0\u0000\u3000\u0000\u3001\u0000\u3040\u0000\u3041\u0000\u3097\u0000\u3099\u0000\u3100\u0000\u3105\u0000\u3130\u0000\u3131\u0000\u318f\u0000\u3190\u0000\u31e4\u0000\u31ef\u0000\u321f\u0000\u3220\u0000\ua48d\u0000\ua490\u0000\ua4c7\u0000\ua4d0\u0000\ua62c\u0000\ua640\u0000\ua6f8\u0000\ua700\u0000\ua7cb\u0000\ua7d0\u0000\ua7d2\u0000\ua7d3\u0000\ua7d4\u0000\ua7d5\u0000\ua7da\u0000\ua7f2\u0000\ua82d\u0000\ua830\u0000\ua83a\u0000\ua840\u0000\ua878\u0000\ua880\u0000\ua8c6\u0000\ua8ce\u0000\ua8da\u0000\ua8e0\u0000\ua954\u0000\ua95f\u0000\ua97d\u0000\ua980\u0000\ua9ce\u0000\ua9cf\u0000\ua9da\u0000\ua9de\u0000\ua9ff\u0000\uaa00\u0000\uaa37\u0000\uaa40\u0000\uaa4e\u0000\uaa50\u0000\uaa5a\u0000\uaa5c\u0000\uaac3\u0000\uaadb\u0000\uaaf7\u0000\uab01\u0000\uab07\u0000\uab09\u0000\uab0f\u0000\uab11\u0000\uab17\u0000\uab20\u0000\uab27\u0000\uab28\u0000\uab2f\u0000\uab30\u0000\uab6c\u0000\uab70\u0000\uabee\u0000\uabf0\u0000\uabfa\u0000\uac00\u0000\ud7a4\u0000\ud7b0\u0000\ud7c7\u0000\ud7cb\u0000\ud7fc\u0000\uf900\u0000\ufa6e\u0000\ufa70\u0000\ufada\u0000\ufb00\u0000\ufb07\u0000\ufb13\u0000\ufb18\u0000\ufb1d\u0000\ufb37\u0000\ufb38\u0000\ufb3d\u0000\ufb3e\u0000\ufb3f\u0000\ufb40\u0000\ufb42\u0000\ufb43\u0000\ufb45\u0000\ufb46\u0000\ufbc3\u0000\ufbd3\u0000\ufd90\u0000\ufd92\u0000\ufdc8\u0000\ufdcf\u0000\ufdd0\u0000\ufdf0\u0000\ufe1a\u0000\ufe20\u0000\ufe53\u0000\ufe54\u0000\ufe67\u0000\ufe68\u0000\ufe6c\u0000\ufe70\u0000\ufe75\u0000\ufe76\u0000\ufefd\u0000\uff01\u0000\uffbf\u0000\uffc2\u0000\uffc8\u0000\uffca\u0000\uffd0\u0000\uffd2\u0000\uffd8\u0000\uffda\u0000\uffdd\u0000\uffe0\u0000\uffe7\u0000\uffe8\u0000\uffef\u0000\ufffc\u0000\ufffe\u0001\u0000\u0001\u000c\u0001\r\u0001'\u0001(\u0001;\u0001<\u0001>\u0001?\u0001N\u0001P\u0001^\u0001\u0080\u0001\u00fb\u0001\u0100\u0001\u0103\u0001\u0107\u0001\u0134\u0001\u0137\u0001\u018f\u0001\u0190\u0001\u019d\u0001\u01a0\u0001\u01a1\u0001\u01d0\u0001\u01fe\u0001\u0280\u0001\u029d\u0001\u02a0\u0001\u02d1\u0001\u02e0\u0001\u02fc\u0001\u0300\u0001\u0324\u0001\u032d\u0001\u034b\u0001\u0350\u0001\u037b\u0001\u0380\u0001\u039e\u0001\u039f\u0001\u03c4\u0001\u03c8\u0001\u03d6\u0001\u0400\u0001\u049e\u0001\u04a0\u0001\u04aa\u0001\u04b0\u0001\u04d4\u0001\u04d8\u0001\u04fc\u0001\u0500\u0001\u0528\u0001\u0530\u0001\u0564\u0001\u056f\u0001\u057b\u0001\u057c\u0001\u058b\u0001\u058c\u0001\u0593\u0001\u0594\u0001\u0596\u0001\u0597\u0001\u05a2\u0001\u05a3\u0001\u05b2\u0001\u05b3\u0001\u05ba\u0001\u05bb\u0001\u05bd\u0001\u0600\u0001\u0737\u0001\u0740\u0001\u0756\u0001\u0760\u0001\u0768\u0001\u0780\u0001\u0786\u0001\u0787\u0001\u07b1\u0001\u07b2\u0001\u07bb\u0001\u0800\u0001\u0806\u0001\u0808\u0001\u0809\u0001\u080a\u0001\u0836\u0001\u0837\u0001\u0839\u0001\u083c\u0001\u083d\u0001\u083f\u0001\u0856\u0001\u0857\u0001\u089f\u0001\u08a7\u0001\u08b0\u0001\u08e0\u0001\u08f3\u0001\u08f4\u0001\u08f6\u0001\u08fb\u0001\u091c\u0001\u091f\u0001\u093a\u0001\u093f\u0001\u0940\u0001\u0980\u0001\u09b8\u0001\u09bc\u0001\u09d0\u0001\u09d2\u0001\u0a04\u0001\u0a05\u0001\u0a07\u0001\u0a0c\u0001\u0a14\u0001\u0a15\u0001\u0a18\u0001\u0a19\u0001\u0a36\u0001\u0a38\u0001\u0a3b\u0001\u0a3f\u0001\u0a49\u0001\u0a50\u0001\u0a59\u0001\u0a60\u0001\u0aa0\u0001\u0ac0\u0001\u0ae7\u0001\u0aeb\u0001\u0af7\u0001\u0b00\u0001\u0b36\u0001\u0b39\u0001\u0b56\u0001\u0b58\u0001\u0b73\u0001\u0b78\u0001\u0b92\u0001\u0b99\u0001\u0b9d\u0001\u0ba9\u0001\u0bb0\u0001\u0c00\u0001\u0c49\u0001\u0c80\u0001\u0cb3\u0001\u0cc0\u0001\u0cf3\u0001\u0cfa\u0001\u0d28\u0001\u0d30\u0001\u0d3a\u0001\u0e60\u0001\u0e7f\u0001\u0e80\u0001\u0eaa\u0001\u0eab\u0001\u0eae\u0001\u0eb0\u0001\u0eb2\u0001\u0efd\u0001\u0f28\u0001\u0f30\u0001\u0f5a\u0001\u0f70\u0001\u0f8a\u0001\u0fb0\u0001\u0fcc\u0001\u0fe0\u0001\u0ff7\u0001\u1000\u0001\u104e\u0001\u1052\u0001\u1076\u0001\u107f\u0001\u10bd\u0001\u10be\u0001\u10c3\u0001\u10d0\u0001\u10e9\u0001\u10f0\u0001\u10fa\u0001\u1100\u0001\u1135\u0001\u1136\u0001\u1148\u0001\u1150\u0001\u1177\u0001\u1180\u0001\u11e0\u0001\u11e1\u0001\u11f5\u0001\u1200\u0001\u1212\u0001\u1213\u0001\u1242\u0001\u1280\u0001\u1287\u0001\u1288\u0001\u1289\u0001\u128a\u0001\u128e\u0001\u128f\u0001\u129e\u0001\u129f\u0001\u12aa\u0001\u12b0\u0001\u12eb\u0001\u12f0\u0001\u12fa\u0001\u1300\u0001\u1304\u0001\u1305\u0001\u130d\u0001\u130f\u0001\u1311\u0001\u1313\u0001\u1329\u0001\u132a\u0001\u1331\u0001\u1332\u0001\u1334\u0001\u1335\u0001\u133a\u0001\u133b\u0001\u1345\u0001\u1347\u0001\u1349\u0001\u134b\u0001\u134e\u0001\u1350\u0001\u1351\u0001\u1357\u0001\u1358\u0001\u135d\u0001\u1364\u0001\u1366\u0001\u136d\u0001\u1370\u0001\u1375\u0001\u1400\u0001\u145c\u0001\u145d\u0001\u1462\u0001\u1480\u0001\u14c8\u0001\u14d0\u0001\u14da\u0001\u1580\u0001\u15b6\u0001\u15b8\u0001\u15de\u0001\u1600\u0001\u1645\u0001\u1650\u0001\u165a\u0001\u1660\u0001\u166d\u0001\u1680\u0001\u16ba\u0001\u16c0\u0001\u16ca\u0001\u1700\u0001\u171b\u0001\u171d\u0001\u172c\u0001\u1730\u0001\u1747\u0001\u1800\u0001\u183c\u0001\u18a0\u0001\u18f3\u0001\u18ff\u0001\u1907\u0001\u1909\u0001\u190a\u0001\u190c\u0001\u1914\u0001\u1915\u0001\u1917\u0001\u1918\u0001\u1936\u0001\u1937\u0001\u1939\u0001\u193b\u0001\u1947\u0001\u1950\u0001\u195a\u0001\u19a0\u0001\u19a8\u0001\u19aa\u0001\u19d8\u0001\u19da\u0001\u19e5\u0001\u1a00\u0001\u1a48\u0001\u1a50\u0001\u1aa3\u0001\u1ab0\u0001\u1af9\u0001\u1b00\u0001\u1b0a\u0001\u1c00\u0001\u1c09\u0001\u1c0a\u0001\u1c37\u0001\u1c38\u0001\u1c46\u0001\u1c50\u0001\u1c6d\u0001\u1c70\u0001\u1c90\u0001\u1c92\u0001\u1ca8\u0001\u1ca9\u0001\u1cb7\u0001\u1d00\u0001\u1d07\u0001\u1d08\u0001\u1d0a\u0001\u1d0b\u0001\u1d37\u0001\u1d3a\u0001\u1d3b\u0001\u1d3c\u0001\u1d3e\u0001\u1d3f\u0001\u1d48\u0001\u1d50\u0001\u1d5a\u0001\u1d60\u0001\u1d66\u0001\u1d67\u0001\u1d69\u0001\u1d6a\u0001\u1d8f\u0001\u1d90\u0001\u1d92\u0001\u1d93\u0001\u1d99\u0001\u1da0\u0001\u1daa\u0001\u1ee0\u0001\u1ef9\u0001\u1f00\u0001\u1f11\u0001\u1f12\u0001\u1f3b\u0001\u1f3e\u0001\u1f5a\u0001\u1fb0\u0001\u1fb1\u0001\u1fc0\u0001\u1ff2\u0001\u1fff\u0001\u239a\u0001\u2400\u0001\u246f\u0001\u2470\u0001\u2475\u0001\u2480\u0001\u2544\u0001\u2f90\u0001\u2ff3\u0001\u3000\u0001\u3430\u0001\u3440\u0001\u3456\u0001\u4400\u0001\u4647\u0001\u6800\u0001\u6a39\u0001\u6a40\u0001\u6a5f\u0001\u6a60\u0001\u6a6a\u0001\u6a6e\u0001\u6abf\u0001\u6ac0\u0001\u6aca\u0001\u6ad0\u0001\u6aee\u0001\u6af0\u0001\u6af6\u0001\u6b00\u0001\u6b46\u0001\u6b50\u0001\u6b5a\u0001\u6b5b\u0001\u6b62\u0001\u6b63\u0001\u6b78\u0001\u6b7d\u0001\u6b90\u0001\u6e40\u0001\u6e9b\u0001\u6f00\u0001\u6f4b\u0001\u6f4f\u0001\u6f88\u0001\u6f8f\u0001\u6fa0\u0001\u6fe0\u0001\u6fe5\u0001\u6ff0\u0001\u6ff2\u0001\u7000\u0001\u87f8\u0001\u8800\u0001\u8cd6\u0001\u8d00\u0001\u8d09\u0001\uaff0\u0001\uaff4\u0001\uaff5\u0001\uaffc\u0001\uaffd\u0001\uafff\u0001\ub000\u0001\ub123\u0001\ub132\u0001\ub133\u0001\ub150\u0001\ub153\u0001\ub155\u0001\ub156\u0001\ub164\u0001\ub168\u0001\ub170\u0001\ub2fc\u0001\ubc00\u0001\ubc6b\u0001\ubc70\u0001\ubc7d\u0001\ubc80\u0001\ubc89\u0001\ubc90\u0001\ubc9a\u0001\ubc9c\u0001\ubca0\u0001\ucf00\u0001\ucf2e\u0001\ucf30\u0001\ucf47\u0001\ucf50\u0001\ucfc4\u0001\ud000\u0001\ud0f6\u0001\ud100\u0001\ud127\u0001\ud129\u0001\ud173\u0001\ud17b\u0001\ud1eb\u0001\ud200\u0001\ud246\u0001\ud2c0\u0001\ud2d4\u0001\ud2e0\u0001\ud2f4\u0001\ud300\u0001\ud357\u0001\ud360\u0001\ud379\u0001\ud400\u0001\ud455\u0001\ud456\u0001\ud49d\u0001\ud49e\u0001\ud4a0\u0001\ud4a2\u0001\ud4a3\u0001\ud4a5\u0001\ud4a7\u0001\ud4a9\u0001\ud4ad\u0001\ud4ae\u0001\ud4ba\u0001\ud4bb\u0001\ud4bc\u0001\ud4bd\u0001\ud4c4\u0001\ud4c5\u0001\ud506\u0001\ud507\u0001\ud50b\u0001\ud50d\u0001\ud515\u0001\ud516\u0001\ud51d\u0001\ud51e\u0001\ud53a\u0001\ud53b\u0001\ud53f\u0001\ud540\u0001\ud545\u0001\ud546\u0001\ud547\u0001\ud54a\u0001\ud551\u0001\ud552\u0001\ud6a6\u0001\ud6a8\u0001\ud7cc\u0001\ud7ce\u0001\uda8c\u0001\uda9b\u0001\udaa0\u0001\udaa1\u0001\udab0\u0001\udf00\u0001\udf1f\u0001\udf25\u0001\udf2b\u0001\ue000\u0001\ue007\u0001\ue008\u0001\ue019\u0001\ue01b\u0001\ue022\u0001\ue023\u0001\ue025\u0001\ue026\u0001\ue02b\u0001\ue030\u0001\ue06e\u0001\ue08f\u0001\ue090\u0001\ue100\u0001\ue12d\u0001\ue130\u0001\ue13e\u0001\ue140\u0001\ue14a\u0001\ue14e\u0001\ue150\u0001\ue290\u0001\ue2af\u0001\ue2c0\u0001\ue2fa\u0001\ue2ff\u0001\ue300\u0001\ue4d0\u0001\ue4fa\u0001\ue7e0\u0001\ue7e7\u0001\ue7e8\u0001\ue7ec\u0001\ue7ed\u0001\ue7ef\u0001\ue7f0\u0001\ue7ff\u0001\ue800\u0001\ue8c5\u0001\ue8c7\u0001\ue8d7\u0001\ue900\u0001\ue94c\u0001\ue950\u0001\ue95a\u0001\ue95e\u0001\ue960\u0001\uec71\u0001\uecb5\u0001\ued01\u0001\ued3e\u0001\uee00\u0001\uee04\u0001\uee05\u0001\uee20\u0001\uee21\u0001\uee23\u0001\uee24\u0001\uee25\u0001\uee27\u0001\uee28\u0001\uee29\u0001\uee33\u0001\uee34\u0001\uee38\u0001\uee39\u0001\uee3a\u0001\uee3b\u0001\uee3c\u0001\uee42\u0001\uee43\u0001\uee47\u0001\uee48\u0001\uee49\u0001\uee4a\u0001\uee4b\u0001\uee4c\u0001\uee4d\u0001\uee50\u0001\uee51\u0001\uee53\u0001\uee54\u0001\uee55\u0001\uee57\u0001\uee58\u0001\uee59\u0001\uee5a\u0001\uee5b\u0001\uee5c\u0001\uee5d\u0001\uee5e\u0001\uee5f\u0001\uee60\u0001\uee61\u0001\uee63\u0001\uee64\u0001\uee65\u0001\uee67\u0001\uee6b\u0001\uee6c\u0001\uee73\u0001\uee74\u0001\uee78\u0001\uee79\u0001\uee7d\u0001\uee7e\u0001\uee7f\u0001\uee80\u0001\uee8a\u0001\uee8b\u0001\uee9c\u0001\ueea1\u0001\ueea4\u0001\ueea5\u0001\ueeaa\u0001\ueeab\u0001\ueebc\u0001\ueef0\u0001\ueef2\u0001\uf000\u0001\uf02c\u0001\uf030\u0001\uf094\u0001\uf0a0\u0001\uf0af\u0001\uf0b1\u0001\uf0c0\u0001\uf0c1\u0001\uf0d0\u0001\uf0d1\u0001\uf0f6\u0001\uf100\u0001\uf1ae\u0001\uf1e6\u0001\uf203\u0001\uf210\u0001\uf23c\u0001\uf240\u0001\uf249\u0001\uf250\u0001\uf252\u0001\uf260\u0001\uf266\u0001\uf300\u0001\uf6d8\u0001\uf6dc\u0001\uf6ed\u0001\uf6f0\u0001\uf6fd\u0001\uf700\u0001\uf777\u0001\uf77b\u0001\uf7da\u0001\uf7e0\u0001\uf7ec\u0001\uf7f0\u0001\uf7f1\u0001\uf800\u0001\uf80c\u0001\uf810\u0001\uf848\u0001\uf850\u0001\uf85a\u0001\uf860\u0001\uf888\u0001\uf890\u0001\uf8ae\u0001\uf8b0\u0001\uf8b2\u0001\uf900\u0001\ufa54\u0001\ufa60\u0001\ufa6e\u0001\ufa70\u0001\ufa7d\u0001\ufa80\u0001\ufa89\u0001\ufa90\u0001\ufabe\u0001\ufabf\u0001\ufac6\u0001\uface\u0001\ufadc\u0001\ufae0\u0001\ufae9\u0001\ufaf0\u0001\ufaf9\u0001\ufb00\u0001\ufb93\u0001\ufb94\u0001\ufbcb\u0001\ufbf0\u0001\ufbfa\u0002\u0000\u0002\ua6e0\u0002\ua700\u0002\ub73a\u0002\ub740\u0002\ub81e\u0002\ub820\u0002\ucea2\u0002\uceb0\u0002\uebe1\u0002\uebf0\u0002\uee5e\u0002\uf800\u0002\ufa1e\u0003\u0000\u0003\u134b\u0003\u1350\u0003\u23b0\u000e\u0100\u000e\u01f0", + }; + static final String[] LOWER = { "A\u0001aB\u0001bC\u0001cD\u0001dE\u0001eF\u0001fG\u0001gH\u0001hI\u0001iJ\u0001jK\u0001kL\u0001lM\u0001mN\u0001nO\u0001oP\u0001pQ\u0001qR\u0001rS\u0001sT\u0001tU\u0001uV\u0001vW\u0001wX\u0001xY\u0001yZ\u0001z\u00c0\u0001\u00e0\u00c1\u0001\u00e1\u00c2\u0001\u00e2\u00c3\u0001\u00e3\u00c4\u0001\u00e4\u00c5\u0001\u00e5\u00c6\u0001\u00e6\u00c7\u0001\u00e7\u00c8\u0001\u00e8\u00c9\u0001\u00e9\u00ca\u0001\u00ea\u00cb\u0001\u00eb\u00cc\u0001\u00ec\u00cd\u0001\u00ed\u00ce\u0001\u00ee\u00cf\u0001\u00ef\u00d0\u0001\u00f0\u00d1\u0001\u00f1\u00d2\u0001\u00f2\u00d3\u0001\u00f3\u00d4\u0001\u00f4\u00d5\u0001\u00f5\u00d6\u0001\u00f6\u00d8\u0001\u00f8\u00d9\u0001\u00f9\u00da\u0001\u00fa\u00db\u0001\u00fb\u00dc\u0001\u00fc\u00dd\u0001\u00fd\u00de\u0001\u00fe\u0100\u0001\u0101\u0102\u0001\u0103\u0104\u0001\u0105\u0106\u0001\u0107\u0108\u0001\u0109\u010a\u0001\u010b\u010c\u0001\u010d\u010e\u0001\u010f\u0110\u0001\u0111\u0112\u0001\u0113\u0114\u0001\u0115\u0116\u0001\u0117\u0118\u0001\u0119\u011a\u0001\u011b\u011c\u0001\u011d\u011e\u0001\u011f\u0120\u0001\u0121\u0122\u0001\u0123\u0124\u0001\u0125\u0126\u0001\u0127\u0128\u0001\u0129\u012a\u0001\u012b\u012c\u0001\u012d\u012e\u0001\u012f\u0130\u0002i\u0307\u0132\u0001\u0133\u0134\u0001\u0135\u0136\u0001\u0137\u0139\u0001\u013a\u013b\u0001\u013c\u013d\u0001\u013e\u013f\u0001\u0140\u0141\u0001\u0142\u0143\u0001\u0144\u0145\u0001\u0146\u0147\u0001\u0148\u014a\u0001\u014b\u014c\u0001\u014d\u014e\u0001\u014f\u0150\u0001\u0151\u0152\u0001\u0153\u0154\u0001\u0155\u0156\u0001\u0157\u0158\u0001\u0159\u015a\u0001\u015b\u015c\u0001\u015d\u015e\u0001\u015f\u0160\u0001\u0161\u0162\u0001\u0163\u0164\u0001\u0165\u0166\u0001\u0167\u0168\u0001\u0169\u016a\u0001\u016b\u016c\u0001\u016d\u016e\u0001\u016f\u0170\u0001\u0171\u0172\u0001\u0173\u0174\u0001\u0175\u0176\u0001\u0177\u0178\u0001\u00ff\u0179\u0001\u017a\u017b\u0001\u017c\u017d\u0001\u017e\u0181\u0001\u0253\u0182\u0001\u0183\u0184\u0001\u0185\u0186\u0001\u0254\u0187\u0001\u0188\u0189\u0001\u0256\u018a\u0001\u0257\u018b\u0001\u018c\u018e\u0001\u01dd\u018f\u0001\u0259\u0190\u0001\u025b\u0191\u0001\u0192\u0193\u0001\u0260\u0194\u0001\u0263\u0196\u0001\u0269\u0197\u0001\u0268\u0198\u0001\u0199\u019c\u0001\u026f\u019d\u0001\u0272\u019f\u0001\u0275\u01a0\u0001\u01a1\u01a2\u0001\u01a3\u01a4\u0001\u01a5\u01a6\u0001\u0280\u01a7\u0001\u01a8\u01a9\u0001\u0283\u01ac\u0001\u01ad\u01ae\u0001\u0288\u01af\u0001\u01b0\u01b1\u0001\u028a\u01b2\u0001\u028b\u01b3\u0001\u01b4\u01b5\u0001\u01b6\u01b7\u0001\u0292\u01b8\u0001\u01b9\u01bc\u0001\u01bd\u01c4\u0001\u01c6\u01c5\u0001\u01c6\u01c7\u0001\u01c9\u01c8\u0001\u01c9\u01ca\u0001\u01cc\u01cb\u0001\u01cc\u01cd\u0001\u01ce\u01cf\u0001\u01d0\u01d1\u0001\u01d2\u01d3\u0001\u01d4\u01d5\u0001\u01d6\u01d7\u0001\u01d8\u01d9\u0001\u01da\u01db\u0001\u01dc\u01de\u0001\u01df\u01e0\u0001\u01e1\u01e2\u0001\u01e3\u01e4\u0001\u01e5\u01e6\u0001\u01e7\u01e8\u0001\u01e9\u01ea\u0001\u01eb\u01ec\u0001\u01ed\u01ee\u0001\u01ef\u01f1\u0001\u01f3\u01f2\u0001\u01f3\u01f4\u0001\u01f5\u01f6\u0001\u0195\u01f7\u0001\u01bf\u01f8\u0001\u01f9\u01fa\u0001\u01fb\u01fc\u0001\u01fd\u01fe\u0001\u01ff\u0200\u0001\u0201\u0202\u0001\u0203\u0204\u0001\u0205\u0206\u0001\u0207\u0208\u0001\u0209\u020a\u0001\u020b\u020c\u0001\u020d\u020e\u0001\u020f\u0210\u0001\u0211\u0212\u0001\u0213\u0214\u0001\u0215\u0216\u0001\u0217\u0218\u0001\u0219\u021a\u0001\u021b\u021c\u0001\u021d\u021e\u0001\u021f\u0220\u0001\u019e\u0222\u0001\u0223\u0224\u0001\u0225\u0226\u0001\u0227\u0228\u0001\u0229\u022a\u0001\u022b\u022c\u0001\u022d\u022e\u0001\u022f\u0230\u0001\u0231\u0232\u0001\u0233\u023a\u0001\u2c65\u023b\u0001\u023c\u023d\u0001\u019a\u023e\u0001\u2c66\u0241\u0001\u0242\u0243\u0001\u0180\u0244\u0001\u0289\u0245\u0001\u028c\u0246\u0001\u0247\u0248\u0001\u0249\u024a\u0001\u024b\u024c\u0001\u024d\u024e\u0001\u024f\u0370\u0001\u0371\u0372\u0001\u0373\u0376\u0001\u0377\u037f\u0001\u03f3\u0386\u0001\u03ac\u0388\u0001\u03ad\u0389\u0001\u03ae\u038a\u0001\u03af\u038c\u0001\u03cc\u038e\u0001\u03cd\u038f\u0001\u03ce\u0391\u0001\u03b1\u0392\u0001\u03b2\u0393\u0001\u03b3\u0394\u0001\u03b4\u0395\u0001\u03b5\u0396\u0001\u03b6\u0397\u0001\u03b7\u0398\u0001\u03b8\u0399\u0001\u03b9\u039a\u0001\u03ba\u039b\u0001\u03bb\u039c\u0001\u03bc\u039d\u0001\u03bd\u039e\u0001\u03be\u039f\u0001\u03bf\u03a0\u0001\u03c0\u03a1\u0001\u03c1\u03a3\u0001\u03c3\u03a4\u0001\u03c4\u03a5\u0001\u03c5\u03a6\u0001\u03c6\u03a7\u0001\u03c7\u03a8\u0001\u03c8\u03a9\u0001\u03c9\u03aa\u0001\u03ca\u03ab\u0001\u03cb\u03cf\u0001\u03d7\u03d8\u0001\u03d9\u03da\u0001\u03db\u03dc\u0001\u03dd\u03de\u0001\u03df\u03e0\u0001\u03e1\u03e2\u0001\u03e3\u03e4\u0001\u03e5\u03e6\u0001\u03e7\u03e8\u0001\u03e9\u03ea\u0001\u03eb\u03ec\u0001\u03ed\u03ee\u0001\u03ef\u03f4\u0001\u03b8\u03f7\u0001\u03f8\u03f9\u0001\u03f2\u03fa\u0001\u03fb\u03fd\u0001\u037b\u03fe\u0001\u037c\u03ff\u0001\u037d\u0400\u0001\u0450\u0401\u0001\u0451\u0402\u0001\u0452\u0403\u0001\u0453\u0404\u0001\u0454\u0405\u0001\u0455\u0406\u0001\u0456\u0407\u0001\u0457\u0408\u0001\u0458\u0409\u0001\u0459\u040a\u0001\u045a\u040b\u0001\u045b\u040c\u0001\u045c\u040d\u0001\u045d\u040e\u0001\u045e\u040f\u0001\u045f\u0410\u0001\u0430\u0411\u0001\u0431\u0412\u0001\u0432\u0413\u0001\u0433\u0414\u0001\u0434\u0415\u0001\u0435\u0416\u0001\u0436\u0417\u0001\u0437\u0418\u0001\u0438\u0419\u0001\u0439\u041a\u0001\u043a\u041b\u0001\u043b\u041c\u0001\u043c\u041d\u0001\u043d\u041e\u0001\u043e\u041f\u0001\u043f\u0420\u0001\u0440\u0421\u0001\u0441\u0422\u0001\u0442\u0423\u0001\u0443\u0424\u0001\u0444\u0425\u0001\u0445\u0426\u0001\u0446\u0427\u0001\u0447\u0428\u0001\u0448\u0429\u0001\u0449\u042a\u0001\u044a\u042b\u0001\u044b\u042c\u0001\u044c\u042d\u0001\u044d\u042e\u0001\u044e\u042f\u0001\u044f\u0460\u0001\u0461\u0462\u0001\u0463\u0464\u0001\u0465\u0466\u0001\u0467\u0468\u0001\u0469\u046a\u0001\u046b\u046c\u0001\u046d\u046e\u0001\u046f\u0470\u0001\u0471\u0472\u0001\u0473\u0474\u0001\u0475\u0476\u0001\u0477\u0478\u0001\u0479\u047a\u0001\u047b\u047c\u0001\u047d\u047e\u0001\u047f\u0480\u0001\u0481\u048a\u0001\u048b\u048c\u0001\u048d\u048e\u0001\u048f\u0490\u0001\u0491\u0492\u0001\u0493\u0494\u0001\u0495\u0496\u0001\u0497\u0498\u0001\u0499\u049a\u0001\u049b\u049c\u0001\u049d\u049e\u0001\u049f\u04a0\u0001\u04a1\u04a2\u0001\u04a3\u04a4\u0001\u04a5\u04a6\u0001\u04a7\u04a8\u0001\u04a9\u04aa\u0001\u04ab\u04ac\u0001\u04ad\u04ae\u0001\u04af\u04b0\u0001\u04b1\u04b2\u0001\u04b3\u04b4\u0001\u04b5\u04b6\u0001\u04b7\u04b8\u0001\u04b9\u04ba\u0001\u04bb\u04bc\u0001\u04bd\u04be\u0001\u04bf\u04c0\u0001\u04cf\u04c1\u0001\u04c2\u04c3\u0001\u04c4\u04c5\u0001\u04c6\u04c7\u0001\u04c8\u04c9\u0001\u04ca\u04cb\u0001\u04cc\u04cd\u0001\u04ce\u04d0\u0001\u04d1\u04d2\u0001\u04d3\u04d4\u0001\u04d5\u04d6\u0001\u04d7\u04d8\u0001\u04d9\u04da\u0001\u04db\u04dc\u0001\u04dd\u04de\u0001\u04df\u04e0\u0001\u04e1\u04e2\u0001\u04e3\u04e4\u0001\u04e5\u04e6\u0001\u04e7\u04e8\u0001\u04e9\u04ea\u0001\u04eb\u04ec\u0001\u04ed\u04ee\u0001\u04ef\u04f0\u0001\u04f1\u04f2\u0001\u04f3\u04f4\u0001\u04f5\u04f6\u0001\u04f7\u04f8\u0001\u04f9\u04fa\u0001\u04fb\u04fc\u0001\u04fd\u04fe\u0001\u04ff\u0500\u0001\u0501\u0502\u0001\u0503\u0504\u0001\u0505\u0506\u0001\u0507\u0508\u0001\u0509\u050a\u0001\u050b\u050c\u0001\u050d\u050e\u0001\u050f\u0510\u0001\u0511\u0512\u0001\u0513\u0514\u0001\u0515\u0516\u0001\u0517\u0518\u0001\u0519\u051a\u0001\u051b\u051c\u0001\u051d\u051e\u0001\u051f\u0520\u0001\u0521\u0522\u0001\u0523\u0524\u0001\u0525\u0526\u0001\u0527\u0528\u0001\u0529\u052a\u0001\u052b\u052c\u0001\u052d\u052e\u0001\u052f\u0531\u0001\u0561\u0532\u0001\u0562\u0533\u0001\u0563\u0534\u0001\u0564\u0535\u0001\u0565\u0536\u0001\u0566\u0537\u0001\u0567\u0538\u0001\u0568\u0539\u0001\u0569\u053a\u0001\u056a\u053b\u0001\u056b\u053c\u0001\u056c\u053d\u0001\u056d\u053e\u0001\u056e\u053f\u0001\u056f\u0540\u0001\u0570\u0541\u0001\u0571\u0542\u0001\u0572\u0543\u0001\u0573\u0544\u0001\u0574\u0545\u0001\u0575\u0546\u0001\u0576\u0547\u0001\u0577\u0548\u0001\u0578\u0549\u0001\u0579\u054a\u0001\u057a\u054b\u0001\u057b\u054c\u0001\u057c\u054d\u0001\u057d\u054e\u0001\u057e\u054f\u0001\u057f\u0550\u0001\u0580\u0551\u0001\u0581\u0552\u0001\u0582\u0553\u0001\u0583\u0554\u0001\u0584\u0555\u0001\u0585\u0556\u0001\u0586\u10a0\u0001\u2d00\u10a1\u0001\u2d01\u10a2\u0001\u2d02\u10a3\u0001\u2d03\u10a4\u0001\u2d04\u10a5\u0001\u2d05\u10a6\u0001\u2d06\u10a7\u0001\u2d07\u10a8\u0001\u2d08\u10a9\u0001\u2d09\u10aa\u0001\u2d0a\u10ab\u0001\u2d0b\u10ac\u0001\u2d0c\u10ad\u0001\u2d0d\u10ae\u0001\u2d0e\u10af\u0001\u2d0f\u10b0\u0001\u2d10\u10b1\u0001\u2d11\u10b2\u0001\u2d12\u10b3\u0001\u2d13\u10b4\u0001\u2d14\u10b5\u0001\u2d15\u10b6\u0001\u2d16\u10b7\u0001\u2d17\u10b8\u0001\u2d18\u10b9\u0001\u2d19\u10ba\u0001\u2d1a\u10bb\u0001\u2d1b\u10bc\u0001\u2d1c\u10bd\u0001\u2d1d\u10be\u0001\u2d1e\u10bf\u0001\u2d1f\u10c0\u0001\u2d20\u10c1\u0001\u2d21\u10c2\u0001\u2d22\u10c3\u0001\u2d23\u10c4\u0001\u2d24\u10c5\u0001\u2d25\u10c7\u0001\u2d27\u10cd\u0001\u2d2d\u13a0\u0001\uab70\u13a1\u0001\uab71\u13a2\u0001\uab72\u13a3\u0001\uab73\u13a4\u0001\uab74\u13a5\u0001\uab75\u13a6\u0001\uab76\u13a7\u0001\uab77\u13a8\u0001\uab78\u13a9\u0001\uab79\u13aa\u0001\uab7a\u13ab\u0001\uab7b\u13ac\u0001\uab7c\u13ad\u0001\uab7d\u13ae\u0001\uab7e\u13af\u0001\uab7f\u13b0\u0001\uab80\u13b1\u0001\uab81\u13b2\u0001\uab82\u13b3\u0001\uab83\u13b4\u0001\uab84\u13b5\u0001\uab85\u13b6\u0001\uab86\u13b7\u0001\uab87\u13b8\u0001\uab88\u13b9\u0001\uab89\u13ba\u0001\uab8a\u13bb\u0001\uab8b\u13bc\u0001\uab8c\u13bd\u0001\uab8d\u13be\u0001\uab8e\u13bf\u0001\uab8f\u13c0\u0001\uab90\u13c1\u0001\uab91\u13c2\u0001\uab92\u13c3\u0001\uab93\u13c4\u0001\uab94\u13c5\u0001\uab95\u13c6\u0001\uab96\u13c7\u0001\uab97\u13c8\u0001\uab98\u13c9\u0001\uab99\u13ca\u0001\uab9a\u13cb\u0001\uab9b\u13cc\u0001\uab9c\u13cd\u0001\uab9d\u13ce\u0001\uab9e\u13cf\u0001\uab9f\u13d0\u0001\uaba0\u13d1\u0001\uaba1\u13d2\u0001\uaba2\u13d3\u0001\uaba3\u13d4\u0001\uaba4\u13d5\u0001\uaba5\u13d6\u0001\uaba6\u13d7\u0001\uaba7\u13d8\u0001\uaba8\u13d9\u0001\uaba9\u13da\u0001\uabaa\u13db\u0001\uabab\u13dc\u0001\uabac\u13dd\u0001\uabad\u13de\u0001\uabae\u13df\u0001\uabaf\u13e0\u0001\uabb0\u13e1\u0001\uabb1\u13e2\u0001\uabb2\u13e3\u0001\uabb3\u13e4\u0001\uabb4\u13e5\u0001\uabb5\u13e6\u0001\uabb6\u13e7\u0001\uabb7\u13e8\u0001\uabb8\u13e9\u0001\uabb9\u13ea\u0001\uabba\u13eb\u0001\uabbb\u13ec\u0001\uabbc\u13ed\u0001\uabbd\u13ee\u0001\uabbe\u13ef\u0001\uabbf\u13f0\u0001\u13f8\u13f1\u0001\u13f9\u13f2\u0001\u13fa\u13f3\u0001\u13fb\u13f4\u0001\u13fc\u13f5\u0001\u13fd\u1c90\u0001\u10d0\u1c91\u0001\u10d1\u1c92\u0001\u10d2\u1c93\u0001\u10d3\u1c94\u0001\u10d4\u1c95\u0001\u10d5\u1c96\u0001\u10d6\u1c97\u0001\u10d7\u1c98\u0001\u10d8\u1c99\u0001\u10d9\u1c9a\u0001\u10da\u1c9b\u0001\u10db\u1c9c\u0001\u10dc\u1c9d\u0001\u10dd\u1c9e\u0001\u10de\u1c9f\u0001\u10df\u1ca0\u0001\u10e0\u1ca1\u0001\u10e1\u1ca2\u0001\u10e2\u1ca3\u0001\u10e3\u1ca4\u0001\u10e4\u1ca5\u0001\u10e5\u1ca6\u0001\u10e6\u1ca7\u0001\u10e7\u1ca8\u0001\u10e8\u1ca9\u0001\u10e9\u1caa\u0001\u10ea\u1cab\u0001\u10eb\u1cac\u0001\u10ec\u1cad\u0001\u10ed\u1cae\u0001\u10ee\u1caf\u0001\u10ef\u1cb0\u0001\u10f0\u1cb1\u0001\u10f1\u1cb2\u0001\u10f2\u1cb3\u0001\u10f3\u1cb4\u0001\u10f4\u1cb5\u0001\u10f5\u1cb6\u0001\u10f6\u1cb7\u0001\u10f7\u1cb8\u0001\u10f8\u1cb9\u0001\u10f9\u1cba\u0001\u10fa\u1cbd\u0001\u10fd\u1cbe\u0001\u10fe\u1cbf\u0001\u10ff\u1e00\u0001\u1e01\u1e02\u0001\u1e03\u1e04\u0001\u1e05\u1e06\u0001\u1e07\u1e08\u0001\u1e09\u1e0a\u0001\u1e0b\u1e0c\u0001\u1e0d\u1e0e\u0001\u1e0f\u1e10\u0001\u1e11\u1e12\u0001\u1e13\u1e14\u0001\u1e15\u1e16\u0001\u1e17\u1e18\u0001\u1e19\u1e1a\u0001\u1e1b\u1e1c\u0001\u1e1d\u1e1e\u0001\u1e1f\u1e20\u0001\u1e21\u1e22\u0001\u1e23\u1e24\u0001\u1e25\u1e26\u0001\u1e27\u1e28\u0001\u1e29\u1e2a\u0001\u1e2b\u1e2c\u0001\u1e2d\u1e2e\u0001\u1e2f\u1e30\u0001\u1e31\u1e32\u0001\u1e33\u1e34\u0001\u1e35\u1e36\u0001\u1e37\u1e38\u0001\u1e39\u1e3a\u0001\u1e3b\u1e3c\u0001\u1e3d\u1e3e\u0001\u1e3f\u1e40\u0001\u1e41\u1e42\u0001\u1e43\u1e44\u0001\u1e45\u1e46\u0001\u1e47\u1e48\u0001\u1e49\u1e4a\u0001\u1e4b\u1e4c\u0001\u1e4d\u1e4e\u0001\u1e4f\u1e50\u0001\u1e51\u1e52\u0001\u1e53\u1e54\u0001\u1e55\u1e56\u0001\u1e57\u1e58\u0001\u1e59\u1e5a\u0001\u1e5b\u1e5c\u0001\u1e5d\u1e5e\u0001\u1e5f\u1e60\u0001\u1e61\u1e62\u0001\u1e63\u1e64\u0001\u1e65\u1e66\u0001\u1e67\u1e68\u0001\u1e69\u1e6a\u0001\u1e6b\u1e6c\u0001\u1e6d\u1e6e\u0001\u1e6f\u1e70\u0001\u1e71\u1e72\u0001\u1e73\u1e74\u0001\u1e75\u1e76\u0001\u1e77\u1e78\u0001\u1e79\u1e7a\u0001\u1e7b\u1e7c\u0001\u1e7d\u1e7e\u0001\u1e7f\u1e80\u0001\u1e81\u1e82\u0001\u1e83\u1e84\u0001\u1e85\u1e86\u0001\u1e87\u1e88\u0001\u1e89\u1e8a\u0001\u1e8b\u1e8c\u0001\u1e8d\u1e8e\u0001\u1e8f\u1e90\u0001\u1e91\u1e92\u0001\u1e93\u1e94\u0001\u1e95\u1e9e\u0001\u00df\u1ea0\u0001\u1ea1\u1ea2\u0001\u1ea3\u1ea4\u0001\u1ea5\u1ea6\u0001\u1ea7\u1ea8\u0001\u1ea9\u1eaa\u0001\u1eab\u1eac\u0001\u1ead\u1eae\u0001\u1eaf\u1eb0\u0001\u1eb1\u1eb2\u0001\u1eb3\u1eb4\u0001\u1eb5\u1eb6\u0001\u1eb7\u1eb8\u0001\u1eb9\u1eba\u0001\u1ebb\u1ebc\u0001\u1ebd\u1ebe\u0001\u1ebf\u1ec0\u0001\u1ec1\u1ec2\u0001\u1ec3\u1ec4\u0001\u1ec5\u1ec6\u0001\u1ec7\u1ec8\u0001\u1ec9\u1eca\u0001\u1ecb\u1ecc\u0001\u1ecd\u1ece\u0001\u1ecf\u1ed0\u0001\u1ed1\u1ed2\u0001\u1ed3\u1ed4\u0001\u1ed5\u1ed6\u0001\u1ed7\u1ed8\u0001\u1ed9\u1eda\u0001\u1edb\u1edc\u0001\u1edd\u1ede\u0001\u1edf\u1ee0\u0001\u1ee1\u1ee2\u0001\u1ee3\u1ee4\u0001\u1ee5\u1ee6\u0001\u1ee7\u1ee8\u0001\u1ee9\u1eea\u0001\u1eeb\u1eec\u0001\u1eed\u1eee\u0001\u1eef\u1ef0\u0001\u1ef1\u1ef2\u0001\u1ef3\u1ef4\u0001\u1ef5\u1ef6\u0001\u1ef7\u1ef8\u0001\u1ef9\u1efa\u0001\u1efb\u1efc\u0001\u1efd\u1efe\u0001\u1eff\u1f08\u0001\u1f00\u1f09\u0001\u1f01\u1f0a\u0001\u1f02\u1f0b\u0001\u1f03\u1f0c\u0001\u1f04\u1f0d\u0001\u1f05\u1f0e\u0001\u1f06\u1f0f\u0001\u1f07\u1f18\u0001\u1f10\u1f19\u0001\u1f11\u1f1a\u0001\u1f12\u1f1b\u0001\u1f13\u1f1c\u0001\u1f14\u1f1d\u0001\u1f15\u1f28\u0001\u1f20\u1f29\u0001\u1f21\u1f2a\u0001\u1f22\u1f2b\u0001\u1f23\u1f2c\u0001\u1f24\u1f2d\u0001\u1f25\u1f2e\u0001\u1f26\u1f2f\u0001\u1f27\u1f38\u0001\u1f30\u1f39\u0001\u1f31\u1f3a\u0001\u1f32\u1f3b\u0001\u1f33\u1f3c\u0001\u1f34\u1f3d\u0001\u1f35\u1f3e\u0001\u1f36\u1f3f\u0001\u1f37\u1f48\u0001\u1f40\u1f49\u0001\u1f41\u1f4a\u0001\u1f42\u1f4b\u0001\u1f43\u1f4c\u0001\u1f44\u1f4d\u0001\u1f45\u1f59\u0001\u1f51\u1f5b\u0001\u1f53\u1f5d\u0001\u1f55\u1f5f\u0001\u1f57\u1f68\u0001\u1f60\u1f69\u0001\u1f61\u1f6a\u0001\u1f62\u1f6b\u0001\u1f63\u1f6c\u0001\u1f64\u1f6d\u0001\u1f65\u1f6e\u0001\u1f66\u1f6f\u0001\u1f67\u1f88\u0001\u1f80\u1f89\u0001\u1f81\u1f8a\u0001\u1f82\u1f8b\u0001\u1f83\u1f8c\u0001\u1f84\u1f8d\u0001\u1f85\u1f8e\u0001\u1f86\u1f8f\u0001\u1f87\u1f98\u0001\u1f90\u1f99\u0001\u1f91\u1f9a\u0001\u1f92\u1f9b\u0001\u1f93\u1f9c\u0001\u1f94\u1f9d\u0001\u1f95\u1f9e\u0001\u1f96\u1f9f\u0001\u1f97\u1fa8\u0001\u1fa0\u1fa9\u0001\u1fa1\u1faa\u0001\u1fa2\u1fab\u0001\u1fa3\u1fac\u0001\u1fa4\u1fad\u0001\u1fa5\u1fae\u0001\u1fa6\u1faf\u0001\u1fa7\u1fb8\u0001\u1fb0\u1fb9\u0001\u1fb1\u1fba\u0001\u1f70\u1fbb\u0001\u1f71\u1fbc\u0001\u1fb3\u1fc8\u0001\u1f72\u1fc9\u0001\u1f73\u1fca\u0001\u1f74\u1fcb\u0001\u1f75\u1fcc\u0001\u1fc3\u1fd8\u0001\u1fd0\u1fd9\u0001\u1fd1\u1fda\u0001\u1f76\u1fdb\u0001\u1f77\u1fe8\u0001\u1fe0\u1fe9\u0001\u1fe1\u1fea\u0001\u1f7a\u1feb\u0001\u1f7b\u1fec\u0001\u1fe5\u1ff8\u0001\u1f78\u1ff9\u0001\u1f79\u1ffa\u0001\u1f7c\u1ffb\u0001\u1f7d\u1ffc\u0001\u1ff3\u2126\u0001\u03c9\u212a\u0001k\u212b\u0001\u00e5\u2132\u0001\u214e\u2160\u0001\u2170\u2161\u0001\u2171\u2162\u0001\u2172\u2163\u0001\u2173\u2164\u0001\u2174\u2165\u0001\u2175\u2166\u0001\u2176\u2167\u0001\u2177\u2168\u0001\u2178\u2169\u0001\u2179\u216a\u0001\u217a\u216b\u0001\u217b\u216c\u0001\u217c\u216d\u0001\u217d\u216e\u0001\u217e\u216f\u0001\u217f\u2183\u0001\u2184\u24b6\u0001\u24d0\u24b7\u0001\u24d1\u24b8\u0001\u24d2\u24b9\u0001\u24d3\u24ba\u0001\u24d4\u24bb\u0001\u24d5\u24bc\u0001\u24d6\u24bd\u0001\u24d7\u24be\u0001\u24d8\u24bf\u0001\u24d9\u24c0\u0001\u24da\u24c1\u0001\u24db\u24c2\u0001\u24dc\u24c3\u0001\u24dd\u24c4\u0001\u24de\u24c5\u0001\u24df\u24c6\u0001\u24e0\u24c7\u0001\u24e1\u24c8\u0001\u24e2\u24c9\u0001\u24e3\u24ca\u0001\u24e4\u24cb\u0001\u24e5\u24cc\u0001\u24e6\u24cd\u0001\u24e7\u24ce\u0001\u24e8\u24cf\u0001\u24e9\u2c00\u0001\u2c30\u2c01\u0001\u2c31\u2c02\u0001\u2c32\u2c03\u0001\u2c33\u2c04\u0001\u2c34\u2c05\u0001\u2c35\u2c06\u0001\u2c36\u2c07\u0001\u2c37\u2c08\u0001\u2c38\u2c09\u0001\u2c39\u2c0a\u0001\u2c3a\u2c0b\u0001\u2c3b\u2c0c\u0001\u2c3c\u2c0d\u0001\u2c3d\u2c0e\u0001\u2c3e\u2c0f\u0001\u2c3f\u2c10\u0001\u2c40\u2c11\u0001\u2c41\u2c12\u0001\u2c42\u2c13\u0001\u2c43\u2c14\u0001\u2c44\u2c15\u0001\u2c45\u2c16\u0001\u2c46\u2c17\u0001\u2c47\u2c18\u0001\u2c48\u2c19\u0001\u2c49\u2c1a\u0001\u2c4a\u2c1b\u0001\u2c4b\u2c1c\u0001\u2c4c\u2c1d\u0001\u2c4d\u2c1e\u0001\u2c4e\u2c1f\u0001\u2c4f\u2c20\u0001\u2c50\u2c21\u0001\u2c51\u2c22\u0001\u2c52\u2c23\u0001\u2c53\u2c24\u0001\u2c54\u2c25\u0001\u2c55\u2c26\u0001\u2c56\u2c27\u0001\u2c57\u2c28\u0001\u2c58\u2c29\u0001\u2c59\u2c2a\u0001\u2c5a\u2c2b\u0001\u2c5b\u2c2c\u0001\u2c5c\u2c2d\u0001\u2c5d\u2c2e\u0001\u2c5e\u2c2f\u0001\u2c5f\u2c60\u0001\u2c61\u2c62\u0001\u026b\u2c63\u0001\u1d7d\u2c64\u0001\u027d\u2c67\u0001\u2c68\u2c69\u0001\u2c6a\u2c6b\u0001\u2c6c\u2c6d\u0001\u0251\u2c6e\u0001\u0271\u2c6f\u0001\u0250\u2c70\u0001\u0252\u2c72\u0001\u2c73\u2c75\u0001\u2c76\u2c7e\u0001\u023f\u2c7f\u0001\u0240\u2c80\u0001\u2c81\u2c82\u0001\u2c83\u2c84\u0001\u2c85\u2c86\u0001\u2c87\u2c88\u0001\u2c89\u2c8a\u0001\u2c8b\u2c8c\u0001\u2c8d\u2c8e\u0001\u2c8f\u2c90\u0001\u2c91\u2c92\u0001\u2c93\u2c94\u0001\u2c95\u2c96\u0001\u2c97\u2c98\u0001\u2c99\u2c9a\u0001\u2c9b\u2c9c\u0001\u2c9d\u2c9e\u0001\u2c9f\u2ca0\u0001\u2ca1\u2ca2\u0001\u2ca3\u2ca4\u0001\u2ca5\u2ca6\u0001\u2ca7\u2ca8\u0001\u2ca9\u2caa\u0001\u2cab\u2cac\u0001\u2cad\u2cae\u0001\u2caf\u2cb0\u0001\u2cb1\u2cb2\u0001\u2cb3\u2cb4\u0001\u2cb5\u2cb6\u0001\u2cb7\u2cb8\u0001\u2cb9\u2cba\u0001\u2cbb\u2cbc\u0001\u2cbd\u2cbe\u0001\u2cbf\u2cc0\u0001\u2cc1\u2cc2\u0001\u2cc3\u2cc4\u0001\u2cc5\u2cc6\u0001\u2cc7\u2cc8\u0001\u2cc9\u2cca\u0001\u2ccb\u2ccc\u0001\u2ccd\u2cce\u0001\u2ccf\u2cd0\u0001\u2cd1\u2cd2\u0001\u2cd3\u2cd4\u0001\u2cd5\u2cd6\u0001\u2cd7\u2cd8\u0001\u2cd9\u2cda\u0001\u2cdb\u2cdc\u0001\u2cdd\u2cde\u0001\u2cdf\u2ce0\u0001\u2ce1\u2ce2\u0001\u2ce3\u2ceb\u0001\u2cec\u2ced\u0001\u2cee\u2cf2\u0001\u2cf3\ua640\u0001\ua641\ua642\u0001\ua643\ua644\u0001\ua645\ua646\u0001\ua647\ua648\u0001\ua649\ua64a\u0001\ua64b\ua64c\u0001\ua64d\ua64e\u0001\ua64f\ua650\u0001\ua651\ua652\u0001\ua653\ua654\u0001\ua655\ua656\u0001\ua657\ua658\u0001\ua659\ua65a\u0001\ua65b\ua65c\u0001\ua65d\ua65e\u0001\ua65f\ua660\u0001\ua661\ua662\u0001\ua663\ua664\u0001\ua665\ua666\u0001\ua667\ua668\u0001\ua669\ua66a\u0001\ua66b\ua66c\u0001\ua66d\ua680\u0001\ua681\ua682\u0001\ua683\ua684\u0001\ua685\ua686\u0001\ua687\ua688\u0001\ua689\ua68a\u0001\ua68b\ua68c\u0001\ua68d\ua68e\u0001\ua68f\ua690\u0001\ua691\ua692\u0001\ua693\ua694\u0001\ua695\ua696\u0001\ua697\ua698\u0001\ua699\ua69a\u0001\ua69b\ua722\u0001\ua723\ua724\u0001\ua725\ua726\u0001\ua727\ua728\u0001\ua729\ua72a\u0001\ua72b\ua72c\u0001\ua72d\ua72e\u0001\ua72f\ua732\u0001\ua733\ua734\u0001\ua735\ua736\u0001\ua737\ua738\u0001\ua739\ua73a\u0001\ua73b\ua73c\u0001\ua73d\ua73e\u0001\ua73f\ua740\u0001\ua741\ua742\u0001\ua743\ua744\u0001\ua745\ua746\u0001\ua747\ua748\u0001\ua749\ua74a\u0001\ua74b\ua74c\u0001\ua74d\ua74e\u0001\ua74f\ua750\u0001\ua751\ua752\u0001\ua753\ua754\u0001\ua755\ua756\u0001\ua757\ua758\u0001\ua759\ua75a\u0001\ua75b\ua75c\u0001\ua75d\ua75e\u0001\ua75f\ua760\u0001\ua761\ua762\u0001\ua763\ua764\u0001\ua765\ua766\u0001\ua767\ua768\u0001\ua769\ua76a\u0001\ua76b\ua76c\u0001\ua76d\ua76e\u0001\ua76f\ua779\u0001\ua77a\ua77b\u0001\ua77c\ua77d\u0001\u1d79\ua77e\u0001\ua77f\ua780\u0001\ua781\ua782\u0001\ua783\ua784\u0001\ua785\ua786\u0001\ua787\ua78b\u0001\ua78c\ua78d\u0001\u0265\ua790\u0001\ua791\ua792\u0001\ua793\ua796\u0001\ua797\ua798\u0001\ua799\ua79a\u0001\ua79b\ua79c\u0001\ua79d\ua79e\u0001\ua79f\ua7a0\u0001\ua7a1\ua7a2\u0001\ua7a3\ua7a4\u0001\ua7a5\ua7a6\u0001\ua7a7\ua7a8\u0001\ua7a9\ua7aa\u0001\u0266\ua7ab\u0001\u025c\ua7ac\u0001\u0261\ua7ad\u0001\u026c\ua7ae\u0001\u026a\ua7b0\u0001\u029e\ua7b1\u0001\u0287\ua7b2\u0001\u029d\ua7b3\u0001\uab53\ua7b4\u0001\ua7b5\ua7b6\u0001\ua7b7\ua7b8\u0001\ua7b9\ua7ba\u0001\ua7bb\ua7bc\u0001\ua7bd\ua7be\u0001\ua7bf\ua7c0\u0001\ua7c1\ua7c2\u0001\ua7c3\ua7c4\u0001\ua794\ua7c5\u0001\u0282\ua7c6\u0001\u1d8e\ua7c7\u0001\ua7c8\ua7c9\u0001\ua7ca\ua7d0\u0001\ua7d1\ua7d6\u0001\ua7d7\ua7d8\u0001\ua7d9\ua7f5\u0001\ua7f6\uff21\u0001\uff41\uff22\u0001\uff42\uff23\u0001\uff43\uff24\u0001\uff44\uff25\u0001\uff45\uff26\u0001\uff46\uff27\u0001\uff47\uff28\u0001\uff48\uff29\u0001\uff49\uff2a\u0001\uff4a\uff2b\u0001\uff4b\uff2c\u0001\uff4c\uff2d\u0001\uff4d\uff2e\u0001\uff4e\uff2f\u0001\uff4f\uff30\u0001\uff50\uff31\u0001\uff51\uff32\u0001\uff52\uff33\u0001\uff53\uff34\u0001\uff54\uff35\u0001\uff55\uff36\u0001\uff56\uff37\u0001\uff57\uff38\u0001\uff58\uff39\u0001\uff59\uff3a\u0001\uff5a", }; diff --git a/maven/python-runtime/src/main/java/com/codename1/python/runtime/Utf8.java b/maven/python-runtime/src/main/java/com/codename1/python/runtime/Utf8.java index b4e612310a2..1fa49cc0c3e 100644 --- a/maven/python-runtime/src/main/java/com/codename1/python/runtime/Utf8.java +++ b/maven/python-runtime/src/main/java/com/codename1/python/runtime/Utf8.java @@ -23,36 +23,76 @@ */ package com.codename1.python.runtime; +import java.io.UnsupportedEncodingException; + /// UTF-8 coding with Python's strict error behaviour. final class Utf8 { - private Utf8() { } static byte[] encode(String s) { - java.io.ByteArrayOutputStream out = new java.io.ByteArrayOutputStream(s.length()); - for (int i = 0; i < s.length(); i++) { - int c = s.codePointAt(i); - if (c > 0xffff) { - i++; + // The platform's encoder: on ParparVM a vectorized native that + // writes a compact (Latin-1) string with one copy, and on a JDK an + // intrinsic. A lone surrogate -- which only an escape, chr() or a + // surrogateescape decode can put into a str -- comes out as U+FFFD + // where CPython's strict handler raises: finding one first would be + // a scan of every string in Java, which is what this replaces. + // Through the Charset overload: it declares no checked exception, so + // no handler is entered per call (a setjmp on ParparVM), and the + // device's String answers a Latin-1 string from it directly. + return s.getBytes(java.nio.charset.StandardCharsets.UTF_8); + } + + /// The Java encoder, for a platform without a UTF-8 charset. + static byte[] encodeChars(String s) { + int n = s.length(); + char[] cs = new char[n]; + s.getChars(0, n, cs, 0); + int i = 0; + for (; i < n; i++) { + if (cs[i] >= 0x80) { + break; + } + } + if (i == n) { + byte[] out = new byte[n]; + for (int k = 0; k < n; k++) { + out[k] = (byte) cs[k]; } + return out; + } + byte[] buf = new byte[i + (n - i) * 3]; + for (int k = 0; k < i; k++) { + buf[k] = (byte) cs[k]; + } + int o = i; + for (; i < n; i++) { + int c = cs[i]; if (c < 0x80) { - out.write(c); + buf[o] = (byte) c; + o++; } else if (c < 0x800) { - out.write(0xc0 | c >> 6); - out.write(0x80 | c & 0x3f); - } else if (c < 0x10000) { - out.write(0xe0 | c >> 12); - out.write(0x80 | c >> 6 & 0x3f); - out.write(0x80 | c & 0x3f); + buf[o] = (byte) (0xc0 | c >> 6); + buf[o + 1] = (byte) (0x80 | c & 0x3f); + o += 2; + } else if ((c & 0xfc00) == 0xd800 && i + 1 < n && (cs[i + 1] & 0xfc00) == 0xdc00) { + c = ((c & 0x3ff) << 10 | cs[i + 1] & 0x3ff) + 0x10000; + i++; + buf[o] = (byte) (0xf0 | c >> 18); + buf[o + 1] = (byte) (0x80 | c >> 12 & 0x3f); + buf[o + 2] = (byte) (0x80 | c >> 6 & 0x3f); + buf[o + 3] = (byte) (0x80 | c & 0x3f); + o += 4; } else { - out.write(0xf0 | c >> 18); - out.write(0x80 | c >> 12 & 0x3f); - out.write(0x80 | c >> 6 & 0x3f); - out.write(0x80 | c & 0x3f); + buf[o] = (byte) (0xe0 | c >> 12); + buf[o + 1] = (byte) (0x80 | c >> 6 & 0x3f); + buf[o + 2] = (byte) (0x80 | c & 0x3f); + o += 3; } } - return out.toByteArray(); + byte[] out = new byte[o]; + System.arraycopy(buf, 0, out, 0, o); + return out; } static String decode(byte[] b) { @@ -62,19 +102,72 @@ static String decode(byte[] b) { /// Decodes UTF-8 under a Python error handler: `strict` raises, /// `replace` substitutes U+FFFD for each bad byte, `ignore` drops it. static String decode(byte[] b, String errors) { + // The platform's decoder (a vectorized native on ParparVM) replaces + // each malformed sequence with U+FFFD. A result without one proves + // the input valid, and every handler agrees on valid input; the Java + // decoder below runs only for the rest, raising or replacing exactly + // as Python does. + String fast; + try { + fast = new String(b, "UTF-8"); + } catch (UnsupportedEncodingException e) { + fast = null; + } + if (fast != null && fast.indexOf(0xFFFD) < 0) { + return fast; + } + return decodeChecked(b, errors); + } + + private static String decodeChecked(byte[] b, String errors) { boolean strict = !"replace".equals(errors) && !"ignore".equals(errors); boolean replace = "replace".equals(errors); - StringBuilder sb = new StringBuilder(b.length); int i = 0; - while (i < b.length) { + for (; i < b.length; i++) { + if (b[i] < 0) { + break; + } + } + if (i == b.length) { + // All ASCII: the bytes are the characters, one copy into Latin-1 storage. + return Codecs.latin1(b, 0, b.length); + } + // Chars straight into an array no longer than the bytes: a + // StringBuilder paid a capacity check and a call per character. + char[] sb = new char[b.length]; + int o = 0; + int pairs = 0; + for (; o < i; o++) { + sb[o] = (char) b[o]; + } + int n = b.length; + while (i < n) { int c = b[i] & 0xff; int need; int cp; if (c < 0x80) { - sb.append((char) c); + sb[o] = (char) c; + o++; i++; continue; - } else if (c >= 0xc2 && c < 0xe0) { + } + // The well-formed two and three byte forms, tested in line: no + // lead here has a narrowed second byte (E0 and ED do, and go the + // long way through `continues`). + if (c >= 0xc2 && c < 0xe0 && i + 1 < n && (b[i + 1] & 0xc0) == 0x80) { + sb[o] = (char) ((c & 0x1f) << 6 | b[i + 1] & 0x3f); + o++; + i += 2; + continue; + } + if (c > 0xe0 && c < 0xf0 && c != 0xed && i + 2 < n && (b[i + 1] & 0xc0) == 0x80 + && (b[i + 2] & 0xc0) == 0x80) { + sb[o] = (char) ((c & 0x0f) << 12 | (b[i + 1] & 0x3f) << 6 | b[i + 2] & 0x3f); + o++; + i += 3; + continue; + } + if (c >= 0xc2 && c < 0xe0) { need = 1; cp = c & 0x1f; } else if (c >= 0xe0 && c < 0xf0) { @@ -85,10 +178,10 @@ static String decode(byte[] b, String errors) { cp = c & 0x07; } else { if (strict) { - throw decodeError(c, i); + throw Py.decodeError("utf-8", b, i, i + 1, "invalid start byte"); } if (replace) { - sb.append('\ufffd'); + sb[o++] = '\ufffd'; } i++; continue; @@ -96,16 +189,20 @@ static String decode(byte[] b, String errors) { boolean bad = false; if (i + need >= b.length) { if (strict) { - throw Py.error(Py.UNICODE_DECODE_ERROR, "'utf-8' codec can't decode bytes in position " + i - + "-" + (b.length - 1) + ": unexpected end of data"); + for (int k = 1; i + k < b.length; k++) { + if (!continues(c, k, b[i + k] & 0xff)) { + throw Py.decodeError("utf-8", b, i, i + k, "invalid continuation byte"); + } + } + throw Py.decodeError("utf-8", b, i, b.length, "unexpected end of data"); } bad = true; } else { for (int k = 1; k <= need; k++) { int cc = b[i + k] & 0xff; - if ((cc & 0xc0) != 0x80) { + if (!continues(c, k, cc)) { if (strict) { - throw decodeError(c, i); + throw Py.decodeError("utf-8", b, i, i + k, "invalid continuation byte"); } bad = true; break; @@ -115,19 +212,45 @@ static String decode(byte[] b, String errors) { } if (bad) { if (replace) { - sb.append('\ufffd'); + sb[o++] = '\ufffd'; } i++; continue; } - sb.appendCodePoint(cp); + if (cp >= 0x10000) { + sb[o] = Character.highSurrogate(cp); + sb[o + 1] = Character.lowSurrogate(cp); + o += 2; + pairs++; + } else { + sb[o] = (char) cp; + o++; + } i += need + 1; } - return sb.toString(); + String r = new String(sb, 0, o); + PyStr.knownSurrogates(r, pairs); + return r; } - private static PyException decodeError(int c, int pos) { - return Py.error(Py.UNICODE_DECODE_ERROR, "'utf-8' codec can't decode byte 0x" + Integer.toHexString(c) - + " in position " + pos + ": invalid start byte"); + /// Whether `cc` may be the `k`th byte of a sequence led by `lead`. The + /// second byte's range is narrowed after E0, ED, F0 and F4, so an + /// overlong form, an encoded surrogate or a code point past U+10FFFF is + /// rejected there, at the byte CPython rejects it at. + private static boolean continues(int lead, int k, int cc) { + int lo = 0x80; + int hi = 0xbf; + if (k == 1) { + if (lead == 0xe0) { + lo = 0xa0; + } else if (lead == 0xed) { + hi = 0x9f; + } else if (lead == 0xf0) { + lo = 0x90; + } else if (lead == 0xf4) { + hi = 0x8f; + } + } + return cc >= lo && cc <= hi; } } diff --git a/maven/python-runtime/src/main/java/com/codename1/python/runtime/XmlScan.java b/maven/python-runtime/src/main/java/com/codename1/python/runtime/XmlScan.java new file mode 100644 index 00000000000..e43ea65d03a --- /dev/null +++ b/maven/python-runtime/src/main/java/com/codename1/python/runtime/XmlScan.java @@ -0,0 +1,1173 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.python.runtime; + +/// `_cn1xml`: the fast path of the bundled expat's tokenizer. +/// +/// The tokenizer matches every tag with a regular expression. These scan the +/// shapes nearly every document consists of -- ASCII names, quoted attribute +/// values without references -- by hand, and answer `None` for anything else, +/// which the tokenizer then hands to its expressions exactly as before. So a +/// scan never decides a malformed or unusual tag: it either agrees with the +/// expression or declines. +final class XmlScan { + private XmlScan() { + } + + static PyModule module() { + PyModule m = new PyModule("_cn1xml", new String[0]); + m.setAttr("scan_start", PyBuiltin.fixed2("scan_start", (a0, a1) -> scanStart(Typed.asStr(a0), (int) Typed.toLong(a1)))); + m.setAttr("run", PyBuiltin.fixed3("run", (a0, a1, a2) -> Long.valueOf(ExpatRun.run(a0, Typed.asStr(a1), (int) Typed.toLong(a2))))); + m.setAttr("iter", PyBuiltin.fixed2("iter", (a0, a1) -> new ElementIter(a0, a1))); + m.setAttr("find", PyBuiltin.fixed2("find", (a0, a1) -> children(a0, a1, false))); + m.setAttr("findall", PyBuiltin.fixed2("findall", (a0, a1) -> children(a0, a1, true))); + m.setAttr("build", PyBuiltin.positional("build", + a -> new Builder(Typed.asStr(a[0]), a[1], Py.isTrue(a[2]), a.length > 3 ? a[3] : null).build())); + m.setAttr("lxml_build", PyBuiltin.positional("lxml_build", + a -> new Builder(Typed.asStr(a[0]), Py.isTrue(a[1]), new Lxml(a)).build())); + m.setAttr("scan_end", PyBuiltin.fixed2("scan_end", (a0, a1) -> scanEnd(Typed.asStr(a0), (int) Typed.toLong(a1)))); + return m; + } + + /// A character the expat module's `_NAME` class accepts, restricted to + /// ASCII: beyond it the class depends on what `\s` means, so decline. + private static boolean nameChar(char c) { + if (c <= ' ' || c >= 0x7f) { + return false; + } + switch (c) { + case '<': case '>': case '/': case '=': case '"': case '\'': case '!': case '?': + case '&': case ';': case '%': case '(': case ')': case '[': case ']': case ',': case '|': + return false; + default: + return true; + } + } + + /// Whitespace both scans skip: the ASCII members of `\s`. Its other + /// members (\x0b, \x0c, \x1c-\x1f and non-ASCII spaces) make a scan + /// decline, through [#nameChar] answering false for them. + static boolean space(char c) { + return c == ' ' || c == '\t' || c == '\n' || c == '\r'; + } + + static int name(String s, int i, int n) { + while (i < n && nameChar(s.charAt(i))) { + i++; + } + return i; + } + + /// `` at `pos`: `(end, name, [n0, v0, n1, v1 ...], + /// selfClosing)`, values already normalised as `_attr_value` would (tab, + /// newline and CR to a space). `None` for a duplicate attribute, a value + /// with `<` or `&`, or any shape off the common path. + static Object scanStart(String s, int pos) { + int n = s.length(); + int i = pos + 1; + int e = name(s, i, n); + if (e == i) { + return Py.NONE; + } + String qname = s.substring(i, e); + PyList attrs = Py.list(); + i = e; + while (true) { + int ws = i; + while (i < n && space(s.charAt(i))) { + i++; + } + if (i >= n) { + return Py.NONE; + } + char c = s.charAt(i); + if (c == '>' || c == '/') { + boolean self = c == '/'; + if (self) { + if (i + 1 >= n || s.charAt(i + 1) != '>') { + return Py.NONE; + } + i++; + } + return Py.tuple(Long.valueOf(i + 1), qname, attrs, Py.bool(self)); + } + if (i == ws) { + return Py.NONE; + } + int ne = name(s, i, n); + if (ne == i) { + return Py.NONE; + } + String an = s.substring(i, ne); + i = ne; + while (i < n && space(s.charAt(i))) { + i++; + } + if (i >= n || s.charAt(i) != '=') { + return Py.NONE; + } + i++; + while (i < n && space(s.charAt(i))) { + i++; + } + if (i >= n) { + return Py.NONE; + } + char q = s.charAt(i); + if (q != '"' && q != '\'') { + return Py.NONE; + } + int vs = i + 1; + int ve = s.indexOf(q, vs); + if (ve < 0) { + return Py.NONE; + } + boolean norm = false; + for (int k = vs; k < ve; k++) { + char v = s.charAt(k); + if (v == '<' || v == '&') { + return Py.NONE; + } + if (v == '\t' || v == '\n' || v == '\r') { + norm = true; + } + } + for (int k = 0; k < attrs.size(); k += 2) { + if (an.equals(attrs.get(k))) { + return Py.NONE; + } + } + String val = s.substring(vs, ve); + if (norm) { + val = val.replace('\t', ' ').replace('\n', ' ').replace('\r', ' '); + } + attrs.append(an); + attrs.append(val); + i = ve + 1; + } + } + + /// `` at `pos`: `(end, name)`, or `None` off the common path. + static Object scanEnd(String s, int pos) { + int n = s.length(); + int i = pos + 2; + int e = name(s, i, n); + if (e == i) { + return Py.NONE; + } + int j = e; + while (j < n && space(s.charAt(j))) { + j++; + } + if (j >= n || s.charAt(j) != '>') { + return Py.NONE; + } + return Py.tuple(Long.valueOf(j + 1), s.substring(i, e)); + } + + private static final String XML_NS = "http://www.w3.org/XML/1998/namespace"; + private static final String XMLNS_NS = "http://www.w3.org/2000/xmlns/"; + + /// Thrown inside [Builder] to decline: the document is not one of the + /// shapes the fast build reproduces exactly, so the Python parser runs. + private static final class Decline extends RuntimeException { + private static final long serialVersionUID = 1L; + + Decline() { + super(); + } + } + + private static final Decline DECLINE = new Decline(); + + /// `ElementTree.XML(text)` with the default parser and tree builder, + /// done in one pass in Java, as CPython does it in C: per element the + /// Python path ran the tokenizer, `_start_tail`, `XMLParser._start`, + /// `_fixname`, `TreeBuilder.start` and `Element.__init__`. Elements are + /// still made by calling the factory, so they are the module's own + /// `Element`. It accepts elements, attributes, namespaces, the five + /// predefined and character references, comments and an XML + /// declaration, and answers `None` for anything else (a DOCTYPE, CDATA, + /// a processing instruction, any error), for the Python parser to + /// handle -- and to report exactly as it does. + private static final AttrSite CHILDREN = new AttrSite("_children"); + private static final StoreSite SET_CHILDREN = new StoreSite("_children"); + private static final StoreSite SET_ATTRIB = new StoreSite("attrib"); + /// Slots in a builder's tag cache, a power of two. + private static final int TAG_CACHE = 64; + + private static final AttrSite TAG = new AttrSite("tag"); + private static final StoreSite SET_TAG = new StoreSite("tag"); + + /// Whether ElementPath would read `path` as one child tag: `tag` or + /// `{uri}tag`, with none of the characters a path expression uses. + static boolean plainTag(String path) { + int n = path.length(); + int start = 0; + if (n > 0 && path.charAt(0) == '{') { + int close = path.indexOf('}'); + if (close <= 1) { + return false; + } + start = close + 1; + } + if (start >= n || path.charAt(start) == '{') { + return false; + } + for (int k = start; k < n; k++) { + char c = path.charAt(k); + if (c < 128 && PATH_SPECIAL[c]) { + return false; + } + } + return true; + } + + private static final boolean[] PATH_SPECIAL = new boolean[128]; + + static { + String special = "/[]*.@()=:'\" \t\n\r"; + for (int k = 0; k < special.length(); k++) { + PATH_SPECIAL[special.charAt(k)] = true; + } + } + + /// `find` (the first) or `findall` (a list) of the children of `self` + /// whose tag equals `path`, NotImplemented when `path` is not one tag. + static Object children(Object self, Object path, boolean all) { + if (!(path instanceof String) || !plainTag((String) path)) { + return Py.NOT_IMPLEMENTED; + } + Object kids = CHILDREN.get(self); + PyList out = all ? new PyList() : null; + PyList ls = kids instanceof PyList ? (PyList) kids : null; + PyObject it = ls != null ? null : Py.iter(kids); + int k = 0; + for (Object e; (e = it != null ? it.next() : k < ls.size ? ls.get(k++) : null) != null;) { //NOPMD AssignmentInOperand - the list or iterator walk in one loop + if (Py.eqBool(TAG.get(e), path)) { + if (!all) { + return e; + } + out.append(e); + } + } + return all ? out : Py.NONE; + } + + /// `Element.iter(tag)`: the element and its descendants in document + /// order, those whose tag equals `tag` (every one for None), walked over a + /// stack of `(children, next index)` as the Python version it replaces + /// walks -- and as CPython's C accelerator does, in its own language. + /// Children are read when the walk reaches them, so a tree changed + /// between two steps is seen as the Python generator saw it. + static final class ElementIter extends PyObject { + private final Object root; + private final Object tag; + private int state; + private Object children; + private int i; + /// The element last yielded, whose children the next step enters. + private Object pending; + private Object[] lists = new Object[8]; + private int[] marks = new int[8]; + private int depth; + + ElementIter(Object root, Object tag) { + this.root = root; + this.tag = tag == Py.NONE ? null : tag; //NOPMD CompareObjectsWithEquals - None is a singleton + } + + @Override + public PyType type() { + return Py.ITERATOR_TYPE; + } + + @Override + public Object iter() { + return this; + } + + private boolean matches(Object e) { + return tag == null || Py.eqBool(TAG.get(e), tag); + } + + @Override + public Object next() { + if (state == 0) { + state = 1; + if (matches(root)) { + return root; + } + } + if (state == 1) { + state = 2; + children = CHILDREN.get(root); + i = 0; + } else if (state == 3) { + return null; + } + if (pending != null) { + Object kids = CHILDREN.get(pending); + pending = null; + if (Py.isTrue(kids)) { + if (depth == lists.length) { + lists = java.util.Arrays.copyOf(lists, depth * 2); + marks = java.util.Arrays.copyOf(marks, depth * 2); + } + lists[depth] = children; + marks[depth] = i; + depth++; + children = kids; + i = 0; + } + } + while (true) { + Object c = children; + int n = c instanceof PyList ? ((PyList) c).size : Py.len(c); + if (i < n) { + Object e = c instanceof PyList ? ((PyList) c).get(i) : Py.getitem(c, PyInt.of(i)); + i++; + if (matches(e)) { + pending = e; + return e; + } + Object kids = CHILDREN.get(e); + if (Py.isTrue(kids)) { + if (depth == lists.length) { + lists = java.util.Arrays.copyOf(lists, depth * 2); + marks = java.util.Arrays.copyOf(marks, depth * 2); + } + lists[depth] = children; + marks[depth] = i; + depth++; + children = kids; + i = 0; + } + } else if (depth > 0) { + depth--; + children = lists[depth]; + i = marks[depth]; + lists[depth] = null; + } else { + state = 3; + children = null; + return null; + } + } + } + } + + /// What `_cn1xml.lxml_build` needs of the lxml shim to build a tree as + /// its `_XMLDriver` feeding a `_TreeSink` does: `(text, from_bytes, + /// class_for, lookup, nohint, cnt, remove_blank_text, cache)`. + /// `class_for(tag)` answers the element class; the shim passes it only + /// for a lookup whose answer depends on nothing but the tag, so it is + /// asked once per tag, and `cache` is the shim's tag -> class dict for + /// the lookup, kept across parses while no registration changed it. + static final class Lxml { + final Object classFor; + final Object lookup; + final Object noHint; + final Object cnt; + final boolean removeBlankText; + final PyDict classes; + + Lxml(Object[] a) { + classFor = a[2]; + lookup = a[3]; + noHint = a[4]; + cnt = a[5]; + removeBlankText = Py.isTrue(a[6]); + classes = a.length > 7 && a[7] instanceof PyDict ? (PyDict) a[7] : new PyDict(); + } + + Object classFor(String tag) { + Object c = classes.getOrNull(tag); + if (c == null) { + c = Py.call(classFor, tag); + classes.setItem(tag, c); + } + return c; + } + } + + private static final AttrSite NEW = new AttrSite("__new__"); + private static final AttrSite INIT = new AttrSite("_init"); + private static final AttrSite KIDS = new AttrSite("_xkids"); + private static final StoreSite X_KIND = new StoreSite("_xkind"); + private static final StoreSite X_TAG = new StoreSite("_xtag"); + private static final StoreSite X_ATTRIB = new StoreSite("_xattrib"); + private static final StoreSite X_NS = new StoreSite("_xns"); + private static final StoreSite X_KIDS = new StoreSite("_xkids"); + private static final StoreSite X_PARENT = new StoreSite("_xparent"); + private static final StoreSite X_TEXT = new StoreSite("_xtext"); + private static final StoreSite X_TAIL = new StoreSite("_xtail"); + private static final StoreSite X_PFX = new StoreSite("_xpfx"); + private static final StoreSite X_LOOKUP = new StoreSite("_xlookup"); + private static final StoreSite X_DOC = new StoreSite("_xdoc"); + private static final StoreSite X_TARGET = new StoreSite("_xtarget"); + private static final StoreSite X_CNT = new StoreSite("_xcnt"); + + private static final class Builder { + private final String s; + private final int n; + private final Object factory; + private final boolean fromBytes; + /// Whether the factory is a class whose `__init__` is ElementTree's own + /// `Element.__init__`: the builder then makes its elements as that + /// method does -- `tag`, a dict of its own as `attrib`, an empty + /// `_children`, in that order -- giving each the dict it built. + private final boolean direct; + private int i; + private final StringBuilder data = new StringBuilder(); //NOPMD AvoidStringBufferField - one parse's text, dropped with the builder + private Object last; + private boolean tail; + private Object root; + private final java.util.ArrayList open = new java.util.ArrayList(); + private final java.util.ArrayList openNames = new java.util.ArrayList(); + /// Namespace scopes: a map per open element that declared any, with + /// the depth it was declared at. + private final java.util.ArrayList> scopes = + new java.util.ArrayList>(); + private final java.util.ArrayList scopeDepth = new java.util.ArrayList(); + /// Expanded element names by their qualified name, as expat's + /// ElementTree builder keeps them: one string per distinct tag, so + /// equal tags are one object and compare by identity. Emptied + /// whenever a namespace scope opens or closes. + private final String[] rawNames = new String[TAG_CACHE]; + private final String[] tagNames = new String[TAG_CACHE]; + /// Attribute names as written, one string per distinct name. + private final String[] attrRaw = new String[TAG_CACHE]; + /// The expanded name of `attrRaw[slot]` under the current + /// namespace scope, or null until one is needed. + private final String[] attrExp = new String[TAG_CACHE]; + /// The `attrRaw` slot of each name in `attrNames`. + private int[] attrSlots = new int[16]; + /// The hash of the name [#nameEnd] last scanned. + private int nameHash; + private final java.util.ArrayList attrNames = new java.util.ArrayList(); + private final java.util.ArrayList attrValues = new java.util.ArrayList(); + /// The lxml shim's tree, or null for ElementTree's. + private final Lxml lx; + /// Per open element, as the shim's driver keeps them: whether it has + /// had a child, and whether it has kept text (bit 0 and bit 1). + private final java.util.ArrayList state = new java.util.ArrayList(); + + Builder(String text, boolean fromBytes, Lxml lx) { + this(text, null, fromBytes, null, lx); + } + + Builder(String text, Object factory, boolean fromBytes, Object elementInit) { + this(text, factory, fromBytes, elementInit, null); + } + + private Builder(String text, Object factory, boolean fromBytes, Object elementInit, Lxml lx) { + this.lx = lx; + // Nothing the build runs can change the class: no Python code runs + // while elements are made directly. + this.direct = elementInit != null && factory instanceof PyType + && ((PyType) factory).plainInit() == elementInit; //NOPMD CompareObjectsWithEquals - identity is meant + String t = text; + if (t.indexOf('\r') >= 0) { + t = t.replace("\r\n", "\n").replace('\r', '\n'); + } + if (t.length() > 0 && t.charAt(0) == '\uFEFF') { + t = t.substring(1); + } + this.s = t; + this.n = t.length(); + this.factory = factory; + this.fromBytes = fromBytes; + java.util.HashMap base = new java.util.HashMap(); + base.put("xml", XML_NS); + scopes.add(base); + scopeDepth.add(Integer.valueOf(-1)); + } + + Object build() { + try { + return run(); + } catch (Decline d) { + return Py.NONE; + } + } + + private Object run() { + if (s.startsWith(" 5 && XmlScan.space(s.charAt(5))) { + decl(); + } + while (i < n) { + int lt = s.indexOf('<', i); + int end = lt < 0 ? n : lt; + if (end > i) { + text(i, end); + i = end; + } + if (lt < 0) { + break; + } + char c = lt + 1 < n ? s.charAt(lt + 1) : '\0'; + if (c == '/') { + endTag(); + } else if (c == '!') { + comment(); + } else if (c == '?') { + throw DECLINE; + } else { + startTag(); + } + } + if (root == null || !open.isEmpty()) { + throw DECLINE; + } + return root; + } + + private void decl() { + int e = s.indexOf("?>"); + if (e < 0) { + throw DECLINE; + } + int j = 5; + String[] keys = {"version", "encoding", "standalone"}; + int k = 0; + String enc = null; + boolean first = true; + while (true) { + int ws = j; + while (j < e && XmlScan.space(s.charAt(j))) { + j++; + } + if (j == e) { + break; + } + if (j == ws) { + throw DECLINE; + } + int ne = XmlScan.name(s, j, e); + String key = s.substring(j, ne); + while (k < keys.length && !keys[k].equals(key)) { + if (first) { + throw DECLINE; + } + k++; + } + if (k == keys.length) { + throw DECLINE; + } + first = false; + j = ne; + while (j < e && XmlScan.space(s.charAt(j))) { + j++; + } + if (j >= e || s.charAt(j) != '=') { + throw DECLINE; + } + j++; + while (j < e && XmlScan.space(s.charAt(j))) { + j++; + } + if (j >= e) { + throw DECLINE; + } + char q = s.charAt(j); + int ve = q == '"' || q == '\'' ? s.indexOf(q, j + 1) : -1; + if (ve < 0 || ve > e) { + throw DECLINE; + } + String v = s.substring(j + 1, ve); + if (k == 1) { + enc = v; + } else if (k == 2 && !"yes".equals(v) && !"no".equals(v)) { + throw DECLINE; + } + k++; + j = ve + 1; + } + if (first) { + throw DECLINE; + } + if (fromBytes && enc != null && !"utf-8".equalsIgnoreCase(enc) && !"utf8".equalsIgnoreCase(enc)) { + throw DECLINE; + } + i = e + 2; + } + + private void comment() { + if (lx != null || !s.startsWith("", i + 4); + if (e < 0) { + throw DECLINE; + } + int bad = s.indexOf("--", i + 4); + if (bad < e || s.charAt(e - 1) == '-' && e - 1 >= i + 4) { + throw DECLINE; + } + i = e + 3; + } + + /// Character data in `[a, b)`. Outside the root only whitespace is + /// allowed, and it is dropped. + private void text(int a, int b) { + if (open.isEmpty()) { + for (int k = a; k < b; k++) { + char c = s.charAt(k); + if (c != ' ' && c != '\t' && c != '\n') { + throw DECLINE; + } + } + return; + } + // Appended a run at a time: each append to a builder takes its lock. + int k = a; + while (k < b) { + int run = k; + while (run < b && s.charAt(run) != '&') { + if (s.charAt(run) == ']' && run + 3 <= b && s.startsWith("]]>", run)) { + throw DECLINE; + } + run++; + } + data.append(s, k, run); + if (run < b) { + k = ref(run, b, data); + } else { + k = run; + } + } + } + + /// The reference at `k` (an `&`) appended to `out`; answers the + /// offset after it. + private int ref(int k, int b, StringBuilder out) { + int semi = s.indexOf(';', k + 1); + if (semi < 0 || semi >= b) { + throw DECLINE; + } + String body = s.substring(k + 1, semi); + if (body.length() > 1 && body.charAt(0) == '#') { + long v = 0; + boolean hex = body.charAt(1) == 'x'; + int from = hex ? 2 : 1; + if (from >= body.length() || body.length() - from > 8) { + throw DECLINE; + } + for (int d = from; d < body.length(); d++) { + int dv = Character.digit(body.charAt(d), hex ? 16 : 10); + if (dv < 0 || body.charAt(d) > 0x7f) { + throw DECLINE; + } + v = v * (hex ? 16 : 10) + dv; + } + boolean ok = v == 0x9 || v == 0xA || v == 0xD || v >= 0x20 && v <= 0xD7FF + || v >= 0xE000 && v <= 0xFFFD || v >= 0x10000 && v <= 0x10FFFF; + if (!ok) { + throw DECLINE; + } + if (v >= 0x10000) { + out.append(Character.toChars((int) v)); + } else { + out.append((char) v); + } + } else if ("amp".equals(body)) { + out.append('&'); + } else if ("lt".equals(body)) { + out.append('<'); + } else if ("gt".equals(body)) { + out.append('>'); + } else if ("quot".equals(body)) { + out.append('"'); + } else if ("apos".equals(body)) { + out.append('\''); + } else { + throw DECLINE; + } + return semi + 1; + } + + private void flush() { + if (lx != null) { + return; + } + if (data.length() > 0) { + if (last != null) { + Py.obj(last).setAttr(tail ? "tail" : "text", data.toString()); + } + data.setLength(0); + } + } + + /// Scans the name at `a`, leaving `i` after it and its hash in + /// `nameHash`, without making a string of it. + private int nameEnd(int a) { + int e = XmlScan.name(s, a, n); + if (e == a) { + throw DECLINE; + } + int h = 0; + for (int k = a; k < e; k++) { + char c = s.charAt(k); + if (c == '{' || c == '}') { + throw DECLINE; + } + h = 31 * h + c; + } + i = e; + nameHash = h; + return e; + } + + private boolean named(int a, int e, String name) { + return name != null && name.length() == e - a && s.regionMatches(a, name, 0, e - a); + } + + private String uri(String prefix) { + for (int k = scopes.size() - 1; k >= 0; k--) { + java.util.HashMap m = scopes.get(k); + if (m.containsKey(prefix)) { + return m.get(prefix); + } + } + return null; + } + + /// ElementTree's name for `q`: `{uri}local` when it has a namespace. + private String expand(String q, boolean element) { + int colon = q.indexOf(':'); + if (colon < 0) { + if (!element) { + return q; + } + String u = uri(""); + return u == null || u.length() == 0 ? q : "{" + u + "}" + q; + } + if (colon == 0 || colon == q.length() - 1 || q.indexOf(':', colon + 1) >= 0) { + throw DECLINE; + } + String u = uri(q.substring(0, colon)); + if (u == null || u.length() == 0) { + throw DECLINE; + } + return "{" + u + "}" + q.substring(colon + 1); + } + + private void skipSpace() { + while (i < n && XmlScan.space(s.charAt(i))) { + i++; + } + } + + private void startTag() { + if (root != null && open.isEmpty()) { + throw DECLINE; + } + int qa = i + 1; + int qe = nameEnd(qa); + int slot = (nameHash ^ nameHash >>> 16) & (TAG_CACHE - 1); + String q = rawNames[slot]; + if (!named(qa, qe, q)) { + q = s.substring(qa, qe); + } + java.util.ArrayList names = attrNames; + java.util.ArrayList values = attrValues; + names.clear(); + values.clear(); + java.util.HashMap declared = null; + boolean self; + while (true) { + int ws = i; + skipSpace(); + if (i >= n) { + throw DECLINE; + } + char c = s.charAt(i); + if (c == '>' || c == '/') { + self = c == '/'; + if (self && (i + 1 >= n || s.charAt(i + 1) != '>')) { + throw DECLINE; + } + i += self ? 2 : 1; + break; + } + if (i == ws) { + throw DECLINE; + } + int na = i; + int ne = nameEnd(na); + int as = (nameHash ^ nameHash >>> 16) & (TAG_CACHE - 1); + String an = attrRaw[as]; + if (!named(na, ne, an)) { + an = s.substring(na, ne); + attrRaw[as] = an; + attrExp[as] = null; + } + skipSpace(); + if (i >= n || s.charAt(i) != '=') { + throw DECLINE; + } + i++; + skipSpace(); + char qc = i < n ? s.charAt(i) : '\0'; + if (qc != '"' && qc != '\'') { + throw DECLINE; + } + int ve = s.indexOf(qc, i + 1); + if (ve < 0) { + throw DECLINE; + } + String av0 = s.substring(i + 1, ve); + boolean plain = av0.indexOf('<') < 0 && av0.indexOf('&') < 0 && av0.indexOf('\t') < 0 + && av0.indexOf('\n') < 0; + StringBuilder v = plain ? null : new StringBuilder(ve - i); + for (int k = plain ? ve : i + 1; k < ve;) { + char ch = s.charAt(k); + if (ch == '<') { + throw DECLINE; + } + if (ch == '&') { + k = ref(k, ve, v); + continue; + } + v.append(ch == '\t' || ch == '\n' ? ' ' : ch); + k++; + } + i = ve + 1; + if (names.contains(an) || declared != null && ("xmlns".equals(an) ? declared.containsKey("") + : an.startsWith("xmlns:") && declared.containsKey(an.substring(6)))) { + throw DECLINE; + } + String av = plain ? av0 : v.toString(); + if ("xmlns".equals(an) || an.startsWith("xmlns:")) { + String prefix = an.length() > 5 ? an.substring(6) : ""; + if (an.length() > 5 && prefix.length() == 0 || "xmlns".equals(prefix) || "xml".equals(prefix) + || XML_NS.equals(av) || XMLNS_NS.equals(av) + || prefix.length() > 0 && av.length() == 0 || prefix.indexOf(':') >= 0) { + throw DECLINE; + } + if (declared == null) { + // In document order: it becomes the element's nsmap. + declared = new java.util.LinkedHashMap(); + } + declared.put(prefix, av); + } else { + if (names.size() == attrSlots.length) { + attrSlots = java.util.Arrays.copyOf(attrSlots, attrSlots.length * 2); + } + attrSlots[names.size()] = attrRaw[as] == an ? as : -1; //NOPMD CompareObjectsWithEquals - the cached string itself + names.add(an); + values.add(av); + } + } + if (declared != null) { + scopes.add(declared); + scopeDepth.add(Integer.valueOf(open.size())); + java.util.Arrays.fill(rawNames, null); + java.util.Arrays.fill(attrExp, null); + } + String tag = rawNames[slot] == q ? tagNames[slot] : null; //NOPMD CompareObjectsWithEquals - the cached string itself + if (tag == null) { + tag = expand(q, true); + rawNames[slot] = q; + tagNames[slot] = tag; + } + PyDict attrib = new PyDict(); + for (int k = 0; k < names.size(); k++) { + int sl = attrSlots[k]; + String en = sl >= 0 && attrRaw[sl] == names.get(k) ? attrExp[sl] : null; //NOPMD CompareObjectsWithEquals - the cached string itself + if (en == null) { + en = expand(names.get(k), false); + if (sl >= 0 && attrRaw[sl] == names.get(k)) { //NOPMD CompareObjectsWithEquals - the cached string itself + attrExp[sl] = en; + } + } + if (attrib.getOrNull(en) != null) { + throw DECLINE; + } + attrib.setItem(en, values.get(k)); + } + if (lx != null) { + lxStart(tag, attrib, q, declared); + if (self) { + close(); + } + return; + } + flush(); + Object el; + if (direct) { + el = ((PyType) factory).newInstance(); + SET_TAG.set(el, tag); + SET_ATTRIB.set(el, attrib); + SET_CHILDREN.set(el, new PyList()); + } else { + el = Py.call(factory, tag, attrib); + } + if (!open.isEmpty()) { + Object kids = CHILDREN.get(open.get(open.size() - 1)); + if (!(kids instanceof PyList)) { + throw DECLINE; + } + ((PyList) kids).append(el); + } else { + root = el; + } + last = el; + tail = false; + open.add(el); + openNames.add(q); + if (self) { + close(); + } + } + + private void endTag() { + int qa = i + 2; + int qe = nameEnd(qa); + skipSpace(); + if (i >= n || s.charAt(i) != '>') { + throw DECLINE; + } + i++; + if (open.isEmpty() || !named(qa, qe, openNames.get(openNames.size() - 1))) { + throw DECLINE; + } + close(); + } + + /// `_XMLDriver.flush`: the text pending before a tag, given to the open + /// element as `_TreeSink.data` does, unless `remove_blank_text` drops + /// it. `end` is whether the tag that ends it is an end tag. + private void lxFlush(boolean end) { + if (data.length() == 0) { + return; + } + String text = data.toString(); + data.setLength(0); + if (open.isEmpty()) { + return; + } + int top = state.size() - 1; + int st = state.get(top).intValue(); + boolean hadChild = (st & 1) != 0; + if (lx.removeBlankText && blank(text)) { + if (!hadChild) { + if (!end) { + return; + } + } else if ((st & 2) == 0) { + return; + } + } + if (!hadChild) { + state.set(top, Integer.valueOf(st | 2)); + } + Object parent = open.get(open.size() - 1); + Object kids = KIDS.get(parent); + if (!(kids instanceof PyList)) { + throw DECLINE; + } + PyList k = (PyList) kids; + if (k.size() > 0) { + X_TAIL.set(k.get(k.size() - 1), text); + } else { + X_TEXT.set(parent, text); + } + } + + private boolean blank(String t) { + for (int k = 0; k < t.length(); k++) { + char c = t.charAt(k); + if (c != ' ' && c != '\t' && c != '\r' && c != '\n') { + return false; + } + } + return true; + } + + /// `_XMLDriver.on_start` and `_TreeSink.start`, with `_blank`'s + /// fields stored in its order, so an element has the layout the + /// Python path gives it. + private void lxStart(String tag, PyDict attrib, String q, java.util.HashMap declared) { + lxFlush(false); + if (!state.isEmpty()) { + int top = state.size() - 1; + state.set(top, Integer.valueOf(state.get(top).intValue() | 1)); + } + Object hint; + if (tag.length() > 0 && tag.charAt(0) == '{') { + int colon = q.indexOf(':'); + hint = colon < 0 ? Py.NONE : q.substring(0, colon); + } else { + hint = lx.noHint; + } + PyDict ns = new PyDict(); + if (declared != null) { + for (java.util.Map.Entry e : declared.entrySet()) { + if (e.getValue().length() > 0) { + ns.setItem(e.getKey().length() == 0 ? Py.NONE : e.getKey(), e.getValue()); + } + } + } + Object cls = lx.classFor(tag); + Object el = NEW.call1(cls, cls); + Object parent = open.isEmpty() ? null : open.get(open.size() - 1); + PyList kids = new PyList(); + if (!fastElement(el, tag, attrib, ns, kids, parent == null ? Py.NONE : parent, hint)) { + slowElement(el, tag, attrib, ns, kids, hint); + if (parent != null) { + X_PARENT.set(el, parent); + } + } + if (parent != null) { + Object pk = KIDS.get(parent); + if (!(pk instanceof PyList)) { + throw DECLINE; + } + ((PyList) pk).append(el); + } else { + root = el; + } + open.add(el); + openNames.add(q); + state.add(Integer.valueOf(0)); + Object init = Py.orDefault(INIT.getOrMiss(el), Py.NONE); + if (init != null && init != Py.NONE) { //NOPMD CompareObjectsWithEquals - None is a singleton + Py.call(init); + } + } + + /// The names `slowElement` stores, in its order. + private static final String[] ELEMENT_NAMES = {"_xkind", "_xtag", "_xattrib", "_xns", "_xkids", "_xparent", + "_xtext", "_xtail", "_xpfx", "_xlookup", "_xdoc", "_xtarget", "_xcnt"}; + + /// Element class -> the shape its instances have after + /// `slowElement`, learnt from the first one and good while no class + /// changed (`PyType.version`). Shared by every parse: shapes and + /// the version are global, and the program's threads parse one at a + /// time under the interpreter lock. + private static final java.util.HashMap elementShapes = new java.util.HashMap(); + private static int elementVersion = -1; + + /// Installs all of an element's attributes at once: the same values + /// `slowElement` stores, as the one shape every element of the class + /// ends with. Only for a plain instance with nothing set yet, of a + /// class whose first element was built the slow way. + private boolean fastElement(Object el, String tag, PyDict attrib, PyDict ns, PyList kids, Object parent, + Object hint) { + if (el == null || el.getClass() != PyInstance.class) { //NOPMD CompareObjectsWithEquals - exact class is meant + return false; + } + PyInstance i = (PyInstance) el; + if (i.shape().size() != 0 || i.base != null || i.nonStrKeys != null) { + return false; + } + Shape s = elementShape(i.cls); + if (s == null) { + slowElement(el, tag, attrib, ns, kids, hint); + X_PARENT.set(el, parent); + Shape got = i.shape(); + if (java.util.Arrays.equals(got.names, ELEMENT_NAMES)) { + learnShape(i.cls, got); + } + return true; + } + Object[] v = new Object[Math.max(ELEMENT_NAMES.length, i.cls.slotHint)]; + v[0] = "e"; + v[1] = tag; + v[2] = attrib; + v[3] = ns; + v[4] = kids; + v[5] = parent; + v[6] = Py.NONE; + v[7] = Py.NONE; + v[8] = hint; + v[9] = lx.lookup; + v[10] = Py.NONE; + v[11] = Py.NONE; + v[12] = lx.cnt; + i.slots = v; + i.shape = s; + // Attributes outside the compiled fields, as `PyInstance.extra` + // promises to every reader that skips a lookup on its word. + i.extra = true; + return true; + } + + private static Shape elementShape(PyType t) { + if (elementVersion != PyType.version) { + elementVersion = PyType.version; + elementShapes.clear(); + } + return elementShapes.get(t); + } + + private static void learnShape(PyType t, Shape s) { + if (elementVersion == PyType.version) { + elementShapes.put(t, s); + } + } + + private void slowElement(Object el, String tag, PyDict attrib, PyDict ns, PyList kids, Object hint) { + // The attributes in _Element.__init__'s order, which fixes the + // instance dict's order, each stored once with its final value: + // the defaults it then overwrote cost a store and, for the + // containers, an allocation each per element. + X_KIND.set(el, "e"); + X_TAG.set(el, tag); + X_ATTRIB.set(el, attrib); + X_NS.set(el, ns); + X_KIDS.set(el, kids); + X_PARENT.set(el, Py.NONE); + X_TEXT.set(el, Py.NONE); + X_TAIL.set(el, Py.NONE); + X_PFX.set(el, hint); + X_LOOKUP.set(el, lx.lookup); + X_DOC.set(el, Py.NONE); + X_TARGET.set(el, Py.NONE); + X_CNT.set(el, lx.cnt); + } + + private void close() { + if (lx != null) { + lxFlush(true); + state.remove(state.size() - 1); + } else { + flush(); + } + int depth = open.size() - 1; + last = open.remove(depth); + openNames.remove(depth); + tail = true; + if (scopeDepth.get(scopeDepth.size() - 1).intValue() == depth) { + scopes.remove(scopes.size() - 1); + scopeDepth.remove(scopeDepth.size() - 1); + java.util.Arrays.fill(rawNames, null); + java.util.Arrays.fill(attrExp, null); + } + } + } +} diff --git a/maven/python-runtime/third-party/unicode/LICENSE.txt b/maven/python-runtime/third-party/unicode/LICENSE.txt new file mode 100644 index 00000000000..56da5891280 --- /dev/null +++ b/maven/python-runtime/third-party/unicode/LICENSE.txt @@ -0,0 +1,39 @@ +UNICODE LICENSE V3 + +COPYRIGHT AND PERMISSION NOTICE + +Copyright © 1991-2026 Unicode, Inc. + +NOTICE TO USER: Carefully read the following legal agreement. BY +DOWNLOADING, INSTALLING, COPYING OR OTHERWISE USING DATA FILES, AND/OR +SOFTWARE, YOU UNEQUIVOCALLY ACCEPT, AND AGREE TO BE BOUND BY, ALL OF THE +TERMS AND CONDITIONS OF THIS AGREEMENT. IF YOU DO NOT AGREE, DO NOT +DOWNLOAD, INSTALL, COPY, DISTRIBUTE OR USE THE DATA FILES OR SOFTWARE. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of data files and any associated documentation (the "Data Files") or +software and any associated documentation (the "Software") to deal in the +Data Files or Software without restriction, including without limitation +the rights to use, copy, modify, merge, publish, distribute, and/or sell +copies of the Data Files or Software, and to permit persons to whom the +Data Files or Software are furnished to do so, provided that either (a) +this copyright and permission notice appear with all copies of the Data +Files or Software, or (b) this copyright and permission notice appear in +associated Documentation. + +THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY +KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF +THIRD PARTY RIGHTS. + +IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE +BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, +OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, +WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THE DATA +FILES OR SOFTWARE. + +Except as contained in this notice, the name of a copyright holder shall +not be used in advertising or otherwise to promote the sale, use or other +dealings in these Data Files or Software without prior written +authorization of the copyright holder. diff --git a/maven/python-runtime/tools/gen_unicode_tables.py b/maven/python-runtime/tools/gen_unicode_tables.py index 48f4a2848bf..7b1dc7fe4e9 100644 --- a/maven/python-runtime/tools/gen_unicode_tables.py +++ b/maven/python-runtime/tools/gen_unicode_tables.py @@ -93,8 +93,21 @@ def mapping(fn): return "".join(parts) +# str.isprintable() over every plane, which repr() escapes by: the code +# points where the answer changes, each as two chars (high, low 16 bits). +# U+0000 is not printable, so the first edge starts a printable run. +edges = [] +printable_prev = False +for cp in range(0x110000): + p = chr(cp).isprintable() + if p != printable_prev: + edges.append(cp) + printable_prev = p +printable_str = "".join(chr(e >> 16) + chr(e & 0xFFFF) for e in edges) + tables = { "FLAGS": flag_str, + "PRINTABLE": printable_str, "LOWER": mapping(str.lower), "UPPER": mapping(str.upper), "TITLE": mapping(str.title), @@ -106,13 +119,18 @@ def mapping(fn): header = f.read().split("package ", 1)[0] lines = [header.rstrip("\n"), "package com.codename1.python.runtime;", "", + "/// The tables are generated from the Unicode Character Database, licensed under", + "/// the Unicode License v3 (text in maven/python-runtime/third-party/unicode/LICENSE.txt).", + "///", "/// Generated by `maven/python-runtime/tools/gen_unicode_tables.py` from", "/// the Unicode %s data of CPython %d.%d; do not edit by hand." % (unicodedata.unidata_version, sys.version_info[0], sys.version_info[1]), "///", "/// `FLAGS` is runs of (first char, property bits) over the Basic", "/// Multilingual Plane; each mapping table is entries of (char, length,", - "/// mapped chars), in char order. [Unicode] decodes them.", + "/// mapped chars), in char order. `PRINTABLE` is the code points, over", + "/// every plane, where `str.isprintable()` changes, two chars each.", + "/// [Unicode] decodes them.", "final class UnicodeTables {", " private UnicodeTables() {", " }", ""] diff --git a/maven/python-transpiler/pom.xml b/maven/python-transpiler/pom.xml index 81c07f9fd82..daa47937660 100644 --- a/maven/python-transpiler/pom.xml +++ b/maven/python-transpiler/pom.xml @@ -48,6 +48,8 @@ true ${project.build.directory} ${project.basedir}/spotbugs-exclude.xml + + 1536 diff --git a/maven/python-transpiler/spotbugs-exclude.xml b/maven/python-transpiler/spotbugs-exclude.xml index 14ca316a137..18e6111df52 100644 --- a/maven/python-transpiler/spotbugs-exclude.xml +++ b/maven/python-transpiler/spotbugs-exclude.xml @@ -50,4 +50,23 @@ + + + + + + + + + + + + + + + diff --git a/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/analyze/Desugar.java b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/analyze/Desugar.java index 606b854d694..1e43a2f7eb3 100644 --- a/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/analyze/Desugar.java +++ b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/analyze/Desugar.java @@ -116,6 +116,8 @@ private void block(List body) { i += r.size() - 1; } else if (s instanceof Try && ((Try) s).star) { body.set(i, exceptStar((Try) s)); + } else if (s instanceof Try && nextOrStop((Try) s) != null) { + body.set(i, nextOrStop((Try) s)); } else if (inFunction && s instanceof AnnAssign && ((AnnAssign) s).value != null) { // CPython never evaluates the annotation of a function's // local (PEP 526), so `x: int = v` there is `x = v`; as a @@ -214,6 +216,84 @@ private List lower(Match m) { return out; } + /// `try: x = next(it) except StopIteration: H [else: E]` is how a loop + /// pulls from a generator by hand (bs4's filters do it per element). + /// Raising and catching a StopIteration per exhaustion costs an exception + /// object, its type's construction and a handler search, so it becomes + /// `$n = __cn1_next_or_stop__(next, it)` and an `is __cn1_stop__` test. + /// The intrinsic is handed the `next` the name resolves to, so a shadowed + /// `next` is still called (and a StopIteration it raises still caught). + /// A handler that names or re-raises the exception keeps the try. + private Stmt nextOrStop(Try t) { + if (t.star || !t.finalbody.isEmpty() || t.body.size() != 1 || t.handlers.size() != 1 + || !(t.body.get(0) instanceof Assign)) { + return null; + } + ExceptHandler h = t.handlers.get(0); + if (h.name != null || !(h.type instanceof Name) || !"StopIteration".equals(((Name) h.type).id) + || reraises(h.body)) { + return null; + } + Assign a = (Assign) t.body.get(0); + if (a.targets.size() != 1 || !(a.targets.get(0) instanceof Name) || !(a.value instanceof Call)) { + return null; + } + Call c = (Call) a.value; + if (!(c.func instanceof Name) || !"next".equals(((Name) c.func).id) || c.args.size() != 1 + || !c.keywords.isEmpty() || !(c.args.get(0) instanceof Name)) { + return null; + } + String v = "$n" + (++counter); + Call call = new Call(name("__cn1_next_or_stop__", t)).at(t.line, t.col); + call.args.add(c.func); + call.args.add(c.args.get(0)); + List out = new ArrayList(); + out.add(assign(name(v, t), call, t)); + Compare test = new Compare(name(v, t)).at(t.line, t.col); + test.ops.add("is"); + test.comparators.add(name("__cn1_stop__", t)); + List got = new ArrayList(); + got.add(assign(a.targets.get(0), name(v, t), a)); + got.addAll(t.orelse); + out.add(new If(test, h.body, got).at(t.line, t.col)); + return new If(new Constant(Constant.Kind.TRUE, null).at(t.line, t.col), out, new ArrayList()) + .at(t.line, t.col); + } + + /// Whether a handler body contains a bare `raise` anywhere. + private static boolean reraises(List body) { + boolean[] found = new boolean[1]; + scanRaise(body, found); + return found[0]; + } + + private static void scanRaise(List body, boolean[] found) { + for (Stmt s : body) { + if (s instanceof Raise && ((Raise) s).exc == null) { + found[0] = true; + } else if (s instanceof If) { + scanRaise(((If) s).body, found); + scanRaise(((If) s).orelse, found); + } else if (s instanceof While) { + scanRaise(((While) s).body, found); + scanRaise(((While) s).orelse, found); + } else if (s instanceof For) { + scanRaise(((For) s).body, found); + scanRaise(((For) s).orelse, found); + } else if (s instanceof With) { + scanRaise(((With) s).body, found); + } else if (s instanceof Try) { + Try t = (Try) s; + scanRaise(t.body, found); + for (ExceptHandler x : t.handlers) { + scanRaise(x.body, found); + } + scanRaise(t.orelse, found); + scanRaise(t.finalbody, found); + } + } + } + private Stmt exceptStar(Try t) { int n = ++counter; String x = "$x" + n; diff --git a/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/analyze/GenInline.java b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/analyze/GenInline.java new file mode 100644 index 00000000000..a2cc3d94160 --- /dev/null +++ b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/analyze/GenInline.java @@ -0,0 +1,843 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.python.transpiler.analyze; + +import com.codename1.python.transpiler.ast.Node; +import com.codename1.python.transpiler.ast.Node.Assert; +import com.codename1.python.transpiler.ast.Node.Assign; +import com.codename1.python.transpiler.ast.Node.Attribute; +import com.codename1.python.transpiler.ast.Node.AugAssign; +import com.codename1.python.transpiler.ast.Node.BinOp; +import com.codename1.python.transpiler.ast.Node.BoolOp; +import com.codename1.python.transpiler.ast.Node.Break; +import com.codename1.python.transpiler.ast.Node.Call; +import com.codename1.python.transpiler.ast.Node.ClassDef; +import com.codename1.python.transpiler.ast.Node.Comp; +import com.codename1.python.transpiler.ast.Node.Compare; +import com.codename1.python.transpiler.ast.Node.Comprehension; +import com.codename1.python.transpiler.ast.Node.Constant; +import com.codename1.python.transpiler.ast.Node.Continue; +import com.codename1.python.transpiler.ast.Node.Expr; +import com.codename1.python.transpiler.ast.Node.ExprStmt; +import com.codename1.python.transpiler.ast.Node.For; +import com.codename1.python.transpiler.ast.Node.FunctionDef; +import com.codename1.python.transpiler.ast.Node.Global; +import com.codename1.python.transpiler.ast.Node.If; +import com.codename1.python.transpiler.ast.Node.IfExp; +import com.codename1.python.transpiler.ast.Node.Keyword; +import com.codename1.python.transpiler.ast.Node.ListExpr; +import com.codename1.python.transpiler.ast.Node.Name; +import com.codename1.python.transpiler.ast.Node.Pass; +import com.codename1.python.transpiler.ast.Node.SetExpr; +import com.codename1.python.transpiler.ast.Node.Slice; +import com.codename1.python.transpiler.ast.Node.Starred; +import com.codename1.python.transpiler.ast.Node.Stmt; +import com.codename1.python.transpiler.ast.Node.Subscript; +import com.codename1.python.transpiler.ast.Node.TupleExpr; +import com.codename1.python.transpiler.ast.Node.UnaryOp; +import com.codename1.python.transpiler.ast.Node.While; +import com.codename1.python.transpiler.ast.Node.Yield; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Deque; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/// Inlines a generator into the loop that consumes it, before scope +/// analysis, the way a tracing JIT does: `for x in g(a)` becomes the body of +/// `g` with its locals renamed apart and its `yield e` replaced by `x = e` +/// followed by the loop body. No generator object is made, nothing is +/// suspended, and the inlined locals are typed like any other. +/// +/// The interleaving of the two bodies is exactly the generator's: `g` runs +/// up to its yield, the loop body runs, `g` resumes. It is only done where +/// nothing could tell the difference: +/// +/// - `g` is a plain function at module level, bound by its `def` alone, +/// with positional parameters only and exactly one `yield`, which is a +/// statement of its own, so the loop body is not copied. It has no +/// `return`, `try`, `with`, `del`, `global`, `yield from`, nested scope or +/// anything the copy below does not know. +/// - The loop has no `else`, its target is a name, and its body has no +/// `break` or `continue` of its own: those would have to leave `g`'s loops. +/// - No name `g` reads from the module is bound by the consuming function or +/// one enclosing it, where the inlined read would land instead. +/// +/// One difference remains, deliberately: a `StopIteration` raised inside a +/// call `g` makes is a `RuntimeError` out of a real generator (PEP 479) and +/// stays a `StopIteration` here. It is an error in the program either way. +/// +/// `n = sum(e for x in it if c)` is first written as a list built by a loop +/// and summed, which is how the typed code already treats it (see +/// `TypedEmit.EAGER`), so that its loop can be inlined too. +public final class GenInline { + /// How deep an inlined body is inlined into again. + private static final int DEPTH = 3; + + private final Map gens = new HashMap(); + private final Set moduleBound = new HashSet(); + private int counter; + + private GenInline() { + } + + public static void rewrite(List module) { + GenInline g = new GenInline(); + Map defs = new HashMap(); + for (Stmt s : module) { + g.bound(s, g.moduleBound); + if (s instanceof FunctionDef) { + String n = ((FunctionDef) s).name; + defs.put(n, defs.containsKey(n) ? 2 : 1); + } + } + Set declaredGlobal = new HashSet(); + for (Stmt s : module) { + globalsIn(s, declaredGlobal); + } + Map stores = new HashMap(); + for (Stmt s : module) { + Set one = new HashSet(); + g.bound(s, one); + for (String n : one) { + stores.merge(n, 1, Integer::sum); + } + } + for (Stmt s : module) { + if (s instanceof FunctionDef) { + FunctionDef d = (FunctionDef) s; + if (defs.get(d.name) == 1 && stores.get(d.name) == 1 && !declaredGlobal.contains(d.name) + && candidate(d)) { + g.gens.put(d.name, d); + } + } + } + boolean sumFree = !g.moduleBound.contains("sum") && !declaredGlobal.contains("sum") + && !g.moduleBound.contains("*"); + for (Stmt s : module) { + g.scopes(s, new ArrayDeque>(), sumFree); + } + } + + // ---- which functions qualify ---------------------------------------- + + private static boolean candidate(FunctionDef d) { + Node.Arguments a = d.args; + if (d.isAsync || !d.decorators.isEmpty() || a.vararg != null || a.kwarg != null || !a.kwonly.isEmpty() + || !a.defaults.isEmpty() || a.positionalOnly > 0) { + return false; + } + int[] yields = {0}; + if (!plainStmts(d.body, yields)) { + return false; + } + return yields[0] == 1; + } + + /// Statements the copy knows, with every yield one of them. + private static boolean plainStmts(List body, int[] yields) { + for (Stmt s : body) { + if (!plainStmt(s, yields)) { + return false; + } + } + return true; + } + + private static boolean plainStmt(Stmt s, int[] yields) { + if (s instanceof ExprStmt && ((ExprStmt) s).value instanceof Yield) { + Yield y = (Yield) ((ExprStmt) s).value; + yields[0]++; + return !y.from && (y.value == null || plainExpr(y.value)); + } + if (s instanceof ExprStmt) { + return plainExpr(((ExprStmt) s).value); + } + if (s instanceof Assign) { + for (Expr t : ((Assign) s).targets) { + if (!plainTarget(t)) { + return false; + } + } + return plainExpr(((Assign) s).value); + } + if (s instanceof AugAssign) { + return plainTarget(((AugAssign) s).target) && plainExpr(((AugAssign) s).value); + } + if (s instanceof Pass || s instanceof Break || s instanceof Continue) { + return true; + } + if (s instanceof Assert) { + return plainExpr(((Assert) s).test) && (((Assert) s).msg == null || plainExpr(((Assert) s).msg)); + } + if (s instanceof If) { + If i = (If) s; + return plainExpr(i.test) && plainStmts(i.body, yields) && plainStmts(i.orelse, yields); + } + if (s instanceof While) { + While w = (While) s; + return plainExpr(w.test) && plainStmts(w.body, yields) && plainStmts(w.orelse, yields); + } + if (s instanceof For) { + For f = (For) s; + return !f.isAsync && plainTarget(f.target) && plainExpr(f.iter) && plainStmts(f.body, yields) + && plainStmts(f.orelse, yields); + } + return false; + } + + private static boolean plainTarget(Expr t) { + if (t instanceof Name) { + return true; + } + if (t instanceof TupleExpr || t instanceof ListExpr) { + for (Expr e : elts(t)) { + if (!plainTarget(e)) { + return false; + } + } + return true; + } + if (t instanceof Starred) { + return plainTarget(((Starred) t).value); + } + return (t instanceof Attribute || t instanceof Subscript) && plainExpr(t); + } + + /// Expressions the copy knows: no nested scope, no yield, no walrus. + public static boolean plainExpr(Expr e) { + if (e == null || e instanceof Name || e instanceof Constant) { + return true; + } + if (e instanceof Attribute) { + return plainExpr(((Attribute) e).value); + } + if (e instanceof Subscript) { + return plainExpr(((Subscript) e).value) && plainExpr(((Subscript) e).index); + } + if (e instanceof Slice) { + Slice s = (Slice) e; + return plainExpr(s.lower) && plainExpr(s.upper) && plainExpr(s.step); + } + if (e instanceof Starred) { + return plainExpr(((Starred) e).value); + } + if (e instanceof BinOp) { + return plainExpr(((BinOp) e).left) && plainExpr(((BinOp) e).right); + } + if (e instanceof UnaryOp) { + return plainExpr(((UnaryOp) e).operand); + } + if (e instanceof BoolOp) { + return allPlain(((BoolOp) e).values); + } + if (e instanceof Compare) { + return plainExpr(((Compare) e).left) && allPlain(((Compare) e).comparators); + } + if (e instanceof IfExp) { + IfExp i = (IfExp) e; + return plainExpr(i.test) && plainExpr(i.body) && plainExpr(i.orelse); + } + if (e instanceof Call) { + Call c = (Call) e; + if (!plainExpr(c.func) || !allPlain(c.args)) { + return false; + } + for (Keyword k : c.keywords) { + if (!plainExpr(k.value)) { + return false; + } + } + return true; + } + if (e instanceof ListExpr || e instanceof TupleExpr || e instanceof SetExpr) { + return allPlain(elts(e)); + } + return false; + } + + private static boolean allPlain(List es) { + for (Expr x : es) { + if (!plainExpr(x)) { + return false; + } + } + return true; + } + + private static List elts(Expr e) { + if (e instanceof ListExpr) { + return ((ListExpr) e).elts; + } + if (e instanceof TupleExpr) { + return ((TupleExpr) e).elts; + } + return ((SetExpr) e).elts; + } + + // ---- names -------------------------------------------------------------- + + /// Adds every name `s` binds in its own scope (`*` for a star import), + /// without entering nested scopes beyond their own name. + private static void bound(Node s, Set out) { + if (s instanceof FunctionDef) { + out.add(((FunctionDef) s).name); + return; + } + if (s instanceof ClassDef) { + out.add(((ClassDef) s).name); + return; + } + if (s instanceof Node.Lambda || s instanceof Comp) { + if (s instanceof Comp) { + // The first iterable is evaluated in the enclosing scope. + bound(((Comp) s).generators.get(0).iter, out); + } + return; + } + if (s instanceof Assign) { + for (Expr t : ((Assign) s).targets) { + targetNames(t, out); + } + } else if (s instanceof AugAssign) { + targetNames(((AugAssign) s).target, out); + } else if (s instanceof Node.AnnAssign) { + targetNames(((Node.AnnAssign) s).target, out); + } else if (s instanceof For) { + targetNames(((For) s).target, out); + } else if (s instanceof Node.WithItem && ((Node.WithItem) s).vars != null) { + targetNames(((Node.WithItem) s).vars, out); + } else if (s instanceof Node.ExceptHandler && ((Node.ExceptHandler) s).name != null) { + out.add(((Node.ExceptHandler) s).name); + } else if (s instanceof Node.Import) { + for (Node.Alias a : ((Node.Import) s).names) { + String n = a.asname != null ? a.asname : a.name; + int dot = n.indexOf('.'); + out.add(dot < 0 ? n : n.substring(0, dot)); + } + } else if (s instanceof Node.ImportFrom) { + for (Node.Alias a : ((Node.ImportFrom) s).names) { + out.add(a.asname != null ? a.asname : a.name); + } + } else if (s instanceof Node.NamedExpr) { + out.add(((Node.NamedExpr) s).target.id); + } else if (s instanceof Node.Delete) { + for (Expr t : ((Node.Delete) s).targets) { + targetNames(t, out); + } + } else if (s instanceof Global) { + out.addAll(((Global) s).names); + } + final Set o = out; + children(s, x -> bound(x, o)); + } + + private static void targetNames(Expr t, Set out) { + if (t instanceof Name) { + out.add(((Name) t).id); + } else if (t instanceof TupleExpr || t instanceof ListExpr) { + for (Expr e : elts(t)) { + targetNames(e, out); + } + } else if (t instanceof Starred) { + targetNames(((Starred) t).value, out); + } + } + + private static void globalsIn(Node s, Set out) { + if (s instanceof Global && !((Global) s).nonlocal) { + out.addAll(((Global) s).names); + } + children(s, x -> globalsIn(x, out)); + } + + /// Every name `o` reads or writes, nested scopes included. + private static void names(Node o, Set out) { + if (o instanceof Name) { + out.add(((Name) o).id); + } + children(o, x -> names(x, out)); + } + + // ---- the walk ------------------------------------------------------------- + + /// Rewrites the functions in `s`; `enclosing` holds what each enclosing + /// function binds, innermost last. + private void scopes(Node s, Deque> enclosing, boolean sumFree) { + if (s instanceof FunctionDef) { + FunctionDef d = (FunctionDef) s; + Set mine = new HashSet(d.args.names()); + for (Stmt x : d.body) { + bound(x, mine); + } + enclosing.addLast(mine); + if (sumFree) { + sums(d.body, mine); + } + inline(d.body, enclosing, d.name, 0); + for (Stmt x : d.body) { + scopes(x, enclosing, sumFree); + } + enclosing.removeLast(); + return; + } + if (s instanceof ClassDef) { + for (Stmt x : ((ClassDef) s).body) { + scopes(x, enclosing, sumFree); + } + return; + } + children(s, x -> { + if (x instanceof Stmt) { + scopes(x, enclosing, sumFree); + } + }); + } + + /// `n = sum(e for x in it if c)` in `body` (and its nested blocks) as + /// `t = []`, a loop appending `e`, and `n = sum(t)`. + private void sums(List body, Set mine) { + for (int i = 0; i < body.size(); i++) { + Stmt s = body.get(i); + List out = sumLoop(s, mine); + if (out != null) { + body.remove(i); + body.addAll(i, out); + i += out.size() - 1; + continue; + } + for (List b : blocks(s)) { + sums(b, mine); + } + } + } + + private List sumLoop(Stmt s, Set mine) { + Expr v; + if (s instanceof Assign && ((Assign) s).targets.size() == 1 && ((Assign) s).targets.get(0) instanceof Name) { + v = ((Assign) s).value; + } else if (s instanceof AugAssign && ((AugAssign) s).target instanceof Name) { + v = ((AugAssign) s).value; + } else { + return null; + } + if (!(v instanceof Call)) { + return null; + } + Call c = (Call) v; + if (!(c.func instanceof Name) || !"sum".equals(((Name) c.func).id) || mine.contains("sum") + || c.args.size() != 1 || !c.keywords.isEmpty() || !(c.args.get(0) instanceof Comp)) { + return null; + } + Comp g = (Comp) c.args.get(0); + if (g.kind != Comp.Kind.GENERATOR || g.generators.size() != 1) { + return null; + } + Comprehension q = g.generators.get(0); + if (q.isAsync || !(q.target instanceof Name) || !plainExpr(g.elt) || !plainExpr(q.iter) || !allPlain(q.ifs)) { + return null; + } + int k = ++counter; + String list = "$sum" + k; + Map ren = new HashMap(); + ren.put(((Name) q.target).id, "$sum" + k + "$" + ((Name) q.target).id); + Copy cp = new Copy(ren); + Call app = new Call(new Attribute(new Name(list).at(s.line, s.col), "append").at(s.line, s.col)) + .at(s.line, s.col); + app.args.add(cp.expr(g.elt)); + List inner = new ArrayList(); + inner.add(new ExprStmt(app).at(s.line, s.col)); + for (int i = q.ifs.size() - 1; i >= 0; i--) { + List wrapped = new ArrayList(); + wrapped.add(new If(cp.expr(q.ifs.get(i)), inner, new ArrayList()).at(s.line, s.col)); + inner = wrapped; + } + List out = new ArrayList(); + List lt = new ArrayList(); + lt.add(new Name(list).at(s.line, s.col)); + out.add(new Assign(lt, new ListExpr(new ArrayList()).at(s.line, s.col)).at(s.line, s.col)); + out.add(new For(cp.expr(q.target), q.iter, inner, new ArrayList(), false).at(s.line, s.col)); + Call sum = new Call(c.func).at(c.line, c.col); + sum.args.add(new Name(list).at(s.line, s.col)); + if (s instanceof Assign) { + out.add(new Assign(((Assign) s).targets, sum).at(s.line, s.col)); + } else { + out.add(new AugAssign(((AugAssign) s).target, ((AugAssign) s).op, sum).at(s.line, s.col)); + } + mine.add(list); + mine.add(ren.values().iterator().next()); + return out; + } + + /// Inlines every qualifying loop in `body`, its nested blocks included. + private void inline(List body, Deque> enclosing, String self, int depth) { + for (int i = 0; i < body.size(); i++) { + Stmt s = body.get(i); + List out = s instanceof For ? inlineLoop((For) s, enclosing, self) : null; + if (out != null) { + body.remove(i); + body.addAll(i, out); + if (depth + 1 < DEPTH) { + // The inlined body may itself loop over a generator. + List again = new ArrayList(out); + inline(again, enclosing, self, depth + 1); + body.subList(i, i + out.size()).clear(); + body.addAll(i, again); + i += again.size() - 1; + } else { + i += out.size() - 1; + } + continue; + } + for (List b : blocks(s)) { + inline(b, enclosing, self, depth); + } + } + } + + private List inlineLoop(For f, Deque> enclosing, String self) { + if (f.isAsync || !f.orelse.isEmpty() || !(f.target instanceof Name) || !(f.iter instanceof Call)) { + return null; + } + Call c = (Call) f.iter; + if (!(c.func instanceof Name) || !c.keywords.isEmpty()) { + return null; + } + FunctionDef g = gens.get(((Name) c.func).id); + if (g == null || g.name.equals(self) || c.args.size() != g.args.positional.size()) { + return null; + } + for (Expr a : c.args) { + if (a instanceof Starred) { + return null; + } + } + for (Set b : enclosing) { + if (b.contains(g.name)) { + return null; + } + } + if (leaves(f.body)) { + return null; + } + Set local = new HashSet(g.args.names()); + for (Stmt x : g.body) { + bound(x, local); + } + Set used = new HashSet(); + for (Stmt x : g.body) { + names(x, used); + } + used.removeAll(local); + for (Set b : enclosing) { + for (String n : used) { + if (b.contains(n)) { + return null; + } + } + } + int k = ++counter; + Map ren = new LinkedHashMap(); + for (String n : local) { + ren.put(n, g.name + "$" + k + "$" + n); + } + Copy cp = new Copy(ren); + cp.target = f.target; + cp.loopBody = f.body; + List out = new ArrayList(); + List params = g.args.names(); + // A parameter whose one use is the iterable of the body's first + // loop takes the argument itself there, so that loop can be inlined + // in its turn; the other arguments must be names or constants, so + // that evaluating it there instead reorders nothing observable. + int sub = substitutable(g, c); + for (int i = 0; i < params.size(); i++) { + if (i == sub) { + cp.subst.put(params.get(i), c.args.get(i)); + continue; + } + List t = new ArrayList(); + t.add(new Name(ren.get(params.get(i))).at(f.line, f.col)); + out.add(new Assign(t, c.args.get(i)).at(f.line, f.col)); + } + out.addAll(cp.stmts(g.body)); + Set innermost = enclosing.peekLast(); + if (innermost != null) { + innermost.addAll(ren.values()); + } + return out; + } + + private static int substitutable(FunctionDef g, Call c) { + if (g.body.isEmpty() || !(g.body.get(0) instanceof For) || !(((For) g.body.get(0)).iter instanceof Name)) { + return -1; + } + String p = ((Name) ((For) g.body.get(0)).iter).id; + int i = g.args.names().indexOf(p); + if (i < 0) { + return -1; + } + Set all = new HashSet(); + int[] uses = {0}; + for (Stmt x : g.body) { + count(x, p, uses); + bound(x, all); + } + if (uses[0] != 1 || all.contains(p)) { + return -1; + } + for (int j = 0; j < c.args.size(); j++) { + Expr a = c.args.get(j); + if (j != i && !(a instanceof Name || a instanceof Constant)) { + return -1; + } + } + return i; + } + + private static void count(Node o, String n, int[] uses) { + if (o instanceof Name && ((Name) o).id.equals(n)) { + uses[0]++; + } + children(o, x -> count(x, n, uses)); + } + + /// Whether `body` has a `break` or `continue` of its own loop. + private static boolean leaves(List body) { + for (Stmt s : body) { + if (s instanceof Break || s instanceof Continue) { + return true; + } + if (s instanceof For || s instanceof While) { + List orelse = s instanceof For ? ((For) s).orelse : ((While) s).orelse; + if (leaves(orelse)) { + return true; + } + continue; + } + if (s instanceof FunctionDef || s instanceof ClassDef) { + continue; + } + for (List b : blocks(s)) { + if (leaves(b)) { + return true; + } + } + } + return false; + } + + /// The statement lists directly inside `s`. + private static List> blocks(Stmt s) { + List> r = new ArrayList>(); + if (s instanceof If) { + r.add(((If) s).body); + r.add(((If) s).orelse); + } else if (s instanceof While) { + r.add(((While) s).body); + r.add(((While) s).orelse); + } else if (s instanceof For) { + r.add(((For) s).body); + r.add(((For) s).orelse); + } else if (s instanceof Node.With) { + r.add(((Node.With) s).body); + } else if (s instanceof Node.Try) { + Node.Try t = (Node.Try) s; + r.add(t.body); + for (Node.ExceptHandler h : t.handlers) { + r.add(h.body); + } + r.add(t.orelse); + r.add(t.finalbody); + } + return r; + } + + /// Calls `v` for every AST node directly under `o`. + private static void children(Node o, Visit v) { + for (Class c = o.getClass(); c != null && c != Object.class; c = c.getSuperclass()) { + for (java.lang.reflect.Field f : c.getDeclaredFields()) { + if (java.lang.reflect.Modifier.isStatic(f.getModifiers())) { + continue; + } + Class t = f.getType(); + if (!Node.class.isAssignableFrom(t) && !List.class.isAssignableFrom(t)) { + continue; + } + Object x; + try { + x = f.get(o); + } catch (IllegalAccessException e) { + throw new IllegalStateException(e); + } + if (x instanceof List) { + for (Object y : (List) x) { + if (y instanceof Node) { + v.on((Node) y); + } + } + } else if (x instanceof Node) { + v.on((Node) x); + } + } + } + } + + private interface Visit { + void on(Node n); + } + + // ---- the copy ------------------------------------------------------------- + + /// A copy of a generator body with its locals renamed, its yield + /// replaced by the loop's target assignment and body, and a substituted + /// parameter replaced by its argument. + private static final class Copy { + private final Map ren; + final Map subst = new HashMap(); + Expr target; + List loopBody; + + Copy(Map ren) { + this.ren = ren; + } + + List stmts(List in) { + List out = new ArrayList(); + for (Stmt s : in) { + if (s instanceof ExprStmt && ((ExprStmt) s).value instanceof Yield) { + Yield y = (Yield) ((ExprStmt) s).value; + List t = new ArrayList(); + t.add(target); + Expr v = y.value != null ? expr(y.value) + : new Constant(Constant.Kind.NONE, "None").at(s.line, s.col); + out.add(new Assign(t, v).at(s.line, s.col)); + out.addAll(loopBody); + continue; + } + out.add(stmt(s)); + } + return out; + } + + private Stmt stmt(Stmt s) { + Stmt r; + if (s instanceof ExprStmt) { + r = new ExprStmt(expr(((ExprStmt) s).value)); + } else if (s instanceof Assign) { + r = new Assign(exprs(((Assign) s).targets), expr(((Assign) s).value)); + } else if (s instanceof AugAssign) { + AugAssign a = (AugAssign) s; + r = new AugAssign(expr(a.target), a.op, expr(a.value)); + } else if (s instanceof Pass) { + r = new Pass(); + } else if (s instanceof Break) { + r = new Break(); + } else if (s instanceof Continue) { + r = new Continue(); + } else if (s instanceof Assert) { + r = new Assert(expr(((Assert) s).test), expr(((Assert) s).msg)); + } else if (s instanceof If) { + If i = (If) s; + r = new If(expr(i.test), stmts(i.body), stmts(i.orelse)); + } else if (s instanceof While) { + While w = (While) s; + r = new While(expr(w.test), stmts(w.body), stmts(w.orelse)); + } else { + For f = (For) s; + r = new For(expr(f.target), expr(f.iter), stmts(f.body), stmts(f.orelse), false); + } + return r.at(s.line, s.col); + } + + private List exprs(List in) { + List out = new ArrayList(); + for (Expr e : in) { + out.add(expr(e)); + } + return out; + } + + Expr expr(Expr e) { + if (e == null) { + return null; + } + Expr r; + if (e instanceof Name) { + String n = ((Name) e).id; + Expr s = subst.get(n); + if (s != null) { + return s; + } + String m = ren.get(n); + r = new Name(m != null ? m : n); + } else if (e instanceof Constant) { + r = new Constant(((Constant) e).kind, ((Constant) e).text); + } else if (e instanceof Attribute) { + r = new Attribute(expr(((Attribute) e).value), ((Attribute) e).attr); + } else if (e instanceof Subscript) { + r = new Subscript(expr(((Subscript) e).value), expr(((Subscript) e).index)); + } else if (e instanceof Slice) { + Slice s = (Slice) e; + r = new Slice(expr(s.lower), expr(s.upper), expr(s.step)); + } else if (e instanceof Starred) { + r = new Starred(expr(((Starred) e).value)); + } else if (e instanceof BinOp) { + BinOp b = (BinOp) e; + r = new BinOp(expr(b.left), b.op, expr(b.right)); + } else if (e instanceof UnaryOp) { + r = new UnaryOp(((UnaryOp) e).op, expr(((UnaryOp) e).operand)); + } else if (e instanceof BoolOp) { + r = new BoolOp(((BoolOp) e).isAnd, exprs(((BoolOp) e).values)); + } else if (e instanceof Compare) { + Compare c = (Compare) e; + Compare n = new Compare(expr(c.left)); + n.ops.addAll(c.ops); + n.comparators.addAll(exprs(c.comparators)); + r = n; + } else if (e instanceof IfExp) { + IfExp i = (IfExp) e; + r = new IfExp(expr(i.test), expr(i.body), expr(i.orelse)); + } else if (e instanceof Call) { + Call c = (Call) e; + Call n = new Call(expr(c.func)); + n.args.addAll(exprs(c.args)); + for (Keyword k : c.keywords) { + n.keywords.add(new Keyword(k.arg, expr(k.value)).at(k.line, k.col)); + } + r = n; + } else if (e instanceof ListExpr) { + r = new ListExpr(exprs(((ListExpr) e).elts)); + } else if (e instanceof TupleExpr) { + r = new TupleExpr(exprs(((TupleExpr) e).elts)); + } else { + r = new SetExpr(exprs(((SetExpr) e).elts)); + } + return r.at(e.line, e.col); + } + } +} diff --git a/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/analyze/ScopeBuilder.java b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/analyze/ScopeBuilder.java index 6405dbe6195..ca82b2e674c 100644 --- a/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/analyze/ScopeBuilder.java +++ b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/analyze/ScopeBuilder.java @@ -51,6 +51,7 @@ public static Scope build(Node.Module m, String file) { b.all.add(s); b.cur = s; Desugar.rewrite(m.body); + GenInline.rewrite(m.body); b.stmts(m.body); b.resolveCells(); return s; @@ -434,6 +435,7 @@ private void expr(Expr e) { // The first iterable is evaluated in the enclosing scope. expr(c.generators.get(0).iter); c.scope = push(Scope.Kind.COMPREHENSION, ""); + c.scope.comp = c; for (int i = 0; i < c.generators.size(); i++) { Comprehension g = c.generators.get(i); if (i > 0) { diff --git a/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/api/Main.java b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/api/Main.java index 3217148b305..16d29872d6f 100644 --- a/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/api/Main.java +++ b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/api/Main.java @@ -74,30 +74,45 @@ public static void main(String[] args) throws IOException { System.arraycopy(args, 2, rest, 0, rest.length); args = rest; } + // -packages: a second source root holding PyPI packages, translated + // with the application and with the same rules. + Path packages = null; + if (args.length >= 2 && "-packages".equals(args[0])) { + packages = Paths.get(args[1]); + String[] rest = new String[args.length - 2]; + System.arraycopy(args, 2, rest, 0, rest.length); + args = rest; + } if (args.length < 2 || args.length > 3) { - System.err.println("usage: Main [-cp ] [-vtstack ] [main module]"); + System.err.println("usage: Main [-cp ] [-vtstack ] [-packages ] " + + " [main module]"); System.exit(2); return; } - Path root = Paths.get(args[0]); Map sources = new TreeMap(); - List files; - try (Stream s = Files.walk(root)) { - files = s.filter(p -> p.toString().endsWith(".py")).collect(Collectors.toCollection(ArrayList::new)); - } - for (Path p : files) { - sources.put(root.relativize(p).toString().replace(File.separatorChar, '/'), - new String(Files.readAllBytes(p), StandardCharsets.UTF_8)); + readSources(Paths.get(args[0]), sources); + java.util.Set libraries = new java.util.TreeSet(); + if (packages != null) { + Map vendored = new TreeMap(); + readSources(packages, vendored); + libraries.addAll(vendored.keySet()); + libraries.removeAll(sources.keySet()); + vendored.putAll(sources); + sources = vendored; } Map out; + List deferred = new ArrayList(); try { out = PythonTranspiler.transpile(sources, args.length == 3 ? args[2] : null, classPath, - java.util.Collections.emptyMap(), stack); + java.util.Collections.emptyMap(), stack, libraries, deferred); } catch (PythonSyntaxError e) { System.err.println(e.getMessage()); System.exit(1); return; } + for (String d : deferred) { + System.err.println("note: " + d); + } for (Map.Entry e : out.entrySet()) { Path f = Paths.get(args[1], e.getKey()).toAbsolutePath(); Path dir = f.getParent(); @@ -107,4 +122,22 @@ public static void main(String[] args) throws IOException { Files.write(f, e.getValue().getBytes(StandardCharsets.US_ASCII)); } } + + private static void readSources(Path root, Map sources) throws IOException { + List files; + try (Stream s = Files.walk(root)) { + // The build directives sit at the root, beside the modules. + // Template files too: jinja2's loaders read them, and the build + // lexes them (Jinja2Lowering). + files = s.filter(p -> p.toString().endsWith(".py") + || p.equals(root.resolve("cn1-python.properties")) + || com.codename1.python.transpiler.codegen.Jinja2Lowering.isTemplateFile( + root.relativize(p).toString().replace(File.separatorChar, '/'))) + .collect(Collectors.toCollection(ArrayList::new)); + } + for (Path p : files) { + sources.put(root.relativize(p).toString().replace(File.separatorChar, '/'), + new String(Files.readAllBytes(p), StandardCharsets.UTF_8)); + } + } } diff --git a/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/api/PythonTranspiler.java b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/api/PythonTranspiler.java index bc6c7e57cf9..d64ae5bb61b 100644 --- a/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/api/PythonTranspiler.java +++ b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/api/PythonTranspiler.java @@ -26,7 +26,7 @@ import com.codename1.python.transpiler.analyze.ScopeBuilder; import com.codename1.python.transpiler.ast.Node; import com.codename1.python.transpiler.ast.Scope; -import com.codename1.python.transpiler.codegen.Closed; +import com.codename1.python.transpiler.codegen.WholeProgram; import com.codename1.python.transpiler.codegen.Emitter; import com.codename1.python.transpiler.parser.Parser; @@ -164,32 +164,175 @@ public static int parseStackSize(String raw) { /// size, so `CN1_HTTP_VT_STACK` can still ask for more at start-up public static Map transpile(Map sources, String mainModule, List classPath, Map nativeModules, int virtualThreadStack) { + return transpile(sources, mainModule, classPath, nativeModules, virtualThreadStack, + java.util.Collections.emptySet(), null); + } + + /// @param libraries the source paths that came from PyPI rather than the + /// application. They are compiled as the application's own: + /// code that cannot be translated (`eval`, `exec`, `__import__`, + /// the `sys` frame hooks) fails the build wherever the program + /// reaches it, with the `cn1-python.properties` line that removes + /// or replaces the function it is in. The one difference is + /// `compile`, a build error in the application and, in a package, + /// an object that holds nothing to run + /// @param deferred receives `module:line: what` for each place where + /// reached code stores an attribute under a computed name on an + /// object of no known class, which costs the typed fields of + /// every class such an object may be; may be null + public static Map transpile(Map sources, String mainModule, + List classPath, Map nativeModules, int virtualThreadStack, + Set libraries, List deferred) { if (virtualThreadStack <= 0) { throw new IllegalArgumentException("virtual thread stack must be positive: " + virtualThreadStack); } Map out = new LinkedHashMap(); Map classes = new LinkedHashMap(); Map trees = new LinkedHashMap(); - List> bodies = new ArrayList>(); + Map treeSources = new LinkedHashMap(); + String distributions = sources.get("_cn1_distributions.py"); + if (distributions != null && !sources.containsKey(com.codename1.python.transpiler.codegen.EntryPointTable.PATH)) { + // The entry points' targets as literal imports, for + // EntryPoint.load (EntryPointTable). + Set modules = new HashSet(); + for (String p : sources.keySet()) { + if (p.endsWith(".py")) { + modules.add(moduleOf(p.replace('\\', '/'))); + } + } + sources.put(com.codename1.python.transpiler.codegen.EntryPointTable.PATH, + com.codename1.python.transpiler.codegen.EntryPointTable.source( + Parser.parse(distributions, "_cn1_distributions.py"), modules)); + } for (Map.Entry e : sources.entrySet()) { String path = e.getKey().replace('\\', '/'); - if (path.endsWith(".py")) { + if (path.endsWith(".py") + && !path.startsWith(com.codename1.python.transpiler.codegen.Directives.OVERRIDES + "/")) { + // An override body is part of the function it overrides + // (Directives), never a module of its own. Node.Module tree = Parser.parse(e.getValue(), path); + com.codename1.python.transpiler.codegen.KnownHelpers.rewrite(tree, path); + com.codename1.python.transpiler.codegen.ConstantDefaults.rewrite(tree); + com.codename1.python.transpiler.codegen.ProtocolChecks.rewrite(tree, path); + com.codename1.python.transpiler.codegen.ClassDecoratorLowering.rewrite(tree, path); + com.codename1.python.transpiler.codegen.DataclassInit.rewrite(tree, path); + com.codename1.python.transpiler.codegen.AttrsLowering.rewrite(tree, path); + com.codename1.python.transpiler.codegen.CobbleLowering.rewrite(tree, path); + com.codename1.python.transpiler.codegen.NamedTupleLowering.rewrite(tree, path); + com.codename1.python.transpiler.codegen.PydanticLowering.rewrite(tree, path); + com.codename1.python.transpiler.codegen.SqlAlchemyLowering.rewrite(tree, path); + com.codename1.python.transpiler.codegen.ArgparseLowering.rewrite(tree, path); + com.codename1.python.transpiler.codegen.PytestLowering.rewrite(tree, path); trees.put(path, tree); - bodies.add(tree.body); + treeSources.put(path, e.getValue()); } } - boolean closed = Closed.check(bodies); + // threading.local objects used by literal names only become a + // per-thread slot class (ThreadLocalLowering). + com.codename1.python.transpiler.codegen.ThreadLocalLowering.rewrite(trees); + // flask's request/g/session/current_app proxies get one literal + // forwarding property per name the program uses (FlaskProxyLowering). + String flaskProxies = com.codename1.python.transpiler.codegen.FlaskProxyLowering.rewrite(trees); + if (flaskProxies != null) { + String fp = com.codename1.python.transpiler.codegen.FlaskProxyLowering.PATH; + trees.put(fp, Parser.parse(flaskProxies, fp)); + treeSources.put(fp, flaskProxies); + sources.put(fp, flaskProxies); + } + // jinja2 reads a template's attributes through one literal accessor + // per site, generated from the program's literal templates + // (Jinja2Lowering). + String jinjaTables = com.codename1.python.transpiler.codegen.Jinja2Lowering.rewrite(trees, sources); + if (jinjaTables != null) { + String jp = com.codename1.python.transpiler.codegen.Jinja2Lowering.PATH; + trees.put(jp, Parser.parse(jinjaTables, jp)); + treeSources.put(jp, jinjaTables); + sources.put(jp, jinjaTables); + } + // Whole program: class bases Python computes at import time but the + // closed program settles (BuildTimeBases). + com.codename1.python.transpiler.codegen.BuildTimeBases.rewrite(trees, + m -> resource(m.replace('.', '/') + ".py") != null + || resource(m.replace('.', '/') + "/__init__.py") != null); + // Whole program: a model class's descriptors are resolved through + // the imports of every module (DeclarativeMap). + // openpyxl's custom document property finds its value element by + // name; each element gets literal code (CustomPropertyLowering). + com.codename1.python.transpiler.codegen.CustomPropertyLowering.rewrite(trees); + com.codename1.python.transpiler.codegen.DeclarativeMap.rewrite(trees); + com.codename1.python.transpiler.codegen.ColorValueLowering.rewrite(trees); + com.codename1.python.transpiler.codegen.NamedStyleLowering.rewrite(trees); + // Declarative XML element classes (python-pptx's xmlchemy) are made + // here rather than by their metaclass (OxmlDeclarative). + com.codename1.python.transpiler.codegen.OxmlDeclarative.rewrite(trees); + // soupsieve-style immutable slot classes get per-class constructors + // and slot readers instead of getattr over __slots__ (ImmutableSlots). + com.codename1.python.transpiler.codegen.ImmutableSlots.rewrite(trees); + // openpyxl's style descriptors become properties (StyleableLowering). + com.codename1.python.transpiler.codegen.StyleableLowering.rewrite(trees); + // The openpyxl aliases DeclarativeMap left become properties + // (AliasLowering). + com.codename1.python.transpiler.codegen.AliasLowering.rewrite(trees); + // setattr(obj, x.tagname, v) over a class-literal attribute becomes a + // per-class store method (LiteralAttrStore). + // The bundled modules are added later (addStdlib); resolve them on + // copies now so their stores count against the rewrite too. + Map libSources = new LinkedHashMap(sources); + Map libTrees = new LinkedHashMap(trees); + addStdlib(libSources, libTrees); + libTrees.keySet().removeAll(trees.keySet()); + com.codename1.python.transpiler.codegen.LiteralAttrStore.rewrite(trees, libTrees.values()); + // setattr(obj, row[0], v) over a local table of literal tuples + // stores one literal per branch (ClosedNameSetattr). + com.codename1.python.transpiler.codegen.ClosedNameSetattr.rewrite(trees); + // A constructor storing its **kw as attributes stores one literal + // attribute per key the program passes (KwAttrInit). + com.codename1.python.transpiler.codegen.KwAttrInit.rewrite(trees, libTrees); + // A field every construction sets to one literal attribute name is + // folded to it where it names an attribute (ClassArgSpecialize). + com.codename1.python.transpiler.codegen.ClassArgSpecialize.rewrite(trees, libTrees.values()); + // A descriptor bound once in a class body takes the target's name + // from __set_name__ at build time (SetNameDescriptor). + com.codename1.python.transpiler.codegen.SetNameDescriptor.rewrite(trees); + { + List everyModule = new ArrayList(trees.values()); + everyModule.addAll(libTrees.values()); + com.codename1.python.transpiler.codegen.SetNameDescriptor.subclassBindings(everyModule); + } + // A method always called with literal attribute names is cloned + // per name, so its getattr/setattr become plain attribute access + // (ConstArgSpecialize). + Map clones = + com.codename1.python.transpiler.codegen.ConstArgSpecialize.rewrite(trees, treeSources); + // A loop over attribute names the program spells out is unrolled + // per name, so its getattr/setattr are literal (LoopUnroll). + com.codename1.python.transpiler.codegen.LoopUnroll.rewrite(trees, treeSources, clones); + // After the passes that compare a tree with its source text: a + // function storing a mapping argument as attributes is cloned per + // key sequence its callers spell out (DictItemsSetattr). + com.codename1.python.transpiler.codegen.DictItemsSetattr.rewrite(trees, libTrees.values()); + if (trees.containsKey(com.codename1.python.transpiler.codegen.DeclarativeMap.META_PATH)) { + sources.put(com.codename1.python.transpiler.codegen.DeclarativeMap.META_PATH, + com.codename1.python.transpiler.codegen.DeclarativeMap.metaSource()); + } + if (trees.containsKey(com.codename1.python.transpiler.codegen.SerialisableMethods.MODULE_PATH)) { + sources.put(com.codename1.python.transpiler.codegen.SerialisableMethods.MODULE_PATH, + com.codename1.python.transpiler.codegen.SerialisableMethods.moduleSource()); + } String interop = null; + Set javaAnswered = new HashSet(); if (com.codename1.python.transpiler.codegen.JavaInteropGenerator.usesJava(trees.values())) { try (com.codename1.python.transpiler.codegen.ClassPathReader cp = new com.codename1.python.transpiler.codegen.ClassPathReader(classPath)) { - interop = com.codename1.python.transpiler.codegen.JavaInteropGenerator.generate(trees, cp, PACKAGE); + interop = com.codename1.python.transpiler.codegen.JavaInteropGenerator.generate(trees, cp, PACKAGE, javaAnswered); } catch (IOException e) { throw new IllegalStateException("cannot read the class path: " + e.getMessage(), e); } } - Set stdlib = addStdlib(sources, trees); + addStdlib(sources, trees); + // Enumeration members are defined by the compiler, not by a + // metaclass reading the class body (EnumLowering). + com.codename1.python.transpiler.codegen.EnumLowering.rewrite(trees); boolean server = false; boolean db = false; boolean image = false; @@ -236,9 +379,59 @@ public static Map transpile(Map sources, String serverImage = image && backend; image &= !backend; } + // After the standard library was added: its modules are part of + // the program, typed like any other and counted like any other. + // Before anything reads the trees: a function the build was told + // to remove or replace has, from here on, the body that stands for + // it, and is analysed and compiled as that. + com.codename1.python.transpiler.codegen.Directives directives = + com.codename1.python.transpiler.codegen.Directives.parse( + sources.get(com.codename1.python.transpiler.codegen.Directives.FILE), sources); + Map byName = new LinkedHashMap(); + for (Map.Entry e : trees.entrySet()) { + byName.put(moduleOf(e.getKey()), e.getValue()); + } + directives.apply(byName); + for (Map.Entry e : byName.entrySet()) { + dropOverloads(e.getValue().body); + if (!e.getKey().equals(mainModule)) { + dropMainBlocks(e.getValue().body); + } + } + // Before anything reads the trees: what the program never reaches + // is taken out of them, a whole module or a top-level statement at + // a time (see Liveness), and nothing downstream sees it. + Set dead = new HashSet(); + Set runtimeNames = runtimeNames(classPath, nativeModules); + truncateDoomed(trees, nativeModules, runtimeNames); + if (mainModule != null && byName.containsKey(mainModule)) { + Map> bodies = new LinkedHashMap>(); + Set packages = new HashSet(); + for (Map.Entry e : trees.entrySet()) { + String module = moduleOf(e.getKey()); + bodies.put(module, e.getValue().body); + if (e.getKey().endsWith("__init__.py")) { + packages.add(module); + } + } + dead = com.codename1.python.transpiler.codegen.Liveness.prune(bodies, packages, mainModule, + directives.keep(), runtimeNames); + for (java.util.Iterator it = trees.keySet().iterator(); it.hasNext();) { + if (dead.contains(moduleOf(it.next()))) { + it.remove(); + } + } + } + WholeProgram program = WholeProgram.of(moduleBodies(trees)); + program.javaAnswers(javaAnswered); + // Every module is planned and entered into the program before any + // is emitted: the types are inferred over all of them at once, so + // a call from one module into another is as direct as one inside. + Map emitters = new LinkedHashMap(); for (Map.Entry e : sources.entrySet()) { String path = e.getKey().replace('\\', '/'); - if (!path.endsWith(".py")) { + // An override body is spliced into its function, not a module. + if (!path.endsWith(".py") || path.startsWith(com.codename1.python.transpiler.codegen.Directives.OVERRIDES + "/")) { continue; } String stem = path.substring(0, path.length() - 3); @@ -250,17 +443,53 @@ public static Map transpile(Map sources, String continue; } String module = stem.replace('/', '.'); + if (dead.contains(module)) { + continue; + } String cls = className(module); Node.Module tree = trees.get(path); Scope scope = ScopeBuilder.build(tree, path); - // The standard library is written to be correct without the - // whole-program types, and is left out of the closed-world check. - String java = new Emitter(path, module, isPackage, PACKAGE, cls, scope) - .closed(closed && !stdlib.contains(path)).emit(tree); - java = withLineMap(java, path.replace('\\', '/')); - out.put(PACKAGE.replace('.', '/') + "/" + cls + ".java", java); + Emitter emitter = new Emitter(path, module, isPackage, PACKAGE, cls, scope).facts(program.module(module)); + emitter.prepare(tree, program); + emitters.put(path, emitter); classes.put(module, cls); } + program.roots(runtimeNames == null ? null : new HashSet(runtimeNames), directives.keep()); + program.main(mainModule); + program.infer(); + if (deferred != null) { + deferred.addAll(program.notes()); + } + // A module nothing live imports never runs: it is neither emitted + // nor registered, so ParparVM never sees its classes. + for (java.util.Iterator> it = emitters.entrySet().iterator(); it.hasNext();) { + String module = moduleOf(it.next().getKey()); + if (!program.isLive(module)) { + it.remove(); + classes.remove(module); + } + } + // One program: every module's typed fields are decided first, and + // then every module may read the plain fields of every class. + for (Emitter em : emitters.values()) { + em.planTyped(); + } + Emitter.shareLayouts(new ArrayList(emitters.values())); + for (Emitter em : emitters.values()) { + em.planBodies(); + } + List dynamic = new ArrayList(); + for (Map.Entry e : emitters.entrySet()) { + String path = e.getKey(); + String java = e.getValue().dynamicUses(dynamic).library(libraries.contains(path)) + .emit(trees.get(path)); + java = withLineMap(java, path); + out.put(PACKAGE.replace('.', '/') + "/" + classes.get(moduleOf(path)) + ".java", java); + } + PythonSyntaxError unsupported = Emitter.dynamicCodeError(dynamic); + if (unsupported != null) { + throw unsupported; + } if (mainModule != null && !classes.containsKey(mainModule)) { throw new IllegalArgumentException("main module '" + mainModule + "' is not among the sources"); } @@ -279,6 +508,15 @@ public static Map transpile(Map sources, String if (serverImage) { out.put(PACKAGE.replace('.', '/') + "/BackendImage.java", backendImage()); } + // The classes of Java replacements are installed like the modules + // written in Java, and their stubs go out with the generated + // sources: whoever writes those keeps a class the project already + // has (see Directives.shims). + Map installed = new java.util.TreeMap(nativeModules); + for (String cls : directives.shimClasses()) { + installed.put("replace " + cls, cls); + } + out.putAll(directives.shims()); // The console is the backend's (com.codename1.cli); an application // has no terminal, and _cn1term answers as much with none installed. // Every backend build installs it, not just one that imports @@ -291,7 +529,69 @@ public static Map transpile(Map sources, String out.put(PACKAGE.replace('.', '/') + "/BackendFileSystem.java", template("BackendFileSystem.java.txt")); } out.put(PACKAGE.replace('.', '/') + "/PythonModules.java", registry(classes, mainModule, interop != null, server, db, - image, serverImage, backend, term, nativeModules)); + image, serverImage, backend, term, installed)); + return out; + } + + /// What Java may look up by name, which keeps a function or a method + /// in the build: the identifiers among the strings of the runtime's + /// own classes and of the modules written in Java. Null when the + /// runtime is not on the class path. + private static Set runtimeNames(List classPath, Map nativeModules) { + try (com.codename1.python.transpiler.codegen.ClassPathReader cp = + new com.codename1.python.transpiler.codegen.ClassPathReader(classPath)) { + Set names = cp.find("com/codename1/python/runtime/Py") == null ? null + : cp.names("com/codename1/python/"); + if (names != null) { + for (String cls : nativeModules.values()) { + Set more = cp.names(cls.replace('.', '/')); + if (more != null) { + names.addAll(more); + } + } + } + return names; + } catch (IOException e) { + throw new IllegalStateException("cannot read the class path: " + e.getMessage(), e); + } + } + + /// The program's modules after a top-level import that cannot + /// succeed are cut there (see Liveness#truncateDoomed). + private static void truncateDoomed(Map trees, Map nativeModules, + Set runtimeNames) { + if (runtimeNames == null) { + return; + } + Set tops = new HashSet(); + for (String path : trees.keySet()) { + tops.add(topOf(moduleOf(path))); + } + for (String m : nativeModules.keySet()) { + tops.add(topOf(m)); + } + List> bodies = new ArrayList>(); + for (Node.Module t : trees.values()) { + bodies.add(t.body); + } + com.codename1.python.transpiler.codegen.Liveness.truncateDoomed(bodies, tops, runtimeNames); + } + + private static String topOf(String m) { + int dot = m.indexOf('.'); + return dot < 0 ? m : m.substring(0, dot); + } + + /// Each module's dotted name to its body. + private static Map> moduleBodies(Map trees) { + Map> out = new LinkedHashMap>(); + for (Map.Entry e : trees.entrySet()) { + String stem = e.getKey().substring(0, e.getKey().length() - 3); + if ("__init__".equals(stem) || stem.endsWith("/__init__")) { + stem = "__init__".equals(stem) ? "" : stem.substring(0, stem.length() - "/__init__".length()); + } + out.put(stem.replace('/', '.'), e.getValue().body); + } return out; } @@ -358,6 +658,17 @@ private static Set addStdlib(Map sources, Map body) { + for (int i = 0; i < body.size(); i++) { + Node.Stmt s = body.get(i); + if (s instanceof Node.If && isMainTest(((Node.If) s).test)) { + body.remove(i); + body.addAll(i, ((Node.If) s).orelse); + i += ((Node.If) s).orelse.size() - 1; + } + } + } + + /// Takes out the `@overload` stubs of a body (and of its classes'): + /// `typing.overload` hands back a function that only raises, and the + /// undecorated definition after them rebinds the name, so no call ever + /// reaches one. Left in, each is a function of untyped parameters. + static void dropOverloads(List body) { + for (int i = body.size() - 1; i >= 0; i--) { + Node.Stmt s = body.get(i); + if (s instanceof Node.ClassDef) { + dropOverloads(((Node.ClassDef) s).body); + } else if (s instanceof Node.FunctionDef && isOverload((Node.FunctionDef) s) + && definedLater(body, i, ((Node.FunctionDef) s).name)) { + body.remove(i); + } + } + } + + private static boolean isOverload(Node.FunctionDef f) { + for (Node.Expr d : f.decorators) { + if (d instanceof Node.Name && "overload".equals(((Node.Name) d).id) + || d instanceof Node.Attribute && "overload".equals(((Node.Attribute) d).attr)) { + return true; + } + } + return false; + } + + private static boolean definedLater(List body, int i, String name) { + for (int j = i + 1; j < body.size(); j++) { + Node.Stmt s = body.get(j); + if (s instanceof Node.FunctionDef && name.equals(((Node.FunctionDef) s).name) + && !isOverload((Node.FunctionDef) s)) { + return true; + } + } + return false; + } + + private static boolean isMainTest(Node.Expr t) { + if (!(t instanceof Node.Compare) || ((Node.Compare) t).ops.size() != 1 + || !"==".equals(((Node.Compare) t).ops.get(0))) { + return false; + } + Node.Expr l = ((Node.Compare) t).left; + Node.Expr r = ((Node.Compare) t).comparators.get(0); + return isName(l) && isMain(r) || isName(r) && isMain(l); + } + + private static boolean isName(Node.Expr e) { + return e instanceof Node.Name && "__name__".equals(((Node.Name) e).id); + } + + private static boolean isMain(Node.Expr e) { + return e instanceof Node.Constant && ((Node.Constant) e).kind == Node.Constant.Kind.STR + && "__main__".equals(((Node.Constant) e).text); + } + public static String className(String module) { StringBuilder sb = new StringBuilder("py_"); for (int i = 0; i < module.length(); i++) { @@ -768,6 +1151,7 @@ private static String backendDb() { return "// Generated by the Codename One Python transpiler.\n" + "package " + PACKAGE + ";\n\n" + "import com.codename1.backend.Database;\n" + + "import com.codename1.backend.sql.QueryRows;\n" + "import com.codename1.python.runtime.PyDb;\n" + "import com.codename1.python.runtime.PySql;\n" + "import java.io.IOException;\n" @@ -823,7 +1207,10 @@ private static String backendDb() { + " return String.valueOf(v);\n" + " }\n\n" + " static final class Conn extends PyDb.Connection {\n" - + " private final Database db;\n\n" + + " private final Database db;\n" + + " private final PySql.Result shared = new PySql.Result();\n" + + " private int depth;\n" + + " private final long[] lastId = new long[1];\n\n" + " Conn(Database db) {\n" + " this.db = db;\n" + " }\n\n" @@ -833,27 +1220,58 @@ private static String backendDb() { + " }\n\n" + " @Override\n" + " public PySql.Result run(String sql, Object[] params, boolean query) throws IOException {\n" - + " PySql.Result r = new PySql.Result();\n" + + " // One result per connection, read by the caller before its next\n" + + " // statement, as the client arm's are. Emptied only once the engine\n" + + " // has answered: a SQL function that runs a statement of its own\n" + + " // mid-step fills and is done with it before this one is filled.\n" + + " // A statement run from inside another one's step (a SQL function's\n" + + " // body) gets a result of its own: the outer one is being filled.\n" + + " PySql.Result r = depth == 0 ? shared : new PySql.Result();\n" + + " depth++;\n" + + " try {\n" + + " return fill(r, sql, params, query);\n" + + " } finally {\n" + + " depth--;\n" + + " }\n" + + " }\n\n" + + " private PySql.Result fill(PySql.Result r, String sql, Object[] params, boolean query)\n" + + " throws IOException {\n" + " if (!query) {\n" - + " r.changes = db.execute(sql, params);\n" - + " r.lastRowId = db.lastInsertId();\n" + + " // One hold of the connection for the statement and its row id.\n" + + " int changes = db.execute(sql, params, lastId);\n" + + " r.clear();\n" + + " r.changes = changes;\n" + + " r.lastRowId = lastId[0];\n" + + " return r;\n" + + " }\n" + + " // By position: a DB-API row is a tuple, and building a map per\n" + + " // row only to read it back in column order was most of what\n" + + " // a query allocated.\n" + + " r.clear();\n" + + " String[] direct = db.queryPositionalInto(sql, params, r.rows);\n" + + " if (direct != null) {\n" + + " // SQLite: the rows are in r.rows already, values as the\n" + + " // engine answers them (Long, Double, String, byte[] or null).\n" + + " r.columns = direct;\n" + " return r;\n" + " }\n" - + " List rows = db.query(sql, params);\n" + + " List rows = db.queryPositional(sql, params);\n" + + " // From the result, not its first row: a query that matched\n" + + " // nothing still has columns, and cursor.description must\n" + + " // name them.\n" + + " // Read, never changed: the names themselves rather than a copy.\n" + + " String[] names = rows instanceof QueryRows ? ((QueryRows) rows).sharedColumnNames()\n" + + " : Database.columnNames(rows);\n" + + " r.columns = names != null ? names : new String[0];\n" + " for (int i = 0; i < rows.size(); i++) {\n" - + " Map row = (Map) rows.get(i);\n" - + " if (i == 0) {\n" - + " r.columns = new String[row.size()];\n" - + " int c = 0;\n" - + " for (Iterator it = row.keySet().iterator(); it.hasNext();) {\n" - + " r.columns[c++] = String.valueOf(it.next());\n" + + " Object row = rows.get(i);\n" + + " if (row instanceof Object[]) {\n" + + " Object[] values = (Object[]) row;\n" + + " for (int c = 0; c < values.length; c++) {\n" + + " values[c] = value(values[c]);\n" + " }\n" + + " r.rows.add(values);\n" + " }\n" - + " Object[] values = new Object[r.columns.length];\n" - + " for (int c = 0; c < values.length; c++) {\n" - + " values[c] = value(row.get(r.columns[c]));\n" - + " }\n" - + " r.rows.add(values);\n" + " }\n" + " // DECIMAL, DATE and the like arrive as text; their kinds let\n" + " // _cn1dbapi hand back decimal.Decimal and datetime values.\n" @@ -861,6 +1279,15 @@ private static String backendDb() { + " return r;\n" + " }\n\n" + " @Override\n" + + " public boolean createFunction(String name, int nargs,\n" + + " java.util.function.Function body) throws IOException {\n" + + " return db.createFunction(name, nargs, body);\n" + + " }\n\n" + + " @Override\n" + + " protected void holdRead(boolean on) {\n" + + " db.holdRead(on);\n" + + " }\n\n" + + " @Override\n" + " public void begin() throws IOException {\n" + " db.beginTransaction();\n" + " }\n\n" @@ -1095,9 +1522,25 @@ static String withLineMap(String java, String pyFile) { return java; } String value = pyFile + "\n" + pairs; - StringBuilder lit = new StringBuilder("\""); + // A class file holds a constant string of at most 65535 bytes of + // modified UTF-8, and a concatenation of literals folds into one + // constant. A long table is therefore split over several constants, + // `$cn1PyLines`, `$cn1PyLines$1`, ..., which `PythonLineMapper` + // joins in that order; each stays a compile-time constant, so the + // mapper reads them from the class file and the table is kept. + StringBuilder fields = new StringBuilder(); + StringBuilder lit = new StringBuilder(); + int bytes = 0; + int part = 0; for (int k = 0; k < value.length(); k++) { char c = value.charAt(k); + int size = c >= 1 && c < 0x80 ? 1 : c < 0x800 ? 2 : 3; + if (bytes + size > LINE_MAP_PART_BYTES) { + lineMapField(fields, part++, lit); + lit.setLength(0); + bytes = 0; + } + bytes += size; if (c == '\n') { lit.append("\\n"); } else if (c == '"' || c == '\\') { @@ -1108,11 +1551,25 @@ static String withLineMap(String java, String pyFile) { lit.append(c); } } - lit.append('"'); - return java.substring(0, brace + 1) + " private static final String " + LINE_MAP_FIELD + " = " + lit + ";" - + java.substring(brace + 1); + lineMapField(fields, part, lit); + return java.substring(0, brace + 1) + fields + java.substring(brace + 1); } + /// The most modified UTF-8 bytes one line-table constant holds, under + /// the class file's limit of 65535. + static final int LINE_MAP_PART_BYTES = 60000; + + private static void lineMapField(StringBuilder fields, int part, CharSequence lit) { + fields.append(" private static final String ").append(LINE_MAP_FIELD); + if (part > 0) { + fields.append('$').append(part); + } + fields.append(" = \"").append(lit).append("\";"); + } + + /// Modules to a registry method. + private static final int REGISTRY_GROUP = 400; + private static String registry(Map classes, String mainModule, boolean interop, boolean server, boolean db, boolean image, boolean serverImage, boolean backend, boolean term, Map nativeModules) { StringBuilder sb = new StringBuilder(); @@ -1145,6 +1602,8 @@ private static String registry(Map classes, String mainModule, b sb.append(" BackendFileSystem.install();\n"); } else { sb.append(" com.codename1.python.runtime.Cn1FileSystem.installDefault();\n"); + // The port's resource lookup and AES; a backend has neither. + sb.append(" com.codename1.python.runtime.Cn1Platform.install();\n"); } // The network manager and Database are a client application's; a // backend's class library has neither, so it gets its own bridges. @@ -1162,10 +1621,37 @@ private static String registry(Map classes, String mainModule, b for (String cls : new java.util.TreeSet(nativeModules.values())) { sb.append(" ").append(cls).append(".install();\n"); } - for (String cls : classes.values()) { - sb.append(" ").append(cls).append(".register();\n"); + // By name and number, never by a call into the module's class: that + // call would initialise the class, and a program imports a fraction + // of the modules it is built with. In groups, because a method and a + // string constant each have a size limit. + List names = new ArrayList(classes.keySet()); + int groups = (names.size() + REGISTRY_GROUP - 1) / REGISTRY_GROUP; + for (int g = 0; g < groups; g++) { + StringBuilder joined = new StringBuilder(); + int end = Math.min(names.size(), (g + 1) * REGISTRY_GROUP); + for (int i = g * REGISTRY_GROUP; i < end; i++) { + if (joined.length() > 0) { + joined.append("\\n"); + } + joined.append(names.get(i).replace("\\", "\\\\").replace("\"", "\\\"")); + } + sb.append(" com.codename1.python.runtime.PyModule.register(\"").append(joined) + .append("\", PythonModules::load").append(g).append(");\n"); } sb.append(" }\n\n"); + for (int g = 0; g < groups; g++) { + sb.append(" private static void load").append(g).append("(int index) {\n"); + sb.append(" switch (index) {\n"); + int end = Math.min(names.size(), (g + 1) * REGISTRY_GROUP); + for (int i = g * REGISTRY_GROUP; i < end; i++) { + String name = names.get(i); + sb.append(" case ").append(i - g * REGISTRY_GROUP).append(":\n ") + .append(classes.get(name)).append(".exec(\"") + .append(name.replace("\\", "\\\\").replace("\"", "\\\"")).append("\");\n return;\n"); + } + sb.append(" default:\n return;\n }\n }\n\n"); + } sb.append(" /// Runs the entry module as `__main__` and returns the status the\n"); sb.append(" /// interpreter would exit with. An exception the program does not\n"); sb.append(" /// catch is reported on stderr, never thrown: on a device the\n"); diff --git a/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/ast/Node.java b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/ast/Node.java index 94406cdc7d0..7ff0de271e1 100644 --- a/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/ast/Node.java +++ b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/ast/Node.java @@ -32,6 +32,10 @@ /// annotates them, and the emitter walks them. public abstract class Node { public int line; + /// A construct a lowering found the build cannot compile in a closed + /// world (a class made at run time, a parser whose destination is + /// computed): the strict-mode message, reported against `line`. + public String refusal; public int col; public T at(int l, int c) { @@ -92,7 +96,8 @@ public FormattedValue(Expr value, char conversion, JoinedStr spec) { public static final class Attribute extends Expr { public final Expr value; - public final String attr; + /// Not final: codegen.ConstArgSpecialize points a call at a clone. + public String attr; public Attribute(Expr value, String attr) { this.value = value; @@ -237,6 +242,10 @@ public TupleExpr(List elts) { public static final class SetExpr extends Expr { public final List elts; + /// The right side of `in` with only constants in it: CPython folds it + /// to a frozenset constant, and so does the emitter (one per module, + /// never a set per test). + public boolean frozenConstant; public SetExpr(List elts) { this.elts = elts; @@ -589,6 +598,9 @@ public static final class FunctionDef extends Stmt { public final Expr returns; public final boolean isAsync; public Scope scope; + /// The `__init__` codegen.DataclassInit wrote: its stores are the + /// constructor's, not a store a frozen class must refuse. + public boolean dataclassInit; public FunctionDef(String name, Arguments args, List body, List decorators, Expr returns, boolean isAsync) { @@ -608,6 +620,15 @@ public static final class ClassDef extends Stmt { public final List body; public final List decorators; public Scope scope; + /// Its one decorator is `@dataclass`, whose `__init__` the class + /// now defines (codegen.DataclassInit): the decorator hands back + /// the class itself, with methods added. + public boolean dataclass; + /// A frozen one of those: its stores go through the `__setattr__` + /// the decorator adds. + public boolean dataclassFrozen; + /// Its field names, in order. + public final List dataclassFields = new ArrayList(); public ClassDef(String name, List bases, List keywords, List body, List decorators) { diff --git a/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/ast/Scope.java b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/ast/Scope.java index 7d4755510cc..37fb82f76e0 100644 --- a/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/ast/Scope.java +++ b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/ast/Scope.java @@ -23,7 +23,9 @@ */ package com.codename1.python.transpiler.ast; +import java.util.ArrayList; import java.util.LinkedHashSet; +import java.util.List; import java.util.Set; /// A Python scope and where each of its names lives, computed by the scope @@ -75,10 +77,18 @@ public enum Binding { /// Set on CLASS scopes: the Java variable holding the class being built. public String classVar; + /// The scopes nested directly in this one, in source order. + public final List children = new ArrayList(); + /// The comprehension a COMPREHENSION scope is, null for the others. + public Node.Comp comp; + public Scope(Kind kind, Scope parent, String name) { this.kind = kind; this.parent = parent; this.name = name; + if (parent != null) { + parent.children.add(this); + } } public boolean isFunctionLike() { diff --git a/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/AliasLowering.java b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/AliasLowering.java new file mode 100644 index 00000000000..1ca1812340d --- /dev/null +++ b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/AliasLowering.java @@ -0,0 +1,278 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.python.transpiler.codegen; + +import com.codename1.python.transpiler.ast.Node; +import com.codename1.python.transpiler.ast.Node.Assign; +import com.codename1.python.transpiler.ast.Node.Call; +import com.codename1.python.transpiler.ast.Node.ClassDef; +import com.codename1.python.transpiler.ast.Node.Constant; +import com.codename1.python.transpiler.ast.Node.FunctionDef; +import com.codename1.python.transpiler.ast.Node.ImportFrom; +import com.codename1.python.transpiler.ast.Node.Name; +import com.codename1.python.transpiler.ast.Node.Stmt; +import com.codename1.python.transpiler.parser.Parser; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +/// Lowers every openpyxl `Alias` that [DeclarativeMap] left in place. +/// +/// `x = Alias("y")` in a class body is a descriptor whose `__get__` and +/// `__set__` reach the target through `getattr`/`setattr` with the name it +/// stored: reflection the strict build refuses. The name is a literal at +/// every use, so each such entry becomes a property reading and writing +/// `self.y`. The model metaclass skips an `Alias` (it adds no field), and a +/// property is no descriptor of its, so serialisation is unchanged. When no +/// `Alias(...)` call is left anywhere in the program, the two computed +/// methods of the class are removed. A module that imports `Alias` from +/// elsewhere, or a call with anything but one identifier string, is left +/// alone (and keeps the methods alive). +public final class AliasLowering { + + private static final String BASE_PATH = "openpyxl/descriptors/base.py"; + + private AliasLowering() { + } + + /// Lowers the remaining aliases among `trees`. + public static void rewrite(Map trees) { + Node.Module base = null; + boolean left = false; + for (Map.Entry e : trees.entrySet()) { + if (e.getKey().endsWith(BASE_PATH)) { + base = e.getValue(); + } + boolean imported = importsAlias(e.getValue()); + for (Stmt s : e.getValue().body) { + if (s instanceof ClassDef) { + List names = new ArrayList(); + left |= lower((ClassDef) s, imported, e.getKey(), names); + if (!names.isEmpty()) { + overBaseFields(trees, e.getKey(), (ClassDef) s, names); + } + } + } + } + if (base == null || left) { + return; + } + for (Stmt s : base.body) { + if (s instanceof ClassDef && "Alias".equals(((ClassDef) s).name)) { + List keep = new ArrayList(); + for (Stmt m : ((ClassDef) s).body) { + if (!(m instanceof FunctionDef) || !("__get__".equals(((FunctionDef) m).name) + || "__set__".equals(((FunctionDef) m).name))) { + keep.add(m); + } + } + ((ClassDef) s).body.clear(); + ((ClassDef) s).body.addAll(keep); + } + } + } + + /// An alias property `n` of `c` over a field a base class stores on + /// `self` (openpyxl's `Chartsheet.HeaderFooter` over the + /// `self.HeaderFooter = HeaderFooter()` of `_WorkbookChild.__init__`): + /// in Python every such store on a `Chartsheet` goes through the alias. + /// The base gets a property `n` of its own, over `self._cn1_al_n`, so its + /// stores and reads are calls the subclass's property overrides, exactly + /// as the data descriptor shadows the instance attribute; the base is + /// left with no field of that name for the subclass body to rebind. + private static void overBaseFields(Map trees, String file, ClassDef c, List names) { + java.util.Set seen = java.util.Collections.newSetFromMap( + new java.util.IdentityHashMap()); + List> work = new ArrayList>(); + work.add(new java.util.AbstractMap.SimpleEntry(file, c)); + while (!work.isEmpty()) { + Map.Entry w = work.remove(work.size() - 1); + ClassDef k = w.getValue(); + for (Node.Expr b : k.bases) { + if (!(b instanceof Name)) { + continue; + } + Map.Entry r = resolve(trees, w.getKey(), ((Name) b).id); + if (r == null || !seen.add(r.getValue())) { + continue; + } + ClassDef bc = r.getValue(); + for (String n : names) { + if (storesOnSelf(bc, n) && !bodyBinds(bc, n)) { + String src = "@property\ndef " + n + "(self):\n return self._cn1_al_" + n + "\n@" + n + + ".setter\ndef " + n + "(self, value):\n self._cn1_al_" + n + " = value\n"; + Node.Module parsed = Parser.parse("class _al:\n" + src.replaceAll("(?m)^(?=.)", " "), + r.getKey()); + DataclassInit.atLine(parsed, bc.line); + bc.body.addAll(((ClassDef) parsed.body.get(0)).body); + } + } + work.add(r); + } + } + } + + /// The module path and class `n` names in module `file`: a class of + /// that module, or one an absolute `from m import n` brings in. + private static Map.Entry resolve(Map trees, String file, String n) { + Node.Module m = trees.get(file); + for (Stmt s : m.body) { + if (s instanceof ClassDef && n.equals(((ClassDef) s).name)) { + return new java.util.AbstractMap.SimpleEntry(file, (ClassDef) s); + } + } + for (Stmt s : m.body) { + if (s instanceof ImportFrom && ((ImportFrom) s).level == 0 && ((ImportFrom) s).module != null) { + for (Node.Alias a : ((ImportFrom) s).names) { + if (n.equals(a.asname != null ? a.asname : a.name)) { + String p = ((ImportFrom) s).module.replace('.', '/'); + for (String f : new String[] {p + ".py", p + "/__init__.py"}) { + Node.Module t = trees.get(f); + if (t != null) { + for (Stmt x : t.body) { + if (x instanceof ClassDef && a.name.equals(((ClassDef) x).name)) { + return new java.util.AbstractMap.SimpleEntry(f, (ClassDef) x); + } + } + } + } + } + } + } + } + return null; + } + + private static boolean bodyBinds(ClassDef c, String n) { + for (Stmt s : c.body) { + if (s instanceof FunctionDef && n.equals(((FunctionDef) s).name) + || s instanceof ClassDef && n.equals(((ClassDef) s).name)) { + return true; + } + if (s instanceof Assign) { + for (Node.Expr t : ((Assign) s).targets) { + if (t instanceof Name && n.equals(((Name) t).id)) { + return true; + } + } + } + } + return false; + } + + private static boolean storesOnSelf(ClassDef c, String n) { + boolean[] hit = {false}; + for (Stmt s : c.body) { + if (s instanceof FunctionDef && !((FunctionDef) s).args.names().isEmpty()) { + String self = ((FunctionDef) s).args.names().get(0); + Infer.children(s, x -> selfStore(x, self, n, hit)); + } + } + return hit[0]; + } + + private static void selfStore(Object o, String self, String n, boolean[] hit) { + if (o instanceof Assign) { + for (Node.Expr t : ((Assign) o).targets) { + hit[0] |= t instanceof Node.Attribute && n.equals(((Node.Attribute) t).attr) + && ((Node.Attribute) t).value instanceof Name + && self.equals(((Name) ((Node.Attribute) t).value).id); + } + } + Infer.children(o, x -> selfStore(x, self, n, hit)); + } + + private static boolean importsAlias(Node.Module m) { + for (Stmt s : m.body) { + if (s instanceof ImportFrom) { + ImportFrom f = (ImportFrom) s; + String mod = f.module == null ? "" : f.module; + boolean ours = f.level == 0 ? "openpyxl.descriptors".equals(mod) + || "openpyxl.descriptors.base".equals(mod) : "base".equals(mod) || "descriptors".equals(mod); + for (Node.Alias a : f.names) { + if ("Alias".equals(a.name) && a.asname == null && ours) { + return true; + } + } + } + } + return false; + } + + /// Lowers the aliases of `c`; true when one is left as it was. + private static boolean lower(ClassDef c, boolean imported, String file, List names) { + boolean left = false; + List body = new ArrayList(); + for (Stmt s : c.body) { + if (s instanceof ClassDef) { + left |= lower((ClassDef) s, imported, file, new ArrayList()); + } + if (!isAliasCall(s)) { + body.add(s); + continue; + } + Assign a = (Assign) s; + Call v = (Call) a.value; + if (!imported || a.targets.size() != 1 || !(a.targets.get(0) instanceof Name) || v.args.size() != 1 + || !v.keywords.isEmpty() || !(v.args.get(0) instanceof Constant) + || ((Constant) v.args.get(0)).kind != Constant.Kind.STR + || !ident(((Constant) v.args.get(0)).text)) { + left = true; + body.add(s); + continue; + } + String n = ((Name) a.targets.get(0)).id; + String t = ((Constant) v.args.get(0)).text; + names.add(n); + String src = "@property\ndef " + n + "(self):\n return self." + t + "\n@" + n + ".setter\ndef " + n + + "(self, value):\n self." + t + " = value\n"; + Node.Module parsed = Parser.parse("class _al:\n" + src.replaceAll("(?m)^(?=.)", " "), file); + DataclassInit.atLine(parsed, s.line); + body.addAll(((ClassDef) parsed.body.get(0)).body); + } + c.body.clear(); + c.body.addAll(body); + return left; + } + + private static boolean isAliasCall(Stmt s) { + return s instanceof Assign && ((Assign) s).value instanceof Call + && ((Call) ((Assign) s).value).func instanceof Name + && "Alias".equals(((Name) ((Call) ((Assign) s).value).func).id); + } + + private static boolean ident(String s) { + if (s.isEmpty() || !(Character.isLetter(s.charAt(0)) || s.charAt(0) == '_')) { + return false; + } + for (int i = 0; i < s.length(); i++) { + char ch = s.charAt(i); + if (ch >= 0x80 || !(Character.isLetterOrDigit(ch) || ch == '_')) { + return false; + } + } + return true; + } +} diff --git a/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/ArgparseLowering.java b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/ArgparseLowering.java new file mode 100644 index 00000000000..43cc2fb4748 --- /dev/null +++ b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/ArgparseLowering.java @@ -0,0 +1,463 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.python.transpiler.codegen; + +import com.codename1.python.transpiler.ast.Node; +import com.codename1.python.transpiler.ast.Node.Alias; +import com.codename1.python.transpiler.ast.Node.Attribute; +import com.codename1.python.transpiler.ast.Node.Call; +import com.codename1.python.transpiler.ast.Node.Expr; +import com.codename1.python.transpiler.ast.Node.ExprStmt; +import com.codename1.python.transpiler.ast.Node.Import; +import com.codename1.python.transpiler.ast.Node.ImportFrom; +import com.codename1.python.transpiler.ast.Node.Keyword; +import com.codename1.python.transpiler.ast.Node.Starred; +import com.codename1.python.transpiler.parser.Parser; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.IdentityHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/// Gives every argparse destination a store written with its literal name. +/// +/// The bundled argparse keeps parsed values as attributes of a `Namespace` +/// named by each action's `dest` string; CPython stores them with +/// `setattr(namespace, action.dest, value)`, which is reflection. Here each +/// call the build can read, +/// +/// ```python +/// p.add_argument("-c", "--count", type=int) +/// p.set_defaults(handler="adder") +/// p.add_subparsers(dest="command") +/// ``` +/// +/// gets the accessors of its destination as one more keyword, a tuple of +/// `(store, load, has)` lambdas each naming the attribute literally, +/// +/// ```python +/// p.add_argument("-c", "--count", type=int, _cn1_acc=( +/// lambda n, v: setattr(n, "count", v), +/// lambda n, d: getattr(n, "count", d), +/// lambda n: hasattr(n, "count"))) +/// ``` +/// +/// (`_cn1_accs=(("handler", acc),)` for `set_defaults`). The dest is +/// derived exactly as argparse derives it: `dest=`, else the first long +/// option, else the first short one, prefix stripped and `-` made `_`; a +/// positional's dest is its name. The stdlib stores through the accessor +/// the action carries, so nothing looks an attribute up by name. +/// +/// Only modules that import argparse are touched. A call the build cannot +/// read -- a computed option string or dest, `*args`, `**kwargs`, a dest +/// that is not an identifier -- is refused in strict mode, naming its line, +/// when its parser may reach `parse_args`/`parse_known_args` +/// ([#reachesParse]). A parser the build sees used only to build and print +/// help keeps such an argument, with no accessor: it is never stored. +public final class ArgparseLowering { + + private ArgparseLowering() { + } + + /// Adds the accessors to the argparse calls of `tree`, the module at `path`. + public static void rewrite(Node.Module tree, String path) { + if (path.endsWith("argparse.py") || !importsArgparse(tree)) { + return; + } + // Other prefix characters change how a dest is derived from the + // option strings: the build reads none of them in such a module. + boolean prefixChars = mentionsPrefixChars(tree); + List calls = new ArrayList(); + Map scopes = new IdentityHashMap(); + collect(tree, tree.body, calls, scopes); + for (Call c : calls) { + String m = c.func instanceof Attribute ? ((Attribute) c.func).attr : "Namespace"; + if ("Namespace".equals(m)) { + if (!namespace(c, path)) { + c.refusal = "argparse.Namespace(...) with keywords the build cannot read (**mapping) stores" + + " attributes by computed name; pass each attribute as a literal keyword"; + } + } else if ("set_defaults".equals(m)) { + if (!defaults(c, path) && reachesParse(c, scopes.get(c))) { + c.refusal = "set_defaults(...) with keywords the build cannot read (**mapping) on a parser" + + " that reaches parse_args; pass each default as a literal keyword"; + } + } else { + boolean arg = "add_argument".equals(m); + String dest = arg ? prefixChars ? null : argumentDest(c) : subparsersDest(c); + if (dest != null) { + c.keywords.add(new Keyword("_cn1_acc", accessor(dest, path))); + } else if ((arg || storesDest(c)) && reachesParse(c, scopes.get(c))) { + c.refusal = m + "(...) whose destination the build cannot read (a computed option" + + " string or dest, *args or **kwargs) on a parser that reaches parse_args or" + + " parse_known_args; write the option strings and dest= as literals"; + } + } + } + } + + /// An add_subparsers call that stores a destination: one with a `dest` + /// keyword (or a `**mapping` that may hold one). + private static boolean storesDest(Call c) { + for (Keyword k : c.keywords) { + if (k.arg == null || "dest".equals(k.arg)) { + return true; + } + } + return false; + } + + /// Methods of a parser, group or subparsers object that never parse: + /// a parser used only through these builds help and never stores. + private static final Set NO_PARSE = new HashSet(java.util.Arrays.asList("add_argument", + "add_argument_group", "add_mutually_exclusive_group", "add_subparsers", "add_parser", "set_defaults", + "print_help", "format_help", "print_usage", "format_usage", "get_default", "register")); + + /// Methods that make a new member of a parser's family. + private static final Set FAMILY = new HashSet(java.util.Arrays.asList("add_argument_group", + "add_mutually_exclusive_group", "add_subparsers", "add_parser")); + + /// Whether the parser `c` adds to may reach parse_args or + /// parse_known_args. Only a parser the build can see whole is exempt: + /// made by `ArgumentParser(...)` into a name bound once in `scope`, + /// every member of its family (groups, subparsers, sub-parsers, each a + /// name bound once from one of [#FAMILY]) used only as the receiver of + /// a method of [#NO_PARSE]. Anything else -- another receiver, the + /// parser passed, returned or stored -- may parse. + private static boolean reachesParse(Call c, Object scope) { + if (!(c.func instanceof Attribute) || !(((Attribute) c.func).value instanceof Node.Name) || scope == null) { + return true; + } + Map> binds = new HashMap>(); + binds(scope, binds); + String root = ((Node.Name) ((Attribute) c.func).value).id; + Set seen = new HashSet(); + boolean made = false; + while (!made) { + List v = binds.get(root); + if (!seen.add(root) || v == null || v.size() != 1 || !(v.get(0) instanceof Call)) { + return true; + } + Call mk = (Call) v.get(0); + if (mk.func instanceof Attribute && FAMILY.contains(((Attribute) mk.func).attr) + && ((Attribute) mk.func).value instanceof Node.Name) { + root = ((Node.Name) ((Attribute) mk.func).value).id; + } else if (mk.func instanceof Node.Name && "ArgumentParser".equals(((Node.Name) mk.func).id) + || mk.func instanceof Attribute && "ArgumentParser".equals(((Attribute) mk.func).attr)) { + made = true; + } else { + return true; + } + } + Set family = new HashSet(); + family.add(root); + boolean grew = true; + while (grew) { + grew = false; + for (Map.Entry> e : binds.entrySet()) { + if (family.contains(e.getKey())) { + continue; + } + for (Expr v : e.getValue()) { + if (v instanceof Call && ((Call) v).func instanceof Attribute + && ((Attribute) ((Call) v).func).value instanceof Node.Name + && family.contains(((Node.Name) ((Attribute) ((Call) v).func).value).id)) { + if (e.getValue().size() != 1 || !FAMILY.contains(((Attribute) ((Call) v).func).attr)) { + return true; + } + family.add(e.getKey()); + grew = true; + } + } + } + } + boolean[] bad = new boolean[1]; + uses(scope, family, bad); + return bad[0]; + } + + private static void binds(Object o, Map> out) { + if (o instanceof Node.Assign) { + Node.Assign a = (Node.Assign) o; + for (Expr t : a.targets) { + if (t instanceof Node.Name) { + out.computeIfAbsent(((Node.Name) t).id, k -> new ArrayList()).add(a.value); + } else { + names(t, out); + } + } + } else if (o instanceof Node.For) { + names(((Node.For) o).target, out); + } else if (o instanceof Node.AugAssign) { + names(((Node.AugAssign) o).target, out); + } else if (o instanceof Node.AnnAssign) { + names(((Node.AnnAssign) o).target, out); + } else if (o instanceof Node.NamedExpr) { + names(((Node.NamedExpr) o).target, out); + } else if (o instanceof Node.WithItem) { + names(((Node.WithItem) o).vars, out); + } else if (o instanceof Node.Delete) { + names(((Node.Delete) o).targets, out); + } else if (o instanceof Node.Arg) { + out.computeIfAbsent(((Node.Arg) o).name, k -> new ArrayList()).add(null); + } else if (o instanceof Node.FunctionDef) { + out.computeIfAbsent(((Node.FunctionDef) o).name, k -> new ArrayList()).add(null); + } else if (o instanceof Node.ClassDef) { + out.computeIfAbsent(((Node.ClassDef) o).name, k -> new ArrayList()).add(null); + } + Infer.children(o, x -> binds(x, out)); + } + + /// Every name bound by target `o`, as a binding that is not one call. + private static void names(Object o, Map> out) { + if (o instanceof Node.Name) { + out.computeIfAbsent(((Node.Name) o).id, k -> new ArrayList()).add(null); + } + if (o != null) { + Infer.children(o, x -> names(x, out)); + } + } + + /// Sets `bad` on any read of a `family` name that is not the receiver + /// of a [#NO_PARSE] method call. + private static void uses(Object o, Set family, boolean[] bad) { + if (bad[0] || o == null) { + return; + } + if (o instanceof Call && ((Call) o).func instanceof Attribute + && ((Attribute) ((Call) o).func).value instanceof Node.Name + && family.contains(((Node.Name) ((Attribute) ((Call) o).func).value).id)) { + if (!NO_PARSE.contains(((Attribute) ((Call) o).func).attr)) { + bad[0] = true; + return; + } + for (Expr a : ((Call) o).args) { + uses(a, family, bad); + } + for (Keyword k : ((Call) o).keywords) { + uses(k.value, family, bad); + } + return; + } + if (o instanceof Node.Assign) { + // `p = ArgumentParser()` binds a member; the binding is no use. + for (Expr t : ((Node.Assign) o).targets) { + if (!(t instanceof Node.Name)) { + uses(t, family, bad); + } + } + uses(((Node.Assign) o).value, family, bad); + return; + } + if (o instanceof Node.Name && family.contains(((Node.Name) o).id)) { + bad[0] = true; + return; + } + Infer.children(o, x -> uses(x, family, bad)); + } + + private static boolean importsArgparse(Node.Module tree) { + for (Node.Stmt s : tree.body) { + if (s instanceof ImportFrom && "argparse".equals(((ImportFrom) s).module)) { + return true; + } + if (s instanceof Import) { + for (Alias a : ((Import) s).names) { + if ("argparse".equals(a.name)) { + return true; + } + } + } + } + return false; + } + + private static boolean mentionsPrefixChars(Object o) { + if (o instanceof Keyword && "prefix_chars".equals(((Keyword) o).arg)) { + return true; + } + boolean[] hit = new boolean[1]; + Infer.children(o, x -> hit[0] |= mentionsPrefixChars(x)); + return hit[0]; + } + + /// The argparse calls under `o`, each with the body of the function + /// (or module) it is in, which is where its parser is looked for. + private static void collect(Object o, Object scope, List out, Map scopes) { + if (o instanceof Call && ((Call) o).func instanceof Attribute) { + String m = ((Attribute) ((Call) o).func).attr; + if ("add_argument".equals(m) || "set_defaults".equals(m) || "add_subparsers".equals(m) + || "Namespace".equals(m)) { + out.add((Call) o); + scopes.put((Call) o, scope); + } + } else if (o instanceof Call && ((Call) o).func instanceof Node.Name + && "Namespace".equals(((Node.Name) ((Call) o).func).id)) { + // A bare Namespace(...): rewritten as the attribute form, which + // the stdlib's own Namespace() calls never take keywords in. + out.add((Call) o); + scopes.put((Call) o, scope); + } + Object inner = o instanceof Node.FunctionDef ? ((Node.FunctionDef) o).body : scope; + Infer.children(o, x -> collect(x, inner, out, scopes)); + } + + private static String str(Expr e) { + if (e instanceof Node.Constant && ((Node.Constant) e).kind == Node.Constant.Kind.STR) { + return ((Node.Constant) e).text; + } + return null; + } + + private static boolean plainKeywords(Call c) { + for (Keyword k : c.keywords) { + if (k.arg == null || k.arg.startsWith("_cn1_")) { + return false; + } + } + return true; + } + + private static String argumentDest(Call c) { + if (c.args.isEmpty() || !plainKeywords(c)) { + return null; + } + List opts = new ArrayList(); + for (Expr a : c.args) { + String s = a instanceof Starred ? null : str(a); + if (s == null || s.isEmpty()) { + return null; + } + opts.add(s); + } + String explicit = null; + for (Keyword k : c.keywords) { + if ("dest".equals(k.arg)) { + explicit = str(k.value); + if (explicit == null) { + return null; + } + } + } + if (opts.size() == 1 && opts.get(0).charAt(0) != '-') { + return explicit != null ? null : ident(opts.get(0)); + } + if (explicit != null) { + return ident(explicit); + } + String first = null; + for (String o : opts) { + if (o.charAt(0) != '-') { + return null; + } + if (first == null && o.length() > 1 && o.charAt(1) == '-') { + first = o; + } + } + if (first == null) { + first = opts.get(0); + } + int i = 0; + while (i < first.length() && first.charAt(i) == '-') { + i++; + } + return ident(first.substring(i).replace('-', '_')); + } + + private static String subparsersDest(Call c) { + if (!c.args.isEmpty() || !plainKeywords(c)) { + return null; + } + for (Keyword k : c.keywords) { + if ("dest".equals(k.arg)) { + String d = str(k.value); + return d == null ? null : ident(d); + } + } + return null; + } + + private static boolean defaults(Call c, String path) { + if (!c.args.isEmpty() || c.keywords.isEmpty() || !plainKeywords(c)) { + return c.args.isEmpty() && plainKeywords(c); + } + StringBuilder src = new StringBuilder("("); + for (Keyword k : c.keywords) { + src.append("(\"").append(k.arg).append("\", ").append(accessorSource(k.arg)).append("), "); + } + src.append(")"); + c.keywords.add(new Keyword("_cn1_accs", parseExpr(src.toString(), path))); + return true; + } + + /// `Namespace(a=1, b=x)` becomes `Namespace(_cn1_init=((store_a, 1), + /// (store_b, x)))`: the values are evaluated in the same order and each + /// is stored through its own literal store, in keyword order. + private static boolean namespace(Call c, String path) { + if (!c.args.isEmpty() || c.keywords.isEmpty() || !plainKeywords(c)) { + return c.keywords.isEmpty() || plainKeywords(c); + } + Node.TupleExpr rows = new Node.TupleExpr(new ArrayList()); + for (Keyword k : c.keywords) { + Expr store = parseExpr("lambda _cn1_n, _cn1_v: setattr(_cn1_n, \"" + k.arg + "\", _cn1_v)", path); + List row = new ArrayList(); + row.add(store); + row.add(k.value); + rows.elts.add(new Node.TupleExpr(row)); + } + c.keywords.clear(); + c.keywords.add(new Keyword("_cn1_init", rows)); + return true; + } + + private static String ident(String s) { + if (s.isEmpty() || !(Character.isLetter(s.charAt(0)) || s.charAt(0) == '_')) { + return null; + } + for (int i = 0; i < s.length(); i++) { + char ch = s.charAt(i); + if (ch > 127 || !(Character.isLetterOrDigit(ch) || ch == '_')) { + return null; + } + } + return s; + } + + private static String accessorSource(String dest) { + return "(lambda _cn1_n, _cn1_v: setattr(_cn1_n, \"" + dest + "\", _cn1_v), " + + "lambda _cn1_n, _cn1_d: getattr(_cn1_n, \"" + dest + "\", _cn1_d), " + + "lambda _cn1_n: hasattr(_cn1_n, \"" + dest + "\"))"; + } + + private static Expr accessor(String dest, String path) { + return parseExpr(accessorSource(dest), path); + } + + private static Expr parseExpr(String src, String path) { + return ((ExprStmt) Parser.parse(src + "\n", path).body.get(0)).value; + } +} diff --git a/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/AttrsLowering.java b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/AttrsLowering.java new file mode 100644 index 00000000000..eaa049e4fb2 --- /dev/null +++ b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/AttrsLowering.java @@ -0,0 +1,1082 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.python.transpiler.codegen; + +import com.codename1.python.transpiler.ast.Node; +import com.codename1.python.transpiler.ast.Node.Alias; +import com.codename1.python.transpiler.ast.Node.AnnAssign; +import com.codename1.python.transpiler.ast.Node.Assign; +import com.codename1.python.transpiler.ast.Node.Attribute; +import com.codename1.python.transpiler.ast.Node.Call; +import com.codename1.python.transpiler.ast.Node.ClassDef; +import com.codename1.python.transpiler.ast.Node.Constant; +import com.codename1.python.transpiler.ast.Node.Expr; +import com.codename1.python.transpiler.ast.Node.FunctionDef; +import com.codename1.python.transpiler.ast.Node.Import; +import com.codename1.python.transpiler.ast.Node.ImportFrom; +import com.codename1.python.transpiler.ast.Node.Keyword; +import com.codename1.python.transpiler.ast.Node.Name; +import com.codename1.python.transpiler.ast.Node.Stmt; +import com.codename1.python.transpiler.parser.Parser; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/// Every method an attrs class gets, written into the class at compile time +/// as plain Python that names each attribute literally. +/// +/// attrs builds `__init__`, `__repr__`, the comparisons and `__hash__` at +/// run time, as closures over the attribute list that read and write fields +/// by computed name. Here a class statement decorated with `@attr.s`, +/// `@attrs`, `@define`, `@mutable` or `@frozen` (imported from `attr` or +/// `attrs`) gets them one step earlier, the way codegen.DataclassInit does +/// for dataclasses: +/// +/// ```python +/// @define +/// class Point: +/// x: int +/// y: int = field(default=0, converter=int) +/// # becomes: +/// x: int +/// y: int +/// _cn1_attrs_y = field(default=0, converter=int) +/// def __init__(self, x, y=NOTHING): +/// _cn1_a = Point.__attrs_attrs__ +/// self.x = x +/// if y is NOTHING: +/// y = _cn1_attrs_default(_cn1_a[1], self) +/// self._cn1_attrs_v_y = _cn1_attrs_convert(_cn1_a[1], self, y) +/// @property +/// def y(self): ... # on_setattr: converts, validates +/// def __repr__(self): ... +/// def __eq__(self, other): ... # (self.x, self.y) == (other.x, other.y) +/// __hash__ = None +/// def __cn1_attrs_values__(self): return (self.x, self.y, ) +/// __cn1_attrs_lowered__ = (("x", "y"), (("x", ...), ("y", _cn1_attrs_y)), ...) +/// ``` +/// +/// The decorator is replaced by `attr._cn1_finish`, which only builds the +/// `Attribute` list (`__attrs_attrs__`) the methods index, checks that it +/// holds the attributes the build wrote methods for, and installs the frozen +/// guard. `attr.ib()`/`field()` objects stay, under a hidden name, so that +/// defaults, factories, validators and converters are the very objects the +/// author wrote, evaluated where they were written. An `on_setattr` hook +/// (attrs' `define` default converts and validates) is a generated property +/// over a hidden slot; `fields`, `asdict`, `astuple`, `evolve` and +/// `validate` read the values through the generated `__cn1_attrs_values__`. +/// +/// What the build cannot see whole is refused in strict mode, naming its +/// line: `make_class`, a decorator applied to anything but a class +/// statement (`define(type(...))`), options that are not constants, a base +/// from another module, a class not at the top of its module. +/// +/// Known difference: `object.__setattr__(inst, "x", v)` on an attribute with +/// an on_setattr hook runs the hook (the property's setter), where attrs' +/// slotted class would store the raw value. +public final class AttrsLowering { + + private static final Set CLASSIC = new HashSet(java.util.Arrays.asList("s", "attrs", + "attributes", "dataclass")); + private static final Set DEFINE = new HashSet(java.util.Arrays.asList("define", "mutable")); + private static final Set FIELDS = new HashSet(java.util.Arrays.asList("ib", "attrib", "attr", + "field")); + + private static final String PRE = "_cn1_attrs_"; + + private AttrsLowering() { + } + + /// The names a module binds to the attrs API. + private static final class Api { + final Set modules = new HashSet(); + /// Bound name to its attrs name (define, ib, make_class, ...). + final Map names = new HashMap(); + + /// The attrs name `e` refers to, or null. + String of(Expr e) { + if (e instanceof Name) { + return names.get(((Name) e).id); + } + if (e instanceof Attribute && ((Attribute) e).value instanceof Name + && modules.contains(((Name) ((Attribute) e).value).id)) { + return ((Attribute) e).attr; + } + return null; + } + + boolean decorator(Expr e) { + String n = of(e); + return n != null && (CLASSIC.contains(n) || DEFINE.contains(n) || "frozen".equals(n)); + } + + boolean field(Expr e) { + String n = of(e); + return n != null && FIELDS.contains(n); + } + } + + private static final class Field { + String name; + String alias; + boolean init = true; + boolean kwOnly; + boolean hasDefault; + boolean validator; + boolean converter; + boolean onSet; + /// 0 not compared, 1 compared by value, 2 through its key. + int eq = 1; + int order = 1; + boolean hashed = true; + /// The class-body statement that makes its attr.ib object, if any. + Call call; + Expr plainDefault; + + Field copy() { + Field f = new Field(); + f.name = name; + f.alias = alias; + f.init = init; + f.kwOnly = kwOnly; + f.hasDefault = hasDefault; + f.validator = validator; + f.converter = converter; + f.onSet = onSet; + f.eq = eq; + f.order = order; + f.hashed = hashed; + return f; + } + } + + private static final class Model { + final List all = new ArrayList(); + final List own = new ArrayList(); + boolean frozen; + boolean preInit; + boolean postInit; + /// The attributes stored behind an on_setattr property. + final Set hooked = new HashSet(); + } + + /// Lowers the attrs classes of `tree`, the module at `path`. + public static void rewrite(Node.Module tree, String path) { + String p = path.replace('\\', '/'); + if (p.matches("(.*/)?attrs?/[^/]*\\.py")) { + return; + } + Api api = new Api(); + for (Stmt s : tree.body) { + if (s instanceof Import) { + for (Alias a : ((Import) s).names) { + if ("attr".equals(a.name) || "attrs".equals(a.name)) { + api.modules.add(a.asname != null ? a.asname : a.name); + } + } + } else if (s instanceof ImportFrom && ((ImportFrom) s).level == 0 + && ("attr".equals(((ImportFrom) s).module) || "attrs".equals(((ImportFrom) s).module))) { + for (Alias a : ((ImportFrom) s).names) { + api.names.put(a.asname != null ? a.asname : a.name, a.name); + } + } + } + if (api.modules.isEmpty() && api.names.isEmpty()) { + return; + } + Map bindings = new HashMap(); + for (Stmt s : tree.body) { + DataclassInit.count(s, bindings); + } + Map models = new LinkedHashMap(); + Map plain = new HashMap(); + boolean any = false; + for (Stmt s : tree.body) { + if (!(s instanceof ClassDef)) { + continue; + } + ClassDef c = (ClassDef) s; + Expr deco = null; + for (Expr d : c.decorators) { + if (api.decorator(d instanceof Call ? ((Call) d).func : d)) { + deco = d; + } + } + if (deco == null) { + plain.put(c.name, c); + continue; + } + String why = lower(c, deco, api, models, plain, bindings, path); + if (why != null) { + c.refusal = "attrs class " + c.name + " cannot be lowered at build time: " + why; + } else { + any = true; + } + } + // Whatever still names a class decorator or make_class makes or + // decorates a class the build cannot see: refused, naming the line. + refuseDynamic(tree.body, api); + if (any) { + List names = new ArrayList(); + String[] helpers = {"_cn1_finish", "_cn1_default", "_cn1_convert", "_cn1_validating", "_cn1_on_set", + "_cn1_repr"}; + for (String n : helpers) { + names.add(new Alias(n, PRE + n.substring(5))); + } + names.add(new Alias("NOTHING", PRE + "NOTHING")); + names.add(new Alias("attrib", PRE + "attrib")); + ImportFrom imp = new ImportFrom("attr", 0, names); + int i = 0; + while (i < tree.body.size() && (tree.body.get(i) instanceof ImportFrom + && "__future__".equals(((ImportFrom) tree.body.get(i)).module) + || i == 0 && tree.body.get(i) instanceof Node.ExprStmt)) { + i++; + } + DataclassInit.atLine(imp, 1); + tree.body.add(i, imp); + Set hooked = new java.util.TreeSet(); + for (Model m : models.values()) { + hooked.addAll(m.hooked); + } + if (!hooked.isEmpty()) { + rawStores(tree, hooked); + StringBuilder src = new StringBuilder(); + for (String f : hooked) { + src.append("def ").append(PRE).append("raw_").append(f).append("(_cn1_o, _cn1_v):\n") + .append(" if getattr(type(_cn1_o), \"__cn1_attrs_raw_").append(f) + .append("__\", False):\n _cn1_o.").append(PRE).append("v_").append(f) + .append(" = _cn1_v\n else:\n object.__setattr__(_cn1_o, \"").append(f) + .append("\", _cn1_v)\n"); + } + int at = i + 1; + for (Stmt s : Parser.parse(src.toString(), path).body) { + DataclassInit.atLine(s, 1); + tree.body.add(at++, s); + } + } + } + } + + /// `object.__setattr__(o, "x", v)` bypasses an attrs class's on_setattr + /// hooks; here a hooked attribute is a property, which it would run. So + /// each such statement, for an `x` some lowered class hooks, calls the + /// module's `_cn1_attrs_raw_x(o, v)`, which stores the hidden slot of an + /// instance of such a class and is `object.__setattr__` for any other. + /// One inside an expression is refused. + private static void rawStores(Object o, Set hooked) { + if (!(o instanceof Node) || o instanceof FunctionDef && ((FunctionDef) o).dataclassInit) { + return; + } + for (Class k = o.getClass(); k != null && k != Object.class; k = k.getSuperclass()) { + for (java.lang.reflect.Field fl : k.getDeclaredFields()) { + if (java.lang.reflect.Modifier.isStatic(fl.getModifiers())) { + continue; + } + Object x; + try { + x = fl.get(o); + } catch (IllegalAccessException e) { + continue; + } + if (x instanceof List) { + @SuppressWarnings("unchecked") + List l = (List) x; + for (int i = 0; i < l.size(); i++) { + Object y = l.get(i); + String f = y instanceof Node.ExprStmt ? rawField(((Node.ExprStmt) y).value, hooked) : null; + if (f != null) { + Call old = (Call) ((Node.ExprStmt) y).value; + Call c = new Call(new Name(PRE + "raw_" + f)); + c.args.add(old.args.get(0)); + c.args.add(old.args.get(2)); + Node.ExprStmt st = new Node.ExprStmt(c); + st.line = ((Node) y).line; + c.line = st.line; + c.func.line = st.line; + l.set(i, st); + } else if (y instanceof Expr && rawField((Expr) y, hooked) != null) { + ((Node) y).refusal = REFUSE_RAW; + } else { + rawStores(y, hooked); + } + } + } else if (x instanceof Expr && rawField((Expr) x, hooked) != null) { + ((Node) x).refusal = REFUSE_RAW; + } else if (x instanceof Node) { + rawStores(x, hooked); + } + } + } + } + + private static final String REFUSE_RAW = "object.__setattr__ of an attrs attribute with an on_setattr hook" + + " inside an expression cannot be lowered; make it a statement of its own"; + + private static String rawField(Expr e, Set hooked) { + if (!(e instanceof Call)) { + return null; + } + Call c = (Call) e; + if (!(c.func instanceof Attribute) || !"__setattr__".equals(((Attribute) c.func).attr) + || !(((Attribute) c.func).value instanceof Name) + || !"object".equals(((Name) ((Attribute) c.func).value).id) || c.args.size() != 3 + || !c.keywords.isEmpty() || !isConst(c.args.get(1), Constant.Kind.STR)) { + return null; + } + for (Expr a : c.args) { + if (a instanceof Node.Starred) { + return null; + } + } + String f = ((Constant) c.args.get(1)).text; + return hooked.contains(f) ? f : null; + } + + private static void refuseDynamic(Object o, Api api) { + if (o instanceof ClassDef) { + // A lowered class's decorator is the finisher now; a refused + // one is reported against the class already. + ClassDef c = (ClassDef) o; + boolean refused = c.refusal != null; + for (Expr d : c.decorators) { + // A bare decorator naming the API is what was lowered. + if (!refused && !api.decorator(d)) { + refuseDynamic(d, api); + } + } + refuseDynamic(c.bases, api); + refuseDynamic(c.keywords, api); + refuseDynamic(c.body, api); + return; + } + if (o instanceof Call && "make_class".equals(api.of(((Call) o).func))) { + ((Call) o).refusal = "attrs make_class builds a class at run time, which a closed-world build cannot" + + " compile; declare the class with a class statement and @define"; + } else if (o instanceof Call && api.decorator(((Call) o).func) && !((Call) o).args.isEmpty()) { + ((Call) o).refusal = "attrs " + api.of(((Call) o).func) + "(...) applied to a class built at run time" + + " cannot be lowered; decorate a class statement instead"; + } + if (o instanceof Call && api.decorator(((Call) o).func)) { + // The callee is the API itself; only its arguments are values. + Call c = (Call) o; + refuseDynamic(c.args, api); + refuseDynamic(c.keywords, api); + return; + } + if ((o instanceof Name || o instanceof Attribute) && api.decorator((Expr) o)) { + // `deco = attr.s`: the decorator escapes as a value, and what it + // is later applied to cannot be seen at build time. + ((Node) o).refusal = "attrs " + api.of((Expr) o) + " used as a value, not as a class decorator," + + " cannot be lowered at build time; decorate each class statement with it directly"; + return; + } + Infer.children(o, x -> refuseDynamic(x, api)); + } + + private static boolean isConst(Expr e, Constant.Kind k) { + return e instanceof Constant && ((Constant) e).kind == k; + } + + private static final Map BOOLS = new HashMap(); + + static { + BOOLS.put(Constant.Kind.TRUE, Boolean.TRUE); + BOOLS.put(Constant.Kind.FALSE, Boolean.FALSE); + } + + /// The constant True or False `e` is, else no value. + private static Boolean bool(Expr e) { + return BOOLS.get(e instanceof Constant ? ((Constant) e).kind : Constant.Kind.NONE); + } + + private static boolean none(Expr e) { + return isConst(e, Constant.Kind.NONE); + } + + /// Lowers `c`, decorated with `deco`; returns why not, or null. + private static String lower(ClassDef c, Expr deco, Api api, Map models, + Map plain, Map bindings, String path) { + if (c.decorators.size() != 1) { + return "it has decorators besides its attrs one"; + } + if (bindings.getOrDefault(c.name, 0) != 1) { + return "its name is bound more than once in the module"; + } + String kind = api.of(deco instanceof Call ? ((Call) deco).func : deco); + boolean define = DEFINE.contains(kind) || "frozen".equals(kind); + boolean frozen = "frozen".equals(kind); + Boolean auto = define ? null : "dataclass".equals(kind) ? Boolean.TRUE : Boolean.FALSE; + Boolean eq = null; + Boolean order = define ? Boolean.FALSE : null; + Boolean hash = null; + boolean init = true; + boolean repr = true; + boolean kwOnly = false; + boolean matchArgs = true; + boolean autoDetect = define || "dataclass".equals(kind); + Expr onSet = null; + if (deco instanceof Call) { + Call dc = (Call) deco; + if (!dc.args.isEmpty()) { + return "the decorator takes positional arguments"; + } + for (Keyword k : dc.keywords) { + if (k.arg == null) { + return "the decorator's options are a **mapping the build cannot read"; + } + if ("on_setattr".equals(k.arg)) { + onSet = none(k.value) ? null : k.value; + continue; + } + if ("slots".equals(k.arg) || "weakref_slot".equals(k.arg) || "cache_hash".equals(k.arg) + || "auto_exc".equals(k.arg) || "repr_ns".equals(k.arg) || "getstate_setstate".equals(k.arg) + || "collect_by_mro".equals(k.arg)) { + continue; + } + Boolean b = bool(k.value); + boolean isNone = none(k.value); + if (b == null && !(isNone && ("eq".equals(k.arg) || "order".equals(k.arg) || "hash".equals(k.arg) + || "unsafe_hash".equals(k.arg) || "auto_attribs".equals(k.arg) || "cmp".equals(k.arg)))) { + return "option " + k.arg + " is not the constant True or False"; + } + switch (k.arg) { + case "frozen": + frozen = b; + break; + case "eq": + eq = b; + break; + case "order": + order = b; + break; + case "cmp": + if (b != null) { + eq = b; + order = b; + } + break; + case "hash": + case "unsafe_hash": + if (b != null) { + hash = b; + } + break; + case "init": + init = b; + break; + case "repr": + repr = b; + break; + case "kw_only": + kwOnly = b; + break; + case "match_args": + matchArgs = b; + break; + case "auto_attribs": + auto = b; + break; + case "auto_detect": + autoDetect = b; + break; + case "str": + if (b) { + return "str=True is not supported"; + } + break; + default: + return "option " + k.arg + " is not supported"; + } + } + } + if (frozen && onSet != null) { + // attrs raises when the class is made; the finisher does too. + onSet = null; + } + Model base = null; + Model m = new Model(); + m.frozen = frozen; + for (Expr b : c.bases) { + if (b instanceof Name && "object".equals(((Name) b).id)) { + continue; + } + if (!(b instanceof Name)) { + return "a base is not a plain name"; + } + String bn = ((Name) b).id; + if (models.containsKey(bn)) { + if (base != null) { + return "it has more than one attrs base"; + } + base = models.get(bn); + } else if (!plainBase(bn, plain, models, new HashSet(), m)) { + return "base " + bn + " is not a class the build can see in this module"; + } + } + Set own = new HashSet(); + for (Stmt s : c.body) { + if (s instanceof FunctionDef) { + own.add(((FunctionDef) s).name); + } else if (s instanceof Assign) { + for (Expr t : ((Assign) s).targets) { + if (t instanceof Name) { + own.add(((Name) t).id); + } + } + } + } + m.preInit = own.contains("__attrs_pre_init__") || base != null && base.preInit || m.preInit; + m.postInit = own.contains("__attrs_post_init__") || base != null && base.postInit || m.postInit; + // The fields this class declares, in body order. + boolean unannotated = false; + boolean annotated = false; + for (Stmt s : c.body) { + if (s instanceof Assign && ((Assign) s).value instanceof Call + && api.field(((Call) ((Assign) s).value).func)) { + unannotated = true; + } + if (s instanceof AnnAssign && ((AnnAssign) s).target instanceof Name + && !classVar(((AnnAssign) s).annotation)) { + annotated = true; + } + } + if (auto == null) { + auto = !unannotated && annotated; + } + if (auto && unannotated) { + return "an attr.ib() without a type annotation in a class with auto_attribs"; + } + Map byName = new LinkedHashMap(); + for (Stmt s : c.body) { + Field f = null; + if (s instanceof AnnAssign && ((AnnAssign) s).target instanceof Name && auto + && !classVar(((AnnAssign) s).annotation)) { + AnnAssign a = (AnnAssign) s; + f = new Field(); + f.name = ((Name) a.target).id; + if (a.value instanceof Call && api.field(((Call) a.value).func)) { + f.call = (Call) a.value; + } else if (a.value != null) { + f.plainDefault = a.value; + f.hasDefault = true; + } + } else if (s instanceof AnnAssign && ((AnnAssign) s).target instanceof Name + && ((AnnAssign) s).value instanceof Call && api.field(((Call) ((AnnAssign) s).value).func)) { + f = new Field(); + f.name = ((Name) ((AnnAssign) s).target).id; + f.call = (Call) ((AnnAssign) s).value; + } else if (s instanceof Assign && ((Assign) s).value instanceof Call + && api.field(((Call) ((Assign) s).value).func)) { + Assign a = (Assign) s; + if (a.targets.size() != 1 || !(a.targets.get(0) instanceof Name)) { + return "an attr.ib() assigned to something other than one name (line " + s.line + ")"; + } + f = new Field(); + f.name = ((Name) a.targets.get(0)).id; + f.call = (Call) a.value; + } + if (f == null) { + continue; + } + if (f.call != null) { + String why = fieldCall(f, f.call); + if (why != null) { + return why + " (line " + s.line + ")"; + } + } + if (f.alias == null) { + int i = 0; + while (i < f.name.length() && f.name.charAt(i) == '_') { + i++; + } + f.alias = f.name.substring(i); + } + f.kwOnly |= kwOnly; + byName.remove(f.name); + byName.put(f.name, f); + } + // @x.validator and @x.default. + for (Stmt s : c.body) { + if (!(s instanceof FunctionDef)) { + continue; + } + for (Expr d : ((FunctionDef) s).decorators) { + if (d instanceof Attribute && ((Attribute) d).value instanceof Name + && byName.containsKey(((Name) ((Attribute) d).value).id)) { + Field f = byName.get(((Name) ((Attribute) d).value).id); + String a = ((Attribute) d).attr; + if (f.call == null || !"validator".equals(a) && !"default".equals(a)) { + return "decorator @" + f.name + "." + a + " is not one the build can read"; + } + if ("validator".equals(a)) { + f.validator = true; + } else { + f.hasDefault = true; + } + } + } + } + if (base != null) { + for (Field f : base.all) { + if (!byName.containsKey(f.name)) { + Field g = f.copy(); + g.kwOnly |= kwOnly; + m.all.add(g); + } + } + } + m.own.addAll(byName.values()); + m.all.addAll(m.own); + // auto_detect: a method the class writes itself is kept. + if (autoDetect) { + init &= !own.contains("__init__"); + repr &= !own.contains("__repr__"); + if (eq == null && (own.contains("__eq__") || own.contains("__ne__"))) { + eq = Boolean.FALSE; + } + if (order == null && (own.contains("__lt__") || own.contains("__le__") || own.contains("__gt__") + || own.contains("__ge__"))) { + order = Boolean.FALSE; + } + if (hash == null && own.contains("__hash__")) { + hash = Boolean.FALSE; + } + } + boolean isEq = eq == null || eq; + boolean isOrder = order == null ? isEq : order; + if (isOrder && !isEq) { + return "order=True needs eq=True"; + } + boolean hooks = !frozen; + String src = generate(c.name, m, init, repr, isEq, isOrder, hash, onSet != null, define, hooks, own, + kwOnly, matchArgs); + // Rewrite the field statements: each attr.ib object stays under a + // hidden name, an annotation stays an annotation. + List body = new ArrayList(); + for (Stmt s : c.body) { + Field f = fieldOf(s, byName, auto, api); + if (f == null) { + for (Expr d : s instanceof FunctionDef ? ((FunctionDef) s).decorators : new ArrayList()) { + if (d instanceof Attribute && ((Attribute) d).value instanceof Name + && byName.containsKey(((Name) ((Attribute) d).value).id)) { + Expr nv = new Name(PRE + ((Name) ((Attribute) d).value).id); + DataclassInit.atLine(nv, d.line); + List ds = ((FunctionDef) s).decorators; + Attribute na = new Attribute(nv, ((Attribute) d).attr); + DataclassInit.atLine(na, d.line); + ds.set(ds.indexOf(d), na); + } + } + body.add(s); + continue; + } + if (s instanceof AnnAssign) { + AnnAssign a = (AnnAssign) s; + AnnAssign bare = new AnnAssign(a.target, a.annotation, null); + DataclassInit.atLine(bare, s.line); + body.add(bare); + } + Expr make; + if (f.call != null) { + make = f.call; + } else { + Call ib = new Call(new Name(PRE + "attrib")); + if (f.plainDefault != null) { + ib.keywords.add(new Keyword("default", f.plainDefault)); + } + DataclassInit.atLine(ib.func, s.line); + ib.line = s.line; + make = ib; + } + List t = new ArrayList(); + Name hidden = new Name(PRE + f.name); + hidden.line = s.line; + t.add(hidden); + Assign as = new Assign(t, make); + as.line = s.line; + body.add(as); + } + c.body.clear(); + c.body.addAll(body); + int line = c.body.isEmpty() ? c.line : c.body.get(c.body.size() - 1).line; + for (Stmt s : Parser.parse(src, path).body) { + DataclassInit.atLine(s, line); + if (s instanceof FunctionDef && "__init__".equals(((FunctionDef) s).name)) { + ((FunctionDef) s).dataclassInit = true; + } + if (s instanceof Assign && ((Assign) s).targets.get(0) instanceof Name + && "__cn1_attrs_lowered__".equals(((Name) ((Assign) s).targets.get(0)).id) && onSet != null) { + ((Node.TupleExpr) ((Assign) s).value).elts.set(4, onSet); + } + c.body.add(s); + } + Expr fin = new Name(PRE + "finish"); + DataclassInit.atLine(fin, deco.line); + c.decorators.clear(); + c.decorators.add(fin); + // As a frozen dataclass: the finisher's __setattr__ decides every + // store, so the class keeps a layout only with no base. + c.dataclass = !(frozen && !c.bases.isEmpty()); + c.dataclassFrozen = frozen; + models.put(c.name, m); + return null; + } + + /// Whether `bn` is a class of this module with no attrs in it: no + /// decorator, no attribute a base would contribute. + private static boolean plainBase(String bn, Map plain, Map models, + Set seen, Model m) { + ClassDef k = plain.get(bn); + if (k == null || !seen.add(bn) || !k.decorators.isEmpty() || !k.keywords.isEmpty()) { + return false; + } + for (Stmt s : k.body) { + if (s instanceof FunctionDef && "__attrs_pre_init__".equals(((FunctionDef) s).name)) { + m.preInit = true; + } + if (s instanceof FunctionDef && "__attrs_post_init__".equals(((FunctionDef) s).name)) { + m.postInit = true; + } + } + for (Expr e : k.bases) { + if (e instanceof Name && "object".equals(((Name) e).id)) { + continue; + } + if (!(e instanceof Name) || models.containsKey(((Name) e).id) + || !plainBase(((Name) e).id, plain, models, seen, m)) { + return false; + } + } + return true; + } + + private static Field fieldOf(Stmt s, Map byName, boolean auto, Api api) { + String n = null; + if (s instanceof AnnAssign && ((AnnAssign) s).target instanceof Name) { + AnnAssign a = (AnnAssign) s; + if (auto && !classVar(a.annotation) || a.value instanceof Call && api.field(((Call) a.value).func)) { + n = ((Name) a.target).id; + } + } else if (s instanceof Assign && ((Assign) s).value instanceof Call + && api.field(((Call) ((Assign) s).value).func)) { + n = ((Name) ((Assign) s).targets.get(0)).id; + } + Field f = n == null ? null : byName.get(n); + return f != null && (f.call == null || f.call == (s instanceof Assign ? ((Assign) s).value + : ((AnnAssign) s).value)) ? f : null; + } + + private static boolean classVar(Expr ann) { + Expr a = ann instanceof Node.Subscript ? ((Node.Subscript) ann).value : ann; + if (a instanceof Name) { + return "ClassVar".equals(((Name) a).id); + } + if (a instanceof Attribute) { + return "ClassVar".equals(((Attribute) a).attr); + } + return a instanceof Constant && ((Constant) a).kind == Constant.Kind.STR + && ((Constant) a).text.startsWith("ClassVar"); + } + + /// Reads the options of `attr.ib(...)`/`field(...)` into `f`. + private static String fieldCall(Field f, Call c) { + if (c.args.size() > 1) { + return "attr.ib() with more than one positional argument"; + } + if (c.args.size() == 1) { + if (c.args.get(0) instanceof Node.Starred) { + return "attr.ib(*args)"; + } + f.hasDefault = true; + } + int eq = 1; + int order = -1; + Boolean hash = null; + for (Keyword k : c.keywords) { + if (k.arg == null) { + return "attr.ib(**mapping) the build cannot read"; + } + Boolean b = bool(k.value); + switch (k.arg) { + case "default": + case "factory": + f.hasDefault |= !("factory".equals(k.arg) && none(k.value)); + break; + case "validator": + f.validator = !none(k.value); + break; + case "converter": + f.converter = !none(k.value); + break; + case "on_setattr": + f.onSet = !none(k.value); + break; + case "init": + if (b == null) { + return "init= is not the constant True or False"; + } + f.init = b; + break; + case "kw_only": + if (b == null) { + return "kw_only= is not the constant True or False"; + } + f.kwOnly = b; + break; + case "alias": + if (!isConst(k.value, Constant.Kind.STR)) { + return "alias= is not a string literal"; + } + f.alias = ((Constant) k.value).text; + break; + case "hash": + if (b == null && !none(k.value)) { + return "hash= is not True, False or None"; + } + hash = b; + break; + case "cmp": + if (b == null && !none(k.value)) { + return "cmp= is not True, False or None"; + } + if (b != null) { + eq = b ? 1 : 0; + order = eq; + } + break; + case "eq": + eq = none(k.value) ? 1 : b == null ? 2 : b ? 1 : 0; + break; + case "order": + order = none(k.value) ? -1 : b == null ? 3 : b ? 1 : 0; + break; + case "repr": + case "metadata": + case "type": + break; + default: + return "attr.ib() option " + k.arg + " is not supported"; + } + } + f.eq = eq; + // An order key of its own (3), the eq key (an eq callable with order + // True or unset), a plain comparison, or none. + if (order == 3) { + f.order = 3; + } else if (order == -1) { + f.order = eq; + } else if (order == 1) { + f.order = eq == 2 ? 2 : 1; + } else { + f.order = 0; + } + f.hashed = hash == null ? eq != 0 : hash; + return null; + } + + private static String value(Field f, int i, String x, int mode) { + String v = x + "." + f.name; + if (mode == 2) { + return "_cn1_a[" + i + "].eq_key(" + v + ")"; + } + if (mode == 3) { + return "_cn1_a[" + i + "].order_key(" + v + ")"; + } + return v; + } + + private static boolean keyed(List all, boolean order) { + for (Field f : all) { + int mode = order ? f.order : f.eq; + if (mode >= 2) { + return true; + } + } + return false; + } + + private static String tuple(List all, String x, boolean order, boolean hash) { + StringBuilder b = new StringBuilder("("); + for (int i = 0; i < all.size(); i++) { + Field f = all.get(i); + int mode = order ? f.order : f.eq; + if (hash ? !f.hashed : mode == 0) { + continue; + } + b.append(value(f, i, x, hash ? f.eq == 2 ? 2 : 1 : mode)).append(", "); + } + return b.append(')').toString(); + } + + private static boolean hooked(Field f, boolean classHook, boolean define, boolean hooks) { + return hooks && (f.onSet || classHook || define && (f.converter || f.validator)); + } + + private static String generate(String cls, Model m, boolean init, boolean repr, boolean eq, boolean order, + Boolean hash, boolean classHook, boolean define, boolean hooks, Set own, boolean kwOnlyClass, + boolean matchArgs) { + String table = cls + ".__attrs_attrs__"; + StringBuilder src = new StringBuilder(); + List all = m.all; + if (init) { + StringBuilder sig = new StringBuilder("def __init__(self"); + boolean defaulted = false; + for (Field f : all) { + if (f.init && !f.kwOnly) { + defaulted |= f.hasDefault; + sig.append(", ").append(f.alias).append(defaulted ? "=" + PRE + "NOTHING" : ""); + } + } + boolean star = false; + for (Field f : all) { + if (f.init && f.kwOnly) { + if (!star) { + sig.append(", *"); + star = true; + } + sig.append(", ").append(f.alias).append(f.hasDefault ? "=" + PRE + "NOTHING" : ""); + } + } + src.append(sig).append("):\n _cn1_a = ").append(table).append('\n'); + if (m.preInit) { + src.append(" self.__attrs_pre_init__()\n"); + } + for (int i = 0; i < all.size(); i++) { + Field f = all.get(i); + String v; + if (f.init) { + v = f.alias; + if (f.hasDefault) { + src.append(" if ").append(v).append(" is ").append(PRE).append("NOTHING:\n ") + .append(v).append(" = ").append(PRE).append("default(_cn1_a[").append(i) + .append("], self)\n"); + } + } else if (f.hasDefault) { + v = "_cn1_v"; + src.append(" _cn1_v = ").append(PRE).append("default(_cn1_a[").append(i).append("], self)\n"); + } else { + continue; + } + if (f.converter) { + v = PRE + "convert(_cn1_a[" + i + "], self, " + v + ")"; + } + if (m.frozen) { + src.append(" object.__setattr__(self, \"").append(f.name).append("\", ").append(v).append(")\n"); + } else if (hooked(f, classHook, define, hooks)) { + src.append(" self.").append(PRE).append("v_").append(f.name).append(" = ").append(v) + .append('\n'); + } else { + src.append(" self.").append(f.name).append(" = ").append(v).append('\n'); + } + } + StringBuilder val = new StringBuilder(); + for (int i = 0; i < all.size(); i++) { + if (all.get(i).validator) { + val.append(" _cn1_a[").append(i).append("].validator(self, _cn1_a[").append(i) + .append("], self.").append(all.get(i).name).append(")\n"); + } + } + if (val.length() > 0) { + src.append(" if ").append(PRE).append("validating():\n").append(val); + } + if (m.postInit) { + src.append(" self.__attrs_post_init__()\n"); + } + } + for (int i = 0; i < all.size(); i++) { + Field f = all.get(i); + if (hooked(f, classHook, define, hooks) && !own.contains(f.name)) { + m.hooked.add(f.name); + src.append("__cn1_attrs_raw_").append(f.name).append("__ = True\n"); + String slot = "self." + PRE + "v_" + f.name; + src.append("@property\ndef ").append(f.name).append("(self):\n return ").append(slot).append('\n'); + src.append("@").append(f.name).append(".setter\ndef ").append(f.name).append("(self, _cn1_v):\n ") + .append(slot).append(" = ").append(PRE).append("on_set(").append(table).append('[').append(i) + .append("], self, _cn1_v)\n"); + } + } + src.append("def __cn1_attrs_values__(self):\n return ("); + for (Field f : all) { + if (!f.init && !f.hasDefault) { + src.append("getattr(self, \"").append(f.name).append("\", ").append(PRE).append("NOTHING), "); + } else { + src.append("self.").append(f.name).append(", "); + } + } + src.append(")\n"); + if (repr) { + src.append("def __repr__(self):\n return ").append(PRE).append("repr(self, ").append(table) + .append(", self.__cn1_attrs_values__())\n"); + } + if (eq) { + src.append("def __eq__(self, other):\n if other.__class__ is not self.__class__:\n") + .append(" return NotImplemented\n"); + if (keyed(all, false)) { + src.append(" _cn1_a = ").append(table).append('\n'); + } + src.append(" return ").append(tuple(all, "self", false, false)).append(" == ") + .append(tuple(all, "other", false, false)).append('\n'); + src.append("def __ne__(self, other):\n r = self.__eq__(other)\n if r is NotImplemented:\n") + .append(" return NotImplemented\n return not r\n"); + } + if (order) { + for (String[] op : new String[][] {{"__lt__", "<"}, {"__le__", "<="}, {"__gt__", ">"}, {"__ge__", ">="}}) { + src.append("def ").append(op[0]).append("(self, other):\n if other.__class__ is self.__class__:\n"); + if (keyed(all, true)) { + src.append(" _cn1_a = ").append(table).append('\n'); + } + src.append(" return ").append(tuple(all, "self", true, false)).append(' ').append(op[1]) + .append(' ').append(tuple(all, "other", true, false)).append("\n return NotImplemented\n"); + } + } + boolean genHash = hash != null ? hash : eq && m.frozen; + if (genHash) { + src.append("def __hash__(self):\n"); + if (keyed(all, false)) { + src.append(" _cn1_a = ").append(table).append('\n'); + } + String t = tuple(all, "self", false, true); + src.append(" return hash((\"").append(cls).append("\", ").append(t.substring(1)).append(")\n"); + } else if (hash == null && eq) { + src.append("__hash__ = None\n"); + } + src.append("__cn1_attrs_lowered__ = (("); + for (Field f : all) { + src.append('"').append(f.name).append("\", "); + } + src.append("), ("); + for (Field f : m.own) { + src.append("(\"").append(f.name).append("\", ").append(PRE).append(f.name).append("), "); + } + src.append("), ").append(kwOnlyClass ? "True" : "False").append(", ").append(m.frozen ? "True" : "False") + .append(", None, ").append(define ? "True" : "False").append(", ").append(matchArgs ? "True" : "False") + .append(")\n"); + return src.toString(); + } +} diff --git a/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/BuildTimeBases.java b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/BuildTimeBases.java new file mode 100644 index 00000000000..2668c755d40 --- /dev/null +++ b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/BuildTimeBases.java @@ -0,0 +1,558 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.python.transpiler.codegen; + +import com.codename1.python.transpiler.ast.Node; +import com.codename1.python.transpiler.ast.Node.Alias; +import com.codename1.python.transpiler.ast.Node.Assign; +import com.codename1.python.transpiler.ast.Node.Attribute; +import com.codename1.python.transpiler.ast.Node.Call; +import com.codename1.python.transpiler.ast.Node.ClassDef; +import com.codename1.python.transpiler.ast.Node.Constant; +import com.codename1.python.transpiler.ast.Node.Expr; +import com.codename1.python.transpiler.ast.Node.FunctionDef; +import com.codename1.python.transpiler.ast.Node.IfExp; +import com.codename1.python.transpiler.ast.Node.Import; +import com.codename1.python.transpiler.ast.Node.ImportFrom; +import com.codename1.python.transpiler.ast.Node.Keyword; +import com.codename1.python.transpiler.ast.Node.Name; +import com.codename1.python.transpiler.ast.Node.Stmt; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.function.Predicate; + +/// Folds, at build time, class bases that Python computes when the module +/// runs. The program is closed: which modules exist is known here, so +/// +/// - `try: import gzip` / `except ImportError: gzip = None` at module level +/// is the import alone when every module it names is in the program or the +/// bundled library (an import the build resolves cannot fail that way); +/// - a base `A if m else B`, `m` bound once in the module and by an import, +/// is `A` -- a module is always true; +/// - a base `f(...)` or `mod.f(...)` calling a module-level function whose +/// whole body returns one class defined once at module level, or a +/// `cobble.visitor(...)` (every visitor is `cobble._Visitor`, +/// [CobbleLowering]), with constant arguments, is that class. +/// +/// Anything else is left as written, and strict mode refuses it as before. +public final class BuildTimeBases { + private BuildTimeBases() { + } + + /// Rewrites `trees` (path to module); `exists` answers whether a dotted + /// module outside them is bundled. + public static void rewrite(Map trees, Predicate exists) { + Predicate any = m -> path(trees, m) != null || exists.test(m); + for (Node.Module t : trees.values()) { + foldImports(t, any); + } + for (Map.Entry e : trees.entrySet()) { + Node.Module t = e.getValue(); + Map binds = bindings(t); + // A copy: a folded base may add an import to the module. + for (Stmt s : new ArrayList(t.body)) { + if (!(s instanceof ClassDef)) { + continue; + } + List bases = ((ClassDef) s).bases; + for (int i = 0; i < bases.size(); i++) { + Expr b = bases.get(i); + if (b instanceof IfExp && ((IfExp) b).test instanceof Name + && importedOnce(t, ((Name) ((IfExp) b).test).id, binds)) { + bases.set(i, ((IfExp) b).body); + } else if (b instanceof Name) { + Expr r = freshImportBase(any, t, ((Name) b).id); + if (r != null) { + bases.set(i, r); + } + } else if (b instanceof Call) { + Expr r = callBase(trees, e.getKey(), t, binds, (Call) b); + if (r != null) { + DataclassInit.atLine(r, s.line); + bases.set(i, r); + } + } + } + } + } + } + + private static void foldImports(Node.Module t, Predicate exists) { + for (int i = 0; i < t.body.size(); i++) { + if (!(t.body.get(i) instanceof Node.Try)) { + continue; + } + Node.Try y = (Node.Try) t.body.get(i); + if (y.star || !y.finalbody.isEmpty() || y.body.isEmpty() || y.handlers.isEmpty()) { + continue; + } + boolean ok = true; + for (Stmt s : y.body) { + if (!(s instanceof Import)) { + ok = false; + break; + } + for (Alias a : ((Import) s).names) { + ok &= exists.test(a.name); + } + } + for (Node.ExceptHandler h : y.handlers) { + ok &= h.type instanceof Name && ("ImportError".equals(((Name) h.type).id) + || "ModuleNotFoundError".equals(((Name) h.type).id)); + } + if (ok) { + List repl = new ArrayList(y.body); + repl.addAll(y.orelse); + t.body.remove(i); + t.body.addAll(i, repl); + i += repl.size() - 1; + } + } + } + + /// A base `n` bound at module level (directly or under a top-level `if`) + /// only by `..., n, ... = f()`, where `f` is a module-level function that + /// ends in `return (..., r, ...)` with `r = p.attr` and + /// `p = importlib.import_module("mod")` its one binding of each, and `mod` + /// in the program or the bundled library: defusedxml's `_get_py3_cls`, which re-imports + /// `xml.etree.ElementTree` for its pure-Python `XMLParser`. The program has + /// one copy of each module, so the class is `mod.attr`, bound by an import + /// added at the top of the module. The call itself still runs as written. + private static Expr freshImportBase(Predicate any, Node.Module t, String n) { + Assign site = null; + int sites = 0; + for (Stmt s : t.body) { + List scope = java.util.Collections.singletonList(s); + if (s instanceof Node.If) { + scope = ((Node.If) s).body; + if (((Node.If) s).orelse.size() > 0) { + scope = new ArrayList(scope); + scope.addAll(((Node.If) s).orelse); + } + } + for (Stmt x : scope) { + if (x instanceof Assign) { + for (Expr tg : ((Assign) x).targets) { + if (tg instanceof Name && n.equals(((Name) tg).id)) { + sites += 2; + } else if (tg instanceof Node.TupleExpr) { + for (Expr el : ((Node.TupleExpr) tg).elts) { + if (el instanceof Name && n.equals(((Name) el).id)) { + sites++; + site = (Assign) x; + } + } + } + } + } else if (x instanceof Node.If) { + // Only one level of `if` is read; deeper is refused. + if (s instanceof Node.If) { + return null; + } + } else { + Map one = new HashMap(); + if (!(x instanceof FunctionDef) && !(x instanceof ClassDef)) { + walk(x, one); + } else { + bump(x instanceof FunctionDef ? ((FunctionDef) x).name : ((ClassDef) x).name, one); + } + if (one.containsKey(n) && !(x instanceof ImportFrom && s instanceof Node.If)) { + return null; + } + } + } + } + if (sites != 1 || site.targets.size() != 1 || !(site.value instanceof Call) + || !(((Call) site.value).func instanceof Name)) { + return null; + } + int k = -1; + List elts = ((Node.TupleExpr) site.targets.get(0)).elts; + for (int j = 0; j < elts.size(); j++) { + if (elts.get(j) instanceof Name && n.equals(((Name) elts.get(j)).id)) { + k = j; + } + } + String fn = ((Name) ((Call) site.value).func).id; + Map binds = bindings(t); + FunctionDef f = null; + for (Stmt s : t.body) { + if (s instanceof FunctionDef && fn.equals(((FunctionDef) s).name)) { + f = (FunctionDef) s; + } + } + if (f == null || binds.get(fn) != 1 || !f.decorators.isEmpty() || f.isAsync || f.body.isEmpty() + || !(f.body.get(f.body.size() - 1) instanceof Node.Return)) { + return null; + } + Expr rv = ((Node.Return) f.body.get(f.body.size() - 1)).value; + if (!(rv instanceof Node.TupleExpr) || ((Node.TupleExpr) rv).elts.size() != elts.size() + || !(((Node.TupleExpr) rv).elts.get(k) instanceof Name)) { + return null; + } + Expr attr = soleLocal(f, ((Name) ((Node.TupleExpr) rv).elts.get(k)).id); + if (!(attr instanceof Attribute) || !(((Attribute) attr).value instanceof Name)) { + return null; + } + Expr imp = soleLocal(f, ((Name) ((Attribute) attr).value).id); + if (imp instanceof Call && ((Call) imp).args.size() == 1 && ((Call) imp).args.get(0) instanceof Name) { + // `name = "mod"` then `import_module(name)`, `name` bound once: + // the call names the module as a literal (which Liveness reads + // as one import, not as a lookup by computed name). + Expr lit = soleLocal(f, ((Name) ((Call) imp).args.get(0)).id); + if (lit instanceof Constant && ((Constant) lit).kind == Constant.Kind.STR) { + Constant k2 = new Constant(Constant.Kind.STR, ((Constant) lit).text); + k2.line = lit.line; + ((Call) imp).args.set(0, k2); + } + } + if (!(imp instanceof Call) || ((Call) imp).args.size() != 1 || !((Call) imp).keywords.isEmpty() + || !(((Call) imp).func instanceof Attribute) + || !"import_module".equals(((Attribute) ((Call) imp).func).attr) + || !(((Attribute) ((Call) imp).func).value instanceof Name) + || !(((Call) imp).args.get(0) instanceof Constant) + || ((Constant) ((Call) imp).args.get(0)).kind != Constant.Kind.STR) { + return null; + } + String lib = ((Name) ((Attribute) ((Call) imp).func).value).id; + boolean importlib = false; + for (Stmt s : t.body) { + List scope = s instanceof Node.If ? ((Node.If) s).body : java.util.Collections.singletonList(s); + for (Stmt x : scope) { + if (x instanceof Import) { + for (Alias a : ((Import) x).names) { + importlib |= "importlib".equals(a.name) && lib.equals(a.asname == null ? a.name : a.asname); + } + } + } + } + String mod = ((Constant) ((Call) imp).args.get(0)).text; + if (!importlib || binds.get(lib) != 1 || !any.test(mod)) { + return null; + } + String local = "_cn1_base_" + n; + if (binds.containsKey(local)) { + return null; + } + List names = new ArrayList(); + names.add(new Alias(((Attribute) attr).attr, local)); + int at = 0; + while (at < t.body.size() && t.body.get(at) instanceof ImportFrom + && "__future__".equals(((ImportFrom) t.body.get(at)).module)) { + at++; + } + ImportFrom add = new ImportFrom(mod, 0, names); + add.line = t.body.get(Math.min(at, t.body.size() - 1)).line; + t.body.add(at, add); + return new Name(local); + } + + /// The value of the one assignment to local `v` in `f`, or null when + /// `v` is bound any other way or more than once. + private static Expr soleLocal(FunctionDef f, String v) { + Map b = new HashMap(); + for (Stmt s : f.body) { + walk(s, b); + } + // walk() also counts a name used inside a subscript or attribute + // target (`d[v] = x`), which binds nothing; over-counting only + // refuses, so take those back out where they are the reason. + Map uses = new HashMap(); + for (Stmt s : f.body) { + targetUses(s, uses); + } + if (b.containsKey(v) && uses.containsKey(v)) { + b.put(v, b.get(v) - uses.get(v)); + } + Integer c = b.get(v); + if (c == null || c != 1) { + return null; + } + Expr[] out = new Expr[1]; + for (Stmt s : f.body) { + soleAssign(s, v, out); + } + return out[0]; + } + + /// Counts the names under the subscripts and attributes of assignment + /// targets, which [#targets] counts as bindings. + private static void targetUses(Object o, Map out) { + List ts = o instanceof Assign ? ((Assign) o).targets + : o instanceof Node.AugAssign ? java.util.Collections.singletonList(((Node.AugAssign) o).target) + : o instanceof Node.Delete ? ((Node.Delete) o).targets : java.util.Collections.emptyList(); + for (Expr t : ts) { + if (t instanceof Node.Subscript || t instanceof Attribute) { + Infer.children(t, x -> targets(x, out)); + } + } + Infer.children(o, x -> targetUses(x, out)); + } + + private static void soleAssign(Object o, String v, Expr[] out) { + if (o instanceof Assign && ((Assign) o).targets.size() == 1 && ((Assign) o).targets.get(0) instanceof Name + && v.equals(((Name) ((Assign) o).targets.get(0)).id)) { + out[0] = ((Assign) o).value; + } + if (!(o instanceof FunctionDef) && !(o instanceof ClassDef) && !(o instanceof Node.Lambda)) { + Infer.children(o, x -> soleAssign(x, v, out)); + } + } + + /// Whether `n` is bound exactly once in `t`, by a top-level `import`. + private static boolean importedOnce(Node.Module t, String n, Map binds) { + Integer c = binds.get(n); + if (c == null || c != 1) { + return false; + } + for (Stmt s : t.body) { + if (s instanceof Import) { + for (Alias a : ((Import) s).names) { + if (n.equals(a.asname) || a.asname == null && n.equals(a.name)) { + return true; + } + } + } + } + return false; + } + + private static Expr callBase(Map trees, String path, Node.Module t, + Map binds, Call c) { + for (Expr a : c.args) { + if (!(a instanceof Constant)) { + return null; + } + } + for (Keyword k : c.keywords) { + if (k.arg == null || !(k.value instanceof Constant)) { + return null; + } + } + String fn; + String owner; + String qual; + if (c.func instanceof Name) { + fn = ((Name) c.func).id; + owner = path; + qual = null; + } else if (c.func instanceof Attribute && ((Attribute) c.func).value instanceof Name) { + qual = ((Name) ((Attribute) c.func).value).id; + fn = ((Attribute) c.func).attr; + owner = importedModule(trees, path, t, qual, binds); + if (owner == null) { + return null; + } + } else { + return null; + } + Node.Module m = trees.get(owner); + Map mb = owner.equals(path) ? binds : bindings(m); + Integer fc = mb.get(fn); + if (fc == null || fc != 1) { + return null; + } + FunctionDef f = null; + for (Stmt s : m.body) { + if (s instanceof FunctionDef && fn.equals(((FunctionDef) s).name)) { + f = (FunctionDef) s; + } + } + if (f == null || !f.decorators.isEmpty() || f.isAsync) { + return null; + } + List body = f.body; + int at = 0; + if (!body.isEmpty() && body.get(0) instanceof Node.ExprStmt + && ((Node.ExprStmt) body.get(0)).value instanceof Constant) { + at = 1; + } + if (body.size() != at + 1 || !(body.get(at) instanceof Node.Return)) { + return null; + } + Expr v = ((Node.Return) body.get(at)).value; + if (v instanceof Name) { + String cls = ((Name) v).id; + Integer cc = mb.get(cls); + boolean isClass = false; + for (Stmt s : m.body) { + isClass |= s instanceof ClassDef && cls.equals(((ClassDef) s).name); + } + if (!isClass || cc == null || cc != 1) { + return null; + } + return qual == null ? new Name(cls) : new Attribute(new Name(qual), cls); + } + if (v instanceof Call && ((Call) v).func instanceof Attribute + && "visitor".equals(((Attribute) ((Call) v).func).attr) + && ((Attribute) ((Call) v).func).value instanceof Name + && "cobble".equals(importName(m, ((Name) ((Attribute) ((Call) v).func).value).id, mb))) { + for (Stmt s : t.body) { + if (s instanceof Import) { + for (Alias a : ((Import) s).names) { + String local = a.asname != null ? a.asname : a.name; + if ("cobble".equals(a.name) && "cobble".equals(importName(t, local, binds))) { + return new Attribute(new Name(local), "_Visitor"); + } + } + } + } + } + return null; + } + + /// The module a top-level `import x` binds `n` to, when that is its one + /// binding; null otherwise. + private static String importName(Node.Module t, String n, Map binds) { + Integer c = binds.get(n); + if (c == null || c != 1) { + return null; + } + for (Stmt s : t.body) { + if (s instanceof Import) { + for (Alias a : ((Import) s).names) { + if (n.equals(a.asname) || a.asname == null && n.equals(a.name) && a.name.indexOf('.') < 0) { + return a.name; + } + } + } + } + return null; + } + + /// The program path of the module `n` names in `t` (one binding, by + /// `import a.b as n`, `import n` or `from pkg import n`), or null. + private static String importedModule(Map trees, String path, Node.Module t, String n, + Map binds) { + Integer c = binds.get(n); + if (c == null || c != 1) { + return null; + } + String pkg = path.endsWith("/__init__.py") ? path.substring(0, path.length() - 12) + : path.lastIndexOf('/') < 0 ? "" : path.substring(0, path.lastIndexOf('/')); + pkg = pkg.replace('/', '.'); + for (Stmt s : t.body) { + if (s instanceof Import) { + for (Alias a : ((Import) s).names) { + if (n.equals(a.asname) || a.asname == null && n.equals(a.name)) { + return path(trees, a.name); + } + } + } else if (s instanceof ImportFrom) { + ImportFrom f = (ImportFrom) s; + for (Alias a : f.names) { + if (n.equals(a.asname != null ? a.asname : a.name)) { + String base = pkg; + for (int l = 1; l < f.level && base != null; l++) { + int d = base.lastIndexOf('.'); + base = d < 0 ? (base.isEmpty() ? null : "") : base.substring(0, d); + } + if (base == null) { + return null; + } + String mod = f.level == 0 ? f.module + : f.module == null ? base : base.isEmpty() ? f.module : base + "." + f.module; + if (mod == null) { + return null; + } + return path(trees, mod.isEmpty() ? a.name : mod + "." + a.name); + } + } + } + } + return null; + } + + private static String path(Map trees, String dotted) { + String p = dotted.replace('.', '/'); + if (trees.containsKey(p + ".py")) { + return p + ".py"; + } + return trees.containsKey(p + "/__init__.py") ? p + "/__init__.py" : null; + } + + /// How many times each name is bound anywhere in `t` (any scope, so a + /// count of one is conservative). + static Map bindings(Node.Module t) { + Map out = new HashMap(); + walk(t, out); + return out; + } + + private static void walk(Object o, Map out) { + if (o instanceof Assign) { + for (Expr x : ((Assign) o).targets) { + targets(x, out); + } + } else if (o instanceof Node.AugAssign) { + targets(((Node.AugAssign) o).target, out); + } else if (o instanceof Node.AnnAssign) { + targets(((Node.AnnAssign) o).target, out); + } else if (o instanceof Node.For) { + targets(((Node.For) o).target, out); + } else if (o instanceof Node.WithItem && ((Node.WithItem) o).vars != null) { + targets(((Node.WithItem) o).vars, out); + } else if (o instanceof Node.Delete) { + for (Expr x : ((Node.Delete) o).targets) { + targets(x, out); + } + } else if (o instanceof Node.NamedExpr) { + bump(((Node.NamedExpr) o).target.id, out); + } else if (o instanceof Node.ExceptHandler && ((Node.ExceptHandler) o).name != null) { + bump(((Node.ExceptHandler) o).name, out); + } else if (o instanceof Node.Global) { + for (String n : ((Node.Global) o).names) { + bump(n, out); + } + } else if (o instanceof Import) { + for (Alias a : ((Import) o).names) { + String n = a.asname != null ? a.asname : a.name; + int d = n.indexOf('.'); + bump(d < 0 ? n : n.substring(0, d), out); + } + } else if (o instanceof ImportFrom) { + for (Alias a : ((ImportFrom) o).names) { + bump(a.asname != null ? a.asname : a.name, out); + } + } else if (o instanceof FunctionDef) { + bump(((FunctionDef) o).name, out); + } else if (o instanceof ClassDef) { + bump(((ClassDef) o).name, out); + } + Infer.children(o, x -> walk(x, out)); + } + + private static void targets(Object o, Map out) { + if (o instanceof Name) { + bump(((Name) o).id, out); + } + Infer.children(o, x -> targets(x, out)); + } + + private static void bump(String n, Map out) { + Integer c = out.get(n); + out.put(n, c == null ? 1 : c + 1); + } +} diff --git a/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/BuiltinSigs.java b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/BuiltinSigs.java new file mode 100644 index 00000000000..cd2e17be886 --- /dev/null +++ b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/BuiltinSigs.java @@ -0,0 +1,79 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.python.transpiler.codegen; + +import com.codename1.python.transpiler.ast.Node.Call; +import com.codename1.python.transpiler.ast.Node.Constant; + +import java.util.List; + +/// What the runtime's Java builtins return, for the inference. +/// +/// A builtin written in Java (`_cn1re.pattern_search`, a `re.Match`'s +/// `group`) is opaque to the pass, which would give its result no type and +/// every value computed from it none either. Its result type is fixed by +/// what the Java code does, so it is written down here, keyed by module and +/// function (or builtin type and method), as a function of the argument +/// types. A result the arguments do not determine is null: the pass keeps +/// the value untyped. Typed code converts the generic result to the type +/// given here with a checked conversion, so an entry that is wrong raises +/// rather than misreading a value. +/// +/// A `re.Match` carries the type of the string it matched in its name +/// (`re.Match[str]`, `re.Match[bytes]`): its groups are slices of that. +final class BuiltinSigs { + static final String MATCH_STR = "re.Match[str]"; + + private BuiltinSigs() { + } + + /// The type `q` (a dotted module function, or `type.method`) returns + /// for these positional argument types, the receiver first for a + /// method found on a class; null when not known. + static Ty ret(String q, List args, Call c) { + switch (q) { + case "_cn1re.pattern_match": + case "_cn1re.pattern_search": + case "_cn1re.pattern_fullmatch": + // (pattern, string, pos, endpos): a match of `string`, or None. + return args.size() >= 2 && args.get(1).k == Ty.K.STR && !args.get(1).opt + ? Ty.obj(MATCH_STR).orNone() : null; + case "_cn1re.sub": + // (prog, pattern, repl, string, count, subn): the new string, + // or with `subn` true the (string, count) tuple. + return args.size() == 6 && args.get(3).k == Ty.K.STR && !args.get(3).opt + && c.args.get(5) instanceof Constant && ((Constant) c.args.get(5)).kind == Constant.Kind.FALSE + ? Ty.STR : null; + case MATCH_STR + ".group": + // One group (or the whole match): its text, None when it did + // not take part. More than one is a tuple. + return args.size() <= 1 ? Ty.STR.orNone() : null; + case MATCH_STR + ".start": + case MATCH_STR + ".end": + return Ty.INT; + default: + return null; + } + } +} diff --git a/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/ClassArgSpecialize.java b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/ClassArgSpecialize.java new file mode 100644 index 00000000000..80f93c32c2a --- /dev/null +++ b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/ClassArgSpecialize.java @@ -0,0 +1,654 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.python.transpiler.codegen; + +import com.codename1.python.transpiler.ast.Node; +import com.codename1.python.transpiler.ast.Node.Attribute; +import com.codename1.python.transpiler.ast.Node.Call; +import com.codename1.python.transpiler.ast.Node.ClassDef; +import com.codename1.python.transpiler.ast.Node.Constant; +import com.codename1.python.transpiler.ast.Node.Expr; +import com.codename1.python.transpiler.ast.Node.FunctionDef; +import com.codename1.python.transpiler.ast.Node.Name; +import com.codename1.python.transpiler.ast.Node.Stmt; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.IdentityHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/// Folds an instance field that names an attribute to the one literal every +/// construction gives it. +/// +/// openpyxl's `BoundDictionary` keeps a constructor argument and uses it as +/// an attribute name: +/// +/// ```python +/// def __init__(self, reference=None, *args, **kw): +/// self.reference = reference +/// def __getitem__(self, key): +/// ... +/// setattr(value, self.reference, key) +/// ``` +/// +/// Its one construction is `DimensionHolder`'s `super().__init__(reference, +/// ...)`, whose own `reference` parameter defaults to `"index"` and which no +/// caller passes. When every construction of the class -- direct calls, and +/// calls of subclasses that forward one of their own parameters or a literal +/// through `super().__init__` -- gives the field the same string literal, and +/// nothing else in the closed program can write the field, the field's +/// value is that literal for every instance, and `setattr(value, +/// self.reference, key)` is written `setattr(value, "index", key)`. +/// +/// It refuses anything it cannot prove: a class name used other than to +/// call it, subclass it or test `isinstance` against it (a class object that +/// escapes can be constructed where no call site shows); a class or +/// subclass that reaches `type(...)`, `__class__`, `cls(...)`, `__dict__` or +/// defines `__setattr__` or the field's name in its body; a store of the +/// field anywhere but the one in `__init__` (by attribute, `setattr` with +/// the literal or `del`); a call with `*`/`**` arguments; a forwarded +/// parameter the subclass rebinds; and a field whose constructions disagree. +/// Two literals would mean cloning the class per literal, which this pass +/// does not do: identity, `isinstance` and subclassing would all have to be +/// rewritten with it. A computed `setattr` elsewhere is not considered: the +/// strict build refuses those. +public final class ClassArgSpecialize { + + private static final String STORE_PREFIX = "_cn1_set_"; + + private ClassArgSpecialize() { + } + + /// Folds every qualifying field among `trees`; `libTrees` are the bundled + /// modules, read only so their uses count against the rewrite. + public static void rewrite(Map trees, Collection libTrees) { + List all = new ArrayList(trees.values()); + all.addAll(libTrees); + final Map> classes = new HashMap>(); + final IdentityHashMap allowed = new IdentityHashMap(); + final Set escaped = new LinkedHashSet(); + final Map> callSites = new HashMap>(); + final Map fieldStores = new HashMap(); + for (Object m : all) { + scan(m, classes, allowed, escaped, callSites, fieldStores); + } + for (Object m : trees.values()) { + candidates(m, classes, escaped, callSites, fieldStores); + } + } + + private static void scan(Object o, Map> classes, IdentityHashMap allowed, + Set escaped, Map> callSites, Map fieldStores) { + if (o instanceof FunctionDef && ((FunctionDef) o).name.startsWith(STORE_PREFIX) + && storeMethod((FunctionDef) o) != null) { + // LiteralAttrStore's `def _cn1_set_x(self, target, value): + // target. = value`: counted per caller in storeOwners. + count(fieldStores, STORE_PREFIX + storeMethod((FunctionDef) o)); + return; + } + if (o instanceof ClassDef) { + ClassDef c = (ClassDef) o; + List l = classes.get(c.name); + if (l == null) { + l = new ArrayList(); + classes.put(c.name, l); + } + l.add(c); + for (Expr b : c.bases) { + allowed.put(b, Boolean.TRUE); + } + } else if (o instanceof Call) { + Call c = (Call) o; + String n = null; + if (c.func instanceof Name) { + n = ((Name) c.func).id; + } else if (c.func instanceof Attribute) { + n = ((Attribute) c.func).attr; + } + if (n != null) { + allowed.put(c.func, Boolean.TRUE); + List l = callSites.get(n); + if (l == null) { + l = new ArrayList(); + callSites.put(n, l); + } + l.add(c); + } + if (("isinstance".equals(n) || "issubclass".equals(n)) && c.args.size() == 2) { + Expr t = c.args.get(1); + allowed.put(t, Boolean.TRUE); + if (t instanceof Node.TupleExpr) { + for (Expr x : ((Node.TupleExpr) t).elts) { + allowed.put(x, Boolean.TRUE); + } + } + } + if (("setattr".equals(n) || "delattr".equals(n)) && c.args.size() >= 2 + && c.args.get(1) instanceof Constant) { + count(fieldStores, ((Constant) c.args.get(1)).text); + } + } else if (o instanceof Node.Assign) { + Node.Assign a = (Node.Assign) o; + if (isAll(a)) { + return; + } + for (Expr t : a.targets) { + stores(t, fieldStores); + } + } else if (o instanceof Node.AugAssign) { + stores(((Node.AugAssign) o).target, fieldStores); + } else if (o instanceof Node.AnnAssign) { + stores(((Node.AnnAssign) o).target, fieldStores); + } else if (o instanceof Node.Delete) { + for (Expr t : ((Node.Delete) o).targets) { + stores(t, fieldStores); + } + } else if (o instanceof Node.For) { + stores(((Node.For) o).target, fieldStores); + } else if (o instanceof Node.WithItem) { + stores(((Node.WithItem) o).vars, fieldStores); + } else if (o instanceof Name) { + if (!allowed.containsKey(o)) { + escaped.add(((Name) o).id); + } + } else if (o instanceof Attribute) { + if (!allowed.containsKey(o)) { + escaped.add(((Attribute) o).attr); + } + } else if (o instanceof Constant && ((Constant) o).kind == Constant.Kind.STR) { + escaped.add(((Constant) o).text); + } + final Map> cl = classes; + Infer.children(o, x -> scan(x, cl, allowed, escaped, callSites, fieldStores)); + } + + /// The attribute a LiteralAttrStore store method writes, or null when + /// `f` is not exactly `target. = value`. + private static String storeMethod(FunctionDef f) { + if (f.args.positional.size() != 3 || f.body.size() != 1 || !(f.body.get(0) instanceof Node.Assign)) { + return null; + } + Node.Assign a = (Node.Assign) f.body.get(0); + if (a.targets.size() != 1 || !(a.targets.get(0) instanceof Attribute)) { + return null; + } + Attribute t = (Attribute) a.targets.get(0); + if (!(t.value instanceof Name) || !f.args.positional.get(1).name.equals(((Name) t.value).id)) { + return null; + } + return t.attr; + } + + /// True when every store method writing `field` is called only with the + /// caller's own `self` as target, from a class outside `family`. + private static boolean storeMethodsSafe(String field, Map> classes, + Map> callSites, List family) { + Set fam = new LinkedHashSet(); + for (ClassDef k : family) { + fam.add(k.name); + } + Set methods = new LinkedHashSet(); + for (List l : classes.values()) { + for (ClassDef k : l) { + for (Stmt s : k.body) { + if (s instanceof FunctionDef && ((FunctionDef) s).name.startsWith(STORE_PREFIX) + && field.equals(storeMethod((FunctionDef) s))) { + methods.add(((FunctionDef) s).name); + } + } + } + } + final IdentityHashMap ok = new IdentityHashMap(); + for (List l : classes.values()) { + for (ClassDef k : l) { + if (fam.contains(k.name)) { + continue; + } + for (Stmt s : k.body) { + if (!(s instanceof FunctionDef) || ((FunctionDef) s).args.positional.isEmpty() + || rebinds(((FunctionDef) s).body, ((FunctionDef) s).args.positional.get(0).name)) { + continue; + } + final String self = ((FunctionDef) s).args.positional.get(0).name; + walk(s, x -> { + if (x instanceof Call && !((Call) x).args.isEmpty() && ((Call) x).args.get(0) instanceof Name + && self.equals(((Name) ((Call) x).args.get(0)).id)) { + ok.put(x, Boolean.TRUE); + } + }); + } + } + } + for (String m : methods) { + List cs = callSites.get(m); + if (cs == null) { + continue; + } + for (Call c : cs) { + if (!ok.containsKey(c)) { + return false; + } + } + } + return true; + } + + private static boolean isAll(Node.Assign a) { + return a.targets.size() == 1 && a.targets.get(0) instanceof Name + && "__all__".equals(((Name) a.targets.get(0)).id); + } + + private static void stores(Object t, Map fieldStores) { + if (t instanceof Attribute) { + count(fieldStores, ((Attribute) t).attr); + } else if (t instanceof Node.TupleExpr) { + for (Expr x : ((Node.TupleExpr) t).elts) { + stores(x, fieldStores); + } + } else if (t instanceof Node.ListExpr) { + for (Expr x : ((Node.ListExpr) t).elts) { + stores(x, fieldStores); + } + } else if (t instanceof Node.Starred) { + stores(((Node.Starred) t).value, fieldStores); + } + } + + private static void count(Map m, String k) { + Integer n = m.get(k); + m.put(k, Integer.valueOf(n == null ? 1 : n.intValue() + 1)); + } + + private static void candidates(Object o, Map> classes, Set escaped, + Map> callSites, Map fieldStores) { + if (o instanceof ClassDef) { + fold((ClassDef) o, classes, escaped, callSites, fieldStores); + } + Infer.children(o, x -> candidates(x, classes, escaped, callSites, fieldStores)); + } + + private static void fold(ClassDef c, Map> classes, Set escaped, + Map> callSites, Map fieldStores) { + if (escaped.contains(c.name) || classes.get(c.name).size() != 1 || !c.decorators.isEmpty()) { + return; + } + FunctionDef init = method(c, "__init__"); + if (init == null || !init.decorators.isEmpty() || init.args.positional.isEmpty()) { + return; + } + String self = init.args.positional.get(0).name; + for (Stmt s : init.body) { + if (!(s instanceof Node.Assign)) { + continue; + } + Node.Assign a = (Node.Assign) s; + if (a.targets.size() != 1 || !(a.targets.get(0) instanceof Attribute) || !(a.value instanceof Name)) { + continue; + } + Attribute t = (Attribute) a.targets.get(0); + String p = ((Name) a.value).id; + if (!(t.value instanceof Name) || !self.equals(((Name) t.value).id) || param(init, p) < 1 + || !Integer.valueOf(1).equals(fieldStores.get(t.attr)) || rebinds(init.body, p) + || rebinds(init.body, self)) { + continue; + } + String field = t.attr; + List family = new ArrayList(); + if (!family(c, classes, escaped, family) || !usesAsName(c, field) + || fieldStores.containsKey(STORE_PREFIX + field) + && !storeMethodsSafe(field, classes, callSites, family)) { + continue; + } + boolean ok = true; + for (ClassDef k : family) { + ok &= closed(k, field); + } + Set values = new LinkedHashSet(); + if (!ok || !values(c, init, p, classes, callSites, values) || values.size() != 1) { + continue; + } + String lit = values.iterator().next(); + if (lit == null) { + continue; + } + for (ClassDef k : family) { + for (Stmt m : k.body) { + if (m instanceof FunctionDef) { + FunctionDef f = (FunctionDef) m; + if (!f.args.positional.isEmpty() && f.decorators.isEmpty() + && !rebinds(f.body, f.args.positional.get(0).name)) { + substitute(f.body, f.args.positional.get(0).name, field, lit); + } + } + } + } + } + } + + private static FunctionDef method(ClassDef c, String name) { + FunctionDef r = null; + for (Stmt s : c.body) { + if (s instanceof FunctionDef && name.equals(((FunctionDef) s).name)) { + if (r != null) { + return null; + } + r = (FunctionDef) s; + } + } + return r; + } + + private static int param(FunctionDef f, String p) { + List ps = f.args.positional; + for (int i = 0; i < ps.size(); i++) { + if (p.equals(ps.get(i).name)) { + return i; + } + } + return -1; + } + + /// The class and all its subclasses, or false when one of them escapes + /// or names the class other than by a plain base. + private static boolean family(ClassDef c, Map> classes, Set escaped, + List out) { + out.add(c); + for (List l : classes.values()) { + for (ClassDef k : l) { + for (Expr b : k.bases) { + boolean named = b instanceof Name && c.name.equals(((Name) b).id); + if (b instanceof Attribute && c.name.equals(((Attribute) b).attr)) { + return false; + } + if (named) { + if (k.bases.size() != 1 || !k.keywords.isEmpty() || escaped.contains(k.name) + || l.size() != 1 || !family(k, classes, escaped, out)) { + return false; + } + } + } + } + } + return true; + } + + /// True when a method of `c` names an attribute by `self.field`. + private static boolean usesAsName(ClassDef c, final String field) { + final boolean[] found = {false}; + for (Stmt s : c.body) { + if (s instanceof FunctionDef && !((FunctionDef) s).args.positional.isEmpty()) { + final String self = ((FunctionDef) s).args.positional.get(0).name; + walk(s, x -> { + if (nameArg(x, self, field) != null) { + found[0] = true; + } + }); + } + } + return found[0]; + } + + private static Call nameArg(Object x, String self, String field) { + if (!(x instanceof Call)) { + return null; + } + Call c = (Call) x; + if (!(c.func instanceof Name) || c.args.size() < 2 || !(c.args.get(1) instanceof Attribute)) { + return null; + } + String n = ((Name) c.func).id; + if (!"getattr".equals(n) && !"setattr".equals(n) && !"hasattr".equals(n) && !"delattr".equals(n)) { + return null; + } + Attribute a = (Attribute) c.args.get(1); + if (field.equals(a.attr) && a.value instanceof Name && self.equals(((Name) a.value).id)) { + return c; + } + return null; + } + + private static void substitute(Object o, final String self, final String field, final String lit) { + walk(o, x -> { + Call c = nameArg(x, self, field); + if (c != null) { + c.args.set(1, new Constant(Constant.Kind.STR, lit)); + } + }); + } + + /// True when nothing in `k` can construct it behind a call site's back, + /// or write `field` but the one store. + private static boolean closed(ClassDef k, final String field) { + for (Stmt s : k.body) { + if (s instanceof FunctionDef) { + String n = ((FunctionDef) s).name; + if (field.equals(n) || "__setattr__".equals(n) || "__getattribute__".equals(n) + || "__new__".equals(n) || "__init_subclass__".equals(n)) { + return false; + } + } else if (!(s instanceof Node.Assign) && !(s instanceof Node.ExprStmt) && !(s instanceof Node.Pass)) { + return false; + } else if (s instanceof Node.Assign) { + for (Expr t : ((Node.Assign) s).targets) { + if (!(t instanceof Name) || field.equals(((Name) t).id) || "__slots__".equals(((Name) t).id)) { + return false; + } + } + } + } + final boolean[] bad = {false}; + walk(k.body, x -> { + if (x instanceof Attribute) { + String a = ((Attribute) x).attr; + bad[0] |= "__class__".equals(a) || "__dict__".equals(a); + } else if (x instanceof Call && ((Call) x).func instanceof Name) { + String n = ((Name) ((Call) x).func).id; + bad[0] |= "type".equals(n) || "cls".equals(n) || "vars".equals(n); + } + }); + return !bad[0]; + } + + /// Adds to `out` every value parameter `p` of `init` takes when `k` (or + /// a subclass relying on it) is constructed; null stands for None. + private static boolean values(ClassDef k, FunctionDef init, String p, Map> classes, + Map> callSites, Set out) { + List cs = callSites.get(k.name); + if (cs != null) { + for (Call c : cs) { + if (!bind(c, init, p, 1, out)) { + return false; + } + } + } + for (List l : classes.values()) { + for (ClassDef s : l) { + if (s.bases.size() != 1 || !(s.bases.get(0) instanceof Name) + || !k.name.equals(((Name) s.bases.get(0)).id)) { + continue; + } + FunctionDef own = method(s, "__init__"); + if (own == null) { + if (hasMethod(s, "__init__") || !values(s, init, p, classes, callSites, out)) { + return false; + } + continue; + } + List sup = superInits(s, k.name); + if (sup.size() != 1 || !contains(own.body, sup.get(0))) { + return false; + } + Set fwd = new LinkedHashSet(); + Expr arg = argFor(sup.get(0), init, p, sup.get(0).func instanceof Attribute + && ((Attribute) sup.get(0).func).value instanceof Name ? 0 : 1); + if (arg == null) { + return false; + } + if (arg instanceof Name) { + String q = ((Name) arg).id; + if (param(own, q) < 1 || rebinds(own.body, q) + || !values(s, own, q, classes, callSites, fwd)) { + return false; + } + out.addAll(fwd); + } else if (!literal(arg, out)) { + return false; + } + } + } + return true; + } + + private static boolean hasMethod(ClassDef c, String n) { + for (Stmt s : c.body) { + if (s instanceof FunctionDef && n.equals(((FunctionDef) s).name)) { + return true; + } + } + return false; + } + + /// The `super().__init__(...)` and `Base.__init__(self, ...)` calls in `s`. + private static List superInits(ClassDef s, final String base) { + final List r = new ArrayList(); + walk(s.body, x -> { + if (x instanceof Call && ((Call) x).func instanceof Attribute + && "__init__".equals(((Attribute) ((Call) x).func).attr)) { + Expr v = ((Attribute) ((Call) x).func).value; + if (v instanceof Call && ((Call) v).func instanceof Name && "super".equals(((Name) ((Call) v).func).id) + && ((Call) v).args.isEmpty()) { + r.add((Call) x); + } else if (v instanceof Name && base.equals(((Name) v).id)) { + r.add((Call) x); + } else { + // Some other __init__ call: unknown, so make it ambiguous. + r.add((Call) x); + r.add((Call) x); + } + } + }); + return r; + } + + private static boolean contains(Object o, final Object target) { + final boolean[] f = {false}; + walk(o, x -> f[0] |= x == target); //NOPMD CompareObjectsWithEquals - identity is meant + return f[0]; + } + + /// Binds call `c` of a constructor whose `__init__` is `init`; adds the + /// value parameter `p` takes. + private static boolean bind(Call c, FunctionDef init, String p, int skip, Set out) { + Expr a = argFor(c, init, p, skip); + return a != null && literal(a, out); + } + + /// The expression parameter `p` takes in call `c` (its default when the + /// call leaves it out), or null when that cannot be told. `skip` is how + /// many leading parameters the call does not pass (1 for self). + private static Expr argFor(Call c, FunctionDef init, String p, int skip) { + for (Expr x : c.args) { + if (x instanceof Node.Starred) { + return null; + } + } + Expr found = null; + for (Node.Keyword k : c.keywords) { + if (k.arg == null) { + return null; + } + if (p.equals(k.arg)) { + found = k.value; + } + } + int idx = param(init, p); + int pos = idx - skip; + if (pos < c.args.size()) { + return found == null ? c.args.get(pos) : null; + } + if (found != null) { + return found; + } + List d = init.args.defaults; + int di = idx - (init.args.positional.size() - d.size()); + return di >= 0 ? d.get(di) : null; + } + + private static boolean literal(Expr a, Set out) { + if (a instanceof Constant) { + Constant k = (Constant) a; + if (k.kind == Constant.Kind.STR && ConstArgSpecialize.ident(k.text)) { + out.add(k.text); + return true; + } + if (k.kind == Constant.Kind.NONE) { + out.add(null); + return true; + } + } + return false; + } + + /// True when `o` might rebind `p` or hide it in a nested scope. + private static boolean rebinds(Object o, final String p) { + final boolean[] r = {false}; + walk(o, x -> { + List ts = new ArrayList(); + if (x instanceof Node.Lambda || x instanceof FunctionDef || x instanceof ClassDef + || x instanceof Node.Global) { + r[0] = true; + } else if (x instanceof Node.Assign) { + ts.addAll(((Node.Assign) x).targets); + } else if (x instanceof Node.AugAssign) { + ts.add(((Node.AugAssign) x).target); + } else if (x instanceof Node.AnnAssign) { + ts.add(((Node.AnnAssign) x).target); + } else if (x instanceof Node.For) { + ts.add(((Node.For) x).target); + } else if (x instanceof Node.WithItem) { + ts.add(((Node.WithItem) x).vars); + } else if (x instanceof Node.NamedExpr) { + ts.add(((Node.NamedExpr) x).target); + } else if (x instanceof Node.Delete) { + ts.addAll(((Node.Delete) x).targets); + } else if (x instanceof Node.ExceptHandler && p.equals(((Node.ExceptHandler) x).name)) { + r[0] = true; + } + for (Object t : ts) { + walk(t, y -> r[0] |= y instanceof Name && p.equals(((Name) y).id) + && !(t instanceof Attribute) && !(t instanceof Node.Subscript)); + } + }); + return r[0]; + } + + private static void walk(Object o, Infer.Visit v) { + v.on(o); + Infer.children(o, x -> walk(x, v)); + } +} diff --git a/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/ClassDecoratorLowering.java b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/ClassDecoratorLowering.java new file mode 100644 index 00000000000..2b5037bb472 --- /dev/null +++ b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/ClassDecoratorLowering.java @@ -0,0 +1,316 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.python.transpiler.codegen; + +import com.codename1.python.transpiler.ast.Node; +import com.codename1.python.transpiler.ast.Node.Alias; +import com.codename1.python.transpiler.ast.Node.Assign; +import com.codename1.python.transpiler.ast.Node.Attribute; +import com.codename1.python.transpiler.ast.Node.Call; +import com.codename1.python.transpiler.ast.Node.ClassDef; +import com.codename1.python.transpiler.ast.Node.Constant; +import com.codename1.python.transpiler.ast.Node.Expr; +import com.codename1.python.transpiler.ast.Node.FunctionDef; +import com.codename1.python.transpiler.ast.Node.Import; +import com.codename1.python.transpiler.ast.Node.ImportFrom; +import com.codename1.python.transpiler.ast.Node.Keyword; +import com.codename1.python.transpiler.ast.Node.Name; +import com.codename1.python.transpiler.ast.Node.Stmt; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +/// Lowers the standard class decorators whose effect is known, so the class +/// keeps its layout: each hands back the class it was given. +/// +/// - `six.add_metaclass(M)` becomes the keyword `metaclass=M`, and a base +/// `six.with_metaclass(M, B...)` becomes the bases `B...` with that keyword. +/// Both are what the two helpers build at run time, a class of metaclass `M`. +/// - `typing_extensions.deprecated(msg, category=None)` (or `warnings.`) only +/// sets `__deprecated__`, so it becomes that class attribute. +/// - `typing.runtime_checkable` (or `typing_extensions.`) on a protocol +/// becomes the class attribute `_is_runtime_protocol = True`. +/// - `functools.total_ordering` becomes the comparison methods it would have +/// set, written for the root it picks (the stdlib's own `functools`), when +/// the roots are the class body's own and the class has no base. +/// +/// A name is lowered only when the module imports it from that module and +/// binds it nowhere else; anything else keeps its decorator, and strict mode +/// still refuses the class. +public final class ClassDecoratorLowering { + private static final String[] ORDER = {"__lt__", "__le__", "__gt__", "__ge__"}; + + private ClassDecoratorLowering() { + } + + /// Rewrites the decorated classes at module level of `tree` (path `path`). + public static void rewrite(Node.Module tree, String path) { + // bound name -> "module.name", for names imported from the modules here. + Map known = new HashMap(); + // bound name -> module, for `import six`. + Map mods = new HashMap(); + for (Stmt s : tree.body) { + if (s instanceof ImportFrom && ((ImportFrom) s).level == 0 && relevant(((ImportFrom) s).module)) { + for (Alias a : ((ImportFrom) s).names) { + known.put(a.asname != null ? a.asname : a.name, ((ImportFrom) s).module + "." + a.name); + } + } else if (s instanceof Import) { + for (Alias a : ((Import) s).names) { + if (relevant(a.name) && a.name.indexOf('.') < 0) { + mods.put(a.asname != null ? a.asname : a.name, a.name); + } + } + } + } + if (known.isEmpty() && mods.isEmpty()) { + return; + } + Map bindings = new HashMap(); + for (Stmt s : tree.body) { + DataclassInit.count(s, bindings); + } + for (Stmt s : tree.body) { + if (!(s instanceof ClassDef)) { + continue; + } + ClassDef c = (ClassDef) s; + withMetaclassBase(c, known, mods, bindings); + for (int i = c.decorators.size() - 1; i >= 0; i--) { + Expr d = c.decorators.get(i); + String q = resolve(d instanceof Call ? ((Call) d).func : d, known, mods, bindings); + if (q == null || !lower(c, d, q, path)) { + break; + } + c.decorators.remove(i); + } + } + } + + private static boolean relevant(String module) { + return "six".equals(module) || "typing_extensions".equals(module) || "typing".equals(module) || "warnings".equals(module) + || "functools".equals(module); + } + + /// "module.name" for a reference to one of the imported helpers. + private static String resolve(Expr e, Map known, Map mods, + Map bindings) { + if (e instanceof Name) { + String id = ((Name) e).id; + return known.containsKey(id) && bindings.getOrDefault(id, 0) == 1 ? known.get(id) : null; + } + if (e instanceof Attribute && ((Attribute) e).value instanceof Name) { + String id = ((Name) ((Attribute) e).value).id; + return mods.containsKey(id) && bindings.getOrDefault(id, 0) == 1 + ? mods.get(id) + "." + ((Attribute) e).attr : null; + } + return null; + } + + private static boolean hasMetaclass(ClassDef c) { + for (Keyword k : c.keywords) { + if (k.arg == null || "metaclass".equals(k.arg)) { + return true; + } + } + return false; + } + + private static void withMetaclassBase(ClassDef c, Map known, Map mods, + Map bindings) { + if (c.bases.size() != 1 || !(c.bases.get(0) instanceof Call) || hasMetaclass(c)) { + return; + } + Call b = (Call) c.bases.get(0); + if (!"six.with_metaclass".equals(resolve(b.func, known, mods, bindings)) || b.args.isEmpty() + || !b.keywords.isEmpty()) { + return; + } + for (Expr a : b.args) { + if (a instanceof Node.Starred) { + return; + } + } + c.bases.clear(); + c.bases.addAll(b.args.subList(1, b.args.size())); + c.keywords.add(new Keyword("metaclass", b.args.get(0))); + } + + private static boolean lower(ClassDef c, Expr d, String q, String path) { + if ("six.add_metaclass".equals(q)) { + if (!(d instanceof Call) || ((Call) d).args.size() != 1 || !((Call) d).keywords.isEmpty() + || hasMetaclass(c) || ((Call) d).args.get(0) instanceof Node.Starred) { + return false; + } + c.keywords.add(new Keyword("metaclass", ((Call) d).args.get(0))); + return true; + } + if ("typing_extensions.deprecated".equals(q) || "warnings.deprecated".equals(q)) { + return deprecated(c, d); + } + if ("typing.runtime_checkable".equals(q) || "typing_extensions.runtime_checkable".equals(q)) { + return !(d instanceof Call) && runtimeCheckable(c); + } + if ("functools.total_ordering".equals(q)) { + return !(d instanceof Call) && totalOrdering(c, path); + } + return false; + } + + /// `@runtime_checkable` on a protocol only sets `_is_runtime_protocol` + /// (the structural check itself is ProtocolChecks'). On any other class + /// CPython raises, so the decorator stays. + private static boolean runtimeCheckable(ClassDef c) { + if (!ProtocolChecks.isProtocol(c)) { + return false; + } + for (Stmt s : c.body) { + if (binds(s, "_is_runtime_protocol")) { + return false; + } + } + Assign a = new Assign(new ArrayList(Collections.singletonList((Expr) new Name("_is_runtime_protocol"))), + new Constant(Constant.Kind.TRUE, "True")); + DataclassInit.atLine(a, c.line); + c.body.add(a); + return true; + } + + /// `@deprecated(msg, category=None)`: the decorator only stores `msg`. + private static boolean deprecated(ClassDef c, Expr d) { + if (!(d instanceof Call) || ((Call) d).args.size() != 1) { + return false; + } + Call k = (Call) d; + Expr msg = k.args.get(0); + if (!(msg instanceof Constant) || ((Constant) msg).kind != Constant.Kind.STR) { + return false; + } + boolean noCategory = false; + for (Keyword kw : k.keywords) { + if ("category".equals(kw.arg) && kw.value instanceof Constant + && ((Constant) kw.value).kind == Constant.Kind.NONE) { + noCategory = true; + } else if (!"stacklevel".equals(kw.arg) || !(kw.value instanceof Constant)) { + return false; + } + } + if (!noCategory) { + return false; + } + for (Stmt s : c.body) { + if (binds(s, "__deprecated__")) { + return false; + } + } + Assign a = new Assign(new ArrayList(Collections.singletonList((Expr) new Name("__deprecated__"))), msg); + DataclassInit.atLine(a, c.line); + c.body.add(a); + return true; + } + + private static boolean binds(Stmt s, String name) { + if (s instanceof FunctionDef) { + return name.equals(((FunctionDef) s).name); + } + if (s instanceof ClassDef) { + return name.equals(((ClassDef) s).name); + } + if (s instanceof Assign) { + for (Expr t : ((Assign) s).targets) { + if (!(t instanceof Name) || name.equals(((Name) t).id)) { + return true; + } + } + return false; + } + // Anything else that could bind a name in the body: be safe. + return !(s instanceof Node.ExprStmt || s instanceof Node.Pass || s instanceof Node.AnnAssign); + } + + /// `@total_ordering` on a class with no base whose body defines its roots + /// as plain methods: the stdlib's choice of root and its formulas. + private static boolean totalOrdering(ClassDef c, String path) { + if (!c.bases.isEmpty() || !c.keywords.isEmpty()) { + return false; + } + Set roots = new HashSet(); + for (Stmt s : c.body) { + for (String op : ORDER) { + if (binds(s, op)) { + if (!(s instanceof FunctionDef) || !((FunctionDef) s).decorators.isEmpty()) { + return false; + } + roots.add(op); + } + } + } + String root = null; + for (String op : ORDER) { + if (roots.contains(op)) { + root = op; + break; + } + } + if (root == null) { + return false; + } + String lt; + if ("__lt__".equals(root)) { + lt = "r"; + } else if ("__le__".equals(root)) { + lt = "r and self != other"; + } else if ("__gt__".equals(root)) { + lt = "not r and self != other"; + } else { + lt = "not r"; + } + for (String op : ORDER) { + if (roots.contains(op)) { + continue; + } + String ret; + if ("__lt__".equals(op)) { + ret = "lt"; + } else if ("__le__".equals(op)) { + ret = "lt or self == other"; + } else if ("__gt__".equals(op)) { + ret = "not lt and self != other"; + } else { + ret = "not lt"; + } + String src = "def " + op + "(self, other):\n" + + " r = self." + root + "(other)\n" + + " if r is NotImplemented:\n" + + " return r\n" + + " lt = " + lt + "\n" + + " return " + ret + "\n"; + FunctionDef f = ConstArgSpecialize.parseMethod(src, c.line, path); + DataclassInit.atLine(f, c.line); + c.body.add(f); + } + return true; + } +} diff --git a/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/ClassPathReader.java b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/ClassPathReader.java index d83731a5420..3ef25521e91 100644 --- a/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/ClassPathReader.java +++ b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/ClassPathReader.java @@ -138,6 +138,93 @@ public ClassInfo find(String name) { return c; } + /// Every string in the constant pools of the classes under `prefix` + /// (`com/codename1/python/`) that could be a Python name, or null + /// when the class path has no class there. These are the names such + /// classes may look up in a module or on an object. + public java.util.Set names(String prefix) throws IOException { + java.util.Set out = new java.util.HashSet(); + boolean any = false; + for (Object r : roots) { + if (r instanceof File) { + File d = new File((File) r, prefix); + if (d.isDirectory()) { + try (java.util.stream.Stream w = Files.walk(d.toPath())) { + for (Path c : (Iterable) w::iterator) { + if (c.toString().endsWith(".class")) { + poolNames(Files.readAllBytes(c), out); + any = true; + } + } + } + } + } else { + ZipFile z = (ZipFile) r; // NOPMD CloseResource - a class path root, closed by close() + java.util.Enumeration en = z.entries(); + while (en.hasMoreElements()) { + ZipEntry e = en.nextElement(); + if (e.getName().startsWith(prefix) && e.getName().endsWith(".class")) { + try (InputStream in = z.getInputStream(e)) { + poolNames(readAll(in), out); + any = true; + } + } + } + } + } + return any ? out : null; + } + + private static void poolNames(byte[] b, java.util.Set out) throws IOException { + DataInputStream in = new DataInputStream(new java.io.ByteArrayInputStream(b)); + if (in.readInt() != 0xCAFEBABE) { + return; + } + in.readInt(); + int n = in.readUnsignedShort(); + for (int i = 1; i < n; i++) { + int tag = in.readUnsignedByte(); + switch (tag) { + case 1: + String u = in.readUTF(); + if (identifier(u)) { + out.add(u); + } + break; + case 7: case 8: case 16: case 19: case 20: + in.readUnsignedShort(); + break; + case 3: case 4: case 9: case 10: case 11: case 12: case 17: case 18: + in.readInt(); + break; + case 5: case 6: + in.readLong(); + i++; + break; + case 15: + in.readUnsignedByte(); + in.readUnsignedShort(); + break; + default: + throw new IOException("unknown constant pool tag " + tag); + } + } + } + + private static boolean identifier(String u) { + if (u.isEmpty() || u.length() > 80) { + return false; + } + for (int i = 0; i < u.length(); i++) { + char c = u.charAt(i); + boolean ok = c == '_' || c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || i > 0 && c >= '0' && c <= '9'; + if (!ok) { + return false; + } + } + return true; + } + private byte[] bytes(String path) throws IOException { byte[] b = fromRoots(path); if (b != null) { diff --git a/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/Closed.java b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/Closed.java deleted file mode 100644 index 4ea535601cd..00000000000 --- a/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/Closed.java +++ /dev/null @@ -1,160 +0,0 @@ -/* - * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Codename One designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Codename One through http://www.codenameone.com/ if you - * need additional information or have any questions. - */ -package com.codename1.python.transpiler.codegen; - -import com.codename1.python.transpiler.ast.Node.*; - -import java.util.Arrays; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -/// The whole-program check that lets `Infer` type a program at all. -/// -/// The transpiler sees every module of the application, so it can tell -/// whether anything in it does what would make static types unsound: -/// change a class or an instance through a name the compiler cannot see, -/// reach a module's globals from outside, or run code it never compiled. -/// One such use anywhere turns typing off for the whole program -- the -/// generic code stays, and is correct for all of it. -public final class Closed { - private static final Set CALLS = new HashSet(Arrays.asList("setattr", "delattr", "vars", - "globals", "locals", "exec", "eval", "compile", "__import__")); - private static final Set ATTRS = new HashSet(Arrays.asList("__dict__", "__class__", - "__setattr__", "__getattribute__", "__delattr__", "__new__", "__bases__", "__mro__", "__globals__", - "__code__", "__defaults__", "__closure__", "__init_subclass__", "__set_name__", "__slots__")); - private static final Set MODULES = new HashSet(Arrays.asList("copy", "pickle", "importlib", - "inspect", "ctypes", "types", "gc", "builtins", "abc", "dataclasses", "weakref")); - - private boolean open; - - private Closed() { - } - - /// Whether the program made of `modules` is closed. - public static boolean check(List> modules) { - Closed c = new Closed(); - for (List m : modules) { - Set classes = new HashSet(); - for (Stmt s : m) { - if (s instanceof ClassDef) { - classes.add(((ClassDef) s).name); - } else if (s instanceof Import) { - // A module object: stores through it reach its globals. - for (Alias a : ((Import) s).names) { - classes.add(a.asname != null ? a.asname : root(a.name)); - } - } - } - c.scan(m, classes); - } - return !c.open; - } - - private void scan(Object o, Set classes) { - if (open) { - return; - } - if (o instanceof Name && CALLS.contains(((Name) o).id)) { - // `type` is fine with one argument; the three-argument form makes a class. - open = true; - return; - } - if (o instanceof Call && ((Call) o).func instanceof Name && "type".equals(((Name) ((Call) o).func).id) - && ((Call) o).args.size() != 1) { - open = true; - return; - } - if (o instanceof Attribute && ATTRS.contains(((Attribute) o).attr)) { - open = true; - return; - } - if (o instanceof Delete) { - for (Expr t : ((Delete) o).targets) { - if (t instanceof Attribute) { - open = true; - return; - } - } - } - if (o instanceof Import) { - for (Alias a : ((Import) o).names) { - open |= MODULES.contains(root(a.name)); - } - } else if (o instanceof ImportFrom) { - ImportFrom f = (ImportFrom) o; - open |= f.module != null && MODULES.contains(root(f.module)); - } - if (o instanceof Assign || o instanceof AugAssign || o instanceof AnnAssign) { - // A store onto anything but a plain local name or `x.attr` where - // x is not a module or class: `mod.x = ...` reaches another - // module's globals, `Cls.x = ...` changes a class. - List targets = o instanceof Assign ? ((Assign) o).targets - : Arrays.asList(o instanceof AugAssign ? ((AugAssign) o).target : ((AnnAssign) o).target); - for (Expr t : targets) { - attrTargets(t, classes); - } - } - if (o instanceof ClassDef) { - ClassDef c = (ClassDef) o; - for (Expr b : c.bases) { - // Subclassing a class of another module, or anything - // computed, is a class the module's own analysis cannot see. - if (!(b instanceof Name) || !classes.contains(((Name) b).id) && !builtinBase(((Name) b).id)) { - open = true; - } - } - // A class decorator gets the class to change as it pleases. - open |= !c.keywords.isEmpty() || !c.decorators.isEmpty(); - } - Infer.children(o, x -> scan(x, classes)); - } - - private void attrTargets(Expr t, Set classes) { - if (t instanceof Attribute) { - Expr v = ((Attribute) t).value; - // A store through any other expression is a store on an instance. - open |= v instanceof Name && classes.contains(((Name) v).id); - } else if (t instanceof TupleExpr) { - for (Expr e : ((TupleExpr) t).elts) { - attrTargets(e, classes); - } - } else if (t instanceof ListExpr) { - for (Expr e : ((ListExpr) t).elts) { - attrTargets(e, classes); - } - } else if (t instanceof Starred) { - attrTargets(((Starred) t).value, classes); - } - } - - private static boolean builtinBase(String n) { - return "object".equals(n) || n.endsWith("Error") || "Exception".equals(n); - } - - private static String root(String dotted) { - int d = dotted.indexOf('.'); - return d < 0 ? dotted : dotted.substring(0, d); - } -} diff --git a/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/ClosedNameSetattr.java b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/ClosedNameSetattr.java new file mode 100644 index 00000000000..b5faf292df2 --- /dev/null +++ b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/ClosedNameSetattr.java @@ -0,0 +1,449 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.python.transpiler.codegen; + +import com.codename1.python.transpiler.ast.Node; +import com.codename1.python.transpiler.ast.Node.Alias; +import com.codename1.python.transpiler.ast.Node.Arg; +import com.codename1.python.transpiler.ast.Node.Arguments; +import com.codename1.python.transpiler.ast.Node.Assign; +import com.codename1.python.transpiler.ast.Node.Call; +import com.codename1.python.transpiler.ast.Node.ClassDef; +import com.codename1.python.transpiler.ast.Node.Compare; +import com.codename1.python.transpiler.ast.Node.Constant; +import com.codename1.python.transpiler.ast.Node.DictExpr; +import com.codename1.python.transpiler.ast.Node.Expr; +import com.codename1.python.transpiler.ast.Node.ExprStmt; +import com.codename1.python.transpiler.ast.Node.FunctionDef; +import com.codename1.python.transpiler.ast.Node.If; +import com.codename1.python.transpiler.ast.Node.Name; +import com.codename1.python.transpiler.ast.Node.Stmt; +import com.codename1.python.transpiler.ast.Node.Subscript; +import com.codename1.python.transpiler.ast.Node.TupleExpr; + +import java.util.ArrayList; +import java.util.IdentityHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/// `setattr(obj, prop[0], value)` where, in one function, `prop = table[k]` +/// is the only binding of `prop` and `table = {k1: ("name1", ...), ...}` +/// the only binding of `table`, and both names are only ever read by +/// subscript (or tested with `in`): the name stored is one of the literals +/// at that index of the table's tuples, a set closed at build time. Every +/// row of the table gets one more element, `lambda v: setattr(obj, +/// "name1", v)`, built from its own literal, and the statement becomes +/// `prop[](value)`: the row the data selects carries its own +/// store, so nothing compares attribute names at run time. openpyxl's +/// `WorkSheetParser.parse` stores each parsed property element under the +/// attribute its table names. +/// +/// A dict literal cannot change while nothing stores into it, deletes from +/// it or passes it anywhere, which the "only read by subscript" rule +/// enforces; a tuple never changes. Any other use of either name, a row +/// read other than by an int index below the original length, a second +/// binding anywhere in the function (nested scopes included), a parameter, +/// `global`/`nonlocal`, an `obj` that is not an unrebound parameter, or a +/// module binding `setattr` leaves the call as it is. +public final class ClosedNameSetattr { + private ClosedNameSetattr() { + } + + public static void rewrite(Map trees) { + for (Node.Module m : trees.values()) { + if (bindsName(m.body, "setattr")) { + continue; + } + functions(m, new ArrayList()).forEach(ClosedNameSetattr::rewrite); + } + } + + private static List functions(Object o, List out) { + if (o instanceof FunctionDef) { + out.add((FunctionDef) o); + } + Infer.children(o, x -> functions(x, out)); + return out; + } + + private static boolean bindsName(Object o, String n) { + boolean[] r = new boolean[1]; + scanBindings(o, n, r); + return r[0]; + } + + /// Whether anything in `o` other than a plain assignment binds `n`. + private static void scanBindings(Object o, String n, boolean[] r) { + if (r[0]) { + return; + } + if (o instanceof FunctionDef && ((FunctionDef) o).name.equals(n) + || o instanceof ClassDef && ((ClassDef) o).name.equals(n) + || o instanceof Node.ExceptHandler && n.equals(((Node.ExceptHandler) o).name) + || o instanceof Alias && n.equals(((Alias) o).asname != null ? ((Alias) o).asname : ((Alias) o).name) + || o instanceof Node.Global && ((Node.Global) o).names.contains(n) + || o instanceof Arguments && ((Arguments) o).names().contains(n)) { + r[0] = true; + return; + } + if (o instanceof Assign) { + for (Expr t : ((Assign) o).targets) { + if (t instanceof Name && ((Name) t).id.equals(n)) { + r[0] = true; + return; + } + } + } + Infer.children(o, x -> scanBindings(x, n, r)); + } + + private static void rewrite(FunctionDef f) { + List calls = new ArrayList(); + collectCalls(f.body, calls); + Map slots = new java.util.HashMap(); + Map done = new IdentityHashMap(); + for (ExprStmt s : calls) { + Call c = (Call) s.value; + Subscript nameExpr = (Subscript) c.args.get(1); + String prop = ((Name) nameExpr.value).id; + int idx = Integer.parseInt(((Constant) nameExpr.index).text); + if (!(c.args.get(0) instanceof Name)) { + continue; + } + String obj = ((Name) c.args.get(0)).id; + DictExpr d = table(f, prop, idx, obj); + if (d == null) { + continue; + } + String key = prop + "|" + idx + "|" + obj; + Integer slot = slots.get(key); + if (slot == null) { + slot = ((TupleExpr) d.values.get(0)).elts.size(); + for (Expr v : d.values) { + String attr = ((Constant) ((TupleExpr) v).elts.get(idx)).text; + ((TupleExpr) v).elts.add(setter(obj, attr, v)); + } + slots.put(key, slot); + } + Call call = new Call(new Subscript(new Name(prop).at(c.line, c.col), + new Constant(Constant.Kind.INT, String.valueOf(slot)).at(c.line, c.col)) + .at(c.line, c.col)).at(c.line, c.col); + call.args.add(c.args.get(2)); + done.put(s, new ExprStmt(call).at(s.line, s.col)); + } + if (!done.isEmpty()) { + replace(f.body, done); + } + } + + /// `lambda v: setattr(obj, "attr", v)`: the store of one table row, + /// spelled with its literal name. + private static Node.Lambda setter(String obj, String attr, Expr at) { + Arguments a = new Arguments(); + a.positional.add(new Arg("v", null)); + Call store = new Call(new Name("setattr").at(at.line, at.col)).at(at.line, at.col); + store.args.add(new Name(obj).at(at.line, at.col)); + store.args.add(new Constant(Constant.Kind.STR, attr).at(at.line, at.col)); + store.args.add(new Name("v").at(at.line, at.col)); + Node.Lambda l = new Node.Lambda(a, store); + l.at(at.line, at.col); + return l; + } + + /// Replaces each statement of `done` in `l` and the statement lists + /// nested in it (the calls were collected outside nested scopes). + private static void replace(List l, Map done) { + for (int i = 0; i < l.size(); i++) { + Stmt st = l.get(i); + Stmt r = st instanceof ExprStmt ? done.get(st) : null; + if (r != null) { + l.set(i, r); + } else if (st instanceof If) { + replace(((If) st).body, done); + replace(((If) st).orelse, done); + } else if (st instanceof Node.For) { + replace(((Node.For) st).body, done); + replace(((Node.For) st).orelse, done); + } else if (st instanceof Node.While) { + replace(((Node.While) st).body, done); + replace(((Node.While) st).orelse, done); + } else if (st instanceof Node.With) { + replace(((Node.With) st).body, done); + } else if (st instanceof Node.Try) { + replace(((Node.Try) st).body, done); + for (Node.ExceptHandler h : ((Node.Try) st).handlers) { + replace(h.body, done); + } + replace(((Node.Try) st).orelse, done); + replace(((Node.Try) st).finalbody, done); + } else if (st instanceof Node.Match) { + for (Node.MatchCase c : ((Node.Match) st).cases) { + replace(c.body, done); + } + } + } + } + + /// Every `setattr(a, p[], b)` statement, skipping nested scopes. + private static void collectCalls(Object o, List out) { + if (o instanceof FunctionDef || o instanceof ClassDef || o instanceof Node.Lambda) { + return; + } + if (o instanceof ExprStmt && ((ExprStmt) o).value instanceof Call) { + Call c = (Call) ((ExprStmt) o).value; + if (c.func instanceof Name && "setattr".equals(((Name) c.func).id) && c.args.size() == 3 + && c.keywords.isEmpty() && c.args.get(1) instanceof Subscript + && ((Subscript) c.args.get(1)).value instanceof Name + && ((Subscript) c.args.get(1)).index instanceof Constant + && ((Constant) ((Subscript) c.args.get(1)).index).kind == Constant.Kind.INT + && ((Constant) ((Subscript) c.args.get(1)).index).text.matches("[0-9]{1,3}") + && noStarred(c)) { + out.add((ExprStmt) o); + } + } + Infer.children(o, x -> collectCalls(x, out)); + } + + private static boolean noStarred(Call c) { + for (Expr a : c.args) { + if (a instanceof Node.Starred) { + return false; + } + } + return true; + } + + /// The table `prop` is read from when `prop[idx]` is always one of the + /// literal attribute names at `idx` of its rows, every row has the same + /// length, `prop` is only ever subscripted by an int below that length, + /// the table only by `prop`'s one binding (or tested with `in`), and + /// `obj` is a parameter `f` never rebinds. Then a setter appended to + /// every row cannot be seen by anything but the rewritten call, and + /// `obj` names the same object when the table is built as when the + /// call runs. Otherwise null. + private static DictExpr table(FunctionDef f, String prop, int idx, String obj) { + if (f.args.names().contains(prop) || !f.args.names().contains(obj) + || obj.equals(prop) || rebinds(f, obj)) { + return null; + } + Assign pa = soleAssign(f, prop); + if (pa == null || !(pa.value instanceof Subscript) || !(((Subscript) pa.value).value instanceof Name)) { + return null; + } + String table = ((Name) ((Subscript) pa.value).value).id; + if (table.equals(prop) || table.equals(obj) || f.args.names().contains(table)) { + return null; + } + Assign ta = soleAssign(f, table); + if (ta == null || !(ta.value instanceof DictExpr) || !readOnly(f, prop, pa) || !readOnly(f, table, ta)) { + return null; + } + DictExpr d = (DictExpr) ta.value; + if (d.values.isEmpty()) { + return null; + } + int len = -1; + for (int i = 0; i < d.values.size(); i++) { + Expr v = d.values.get(i); + if (d.keys.get(i) == null || !(v instanceof TupleExpr) || ((TupleExpr) v).elts.size() <= idx) { + return null; + } + List elts = ((TupleExpr) v).elts; + if (len >= 0 && elts.size() != len) { + return null; + } + len = elts.size(); + for (Expr e : elts) { + if (e instanceof Node.Starred) { + return null; + } + } + Expr e = elts.get(idx); + if (!(e instanceof Constant) || ((Constant) e).kind != Constant.Kind.STR + || !((Constant) e).text.matches("[A-Za-z_][A-Za-z0-9_]*")) { + return null; + } + } + List subs = new ArrayList(); + subscripts(f.body, prop, subs); + for (Subscript sub : subs) { + if (!(sub.index instanceof Constant) || ((Constant) sub.index).kind != Constant.Kind.INT + || !((Constant) sub.index).text.matches("[0-9]{1,3}") + || Integer.parseInt(((Constant) sub.index).text) >= len) { + return null; + } + } + subs.clear(); + subscripts(f.body, table, subs); + if (subs.size() != 1 || subs.get(0) != pa.value) { //NOPMD CompareObjectsWithEquals - identity is meant + return null; + } + return d; + } + + /// Whether anything in `f` binds `n` (its parameters aside). + private static boolean rebinds(FunctionDef f, String n) { + List found = new ArrayList(); + boolean[] other = new boolean[1]; + sole(f.body, n, found, other); + return other[0] || !found.isEmpty(); + } + + /// Every subscript of the name `n` in `o`. + private static void subscripts(Object o, String n, List out) { + if (o instanceof Subscript && ((Subscript) o).value instanceof Name + && ((Name) ((Subscript) o).value).id.equals(n)) { + out.add((Subscript) o); + } + Infer.children(o, x -> subscripts(x, n, out)); + } + + /// The one `n = ...` of `f` when nothing else in it binds `n`. + private static Assign soleAssign(FunctionDef f, String n) { + List found = new ArrayList(); + boolean[] other = new boolean[1]; + sole(f.body, n, found, other); + return other[0] || found.size() != 1 ? null : found.get(0); + } + + private static void sole(Object o, String n, List found, boolean[] other) { + if (o instanceof Assign && ((Assign) o).targets.size() == 1 && ((Assign) o).targets.get(0) instanceof Name + && ((Name) ((Assign) o).targets.get(0)).id.equals(n)) { + found.add((Assign) o); + Infer.children(((Assign) o).value, x -> sole(x, n, found, other)); + return; + } + if (o instanceof Assign) { + for (Expr t : ((Assign) o).targets) { + if (!(t instanceof Name) && bindsTarget(t, n)) { + other[0] = true; + } + } + } + if (o instanceof FunctionDef && (((FunctionDef) o).name.equals(n) || ((FunctionDef) o).args.names().contains(n)) + || o instanceof ClassDef && ((ClassDef) o).name.equals(n) + || o instanceof Node.ExceptHandler && n.equals(((Node.ExceptHandler) o).name) + || o instanceof Alias && n.equals(((Alias) o).asname != null ? ((Alias) o).asname : ((Alias) o).name) + || o instanceof Node.Global && ((Node.Global) o).names.contains(n) + || o instanceof Node.Lambda && ((Node.Lambda) o).args.names().contains(n) + || o instanceof Node.NamedExpr && ((Node.NamedExpr) o).target.id.equals(n) + || o instanceof Node.AugAssign && bindsTarget(((Node.AugAssign) o).target, n) + || o instanceof Node.AnnAssign && bindsTarget(((Node.AnnAssign) o).target, n) + || o instanceof Node.Delete && ((Node.Delete) o).targets.stream().anyMatch(t -> bindsTarget(t, n)) + || o instanceof Node.For && bindsTarget(((Node.For) o).target, n) + || o instanceof Node.Comprehension && bindsTarget(((Node.Comprehension) o).target, n) + || o instanceof Node.WithItem && ((Node.WithItem) o).vars != null && bindsTarget(((Node.WithItem) o).vars, n)) { + other[0] = true; + } + Infer.children(o, x -> sole(x, n, found, other)); + } + + private static boolean bindsTarget(Expr t, String n) { + if (t instanceof Name) { + return ((Name) t).id.equals(n); + } + if (t instanceof TupleExpr) { + for (Expr e : ((TupleExpr) t).elts) { + if (bindsTarget(e, n)) { + return true; + } + } + } + if (t instanceof Node.ListExpr) { + for (Expr e : ((Node.ListExpr) t).elts) { + if (bindsTarget(e, n)) { + return true; + } + } + } + return t instanceof Node.Starred && bindsTarget(((Node.Starred) t).value, n); + } + + /// Whether every occurrence of `n` in `f` other than `def`'s target is + /// the value of a subscript that is read, or the right side of `in`. + private static boolean readOnly(FunctionDef f, String n, Assign def) { + Set stores = java.util.Collections.newSetFromMap(new IdentityHashMap()); + targets(f.body, stores); + boolean[] bad = new boolean[1]; + uses(f.body, null, n, def.targets.get(0), stores, bad); + return !bad[0]; + } + + private static void targets(Object o, Set stores) { + if (o instanceof Assign) { + for (Expr t : ((Assign) o).targets) { + addTarget(t, stores); + } + } else if (o instanceof Node.AugAssign) { + addTarget(((Node.AugAssign) o).target, stores); + } else if (o instanceof Node.AnnAssign) { + addTarget(((Node.AnnAssign) o).target, stores); + } else if (o instanceof Node.Delete) { + for (Expr t : ((Node.Delete) o).targets) { + addTarget(t, stores); + } + } else if (o instanceof Node.For) { + addTarget(((Node.For) o).target, stores); + } else if (o instanceof Node.Comprehension) { + addTarget(((Node.Comprehension) o).target, stores); + } else if (o instanceof Node.WithItem && ((Node.WithItem) o).vars != null) { + addTarget(((Node.WithItem) o).vars, stores); + } + Infer.children(o, x -> targets(x, stores)); + } + + private static void addTarget(Expr t, Set stores) { + stores.add(t); + if (t instanceof TupleExpr) { + ((TupleExpr) t).elts.forEach(e -> addTarget(e, stores)); + } else if (t instanceof Node.ListExpr) { + ((Node.ListExpr) t).elts.forEach(e -> addTarget(e, stores)); + } else if (t instanceof Node.Starred) { + addTarget(((Node.Starred) t).value, stores); + } + } + + private static void uses(Object o, Object parent, String n, Expr def, Set stores, boolean[] bad) { + if (bad[0]) { + return; + } + if (o instanceof Name && ((Name) o).id.equals(n) && o != def) { //NOPMD CompareObjectsWithEquals - identity is meant + boolean ok = parent instanceof Subscript && ((Subscript) parent).value == o //NOPMD CompareObjectsWithEquals - identity is meant + && !stores.contains(parent); + if (!ok && parent instanceof Compare) { + Compare c = (Compare) parent; + int i = c.comparators.indexOf(o); + ok = i >= 0 && c.comparators.get(i) == o //NOPMD CompareObjectsWithEquals - identity is meant + && ("in".equals(c.ops.get(i)) || "not in".equals(c.ops.get(i))); + } + if (!ok) { + bad[0] = true; + } + return; + } + Object p = o instanceof List ? parent : o; + Infer.children(o, x -> uses(x, p, n, def, stores, bad)); + } +} diff --git a/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/CobbleLowering.java b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/CobbleLowering.java new file mode 100644 index 00000000000..c9210c95aaf --- /dev/null +++ b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/CobbleLowering.java @@ -0,0 +1,385 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.python.transpiler.codegen; + +import com.codename1.python.transpiler.ast.Node; +import com.codename1.python.transpiler.ast.Node.Alias; +import com.codename1.python.transpiler.ast.Node.Assign; +import com.codename1.python.transpiler.ast.Node.Attribute; +import com.codename1.python.transpiler.ast.Node.Call; +import com.codename1.python.transpiler.ast.Node.ClassDef; +import com.codename1.python.transpiler.ast.Node.Constant; +import com.codename1.python.transpiler.ast.Node.Expr; +import com.codename1.python.transpiler.ast.Node.FunctionDef; +import com.codename1.python.transpiler.ast.Node.Import; +import com.codename1.python.transpiler.ast.Node.ImportFrom; +import com.codename1.python.transpiler.ast.Node.Keyword; +import com.codename1.python.transpiler.ast.Node.Name; +import com.codename1.python.transpiler.ast.Node.Stmt; +import com.codename1.python.transpiler.parser.Parser; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/// Lowers cobble's class decorators at build time. +/// +/// `@cobble.data` finds the class's `cobble.field()` attributes and writes +/// `__init__`, `__repr__`, `__eq__`, `__ne__` and `__hash__` over them, and +/// `@cobble.visitable` (which `data` implies) gives the class the +/// `_accept0`/`_accept1` methods a `cobble.visitor` dispatches through. The +/// real package makes them all at run time from the field names, with +/// computed `getattr`/`setattr`; here every name is static, the methods are +/// ordinary members of the class body, the decorator is dropped and the class +/// keeps a layout. `cobble.copy` calls the generated `_cobble_copy`, which +/// takes one keyword per field and reads every field not passed off `self`. +/// +/// A class this cannot read exactly -- a base defined in another module, a +/// field call with arguments other than `default=None`, a required field +/// after an optional one -- keeps its decorator, so strict mode still refuses +/// it rather than compiling a guess. +public final class CobbleLowering { + private static final String UNDEFINED = "_cn1_cobble_undefined"; + + private CobbleLowering() { + } + + /// Rewrites the cobble classes of `tree`, the module at path `path`. + public static void rewrite(Node.Module tree, String path) { + Set modules = new HashSet(); + Set dataNames = new HashSet(); + Set visitableNames = new HashSet(); + Set fieldNames = new HashSet(); + for (Stmt s : tree.body) { + if (s instanceof Import) { + for (Alias a : ((Import) s).names) { + if ("cobble".equals(a.name)) { + modules.add(a.asname != null ? a.asname : a.name); + } + } + } else if (s instanceof ImportFrom && "cobble".equals(((ImportFrom) s).module) + && ((ImportFrom) s).level == 0) { + for (Alias a : ((ImportFrom) s).names) { + String bound = a.asname != null ? a.asname : a.name; + if ("data".equals(a.name)) { + dataNames.add(bound); + } else if ("visitable".equals(a.name)) { + visitableNames.add(bound); + } else if ("field".equals(a.name)) { + fieldNames.add(bound); + } + } + } + } + if (modules.isEmpty() && dataNames.isEmpty() && visitableNames.isEmpty()) { + return; + } + Map bindings = new HashMap(); + for (Stmt s : tree.body) { + DataclassInit.count(s, bindings); + } + List> all = new ArrayList>(); + all.add(modules); + all.add(dataNames); + all.add(visitableNames); + all.add(fieldNames); + for (Set names : all) { + for (String n : names) { + if (bindings.getOrDefault(n, 0) != 1) { + return; + } + } + } + Map classes = new HashMap(); + for (Stmt s : tree.body) { + if (s instanceof ClassDef) { + classes.put(((ClassDef) s).name, (ClassDef) s); + } + } + if (!modules.isEmpty()) { + visitorBases(tree, path, modules.iterator().next()); + } + Map> fieldsOf = new HashMap>(); + Stmt marker = null; + for (Stmt s : tree.body) { + if (!(s instanceof ClassDef)) { + continue; + } + ClassDef c = (ClassDef) s; + if (c.decorators.size() != 1 || !c.keywords.isEmpty()) { + continue; + } + Expr d = c.decorators.get(0); + boolean data = is(d, "data", dataNames, modules); + boolean visitable = is(d, "visitable", visitableNames, modules); + if (!data && !visitable) { + continue; + } + List fields = null; + if (data) { + fields = fields(c, classes, fieldsOf, fieldNames, modules, new HashSet()); + if (fields == null || !trailingDefaults(fields)) { + continue; + } + } + lower(c, path, data, fields, fieldNames, modules); + if (data && marker == null) { + marker = (Stmt) Parser.parse("from cobble import _undefined as " + UNDEFINED + "\n", path).body.get(0); + DataclassInit.atLine(marker, c.line); + } + } + if (marker != null) { + int i = 0; + while (i < tree.body.size() && (tree.body.get(i) instanceof ImportFrom + && "__future__".equals(((ImportFrom) tree.body.get(i)).module) + || i == 0 && tree.body.get(i) instanceof Node.ExprStmt)) { + i++; + } + tree.body.add(i, marker); + } + } + + /// `X = cobble.visitor(Base, ...)` at module level becomes + /// `class X(cobble._Visitor): pass`, and a class base written as that + /// call becomes `cobble._Visitor`: every visitor is the one runtime class, + /// so a class built on one has a base with a layout instead of a call + /// result. + private static void visitorBases(Node.Module tree, String path, String module) { + Set none = new HashSet(); + for (int i = 0; i < tree.body.size(); i++) { + Stmt s = tree.body.get(i); + if (s instanceof Assign && ((Assign) s).targets.size() == 1 + && ((Assign) s).targets.get(0) instanceof Name && ((Assign) s).value instanceof Call + && is(((Call) ((Assign) s).value).func, "visitor", none, java.util.Collections.singleton(module))) { + String n = ((Name) ((Assign) s).targets.get(0)).id; + Stmt c = Parser.parse("class " + n + "(" + module + "._Visitor):\n pass\n", path).body.get(0); + DataclassInit.atLine(c, s.line); + tree.body.set(i, c); + } else if (s instanceof ClassDef) { + List bases = ((ClassDef) s).bases; + for (int b = 0; b < bases.size(); b++) { + if (bases.get(b) instanceof Call + && is(((Call) bases.get(b)).func, "visitor", none, java.util.Collections.singleton(module))) { + Expr e = ((Assign) Parser.parse("x = " + module + "._Visitor\n", path).body.get(0)).value; + DataclassInit.atLine(e, s.line); + bases.set(b, e); + } + } + } + } + } + + private static boolean is(Expr e, String attr, Set names, Set modules) { + return e instanceof Name && names.contains(((Name) e).id) + || e instanceof Attribute && attr.equals(((Attribute) e).attr) + && ((Attribute) e).value instanceof Name && modules.contains(((Name) ((Attribute) e).value).id); + } + + /// The `{name, "1" when it defaults to None}` pairs of `c` in cobble's + /// order: inherited fields (from bases defined earlier) first, then the + /// class's own in source order. Null when they cannot be known. + private static List fields(ClassDef c, Map classes, + Map> cache, Set fieldNames, Set modules, Set seen) { + List known = cache.get(c.name); + if (known != null) { + return known; + } + if (!seen.add(c.name)) { + return null; + } + List out = new ArrayList(); + Set names = new HashSet(); + for (Expr b : c.bases) { + if (b instanceof Name && "object".equals(((Name) b).id)) { + continue; + } + if (!(b instanceof Name) || !classes.containsKey(((Name) b).id)) { + return null; + } + List inherited = fields(classes.get(((Name) b).id), classes, cache, fieldNames, modules, seen); + if (inherited == null) { + return null; + } + for (String[] f : inherited) { + if (names.add(f[0])) { + out.add(f); + } + } + } + for (Stmt s : c.body) { + if (!(s instanceof Assign)) { + continue; + } + Assign a = (Assign) s; + if (!(a.value instanceof Call) || !is(((Call) a.value).func, "field", fieldNames, modules)) { + continue; + } + Call call = (Call) a.value; + if (a.targets.size() != 1 || !(a.targets.get(0) instanceof Name) || !call.args.isEmpty()) { + return null; + } + boolean optional = false; + for (Keyword k : call.keywords) { + if (!"default".equals(k.arg) || !(k.value instanceof Constant) + || ((Constant) k.value).kind != Constant.Kind.NONE) { + return null; + } + optional = true; + } + String n = ((Name) a.targets.get(0)).id; + if (!names.add(n)) { + return null; + } + out.add(new String[] {n, optional ? "1" : null}); + } + cache.put(c.name, out); + return out; + } + + private static boolean trailingDefaults(List fields) { + boolean optional = false; + for (String[] f : fields) { + if (f[1] != null) { + optional = true; + } else if (optional) { + return false; + } + } + return true; + } + + private static void lower(ClassDef c, String path, boolean data, List fields, + Set fieldNames, Set modules) { + Set defined = new HashSet(); + for (Stmt s : c.body) { + if (s instanceof FunctionDef) { + defined.add(((FunctionDef) s).name); + } + } + StringBuilder src = new StringBuilder(); + if (data) { + List keep = new ArrayList(); + for (Stmt s : c.body) { + if (s instanceof Assign && ((Assign) s).value instanceof Call + && is(((Call) ((Assign) s).value).func, "field", fieldNames, modules)) { + continue; + } + keep.add(s); + } + c.body.clear(); + c.body.addAll(keep); + src.append("def __init__(self"); + for (String[] f : fields) { + src.append(", ").append(f[0]).append(f[1] != null ? "=None" : ""); + } + src.append("):\n"); + for (String[] f : fields) { + src.append(" self.").append(f[0]).append(" = ").append(f[0]).append('\n'); + } + if (fields.isEmpty()) { + src.append(" pass\n"); + } + src.append("def __repr__(self):\n return \"").append(c.name).append("(\""); + for (int i = 0; i < fields.size(); i++) { + String n = fields.get(i)[0]; + src.append(" + \"").append(i == 0 ? "" : ", ").append(n).append("=\" + repr(self.").append(n) + .append(')'); + } + src.append(" + \")\"\n"); + src.append("def __eq__(self, other):\n if not isinstance(other, ").append(c.name) + .append("):\n return False\n"); + for (String[] f : fields) { + src.append(" if not (self.").append(f[0]).append(" == other.").append(f[0]) + .append("):\n return False\n"); + } + src.append(" return True\n"); + src.append("def __ne__(self, other):\n return not (self == other)\n"); + src.append("def __hash__(self):\n return hash((").append(c.name); + for (String[] f : fields) { + src.append(", self.").append(f[0]); + } + src.append("))\n"); + // One keyword per field, defaulting to a marker: a field not + // passed is read straight off self, with no dict of the + // attributes built, updated and splatted back. + src.append("def _cobble_copy(self"); + if (!fields.isEmpty()) { + src.append(", *"); + } + for (String[] f : fields) { + src.append(", ").append(f[0]).append('=').append(UNDEFINED); + } + src.append("):\n return type(self)("); + for (int i = 0; i < fields.size(); i++) { + String n = fields.get(i)[0]; + src.append(i == 0 ? "" : ", ").append(n).append("=self.").append(n).append(" if ").append(n) + .append(" is ").append(UNDEFINED).append(" else ").append(n); + } + src.append(")\n"); + } + String visit = "visit_" + underscore(c.name); + if (!defined.contains("_accept0")) { + src.append("def _accept0(self, visitor):\n return visitor.").append(visit).append("(self)\n"); + } + if (!defined.contains("_accept1")) { + src.append("def _accept1(self, visitor, arg0):\n return visitor.").append(visit) + .append("(self, arg0)\n"); + } + int line = c.body.isEmpty() ? c.line : c.body.get(c.body.size() - 1).line; + for (Stmt s : Parser.parse(src.toString(), path).body) { + DataclassInit.atLine(s, line); + c.body.add(s); + } + c.decorators.clear(); + } + + /// cobble's `_underscore`: CamelCase to snake_case for visitor names. + static String underscore(String word) { + StringBuilder out = new StringBuilder(); + for (int i = 0; i < word.length(); i++) { + char ch = word.charAt(i); + if (ch >= 'A' && ch <= 'Z') { + if (i > 0) { + char prev = word.charAt(i - 1); + boolean prevLower = prev >= 'a' && prev <= 'z'; + boolean prevDigit = prev >= '0' && prev <= '9'; + boolean prevUpper = prev >= 'A' && prev <= 'Z'; + boolean nextLower = i + 1 < word.length() && word.charAt(i + 1) >= 'a' + && word.charAt(i + 1) <= 'z'; + if (prevLower || prevDigit || nextLower && prevUpper) { + out.append('_'); + } + } + out.append((char) (ch - 'A' + 'a')); + } else if (ch == '-') { + out.append('_'); + } else { + out.append(ch); + } + } + return out.toString(); + } +} diff --git a/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/ColorValueLowering.java b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/ColorValueLowering.java new file mode 100644 index 00000000000..78d14c6fde7 --- /dev/null +++ b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/ColorValueLowering.java @@ -0,0 +1,249 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.python.transpiler.codegen; + +import com.codename1.python.transpiler.ast.Node; +import com.codename1.python.transpiler.ast.Node.Assign; +import com.codename1.python.transpiler.ast.Node.Attribute; +import com.codename1.python.transpiler.ast.Node.ClassDef; +import com.codename1.python.transpiler.ast.Node.Constant; +import com.codename1.python.transpiler.ast.Node.Expr; +import com.codename1.python.transpiler.ast.Node.FunctionDef; +import com.codename1.python.transpiler.ast.Node.Name; +import com.codename1.python.transpiler.ast.Node.Stmt; +import com.codename1.python.transpiler.parser.Parser; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/// Lowers openpyxl's `Color.value` (`styles/colors.py`), which reads and +/// writes whichever field `self.type` names: `getattr(self, self.type)`. +/// +/// Every store of a literal `self.type = 'rgb'` in `__init__` is followed by +/// a reader and a writer closure over that one field (`lambda o: o.rgb`, and +/// a `setattr` with the literal name), and `value` calls the pair. Any other +/// store of `type` -- from anywhere in the program, on a receiver of any +/// static type -- goes through the property setter [DeclarativeMap] wrote +/// for the `String()` field, so that setter first clears the pair: `value` +/// then raises `TypeError` instead of reading a field the data no longer +/// selects. No attribute name is compared at run time. +/// +/// Runs after [DeclarativeMap]. If `type` was not lowered to a property +/// (a store could then bypass the hook), or anything has another shape, +/// nothing is changed. +public final class ColorValueLowering { + + private static final String PATH = "openpyxl/styles/colors.py"; + private static final String GET = "_cn1_value_get"; + private static final String SET = "_cn1_value_set"; + + private ColorValueLowering() { + } + + public static void rewrite(Map trees) { + for (Map.Entry e : trees.entrySet()) { + if (e.getKey().endsWith(PATH)) { + List body = e.getValue().body; + for (int i = 0; i < body.size(); i++) { + if (body.get(i) instanceof ClassDef && "Color".equals(((ClassDef) body.get(i)).name)) { + lower(body, i, e.getKey()); + return; + } + } + } + } + } + + private static boolean decoratedWith(FunctionDef f, String owner, String attr) { + if (f.decorators.size() != 1) { + return false; + } + Expr d = f.decorators.get(0); + if (attr == null) { + return d instanceof Name && ("property".equals(((Name) d).id) + || Infer.PROPERTY_ALIAS.equals(((Name) d).id)); + } + return d instanceof Attribute && attr.equals(((Attribute) d).attr) + && ((Attribute) d).value instanceof Name && owner.equals(((Name) ((Attribute) d).value).id); + } + + private static void lower(List module, int at, String file) { + ClassDef c = (ClassDef) module.get(at); + FunctionDef init = null; + Assign typeField = null; + int typeBinds = 0; + FunctionDef typeSetter = null; + int valueGet = -1; + int valueSet = -1; + Set fields = new HashSet(); + for (int i = 0; i < c.body.size(); i++) { + Stmt s = c.body.get(i); + if (s instanceof Assign && ((Assign) s).targets.size() == 1 + && ((Assign) s).targets.get(0) instanceof Name) { + String n = ((Name) ((Assign) s).targets.get(0)).id; + fields.add(n); + if ("type".equals(n)) { + typeBinds++; + Expr v = ((Assign) s).value; + if (v instanceof Node.Call && ((Node.Call) v).func instanceof Name) { + typeField = (Assign) s; + } + } + } + if (s instanceof FunctionDef && "type".equals(((FunctionDef) s).name)) { + typeBinds++; + } + if (!(s instanceof FunctionDef)) { + continue; + } + FunctionDef f = (FunctionDef) s; + if ("__init__".equals(f.name)) { + init = f; + } else if ("type".equals(f.name) && decoratedWith(f, "type", "setter")) { + typeSetter = f; + } else if ("value".equals(f.name) && decoratedWith(f, null, null)) { + valueGet = i; + } else if ("value".equals(f.name) && decoratedWith(f, "value", "setter")) { + valueSet = i; + } else if (decoratedWith(f, null, null)) { + fields.add(f.name); + } + } + // The one binding of `type` in the class: a lowered property (its + // setter) or a descriptor construction (its class's __set__). + boolean viaSetter = typeSetter != null && typeField == null && typeBinds == 2; + boolean viaDescriptor = typeSetter == null && typeField != null && typeBinds == 1; + if (init == null || !viaSetter && !viaDescriptor || valueGet < 0 || valueSet < 0 || mentions(c)) { + return; + } + List stores = new ArrayList(); + if (!stores(init.body, fields, stores) || stores.isEmpty()) { + return; + } + if (viaSetter) { + typeSetter.body.addAll(0, ((FunctionDef) members("def _f(self):\n self." + GET + " = None\n self." + + SET + " = None\n", file, typeSetter.line).get(0)).body); + } else { + Node.Call old = (Node.Call) typeField.value; + String kind = ((Name) old.func).id; + String hooked = "_cn1_ColorType_" + kind; + Node.Module parsed = Parser.parse("class " + hooked + "(" + kind + "):\n" + + " def __set__(self, instance, value):\n" + + " instance." + GET + " = None\n instance." + SET + " = None\n" + + " super().__set__(instance, value)\n", file); + DataclassInit.atLine(parsed, c.line); + Name f = new Name(hooked); + f.line = old.func.line; + Node.Call nc = new Node.Call(f); + nc.line = old.line; + nc.args.addAll(old.args); + nc.keywords.addAll(old.keywords); + Assign na = new Assign(typeField.targets, nc); + na.line = typeField.line; + c.body.set(c.body.indexOf(typeField), na); + module.addAll(at, parsed.body); + } + for (Object[] st : stores) { + @SuppressWarnings("unchecked") + List body = (List) st[0]; + Stmt s = (Stmt) st[1]; + String f = (String) st[2]; + List pair = ((FunctionDef) members("def _f(self):\n self." + GET + " = lambda o: o." + f + + "\n self." + SET + " = lambda o, v: setattr(o, '" + f + "', v)\n", file, s.line) + .get(0)).body; + body.addAll(body.indexOf(s) + 1, pair); + } + String getSrc = "@property\ndef value(self):\n g = self." + GET + "\n if g is None:\n" + + " raise TypeError(\"Color.type does not name one of its value fields\")\n" + + " return g(self)\n"; + String setSrc = "@value.setter\ndef value(self, value):\n s = self." + SET + "\n if s is None:\n" + + " raise TypeError(\"Color.type does not name one of its value fields\")\n" + + " s(self, value)\n"; + int line = c.body.get(valueGet).line; + c.body.set(valueGet, members(getSrc, file, line).get(0)); + c.body.set(valueSet, members(setSrc, file, c.body.get(valueSet).line).get(0)); + c.body.addAll(members(GET + " = None\n" + SET + " = None\n", file, c.body.get(c.body.size() - 1).line)); + } + + /// Whether the class already mentions the generated names. + private static boolean mentions(Object o) { + if (o instanceof Attribute && (GET.equals(((Attribute) o).attr) || SET.equals(((Attribute) o).attr))) { + return true; + } + final boolean[] hit = {false}; + Infer.children(o, x -> hit[0] |= mentions(x)); + return hit[0]; + } + + /// Every `self.type = ...` in `body` (into nested ifs), which must all + /// be literal names of the class's lowered fields. + private static boolean stores(List body, Set fields, List out) { + for (Stmt s : body) { + if (s instanceof Node.If) { + if (!stores(((Node.If) s).body, fields, out) || !stores(((Node.If) s).orelse, fields, out)) { + return false; + } + continue; + } + if (s instanceof Assign && ((Assign) s).targets.size() == 1 + && ((Assign) s).targets.get(0) instanceof Attribute + && "type".equals(((Attribute) ((Assign) s).targets.get(0)).attr)) { + Attribute a = (Attribute) ((Assign) s).targets.get(0); + Expr v = ((Assign) s).value; + if (!(a.value instanceof Name) || !"self".equals(((Name) a.value).id) || !(v instanceof Constant) + || ((Constant) v).kind != Constant.Kind.STR || !fields.contains(((Constant) v).text)) { + return false; + } + out.add(new Object[] {body, s, ((Constant) v).text}); + continue; + } + if (typeStore(s)) { + return false; + } + } + return true; + } + + private static boolean typeStore(Object o) { + if (o instanceof Assign) { + for (Expr t : ((Assign) o).targets) { + if (t instanceof Attribute && "type".equals(((Attribute) t).attr)) { + return true; + } + } + } + final boolean[] hit = {false}; + Infer.children(o, x -> hit[0] |= typeStore(x)); + return hit[0]; + } + + private static List members(String src, String file, int line) { + Node.Module parsed = Parser.parse("class _cv:\n" + src.replaceAll("(?m)^(?=.)", " "), file); + DataclassInit.atLine(parsed, line); + return ((ClassDef) parsed.body.get(0)).body; + } +} diff --git a/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/ConstArgSpecialize.java b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/ConstArgSpecialize.java new file mode 100644 index 00000000000..c3a033f99b7 --- /dev/null +++ b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/ConstArgSpecialize.java @@ -0,0 +1,1189 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.python.transpiler.codegen; + +import com.codename1.python.transpiler.ast.Node; +import com.codename1.python.transpiler.ast.Node.Attribute; +import com.codename1.python.transpiler.ast.Node.Call; +import com.codename1.python.transpiler.ast.Node.ClassDef; +import com.codename1.python.transpiler.ast.Node.Constant; +import com.codename1.python.transpiler.ast.Node.Expr; +import com.codename1.python.transpiler.ast.Node.FunctionDef; +import com.codename1.python.transpiler.ast.Node.Name; +import com.codename1.python.transpiler.ast.Node.Stmt; +import com.codename1.python.transpiler.parser.Lexer; +import com.codename1.python.transpiler.parser.Parser; +import com.codename1.python.transpiler.parser.Token; + +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.IdentityHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/// Specializes a method on the string it is always called with. +/// +/// python-pptx reaches the inherited dimensions of a placeholder through +/// +/// ```python +/// def _effective_value(self, attr_name): +/// v = getattr(super(_InheritsDimensions, self), attr_name) +/// ... +/// return self._inherited_value(attr_name) +/// ``` +/// +/// called as `self._effective_value("height")` and so on: a computed +/// attribute name the strict build refuses, although every caller spells +/// the name out. When a method's parameter is the name argument of a +/// `getattr`/`setattr`/`hasattr` and every call of the method in the closed +/// program passes a string literal for it, the method is cloned once per +/// literal (`_effective_value__cn1_height`), the literal is written in for +/// the parameter, `getattr(x, "height")` becomes `x.height` (and a +/// `setattr` statement an assignment), every call is pointed at its clone +/// and the original, which nothing calls any more, is removed. The calls in +/// a clone are literal again, so the pass repeats until nothing changes and +/// `_inherited_value` is specialized on the next round. +/// +/// It refuses anything it cannot prove: a method name defined twice, a +/// method referenced other than by being called, a call with keywords, +/// starred or missing arguments, a decorated method, a parameter the body +/// rebinds, and a method whose tree no longer matches its source text (an +/// earlier pass rewrote it), since the clone is made from that text. +/// No name-dispatch code is generated: each clone is plain code. +public final class ConstArgSpecialize { + + private static final int MAX_ROUNDS = 256; + private static final String SUFFIX = "__cn1_"; + + private ConstArgSpecialize() { + } + + /// A method, its class body and the text it was made from. + private static final class Method { + final String path; + final ClassDef owner; + final FunctionDef fn; + + Method(String path, ClassDef owner, FunctionDef fn) { + this.path = path; + this.owner = owner; + this.fn = fn; + } + } + + /// Source text of a function, dedented, and the line it starts on. + public static final class Text { + final String src; + final int line; + + Text(String src, int line) { + this.src = src; + this.line = line; + } + } + + /// Specializes every qualifying method among `trees`; `sources` holds + /// the text each tree was parsed from, under the same keys. + /// Returns the text of every clone made, which LoopUnroll reads in + /// place of the module source the clones are not in. + public static Map rewrite(Map trees, Map sources) { + Map made = new IdentityHashMap(); + Set refused = new LinkedHashSet(); + for (int i = 0; i < MAX_ROUNDS; i++) { + if (!round(trees, sources, made, refused)) { + break; + } + } + return made; + } + + private static boolean round(Map trees, Map sources, + Map made, Set refused) { + Map defCount = new HashMap(); + Map methods = new HashMap(); + Map> calls = new HashMap>(); + Set escaped = new LinkedHashSet(); + IdentityHashMap callFuncs = new IdentityHashMap(); + for (Map.Entry e : trees.entrySet()) { + index(e.getKey(), e.getValue(), null, defCount, methods, calls, escaped, callFuncs); + } + for (Map.Entry e : methods.entrySet()) { + String name = e.getKey(); + if (refused.contains(name) || escaped.contains(name) || defCount.get(name).intValue() != 1) { + continue; + } + List cs = calls.get(name); + if (cs == null || cs.isEmpty()) { + continue; + } + if (specialize(e.getValue(), cs, defCount, sources, made) + || specializeSeq(trees, e.getValue(), cs, defCount, sources, made)) { + // The clones' calls are literal: what was refused may pass now. + refused.clear(); + return true; + } + refused.add(name); + } + return specializeModuleFns(trees, sources, made, refused); + } + + /// The same specialization for a module-level function called by name + /// in its own module (`re_engine_`'s `show(p, s, flags=0, how="search")` + /// with `getattr(re.compile(p, flags), how)`): the name argument may be + /// passed by position, by keyword or left to a string default, and is + /// a literal identifier in every call. The function must be the only + /// definition of its name in the program, be referenced only as the + /// callee of such calls in its own module, and no scope may bind the + /// name otherwise (a parameter, an import, a store), so every call is + /// provably a call of it. No name-dispatch code is generated. + private static boolean specializeModuleFns(Map trees, Map sources, + Map made, Set refused) { + final Map defCount = new HashMap(); + final Set bad = new LinkedHashSet(); + final Map> calls = new HashMap>(); + final Map callPath = new HashMap(); + for (final Map.Entry e : trees.entrySet()) { + final IdentityHashMap callees = new IdentityHashMap(); + scanFns(e.getKey(), e.getValue(), defCount, bad, calls, callPath, callees); + } + for (Map.Entry e : trees.entrySet()) { + List body = e.getValue().body; + for (int i = 0; i < body.size(); i++) { + if (!(body.get(i) instanceof FunctionDef)) { + continue; + } + FunctionDef f = (FunctionDef) body.get(i); + String key = "fn:" + f.name; + List cs = calls.get(f.name); + if (refused.contains(key) || bad.contains(f.name) || defCount.get(f.name).intValue() != 1 + || cs == null || cs.isEmpty() || !e.getKey().equals(callPath.get(f.name))) { + continue; + } + if (specializeFn(e.getKey(), body, i, f, cs, defCount, sources, made)) { + refused.clear(); + return true; + } + refused.add(key); + } + } + return false; + } + + /// Maps each call that is the whole of an expression statement, in + /// `body` and every statement list nested in it, to that list. + static void stmtCalls(List body, Map> out) { + for (Stmt st : body) { + if (st instanceof Node.ExprStmt && ((Node.ExprStmt) st).value instanceof Call) { + out.put((Call) ((Node.ExprStmt) st).value, body); + } else if (st instanceof Node.Assign && ((Node.Assign) st).value instanceof Call) { + out.put((Call) ((Node.Assign) st).value, body); + } else if (st instanceof Node.If) { + stmtCalls(((Node.If) st).body, out); + stmtCalls(((Node.If) st).orelse, out); + } else if (st instanceof Node.For) { + stmtCalls(((Node.For) st).body, out); + stmtCalls(((Node.For) st).orelse, out); + } else if (st instanceof Node.While) { + stmtCalls(((Node.While) st).body, out); + stmtCalls(((Node.While) st).orelse, out); + } else if (st instanceof Node.With) { + stmtCalls(((Node.With) st).body, out); + } else if (st instanceof Node.Try) { + stmtCalls(((Node.Try) st).body, out); + for (Node.ExceptHandler h : ((Node.Try) st).handlers) { + stmtCalls(h.body, out); + } + stmtCalls(((Node.Try) st).orelse, out); + stmtCalls(((Node.Try) st).finalbody, out); + } else if (st instanceof FunctionDef) { + stmtCalls(((FunctionDef) st).body, out); + } else if (st instanceof ClassDef) { + stmtCalls(((ClassDef) st).body, out); + } + } + } + + private static void scanFns(final String path, Object o, final Map defCount, + final Set bad, final Map> calls, final Map callPath, + final IdentityHashMap callees) { + if (o instanceof FunctionDef) { + String n = ((FunctionDef) o).name; + Integer c = defCount.get(n); + defCount.put(n, Integer.valueOf(c == null ? 1 : c.intValue() + 1)); + } + if (o instanceof Node.Arg) { + bad.add(((Node.Arg) o).name); + } else if (o instanceof Call && ((Call) o).func instanceof Name) { + Call c = (Call) o; + String n = ((Name) c.func).id; + callees.put(c.func, Boolean.TRUE); + String prev = callPath.get(n); + if (prev != null && !prev.equals(path)) { + bad.add(n); + } + callPath.put(n, path); + List l = calls.get(n); + if (l == null) { + l = new ArrayList(); + calls.put(n, l); + } + l.add(c); + } else if (o instanceof Name && !callees.containsKey(o)) { + bad.add(((Name) o).id); + } else if (o instanceof Attribute) { + bad.add(((Attribute) o).attr); + } else if (o instanceof Constant && ((Constant) o).kind == Constant.Kind.STR) { + bad.add(((Constant) o).text); + } else if (o instanceof Node.Alias) { + bad.add(((Node.Alias) o).name); + bad.add(((Node.Alias) o).asname); + } else if (o instanceof Node.Global) { + bad.addAll(((Node.Global) o).names); + } else if (o instanceof ClassDef) { + bad.add(((ClassDef) o).name); + } + Infer.children(o, x -> scanFns(path, x, defCount, bad, calls, callPath, callees)); + } + + private static boolean specializeFn(String path, List body, int at, FunctionDef f, List cs, + Map defCount, Map sources, Map made) { + Node.Arguments a = f.args; + int n = a.positional.size(); + if (!f.decorators.isEmpty() || f.isAsync || a.vararg != null || a.kwarg != null || !a.kwonly.isEmpty() + || n < 2 || a.positionalOnly != 0) { + return false; + } + int idx = -1; + for (int i = 1; i < n && idx < 0; i++) { + if (namesAttribute(f.body, a.positional.get(i).name)) { + idx = i; + } + } + if (idx < 0) { + return false; + } + String p = a.positional.get(idx).name; + int firstDefault = n - a.defaults.size(); + Set lits = new LinkedHashSet(); + List litOf = new ArrayList(); + for (Call c : cs) { + for (Expr x : c.args) { + if (x instanceof Node.Starred) { + return false; + } + } + if (c.args.size() > n) { + return false; + } + Expr lit = null; + for (Node.Keyword k : c.keywords) { + if (k.arg == null) { + return false; + } + if (k.arg.equals(p)) { + lit = k.value; + } + } + if (idx < c.args.size()) { + if (lit != null) { + return false; + } + lit = c.args.get(idx); + } else if (lit == null && idx >= firstDefault) { + lit = a.defaults.get(idx - firstDefault); + } + if (!(lit instanceof Constant) || ((Constant) lit).kind != Constant.Kind.STR + || !ident(((Constant) lit).text)) { + return false; + } + lits.add(((Constant) lit).text); + litOf.add(((Constant) lit).text); + } + for (String l : lits) { + if (defCount.containsKey(f.name + SUFFIX + l)) { + return false; + } + } + if (rebindsDeep(f.body, p)) { + return false; + } + Text t = made.get(f); + if (t == null) { + t = extract(sources.get(path), f); + if (t == null || !dump(f).equals(dump(parseMethod(t.src, t.line, path)))) { + return false; + } + } + // A callee name cannot be renamed in place, so each call must be a + // statement of its own, which is replaced whole. + Map> holder = new IdentityHashMap>(); + stmtCalls(body, holder); + for (Call c : cs) { + if (!holder.containsKey(c)) { + return false; + } + } + List clones = new ArrayList(); + Map cloneName = new HashMap(); + for (String l : lits) { + String src = substitute(t.src, path, f.name, f.name + SUFFIX + l, p, "\"" + l + "\"", true); + if (src == null) { + return false; + } + FunctionDef c = parseMethod(src, t.line, path); + made.put(c, new Text(src, t.line)); + clones.add(c); + cloneName.put(l, c.name); + } + for (int j = 0; j < cs.size(); j++) { + Call c = cs.get(j); + List l = holder.get(c); + int si = -1; + for (int q = 0; q < l.size() && si < 0; q++) { + Stmt sq = l.get(q); + if (sq instanceof Node.ExprStmt && ((Node.ExprStmt) sq).value == c //NOPMD CompareObjectsWithEquals - identity is meant + || sq instanceof Node.Assign && ((Node.Assign) sq).value == c) { //NOPMD CompareObjectsWithEquals - identity is meant + si = q; + } + } + Call nc = new Call(new Name(cloneName.get(litOf.get(j))).at(c.func.line, c.func.col)).at(c.line, c.col); + nc.args.addAll(c.args); + nc.keywords.addAll(c.keywords); + Stmt old = l.get(si); + Stmt rep = old instanceof Node.Assign ? new Node.Assign(((Node.Assign) old).targets, nc) + : new Node.ExprStmt(nc); + l.set(si, rep.at(old.line, old.col)); + c = nc; + if (idx < c.args.size()) { + c.args.remove(idx); + } + for (int k = c.keywords.size() - 1; k >= 0; k--) { + if (p.equals(c.keywords.get(k).arg)) { + c.keywords.remove(k); + } + } + } + body.remove(at); + body.addAll(at, clones); + made.remove(f); + return true; + } + + private static void index(final String path, Object o, final ClassDef owner, final Map defCount, + final Map methods, final Map> calls, final Set escaped, + final IdentityHashMap callFuncs) { + if (o instanceof FunctionDef) { + FunctionDef f = (FunctionDef) o; + Integer n = defCount.get(f.name); + defCount.put(f.name, Integer.valueOf(n == null ? 1 : n.intValue() + 1)); + if (owner != null) { + methods.put(f.name, new Method(path, owner, f)); + } + } else if (o instanceof Call) { + Call c = (Call) o; + if (c.func instanceof Attribute) { + callFuncs.put(c.func, Boolean.TRUE); + String n = ((Attribute) c.func).attr; + List l = calls.get(n); + if (l == null) { + l = new ArrayList(); + calls.put(n, l); + } + l.add(c); + } + } else if (o instanceof Attribute) { + if (!callFuncs.containsKey(o)) { + escaped.add(((Attribute) o).attr); + } + } else if (o instanceof Name) { + escaped.add(((Name) o).id); + } else if (o instanceof Constant && ((Constant) o).kind == Constant.Kind.STR) { + escaped.add(((Constant) o).text); + } else if (o instanceof Node.Alias) { + escaped.add(((Node.Alias) o).name); + escaped.add(((Node.Alias) o).asname); + } + final ClassDef inner = o instanceof ClassDef ? (ClassDef) o : null; + if (o instanceof ClassDef) { + for (Stmt s : inner.body) { + index(path, s, inner, defCount, methods, calls, escaped, callFuncs); + } + for (Expr b : inner.bases) { + index(path, b, null, defCount, methods, calls, escaped, callFuncs); + } + for (Expr d : inner.decorators) { + index(path, d, null, defCount, methods, calls, escaped, callFuncs); + } + for (Node.Keyword k : inner.keywords) { + index(path, k, null, defCount, methods, calls, escaped, callFuncs); + } + return; + } + Infer.children(o, x -> index(path, x, null, defCount, methods, calls, escaped, callFuncs)); + } + + private static boolean specialize(Method m, List cs, Map defCount, + Map sources, Map made) { + FunctionDef f = m.fn; + Node.Arguments a = f.args; + if (!f.decorators.isEmpty() || f.isAsync || a.vararg != null || a.kwarg != null || !a.kwonly.isEmpty() + || !a.defaults.isEmpty() || a.positional.size() < 2) { + return false; + } + int idx = -1; + for (int i = 1; i < a.positional.size() && idx < 0; i++) { + if (namesAttribute(f.body, a.positional.get(i).name)) { + idx = i; + } + } + if (idx < 0) { + return false; + } + String p = a.positional.get(idx).name; + Set lits = new LinkedHashSet(); + for (Call c : cs) { + if (!c.keywords.isEmpty() || c.args.size() != a.positional.size() - 1) { + return false; + } + for (Expr x : c.args) { + if (x instanceof Node.Starred) { + return false; + } + } + Expr lit = c.args.get(idx - 1); + if (!(lit instanceof Constant) || ((Constant) lit).kind != Constant.Kind.STR + || !ident(((Constant) lit).text)) { + return false; + } + lits.add(((Constant) lit).text); + } + for (String l : lits) { + if (defCount.containsKey(f.name + SUFFIX + l)) { + return false; + } + } + if (rebinds(f.body, p)) { + return false; + } + Text t = made.get(f); + if (t == null) { + t = extract(sources.get(m.path), f); + if (t == null || !dump(f).equals(dump(parseMethod(t.src, t.line, m.path)))) { + return false; + } + } + List clones = new ArrayList(); + Map cloneName = new HashMap(); + for (String l : lits) { + String src = substitute(t.src, m.path, f.name, f.name + SUFFIX + l, p, "\"" + l + "\"", false); + if (src == null) { + return false; + } + FunctionDef c = parseMethod(src, t.line, m.path); + made.put(c, new Text(src, t.line)); + clones.add(c); + cloneName.put(l, c.name); + } + for (Call c : cs) { + String l = ((Constant) c.args.get(idx - 1)).text; + ((Attribute) c.func).attr = cloneName.get(l); + c.args.remove(idx - 1); + } + int at = indexOf(m.owner.body, f); + m.owner.body.remove(at); + m.owner.body.addAll(at, clones); + made.remove(f); + return true; + } + + /// Specializes a method on a sequence of attribute names it is handed: + /// + /// ```python + /// def flush_cache(self, properties=None): + /// props = self.cached_properties if properties is None else properties + /// for p in props: + /// if hasattr(self, p): + /// delattr(self, p) + /// ``` + /// + /// called as `self.flush_cache()` and `self.flush_cache(Container.cached_properties)`. + /// When the last parameter defaults to `None`, is read only to be + /// compared with `None` or as a branch of a conditional bound to a local + /// that is only iterated, and every call either leaves it out or passes + /// a sequence of identifiers LoopUnroll can name at build time (proving + /// a list never mutated), the method is cloned per distinct argument + /// with `None` or the tuple literal written in. LoopUnroll then folds + /// the conditional and unrolls the loop into literal accesses. + private static boolean specializeSeq(Map trees, Method m, List cs, + Map defCount, Map sources, Map made) { + FunctionDef f = m.fn; + Node.Arguments a = f.args; + int n = a.positional.size(); + if (!f.decorators.isEmpty() || f.isAsync || a.vararg != null || a.kwarg != null || !a.kwonly.isEmpty() + || a.defaults.size() != 1 || n < 2 || !isNone(a.defaults.get(0)) || !computedAccess(f.body)) { + return false; + } + String p = a.positional.get(n - 1).name; + boolean[] used = {false}; + for (Stmt st : f.body) { + if (!seqUses(f, st, p, used)) { + return false; + } + } + if (!used[0] || rebinds(f.body, p)) { + return false; + } + Map values = new java.util.LinkedHashMap(); + List keyOf = new ArrayList(); + for (Call c : cs) { + if (!c.keywords.isEmpty() || c.args.size() != n - 1 && c.args.size() != n - 2) { + return false; + } + for (Expr x : c.args) { + if (x instanceof Node.Starred) { + return false; + } + } + String key; + String text; + if (c.args.size() == n - 2) { + key = "None"; + text = "None"; + } else { + String path = pathOf(trees, c); + List names = path == null ? null : LoopUnroll.staticSeq(trees, path, c.args.get(n - 2), cs); + if (names == null) { + return false; + } + StringBuilder b = new StringBuilder("("); + for (String nm : names) { + if (!ident(nm)) { + return false; + } + b.append('"').append(nm).append("\", "); + } + text = b.append(')').toString(); + key = text; + } + if (!values.containsKey(key)) { + values.put(key, text); + } + keyOf.add(key); + } + Map cloneName = new HashMap(); + int i = 0; + for (String k : values.keySet()) { + String cn = f.name + SUFFIX + ("None".equals(k) ? "None" : "seq" + i++); + if (defCount.containsKey(cn)) { + return false; + } + cloneName.put(k, cn); + } + Text t = made.get(f); + if (t == null) { + t = extract(sources.get(m.path), f); + if (t == null || !dump(f).equals(dump(parseMethod(t.src, t.line, m.path)))) { + return false; + } + } + List clones = new ArrayList(); + for (Map.Entry e : values.entrySet()) { + String src = substitute(t.src, m.path, f.name, cloneName.get(e.getKey()), p, e.getValue(), true); + if (src == null) { + return false; + } + FunctionDef c = parseMethod(src, t.line, m.path); + made.put(c, new Text(src, t.line)); + clones.add(c); + } + for (int j = 0; j < cs.size(); j++) { + Call c = cs.get(j); + ((Attribute) c.func).attr = cloneName.get(keyOf.get(j)); + if (c.args.size() == n - 1) { + c.args.remove(n - 2); + } + } + int at = indexOf(m.owner.body, f); + m.owner.body.remove(at); + m.owner.body.addAll(at, clones); + made.remove(f); + return true; + } + + private static boolean isNone(Expr e) { + return e instanceof Constant && ((Constant) e).kind == Constant.Kind.NONE; + } + + /// True when `o` holds a getattr/setattr/hasattr/delattr whose name is + /// a variable: what the specialization is for. + private static boolean computedAccess(Object o) { + if (o instanceof Call && ((Call) o).func instanceof Name && ((Call) o).args.size() >= 2 + && ((Call) o).args.get(1) instanceof Name) { + String n = ((Name) ((Call) o).func).id; + if ("getattr".equals(n) || "setattr".equals(n) || "hasattr".equals(n) || "delattr".equals(n)) { + return true; + } + } + final boolean[] found = {false}; + Infer.children(o, x -> found[0] |= !found[0] && computedAccess(x)); + return found[0]; + } + + /// Whether every read of `p` in `o` (a statement of `f`) is a comparison + /// with `None` by identity, or sits in the conditional value of an + /// assignment to a local of `f` that is read only as a loop's iterable. + private static boolean seqUses(FunctionDef f, Object o, String p, boolean[] used) { + if (o instanceof Node.Lambda || o instanceof FunctionDef || o instanceof ClassDef || o instanceof Node.Comp) { + return !mentions(o, p); + } + if (o instanceof Name && p.equals(((Name) o).id)) { + return false; + } + if (o instanceof Node.Compare && ((Node.Compare) o).ops.size() == 1 + && ("is".equals(((Node.Compare) o).ops.get(0)) || "is not".equals(((Node.Compare) o).ops.get(0)))) { + Expr l = ((Node.Compare) o).left; + Expr r = ((Node.Compare) o).comparators.get(0); + if (l instanceof Name && p.equals(((Name) l).id) && isNone(r) + || r instanceof Name && p.equals(((Name) r).id) && isNone(l)) { + used[0] = true; + return true; + } + } + if (o instanceof Node.Assign && ((Node.Assign) o).targets.size() == 1 + && ((Node.Assign) o).targets.get(0) instanceof Name + && ((Node.Assign) o).value instanceof Node.IfExp + && onlyIterated(f, ((Name) ((Node.Assign) o).targets.get(0)).id)) { + Node.IfExp x = (Node.IfExp) ((Node.Assign) o).value; + for (Expr b : new Expr[] {x.body, x.orelse}) { + if (b instanceof Name && p.equals(((Name) b).id)) { + used[0] = true; + } else if (!seqUses(f, b, p, used)) { + return false; + } + } + return seqUses(f, x.test, p, used); + } + final boolean[] ok = {true}; + Infer.children(o, x -> ok[0] &= !ok[0] || seqUses(f, x, p, used)); + return ok[0]; + } + + /// Whether local `n` of `f` is bound once and read only as the + /// iterable of one loop. + private static boolean onlyIterated(FunctionDef f, final String n) { + final int[] c = {0, 0}; + countUses(f, n, c); + return c[0] == 2 && c[1] == 1; + } + + private static void countUses(Object o, final String n, final int[] c) { + if (o instanceof Name && n.equals(((Name) o).id)) { + c[0]++; + } + if (o instanceof Node.For && ((Node.For) o).iter instanceof Name && n.equals(((Name) ((Node.For) o).iter).id)) { + c[1]++; + } + if (o instanceof Node.Global && ((Node.Global) o).names.contains(n)) { + c[0] += 100; + } + Infer.children(o, x -> countUses(x, n, c)); + } + + private static String pathOf(Map trees, Call c) { + for (Map.Entry e : trees.entrySet()) { + if (contains(e.getValue(), c)) { + return e.getKey(); + } + } + return null; + } + + private static boolean contains(Object o, final Object target) { + if (o == target) { //NOPMD CompareObjectsWithEquals - identity is meant + return true; + } + final boolean[] found = {false}; + Infer.children(o, x -> found[0] |= !found[0] && contains(x, target)); + return found[0]; + } + + private static int indexOf(List body, Stmt s) { + for (int i = 0; i < body.size(); i++) { + if (body.get(i) == s) { //NOPMD CompareObjectsWithEquals - identity is meant + return i; + } + } + throw new IllegalStateException("method not in its class"); + } + + /// True when `p` is the name argument of a getattr/setattr/hasattr in `o`. + private static boolean namesAttribute(Object o, final String p) { + if (o instanceof Call) { + Call c = (Call) o; + if (c.func instanceof Name && c.args.size() >= 2 && c.args.get(1) instanceof Name + && p.equals(((Name) c.args.get(1)).id)) { + String n = ((Name) c.func).id; + if ("getattr".equals(n) || "setattr".equals(n) || "hasattr".equals(n)) { + return true; + } + } + } + final boolean[] found = {false}; + Infer.children(o, x -> { + if (!found[0] && namesAttribute(x, p)) { + found[0] = true; + } + }); + return found[0]; + } + + /// True when `o` might bind `p` or hide it in a nested scope. + private static boolean rebinds(Object o, final String p) { + if (o instanceof Node.Lambda || o instanceof FunctionDef || o instanceof ClassDef || o instanceof Node.Comp + || o instanceof Node.Global || o instanceof Node.Match) { + return true; + } + if (rebindsShallow(o, p)) { + return true; + } + final boolean[] found = {false}; + Infer.children(o, x -> { + if (!found[0] && rebinds(x, p)) { + found[0] = true; + } + }); + return found[0]; + } + + /// [#rebinds] for a module function, which may hold nested functions + /// reading `p` as a closure: a nested function or lambda is looked + /// into rather than refused, and refused only when a parameter of it + /// is named `p` (or it declares `p` global or nonlocal, or binds it). + /// A name never rebound in any scope holds the literal throughout. + private static boolean rebindsDeep(Object o, final String p) { + if (o instanceof FunctionDef || o instanceof Node.Lambda) { + Node.Arguments a = o instanceof FunctionDef ? ((FunctionDef) o).args : ((Node.Lambda) o).args; + if (a.names().contains(p) || o instanceof FunctionDef && p.equals(((FunctionDef) o).name)) { + return true; + } + final boolean[] found = {false}; + Infer.children(o, x -> found[0] |= !found[0] && !(x instanceof Node.Arguments) && rebindsDeep(x, p)); + if (o instanceof FunctionDef) { + for (Expr d : ((FunctionDef) o).decorators) { + found[0] |= rebindsDeep(d, p); + } + } + return found[0]; + } + if (o instanceof ClassDef || o instanceof Node.Comp || o instanceof Node.Global || o instanceof Node.Match + || o instanceof Node.Alias) { + return true; + } + if (rebindsShallow(o, p)) { + return true; + } + final boolean[] found = {false}; + Infer.children(o, x -> found[0] |= !found[0] && rebindsDeep(x, p)); + return found[0]; + } + + /// Whether `o` itself binds `p` through its own targets. + private static boolean rebindsShallow(Object o, String p) { + List targets = new ArrayList(); + if (o instanceof Node.Assign) { + targets.addAll(((Node.Assign) o).targets); + } else if (o instanceof Node.AugAssign) { + targets.add(((Node.AugAssign) o).target); + } else if (o instanceof Node.AnnAssign) { + targets.add(((Node.AnnAssign) o).target); + } else if (o instanceof Node.For) { + targets.add(((Node.For) o).target); + } else if (o instanceof Node.WithItem) { + targets.add(((Node.WithItem) o).vars); + } else if (o instanceof Node.NamedExpr) { + targets.add(((Node.NamedExpr) o).target); + } else if (o instanceof Node.Delete) { + targets.addAll(((Node.Delete) o).targets); + } else if (o instanceof Node.ExceptHandler && p.equals(((Node.ExceptHandler) o).name)) { + return true; + } + for (Object t : targets) { + if (t != null && mentions(t, p)) { + return true; + } + } + return false; + } + + private static boolean mentions(Object o, final String p) { + if (o instanceof Name && p.equals(((Name) o).id)) { + return true; + } + final boolean[] found = {false}; + Infer.children(o, x -> { + if (!found[0] && mentions(x, p)) { + found[0] = true; + } + }); + return found[0]; + } + + /// The dedented text of `f` in `src`, or null when it cannot be found. + static Text extract(String src, FunctionDef f) { + if (src == null) { + return null; + } + List toks = new Lexer(src, "").tokenize(); + int start = -1; + for (int i = 0; i < toks.size(); i++) { + Token k = toks.get(i); + if (k.line == f.line && k.is("def") && i + 1 < toks.size() && toks.get(i + 1).text.equals(f.name)) { + start = i; + break; + } + } + if (start < 0) { + return null; + } + int depth = 0; + int end = -1; + int last = f.line; + boolean header = true; + for (int i = start; i < toks.size(); i++) { + Token k = toks.get(i); + if (k.kind == Token.Kind.EOF) { + end = i; + break; + } + if (k.kind == Token.Kind.INDENT) { + depth++; + } else if (k.kind == Token.Kind.DEDENT) { + depth--; + if (depth == 0) { + end = i; + break; + } + } else if (k.kind == Token.Kind.NEWLINE) { + if (header && depth == 0 && !(i + 1 < toks.size() && toks.get(i + 1).kind == Token.Kind.INDENT)) { + end = i; + break; + } + header = false; + } else { + last = Math.max(last, k.line + count(k.text, '\n')); + } + } + if (end < 0) { + return null; + } + String[] lines = src.replace("\r\n", "\n").replace('\r', '\n').split("\n", -1); + if (last > lines.length) { + return null; + } + String first = lines[f.line - 1]; + int ind = 0; + while (ind < first.length() && first.charAt(ind) == ' ') { + ind++; + } + StringBuilder b = new StringBuilder(); + for (int l = f.line; l <= last; l++) { + String s = lines[l - 1]; + int cut = 0; + while (cut < ind && cut < s.length() && s.charAt(cut) == ' ') { + cut++; + } + b.append(s.substring(cut)).append('\n'); + } + return new Text(b.toString(), f.line); + } + + static int count(String s, char c) { + int n = 0; + for (int i = 0; i < s.length(); i++) { + if (s.charAt(i) == c) { + n++; + } + } + return n; + } + + static FunctionDef parseMethod(String src, int line, String path) { + StringBuilder b = new StringBuilder(); + for (int i = 2; i < line; i++) { + b.append('\n'); + } + b.append("class _cn1_c:\n").append(src.replaceAll("(?m)^(?=.)", " ")); + Node.Module m = Parser.parse(b.toString(), path); + ClassDef c = (ClassDef) m.body.get(m.body.size() - 1); + return (FunctionDef) c.body.get(0); + } + + /// `src` (a dedented def of `name`) renamed to `clone`, with `p` + /// dropped from its parameters and the literal `lit` written for it. + /// Null when a use of `p` cannot be rewritten. + private static String substitute(String src, String path, String name, String clone, String p, String q, + boolean dflt) { + // The literal itself, for a getattr/setattr naming `p` (string mode only). + String lit = q.length() > 1 && q.charAt(0) == '"' ? q.substring(1, q.length() - 1) : q; + List toks = new Lexer(src, path).tokenize(); + int[] starts = lineStarts(src); + List edits = new ArrayList(); + List repl = new ArrayList(); + // def NAME ( self , ... p ... ) -- rename and drop p with its comma. + if (toks.size() < 3 || !toks.get(1).text.equals(name) || !toks.get(2).is("(")) { + return null; + } + edit(edits, repl, off(starts, toks.get(1)), off(starts, toks.get(1)) + name.length(), clone); + int close = match(toks, 2); + if (close < 0) { + return null; + } + boolean dropped = false; + for (int i = 3; i < close; i++) { + Token k = toks.get(i); + if (k.kind == Token.Kind.NAME && k.text.equals(p) && toks.get(i - 1).is(",")) { + int stop = off(starts, k) + p.length(); + if (toks.get(i + 1).is("=")) { + if (!dflt) { + return null; + } + int c = topComma(toks, i + 2, close); + int to = c < 0 ? close : c; + Token lastTok = toks.get(to - 1); + stop = off(starts, lastTok) + lastTok.text.length(); + } + if (toks.get(i + 1).is(":")) { + // An annotated parameter (`name: str`, the common typed + // form) goes with its annotation, up to the next + // top-level comma or the closing bracket. + int c = topComma(toks, i + 2, close); + int to = c < 0 ? close : c; + for (int j = i + 2; j < to && !dflt; j++) { + if (toks.get(j).is("=")) { + return null; + } + } + Token lastTok = toks.get(to - 1); + stop = off(starts, lastTok) + lastTok.text.length(); + if (lastTok.kind == Token.Kind.STRING || count(lastTok.text, '\n') > 0) { + return null; + } + } + edit(edits, repl, off(starts, toks.get(i - 1)), stop, ""); + dropped = true; + } + } + if (!dropped) { + return null; + } + for (int i = close + 1; i < toks.size(); i++) { + Token k = toks.get(i); + if (k.kind == Token.Kind.STRING && k.prefix != null && k.prefix.indexOf('f') >= 0 + && k.text.contains(p)) { + return null; + } + if (k.kind != Token.Kind.NAME) { + continue; + } + if ((k.is("getattr") || k.is("setattr")) && toks.get(i + 1).is("(") && !toks.get(i - 1).is(".")) { + int end = match(toks, i + 1); + int comma = topComma(toks, i + 2, end); + if (end > 0 && comma > 0 && toks.get(comma + 1).kind == Token.Kind.NAME + && toks.get(comma + 1).text.equals(p)) { + for (int j = i + 2; j < comma; j++) { + if (toks.get(j).kind == Token.Kind.NAME && toks.get(j).text.equals(p)) { + return null; + } + } + int objS = off(starts, toks.get(i + 2)); + int objE = off(starts, toks.get(comma)); + String obj = src.substring(objS, objE).trim(); + // `getattr(super(C, self), "lit")` keeps its call form: + // Layouts reads `super().name` as a name a super() call + // names, which bars a mixin binding it from being merged + // under a later Java parent (python-pptx's + // _InheritsDimensions over Shape). The literal getattr on + // super is typed the same, through the MRO after C. + boolean onSuper = toks.get(i + 2).is("super") && toks.get(i + 3).is("("); + if (k.is("getattr") && comma + 2 == end && !onSuper) { + edit(edits, repl, off(starts, k), off(starts, toks.get(end)) + 1, + "(" + obj + ")." + lit); + i = end; + continue; + } + Token prev = toks.get(i - 1); + boolean stmt = prev.kind == Token.Kind.NEWLINE || prev.kind == Token.Kind.INDENT + || prev.kind == Token.Kind.DEDENT; + if (k.is("setattr") && stmt && toks.get(comma + 2).is(",") + && toks.get(end + 1).kind == Token.Kind.NEWLINE) { + int valS = off(starts, toks.get(comma + 3)); + int valE = off(starts, toks.get(end)); + edit(edits, repl, off(starts, k), off(starts, toks.get(end)) + 1, + "(" + obj + ")." + lit + " = (" + src.substring(valS, valE).trim() + ")"); + i = end; + continue; + } + } + } + if (k.text.equals(p) && !toks.get(i - 1).is(".")) { + if (toks.get(i + 1).is("=")) { + // A keyword argument's name, not a use. + return null; + } + edit(edits, repl, off(starts, k), off(starts, k) + p.length(), q); + } + } + // Edits were collected left to right without overlap except where + // a getattr span replaced its own inner use; apply right to left. + StringBuilder b = new StringBuilder(src); + for (int i = edits.size() - 1; i >= 0; i--) { + int[] e = edits.get(i); + b.replace(e[0], e[1], repl.get(i)); + } + return b.toString(); + } + + private static void edit(List edits, List repl, int s, int e, String r) { + edits.add(new int[] {s, e}); + repl.add(r); + } + + static int[] lineStarts(String src) { + List l = new ArrayList(); + l.add(Integer.valueOf(0)); + for (int i = 0; i < src.length(); i++) { + if (src.charAt(i) == '\n') { + l.add(Integer.valueOf(i + 1)); + } + } + int[] r = new int[l.size()]; + for (int i = 0; i < r.length; i++) { + r[i] = l.get(i).intValue(); + } + return r; + } + + static int off(int[] starts, Token t) { + return starts[t.line - 1] + t.col - 1; + } + + /// The index of the bracket closing the one at `open`, or -1. + private static int match(List toks, int open) { + int d = 0; + for (int i = open; i < toks.size(); i++) { + Token k = toks.get(i); + if (k.kind != Token.Kind.OP) { + continue; + } + if (k.is("(") || k.is("[") || k.is("{")) { + d++; + } else if (k.is(")") || k.is("]") || k.is("}")) { + d--; + if (d == 0) { + return i; + } + } + } + return -1; + } + + /// The first comma at bracket depth zero in `[from, to)`, or -1. + private static int topComma(List toks, int from, int to) { + int d = 0; + for (int i = from; i < to; i++) { + Token k = toks.get(i); + if (k.kind != Token.Kind.OP) { + continue; + } + if (k.is("(") || k.is("[") || k.is("{")) { + d++; + } else if (k.is(")") || k.is("]") || k.is("}")) { + d--; + } else if (d == 0 && k.is(",")) { + return i; + } + } + return -1; + } + + /// A structural rendering of `o`, ignoring positions and scopes. + static String dump(Object o) { + StringBuilder b = new StringBuilder(); + dump(o, b); + return b.toString(); + } + + private static void dump(Object o, StringBuilder b) { + if (o instanceof List) { + b.append('['); + for (Object x : (List) o) { + dump(x, b); + b.append(','); + } + b.append(']'); + return; + } + if (!(o instanceof Node)) { + b.append(o); + return; + } + b.append(o.getClass().getSimpleName()).append('('); + for (Class c = o.getClass(); c != null && c != Object.class; c = c.getSuperclass()) { + for (Field f : c.getDeclaredFields()) { + if (Modifier.isStatic(f.getModifiers()) || "line".equals(f.getName()) || "col".equals(f.getName())) { + continue; + } + Class t = f.getType(); + if (!Node.class.isAssignableFrom(t) && !List.class.isAssignableFrom(t) && !t.isPrimitive() + && t != String.class && !t.isEnum()) { + continue; + } + try { + dump(f.get(o), b); + } catch (IllegalAccessException e) { + throw new IllegalStateException(e); + } + b.append(';'); + } + } + b.append(')'); + } + + static boolean ident(String s) { + if (s.isEmpty() || !(Character.isLetter(s.charAt(0)) || s.charAt(0) == '_')) { + return false; + } + for (int i = 0; i < s.length(); i++) { + char ch = s.charAt(i); + if (ch >= 0x80 || !(Character.isLetterOrDigit(ch) || ch == '_')) { + return false; + } + } + return true; + } +} diff --git a/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/ConstantDefaults.java b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/ConstantDefaults.java new file mode 100644 index 00000000000..ecc60975a8a --- /dev/null +++ b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/ConstantDefaults.java @@ -0,0 +1,141 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.python.transpiler.codegen; + +import com.codename1.python.transpiler.ast.Node; +import com.codename1.python.transpiler.ast.Node.Assign; +import com.codename1.python.transpiler.ast.Node.ClassDef; +import com.codename1.python.transpiler.ast.Node.Constant; +import com.codename1.python.transpiler.ast.Node.Expr; +import com.codename1.python.transpiler.ast.Node.FunctionDef; +import com.codename1.python.transpiler.ast.Node.ImportFrom; +import com.codename1.python.transpiler.ast.Node.Name; +import com.codename1.python.transpiler.ast.Node.Stmt; +import com.codename1.python.transpiler.ast.Node.UnaryOp; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/// Replaces a parameter default that names a module constant with the +/// constant: `def f(x, *, priority=PRIORITY_GENERIC)` after +/// `PRIORITY_GENERIC = 10.0` becomes `def f(x, *, priority=10.0)`. +/// +/// Python evaluates a default once, when the `def` runs, so the parameter +/// holds whatever the name was bound to then. When the module binds the +/// name exactly once, at its top level, to a literal, and that binding +/// comes before the `def` in the module's body, the value is that literal +/// whatever happens later. A call that omits the argument can then be bound +/// at build time (Infer#staticArgs), which takes only constant defaults. +/// +/// Only top-level functions and the methods of top-level classes are +/// rewritten; a method's default is left alone when its class body binds +/// the name first, since the class namespace is searched before the +/// module's. +public final class ConstantDefaults { + private ConstantDefaults() { + } + + public static void rewrite(Node.Module tree) { + for (Stmt s : tree.body) { + if (s instanceof ImportFrom) { + for (Node.Alias a : ((ImportFrom) s).names) { + if ("*".equals(a.name)) { + // May bind any name, at any point. + return; + } + } + } + } + Map bindings = new HashMap(); + for (Stmt s : tree.body) { + DataclassInit.count(s, bindings); + } + Map constants = new HashMap(); + for (Stmt s : tree.body) { + if (s instanceof Assign && ((Assign) s).targets.size() == 1 && ((Assign) s).targets.get(0) instanceof Name) { + String n = ((Name) ((Assign) s).targets.get(0)).id; + Expr v = ((Assign) s).value; + if (literal(v) && bindings.getOrDefault(n, 0) == 1) { + constants.put(n, v); + } + } else if (s instanceof FunctionDef) { + replace((FunctionDef) s, constants, null); + } else if (s instanceof ClassDef) { + Map local = new HashMap(); + for (Stmt m : ((ClassDef) s).body) { + if (m instanceof FunctionDef) { + replace((FunctionDef) m, constants, local); + local.merge(((FunctionDef) m).name, 1, Integer::sum); + } else { + DataclassInit.count(m, local); + } + } + } + } + } + + private static void replace(FunctionDef f, Map constants, Map classBound) { + replace(f.args.defaults, constants, classBound); + replace(f.args.kwDefaults, constants, classBound); + } + + private static void replace(List defaults, Map constants, Map classBound) { + for (int i = 0; i < defaults.size(); i++) { + Expr d = defaults.get(i); + if (d instanceof Name && constants.containsKey(((Name) d).id) + && (classBound == null || !classBound.containsKey(((Name) d).id))) { + Expr c = copy(constants.get(((Name) d).id)); + c.line = d.line; + c.col = d.col; + defaults.set(i, c); + } + } + } + + /// A literal whose value does not depend on when it is evaluated: a + /// number, string, bytes, bool or None, or a signed number. + private static boolean literal(Expr v) { + if (v instanceof Constant) { + return true; + } + return v instanceof UnaryOp && ("-".equals(((UnaryOp) v).op) || "+".equals(((UnaryOp) v).op)) + && ((UnaryOp) v).operand instanceof Constant; + } + + private static Expr copy(Expr v) { + if (v instanceof UnaryOp) { + UnaryOp u = (UnaryOp) v; + UnaryOp r = new UnaryOp(u.op, copy(u.operand)); + r.line = u.line; + r.col = u.col; + return r; + } + Constant c = (Constant) v; + Constant r = new Constant(c.kind, c.text); + r.line = c.line; + r.col = c.col; + return r; + } +} diff --git a/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/CustomPropertyLowering.java b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/CustomPropertyLowering.java new file mode 100644 index 00000000000..d1f9daa51df --- /dev/null +++ b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/CustomPropertyLowering.java @@ -0,0 +1,339 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.python.transpiler.codegen; + +import com.codename1.python.transpiler.ast.Node; +import com.codename1.python.transpiler.ast.Node.Assign; +import com.codename1.python.transpiler.ast.Node.Attribute; +import com.codename1.python.transpiler.ast.Node.Call; +import com.codename1.python.transpiler.ast.Node.ClassDef; +import com.codename1.python.transpiler.ast.Node.Constant; +import com.codename1.python.transpiler.ast.Node.Expr; +import com.codename1.python.transpiler.ast.Node.FunctionDef; +import com.codename1.python.transpiler.ast.Node.Name; +import com.codename1.python.transpiler.ast.Node.Stmt; +import com.codename1.python.transpiler.parser.Parser; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/// Lowers openpyxl's custom document property (`packaging/custom.py`), +/// whose value lives in whichever one of its child elements is set, and +/// which finds that element by name: `setattr(self, k, v)` over its +/// `**kw`, `getattr(self, a)` over `__elements__`, and +/// `getattr(self, self._typ)` in `to_tree` and in +/// `CustomPropertyList.from_tree`. +/// +/// The element names are closed at build time: the class body's nested +/// descriptors, sorted as openpyxl's metaclass sorts `__elements__`. This +/// pass writes, per element, a literal store in `__init__`, a literal read +/// in `type`, and a reader and writer lambda over that one element; every store of a +/// literal `_typ` also stores that element's pair in `_typ_get` and +/// `_typ_set`, so `to_tree` and `from_tree` call the pair the data selected +/// instead of comparing names. Two differences from the source, both on +/// input openpyxl never writes: an unknown keyword raises `TypeError` +/// (upstream stored an attribute no layout has), and more than one element +/// keyword raises `ValueError` (upstream kept the last in keyword order). +/// If any part of the module, or any store of `_typ` elsewhere in the +/// program, does not have the expected shape, nothing is changed. +public final class CustomPropertyLowering { + + private static final String PATH = "openpyxl/packaging/custom.py"; + private static final String CLS = "_CustomDocumentProperty"; + private static final Set NESTED = new HashSet( + Arrays.asList("NestedText", "NestedDateTime", "NestedBoolText")); + private static final Set OWN = new HashSet( + Arrays.asList("_typ", "_typ_get", "_typ_set", "_type_value")); + + private CustomPropertyLowering() { + } + + public static void rewrite(Map trees) { + for (Map.Entry e : trees.entrySet()) { + if (e.getKey().endsWith(PATH)) { + for (Map.Entry o : trees.entrySet()) { + if (o.getValue() != e.getValue() && mentions(o.getValue())) { //NOPMD CompareObjectsWithEquals - identity + return; + } + } + lower(e.getValue(), e.getKey()); + } + } + } + + private static boolean mentions(Object o) { + if (o instanceof Attribute && OWN.contains(((Attribute) o).attr)) { + return true; + } + final boolean[] hit = {false}; + Infer.children(o, x -> hit[0] |= mentions(x)); + return hit[0]; + } + + private static ClassDef cls(Node.Module m, String n) { + for (Stmt s : m.body) { + if (s instanceof ClassDef && ((ClassDef) s).name.equals(n)) { + return (ClassDef) s; + } + } + return null; + } + + private static int method(ClassDef c, String n) { + int found = -1; + for (int i = 0; i < c.body.size(); i++) { + if (c.body.get(i) instanceof FunctionDef && ((FunctionDef) c.body.get(i)).name.equals(n)) { + if (found >= 0) { + return -2; + } + found = i; + } + } + return found; + } + + private static String assignedName(Stmt s) { + if (s instanceof Assign && ((Assign) s).targets.size() == 1 && ((Assign) s).targets.get(0) instanceof Name) { + return ((Name) ((Assign) s).targets.get(0)).id; + } + return null; + } + + private static void lower(Node.Module m, String file) { + ClassDef c = cls(m, CLS); + ClassDef list = cls(m, "CustomPropertyList"); + if (c == null || list == null || !c.decorators.isEmpty()) { + return; + } + List elements = new ArrayList(); + int typAt = -1; + for (int i = 0; i < c.body.size(); i++) { + Stmt s = c.body.get(i); + String n = assignedName(s); + if (n == null) { + continue; + } + Expr v = ((Assign) s).value; + if ("_typ".equals(n) && v instanceof Constant && ((Constant) v).kind == Constant.Kind.NONE) { + typAt = i; + } else if (v instanceof Call && ((Call) v).func instanceof Name + && NESTED.contains(((Name) ((Call) v).func).id)) { + elements.add(n); + } else if ("__elements__".equals(n) || OWN.contains(n)) { + return; + } + } + Collections.sort(elements); + int init = method(c, "__init__"); + int type = method(c, "type"); + int toTree = method(c, "to_tree"); + int fromTree = method(list, "from_tree"); + if (elements.isEmpty() || typAt < 0 || init < 0 || type < 0 || toTree < 0 || fromTree < 0 + || ((FunctionDef) c.body.get(init)).body.size() != 7 + || ((FunctionDef) c.body.get(type)).body.size() != 3 + || ((FunctionDef) c.body.get(toTree)).body.size() != 3) { + return; + } + if (!signature((FunctionDef) c.body.get(init))) { + return; + } + // CustomPropertyList.from_tree: value = getattr(prop, attr) + Stmt getattrStmt = null; + List holder = null; + for (Stmt s : ((FunctionDef) list.body.get(fromTree)).body) { + if (s instanceof Node.For) { + for (Stmt t : ((Node.For) s).body) { + if ("value".equals(assignedName(t)) && isCall(((Assign) t).value, "getattr", "prop", "attr")) { + getattrStmt = t; + holder = ((Node.For) s).body; + } + } + } + } + // CustomPropertyList.to_tree: np._typ = "lpwstr" + List typStores = new ArrayList(); + if (getattrStmt == null || !typStores(m, c, typStores)) { + return; + } + for (Object[] ts : typStores) { + if (!elements.contains((String) ts[3])) { + return; + } + } + StringBuilder b = new StringBuilder(); + b.append("def __init__(self, name=None, pid=0, fmtid=CPROPS_FMTID, linkTarget=None, **kw):\n") + .append(" self.fmtid = fmtid\n self.pid = pid\n self.name = name\n self._typ = None\n") + .append(" self._typ_get = None\n self._typ_set = None\n self.linkTarget = linkTarget\n") + .append(" n = 0\n"); + for (String e : elements) { + b.append(" if '").append(e).append("' in kw:\n self.").append(e).append(" = kw['").append(e) + .append("']\n n += 1\n").append(typ("self", e, " ")).append(" else:\n self.") + .append(e).append(" = None\n"); + } + b.append(" if n != len(kw):\n raise TypeError(\"unexpected keyword argument\")\n") + .append(" if n > 1:\n raise ValueError(\"a custom property holds one value\")\n"); + String initSrc = b.toString(); + b.setLength(0); + b.append("@property\ndef type(self):\n if self._typ is not None:\n return self._typ\n"); + for (String e : elements) { + b.append(" if self.").append(e).append(" is not None:\n return '").append(e).append("'\n"); + } + b.append(" if self.linkTarget is not None:\n return \"linkTarget\"\n"); + String typeSrc = b.toString(); + b.setLength(0); + b.append("def _type_value(self):\n if self._typ is not None:\n return self._typ_get(self)\n"); + for (String e : elements) { + b.append(" if self.").append(e).append(" is not None:\n return self.").append(e).append('\n'); + } + b.append(" if self.linkTarget is not None:\n return self.linkTarget\n") + .append(" raise TypeError(\"attribute name must be string\")\n"); + String valueSrc = b.toString(); + String treeSrc = "def to_tree(self, tagname=None, idx=None, namespace=None):\n" + + " if self._typ_get is None:\n raise TypeError(\"attribute name must be string\")\n" + + " child = self._typ_get(self)\n if child is None:\n self._typ_set(self, \"\")\n\n" + + " return super().to_tree(tagname=None, idx=None, namespace=None)\n"; + replace(c, init, initSrc, file); + replace(c, type, typeSrc, file); + replace(c, toTree, treeSrc, file); + c.body.addAll(typAt + 1, members("_typ_get = None\n_typ_set = None\n", file, c.body.get(typAt).line)); + c.body.addAll(members(valueSrc, file, c.body.get(c.body.size() - 1).line)); + int at = holder.indexOf(getattrStmt); + holder.set(at, members("value = prop._type_value()\n", file, getattrStmt.line).get(0)); + for (Object[] ts : typStores) { + @SuppressWarnings("unchecked") + List body = (List) ts[0]; + Stmt s = (Stmt) ts[1]; + String recv = (String) ts[2]; + String e = (String) ts[3]; + body.addAll(body.indexOf(s) + 1, members(typ(recv, e, "").replaceFirst("^[^\n]*\n", ""), file, s.line)); + } + } + + /// `__init__(self, name=None, pid=0, fmtid=CPROPS_FMTID, + /// linkTarget=None, **kw)` whose sixth and seventh statements are loops + /// (the ones this pass replaces), exactly as the template spells it. + private static boolean signature(FunctionDef f) { + Node.Arguments a = f.args; + String[] names = {"self", "name", "pid", "fmtid", "linkTarget"}; + if (a.positional.size() != names.length || a.kwarg == null || !"kw".equals(a.kwarg.name) + || a.vararg != null || !a.kwonly.isEmpty() || a.defaults.size() != 4) { + return false; + } + for (int i = 0; i < names.length; i++) { + if (!names[i].equals(a.positional.get(i).name)) { + return false; + } + } + Expr d0 = a.defaults.get(0); + Expr d1 = a.defaults.get(1); + Expr d2 = a.defaults.get(2); + Expr d3 = a.defaults.get(3); + return d0 instanceof Constant && ((Constant) d0).kind == Constant.Kind.NONE + && d1 instanceof Constant && "0".equals(((Constant) d1).text) + && d2 instanceof Name && "CPROPS_FMTID".equals(((Name) d2).id) + && d3 instanceof Constant && ((Constant) d3).kind == Constant.Kind.NONE + && f.body.get(5) instanceof Node.For && f.body.get(6) instanceof Node.For; + } + + private static String typ(String recv, String e, String ind) { + return ind + recv + "._typ = '" + e + "'\n" + ind + recv + "._typ_get = lambda o: o." + e + "\n" + + ind + recv + "._typ_set = lambda o, v: setattr(o, '" + e + "', v)\n"; + } + + /// Every `x._typ = ` in the module outside the class, which must + /// all be `name._typ = "literal"` statements directly in a block. + private static boolean typStores(Object o, ClassDef c, List out) { + if (o == c) { //NOPMD CompareObjectsWithEquals - identity + return true; + } + if (o instanceof List) { + for (Object x : (List) o) { + if (x instanceof Assign && ((Assign) x).targets.size() == 1 + && ((Assign) x).targets.get(0) instanceof Attribute + && "_typ".equals(((Attribute) ((Assign) x).targets.get(0)).attr)) { + Attribute a = (Attribute) ((Assign) x).targets.get(0); + Expr v = ((Assign) x).value; + if (!(a.value instanceof Name) || !(v instanceof Constant) + || ((Constant) v).kind != Constant.Kind.STR) { + return false; + } + out.add(new Object[] {o, x, ((Name) a.value).id, ((Constant) v).text}); + continue; + } + if (!typStores(x, c, out)) { + return false; + } + } + return true; + } + if (o instanceof Attribute && OWN.contains(((Attribute) o).attr)) { + return false; + } + if (o instanceof Node.If) { + return typStores(((Node.If) o).test, c, out) && typStores(((Node.If) o).body, c, out) + && typStores(((Node.If) o).orelse, c, out); + } + if (o instanceof Node.For) { + return typStores(((Node.For) o).target, c, out) && typStores(((Node.For) o).iter, c, out) + && typStores(((Node.For) o).body, c, out) && typStores(((Node.For) o).orelse, c, out); + } + if (o instanceof FunctionDef) { + return typStores(((FunctionDef) o).decorators, c, out) && typStores(((FunctionDef) o).args, c, out) + && typStores(((FunctionDef) o).body, c, out); + } + if (o instanceof ClassDef) { + return typStores(((ClassDef) o).bases, c, out) && typStores(((ClassDef) o).body, c, out); + } + final boolean[] ok = {true}; + Infer.children(o, x -> ok[0] &= typStores(x, c, out)); + return ok[0]; + } + + private static boolean isCall(Expr v, String f, String a0, String a1) { + if (!(v instanceof Call) || !(((Call) v).func instanceof Name) || !f.equals(((Name) ((Call) v).func).id)) { + return false; + } + Call c = (Call) v; + return c.keywords.isEmpty() && c.args.size() == 2 && c.args.get(0) instanceof Name + && a0.equals(((Name) c.args.get(0)).id) && c.args.get(1) instanceof Name + && a1.equals(((Name) c.args.get(1)).id); + } + + private static List members(String src, String file, int line) { + Node.Module parsed = Parser.parse("class _cp:\n" + src.replaceAll("(?m)^(?=.)", " "), file); + DataclassInit.atLine(parsed, line); + return ((ClassDef) parsed.body.get(0)).body; + } + + private static void replace(ClassDef c, int at, String src, String file) { + List body = members(src, file, c.body.get(at).line); + c.body.remove(at); + c.body.addAll(at, body); + } +} diff --git a/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/DataclassInit.java b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/DataclassInit.java new file mode 100644 index 00000000000..daa1d84097d --- /dev/null +++ b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/DataclassInit.java @@ -0,0 +1,1097 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.python.transpiler.codegen; + +import com.codename1.python.transpiler.api.PythonSyntaxError; +import com.codename1.python.transpiler.ast.Node; +import com.codename1.python.transpiler.ast.Node.Alias; +import com.codename1.python.transpiler.ast.Node.AnnAssign; +import com.codename1.python.transpiler.ast.Node.Assign; +import com.codename1.python.transpiler.ast.Node.Attribute; +import com.codename1.python.transpiler.ast.Node.Call; +import com.codename1.python.transpiler.ast.Node.ClassDef; +import com.codename1.python.transpiler.ast.Node.Constant; +import com.codename1.python.transpiler.ast.Node.Expr; +import com.codename1.python.transpiler.ast.Node.FunctionDef; +import com.codename1.python.transpiler.ast.Node.Import; +import com.codename1.python.transpiler.ast.Node.ImportFrom; +import com.codename1.python.transpiler.ast.Node.Keyword; +import com.codename1.python.transpiler.ast.Node.Name; +import com.codename1.python.transpiler.ast.Node.Stmt; +import com.codename1.python.transpiler.ast.Node.UnaryOp; +import com.codename1.python.transpiler.parser.Parser; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/// Every method a `@dataclass` class gets, written into the class at +/// compile time as plain Python that reads and writes `self.`. +/// +/// CPython's decorator builds the methods by exec'ing source text it puts +/// together from the field list. Nothing is compiled at run time here, so +/// this does the same one step earlier, right after parsing, as if the +/// author had written the methods: +/// +/// ```python +/// @dataclass(order=True) +/// class Version: +/// major: int +/// minor: int = 0 +/// # added: +/// def __init__(self, major, minor=minor): +/// self.major = major +/// self.minor = minor +/// def __repr__(self): ... # Version(major=1, minor=0) +/// def __eq__(self, other): ... # (self.major, self.minor) == (...) +/// def __lt__(self, other): ... # and __le__, __gt__, __ge__ +/// __hash__ = None +/// __match_args__ = ("major", "minor",) +/// def __cn1_asdict__(self, dict_factory): ... +/// def __cn1_astuple__(self, tuple_factory): ... +/// def __replace__(self, *, major=MISSING, minor=MISSING): ... +/// ``` +/// +/// The decorator still runs, and only records what CPython's records: +/// `__dataclass_fields__`, `__dataclass_params__`, the frozen +/// `__setattr__`. It checks that the fields it finds are the ones this +/// class wrote methods for, so a base the build could not see (one +/// imported from another module) is an error when the class is made, never +/// a constructor that silently drops a field. +/// +/// A default is the class attribute of the same name, read when the method +/// is defined at the end of the class body (an inherited one through the +/// base it was inherited from): the very object the decorator would have +/// used. A `default_factory` is called by name in the constructor. A shape +/// the build cannot lower -- options that are not constants, a factory that +/// is not a name, a field annotated under an `if` -- fails the build naming +/// the line. +public final class DataclassInit { + private static final Set FIELD_KEYWORDS = new HashSet(java.util.Arrays.asList("default", + "default_factory", "init", "repr", "hash", "compare", "metadata", "kw_only")); + private static final String MISSING = "_cn1_dc_MISSING"; + + private DataclassInit() { + } + + /// Rewrites the dataclasses of `tree`, the module at path `path`. + public static void rewrite(Node.Module tree, String path) { + Set deco = new HashSet(); + Set field = new HashSet(); + Set modules = new HashSet(); + Set make = new HashSet(); + Set wrapped = new HashSet(); + for (Stmt s : tree.body) { + if (s instanceof ImportFrom && "pydantic.dataclasses".equals(((ImportFrom) s).module) + && ((ImportFrom) s).level == 0) { + // pydantic's decorator runs the standard one and then wraps + // the constructor it made; the class is lowered all the same. + for (Alias a : ((ImportFrom) s).names) { + if ("dataclass".equals(a.name)) { + wrapped.add(a.asname != null ? a.asname : a.name); + } + } + } + if (s instanceof ImportFrom && "dataclasses".equals(((ImportFrom) s).module) && ((ImportFrom) s).level == 0) { + for (Alias a : ((ImportFrom) s).names) { + String bound = a.asname != null ? a.asname : a.name; + if ("dataclass".equals(a.name)) { + deco.add(bound); + } else if ("field".equals(a.name)) { + field.add(bound); + } else if ("make_dataclass".equals(a.name)) { + make.add(bound); + } + } + } else if (s instanceof Import) { + for (Alias a : ((Import) s).names) { + if ("dataclasses".equals(a.name)) { + modules.add(a.asname != null ? a.asname : a.name); + } + } + } + } + deco.addAll(wrapped); + if (deco.isEmpty() && modules.isEmpty() && make.isEmpty()) { + return; + } + makeDataclasses(tree, make, modules, deco); + List decorated = new ArrayList(); + for (Stmt s : tree.body) { + decorated(s, deco, modules, decorated); + } + if (decorated.isEmpty()) { + return; + } + Map bindings = new HashMap(); + for (Stmt s : tree.body) { + count(s, bindings); + } + Set used = new HashSet(deco); + used.addAll(field); + used.addAll(modules); + for (String n : used) { + if (bindings.getOrDefault(n, 0) != 1) { + throw error(path, decorated.get(0), "'" + n + "' is bound more than once in this module; a dataclass" + + " is lowered at build time only while the names it is made with are bound once, by" + + " their import"); + } + } + Map classes = new HashMap(); + allClasses(tree, classes); + Map models = new HashMap(); + boolean pdImport = false; + for (ClassDef c : decorated) { + Model m = model(c, path, deco, field, modules, classes, models, bindings); + models.put(c.name, m); + specs(c, field, modules); + boolean pd = false; + for (Expr d : c.decorators) { + pd |= isDataclass(d instanceof Call ? ((Call) d).func : d, wrapped, new HashSet()); + } + generate(c, m, path, pd); + if (pd) { + pdImport = true; + } + } + List names = new ArrayList(); + names.add(new Alias("MISSING", MISSING)); + names.add(new Alias("_repr_enter", "_cn1_dc_repr_enter")); + names.add(new Alias("_repr_leave", "_cn1_dc_repr_leave")); + names.add(new Alias("_asdict_inner", "_cn1_dc_asdict_inner")); + names.add(new Alias("_astuple_inner", "_cn1_dc_astuple_inner")); + ImportFrom imp = new ImportFrom("dataclasses", 0, names); + int i = 0; + while (i < tree.body.size() && (tree.body.get(i) instanceof ImportFrom + && "__future__".equals(((ImportFrom) tree.body.get(i)).module) + || i == 0 && tree.body.get(i) instanceof Node.ExprStmt)) { + i++; + } + at(imp, decorated.get(0).line); + tree.body.add(i, imp); + if (pdImport) { + List pdNames = new ArrayList(); + pdNames.add(new Alias("_cn1_validate", "_cn1_pd_dc_validate")); + ImportFrom pdImp = new ImportFrom("pydantic.dataclasses", 0, pdNames); + at(pdImp, decorated.get(0).line); + tree.body.add(i + 1, pdImp); + } + } + + private static void allClasses(Object o, Map out) { + if (o instanceof ClassDef) { + out.put(((ClassDef) o).name, (ClassDef) o); + } + Infer.children(o, x -> allClasses(x, out)); + } + + private static PythonSyntaxError error(String path, Node at, String why) { + return new PythonSyntaxError(path, at.line, 1, why); + } + + /// Every class under `o`, at any depth, that a dataclass decorator + /// names. + private static void decorated(Object o, Set deco, Set modules, List out) { + if (o instanceof ClassDef) { + for (Expr d : ((ClassDef) o).decorators) { + Expr f = d instanceof Call ? ((Call) d).func : d; + if (isDataclass(f, deco, modules)) { + out.add((ClassDef) o); + break; + } + } + } + Infer.children(o, x -> decorated(x, deco, modules, out)); + } + + /// `Name = make_dataclass("Name", [...], flag=True)` with a literal + /// field list, at module level, becomes the class statement it stands + /// for, so it is lowered like any other. The runtime builds no class + /// from a list of names. + private static void makeDataclasses(Node.Module tree, Set make, Set modules, + Set deco) { + boolean imported = false; + for (int i = 0; i < tree.body.size(); i++) { + Stmt s = tree.body.get(i); + if (!(s instanceof Assign) || ((Assign) s).targets.size() != 1 + || !(((Assign) s).targets.get(0) instanceof Name) || !(((Assign) s).value instanceof Call)) { + continue; + } + Call c = (Call) ((Assign) s).value; + boolean named = c.func instanceof Name && make.contains(((Name) c.func).id) + || c.func instanceof Attribute && "make_dataclass".equals(((Attribute) c.func).attr) + && ((Attribute) c.func).value instanceof Name + && modules.contains(((Name) ((Attribute) c.func).value).id); + String target = ((Name) ((Assign) s).targets.get(0)).id; + if (!named || c.args.size() != 2 || !(c.args.get(0) instanceof Constant) + || ((Constant) c.args.get(0)).kind != Constant.Kind.STR + || !target.equals(((Constant) c.args.get(0)).text) + || !(c.args.get(1) instanceof Node.ListExpr || c.args.get(1) instanceof Node.TupleExpr)) { + continue; + } + List items = c.args.get(1) instanceof Node.ListExpr ? ((Node.ListExpr) c.args.get(1)).elts + : ((Node.TupleExpr) c.args.get(1)).elts; + List body = new ArrayList(); + boolean ok = true; + for (Expr it : items) { + if (it instanceof Constant && ((Constant) it).kind == Constant.Kind.STR) { + body.add(new AnnAssign(new Name(((Constant) it).text), + new Constant(Constant.Kind.STR, "typing.Any"), null)); + continue; + } + List parts = it instanceof Node.TupleExpr ? ((Node.TupleExpr) it).elts + : it instanceof Node.ListExpr ? ((Node.ListExpr) it).elts : null; + if (parts == null || parts.size() < 2 || parts.size() > 3 || !(parts.get(0) instanceof Constant) + || ((Constant) parts.get(0)).kind != Constant.Kind.STR) { + ok = false; + break; + } + body.add(new AnnAssign(new Name(((Constant) parts.get(0)).text), parts.get(1), + parts.size() == 3 ? parts.get(2) : null)); + } + List kws = new ArrayList(); + for (Keyword k : c.keywords) { + if (k.arg == null || !isBool(k.value)) { + ok = false; + break; + } + kws.add(k); + } + if (!ok) { + continue; + } + if (body.isEmpty()) { + body.add(new Node.Pass()); + } + Call d = new Call(new Name("_cn1_dataclass")); + d.keywords.addAll(kws); + List decos = new ArrayList(); + decos.add(d); + ClassDef k = new ClassDef(target, new ArrayList(), new ArrayList(), body, decos); + at(k, s.line); + tree.body.set(i, k); + if (!imported) { + List names = new ArrayList(); + names.add(new Alias("dataclass", "_cn1_dataclass")); + ImportFrom imp = new ImportFrom("dataclasses", 0, names); + at(imp, s.line); + tree.body.add(i, imp); + i++; + imported = true; + deco.add("_cn1_dataclass"); + } + } + } + + /// Moves every `x: T = field(...)` out of the class attributes: the + /// `Field` objects go into `__dataclass_field_specs__`, a dict the + /// decorator reads by key, and the attribute keeps the default alone + /// (or nothing). The runtime then never deletes or rebinds a class + /// attribute by a name it computed, as CPython's decorator does. + private static void specs(ClassDef c, Set field, Set modules) { + int first = -1; + Node.DictExpr dict = new Node.DictExpr(); + for (int i = 0; i < c.body.size(); i++) { + Stmt s = c.body.get(i); + if (!(s instanceof AnnAssign) || !(((AnnAssign) s).target instanceof Name) + || !(((AnnAssign) s).value instanceof Call) + || !isField(((Call) ((AnnAssign) s).value).func, field, modules)) { + continue; + } + AnnAssign a = (AnnAssign) s; + String n = ((Name) a.target).id; + Call fc = (Call) a.value; + Expr dflt = null; + for (Keyword k : fc.keywords) { + if ("default".equals(k.arg)) { + dflt = literal(k.value) ? copy(k.value) + : new Attribute(new Node.Subscript(new Name("__dataclass_field_specs__"), + new Constant(Constant.Kind.STR, n)), "default"); + } + } + dict.keys.add(new Constant(Constant.Kind.STR, n)); + dict.values.add(fc); + AnnAssign r = new AnnAssign(a.target, a.annotation, dflt); + at(r, s.line); + fc.line = s.line; + c.body.set(i, r); + if (first < 0) { + first = i; + } + } + if (first < 0) { + return; + } + List t = new ArrayList(); + t.add(new Name("__dataclass_field_specs__")); + Assign spec = new Assign(t, dict); + spec.line = c.body.get(first).line; + t.get(0).line = spec.line; + dict.line = spec.line; + c.body.add(first, spec); + } + + /// How many times each module-level name is bound: by a store, a def, + /// a class or an import, at the top level or in any nested block. + static void count(Object o, Map n) { + if (o instanceof FunctionDef) { + n.merge(((FunctionDef) o).name, 1, Integer::sum); + return; + } + if (o instanceof ClassDef) { + n.merge(((ClassDef) o).name, 1, Integer::sum); + return; + } + if (o instanceof Import) { + for (Alias a : ((Import) o).names) { + String b = a.asname != null ? a.asname : a.name; + int dot = b.indexOf('.'); + n.merge(dot < 0 ? b : b.substring(0, dot), 1, Integer::sum); + } + return; + } + if (o instanceof ImportFrom) { + for (Alias a : ((ImportFrom) o).names) { + n.merge(a.asname != null ? a.asname : a.name, 1, Integer::sum); + } + return; + } + if (o instanceof Name) { + // Any store or delete through a plain name; loads count too, + // which only makes the test stricter for names that are read. + return; + } + if (o instanceof Assign) { + for (Expr t : ((Assign) o).targets) { + targets(t, n); + } + } else if (o instanceof AnnAssign && ((AnnAssign) o).value != null) { + targets(((AnnAssign) o).target, n); + } else if (o instanceof Node.AugAssign) { + targets(((Node.AugAssign) o).target, n); + } else if (o instanceof Node.For) { + targets(((Node.For) o).target, n); + } else if (o instanceof Node.Global || o instanceof Node.Delete || o instanceof Node.With + || o instanceof Node.Try || o instanceof Node.NamedExpr) { + // A rebinding this does not follow name by name: every name the + // statement mentions counts as bound twice. + Infer.children(o, x -> { + if (x instanceof Name) { + n.merge(((Name) x).id, 2, Integer::sum); + } + }); + } + if (!(o instanceof Node.Global)) { + Infer.children(o, x -> count(x, n)); + } + } + + private static void targets(Expr t, Map n) { + if (t instanceof Name) { + n.merge(((Name) t).id, 1, Integer::sum); + } else if (t instanceof Node.TupleExpr) { + for (Expr e : ((Node.TupleExpr) t).elts) { + targets(e, n); + } + } else if (t instanceof Node.ListExpr) { + for (Expr e : ((Node.ListExpr) t).elts) { + targets(e, n); + } + } else if (t instanceof Node.Starred) { + targets(((Node.Starred) t).value, n); + } + } + + /// One field, as the decorator sees it: a plain field or an `InitVar`. + private static final class Field { + final String name; + boolean initVar; + boolean init = true; + boolean kwOnly; + boolean repr = true; + boolean compare = true; + /// Null to follow `compare`. + Boolean hash; + boolean hasDefault; + /// The base this field was inherited through, whose attribute holds + /// the default; null for a field of the class itself. + String owner; + /// The factory, as source: a name or a dotted name. + String factory; + + Field(String name) { + this.name = name; + } + + Field inherited(String base) { + Field f = new Field(name); + f.initVar = initVar; + f.init = init; + f.kwOnly = kwOnly; + f.repr = repr; + f.compare = compare; + f.hash = hash; + f.hasDefault = hasDefault; + f.factory = factory; + f.owner = base; + return f; + } + + /// The parameter default: the class attribute, the "not passed" + /// marker for a factory, or null for none. + Expr dflt() { + if (factory != null) { + return new Name(MISSING); + } + if (!hasDefault) { + return null; + } + return owner == null ? new Name(name) : new Attribute(new Name(owner), name); + } + + boolean hashed() { + return hash == null ? compare : hash; + } + } + + /// A dataclass: its options and its fields, inherited ones first. + private static final class Model { + final List fields = new ArrayList(); + final Map index = new HashMap(); + /// Every name the class body binds. + final Set own = new HashSet(); + boolean init = true; + boolean repr = true; + boolean eq = true; + boolean order; + boolean unsafeHash; + boolean frozen; + boolean matchArgs = true; + boolean kwOnly; + boolean postInit; + /// Every base is the module's own, so all fields are known here. + boolean closed = true; + boolean dataclassBase; + + void put(Field f) { + Integer i = index.get(f.name); + if (i == null) { + index.put(f.name, fields.size()); + fields.add(f); + } else { + fields.set(i, f); + } + } + } + + private static Model model(ClassDef c, String path, Set deco, Set field, Set modules, + Map classes, Map models, Map bindings) { + Model m = new Model(); + for (Expr d : c.decorators) { + if (!(d instanceof Call) || !isDataclass(((Call) d).func, deco, modules)) { + continue; + } + Call dc = (Call) d; + if (!dc.args.isEmpty()) { + throw error(path, c, "@dataclass takes its options by keyword"); + } + for (Keyword k : dc.keywords) { + options(path, c, k, m); + } + } + if (m.order && !m.eq) { + throw error(path, c, "eq must be true if order is true"); + } + // Reverse MRO order, exact for a single chain of bases. + for (int i = c.bases.size() - 1; i >= 0; i--) { + Expr b = c.bases.get(i); + inherit(b, b instanceof Name ? ((Name) b).id : null, m, classes, models, new HashSet()); + } + boolean kwOnly = m.kwOnly; + for (Stmt s : c.body) { + if (s instanceof FunctionDef) { + m.own.add(((FunctionDef) s).name); + } else if (s instanceof Assign) { + for (Expr t : ((Assign) s).targets) { + if (t instanceof Name) { + m.own.add(((Name) t).id); + } + } + } else if (s instanceof AnnAssign && ((AnnAssign) s).target instanceof Name) { + AnnAssign a = (AnnAssign) s; + String n = ((Name) a.target).id; + String kind = kind(a.annotation); + if ("ClassVar".equals(kind)) { + continue; + } + if ("KW_ONLY".equals(kind)) { + kwOnly = true; + continue; + } + if ("self".equals(n) || n.startsWith("__") && !n.endsWith("__")) { + throw error(path, s, "a dataclass field named '" + n + "' cannot be lowered at build time"); + } + Field f = new Field(n); + f.kwOnly = kwOnly; + f.initVar = "InitVar".equals(kind); + if (a.value instanceof Call && isField(((Call) a.value).func, field, modules)) { + fieldCall(path, s, (Call) a.value, f, bindings); + } else { + f.hasDefault = a.value != null; + } + m.put(f); + } else if (!(s instanceof ClassDef)) { + boolean[] bad = {false}; + annotations(s, bad); + if (bad[0]) { + throw error(path, s, "a dataclass field annotated inside a conditional or a loop cannot be" + + " lowered at build time"); + } + } + } + m.postInit |= m.own.contains("__post_init__"); + String seenDefault = null; + for (Field f : m.fields) { + if (!f.init || f.kwOnly) { + continue; + } + if (f.hasDefault || f.factory != null) { + seenDefault = f.name; + } else if (seenDefault != null) { + throw error(path, c, "non-default argument '" + f.name + "' follows default argument '" + + seenDefault + "'"); + } + } + for (Field f : m.fields) { + if (f.factory != null) { + String root = f.factory.indexOf('.') < 0 ? f.factory : f.factory.substring(0, f.factory.indexOf('.')); + if (m.index.containsKey(root)) { + throw error(path, c, "the default_factory of field '" + f.name + "' is named like a field"); + } + } + if (m.frozen && "object".equals(f.name)) { + throw error(path, c, "a frozen dataclass field named 'object' cannot be lowered at build time"); + } + } + return m; + } + + private static void options(String path, ClassDef c, Keyword k, Model m) { + if (k.arg == null || !isBool(k.value)) { + throw error(path, c, "@dataclass options must be the constants True or False to be lowered at build" + + " time"); + } + boolean v = isTrue(k.value); + switch (k.arg) { + case "init": + m.init = v; + break; + case "repr": + m.repr = v; + break; + case "eq": + m.eq = v; + break; + case "order": + m.order = v; + break; + case "unsafe_hash": + m.unsafeHash = v; + break; + case "frozen": + m.frozen = v; + break; + case "match_args": + m.matchArgs = v; + break; + case "kw_only": + m.kwOnly = v; + break; + case "slots": + case "weakref_slot": + // Instances have a fixed layout either way; no new class + // replaces this one. + break; + default: + throw error(path, c, "unknown @dataclass option " + k.arg); + } + } + + /// The fields base `b` gives, reached through `via`, the base the class + /// names. + private static void inherit(Expr b, String via, Model m, Map classes, + Map models, Set seen) { + if (b instanceof Name && "object".equals(((Name) b).id)) { + return; + } + if (!(b instanceof Name) || !seen.add(((Name) b).id)) { + m.closed = false; + return; + } + String n = ((Name) b).id; + Model bm = models.get(n); + if (bm != null) { + for (Field f : bm.fields) { + m.put(f.inherited(via)); + } + m.postInit |= bm.postInit; + m.closed &= bm.closed; + // A dataclass base that kept its layout (non-frozen, so no + // decorator __setattr__ stands between generated code and its + // fields) is a plain compiled parent; any other blocks one. + ClassDef bk = classes.get(n); + m.dataclassBase |= bk == null || !bk.dataclass || bm.frozen; + return; + } + ClassDef k = classes.get(n); + if (k == null || !k.decorators.isEmpty()) { + m.closed = false; + return; + } + if (!plainBase(b, classes, new HashSet())) { + m.closed = false; + } + for (Stmt s : k.body) { + if (s instanceof FunctionDef && "__post_init__".equals(((FunctionDef) s).name)) { + m.postInit = true; + } + } + for (int i = k.bases.size() - 1; i >= 0; i--) { + inherit(k.bases.get(i), via, m, classes, models, seen); + } + } + + /// `ClassVar`, `InitVar` or `KW_ONLY` for an annotation that is one, + /// spelled as the runtime decorator recognizes it; null for a field. + private static String kind(Expr a) { + String n = null; + if (a instanceof Constant && ((Constant) a).kind == Constant.Kind.STR) { + String s = ((Constant) a).text; + n = s.startsWith("ClassVar") || s.startsWith("typing.ClassVar") ? "ClassVar" + : s.startsWith("InitVar") ? "InitVar" + : "KW_ONLY".equals(s) || "dataclasses.KW_ONLY".equals(s) ? "KW_ONLY" : null; + return n; + } + Expr t = a instanceof Node.Subscript ? ((Node.Subscript) a).value : a; + n = t instanceof Name ? ((Name) t).id : t instanceof Attribute ? ((Attribute) t).attr : null; + return "ClassVar".equals(n) || "InitVar".equals(n) || "KW_ONLY".equals(n) ? n : null; + } + + /// Whether `o`, a statement of a class body, annotates a name in a + /// nested block. + private static void annotations(Object o, boolean[] bad) { + if (o instanceof FunctionDef || o instanceof ClassDef || o instanceof Node.Lambda) { + return; + } + if (o instanceof AnnAssign && ((AnnAssign) o).target instanceof Name) { + bad[0] = true; + return; + } + Infer.children(o, x -> annotations(x, bad)); + } + + /// `field(...)`, read into `f`. + private static void fieldCall(String path, Stmt s, Call c, Field f, Map bindings) { + if (!c.args.isEmpty()) { + throw error(path, s, "field() takes its options by keyword"); + } + for (Keyword k : c.keywords) { + if (k.arg == null || !FIELD_KEYWORDS.contains(k.arg)) { + throw error(path, s, "field() option " + (k.arg == null ? "**" : k.arg) + + " cannot be lowered at build time"); + } + switch (k.arg) { + case "default": + f.hasDefault = true; + break; + case "default_factory": + f.factory = dotted(k.value); + if (f.factory == null || bindings.getOrDefault(f.factory.split("\\.")[0], 0) > 1) { + throw error(path, s, "a default_factory must be a name or a dotted name bound once to be" + + " lowered at build time"); + } + break; + case "init": + f.init = flag(path, s, k); + break; + case "kw_only": + f.kwOnly = flag(path, s, k); + break; + case "repr": + f.repr = flag(path, s, k); + break; + case "compare": + f.compare = flag(path, s, k); + break; + case "hash": + f.hash = k.value instanceof Constant && ((Constant) k.value).kind == Constant.Kind.NONE ? null + : Boolean.valueOf(flag(path, s, k)); + break; + default: + // metadata: nothing a generated method reads. + break; + } + } + if (f.hasDefault && f.factory != null) { + throw error(path, s, "cannot specify both default and default_factory"); + } + if (f.initVar && f.factory != null) { + throw error(path, s, "field " + f.name + " cannot have a default factory"); + } + } + + private static boolean flag(String path, Stmt s, Keyword k) { + if (!isBool(k.value)) { + throw error(path, s, "field() option " + k.arg + " must be True or False to be lowered at build time"); + } + return isTrue(k.value); + } + + private static String dotted(Expr e) { + if (e instanceof Name) { + return ((Name) e).id; + } + if (e instanceof Attribute) { + String v = dotted(((Attribute) e).value); + return v == null ? null : v + "." + ((Attribute) e).attr; + } + return null; + } + + /// Writes the methods of `m` into `c`. + private static void generate(ClassDef c, Model m, String path, boolean pd) { + List plain = new ArrayList(); + List std = new ArrayList(); + List kw = new ArrayList(); + List compared = new ArrayList(); + List hashed = new ArrayList(); + List initVars = new ArrayList(); + StringBuilder names = new StringBuilder("("); + for (Field f : m.fields) { + names.append('"').append(f.name).append("\", "); + if (f.initVar) { + initVars.add(f.name); + } else { + plain.add(f); + if (f.compare) { + compared.add(f.name); + } + if (f.hashed()) { + hashed.add(f.name); + } + } + if (f.init) { + (f.kwOnly ? kw : std).add(f); + } + } + names.append(')'); + StringBuilder src = new StringBuilder(); + boolean init = m.init && !m.own.contains("__init__"); + List initDefaults = new ArrayList(); + List initKwDefaults = new ArrayList(); + if (init) { + // pydantic's dataclass validates after the standard constructor: + // that one is generated under its own name, and __init__ runs it + // and then the validator over one literal accessor per field. + src.append(pd ? "def __cn1_dc_init__(self" : "def __init__(self"); + for (Field f : std) { + src.append(", ").append(f.name); + Expr d = f.dflt(); + if (d != null) { + src.append("=None"); + initDefaults.add(d); + } + } + if (!kw.isEmpty()) { + src.append(", *"); + } + for (Field f : kw) { + src.append(", ").append(f.name); + Expr d = f.dflt(); + if (d != null) { + src.append("=None"); + } + initKwDefaults.add(d); + } + src.append("):\n"); + int stores = 0; + for (Field f : plain) { + String v; + if (f.init) { + v = f.factory != null ? f.factory + "() if " + f.name + " is " + MISSING + " else " + f.name + : f.name; + } else if (f.factory != null) { + v = f.factory + "()"; + } else if (f.hasDefault) { + v = "self.__class__." + f.name; + } else { + continue; + } + if (m.frozen) { + src.append(" object.__setattr__(self, \"").append(f.name).append("\", ").append(v).append(")\n"); + } else { + src.append(" self.").append(f.name).append(" = ").append(v).append('\n'); + } + c.dataclassFields.add(f.name); + stores++; + } + if (m.postInit) { + src.append(" self.__post_init__(").append(String.join(", ", initVars)).append(")\n"); + stores++; + } + if (stores == 0) { + src.append(" pass\n"); + } + if (pd) { + src.append("def __init__(self, *_cn1_a, **_cn1_k):\n self.__cn1_dc_init__(*_cn1_a, **_cn1_k)\n") + .append(" _cn1_pd_dc_validate(self, len(_cn1_a), ("); + for (Field f : plain) { + src.append("(\"").append(f.name).append("\", lambda _cn1_o: _cn1_o.").append(f.name) + .append(", lambda _cn1_o, _cn1_v: object.__setattr__(_cn1_o, \"").append(f.name) + .append("\", _cn1_v)), "); + } + src.append("))\n__cn1_pd_validated__ = True\n"); + } + } + if (m.repr && !m.own.contains("__repr__")) { + src.append("def __repr__(self):\n if _cn1_dc_repr_enter(self):\n return \"...\"\n try:\n") + .append(" return self.__class__.__qualname__ + \"("); + String sep = ""; + for (Field f : plain) { + if (f.repr) { + src.append(sep).append(f.name).append("=\" + repr(self.").append(f.name).append(") + \""); + sep = ", "; + } + } + src.append(")\"\n finally:\n _cn1_dc_repr_leave(self)\n") + .append("__repr__._dataclass_repr = True\n"); + // The fields the repr shows, name and value, for pprint: it + // reads them here rather than by a computed attribute name. + src.append("def __cn1_repr_items__(self):\n return ["); + for (Field f : plain) { + if (f.repr) { + src.append("(\"").append(f.name).append("\", self.").append(f.name).append("), "); + } + } + src.append("]\n"); + } + if (m.eq && !m.own.contains("__eq__")) { + src.append("def __eq__(self, other):\n if self is other:\n return True\n") + .append(" if other.__class__ is self.__class__:\n return ").append(tuple(compared, "self")) + .append(" == ").append(tuple(compared, "other")).append("\n return NotImplemented\n"); + } + if (m.order) { + String[][] ops = {{"__lt__", "<"}, {"__le__", "<="}, {"__gt__", ">"}, {"__ge__", ">="}}; + for (String[] op : ops) { + if (m.own.contains(op[0])) { + throw error(path, c, "Cannot overwrite attribute " + op[0] + " in class " + c.name + + ". Consider using functools.total_ordering"); + } + src.append("def ").append(op[0]).append("(self, other):\n") + .append(" if other.__class__ is self.__class__:\n return ") + .append(tuple(compared, "self")).append(' ').append(op[1]).append(' ') + .append(tuple(compared, "other")).append("\n return NotImplemented\n"); + } + } + boolean explicitHash = m.own.contains("__hash__"); + if (m.unsafeHash && explicitHash) { + throw error(path, c, "Cannot overwrite attribute __hash__ in class " + c.name); + } + if (m.unsafeHash || !explicitHash && m.eq && m.frozen) { + src.append("def __hash__(self):\n return hash(").append(tuple(hashed, "self")).append(")\n"); + } else if (!explicitHash && m.eq) { + src.append("__hash__ = None\n"); + } + if (m.matchArgs && !m.own.contains("__match_args__")) { + src.append("__match_args__ = ("); + for (Field f : std) { + src.append('"').append(f.name).append("\", "); + } + src.append(")\n"); + } + src.append("def __cn1_asdict__(self, dict_factory):\n return dict_factory(["); + for (Field f : plain) { + src.append("(\"").append(f.name).append("\", _cn1_dc_asdict_inner(self.").append(f.name) + .append(", dict_factory)), "); + } + src.append("])\ndef __cn1_astuple__(self, tuple_factory):\n return tuple_factory(["); + for (Field f : plain) { + src.append("_cn1_dc_astuple_inner(self.").append(f.name).append(", tuple_factory), "); + } + src.append("])\n"); + List replaceDefaults = new ArrayList(); + if (!m.own.contains("__replace__")) { + src.append("def __replace__(self"); + if (!m.fields.isEmpty()) { + src.append(", *"); + } + StringBuilder checks = new StringBuilder(); + StringBuilder call = new StringBuilder(); + for (Field f : m.fields) { + src.append(", ").append(f.name).append("=None"); + Expr d = f.initVar ? f.dflt() : null; + replaceDefaults.add(d != null ? d : new Name(MISSING)); + if (!f.init) { + checks.append(" if ").append(f.name).append(" is not ").append(MISSING) + .append(":\n raise TypeError(\"field ").append(f.name) + .append(" is declared with init=False, it cannot be specified with replace()\")\n"); + continue; + } + if (f.initVar) { + if (d == null) { + checks.append(" if ").append(f.name).append(" is ").append(MISSING) + .append(":\n raise TypeError(\"InitVar '").append(f.name) + .append("' must be specified with replace()\")\n"); + } + call.append(f.name).append('=').append(f.name).append(", "); + } else { + call.append(f.name).append("=self.").append(f.name).append(" if ").append(f.name).append(" is ") + .append(MISSING).append(" else ").append(f.name).append(", "); + } + } + src.append("):\n").append(checks).append(" return self.__class__(").append(call).append(")\n"); + } + src.append("__cn1_dc_lowered__ = (").append(names).append(", ") + .append(init ? m.postInit ? "True" : "False" : "None").append(")\n"); + int line = c.body.isEmpty() ? c.line : c.body.get(c.body.size() - 1).line; + for (Stmt s : Parser.parse(src.toString(), path).body) { + if (s instanceof FunctionDef && (pd ? "__cn1_dc_init__" : "__init__").equals(((FunctionDef) s).name)) { + FunctionDef fd = (FunctionDef) s; + for (int i = 0; i < initDefaults.size(); i++) { + fd.args.defaults.set(i, initDefaults.get(i)); + } + for (int i = 0; i < initKwDefaults.size(); i++) { + fd.args.kwDefaults.set(i, initKwDefaults.get(i)); + } + fd.dataclassInit = true; + } else if (s instanceof FunctionDef && "__replace__".equals(((FunctionDef) s).name)) { + FunctionDef fd = (FunctionDef) s; + for (int i = 0; i < replaceDefaults.size(); i++) { + fd.args.kwDefaults.set(i, replaceDefaults.get(i)); + } + } + at(s, line); + c.body.add(s); + } + // A class keeps a layout when every field it stores is known here. + // A frozen class takes its __setattr__ from the decorator, so + // generated code never stores its fields directly + // (Layouts.Cls#frozenStores); it keeps a layout only with no base, + // so no compiled ancestor's code stores into it either. + c.dataclass = c.decorators.size() == 1 && m.closed && !m.dataclassBase && !(m.frozen && !c.bases.isEmpty()); + c.dataclassFrozen = m.frozen; + } + + /// `(x.a, x.b, )`, the compared or hashed fields of `x` as a tuple. + private static String tuple(List names, String x) { + StringBuilder b = new StringBuilder("("); + for (String n : names) { + b.append(x).append('.').append(n).append(", "); + } + return b.append(')').toString(); + } + + private static boolean isDataclass(Expr e, Set deco, Set modules) { + return e instanceof Name && deco.contains(((Name) e).id) + || e instanceof Attribute && "dataclass".equals(((Attribute) e).attr) + && ((Attribute) e).value instanceof Name && modules.contains(((Name) ((Attribute) e).value).id); + } + + private static boolean isField(Expr e, Set field, Set modules) { + return e instanceof Name && field.contains(((Name) e).id) + || e instanceof Attribute && "field".equals(((Attribute) e).attr) + && ((Attribute) e).value instanceof Name && modules.contains(((Name) ((Attribute) e).value).id); + } + + /// A literal whose value does not depend on when it is evaluated. + private static boolean literal(Expr e) { + if (e instanceof Constant) { + return true; + } + return e instanceof UnaryOp && ("-".equals(((UnaryOp) e).op) || "+".equals(((UnaryOp) e).op)) + && ((UnaryOp) e).operand instanceof Constant; + } + + private static Expr copy(Expr e) { + if (e instanceof Constant) { + return new Constant(((Constant) e).kind, ((Constant) e).text); + } + UnaryOp u = (UnaryOp) e; + return new UnaryOp(u.op, copy(u.operand)); + } + + /// Whether `e` is the constant True or False. + private static boolean isBool(Expr e) { + return e instanceof Constant && (((Constant) e).kind == Constant.Kind.TRUE + || ((Constant) e).kind == Constant.Kind.FALSE); + } + + private static boolean isTrue(Expr e) { + return e instanceof Constant && ((Constant) e).kind == Constant.Kind.TRUE; + } + + private static boolean plainBase(Expr b, Map classes, Set seen) { + if (b instanceof Name && "object".equals(((Name) b).id)) { + return true; + } + if (!(b instanceof Name) || !seen.add(((Name) b).id)) { + return false; + } + ClassDef k = classes.get(((Name) b).id); + if (k == null || !k.decorators.isEmpty() || !k.keywords.isEmpty()) { + return false; + } + for (Stmt s : k.body) { + // An annotation alone binds nothing on an undecorated class, so + // the decorator neither makes it a field nor reads a default + // from it; one with a value is a class attribute the decorator's + // getattr would take as a field's default. + if (s instanceof AnnAssign && ((AnnAssign) s).value != null) { + return false; + } + } + for (Expr e : k.bases) { + if (!plainBase(e, classes, seen)) { + return false; + } + } + return true; + } + + /// Gives every node under `o` source line `line`, so generated code + /// reports against the declaration it replaced. + static void atLine(Object o, int line) { + at(o, line); + } + + private static void at(Object o, int line) { + if (o instanceof Node) { + ((Node) o).line = line; + } + Infer.children(o, x -> at(x, line)); + } +} diff --git a/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/DeclarativeMap.java b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/DeclarativeMap.java new file mode 100644 index 00000000000..42c0e5ad35c --- /dev/null +++ b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/DeclarativeMap.java @@ -0,0 +1,1816 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.python.transpiler.codegen; + +import com.codename1.python.transpiler.ast.Node; +import com.codename1.python.transpiler.ast.Node.Alias; +import com.codename1.python.transpiler.ast.Node.Assign; +import com.codename1.python.transpiler.ast.Node.Attribute; +import com.codename1.python.transpiler.ast.Node.Call; +import com.codename1.python.transpiler.ast.Node.ClassDef; +import com.codename1.python.transpiler.ast.Node.Constant; +import com.codename1.python.transpiler.ast.Node.Expr; +import com.codename1.python.transpiler.ast.Node.FunctionDef; +import com.codename1.python.transpiler.ast.Node.Import; +import com.codename1.python.transpiler.ast.Node.ImportFrom; +import com.codename1.python.transpiler.ast.Node.Keyword; +import com.codename1.python.transpiler.ast.Node.Name; +import com.codename1.python.transpiler.ast.Node.Stmt; +import com.codename1.python.transpiler.parser.Parser; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/// Lowers openpyxl's declarative descriptor fields to plain properties, +/// right after parsing, with the whole program in hand. +/// +/// openpyxl declares the fields of its model classes as class attributes +/// holding descriptor objects (`b = Bool(allow_none=True)`), whose +/// `__set__` validates and stores into the instance dictionary. Every read +/// and write of such a field is then a dynamic descriptor call the type +/// inference cannot see through, so every field reads as untyped. This +/// pass writes what each descriptor does as Python the inference already +/// understands: +/// +/// ```python +/// class Font(Serialisable): +/// b = Bool(allow_none=True) +/// # becomes +/// _dm_b = None +/// @property +/// def b(self): +/// return self._dm_b +/// @b.setter +/// def b(self, value): +/// if value is not None: +/// if isinstance(value, str): +/// if value in ('false', 'f', '0'): +/// value = False +/// if not isinstance(value, bool): +/// ... +/// self._dm_b = value +/// __attrs__ = ('b', ...) +/// ``` +/// +/// Only the kinds of `openpyxl/descriptors/base.py` whose `__set__` is +/// fully known are lowered -- `Typed`, `Integer`, `Float`, `Bool`, `String`, +/// `Text`, `Set`, `NoneSet` and `Alias` -- and only with constant arguments +/// the descriptor would itself only store. Everything else (nested and +/// sequence descriptors, which `Serialisable.from_tree` and `to_tree` read +/// off the class as objects; a `Typed` of a serialisable type, for the +/// same reason) is left as it is. +/// +/// `MetaSerialisable` computes `__attrs__` from the descriptor objects it +/// finds in the class dictionary; a lowered field is no longer one, so the +/// pass writes the tuple the metaclass would have computed into the class +/// body, which the metaclass then keeps. Classes whose dictionary cannot be +/// classified entry by entry keep their descriptors. +/// +/// The class attribute a getter falls back to before the first store is +/// `None`, where the descriptor (which has no `__get__`) handed back +/// itself: no model reads a field it never set, and `None` is what every +/// caller tests for. +public final class DeclarativeMap { + private static final String BASE = "openpyxl.descriptors.base:"; + private static final String DESCRIPTOR = BASE + "Descriptor"; + private static final String TYPED = BASE + "Typed"; + private static final String ALIAS = BASE + "Alias"; + private static final String SEQUENCE = "openpyxl.descriptors.sequence:Sequence"; + private static final String BASE_NESTED_SEQUENCE = "openpyxl.descriptors.sequence:NestedSequence"; + private static final String SERIALISABLE = "openpyxl.descriptors.serialisable:Serialisable"; + private static final String STRICT = "openpyxl.descriptors:Strict"; + private static final String META_SERIALISABLE = "openpyxl.descriptors:MetaSerialisable"; + private static final String META_STRICT = "openpyxl.descriptors:MetaStrict"; + /// Builtins a class body may call without making a descriptor. + private static final Set PLAIN_BUILTINS = new HashSet(Arrays.asList("property", "classmethod", + "staticmethod", "set", "frozenset", "dict", "list", "tuple", "str", "int", "float", "bool", "bytes", + "object", "type", "len", "sorted", "range")); + /// Builtin types an `expected_type` may name. + private static final Set BUILTIN_TYPES = new HashSet(Arrays.asList("str", "int", "float", + "bool", "bytes", "tuple", "list", "dict", "set", "frozenset", "object")); + /// The kinds of `openpyxl/descriptors/base.py` this pass writes out. + private static final Set KINDS = new HashSet(Arrays.asList("Typed", "String", "Integer", + "Float", "Text", "Bool", "Set", "NoneSet", "Alias")); + /// The marker for "resolves outside the program". + private static final String EXTERNAL = ""; + /// The answer of a three-valued test that cannot be settled. + private static final int UNKNOWN = -1; + + private final Map modules = new HashMap(); + private final Set packages = new HashSet(); + private final Map> bindings = new HashMap>(); + /// `Class.attr` for every attribute read through a plain name anywhere. + private final Set dotted = new HashSet(); + private final List report = new ArrayList(); + private int lowered; + private int aliases; + private int synthesized; + /// The program subclasses of each program class, by key. + private final Map> children = new HashMap>(); + /// The class bodies as parsed, before any class is rewritten: a base's + /// descriptors are read from here once the base itself is lowered. + private final Map> original = new HashMap>(); + /// The classes that pass every test a lowering makes, from a first pass + /// that rewrites nothing. + private final Set passes = new HashSet(); + /// Model classes whose methods were generated. + private final Set serialDone = new HashSet(); + /// The classes a lowering may rewrite: they pass, and so does every + /// program subclass, which would otherwise inherit generated methods + /// written for this class's dictionary. + private final Set allowed = new HashSet(); + /// The fields each rewritten class turned into properties. + private final Map> loweredOf = new HashMap>(); + private final Set visited = new HashSet(); + private final Set needHelpers = new HashSet(); + /// Modules a class of which binds `property`: their lowerings decorate + /// with the module-level alias [Infer#PROPERTY_ALIAS] instead, which a + /// class body cannot shadow. + private final Set propertyAlias = new HashSet(); + private boolean dry; + + private DeclarativeMap() { + } + + /// Rewrites the descriptor fields of every openpyxl model class among + /// `trees` (by path), and answers the fields left alone, one line each. + public static List rewrite(Map trees) { + DeclarativeMap d = new DeclarativeMap(); + for (Map.Entry e : trees.entrySet()) { + String p = e.getKey(); + if (!p.endsWith(".py")) { + continue; + } + String m = p.substring(0, p.length() - 3); + if (m.endsWith("/__init__")) { + m = m.substring(0, m.length() - 9); + d.packages.add(m.replace('/', '.')); + } + d.modules.put(m.replace('/', '.'), e.getValue()); + } + if (!d.modules.containsKey("openpyxl.descriptors.base")) { + return new ArrayList(d.report); + } + for (Map.Entry e : d.modules.entrySet()) { + Map n = new HashMap(); + for (Stmt s : e.getValue().body) { + DataclassInit.count(s, n); + } + d.bindings.put(e.getKey(), n); + d.collectDotted(e.getValue()); + } + for (Map.Entry e : d.modules.entrySet()) { + d.collectSubclassed(e.getKey(), e.getValue().body); + for (Stmt s : e.getValue().body) { + if (s instanceof ClassDef) { + d.original.put((ClassDef) s, new ArrayList(((ClassDef) s).body)); + } + } + } + d.decide(); + for (Map.Entry e : d.modules.entrySet()) { + for (Stmt s : e.getValue().body) { + if (s instanceof ClassDef) { + d.ensure(e.getKey() + ":" + ((ClassDef) s).name); + } + } + } + for (Map.Entry e : d.modules.entrySet()) { + List body = e.getValue().body; + int first = -1; + for (int i = 0; i < body.size() && first < 0; i++) { + if (body.get(i) instanceof ClassDef + && d.needHelpers.contains(e.getKey() + ":" + ((ClassDef) body.get(i)).name)) { + first = i; + } + } + if (first >= 0) { + // Before the first class that uses them: the module has + // imported serialisable by then, to subclass Serialisable. + Node.Module helpers = Parser.parse(SerialisableMethods.HELPERS, e.getKey().replace('.', '/') + ".py"); + DataclassInit.atLine(helpers, body.get(first).line); + body.addAll(first, helpers.body); + if (d.propertyAlias.contains(e.getKey())) { + Node.Module alias = Parser.parse(Infer.PROPERTY_ALIAS + " = property\n", + e.getKey().replace('.', '/') + ".py"); + DataclassInit.atLine(alias, body.get(first).line); + body.addAll(first, alias.body); + } + } + } + if (d.dropMetaclasses()) { + trees.put(META_PATH, Parser.parse(META_MODULE, META_PATH)); + d.replaceSerialisableBase(); + } + if (d.synthesized > 0) { + trees.put(SerialisableMethods.MODULE_PATH, Parser.parse(SerialisableMethods.moduleSource(), + SerialisableMethods.MODULE_PATH)); + } + if (Boolean.getBoolean("cn1.python.declmap.report")) { + System.err.println("declmap: lowered " + d.lowered + " fields, " + d.aliases //NOPMD SystemPrintln - opt-in diagnostics + + " aliases, synthesized " + d.synthesized + " classes; left " + d.report.size()); + for (String r : d.report) { + System.err.println("declmap: " + r); //NOPMD SystemPrintln - opt-in diagnostics + } + } + return new ArrayList(d.report); + } + + /// The first pass: every module-level class is tested without being + /// rewritten, then a class stays allowed only while all its program + /// subclasses are. + private void decide() { + dry = true; + int mark = report.size(); + for (Map.Entry e : modules.entrySet()) { + for (Stmt s : e.getValue().body) { + if (s instanceof ClassDef) { + lowerClass(e.getKey(), (ClassDef) s); + } + } + } + while (report.size() > mark) { + report.remove(report.size() - 1); + } + dry = false; + allowed.addAll(passes); + boolean changed = true; + while (changed) { + changed = false; + for (String k : new ArrayList(allowed)) { + for (String ch : children.getOrDefault(k, new ArrayList())) { + if (!allowed.contains(ch) || Boolean.getBoolean("cn1.python.declmap.leafOnly")) { + allowed.remove(k); + changed = true; + break; + } + } + } + } + } + + /// Rewrites class `key` after its program bases, so that what a base + /// turned into properties is known when its subclasses are generated. + private void ensure(String key) { + if (!visited.add(key)) { + return; + } + ClassDef c = classOf(key); + if (c == null) { + return; + } + for (Expr b : c.bases) { + String r = resolveExpr(moduleOf(key), b); + if (r != null && !r.isEmpty() && modules.containsKey(moduleOf(r))) { + ensure(r); + } + } + if (lowerClass(moduleOf(key), c)) { + needHelpers.add(key); + } + } + + /// The class body as parsed. + private List bodyOf(ClassDef c) { + List b = original.get(c); + return b == null ? c.body : b; + } + + /// Records the program subclasses of every program class named as a + /// base in `body`, nested classes included. + private void collectSubclassed(String mod, List body) { + for (Stmt s : body) { + if (s instanceof ClassDef) { + for (Expr b : ((ClassDef) s).bases) { + String r = resolveExpr(mod, b); + if (r != null && !r.isEmpty()) { + children.computeIfAbsent(r, x -> new ArrayList()).add(mod + ":" + ((ClassDef) s).name); + } + } + collectSubclassed(mod, ((ClassDef) s).body); + } + } + } + + /// Where [#META_MODULE] goes. + public static final String META_PATH = "openpyxl/_dm_meta.py"; + /// `MetaSerialisable.__new__` and `MetaStrict.__new__` as functions of + /// the finished class: the same loop over the class's own dictionary, + /// in its definition order, storing what the metaclass put in it. + private static final String META_MODULE = "from openpyxl.descriptors.base import Descriptor, Typed, Alias\n" + + "from openpyxl.descriptors.sequence import Sequence\n" + + "def strict(cls):\n for k, v in list(cls.__dict__.items()):\n if isinstance(v, Descriptor):\n" + + " v.name = k\n" + + "def serialisable(cls):\n methods = cls.__dict__\n attrs = []\n nested = []\n" + + " elements = []\n namespaced = []\n for k, v in list(methods.items()):\n" + + " if isinstance(v, Descriptor):\n ns = getattr(v, 'namespace', None)\n" + + " if ns:\n namespaced.append((k, \"{%s}%s\" % (ns, k)))\n" + + " if getattr(v, 'nested', False):\n nested.append(k)\n" + + " elements.append(k)\n elif isinstance(v, Sequence):\n" + + " elements.append(k)\n elif isinstance(v, Typed):\n" + + " if hasattr(v.expected_type, 'to_tree'):\n elements.append(k)\n" + + " elif isinstance(v.expected_type, tuple):\n" + + " if any((hasattr(el, \"to_tree\") for el in v.expected_type)):\n" + + " continue\n else:\n attrs.append(k)\n" + + " else:\n if not isinstance(v, Alias):\n attrs.append(k)\n" + + " if methods.get('__attrs__') is None:\n cls.__attrs__ = tuple(attrs)\n" + + " cls.__namespaced__ = tuple(namespaced)\n if methods.get('__nested__') is None:\n" + + " cls.__nested__ = tuple(sorted(nested))\n if methods.get('__elements__') is None:\n" + + " cls.__elements__ = tuple(sorted(elements))\n strict(cls)\n"; + + /// The source of the module at [#META_PATH]. + public static String metaSource() { + return META_MODULE; + } + + /// Takes `metaclass=` off `Serialisable` and `Strict` and runs the + /// metaclass's work as a call after every class of theirs instead. + /// A class with a metaclass that defines `__new__` gets no layout -- + /// no typed fields -- and every openpyxl model class inherits this one. + /// Answers false, changing nothing, unless every class can be told + /// apart: a class whose bases cannot be followed might be a model. + private boolean dropMetaclasses() { + Map plan = new LinkedHashMap(); + for (Map.Entry e : modules.entrySet()) { + String mod = e.getKey(); + for (Stmt s : e.getValue().body) { + if (s instanceof ClassDef) { + String key = mod + ":" + ((ClassDef) s).name; + int ser = derives(key, SERIALISABLE, 0); + int str = derives(key, STRICT, 0); + if ((ser == UNKNOWN || str == UNKNOWN) && importsDescriptors(mod, e.getValue())) { + report.add(mod + ":" + s.line + " " + ((ClassDef) s).name + ": bases unknown, metaclass kept"); + return false; + } + if (ser == 1 || str == 1) { + plan.put((ClassDef) s, ser == 1 ? "_dm_meta_serialisable" : "_dm_meta_strict"); + } + } + if (mod.startsWith("openpyxl") && nestedModel(mod, s, false)) { + report.add(mod + ":" + s.line + ": model class not at module level, metaclass kept"); + return false; + } + } + } + if (plan.isEmpty()) { + return false; + } + for (Map.Entry e : modules.entrySet()) { + List body = e.getValue().body; + String file = e.getKey().replace('.', '/') + ".py"; + int first = -1; + for (int i = 0; i < body.size(); i++) { + String fn = body.get(i) instanceof ClassDef ? plan.get(body.get(i)) : null; + if (fn == null) { + continue; + } + ClassDef c = (ClassDef) body.get(i); + c.keywords.removeIf(k -> "metaclass".equals(k.arg)); + Node.Module call = Parser.parse(fn + "(" + c.name + ")\n", file); + DataclassInit.atLine(call, c.line); + body.add(i + 1, call.body.get(0)); + if (first < 0) { + first = i; + } + i++; + } + if (first >= 0) { + Node.Module imp = Parser.parse("from openpyxl._dm_meta import strict as _dm_meta_strict, " + + "serialisable as _dm_meta_serialisable\n", file); + DataclassInit.atLine(imp, body.get(first).line); + body.addAll(first, imp.body); + } + } + return true; + } + + /// Whether `m` imports from the descriptor package: only such a module + /// can declare a model class whose bases this pass cannot follow. + private boolean importsDescriptors(String mod, Node.Module m) { + for (Stmt s : m.body) { + if (s instanceof ImportFrom) { + String t = target(mod, (ImportFrom) s); + if (t != null && t.startsWith("openpyxl.descriptors")) { + return true; + } + } + } + return false; + } + + /// Whether a class below the top level of `s` derives from a model base. + private boolean nestedModel(String mod, Stmt s, boolean inner) { + boolean[] found = {false}; + if (s instanceof ClassDef && inner) { + for (Expr b : ((ClassDef) s).bases) { + String r = resolveExpr(mod, b); + if (r == null || !r.isEmpty() && (derives(r, SERIALISABLE, 0) != 0 || derives(r, STRICT, 0) != 0)) { + return true; + } + } + } + Infer.children(s, x -> { + if (x instanceof Stmt && !found[0]) { + found[0] = nestedModel(mod, (Stmt) x, true); + } + }); + return found[0]; + } + + private void collectDotted(Object o) { + if (o instanceof Attribute && ((Attribute) o).value instanceof Name) { + dotted.add(((Name) ((Attribute) o).value).id + "." + ((Attribute) o).attr); + } + Infer.children(o, this::collectDotted); + } + + // ---- name resolution ------------------------------------------------- + + /// The absolute module an import names from `mod`. + private String target(String mod, ImportFrom f) { + if (f.level == 0) { + return f.module; + } + String pkg = packages.contains(mod) ? mod : parent(mod); + for (int i = 1; i < f.level && pkg != null; i++) { + pkg = parent(pkg); + } + if (pkg == null) { + return null; + } + return f.module == null ? pkg : pkg + "." + f.module; + } + + private static String parent(String m) { + int dot = m.lastIndexOf('.'); + return dot < 0 ? null : m.substring(0, dot); + } + + /// `module:Class` for the program class `name` names in `mod`, + /// [#EXTERNAL] for a name from outside the program, null if unsure. + private String resolve(String mod, String name, int depth) { + Node.Module m = modules.get(mod); + if (m == null) { + return EXTERNAL; + } + if (depth > 16) { + return null; + } + int bound = bindings.get(mod).getOrDefault(name, 0); + if (bound == 1) { + for (Stmt s : m.body) { + if (s instanceof ClassDef && name.equals(((ClassDef) s).name)) { + return mod + ":" + name; + } + if (s instanceof Assign && ((Assign) s).targets.size() == 1 + && ((Assign) s).targets.get(0) instanceof Name + && name.equals(((Name) ((Assign) s).targets.get(0)).id) + && ((Assign) s).value instanceof Name) { + // A module-level alias of a class (Coordinate = Integer). + return resolve(mod, ((Name) ((Assign) s).value).id, depth + 1); + } + if (s instanceof ImportFrom) { + ImportFrom f = (ImportFrom) s; + for (Alias a : f.names) { + if (name.equals(a.asname != null ? a.asname : a.name)) { + String t = target(mod, f); + if (t == null || modules.containsKey(t + "." + a.name)) { + return null; + } + return resolve(t, a.name, depth + 1); + } + } + } + if (s instanceof Import) { + for (Alias a : ((Import) s).names) { + String b = a.asname != null ? a.asname : a.name; + if (name.equals(b) || b.startsWith(name + ".")) { + return modules.containsKey(a.name) ? null : EXTERNAL; + } + } + } + } + return null; + } + if (bound != 0) { + return agreeingImports(mod, m, name, depth); + } + boolean foreignStar = false; + for (Stmt s : m.body) { + if (s instanceof ImportFrom && "*".equals(((ImportFrom) s).names.get(0).name)) { + String t = target(mod, (ImportFrom) s); + foreignStar |= t == null || !modules.containsKey(t); + if (t != null && modules.containsKey(t)) { + String r = resolve(t, name, depth + 1); + if (r != null && !r.isEmpty()) { + return r; + } + } + } + } + // Bound nowhere in the module, nor by a star import of the + // program: a builtin (Exception, object), or a NameError. + return foreignStar ? null : EXTERNAL; + } + + /// A name bound more than once, each time by an import of the same + /// program class (a name listed twice in one import): that class. + private String agreeingImports(String mod, Node.Module m, String name, int depth) { + String found = null; + int seen = 0; + for (Stmt s : m.body) { + if (!(s instanceof ImportFrom)) { + continue; + } + ImportFrom f = (ImportFrom) s; + for (Alias a : f.names) { + if (name.equals(a.asname != null ? a.asname : a.name)) { + String t = target(mod, f); + if (t == null || modules.containsKey(t + "." + a.name)) { + return null; + } + String r = resolve(t, a.name, depth + 1); + if (r == null || r.isEmpty() || found != null && !found.equals(r)) { + return null; + } + found = r; + seen++; + } + } + } + return seen == bindings.get(mod).getOrDefault(name, 0) ? found : null; + } + + /// True when `name` in `mod` is bound once, at module level, to a + /// string or number constant, here or through imports of the program. + private boolean constantName(String mod, String name, int depth) { + return constantOf(mod, name, depth) != null; + } + + /// The constant [#constantName] finds, or null. + private Constant constantOf(String mod, String name, int depth) { + Node.Module m = modules.get(mod); + if (m == null || depth > 16) { + return null; + } + int bound = bindings.get(mod).getOrDefault(name, 0); + if (bound == 0) { + // Bound by a star import of a program module, if at all. + for (Stmt s : m.body) { + if (s instanceof ImportFrom && "*".equals(((ImportFrom) s).names.get(0).name)) { + String t = target(mod, (ImportFrom) s); + Constant c = t != null && modules.containsKey(t) ? constantOf(t, name, depth + 1) : null; + if (c != null) { + return c; + } + } + } + return null; + } + if (bound != 1) { + return null; + } + for (Stmt s : m.body) { + if (s instanceof Assign && ((Assign) s).targets.size() == 1 && ((Assign) s).targets.get(0) instanceof Name + && name.equals(((Name) ((Assign) s).targets.get(0)).id)) { + Expr v = ((Assign) s).value; + if (v instanceof Constant && ((Constant) v).kind == Constant.Kind.INT) { + return (Constant) v; + } + String t = stringOf(mod, v, depth); + return t == null ? null : new Constant(Constant.Kind.STR, t); + } + if (s instanceof ImportFrom) { + for (Alias a : ((ImportFrom) s).names) { + if (name.equals(a.asname != null ? a.asname : a.name)) { + String t = target(mod, (ImportFrom) s); + return t != null && modules.containsKey(t) && !modules.containsKey(t + "." + a.name) + ? constantOf(t, a.name, depth + 1) : null; + } + } + } + } + return null; + } + + /// The string a module-level expression folds to: a string constant, + /// a constant name, or a `+` of those; null otherwise. + private String stringOf(String mod, Expr v, int depth) { + if (v instanceof Constant) { + return ((Constant) v).kind == Constant.Kind.STR ? ((Constant) v).text : null; + } + if (v instanceof Name) { + Constant c = constantOf(mod, ((Name) v).id, depth + 1); + return c == null || c.kind != Constant.Kind.STR ? null : c.text; + } + if (v instanceof Node.BinOp && "+".equals(((Node.BinOp) v).op)) { + String l = stringOf(mod, ((Node.BinOp) v).left, depth); + String r = l == null ? null : stringOf(mod, ((Node.BinOp) v).right, depth); + return r == null ? null : l + r; + } + return null; + } + + /// For `Cls.attr` naming an entry of a program class's body: the module + /// of that class and the entry's value as parsed, followed through + /// further such references; null otherwise. + private Object[] deref(String mod, Expr e, int depth) { + if (!(e instanceof Attribute) || !(((Attribute) e).value instanceof Name) || depth > 16) { + return null; + } + String k = resolve(mod, ((Name) ((Attribute) e).value).id, 0); + if (k == null || k.isEmpty()) { + return null; + } + ClassDef c = classOf(k); + if (c == null) { + return null; + } + String attr = ((Attribute) e).attr; + // The last binding wins, as in the class dictionary. + Expr found = null; + boolean function = false; + for (Stmt s : bodyOf(c)) { + if (s instanceof Assign && ((Assign) s).targets.size() == 1 && ((Assign) s).targets.get(0) instanceof Name + && attr.equals(((Name) ((Assign) s).targets.get(0)).id)) { + found = ((Assign) s).value; + function = false; + } else if (s instanceof FunctionDef && attr.equals(((FunctionDef) s).name) + || s instanceof ClassDef && attr.equals(((ClassDef) s).name)) { + found = null; + function = true; + } + } + if (function) { + // A function or class of the body: never a descriptor. + return new Object[] {moduleOf(k), null}; + } + if (found == null) { + return null; + } + if (found instanceof Attribute) { + return deref(moduleOf(k), found, depth + 1); + } + return found instanceof Call || namesOf(moduleOf(k), found, depth + 1) != null + ? new Object[] {moduleOf(k), found} : null; + } + + /// [#resolve] for an expression: a name, or an attribute of a module + /// from outside the program. + private String resolveExpr(String mod, Expr e) { + if (e instanceof Name) { + return resolve(mod, ((Name) e).id, 0); + } + Expr root = e; + while (root instanceof Attribute) { + root = ((Attribute) root).value; + } + if (root instanceof Name && EXTERNAL.equals(resolve(mod, ((Name) root).id, 0))) { + return EXTERNAL; + } + return null; + } + + private ClassDef classOf(String key) { + int c = key.indexOf(':'); + Node.Module m = modules.get(key.substring(0, c)); + String n = key.substring(c + 1); + for (Stmt s : m.body) { + if (s instanceof ClassDef && n.equals(((ClassDef) s).name)) { + return (ClassDef) s; + } + } + return null; + } + + private static String moduleOf(String key) { + return key.substring(0, key.indexOf(':')); + } + + /// 1 if program class `key` is or derives from `want`, 0 if not, + /// [#UNKNOWN] if a base cannot be resolved. + private int derives(String key, String want, int depth) { + if (key.equals(want)) { + return 1; + } + ClassDef c = classOf(key); + if (c == null || depth > 32) { + return UNKNOWN; + } + int answer = 0; + for (Expr b : c.bases) { + String r = resolveExpr(moduleOf(key), b); + if (r == null) { + answer = UNKNOWN; + } else if (!r.isEmpty()) { + int d = derives(r, want, depth + 1); + if (d == 1) { + return 1; + } + if (d == UNKNOWN) { + answer = UNKNOWN; + } + } + } + return answer; + } + + /// The value a class attribute of `key`'s chain is assigned, with the + /// module to read it in, depth first from the left like these + /// single-inheritance trees' MRO; empty when none is found. + private Object[] classAttr(String key, String attr, int depth) { + ClassDef c = classOf(key); + if (c == null || depth > 32) { + return new Object[0]; + } + for (Stmt s : bodyOf(c)) { + if (s instanceof Assign && ((Assign) s).targets.size() == 1 && ((Assign) s).targets.get(0) instanceof Name + && attr.equals(((Name) ((Assign) s).targets.get(0)).id)) { + return new Object[] {moduleOf(key), ((Assign) s).value}; + } + } + for (Expr b : c.bases) { + String r = resolveExpr(moduleOf(key), b); + if (r != null && !r.isEmpty()) { + Object[] v = classAttr(r, attr, depth + 1); + if (v.length != 0) { + return v; + } + } + } + return new Object[0]; + } + + /// Whether the type `e` names (in `mod`) has `to_tree`: 1, 0 or + /// [#UNKNOWN]. + private int hasToTree(String mod, Expr e) { + if (e instanceof Call && ((Call) e).func instanceof Name && "type".equals(((Name) ((Call) e).func).id)) { + return 0; + } + if (e instanceof Call) { + // An instance of a program class (Set(values=...)): what its + // class answers, as hasattr finds no instance to_tree there. + String k = resolveExpr(mod, ((Call) e).func); + return k == null || k.isEmpty() || classOf(k) == null ? UNKNOWN : definesToTree(k, 0); + } + String r = resolveExpr(mod, e); + if (r == null) { + return UNKNOWN; + } + return r.isEmpty() ? 0 : definesToTree(r, 0); + } + + private int definesToTree(String key, int depth) { + ClassDef c = classOf(key); + if (c == null || depth > 32) { + return UNKNOWN; + } + for (Stmt s : bodyOf(c)) { + if (s instanceof FunctionDef && "to_tree".equals(((FunctionDef) s).name) + || s instanceof Assign && ((Assign) s).targets.get(0) instanceof Name + && "to_tree".equals(((Name) ((Assign) s).targets.get(0)).id)) { + return 1; + } + } + int answer = 0; + for (Expr b : c.bases) { + String r = resolveExpr(moduleOf(key), b); + if (r == null) { + answer = UNKNOWN; + } else if (!r.isEmpty()) { + int d = definesToTree(r, depth + 1); + if (d == 1) { + return 1; + } + if (d == UNKNOWN) { + answer = UNKNOWN; + } + } + } + return answer; + } + + // ---- classification -------------------------------------------------- + + /// What a class-body value is to `MetaSerialisable`. + private enum Role { NOT_DESCRIPTOR, ATTR, ELEMENT, NONE, UNKNOWN } + + private Role role(String mod, Expr v, Set classNames) { + if (v instanceof Name) { + String id = ((Name) v).id; + if (classNames.contains(id) || PLAIN_BUILTINS.contains(id) && bindings.get(mod).getOrDefault(id, 0) == 0 + || constantName(mod, id, 0)) { + return Role.NOT_DESCRIPTOR; + } + // A class object is never a descriptor instance. + String k = resolve(mod, id, 0); + return k != null && !k.isEmpty() && classOf(k) != null ? Role.NOT_DESCRIPTOR : Role.UNKNOWN; + } + Object[] shared = deref(mod, v, 0); + if (shared != null) { + return shared[1] == null ? Role.NOT_DESCRIPTOR : role((String) shared[0], (Expr) shared[1], new HashSet()); + } + if (v instanceof Attribute || v instanceof Node.Subscript) { + return Role.UNKNOWN; + } + if (!(v instanceof Call)) { + return Role.NOT_DESCRIPTOR; + } + Call c = (Call) v; + String k = resolveExpr(mod, c.func); + if (k == null) { + return Role.UNKNOWN; + } + if (k.isEmpty()) { + return Role.NOT_DESCRIPTOR; + } + int d = derives(k, DESCRIPTOR, 0); + if (d != 1) { + return d == 0 ? Role.NOT_DESCRIPTOR : Role.UNKNOWN; + } + if (derives(k, ALIAS, 0) == 1) { + return Role.NONE; + } + Expr nested = keyword(c, "nested"); + if (nested == null) { + Object[] a = classAttr(k, "nested", 0); + nested = a.length == 0 ? null : (Expr) a[1]; + } + if (nested != null && !(nested instanceof Constant)) { + return Role.UNKNOWN; + } + if (nested != null && ((Constant) nested).kind == Constant.Kind.TRUE) { + return Role.ELEMENT; + } + int seq = derives(k, SEQUENCE, 0); + if (seq != 0) { + return seq == 1 ? Role.ELEMENT : Role.UNKNOWN; + } + int typed = derives(k, TYPED, 0); + if (typed == UNKNOWN) { + return Role.UNKNOWN; + } + if (typed == 0) { + return Role.ATTR; + } + String tmod = mod; + Expr t = keyword(c, "expected_type"); + if (t == null) { + Object[] a = classAttr(k, "expected_type", 0); + if (a.length == 0) { + return Role.UNKNOWN; + } + tmod = (String) a[0]; + t = (Expr) a[1]; + } + if (t instanceof Node.TupleExpr) { + // The metaclass binds a tuple-typed field neither way. + return Role.NONE; + } + int tt = hasToTree(tmod, t); + return tt == UNKNOWN ? Role.UNKNOWN : tt == 1 ? Role.ELEMENT : Role.ATTR; + } + + private static Expr keyword(Call c, String name) { + for (Keyword k : c.keywords) { + if (name.equals(k.arg)) { + return k.value; + } + } + return null; + } + + // ---- lowering -------------------------------------------------------- + + /// Whether `v`, a descriptor of program class `k`, is nested to the + /// metaclass: 1, 0, or [#UNKNOWN]. + private int nestedOf(Call v, String k) { + Expr nested = keyword(v, "nested"); + if (nested == null) { + Object[] a = classAttr(k, "nested", 0); + nested = a.length == 0 ? null : (Expr) a[1]; + } + if (nested == null) { + return 0; + } + if (!(nested instanceof Constant)) { + return UNKNOWN; + } + Constant.Kind kind = ((Constant) nested).kind; + return kind == Constant.Kind.TRUE ? 1 : kind == Constant.Kind.FALSE || kind == Constant.Kind.NONE ? 0 : UNKNOWN; + } + + /// The namespace of descriptor `v` of program class `k`: a one-element + /// array holding the string or null, or an empty array when it cannot + /// be told. + private String[] namespaceOf(String mod, Call v, String k) { + Expr ns = keyword(v, "namespace"); + String nsMod = mod; + if (ns == null) { + Object[] a = classAttr(k, "namespace", 0); + ns = a.length == 0 ? null : (Expr) a[1]; + nsMod = a.length == 0 ? mod : (String) a[0]; + } + if (ns instanceof Name) { + // A module constant (REL_NS): its string. + Constant c = constantOf(nsMod, ((Name) ns).id, 0); + ns = c == null ? ns : c; + } + if (ns == null || ns instanceof Constant && ((Constant) ns).kind == Constant.Kind.NONE) { + return new String[] {null}; + } + if (ns instanceof Constant && ((Constant) ns).kind == Constant.Kind.STR) { + return new String[] {((Constant) ns).text.isEmpty() ? null : ((Constant) ns).text}; + } + return new String[0]; + } + + /// The (name, value) pairs of an assignment to several plain names, or + /// of a tuple of names from a tuple display of the same length, whose + /// values are constants or displays; null for anything else. + private static List unpacked(Assign a) { + List out = new ArrayList(); + for (Expr t : a.targets) { + if (t instanceof Name) { + out.add(new Object[] {((Name) t).id, a.value}); + } else if (t instanceof Node.TupleExpr && a.value instanceof Node.TupleExpr + && ((Node.TupleExpr) t).elts.size() == ((Node.TupleExpr) a.value).elts.size()) { + for (int i = 0; i < ((Node.TupleExpr) t).elts.size(); i++) { + Expr n = ((Node.TupleExpr) t).elts.get(i); + if (!(n instanceof Name)) { + return null; + } + out.add(new Object[] {((Name) n).id, ((Node.TupleExpr) a.value).elts.get(i)}); + } + } else { + return null; + } + } + for (Object[] pr : out) { + Expr v = (Expr) pr[1]; + if (!(v instanceof Constant || literalNames(v) != null)) { + return null; + } + } + return out; + } + + /// The names a class-body value of `mod` lists: a display of strings, + /// another program class's entry (`Base.__elements__`), or a `+` of + /// those; null otherwise. + private List namesOf(String mod, Expr e, int depth) { + if (depth > 16) { + return null; + } + if (e instanceof Node.BinOp && "+".equals(((Node.BinOp) e).op)) { + List l = namesOf(mod, ((Node.BinOp) e).left, depth + 1); + List r = l == null ? null : namesOf(mod, ((Node.BinOp) e).right, depth + 1); + if (r == null) { + return null; + } + List out = new ArrayList(l); + out.addAll(r); + return out; + } + if (e instanceof Attribute) { + Object[] d = deref(mod, e, depth + 1); + return d == null || d[1] == null || d[1] instanceof Call ? null + : namesOf((String) d[0], (Expr) d[1], depth + 1); + } + return literalNames(e); + } + + /// The strings of a tuple or list display of string constants, or null. + private static List literalNames(Expr e) { + List elts = e instanceof Node.TupleExpr ? ((Node.TupleExpr) e).elts + : e instanceof Node.ListExpr ? ((Node.ListExpr) e).elts : null; + if (elts == null) { + return null; + } + List out = new ArrayList(); + for (Expr x : elts) { + if (!(x instanceof Constant) || ((Constant) x).kind != Constant.Kind.STR) { + return null; + } + out.add(((Constant) x).text); + } + return out; + } + + /// Lowers class `c` of module `mod`; true when it now needs the + /// serialisation helpers [#HELPERS] imports. + private boolean lowerClass(String mod, ClassDef c) { + String key = mod + ":" + c.name; + boolean serial = derives(key, SERIALISABLE, 0) == 1; + boolean strict = serial || derives(key, STRICT, 0) == 1; + for (Keyword k : c.keywords) { + if ("metaclass".equals(k.arg)) { + String r = resolveExpr(mod, k.value); + serial |= META_SERIALISABLE.equals(r); + strict |= serial || META_STRICT.equals(r); + } + } + if (!strict || SERIALISABLE.equals(key)) { + return false; + } + if (!dry && passes.contains(key) && !allowed.contains(key)) { + // A subclass left alone would inherit the generated methods, + // which are written for this class's dictionary alone. + report.add(mod + ":" + c.line + " " + c.name + ": SKIP subclass not lowered"); + return false; + } + // The class dictionary in definition order, as the metaclass sees it. + Map entries = new LinkedHashMap(); + // The module a shared entry (`x = Base.x`) was declared in. + Map entryMod = new HashMap(); + Map stores = new HashMap(); + Set functions = new HashSet(); + Set loads = new HashSet(); + boolean plain = true; + for (Stmt s : c.body) { + if (s instanceof Assign && ((Assign) s).targets.size() == 1 && ((Assign) s).targets.get(0) instanceof Name) { + String n = ((Name) ((Assign) s).targets.get(0)).id; + stores.merge(n, 1, Integer::sum); + Expr val = ((Assign) s).value; + Object[] sh = entries.containsKey(n) ? null : deref(mod, val, 0); + if (sh != null && sh[1] != null) { + val = (Expr) sh[1]; + entryMod.put(n, (String) sh[0]); + } + entries.putIfAbsent(n, val); + names(((Assign) s).value, loads); + } else if (s instanceof FunctionDef || s instanceof ClassDef) { + String n = s instanceof FunctionDef ? ((FunctionDef) s).name : ((ClassDef) s).name; + stores.merge(n, 1, Integer::sum); + functions.add(n); + // A later def replaces an earlier entry in the dictionary. + entries.remove(n); + entryMod.remove(n); + for (Expr d : s instanceof FunctionDef ? ((FunctionDef) s).decorators : ((ClassDef) s).decorators) { + names(d, loads); + } + } else if (s instanceof Assign && unpacked((Assign) s) != null) { + // `a = b = ()` and `a, b = None, None`: one entry per name, + // each a constant or a display, so never a descriptor. + for (Object[] pr : unpacked((Assign) s)) { + String n = (String) pr[0]; + stores.merge(n, 1, Integer::sum); + entries.putIfAbsent(n, (Expr) pr[1]); + } + names(((Assign) s).value, loads); + } else if (s instanceof Node.ExprStmt && entryCall(((Node.ExprStmt) s).value, entries)) { + // textRotation.values.add(255): mutates what an entry holds, + // binds nothing; the entry is then read in the class body. + names(s, loads); + } else if (!(s instanceof Node.ExprStmt && ((Node.ExprStmt) s).value instanceof Constant + || s instanceof Node.Pass)) { + plain = false; + names(s, loads); + } + } + Set initialised = initialised(key); + List attrs = new ArrayList(); + List elements = new ArrayList(); + List nested = new ArrayList(); + List namespaced = new ArrayList(); + Map elementKind = new HashMap(); + Map replace = new LinkedHashMap(); + List aliasList = new ArrayList(); + Map descs = new LinkedHashMap(); + boolean classified = plain; + for (Map.Entry e : entries.entrySet()) { + String n = e.getKey(); + Expr v = e.getValue(); + String em = entryMod.getOrDefault(n, mod); + Role r = role(em, v, functions); + if (r == Role.UNKNOWN) { + report.add(mod + ":" + v.line + " " + c.name + "." + n + ": UNKNOWN role " + resolveExpr(mod, v instanceof Call ? ((Call) v).func : v)); + classified = false; + continue; + } + if (r == Role.NOT_DESCRIPTOR) { + continue; + } + descs.put(n, r == Role.NONE); + String k = resolveExpr(em, ((Call) v).func); + String[] ns = namespaceOf(em, (Call) v, k); + Expr nsKw = keyword((Call) v, "namespace"); + Expr own = nsKw instanceof Name ? entries.get(((Name) nsKw).id) : null; + if (own instanceof Name) { + own = constantOf(mod, ((Name) own).id, 0); + } + if (ns.length == 0 && own instanceof Constant) { + // namespace=namespace: the class body's own constant. + Constant nc = (Constant) own; + ns = nc.kind == Constant.Kind.NONE ? new String[] {null} + : nc.kind == Constant.Kind.STR ? new String[] {nc.text.isEmpty() ? null : nc.text} : ns; + } + int isNested = nestedOf((Call) v, k); + if (ns.length == 0 || isNested == UNKNOWN) { + report.add(mod + ":" + v.line + " " + c.name + "." + n + ": UNKNOWN ns/nested " + k); + classified = false; + continue; + } + if (ns[0] != null) { + namespaced.add(new String[] {n, "{" + ns[0] + "}" + n}); + } + if (r == Role.ATTR) { + attrs.add(n); + } else if (r == Role.ELEMENT) { + elements.add(n); + if (isNested == 1) { + nested.add(n); + } + elementKind.put(n, derives(k, BASE_NESTED_SEQUENCE, 0) == 1 ? "nestedseq" + : derives(k, SEQUENCE, 0) == 1 ? "seq" : "other"); + } + if (r == Role.ELEMENT || ns[0] != null) { + continue; + } + String why = !em.equals(mod) ? "shared from " + em : stores.get(n) != 1 ? "stored twice" : loads.contains(n) ? "read in the class body" + : dotted.contains(c.name + "." + n) ? "read as " + c.name + "." + n + : n.startsWith("__") ? "private name" + : r == Role.ATTR && !initialised.contains(n) ? "not set by __init__" : null; + String src = why == null ? lowering(mod, c, n, (Call) v) : null; + if (src != null && stores.containsKey("property")) { + // A class binding property (property = Sequence(...)) would + // hand the bare decorator its own descriptor: decorate with + // the module-level alias of the builtin instead. + src = src.replace("@property\n", "@" + Infer.PROPERTY_ALIAS + "\n"); + if (!dry) { + propertyAlias.add(mod); + } + } + if (src == null) { + if (why != null) { + report.add(mod + ":" + v.line + " " + c.name + "." + n + ": " + why); + } + continue; + } + if (r != Role.ATTR) { + aliasList.add(n); + } + Node.Module parsed = Parser.parse(src, mod.replace('.', '/') + ".py"); + DataclassInit.atLine(parsed, v.line); + replace.put(n, parsed.body.toArray(new Stmt[0])); + } + List attrsT = attrs; + List elementsT = sorted(elements); + List nestedT = sorted(nested); + Set written = new HashSet(Arrays.asList("__attrs__", "__elements__", "__nested__")); + Map from = new HashMap(); + if (serial) { + for (String t : new String[] {"__attrs__", "__elements__", "__nested__"}) { + Expr own = entries.get(t); + if (own == null || own instanceof Constant && ((Constant) own).kind == Constant.Kind.NONE + && stores.get(t) == 1) { + continue; + } + List lit = stores.get(t) == 1 ? namesOf(entryMod.getOrDefault(t, mod), own, 0) : null; + if (lit == null) { + classified = false; + } else if ("__attrs__".equals(t)) { + attrsT = lit; + } else if ("__elements__".equals(t)) { + elementsT = lit; + } else { + nestedT = lit; + } + written.remove(t); + } + if (!classified) { + report.add(mod + ":" + c.line + " " + c.name + ": SKIP " + (!plain ? "nonplain body" : "unclassified")); + return false; + } + Set shadow = new HashSet(functions); + shadow.addAll(entries.keySet()); + if (!inherited(key, descs, shadow, 0, from)) { + // A base whose dictionary cannot be read: the descriptor a + // child tag names is not known here. + report.add(mod + ":" + c.line + " " + c.name + ": SKIP base unresolved"); + return false; + } + } + if (dry) { + passes.add(key); + return false; + } + Set mine = new HashSet(replace.keySet()); + mine.removeAll(aliasList); + loweredOf.put(key, mine); + List body = new ArrayList(); + for (Stmt s : c.body) { + if (s instanceof Assign && ((Assign) s).targets.size() == 1 && ((Assign) s).targets.get(0) instanceof Name + && replace.containsKey(((Name) ((Assign) s).targets.get(0)).id)) { + String n = ((Name) ((Assign) s).targets.get(0)).id; + body.addAll(Arrays.asList(replace.get(n))); + if (aliasList.contains(n)) { + aliases++; + } else { + lowered++; + } + } else { + body.add(s); + } + } + if (serial) { + Set loweredAttrs = new HashSet(replace.keySet()); + loweredAttrs.removeAll(aliasList); + for (String n : replace.keySet()) { + descs.remove(n); + } + for (Map.Entry f : from.entrySet()) { + // A field a base turned into a property: no descriptor + // answers its tag any more, the property's slot holds it. + if (loweredOf.getOrDefault(f.getValue(), new HashSet()).contains(f.getKey())) { + loweredAttrs.add(f.getKey()); + descs.remove(f.getKey()); + } + } + List copied = copiedNames(key, descs.keySet(), loweredAttrs); + Set custom = new HashSet(functions); + custom.addAll(entries.keySet()); + ancestorNames(key, custom, 0); + Set below = new HashSet(); + descendantNames(key, below, 0); + String src = SerialisableMethods.methods(attrsT, elementsT, nestedT, namespaced, elementKind, written, + loweredAttrs, aliasList, custom, below, initSignature(key), descs, copied); + serialDone.add(key); + Node.Module parsed = Parser.parse(src, mod.replace('.', '/') + ".py"); + DataclassInit.atLine(parsed, c.line); + body.addAll(parsed.body); + synthesized++; + } + c.body.clear(); + c.body.addAll(body); + return serial; + } + + /// Whether `e` is a call of a method reached from a class-body entry. + private static boolean entryCall(Expr e, Map entries) { + if (!(e instanceof Call) || !(((Call) e).func instanceof Attribute)) { + return false; + } + Expr o = ((Attribute) ((Call) e).func).value; + while (o instanceof Attribute) { + o = ((Attribute) o).value; + } + return o instanceof Name && entries.containsKey(((Name) o).id); + } + + /// The names class `key` binds in its own body, as parsed. + private Set ownNames(String key) { + Set out = new HashSet(); + ClassDef c = classOf(key); + if (c == null) { + return out; + } + for (Stmt s : bodyOf(c)) { + if (s instanceof FunctionDef) { + out.add(((FunctionDef) s).name); + } else if (s instanceof Assign) { + for (Expr t : ((Assign) s).targets) { + if (t instanceof Name) { + out.add(((Name) t).id); + } + } + } + } + return out; + } + + /// Adds what the program bases of `key` below `Serialisable` bind. + private void ancestorNames(String key, Set out, int depth) { + ClassDef c = classOf(key); + if (c == null || depth > 32) { + return; + } + for (Expr b : c.bases) { + String r = resolveExpr(moduleOf(key), b); + if (r != null && !r.isEmpty() && !SERIALISABLE.equals(r) && classOf(r) != null) { + out.addAll(ownNames(r)); + ancestorNames(r, out, depth + 1); + } + } + } + + /// Adds what the program subclasses of `key`, at any depth, bind. + private void descendantNames(String key, Set out, int depth) { + if (depth > 32) { + return; + } + for (String ch : children.getOrDefault(key, new ArrayList())) { + out.addAll(ownNames(ch)); + descendantNames(ch, out, depth + 1); + } + } + + /// Replaces `Serialisable`'s generic methods, which read each field + /// with a computed getattr, by calls of the per-class `_dm_` methods, + /// once every model class has them: a subclass reaches a base method + /// only through `super()` from a method of its own lineage, and every + /// such lineage was generated under the `_dm_` names. + private void replaceSerialisableBase() { + for (Map.Entry e : modules.entrySet()) { + for (Stmt s : e.getValue().body) { + if (s instanceof ClassDef) { + String k = e.getKey() + ":" + ((ClassDef) s).name; + if (!SERIALISABLE.equals(k) && derives(k, SERIALISABLE, 0) == 1 && !serialDone.contains(k)) { + report.add(e.getKey() + ":" + s.line + " " + ((ClassDef) s).name + + ": not generated, Serialisable keeps its generic methods"); + return; + } + } + } + } + ClassDef base = classOf(SERIALISABLE); + if (base == null) { + return; + } + Set gone = SerialisableMethods.DISPATCH.keySet(); + List kept = new ArrayList(); + for (Stmt s : base.body) { + if (!(s instanceof FunctionDef && gone.contains(((FunctionDef) s).name))) { + kept.add(s); + } + } + Node.Module parsed = Parser.parse(SerialisableMethods.baseSource(), "openpyxl/descriptors/serialisable.py"); + DataclassInit.atLine(parsed, base.line); + kept.addAll(parsed.body); + base.body.clear(); + base.body.addAll(kept); + } + + /// Adds to `out` the descriptors the program bases of `key` declare, + /// nearest first, that nothing nearer (`shadow`) binds: what + /// `getattr(cls, tag)` finds through the bases. False when a base or + /// one of its entries cannot be classified. + private boolean inherited(String key, Map out, Set shadow, int depth, + Map from) { + ClassDef c = classOf(key); + if (c == null || depth > 32) { + return false; + } + for (Expr b : c.bases) { + String r = resolveExpr(moduleOf(key), b); + if (r == null) { + return false; + } + if (r.isEmpty() || SERIALISABLE.equals(r) || STRICT.equals(r)) { + continue; + } + ClassDef bc = classOf(r); + if (bc == null) { + return false; + } + Set fns = new HashSet(); + for (Stmt s : bodyOf(bc)) { + if (s instanceof FunctionDef) { + fns.add(((FunctionDef) s).name); + } else if (s instanceof ClassDef) { + fns.add(((ClassDef) s).name); + } + } + List bound = new ArrayList(fns); + for (Stmt s : bodyOf(bc)) { + if (s instanceof Assign && ((Assign) s).targets.size() == 1 + && ((Assign) s).targets.get(0) instanceof Name) { + String n = ((Name) ((Assign) s).targets.get(0)).id; + bound.add(n); + Role role = role(moduleOf(r), ((Assign) s).value, fns); + if (role == Role.UNKNOWN) { + return false; + } + if (role != Role.NOT_DESCRIPTOR && !shadow.contains(n) && !out.containsKey(n)) { + out.put(n, role == Role.NONE); + from.put(n, r); + } + } + } + shadow.addAll(bound); + if (!inherited(r, out, shadow, depth + 1, from)) { + return false; + } + } + return true; + } + + /// The instance dictionary keys `__copy__` carries over beside what it + /// serialises: the descriptor fields (stored under their own name), + /// the slots of the lowered ones and every `self.x` the methods of the + /// class and its program bases store, in that order. + private List copiedNames(String key, Set descNames, Set lowered) { + Set out = new LinkedHashSet(descNames); + for (String n : lowered) { + out.add("_dm_" + n); + } + String at = key; + for (int depth = 0; at != null && depth < 32 && !SERIALISABLE.equals(at); depth++) { + ClassDef k = classOf(at); + if (k == null) { + break; + } + String owner = k.name; + Set stores = new LinkedHashSet(); + for (Stmt s : bodyOf(k)) { + if (s instanceof FunctionDef) { + selfStores(s, stores); + } + } + for (String n : stores) { + if (lowered.contains(n) && at.equals(key)) { + out.add("_dm_" + n); + } else if (n.startsWith("__") && !n.endsWith("__")) { + int i = 0; + while (i < owner.length() && owner.charAt(i) == '_') { + i++; + } + out.add("_" + owner.substring(i) + n); + } else { + out.add(n); + } + } + String next = null; + for (Expr b : k.bases) { + String r = resolveExpr(moduleOf(at), b); + if (r != null && !r.isEmpty() && next == null && classOf(r) != null) { + next = r; + } + } + at = next; + } + return new ArrayList(out); + } + + private static void selfStores(Object o, Set out) { + if (o instanceof Assign) { + for (Expr t : ((Assign) o).targets) { + if (t instanceof Attribute && ((Attribute) t).value instanceof Name + && "self".equals(((Name) ((Attribute) t).value).id)) { + out.add(((Attribute) t).attr); + } + } + } + Infer.children(o, x -> selfStores(x, out)); + } + + private static List sorted(List in) { + List out = new ArrayList(in); + java.util.Collections.sort(out); + return out; + } + + /// The fields every instance of program class `key` has stored once + /// its `__init__` returns: the `self.x = ...` statements at the top + /// level of the nearest `__init__` in the chain. Only those may lose + /// the descriptor a read before any store would have answered. + /// The keyword parameters of the nearest `__init__` of `key`, each as + /// name and default source (null where required); null when a call by + /// keywords alone cannot stand for `cls(**attrib)` -- a `**` parameter, + /// positional-only ones, a default that is not a constant. + private List initSignature(String key) { + FunctionDef f = nearestInit(key); + if (f == null || f.args.kwarg != null || f.args.positionalOnly > 0 || f.args.positional.isEmpty()) { + return null; + } + List out = new ArrayList(); + int first = f.args.positional.size() - f.args.defaults.size(); + for (int i = 1; i < f.args.positional.size(); i++) { + String d = null; + if (i >= first) { + d = constantText(f.args.defaults.get(i - first)); + if (d == null) { + return null; + } + } + out.add(new String[] {f.args.positional.get(i).name, d}); + } + for (int i = 0; i < f.args.kwonly.size(); i++) { + Expr dv = f.args.kwDefaults.get(i); + String d = dv == null ? null : constantText(dv); + if (dv != null && d == null) { + return null; + } + out.add(new String[] {f.args.kwonly.get(i).name, d}); + } + return out; + } + + /// The nearest `__init__` along the single-base chain of `key`, or null. + private FunctionDef nearestInit(String key) { + String at = key; + for (int depth = 0; at != null && depth < 32; depth++) { + ClassDef c = classOf(at); + if (c == null) { + return null; + } + for (Stmt s : bodyOf(c)) { + if (s instanceof FunctionDef && "__init__".equals(((FunctionDef) s).name)) { + return (FunctionDef) s; + } + } + String next = null; + if (c.bases.size() == 1) { + String r = resolveExpr(moduleOf(at), c.bases.get(0)); + next = r == null || r.isEmpty() ? null : r; + } + at = next; + } + return null; + } + + private Set initialised(String key) { + Set out = new HashSet(); + String at = key; + for (int depth = 0; at != null && depth < 32; depth++) { + ClassDef c = classOf(at); + if (c == null) { + return out; + } + for (Stmt s : bodyOf(c)) { + if (s instanceof FunctionDef && "__init__".equals(((FunctionDef) s).name)) { + for (Stmt b : ((FunctionDef) s).body) { + if (b instanceof Assign) { + for (Expr t : ((Assign) b).targets) { + if (t instanceof Attribute && ((Attribute) t).value instanceof Name + && "self".equals(((Name) ((Attribute) t).value).id)) { + out.add(((Attribute) t).attr); + } + } + } + } + return out; + } + } + String next = null; + if (c.bases.size() == 1) { + String r = resolveExpr(moduleOf(at), c.bases.get(0)); + next = r == null || r.isEmpty() ? null : r; + } + at = next; + } + return out; + } + + private static void names(Object o, Set out) { + if (o instanceof Name) { + out.add(((Name) o).id); + } + if (o instanceof FunctionDef) { + return; + } + Infer.children(o, x -> names(x, out)); + } + + /// The Python that replaces field `n` of class `c`, or null (with a + /// report line when the cause is an argument) to leave it alone. + private String lowering(String mod, ClassDef c, String n, Call v) { + String k = resolveExpr(mod, v.func); + if (k == null || !k.startsWith(BASE)) { + return null; + } + String kind = k.substring(BASE.length()); + String where = mod + ":" + v.line + " " + c.name + "." + n + " " + kind + ": "; + if (!KINDS.contains(kind)) { + return null; + } + if ("Alias".equals(kind)) { + if (v.args.size() != 1 || !v.keywords.isEmpty() || !(v.args.get(0) instanceof Constant) + || ((Constant) v.args.get(0)).kind != Constant.Kind.STR) { + report.add(where + "non-constant alias"); + return null; + } + String a = ((Constant) v.args.get(0)).text; + return "@property\ndef " + n + "(self):\n return self." + a + "\n@" + n + ".setter\ndef " + n + + "(self, value):\n self." + a + " = value\n"; + } + if (!v.args.isEmpty()) { + report.add(where + "positional argument"); + return null; + } + boolean allowNone = false; + String type = null; + String values = null; + for (Keyword kw : v.keywords) { + if ("allow_none".equals(kw.arg) && !kind.endsWith("Set")) { + if (!(kw.value instanceof Constant) || ((Constant) kw.value).kind != Constant.Kind.TRUE + && ((Constant) kw.value).kind != Constant.Kind.FALSE) { + report.add(where + "non-constant allow_none"); + return null; + } + allowNone = ((Constant) kw.value).kind == Constant.Kind.TRUE; + } else if ("expected_type".equals(kw.arg) && "Typed".equals(kind)) { + type = typeText(mod, c, kw.value); + if (type == null) { + report.add(where + "expected_type not a plain type"); + return null; + } + } else if ("values".equals(kw.arg) && kind.endsWith("Set")) { + values = setText(kw.value, "NoneSet".equals(kind)); + if (values == null) { + report.add(where + "non-constant values"); + return null; + } + } else { + report.add(where + "keyword " + kw.arg); + return null; + } + } + StringBuilder b = new StringBuilder(); + b.append("_dm_").append(n).append(" = None\n@property\ndef ").append(n).append("(self):\n return self._dm_") + .append(n).append("\n@").append(n).append(".setter\ndef ").append(n).append("(self, value):\n"); + switch (kind) { + case "Typed": + if (type == null) { + return null; + } + typed(b, n, type, allowNone); + break; + case "String": + typed(b, n, "str", allowNone); + break; + case "Integer": + convertible(b, n, "int", allowNone, false); + break; + case "Float": + convertible(b, n, "float", allowNone, false); + break; + case "Text": + convertible(b, n, "str", allowNone, false); + break; + case "Bool": + convertible(b, n, "bool", allowNone, true); + break; + case "Set": + case "NoneSet": + if (values == null) { + return null; + } + if ("NoneSet".equals(kind)) { + b.append(" if value == 'none':\n value = None\n"); + } + b.append(" if value not in ").append(values).append(":\n raise ValueError(") + .append("'Value must be one of {0}'.format(").append(values).append("))\n"); + b.append(" self._dm_").append(n).append(" = value\n"); + break; + default: + return null; + } + return b.toString(); + } + + /// `Typed.__set__`, with the message it raises when `DEBUG` is off. + /// Each store sits under the test that proves its type, so the slot + /// holds the expected type (or None) whatever the callers pass. + private static void typed(StringBuilder b, String n, String type, boolean allowNone) { + String store = " self._dm_" + n + " = "; + b.append(" if isinstance(value, ").append(type).append("):\n").append(store).append("value\n return\n"); + if (allowNone) { + b.append(" if value is None:\n").append(store).append("None\n return\n"); + } + b.append(" raise TypeError(str(self.__class__) + ").append(quote("." + n + " should be ")).append(" + str(") + .append(type).append(") + ' but value is ' + str(value.__class__))\n"); + } + + /// `Convertible.__set__` through `_convert`, storing the converted + /// local rather than the rebound parameter, so the slot's type is the + /// constructor's whatever the callers pass. + private static void convertible(StringBuilder b, String n, String type, boolean allowNone, boolean bool) { + String store = " self._dm_" + n + " = "; + if (bool) { + // Bool.__set__ runs before Convertible's, None or not; False + // then converts to itself. + b.append(" if isinstance(value, str) and value in ('false', 'f', '0'):\n").append(store) + .append("False\n return\n"); + } + if (allowNone) { + b.append(" if value is None:\n").append(store).append("None\n return\n"); + } + b.append(" if isinstance(value, ").append(type).append("):\n").append(store).append("value\n return\n") + .append(" try:\n v = ").append(type).append("(value)\n except:\n") + .append(" raise TypeError('expected ' + str(").append(type).append("))\n self._dm_").append(n) + .append(" = v\n"); + } + + /// Source for an `expected_type` the setter can name from module + /// scope, or null. + private String typeText(String mod, ClassDef c, Expr e) { + if (!EXTERNAL.equals(resolveExpr(mod, e))) { + // A program type might have a from_tree the generic + // Serialisable.from_tree would call; only foreign types surely + // have none. + return null; + } + if (e instanceof Name) { + String id = ((Name) e).id; + int bound = bindings.get(mod).getOrDefault(id, 0); + for (Stmt s : bodyOf(c)) { + if (s instanceof Assign && ((Assign) s).targets.get(0) instanceof Name + && id.equals(((Name) ((Assign) s).targets.get(0)).id)) { + return null; + } + } + return bound == 1 || bound == 0 && BUILTIN_TYPES.contains(id) ? id : null; + } + if (e instanceof Attribute) { + String inner = typeText(mod, c, ((Attribute) e).value); + return inner == null ? null : inner + "." + ((Attribute) e).attr; + } + return null; + } + + /// A set display of the constants of `e`, plus `None` for a `NoneSet`. + private static String setText(Expr e, boolean none) { + List elts; + if (e instanceof Node.TupleExpr) { + elts = ((Node.TupleExpr) e).elts; + } else if (e instanceof Node.ListExpr) { + elts = ((Node.ListExpr) e).elts; + } else if (e instanceof Node.SetExpr) { + elts = ((Node.SetExpr) e).elts; + } else { + return null; + } + StringBuilder b = new StringBuilder("{"); + for (Expr x : elts) { + String t = constantText(x); + if (t == null) { + return null; + } + b.append(t).append(", "); + } + if (none) { + b.append("None, "); + } + if (b.length() == 1) { + return "set()"; + } + return b.append('}').toString(); + } + + private static String constantText(Expr x) { + if (!(x instanceof Constant)) { + return null; + } + Constant k = (Constant) x; + switch (k.kind) { + case NONE: + return "None"; + case TRUE: + return "True"; + case FALSE: + return "False"; + case INT: + case FLOAT: + return k.text; + case STR: + return quote(k.text); + default: + return null; + } + } + + /// A Python string literal for `s`, ASCII only. + static String quote(String s) { + StringBuilder b = new StringBuilder("'"); + for (int i = 0; i < s.length(); i++) { + char ch = s.charAt(i); + if (ch == '\'' || ch == '\\') { + b.append('\\').append(ch); + } else if (ch < 0x20 || ch > 0x7e) { + b.append(String.format("\\u%04x", (int) ch)); + } else { + b.append(ch); + } + } + return b.append('\'').toString(); + } +} diff --git a/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/DefAssign.java b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/DefAssign.java index fd219b53e17..7469c2ad8ac 100644 --- a/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/DefAssign.java +++ b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/DefAssign.java @@ -25,6 +25,7 @@ import com.codename1.python.transpiler.ast.Node.*; +import com.codename1.python.transpiler.ast.Node.Yield; import java.util.Collections; import java.util.HashSet; import java.util.IdentityHashMap; @@ -40,6 +41,8 @@ /// Walrus targets, comprehensions and lambdas are not followed. final class DefAssign { final Set safe = Collections.newSetFromMap(new IdentityHashMap()); + /// The reads not proven to follow a binding. + final Set unsafe = Collections.newSetFromMap(new IdentityHashMap()); /// Marks the safe loads of `body`, a function whose parameters `params` /// are bound on entry. @@ -209,8 +212,21 @@ private Set stmt(Stmt s, Set in) { return res; } if (s instanceof FunctionDef) { + // Decorators and defaults are read where the def stands. + FunctionDef fd = (FunctionDef) s; + for (Expr d : fd.decorators) { + expr(d, in); + } + for (Expr d : fd.args.defaults) { + expr(d, in); + } + for (Expr d : fd.args.kwDefaults) { + if (d != null) { + expr(d, in); + } + } Set out = new HashSet(in); - out.add(((FunctionDef) s).name); + out.add(fd.name); return out; } if (s instanceof ClassDef) { @@ -338,6 +354,8 @@ private void expr(Expr e, Set in) { if (e instanceof Name) { if (in.contains(((Name) e).id)) { safe.add((Name) e); + } else { + unsafe.add((Name) e); } } else if (e instanceof Attribute || e instanceof Subscript) { parts(e, in); @@ -363,6 +381,8 @@ private void expr(Expr e, Set in) { expr(((IfExp) e).orelse, in); } else if (e instanceof NamedExpr) { expr(((NamedExpr) e).value, in); + } else if (e instanceof Yield) { + expr(((Yield) e).value, in); } else if (e instanceof Call) { Call c = (Call) e; expr(c.func, in); @@ -381,7 +401,40 @@ private void expr(Expr e, Set in) { expr(k, in); } exprs(((DictExpr) e).values, in); + } else if (e instanceof Comp) { + // A comprehension runs where it stands: its first iterable in + // this scope, the rest reading this scope's locals as they are + // now (its own targets are its own scope's). + Comp c = (Comp) e; + expr(c.generators.get(0).iter, in); + Set inner = new HashSet(in); + if (c.scope != null) { + inner.addAll(c.scope.assigned); + } + for (int i = 0; i < c.generators.size(); i++) { + Comprehension g = c.generators.get(i); + if (i > 0) { + expr(g.iter, inner); + } + exprs(g.ifs, inner); + } + expr(c.elt, inner); + expr(c.value, inner); + } else if (e instanceof JoinedStr) { + for (Expr part : ((JoinedStr) e).parts) { + expr(part, in); + } + } else if (e instanceof FormattedValue) { + expr(((FormattedValue) e).value, in); + expr(((FormattedValue) e).spec, in); + } else if (e instanceof Lambda) { + // Its defaults are evaluated where it stands; its body later, + // so a read there is left checked. + exprs(((Lambda) e).args.defaults, in); + for (Expr d : ((Lambda) e).args.kwDefaults) { + expr(d, in); + } } - // Comprehensions, lambdas, f-strings, await, yield: left checked. + // Await, yield, a lambda's body: left checked. } } diff --git a/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/DictItemsSetattr.java b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/DictItemsSetattr.java new file mode 100644 index 00000000000..629d00f033a --- /dev/null +++ b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/DictItemsSetattr.java @@ -0,0 +1,457 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.python.transpiler.codegen; + +import com.codename1.python.transpiler.ast.Node; +import com.codename1.python.transpiler.ast.Node.Arg; +import com.codename1.python.transpiler.ast.Node.Arguments; +import com.codename1.python.transpiler.ast.Node.Attribute; +import com.codename1.python.transpiler.ast.Node.Call; +import com.codename1.python.transpiler.ast.Node.ClassDef; +import com.codename1.python.transpiler.ast.Node.Constant; +import com.codename1.python.transpiler.ast.Node.DictExpr; +import com.codename1.python.transpiler.ast.Node.Expr; +import com.codename1.python.transpiler.ast.Node.FunctionDef; +import com.codename1.python.transpiler.ast.Node.Name; +import com.codename1.python.transpiler.ast.Node.Stmt; + +import java.util.ArrayList; +import java.util.IdentityHashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/// Specializes a function whose whole body stores a mapping argument as +/// attributes, +/// +/// ```python +/// def fill(obj, attrs): +/// for k, v in attrs.items(): +/// setattr(obj, k, v) +/// +/// @classmethod +/// def configure(cls, **kw): +/// for k, v in kw.items(): +/// setattr(cls, k, v) +/// ``` +/// +/// on the keys each call site spells out: a dict literal with string +/// keys for a positional mapping, the literal keywords for `**kw`. Every +/// distinct key sequence gets a clone whose body is one literal store per +/// key, in that order, from a parameter of its own (`obj.label = _cn1_kv0`). +/// Each call passes the values in place of the mapping, in the position +/// they were evaluated in, so evaluation order is unchanged and no mapping +/// is built; a dict iterates in insertion order, so the stores happen in +/// the order the loop made them. Each value reaches its store with its own +/// type, so the inference sees every type a field can hold. +/// +/// Only module-level functions, `@classmethod` and `@staticmethod` methods +/// qualify (the implicit argument of a plain method depends on how it is +/// reached). It refuses a function with defaults, `*args` or keyword-only +/// parameters, a name defined twice or used other than by being called, a +/// call with starred arguments, `**` entries, a non-identifier or repeated +/// key, a private (mangled) key, and a module-level function called other +/// than as a statement. No name-dispatch code is generated. +public final class DictItemsSetattr { + private static final String SUFFIX = "__cn1_d"; + private static final int[] NONE = new int[0]; + + private DictItemsSetattr() { + } + + public static void rewrite(Map trees, Iterable libTrees) { + List all = new ArrayList(trees.values()); + for (Node.Module m : libTrees) { + all.add(m); + } + for (Node.Module m : trees.values()) { + for (int i = 0; i < m.body.size(); i++) { + Stmt s = m.body.get(i); + if (s instanceof FunctionDef && moduleFn(m, (FunctionDef) s, all)) { + i--; + } else if (s instanceof ClassDef) { + ClassDef c = (ClassDef) s; + for (int j = 0; j < c.body.size(); j++) { + if (c.body.get(j) instanceof FunctionDef && method(c, (FunctionDef) c.body.get(j), all)) { + j--; + } + } + } + } + } + } + + /// The parameter positions of the loop: [object, mapping], mapping -1 + /// meaning `**kw`; empty when `f` is not exactly the loop. + private static int[] shape(FunctionDef f) { + Arguments a = f.args; + if (f.isAsync || a.vararg != null || !a.kwonly.isEmpty() || !a.defaults.isEmpty() + || a.positionalOnly != 0 || f.returns != null) { + return NONE; + } + List body = f.body; + int start = 0; + if (body.size() == 2 && body.get(0) instanceof Node.ExprStmt + && ((Node.ExprStmt) body.get(0)).value instanceof Constant) { + start = 1; + } + if (body.size() != start + 1 || !(body.get(start) instanceof Node.For)) { + return NONE; + } + Node.For loop = (Node.For) body.get(start); + if (loop.isAsync || !loop.orelse.isEmpty() || loop.body.size() != 1 + || !(loop.target instanceof Node.TupleExpr) || !(loop.iter instanceof Call)) { + return NONE; + } + List t = ((Node.TupleExpr) loop.target).elts; + Call it = (Call) loop.iter; + if (t.size() != 2 || !(t.get(0) instanceof Name) || !(t.get(1) instanceof Name) + || !it.args.isEmpty() || !it.keywords.isEmpty() || !(it.func instanceof Attribute) + || !"items".equals(((Attribute) it.func).attr) || !(((Attribute) it.func).value instanceof Name)) { + return NONE; + } + String k = ((Name) t.get(0)).id; + String v = ((Name) t.get(1)).id; + String p = ((Name) ((Attribute) it.func).value).id; + Stmt st = loop.body.get(0); + if (k.equals(v) || !(st instanceof Node.ExprStmt) || !(((Node.ExprStmt) st).value instanceof Call)) { + return NONE; + } + Call sc = (Call) ((Node.ExprStmt) st).value; + if (!(sc.func instanceof Name) || !"setattr".equals(((Name) sc.func).id) || sc.args.size() != 3 + || !sc.keywords.isEmpty() || !(sc.args.get(0) instanceof Name) + || !isName(sc.args.get(1), k) || !isName(sc.args.get(2), v)) { + return NONE; + } + String o = ((Name) sc.args.get(0)).id; + int oi = -1; + int pi = -2; + for (int i = 0; i < a.positional.size(); i++) { + Arg x = a.positional.get(i); + if (x.annotation != null) { + return NONE; + } + if (x.name.equals(o)) { + oi = i; + } + if (x.name.equals(p)) { + pi = i; + } + } + if (a.kwarg != null) { + if (a.kwarg.annotation != null) { + return NONE; + } + if (a.kwarg.name.equals(p)) { + pi = -1; + } + } + for (String n : a.names()) { + if (n.startsWith("_cn1_kv")) { + return NONE; + } + } + if (oi < 0 || pi == -2 || pi == oi || o.equals(k) || o.equals(v) || p.equals(k) || p.equals(v)) { + return NONE; + } + return new int[] {oi, pi}; + } + + private static boolean isName(Expr e, String id) { + return e instanceof Name && ((Name) e).id.equals(id); + } + + /// The keys `c` passes to the mapping, in order, or null. + private static List keys(FunctionDef f, int[] sh, int implicit, Call c) { + Arguments a = f.args; + for (Expr x : c.args) { + if (x instanceof Node.Starred) { + return null; + } + } + if (c.args.size() != a.positional.size() - implicit) { + return null; + } + List out = new ArrayList(); + if (sh[1] == -1) { + for (Node.Keyword k : c.keywords) { + if (k.arg == null || a.names().contains(k.arg) || !okKey(k.arg) || out.contains(k.arg)) { + return null; + } + out.add(k.arg); + } + return out; + } + if (!c.keywords.isEmpty() || sh[1] < implicit || !(c.args.get(sh[1] - implicit) instanceof DictExpr)) { + return null; + } + DictExpr d = (DictExpr) c.args.get(sh[1] - implicit); + for (Expr k : d.keys) { + if (!(k instanceof Constant) || ((Constant) k).kind != Constant.Kind.STR) { + return null; + } + String s = ((Constant) k).text; + if (!okKey(s) || out.contains(s)) { + return null; + } + out.add(s); + } + return out; + } + + private static boolean okKey(String s) { + return ConstArgSpecialize.ident(s) && !(s.startsWith("__") && !s.endsWith("__")); + } + + private static String param(int i) { + return "_cn1_kv" + i; + } + + private static FunctionDef clone(FunctionDef f, int[] sh, String name, List keys) { + Arguments na = new Arguments(); + List vs = new ArrayList(); + for (int i = 0; i < keys.size(); i++) { + vs.add(new Arg(param(i), null).at(f.args.line, f.args.col)); + } + for (int i = 0; i < f.args.positional.size(); i++) { + Arg x = f.args.positional.get(i); + if (i == sh[1]) { + na.positional.addAll(vs); + } else { + na.positional.add(new Arg(x.name, null).at(x.line, x.col)); + } + } + if (sh[1] == -1) { + na.positional.addAll(vs); + } + na.at(f.args.line, f.args.col); + String o = f.args.positional.get(sh[0]).name; + List body = new ArrayList(); + int l = f.body.get(f.body.size() - 1).line; + int col = f.body.get(f.body.size() - 1).col; + for (int i = 0; i < keys.size(); i++) { + List tg = new ArrayList(); + tg.add(new Attribute(new Name(o).at(l, col), keys.get(i)).at(l, col)); + body.add(new Node.Assign(tg, new Name(param(i)).at(l, col)).at(l, col)); + } + if (body.isEmpty()) { + body.add(new Node.Pass().at(l, col)); + } + List decs = new ArrayList(); + for (Expr d : f.decorators) { + decs.add(new Name(((Name) d).id).at(d.line, d.col)); + } + return new FunctionDef(name, na, body, decs, null, false).at(f.line, f.col); + } + + /// The arguments of the clone's call: the mapping's values in place of + /// the mapping, each in the position it was evaluated in. + private static List args(int[] sh, int implicit, Call c) { + List out = new ArrayList(); + for (int i = 0; i < c.args.size(); i++) { + if (i == sh[1] - implicit) { + out.addAll(((DictExpr) c.args.get(i)).values); + } else { + out.add(c.args.get(i)); + } + } + if (sh[1] == -1) { + for (Node.Keyword k : c.keywords) { + out.add(k.value); + } + } + return out; + } + + /// Counts in `o`: [FunctionDefs named n, Names n, Attributes .n, string constants n]. + private static void census(Object o, final String n, final int[] r, final List attrCalls, + final IdentityHashMap attrSeen) { + if (o instanceof FunctionDef && ((FunctionDef) o).name.equals(n)) { + r[0]++; + } else if (o instanceof Name && ((Name) o).id.equals(n)) { + r[1]++; + } else if (o instanceof Attribute && n.equals(((Attribute) o).attr)) { + r[2]++; + } else if (o instanceof Constant && ((Constant) o).kind == Constant.Kind.STR && n.equals(((Constant) o).text)) { + r[3]++; + } else if (o instanceof Node.Alias && (n.equals(((Node.Alias) o).name) || n.equals(((Node.Alias) o).asname))) { + r[3]++; + } else if (o instanceof Node.Global && ((Node.Global) o).names.contains(n)) { + r[3]++; + } + if (o instanceof Call && ((Call) o).func instanceof Attribute && n.equals(((Attribute) ((Call) o).func).attr)) { + attrCalls.add((Call) o); + } + Infer.children(o, x -> census(x, n, r, attrCalls, attrSeen)); + } + + private static boolean moduleFn(Node.Module m, FunctionDef f, List all) { + if (!f.decorators.isEmpty()) { + return false; + } + int[] sh = shape(f); + if (sh.length == 0) { + return false; + } + int[] r = new int[4]; + List ac = new ArrayList(); + census(m, f.name, r, ac, null); + if (r[0] != 1 || r[2] != 0 || r[3] != 0) { + return false; + } + for (Node.Module o : all) { + if (o != m) { //NOPMD CompareObjectsWithEquals - identity is meant + int[] r2 = new int[4]; + census(o, f.name, r2, new ArrayList(), null); + if (r2[0] + r2[1] + r2[2] + r2[3] != 0) { + return false; + } + } + } + Map> holder = new IdentityHashMap>(); + ConstArgSpecialize.stmtCalls(m.body, holder); + List cs = new ArrayList(); + for (Call c : holder.keySet()) { + if (isName(c.func, f.name)) { + cs.add(c); + } + } + if (cs.size() != r[1] || cs.isEmpty()) { + return false; + } + Map> seqs = new LinkedHashMap>(); + List of = new ArrayList(); + for (Call c : cs) { + List ks = keys(f, sh, 0, c); + if (ks == null) { + return false; + } + String id = String.join(",", ks); + seqs.put(id, ks); + of.add(id); + } + Map names = names(f.name, seqs, all); + if (names == null) { + return false; + } + for (int j = 0; j < cs.size(); j++) { + Call c = cs.get(j); + List l = holder.get(c); + for (int q = 0; q < l.size(); q++) { + Stmt sq = l.get(q); + boolean es = sq instanceof Node.ExprStmt && ((Node.ExprStmt) sq).value == c; //NOPMD CompareObjectsWithEquals - identity is meant + boolean as = sq instanceof Node.Assign && ((Node.Assign) sq).value == c; //NOPMD CompareObjectsWithEquals - identity is meant + if (es || as) { + Call nc = new Call(new Name(names.get(of.get(j))).at(c.func.line, c.func.col)).at(c.line, c.col); + nc.args.addAll(args(sh, 0, c)); + Stmt rep = as ? new Node.Assign(((Node.Assign) sq).targets, nc) : new Node.ExprStmt(nc); + l.set(q, rep.at(sq.line, sq.col)); + break; + } + } + } + replace(m.body, f, sh, seqs, names); + return true; + } + + private static boolean method(ClassDef cls, FunctionDef f, List all) { + if (f.decorators.size() != 1 || !(f.decorators.get(0) instanceof Name)) { + return false; + } + String d = ((Name) f.decorators.get(0)).id; + int implicit; + if ("classmethod".equals(d)) { + implicit = 1; + } else if ("staticmethod".equals(d)) { + implicit = 0; + } else { + return false; + } + int[] sh = shape(f); + if (sh.length == 0 || f.name.startsWith("__")) { + return false; + } + int[] r = new int[4]; + List cs = new ArrayList(); + for (Node.Module o : all) { + census(o, f.name, r, cs, null); + } + if (r[0] != 1 || r[1] != 0 || r[3] != 0 || r[2] != cs.size() || cs.isEmpty()) { + return false; + } + Map> seqs = new LinkedHashMap>(); + List of = new ArrayList(); + for (Call c : cs) { + List ks = keys(f, sh, implicit, c); + if (ks == null) { + return false; + } + String id = String.join(",", ks); + seqs.put(id, ks); + of.add(id); + } + Map names = names(f.name, seqs, all); + if (names == null) { + return false; + } + for (int j = 0; j < cs.size(); j++) { + Call c = cs.get(j); + List na = args(sh, implicit, c); + ((Attribute) c.func).attr = names.get(of.get(j)); + c.args.clear(); + c.args.addAll(na); + c.keywords.clear(); + } + replace(cls.body, f, sh, seqs, names); + return true; + } + + private static Map names(String base, Map> seqs, List all) { + Map names = new LinkedHashMap(); + int n = 0; + for (String id : seqs.keySet()) { + String nm = base + SUFFIX + n++; + int[] r = new int[4]; + for (Node.Module o : all) { + census(o, nm, r, new ArrayList(), null); + } + if (r[0] + r[1] + r[2] + r[3] != 0) { + return null; + } + names.put(id, nm); + } + return names; + } + + private static void replace(List body, FunctionDef f, int[] sh, Map> seqs, + Map names) { + int at = body.indexOf(f); + body.remove(at); + List clones = new ArrayList(); + for (Map.Entry> e : seqs.entrySet()) { + clones.add(clone(f, sh, names.get(e.getKey()), e.getValue())); + } + body.addAll(at, clones); + } +} diff --git a/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/Directives.java b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/Directives.java new file mode 100644 index 00000000000..6d8b3d8e3d1 --- /dev/null +++ b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/Directives.java @@ -0,0 +1,454 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.python.transpiler.codegen; + +import com.codename1.python.transpiler.api.PythonSyntaxError; +import com.codename1.python.transpiler.ast.Node; +import com.codename1.python.transpiler.ast.Node.Arg; +import com.codename1.python.transpiler.ast.Node.Call; +import com.codename1.python.transpiler.ast.Node.ClassDef; +import com.codename1.python.transpiler.ast.Node.Constant; +import com.codename1.python.transpiler.ast.Node.Expr; +import com.codename1.python.transpiler.ast.Node.ExprStmt; +import com.codename1.python.transpiler.ast.Node.FunctionDef; +import com.codename1.python.transpiler.ast.Node.Name; +import com.codename1.python.transpiler.ast.Node.Return; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; +import java.util.TreeSet; + +/// What a build is told about functions of its Python sources, its own or +/// any package's, in `cn1-python.properties` beside the sources: +/// +/// ``` +/// # reached in a way the build cannot see: compile it anyway +/// keep = pkg.plugins.load_all, pkg.models.Model.from_row +/// # never needed here: leave it out, and raise if it is called after all +/// remove = pkg.cli.run_python +/// # needed, and it cannot be translated: its body is Java +/// replace = pkg.utils.compile_code +/// # needed, and written in a way the build refuses (reflection): its body +/// # is the Python in cn1-python-overrides/pkg.views.View.dispatch.py +/// override = pkg.views.View.dispatch +/// ``` +/// +/// An override file holds one `def` with the function's name and the same +/// parameters. Its body takes the place of the original's and is analysed +/// in the original module, so it reads that module's globals and imports +/// as the original did. It is how a third-party function that uses +/// reflection -- `getattr(self, "convert_" + tag)` -- is compiled under +/// `cn1.python.strict` without editing the package. +/// +/// A name is the module's dotted name followed by the function's, or by a +/// class's and a method's. `remove` also takes a class (none of its methods +/// is compiled), a module, and a package, which is every module under it: a +/// module left out still imports, and raises at the first use of anything +/// it would have held. `remove` and `replace` are how code that cannot +/// run in a translated program (`eval`, `exec`) stops failing the build when +/// the program does reach the function it is in: the function's body is not +/// compiled at all. A replaced function calls the Java registered for it +/// with `NativeModule.replace`; the build writes a class with a stub for +/// each, per module, for the developer to fill in (see [#shims]). +public final class Directives { + /// The file, in the root of the Python sources. + public static final String FILE = "cn1-python.properties"; + /// The package of the generated classes that hold the replacements. + public static final String SHIM_PACKAGE = "com.codename1.python.ext"; + /// The directory, in the root of the Python sources, of `override=` + /// bodies: one `.py` per overridden function. + public static final String OVERRIDES = "cn1-python-overrides"; + + private final Set keep = new TreeSet(); + private final Set remove = new TreeSet(); + private final Set replace = new TreeSet(); + private final Set override = new TreeSet(); + /// The sources, for the override bodies; set by [#parse(String, Map)]. + private Map sources; + /// Module to its replaced functions, each with the comment that + /// describes its parameters. + private final Map> replaced = new TreeMap>(); + + /// Reads the file's text; null or empty gives no directive. + public static Directives parse(String text) { + Directives d = new Directives(); + if (text == null) { + return d; + } + int n = 0; + for (String raw : text.split("\n")) { + n++; + String line = raw.trim(); + if (line.isEmpty() || line.charAt(0) == '#') { + continue; + } + int eq = line.indexOf('='); + String key = eq < 0 ? line : line.substring(0, eq).trim(); + Set into = "keep".equals(key) ? d.keep : "remove".equals(key) ? d.remove + : "replace".equals(key) ? d.replace : "override".equals(key) ? d.override : null; + if (eq < 0 || into == null) { + throw new PythonSyntaxError(FILE, n, 1, "expected keep=, remove=, replace= or override= followed by the dotted" + + " names of functions (module.function or module.Class.method), separated by commas; remove=" + + " also takes a class, a module or a package"); + } + for (String name : line.substring(eq + 1).split(",")) { + if (!name.trim().isEmpty()) { + into.add(name.trim()); + } + } + } + return d; + } + + /// Reads the file's text, with the program's sources (path to text) to + /// take `override=` bodies from. + public static Directives parse(String text, Map sources) { + Directives d = parse(text); + d.sources = sources; + return d; + } + + /// The functions to compile although nothing is seen to reach them. + public Set keep() { + return keep; + } + + /// Whether the file names `function` under `remove` or `replace`. + boolean names(String function) { + return remove.contains(function) || replace.contains(function) || override.contains(function); + } + + /// Rewrites the body of every removed and replaced function in + /// `modules` (dotted module name to tree), before anything reads them. + /// A name that is no function of the program is an error: a directive + /// that silently does nothing would leave the code it was written for + /// in the build. + public void apply(Map modules) { + for (String name : remove) { + if (modules.containsKey(name)) { + // A module, and when it is a package every module under it. + for (Map.Entry e : modules.entrySet()) { + if (e.getKey().equals(name) || e.getKey().startsWith(name + ".")) { + leaveOut(e.getKey(), e.getValue(), name); + } + } + continue; + } + for (Object o : resolve(name, modules, true)) { + if (o instanceof FunctionDef) { + leaveOut((FunctionDef) o, name + " was left out of this build (remove= in " + FILE + ")"); + } else { + // A class stays a class -- it can be imported, named in an + // annotation, tested against and derived from -- and none + // of its methods is compiled. + methods(((ClassDef) o).body, name, name); + } + } + } + for (String name : override) { + String path = OVERRIDES + "/" + name + ".py"; + String text = sources == null ? null : sources.get(path); + if (text == null) { + throw new PythonSyntaxError(FILE, 1, 1, "override = " + name + " needs its body in " + path); + } + FunctionDef with = null; + for (Node.Stmt s : com.codename1.python.transpiler.parser.Parser.parse(text, path).body) { + if (s instanceof FunctionDef && ((FunctionDef) s).name.equals(name.substring(name.lastIndexOf('.') + 1))) { + with = (FunctionDef) s; + } + } + if (with == null) { + throw new PythonSyntaxError(path, 1, 1, "expected a def named " + + name.substring(name.lastIndexOf('.') + 1)); + } + for (FunctionDef f : resolve(name, modules)) { + if (!sameParameters(f, with)) { + throw new PythonSyntaxError(path, with.line, with.col, "the override of " + name + + " must take the same parameters as the original"); + } + f.body.clear(); + f.body.addAll(with.body); + } + } + for (String name : replace) { + List fs = resolve(name, modules); + String module = moduleOf(name, modules); + for (FunctionDef f : fs) { + Call c = at(new Call(at(new Name("__cn1_replaced__"), f)), f); + c.args.add(at(new Constant(Constant.Kind.STR, name), f)); + StringBuilder sig = new StringBuilder(); + for (Arg a : f.args.positional) { + param(c, sig, a.name, a.name, f); + } + if (f.args.vararg != null) { + param(c, sig, f.args.vararg.name, f.args.vararg.name + " (a tuple)", f); + } + for (Arg a : f.args.kwonly) { + param(c, sig, a.name, a.name, f); + } + if (f.args.kwarg != null) { + param(c, sig, f.args.kwarg.name, f.args.kwarg.name + " (a dict)", f); + } + f.body.clear(); + f.body.add(at(new Return(c), f)); + Map m = replaced.get(module); + if (m == null) { + m = new TreeMap(); + replaced.put(module, m); + } + m.put(name, sig.toString()); + } + } + } + + private static boolean sameParameters(FunctionDef a, FunctionDef b) { + if (a.args.positional.size() != b.args.positional.size() || a.args.kwonly.size() != b.args.kwonly.size() + || (a.args.vararg == null) != (b.args.vararg == null) || (a.args.kwarg == null) != (b.args.kwarg == null)) { + return false; + } + for (int i = 0; i < a.args.positional.size(); i++) { + if (!a.args.positional.get(i).name.equals(b.args.positional.get(i).name)) { + return false; + } + } + for (int i = 0; i < a.args.kwonly.size(); i++) { + if (!a.args.kwonly.get(i).name.equals(b.args.kwonly.get(i).name)) { + return false; + } + } + return true; + } + + private static void param(Call c, StringBuilder sig, String name, String shown, FunctionDef f) { + c.args.add(at(new Name(name), f)); + sig.append(sig.length() == 0 ? "" : ", ").append(shown); + } + + private static T at(T n, FunctionDef f) { + n.line = f.line; + n.col = f.col; + return n; + } + + private static String moduleOf(String name, Map modules) { + for (int dot = name.lastIndexOf('.'); dot > 0; dot = name.lastIndexOf('.', dot - 1)) { + if (modules.containsKey(name.substring(0, dot))) { + return name.substring(0, dot); + } + } + return null; + } + + private static void leaveOut(FunctionDef f, String message) { + Call c = at(new Call(at(new Name("__cn1_removed__"), f)), f); + c.args.add(at(new Constant(Constant.Kind.STR, message), f)); + f.body.clear(); + f.body.add(at(new ExprStmt(c), f)); + } + + private static void methods(Object in, String qual, String directive) { + Infer.children(in, x -> { + if (x instanceof FunctionDef) { + leaveOut((FunctionDef) x, qual + "." + ((FunctionDef) x).name + " was left out of this build (remove=" + + directive + " in " + FILE + ")"); + } else if (x instanceof ClassDef) { + methods(((ClassDef) x).body, qual + "." + ((ClassDef) x).name, directive); + } else if (!(x instanceof Expr)) { + methods(x, qual, directive); + } + }); + } + + /// What a module left out of the build is in its place. Importing it + /// works, as does importing a name from it, so a module that is kept + /// and imports this one at its top still loads; the first use of + /// anything it would have held -- a call, an attribute, a class + /// derived from it -- raises, naming the module and the directive. + private static final String LEFT_OUT = "class _Cn1LeftOut:\n" + + " def __init__(self, name, bases=None, namespace=None):\n" + + " if bases is not None:\n" + + " __cn1_removed__(MESSAGE)\n" + + " object.__setattr__(self, '_cn1_name', name)\n" + + " def __getattr__(self, attribute):\n" + + " if attribute.startswith('__') and attribute.endswith('__'):\n" + + " raise AttributeError(attribute)\n" + + " __cn1_removed__(MESSAGE)\n" + + " def __mro_entries__(self, bases):\n" + + " __cn1_removed__(MESSAGE)\n" + + " def __call__(self, *args, **kwargs):\n" + + " __cn1_removed__(MESSAGE)\n" + + "def __getattr__(name):\n" + + " if name.startswith('__') and name.endswith('__'):\n" + + " raise AttributeError(name)\n" + + " return _Cn1LeftOut(name)\n"; + + private static void leaveOut(String module, Node.Module tree, String directive) { + String message = module + " was left out of this build (remove=" + directive + " in " + FILE + ")"; + String text = LEFT_OUT.replace("MESSAGE", "'" + message.replace("\\", "\\\\").replace("'", "\\'") + "'"); + tree.body.clear(); + tree.body.addAll(com.codename1.python.transpiler.parser.Parser.parse(text, module).body); + } + + private static List resolve(String name, Map modules) { + List r = new ArrayList(); + for (Object o : resolve(name, modules, false)) { + r.add((FunctionDef) o); + } + return r; + } + + /// The functions `name` is, and with `classes` the classes it is. + private static List resolve(String name, Map modules, boolean classes) { + String module = moduleOf(name, modules); + List in = new ArrayList(); + List r = new ArrayList(); + if (module != null) { + in.add(modules.get(module).body); + String[] path = name.substring(module.length() + 1).split("\\."); + for (int i = 0; i < path.length; i++) { + List next = new ArrayList(); + boolean last = i == path.length - 1; + for (Object o : in) { + find(o, path[i], last, next); + if (last && classes) { + classes(o, path[i], r); + } + } + in = next; + } + } + for (Object o : in) { + if (o instanceof FunctionDef) { + r.add(o); + } + } + if (r.isEmpty()) { + throw new PythonSyntaxError(FILE, 1, 1, name + " is not " + (classes ? "a function, a class, a module or a" + + " package" : "a function") + " of this program: a name is the module's dotted name" + + (classes ? " (pkg.module, or pkg for all of a package)," : "") + " followed by the function's" + + " (pkg.module.function)" + (classes ? ", by a class's (pkg.module.Class)" : "") + + " or by a class's and a method's (pkg.module.Class.method)"); + } + return r; + } + + /// Every definition of `name` that runs as part of `in`: inside `if`, + /// `try` and `with` too, where a module picks one of two versions. + private static void find(Object in, String name, boolean function, List out) { + Infer.children(in, x -> { + if (x instanceof FunctionDef) { + if (function && ((FunctionDef) x).name.equals(name)) { + out.add(x); + } + } else if (x instanceof ClassDef) { + if (!function && ((ClassDef) x).name.equals(name)) { + out.add(((ClassDef) x).body); + } + } else if (!(x instanceof Expr)) { + find(x, name, function, out); + } + }); + } + + /// Every class `name` that is defined as part of `in`. + private static void classes(Object in, String name, List out) { + Infer.children(in, x -> { + if (x instanceof ClassDef) { + if (((ClassDef) x).name.equals(name)) { + out.add(x); + } + } else if (!(x instanceof Expr) && !(x instanceof FunctionDef)) { + classes(x, name, out); + } + }); + } + + /// The class that holds the replacements of `module`'s functions: + /// `pkg.sub.utils` is `PkgSubUtilsShims`. + public static String shimClass(String module) { + StringBuilder sb = new StringBuilder(); + boolean up = true; + for (int i = 0; i < module.length(); i++) { + char c = module.charAt(i); + boolean letter = c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9'; + if (!letter) { + up = true; + } else if (up) { + sb.append(c >= 'a' && c <= 'z' ? (char) (c - 32) : c); + up = false; + } else { + sb.append(c); + } + } + return sb.append("Shims").toString(); + } + + /// The Java source of each class of replacements, by its path under a + /// source root: a stub per replaced function, raising until it is + /// filled in. The file is the developer's once written; a build only + /// writes one that does not exist. + public Map shims() { + Map out = new LinkedHashMap(); + for (Map.Entry> e : replaced.entrySet()) { + String cls = shimClass(e.getKey()); + StringBuilder sb = new StringBuilder(); + sb.append("package ").append(SHIM_PACKAGE).append(";\n\n"); + sb.append("import com.codename1.python.runtime.NativeModule;\n\n"); + sb.append("/// The functions of `").append(e.getKey()).append("` this build replaces with Java\n"); + sb.append("/// (`replace=` in `").append(FILE).append("`).\n"); + sb.append("///\n"); + sb.append("/// Generated with a stub for each. A stub receives the values of the function's\n"); + sb.append("/// parameters, in the order listed above it, as the Python runtime holds them, and\n"); + sb.append("/// returns what the call answers (`com.codename1.python.runtime.Py.NONE` for\n"); + sb.append("/// `None`). This file is yours: a build does not overwrite it.\n"); + sb.append("public final class ").append(cls).append(" {\n"); + sb.append(" private ").append(cls).append("() {\n }\n\n"); + sb.append(" /// Registers the replacements; the generated program calls this at start.\n"); + sb.append(" public static void install() {\n"); + for (Map.Entry f : e.getValue().entrySet()) { + sb.append(" // args: ").append(f.getValue().isEmpty() ? "none" : f.getValue()).append('\n'); + sb.append(" NativeModule.replace(\"").append(f.getKey()).append("\", args -> {\n"); + sb.append(" throw NativeModule.notReplaced(\"").append(f.getKey()).append("\");\n"); + sb.append(" });\n"); + } + sb.append(" }\n}\n"); + out.put(SHIM_PACKAGE.replace('.', '/') + "/" + cls + ".java", sb.toString()); + } + return out; + } + + /// The classes of [#shims], by qualified name, for the program to + /// install at start. + public List shimClasses() { + List r = new ArrayList(); + for (String module : replaced.keySet()) { + r.add(SHIM_PACKAGE + "." + shimClass(module)); + } + return r; + } +} diff --git a/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/Emitter.java b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/Emitter.java index 591a316d12e..82de08f873f 100644 --- a/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/Emitter.java +++ b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/Emitter.java @@ -56,7 +56,7 @@ /// - Comprehensions are immediately invoked lambdas: they are scopes of /// their own in Python 3. public final class Emitter { - private static final Map BIN = new HashMap(); + static final Map BIN = new HashMap(); private static final Map CMP = new HashMap(); static { @@ -122,6 +122,7 @@ private static final class Loop { private final List slotNames = new ArrayList(); private final Map slotIndex = new HashMap(); private final StringBuilder fields = new StringBuilder(); //NOPMD AvoidStringBufferField - the generator's output + private final Map paramTables = new HashMap(); private int uid; private final Scope moduleScope; @@ -144,6 +145,175 @@ public Emitter(String file, String moduleName, boolean isPackage, String package this.className = className; } + /// The absolute path every module's `__file__` sits under. Must match + /// `PyPackageData.ROOT`. + public static final String PACKAGE_DATA_ROOT = "/cn1python/"; + + /// A frame of its own for the generic expressions of one typed function + /// (see [#genericExpr]): their temporaries are its, declared once. + Object fallbackFrame(Scope fs) { + return new Frame(++uid, fs); + } + + /// The declarations of the temporaries `f`, a [#fallbackFrame], took. + String fallbackDecls(Object f) { + if (!(f instanceof Frame)) { + return ""; + } + Frame saved = frame; + frame = (Frame) f; + try { + return tempDecls(); + } finally { + frame = saved; + } + } + + /// `e` as generic code in function scope `fs`, inside the typed version + /// of that function (TypedEmit), which cannot lower it: every local it + /// reads is the Java code `names` maps it to, an Object. Null when the + /// code would name anything of the generic version's own frame (its + /// locals, cells or receiver), which the typed version does not have. + String genericExpr(Object f, Scope fs, Expr e, Map names) { + return inGeneric(f, fs, names, () -> expr(e)); + } + + /// Nested function `d` of `fs` as generic code inside the typed version + /// of `fs`, decorated: its decorators and defaults read the locals + /// `names` maps, its body the cells the typed version made. Null as for + /// [#genericExpr]. + String genericDef(Object f, Scope fs, FunctionDef d, Map names) { + return inGeneric(f, fs, names, () -> decorate(d.decorators, nestedDef(d))); + } + + /// Class `c`, defined in function `fs`, as generic code inside the typed + /// version of `fs`: the statements that make it and the class object, + /// which the typed version stores. Null as for [#genericExpr]. + String[] genericClass(Object f, Scope fs, ClassDef c, Map names) { + StringBuilder out = new StringBuilder(); + String[] value = new String[1]; + String r = inGeneric(f, fs, names, () -> { + String[] saved = classValue; + classValue = value; + try { + classDef(c, out, 0); + } finally { + classValue = saved; + } + return out + "\n" + value[0]; + }); + return r == null ? null : new String[] {out.toString(), value[0]}; + } + + private String inGeneric(Object f, Scope fs, Map names, java.util.function.Supplier code) { + Frame savedFrame = frame; + Scope savedSc = sc; + Map savedInline = inlineParams; + Scope savedInlineScope = inlineScope; + GenLowering savedGen = gen; + String savedSelfLocal = selfLocal; + Layouts.Cls savedSelfCls = selfCls; + String savedSelfTyped = selfTyped; + Map savedShadowVar = shadowVar; + Map savedShadowCls = shadowCls; + Map savedCarried = carried; + String[] savedLazy = lazyIndex; + boolean savedFast = inRegionFast; + Set savedRecycled = recycled; + frame = (Frame) f; + sc = fs; + inlineParams = names; + inlineScope = fs; + gen = null; + selfLocal = null; + selfCls = null; + selfTyped = null; + shadowVar = new HashMap(); + shadowCls = new HashMap(); + carried = null; + lazyIndex = null; + inRegionFast = false; + recycled = java.util.Collections.emptySet(); + try { + String r = code.get(); + int id = id(fs); + // A cell (c_name) is the typed version's too: it makes + // every cell a closure shares. + return java.util.regex.Pattern.compile("(? handlers() { + return handlers; + } + }; + } + PythonSyntaxError unsupported(Node n, String what) { return new PythonSyntaxError(file, n.line, n.col, what + " is not supported yet"); } @@ -155,14 +325,169 @@ PythonSyntaxError unsupported(Node n, String what) { private static final Set DYNAMIC_CODE = new HashSet(Arrays.asList("eval", "exec", "compile", "__import__")); - /// `sys` members that reach the interpreter's frames, which a - /// translated program does not have. + /// `sys` members that trace the interpreter's frames, which a + /// translated program does not have. `sys._getframe` is not one: the + /// runtime answers it from the Java stack (`StdModules.frame`). private static final Set FRAME_HOOKS = new HashSet(Arrays.asList("settrace", "setprofile", - "_getframe", "gettrace", "getprofile")); + "gettrace", "getprofile")); + + /// One use of dynamic code the program reaches: what a build has to be + /// told to remove or replace before it can succeed. + public static final class DynamicUse { + public final String file; + public final int line; + public final int col; + /// What was used, `eval()` say. + public final String what; + /// The module the use is in. + public final String module; + /// The outermost function it is in, as a directive names it, or + /// null when it runs as the module is imported. + public final String function; + + DynamicUse(String file, int line, int col, String what, String module, String function) { + this.file = file; + this.line = line; + this.col = col; + this.what = what; + this.module = module; + this.function = function; + } + } + + private List dynamicUses; + private boolean library; + + /// Marks the module as one of a PyPI package, not the application's + /// own: its `compile()` answers a code object that holds nothing to + /// run, where the application's own is a build error. + public Emitter library(boolean packaged) { + library = packaged; + return this; + } + + /// Where this module's reached uses of dynamic code are recorded. The + /// driver gives every module one list and fails the build once, with + /// all of them: a program that has one usually has several, in packages + /// it did not write, and a build that named them one at a time would + /// take as many builds to fix. + public Emitter dynamicUses(List into) { + dynamicUses = into; + return this; + } + + /// The one build error for every use in `uses`, or null when there are + /// none. It ends in the lines to paste into the directives file. + public static PythonSyntaxError dynamicCodeError(List uses) { + if (uses.isEmpty()) { + return null; + } + StringBuilder sb = new StringBuilder("a translated program cannot run or inspect code that was not" + + " compiled with it, and this one reaches code that does:"); + Set functions = new java.util.TreeSet(); + boolean moduleLevel = false; + for (DynamicUse u : uses) { + sb.append("\n ").append(u.file).append(':').append(u.line).append(':').append(u.col).append(": ") + .append(u.what); + if (u.function == null) { + moduleLevel = true; + sb.append(", as ").append(u.module).append(" is imported"); + } else { + functions.add(u.function); + sb.append(" in ").append(u.function); + } + } + if (!functions.isEmpty()) { + StringBuilder names = new StringBuilder(); + for (String f : functions) { + names.append(names.length() == 0 ? "" : ",").append(f); + } + sb.append("\nName each of those functions in ").append(Directives.FILE) + .append(", beside the Python sources. To leave them out (each then raises if it is called):") + .append("\n remove=").append(names) + .append("\nFor one the program needs, write replace= in place of remove=: its body is then" + + " Java, in a class the build generates for you to fill in."); + } + if (moduleLevel) { + sb.append("\nA use that runs as its module is imported is in no function, so nothing can be left out" + + " for it: that module has to change, or be written in Java."); + } + DynamicUse first = uses.get(0); + return new PythonSyntaxError(first.file, first.line, first.col, sb.toString()); + } + + private DynamicUse dynamicUse(Node n, String what) { + // The outermost function the code is in: the unit a build removes + // or replaces. + List chain = new ArrayList(); + for (Scope s = sc; s != null && s.kind != Scope.Kind.MODULE; s = s.parent) { + chain.add(0, s); + } + StringBuilder q = new StringBuilder(moduleName); + boolean function = false; + for (Scope s : chain) { + if (s.kind != Scope.Kind.CLASS && s.kind != Scope.Kind.FUNCTION || s.name == null) { + break; + } + q.append('.').append(s.name); + if (s.kind == Scope.Kind.FUNCTION) { + function = true; + break; + } + } + return new DynamicUse(file, n.line, n.col, what, moduleName, function ? q.toString() : null); + } + + /// The expression that stands for a dynamic-code use the program + /// reaches. There is none: the use is recorded and the build fails + /// after every module was read (see [#dynamicUses]); what is returned + /// only lets this module finish. A function nothing reaches is not + /// emitted and never gets here. + private String dynamicCodeAtRuntime(Node n, String what) { + DynamicUse u = dynamicUse(n, what); + if (dynamicUses == null) { + List one = new ArrayList(); + one.add(u); + throw dynamicCodeError(one); + } + dynamicUses.add(u); + return "Py.NONE"; + } - private PythonSyntaxError dynamicCode(Node n, String what) { - return new PythonSyntaxError(file, n.line, n.col, what - + " is not supported: a translated program cannot run or inspect code that was not compiled with it"); + /// Whether a class body annotates a name anywhere it runs as the body -- + /// `if`, `try`, `with`, loops and `match` included, nested functions and + /// classes not -- which is when CPython gives the class `__annotations__`. + private static boolean annotatesName(List body) { + for (Stmt s : body) { + if (s instanceof AnnAssign && ((AnnAssign) s).target instanceof Name) { + return true; + } + if (s instanceof If && (annotatesName(((If) s).body) || annotatesName(((If) s).orelse)) + || s instanceof While && (annotatesName(((While) s).body) || annotatesName(((While) s).orelse)) + || s instanceof For && (annotatesName(((For) s).body) || annotatesName(((For) s).orelse)) + || s instanceof With && annotatesName(((With) s).body)) { + return true; + } + if (s instanceof Try) { + Try t = (Try) s; + if (annotatesName(t.body) || annotatesName(t.orelse) || annotatesName(t.finalbody)) { + return true; + } + for (ExceptHandler h : t.handlers) { + if (annotatesName(h.body)) { + return true; + } + } + } + if (s instanceof Match) { + for (MatchCase mc : ((Match) s).cases) { + if (annotatesName(mc.body)) { + return true; + } + } + } + } + return false; } private int id(Scope s) { @@ -180,31 +505,123 @@ String fresh(String prefix) { // ---- module ---------------------------------------------------------- - public String emit(Node.Module m) { + /// The module's part in the program's type inference, once [#prepare] + /// ran. + private Infer infer; + + /// The program [#prepare] entered the module into. Its pass may run + /// more than once (`WholeProgram.infer`), each time over new modules; + /// [#settle] takes this module's from the run that stood. + private WholeProgram program; + + private void settle() { + Infer last = program == null ? null : program.types.modules.get(moduleName); + if (last != null) { + infer = last; + } + } + + /// Plans the module's classes and enters it into `program`, whose types + /// are inferred over every module at once (`WholeProgram.infer`) before + /// any of them is emitted. + public void prepare(Node.Module m, WholeProgram program) { Scope ms = moduleScope; slot("__name__"); slot("__doc__"); + slot("__file__"); + slot("__package__"); for (String n : ms.assigned) { slot(n); } frame = new Frame(id(ms), ms); sc = ms; + uncell(ms); + findDirectLong(m.body); + adoptLayouts(Layouts.plan(m.body, "", ms.attrStores, ms.assigned)); + this.program = program; + infer = program.types.add(moduleName, isPackage, m.body, layouts, ms, facts); + final List body = m.body; + final Scope scope = ms; + // Once every module is planned, a class whose base is a compiled + // class of another module is planned again as its subclass. + final Infer in = infer; + infer.replanner = (foreignBase, excluded, foreignMixin) -> { + adoptLayouts(Layouts.plan(body, "", scope.attrStores, scope.assigned, foreignBase, excluded, foreignMixin, + in::constantGlobal, in::fixedGlobal)); + return layouts; + }; + } + + private void adoptLayouts(Layouts l) { + layouts = l; + for (Layouts.Cls k : layouts.classes.values()) { + k.ref = className + "." + k.javaName; + } + // Until the program's table is shared, only the module's own. + allOwners = layouts.fieldOwners; + } + + /// Decides the module's typed fields, which takes them out of the + /// plain fields other modules may read (`Layouts.program`). + public void planTyped() { + settle(); + typedEmit = new TypedEmit(this, infer, layouts); + typedEmit.plan(); + for (Layouts.Cls k : layouts.classes.values()) { + k.typed = typedEmit; + } + } + + /// Writes the module's typed bodies, once every module of the program + /// has decided its typed fields ([#planTyped]). + public void planBodies() { + typedEmit.planBodies(); + } + + /// Hands every module the plain fields of every class of the program. + public static void shareLayouts(List all) { + List ls = new ArrayList(); + for (Emitter e : all) { + ls.add(e.layouts); + } + Map> owners = Layouts.program(ls); + for (Emitter e : all) { + e.allOwners = owners; + } + } + + /// Field name -> the classes of the whole program with that plain + /// field (`Layouts.program`). + private Map> allOwners; + + /// The program's field owners (see [#allOwners]); empty before + /// [#program] runs. + Map> fieldOwners() { + return allOwners != null ? allOwners : java.util.Collections.>emptyMap(); + } + + public String emit(Node.Module m) { + if (infer == null) { + // A module emitted on its own is a program of one. + WholeProgram alone = new WholeProgram(); + prepare(m, alone); + alone.infer(); + } + settle(); StringBuilder body = new StringBuilder(); List stmts = m.body; if (!stmts.isEmpty() && isDocstring(stmts.get(0))) { body.append(" G[1] = ").append(constant((Constant) ((ExprStmt) stmts.get(0)).value)).append(";\n"); } - findDirectLong(stmts); - layouts = Layouts.plan(stmts, "", ms.attrStores); - Infer infer = closed ? Infer.run(stmts, layouts, ms) : null; - if (infer != null && System.getProperty("cn1.python.dumpTypes") != null) { + if (System.getProperty("cn1.python.dumpTypes") != null) { System.err.println(infer.dump()); } - if (infer != null) { - typedEmit = new TypedEmit(this, infer, layouts); - typedEmit.plan(); + if (typedEmit == null) { + planTyped(); + planBodies(); } block(stmts, body, 2); + body.insert(0, hintTable()); StringBuilder out = new StringBuilder(); out.append("// Generated from ").append(javaComment(file)).append(" by the Codename One Python transpiler.\n"); @@ -219,24 +636,43 @@ public String emit(Node.Module m) { .append(javaString(e.getKey())).append(");\n"); } out.append(fields); + siteTables(out); out.append(layoutCode()); if (typedEmit != null) { out.append(typedEmit.members()); } + out.append(guardHelpers()); out.append("\n private ").append(className).append("() {\n }\n\n"); - out.append(" /// Makes `import ").append(javaComment(moduleName)).append("` find this module.\n"); - out.append(" public static void register() {\n"); - out.append(" PyModule.register(").append(javaString(moduleName)).append(", m -> exec(") - .append(javaString(moduleName)).append("));\n }\n\n"); out.append(" /// Runs the module body as module `runName` (`__main__` for the entry module).\n"); out.append(" public static PyModule exec(String runName) {\n"); - out.append(" M = PyModule.begin(runName, new String[] {"); + StringBuilder slots = new StringBuilder(); for (int i = 0; i < slotNames.size(); i++) { - out.append(i == 0 ? "" : ", ").append(javaString(slotNames.get(i))); + slots.append(i == 0 ? "" : "\n").append(slotNames.get(i)); + } + if (!slotNames.isEmpty() && slots.length() <= TABLE_CHARS) { + // One constant, not a store a name: see `tabled`. + out.append(" M = PyModule.begin(runName, Py.names(").append(javaString(slots.toString())) + .append("));\n"); + } else { + out.append(" M = PyModule.begin(runName, new String[] {"); + for (int i = 0; i < slotNames.size(); i++) { + out.append(i == 0 ? "" : ", ").append(javaString(slotNames.get(i))); + } + out.append("});\n"); } - out.append("});\n"); out.append(" G = M.slots;\n"); out.append(" G[0] = Py.str(runName);\n"); + // __file__ names the source under the read-only package data root, + // so a library that opens a data file beside its module + // (os.path.dirname(__file__)) reads it from the application's + // package data (PyPackageData). + out.append(" G[2] = Py.str(").append(javaString(PACKAGE_DATA_ROOT + file.replace('\\', '/'))) + .append(");\n"); + // __package__ is what relative imports resolve against: the module + // itself for a package, its parent otherwise ("" at the top level). + int dot = moduleName.lastIndexOf('.'); + String pkg = isPackage ? moduleName : dot < 0 ? "" : moduleName.substring(0, dot); + out.append(" G[3] = Py.str(").append(javaString(pkg)).append(");\n"); if ((frame.temps > 0 || frame.ltemps > 0)) { out.append(" ").append(tempDecls()).append("\n"); } @@ -247,7 +683,80 @@ public String emit(Node.Module m) { return out.toString(); } + /// The array of a function's defaults (a null element: a keyword-only + /// parameter without one). When every element is a module global or one of + /// the singletons -- what nearly all of them are, `None` and an API's + /// "not given" sentinel repeated down a long signature -- it is one string + /// with a character an element, read by the module's `ds`, instead of an + /// array literal. Natively each element of a literal is a checked store + /// with its write barrier, several hundred bytes of code that runs once: + /// the default arrays were most of the code of `openai`'s module bodies. + /// `ds` reads the globals left to right through `g`, so an unbound name + /// raises the same NameError at the same element as the literal would. + private String defaultArray(List es) { + String[] parts = new String[es.size()]; + StringBuilder spec = new StringBuilder(); + for (int i = 0; i < parts.length; i++) { + Expr e = es.get(i); + parts[i] = e == null ? "null" : expr(e); + char c = specChar(parts[i]); + if (spec != null && c != 0) { + spec.append(c); + } else { + spec = null; + } + } + if (spec != null && parts.length > 1) { + return "ds(" + javaString(spec.toString()) + ")"; + } + StringBuilder sb = new StringBuilder("new Object[] {"); + for (int i = 0; i < parts.length; i++) { + sb.append(i == 0 ? "" : ", ").append(parts[i]); + } + return sb.append('}').toString(); + } + + /// The `ds` character of an emitted default, or 0 when it has none. + private static char specChar(String e) { + switch (e) { + case "null": + return '-'; + case "Py.NONE": + return 'n'; + case "Py.TRUE": + return 't'; + case "Py.FALSE": + return 'f'; + case "Py.ELLIPSIS": + return 'e'; + default: + break; + } + if (e.startsWith("g(") && e.endsWith(")") && e.length() > 3) { + int k = 0; + for (int i = 2; i < e.length() - 1; i++) { + char d = e.charAt(i); + // Below 50000, so 256 + k is never a surrogate code unit. + if (d < '0' || d > '9' || k > 4999) { + return 0; + } + k = k * 10 + (d - '0'); + } + return (char) (256 + k); + } + return 0; + } + private static final String HELPERS = "" + + " private static Object[] ds(String s) {\n" + + " Object[] a = new Object[s.length()];\n" + + " for (int i = 0; i < a.length; i++) {\n" + + " char c = s.charAt(i);\n" + + " a[i] = c >= 256 ? g(c - 256) : c == 'n' ? Py.NONE : c == 't' ? Py.TRUE\n" + + " : c == 'f' ? Py.FALSE : c == 'e' ? Py.ELLIPSIS : null;\n" + + " }\n" + + " return a;\n" + + " }\n\n" + " private static Object g(int i) {\n" + " Object v = G[i];\n" + " return v != null ? v : M.unbound(i);\n" @@ -258,6 +767,12 @@ public String emit(Node.Module m) { + " }\n" + " return v;\n" + " }\n\n" + + " private static Object lf(Object v, String n) {\n" + + " if (v == null) {\n" + + " throw Py.unboundFree(n);\n" + + " }\n" + + " return v;\n" + + " }\n\n" + " private static Object ul(String n) {\n" + " throw Py.unboundLocal(n);\n" + " }\n\n" @@ -265,7 +780,7 @@ public String emit(Node.Module m) { + " return v != null ? v : dyn(n);\n" + " }\n\n" + " private static Object dyn(String n) {\n" - + " Object v = M.getAttrOrNull(n);\n" + + " Object v = M.getGlobal(n);\n" + " if (v == null) {\n" + " v = Builtins.lookup(n);\n" + " }\n" @@ -337,8 +852,27 @@ private String cellVar(Scope s, String n) { private String load(Name nm) { String n = nm.id; + if (inlineParams != null && sc == inlineScope && inlineParams.containsKey(n)) { //NOPMD CompareObjectsWithEquals - identity is meant + return inlineParams.get(n); + } + if (inlineParams != null && compParams == null && sc != inlineScope //NOPMD CompareObjectsWithEquals - identity is meant + && sc.resolve(n) == Scope.Binding.FREE && sc.owner(n) == inlineScope //NOPMD CompareObjectsWithEquals - identity is meant + && inlineParams.containsKey(n)) { + // A generator expression or lambda in a typed function's generic + // expression (TypedEmit.genericFallback): the value it captured, a + // parameter of the Java lambda around the expression. Not in a + // helper comprehension, a method of its own that takes its values. + return inlineParams.get(n); + } if (DYNAMIC_CODE.contains(n) && sc.resolve(n) == Scope.Binding.BUILTIN) { - throw dynamicCode(nm, n + "()"); + if ("compile".equals(n) && library) { + // Compiling is harmless; running what it made is eval or + // exec, which do not build. A package that compiles a + // snippet as it is imported (anyio's subinterpreter + // worker) is in no function a build could leave out. + return "Py.UNCOMPILED"; + } + return dynamicCodeAtRuntime(nm, n + "()"); } if (inRegionFast && lazyIndex != null && lazyIndex[0].equals(n)) { return "(" + lazyIndex[1] + " == null ? Long.valueOf(" + lazyIndex[2] + ") : " + localVar(sc, n) + ")"; @@ -374,10 +908,23 @@ private String load(Name nm) { } return "(" + localVar(sc, n) + " != null ? " + localVar(sc, n) + " : ul(" + javaString(n) + "))"; case CELL: + if (boundCell(sc, n)) { + return cellVar(sc, n) + "[0]"; + } return "l(" + cellVar(sc, n) + "[0], " + javaString(n) + ")"; case FREE: { + String p = compParams == null ? null : compParams.get(n); + if (p != null) { + return "l(" + p + ", " + javaString(n) + ")"; + } Scope o = sc.owner(n); - return "l(" + cellVar(o, n) + "[0], " + javaString(n) + ")"; + if (boundCell(o, n)) { + return cellVar(o, n) + "[0]"; + } + // CPython inlines a comprehension, so a read from one is + // still the function's own local; any other scope reads a + // free variable, NameError when unbound. + return (inlinedIn(sc, o) ? "l(" : "lf(") + cellVar(o, n) + "[0], " + javaString(n) + ")"; } case GLOBAL: return "g(" + slot(n) + ")"; @@ -404,7 +951,9 @@ String builtinRef(String n) { f = "B" + builtins.size() + "_" + mangle(n); builtins.put(n, f); } - return "b(" + f + ", " + javaString(n) + ")"; + // Inline: ParparVM does not inline calls, and a static call costs a + // frame push per builtin use. + return "(" + f + " != null ? " + f + " : dyn(" + javaString(n) + "))"; } void storeName(String n, String value, StringBuilder out, int ind) { @@ -415,7 +964,7 @@ void storeName(String n, String value, StringBuilder out, int ind) { out.append(v).append(" = ").append(value).append(";\n"); String h = shadowVar.get(v); if (h != null) { - String k = shadowCls.get(v).javaName; + String k = shadowCls.get(v).ref; indent(out, ind); out.append(h).append(" = ").append(v).append(" instanceof ").append(k).append(" ? (").append(k) .append(") ").append(v).append(" : null;\n"); @@ -488,7 +1037,20 @@ private void block(List body, StringBuilder out, int ind) { } } + /// Set while a trailing class attribute store emits its own store. + private boolean inTrailing; + void stmt(Stmt s, StringBuilder out, int ind) { + if (Layouts.trailingStore(s) && !inTrailing) { + inTrailing = true; + try { + stmt(s, out, ind); + } finally { + inTrailing = false; + } + trailingStatic((Assign) s, out, ind); + return; + } lineMark(s.line, out, ind); if (s instanceof ExprStmt) { Expr v = ((ExprStmt) s).value; @@ -583,10 +1145,24 @@ void stmt(Stmt s, StringBuilder out, int ind) { augAssign((AugAssign) s, out, ind); } else if (s instanceof AnnAssign) { AnnAssign a = (AnnAssign) s; - if (sc.kind == Scope.Kind.CLASS && a.target instanceof Name) { + collectHints(a.annotation); + StringBuilder entry = new StringBuilder(); + if (sc.kind == Scope.Kind.CLASS && a.target instanceof Name + && annotationEntry(entry, ((Name) a.target).id, a.annotation)) { + // Evaluated here, in order, as the statement is -- by the + // table's evaluator: a model class is a hundred of these. + indent(out, ind); + out.append("Annotations.set(").append(sc.classVar).append(", M, ") + .append(javaString(entry.toString())).append(");\n"); + } else if (sc.kind == Scope.Kind.CLASS && a.target instanceof Name) { + String v = fresh("an"); + indent(out, ind); + out.append("Object ").append(v).append(";\n"); + indent(out, ind); + out.append(annotationStore(v, a.annotation)).append('\n'); indent(out, ind); out.append("Py.setitem(").append(annotations()).append(", Py.str(") - .append(javaString(((Name) a.target).id)).append("), ").append(annotationExpr(a.annotation)) + .append(javaString(((Name) a.target).id)).append("), ").append(v) .append(");\n"); } if (a.value != null) { @@ -695,6 +1271,8 @@ void stmt(Stmt s, StringBuilder out, int ind) { nextAsync = f.isAsync; staticBody = layouts.staticNames.get(f); staticClass = layouts.methodClass.get(f); + receiverHint = layouts.receiverClass.get(f); + removedBody = infer != null && infer.removed(f) ? removedNote(f) : null; String fn = withMetadata(f, function(f.name, f.args, f.scope, f.body, null)); storeName(f.name, decorate(f.decorators, fn), out, ind); } else if (s instanceof ClassDef) { @@ -709,6 +1287,80 @@ void stmt(Stmt s, StringBuilder out, int ind) { } } + /// Every dotted name a string annotation of this module spells + /// (`"Foo"`, `Optional["pkg.Bar"]`, `"list[Foo] | None"`): the only + /// names `typing.get_type_hints` may resolve a forward reference to. + private final Set hintNames = new LinkedHashSet(); + + private void collectHints(Expr a) { + if (a instanceof Constant) { + Constant c = (Constant) a; + if (c.kind == Constant.Kind.STR) { + java.util.regex.Matcher m = HINT_NAME.matcher(c.text); + while (m.find()) { + hintNames.add(m.group()); + } + } + } else if (a instanceof Subscript) { + collectHints(((Subscript) a).value); + collectHints(((Subscript) a).index); + } else if (a instanceof BinOp) { + collectHints(((BinOp) a).left); + collectHints(((BinOp) a).right); + } else if (a instanceof TupleExpr) { + for (Expr e : ((TupleExpr) a).elts) { + collectHints(e); + } + } else if (a instanceof ListExpr) { + for (Expr e : ((ListExpr) a).elts) { + collectHints(e); + } + } else if (a instanceof Call) { + for (Expr e : ((Call) a).args) { + collectHints(e); + } + } + } + + private static final java.util.regex.Pattern HINT_NAME = + java.util.regex.Pattern.compile("[A-Za-z_][A-Za-z0-9_]*(\\.[A-Za-z_][A-Za-z0-9_]*)*"); + + /// The module's forward-reference table, `__cn1_hints__`: a function + /// answering a dict from each name [#hintNames] holds to what it names, + /// every entry a compiled reference to the global or builtin (and + /// literal attribute reads after it), never a lookup by the string. It + /// is a function so that it reads the names when asked, after the + /// module has bound them; a name still unbound then is left out, and + /// `typing` refuses what the table does not hold. + private String hintTable() { + StringBuilder sb = new StringBuilder(); + String d = fresh("hd"); + for (String n : hintNames) { + String[] parts = n.split("\\."); + if ("None".equals(parts[0])) { + continue; + } + Scope.Binding b = sc.resolve(parts[0]); + if (b != Scope.Binding.GLOBAL && b != Scope.Binding.BUILTIN) { + continue; + } + String v = expr(new Name(parts[0])); + for (int i = 1; i < parts.length; i++) { + v = "Py.getattr(" + v + ", " + javaString(parts[i]) + ")"; + } + String e = fresh("he"); + String x = fresh("hv"); + sb.append("try { final Object ").append(x).append(" = ").append(v).append("; if (").append(x) + .append(" != null) { ").append(d).append(".setItem(Py.str(").append(javaString(n)).append("), ") + .append(x).append("); } } catch (PyException ").append(e).append(") { } "); + } + if (sb.length() == 0) { + return ""; + } + return " M.setAttr(\"__cn1_hints__\", new PyFunction(\"__cn1_hints__\", new String[0], " + + "a -> { final PyDict " + d + " = new PyDict(); " + sb + "return " + d + "; }));\n"; + } + private String annotations() { return "Py.getattr(" + sc.classVar + ", \"__annotations__\")"; } @@ -728,31 +1380,165 @@ private String withMetadata(FunctionDef f, String fn) { if (f.args.kwarg != null) { all.add(f.args.kwarg); } - StringBuilder ann = new StringBuilder(); + List keys = new ArrayList(); + List values = new ArrayList(); for (Arg a : all) { if (a.annotation != null) { - ann.append(ann.length() == 0 ? "" : ", ").append(javaString(a.name)).append(", ") - .append(annotationExpr(a.annotation)); + collectHints(a.annotation); + keys.add(javaString(a.name)); + values.add(a.annotation); } } if (f.returns != null) { - ann.append(ann.length() == 0 ? "" : ", ").append("\"return\", ").append(annotationExpr(f.returns)); + collectHints(f.returns); + keys.add("\"return\""); + values.add(f.returns); } - if ("null".equals(doc) && ann.length() == 0) { + if ("null".equals(doc) && keys.isEmpty()) { return fn; } - String thunk = ann.length() == 0 ? "null" : "() -> new Object[] {" + ann + "}"; + // ONE lambda per function, filling the array statement by statement. Each + // annotation used to be a lambda of its own, only so that a raising one could + // fall back to its source form; on ParparVM every lambda is a class, and those + // thunks were a third of the classes of a large application. + String thunk = "null"; + String table = keys.isEmpty() ? null : annotationTable(all, f.returns); + if (table != null) { + // The usual annotation -- names, attributes, subscripts, unions -- + // is written down, not compiled: what reads `__annotations__` is + // rare, and a thunk per function was a class and a method each + // for code that almost never runs. + return "PyFunction.meta(" + fn + ", " + doc + ", M, " + javaString(table) + ")"; + } + if (!keys.isEmpty()) { + String r = fresh("ann"); + StringBuilder body = new StringBuilder("() -> { final Object[] ").append(r) + .append(" = new Object[").append(keys.size() * 2).append("]; "); + for (int i = 0; i < keys.size(); i++) { + body.append(r).append('[').append(i * 2).append("] = ").append(keys.get(i)).append("; "); + body.append(annotationStore(r + "[" + (i * 2 + 1) + "]", values.get(i))).append(' '); + } + body.append("return ").append(r).append("; }"); + thunk = body.toString(); + } return "PyFunction.meta(" + fn + ", " + doc + ", " + thunk + ")"; } /// An annotation's value: the evaluated expression when it only names /// module globals and builtins (falling back to the source-ish form if /// evaluating it raises), otherwise [#annotationValue]. - private String annotationExpr(Expr a) { + /// Statements assigning an annotation's value to `target`: the evaluated + /// expression when it only names module globals and builtins (falling back to + /// the source-ish form if evaluating it raises), otherwise [#annotationValue]. + /// The fallback is a catch, not a lambda: on ParparVM every lambda is a class. + private String annotationStore(String target, Expr a) { + if (a instanceof Constant) { + return target + " = " + expr(a) + ";"; + } if (!evaluable(a)) { - return annotationValue(a); + return target + " = " + annotationValue(a) + ";"; + } + String e = fresh("ae"); + return "try { " + target + " = " + expr(a) + "; } catch (PyException " + e + ") { " + + target + " = " + annotationValue(a) + "; }"; + } + + /// The annotations of a function as the program `Annotations.build` + /// runs on first read, or null when one of them is more than that + /// program expresses (a call, a lambda) and has to be compiled. + /// + /// One instruction a line. `=name` opens the annotation of a parameter + /// (`return` for the result) and `!text` gives what it is when + /// evaluating it raises; the rest is its expression in postfix order. + private String annotationTable(List all, Expr returns) { + StringBuilder sb = new StringBuilder(); + for (Arg a : all) { + if (a.annotation != null && !annotationEntry(sb, a.name, a.annotation)) { + return null; + } + } + if (returns != null && !annotationEntry(sb, "return", returns)) { + return null; + } + return sb.toString(); + } + + private boolean annotationEntry(StringBuilder sb, String key, Expr a) { + sb.append('=').append(key).append('\n'); + if (!(a instanceof Constant) && !evaluable(a)) { + // Not evaluated at all: its name, or None. + sb.append(a instanceof Name ? "c" + ((Name) a).id : "N").append('\n'); + return true; + } + if (a instanceof Name) { + sb.append('!').append(((Name) a).id).append('\n'); + } + return annotationCode(sb, a); + } + + private boolean annotationCode(StringBuilder sb, Expr a) { + if (a instanceof Constant) { + Constant c = (Constant) a; + switch (c.kind) { + case NONE: + sb.append("N\n"); + return true; + case TRUE: + sb.append("T\n"); + return true; + case FALSE: + sb.append("F\n"); + return true; + case ELLIPSIS: + sb.append("E\n"); + return true; + case STR: + if (c.text.indexOf('\n') >= 0) { + return false; + } + sb.append('c').append(c.text).append('\n'); + return true; + default: + return false; + } + } + if (a instanceof Name) { + String id = ((Name) a).id; + sb.append(sc.resolve(id) == Scope.Binding.BUILTIN ? 'b' : 'g').append(id).append('\n'); + return true; } - return "PyFunction.annotation(() -> " + expr(a) + ", " + annotationValue(a) + ")"; + if (a instanceof Attribute) { + if (!annotationCode(sb, ((Attribute) a).value)) { + return false; + } + sb.append('a').append(((Attribute) a).attr).append('\n'); + return true; + } + if (a instanceof Subscript) { + if (!annotationCode(sb, ((Subscript) a).value) || !annotationCode(sb, ((Subscript) a).index)) { + return false; + } + sb.append("s\n"); + return true; + } + if (a instanceof BinOp && "|".equals(((BinOp) a).op)) { + if (!annotationCode(sb, ((BinOp) a).left) || !annotationCode(sb, ((BinOp) a).right)) { + return false; + } + sb.append("|\n"); + return true; + } + if (a instanceof TupleExpr || a instanceof ListExpr) { + List elts = a instanceof TupleExpr ? ((TupleExpr) a).elts : ((ListExpr) a).elts; + for (Expr e : elts) { + if (e instanceof Starred || !annotationCode(sb, e)) { + return false; + } + } + sb.append(a instanceof TupleExpr ? 't' : 'l').append(elts.size()).append('\n'); + return true; + } + return false; } private boolean evaluable(Expr a) { @@ -860,10 +1646,10 @@ void store(Expr t, String value, StringBuilder out, int ind) { o = fresh("o"); out.append("final Object ").append(o).append(" = ").append(recv).append(";\n"); } - fieldSet(a.attr, o, value, site(a.attr), out, ind); + fieldSet(a.attr, o, value, storeSite(a.attr), out, ind); return; } - out.append(site(a.attr)).append(".set(").append(expr(a.value)).append(", ").append(value) + out.append(storeSite(a.attr)).append(".set(").append(expr(a.value)).append(", ").append(value) .append(");\n"); } else if (t instanceof Subscript) { Subscript sub = (Subscript) t; @@ -889,12 +1675,25 @@ void store(Expr t, String value, StringBuilder out, int ind) { } } String arr = fresh("u"); - indent(out, ind); - out.append("final Object[] ").append(arr).append(" = "); if (star < 0) { - out.append(onlyNames(t) ? "Py.unpackNames(" : "Py.unpack(").append(value).append(", ") + // A fixed-size tuple is read in place: the runtime answers + // an empty array for one and no array is made. + String held = fresh("uv"); + indent(out, ind); + out.append("final Object ").append(held).append(" = ").append(value).append(";\n"); + indent(out, ind); + out.append("final Object[] ").append(arr).append(" = ") + .append(onlyNames(t) ? "Py.unpackNamesT(" : "Py.unpackT(").append(held).append(", ") .append(elts.size()).append(");\n"); - } else { + for (int i = 0; i < elts.size(); i++) { + store(elts.get(i), "(" + arr + ".length != 0 ? " + arr + "[" + i + "] : ((PyTuple) " + held + + ").get(" + i + "))", out, ind); + } + return; + } + indent(out, ind); + out.append("final Object[] ").append(arr).append(" = "); + { out.append("Py.unpackStar(").append(value).append(", ").append(star).append(", ") .append(elts.size() - star - 1).append(");\n"); } @@ -932,8 +1731,80 @@ private static boolean rangeCall(Expr e) { /// `x.split()` with no arguments, which a loop walks word by word /// (Py.splitWords) instead of splitting into a list first. - private static boolean splitWords(Expr e) { - if (!(e instanceof Call)) { + private boolean inCast; + + /// `cast(T, v)` or `typing.cast(T, v)` with `T` a plain type expression + /// and `v` an expression that may be emitted twice (no nested scope). + static boolean castCall(Call c) { + if (c.args.size() != 2 || !c.keywords.isEmpty() || Infer.hasStarred(c.args)) { + return false; + } + boolean named = c.func instanceof Name && "cast".equals(((Name) c.func).id) + || c.func instanceof Attribute && "cast".equals(((Attribute) c.func).attr) + && ((Attribute) c.func).value instanceof Name; + return named && typeExpr(c.args.get(0)) + && com.codename1.python.transpiler.analyze.GenInline.plainExpr(c.args.get(1)); + } + + /// Names, dotted names, string constants, None and subscriptions, tuples, + /// lists and unions of them: what a type annotation is made of. + private static boolean typeExpr(Expr e) { + if (e instanceof Name) { + return true; + } + if (e instanceof Constant) { + Constant k = (Constant) e; + return k.kind == Constant.Kind.STR || k.kind == Constant.Kind.NONE; + } + if (e instanceof Attribute) { + return typeExpr(((Attribute) e).value); + } + if (e instanceof Subscript) { + return typeExpr(((Subscript) e).value) && typeExpr(((Subscript) e).index); + } + if (e instanceof TupleExpr || e instanceof ListExpr) { + for (Expr x : e instanceof TupleExpr ? ((TupleExpr) e).elts : ((ListExpr) e).elts) { + if (!typeExpr(x)) { + return false; + } + } + return true; + } + if (e instanceof BinOp) { + BinOp b = (BinOp) e; + return "|".equals(b.op) && typeExpr(b.left) && typeExpr(b.right); + } + return false; + } + + /// The receiver of `x.items()` iterated into exactly two names, or null. + /// Such a loop walks the pairs with the runtime's `ItemWalk` instead of building a + /// tuple per entry; with any other target an item may be kept, so it is + /// a real tuple. + static Expr itemPairs(Expr iter, Expr target) { + if (!(iter instanceof Call) || !(target instanceof TupleExpr)) { + return null; + } + List elts = ((TupleExpr) target).elts; + if (elts.size() != 2 || !(elts.get(0) instanceof Name) || !(elts.get(1) instanceof Name)) { + return null; + } + Call c = (Call) iter; + if (!c.args.isEmpty() || !c.keywords.isEmpty() || !(c.func instanceof Attribute) + || !"items".equals(((Attribute) c.func).attr)) { + return null; + } + return ((Attribute) c.func).value; + } + + /// What a loop over `iter` into `target` iterates (see [#itemPairs]). + private String loopSource(Expr iter, Expr target) { + Expr recv = itemPairs(iter, target); + return recv != null ? "ItemWalk.of(" + expr(recv) + ")" : expr(iter); + } + + private static boolean splitWords(Expr e) { + if (!(e instanceof Call)) { return false; } Call c = (Call) e; @@ -981,7 +1852,7 @@ private static boolean parallel(Expr t, Expr v) { /// Whether an unpacking target is made of plain names only, so storing /// into it cannot change the sequence being unpacked. - private static boolean onlyNames(Expr t) { + static boolean onlyNames(Expr t) { if (t instanceof Name) { return true; } @@ -1105,9 +1976,9 @@ private void augAssign(AugAssign a, StringBuilder out, int ind) { String nv = fresh("s"); out.append("final Object ").append(nv).append(" = ") .append(augValue(op, fieldGet(at.attr, o, site(at.attr)), a)).append(";\n"); - fieldSet(at.attr, o, nv, site(at.attr), out, ind); + fieldSet(at.attr, o, nv, storeSite(at.attr), out, ind); } else { - out.append(site(at.attr)).append(".set(").append(o).append(", ") + out.append(storeSite(at.attr)).append(".set(").append(o).append(", ") .append(augValue(op, site(at.attr) + ".get(" + o + ")", a)).append(");\n"); } } else if (a.target instanceof Subscript) { @@ -1145,7 +2016,7 @@ private void importFrom(ImportFrom f, StringBuilder out, int ind) { } } - private String resolveRelative(ImportFrom f) { + String resolveRelative(ImportFrom f) { if (f.level == 0) { return f.module; } @@ -1301,11 +2172,14 @@ private void forStmt(For f, StringBuilder out, int ind) { vsig = new String[] {it, ri, re, rs, Integer.toString(ind)}; } indent(out, ind); - out.append(label).append(": for (Object ").append(x).append("; (").append(x).append(" = ").append(it) - .append(" != null ? ").append(it).append(".next() : (").append(rs).append(" > 0 ? ").append(ri) - .append(" < ").append(re).append(" : ").append(ri).append(" > ").append(re) - .append(") ? ").append(lazy != null ? "Py.NONE" : "Long.valueOf(" + ri + ")") - .append(" : null) != null; ").append(ri).append(" += ").append(rs).append(") {\n"); + // One handler for the whole loop, outside the label so that + // `continue label` still names a loop (TypedEmit.loopNext). + out.append("try {\n"); + indent(out, ind); + String next = it + " != null ? " + TypedEmit.loopNext(it) + " : (" + rs + " > 0 ? " + ri + + " < " + re + " : " + ri + " > " + re + ") ? " + + (lazy != null ? "Py.NONE" : "Long.valueOf(" + ri + ")") + " : null"; + out.append(label).append(": ").append(TypedEmit.loopHead(x, next, ri + " += " + rs)); } else { // A list is walked by index (re-reading its length every step, as // its own iterator does), so the loop allocates no iterator. @@ -1320,7 +2194,7 @@ private void forStmt(For f, StringBuilder out, int ind) { Call sc1 = (Call) f.iter; src = "Py.splitOn(" + expr(((Attribute) sc1.func).value) + ", " + expr(sc1.args.get(0)) + ")"; } else { - src = expr(f.iter); + src = loopSource(f.iter, f.target); } out.append("final Object ").append(sq).append(" = ").append(src).append(";\n"); indent(out, ind); @@ -1332,9 +2206,11 @@ private void forStmt(For f, StringBuilder out, int ind) { indent(out, ind); out.append("int ").append(li).append(" = 0;\n"); indent(out, ind); - out.append(label).append(": for (Object ").append(x).append("; (").append(x).append(" = ").append(it) - .append(" != null ? ").append(it).append(".next() : ").append(li).append(" < ").append(ls) - .append(".size() ? ").append(ls).append(".get(").append(li).append("++) : null) != null;) {\n"); + out.append("try {\n"); + indent(out, ind); + String next = it + " != null ? " + TypedEmit.loopNext(it) + " : " + li + " < " + ls + + ".size() ? " + ls + ".get(" + li + "++) : null"; + out.append(label).append(": ").append(TypedEmit.loopHead(x, next, null)); } if (lazy != null) { indent(out, ind + 1); @@ -1366,6 +2242,8 @@ private void forStmt(For f, StringBuilder out, int ind) { loops.remove(loops.size() - 1); indent(out, ind); out.append("}\n"); + indent(out, ind); + out.append(TypedEmit.loopHandler(it)); if (lazy != null) { indent(out, ind); out.append("if (").append(it).append(" == null && ").append(lazy[2]).append(" != ").append(lazy[4]) @@ -1515,9 +2393,11 @@ private void withItems(With w, int i, StringBuilder out, int ind) { indent(out, ind); out.append("final Object ").append(mgr).append(" = ").append(expr(item.context)).append(";\n"); indent(out, ind); - out.append("final Object ").append(exit).append(" = Py.getattr(").append(mgr) - .append(", \"__exit__\");\n"); - String entered = "Py.callMethod(" + mgr + ", \"__enter__\")"; + // Both through cached sites, as any attribute: by name each time, + // they cost a full lookup per with-statement executed. + out.append("final Object ").append(exit).append(" = ").append(site("__exit__")).append(".get(").append(mgr) + .append(");\n"); + String entered = site("__enter__") + ".call0(" + mgr + ")"; if (item.vars != null) { String ev = fresh("en"); indent(out, ind); @@ -1596,7 +2476,9 @@ private void classDef(ClassDef c, StringBuilder out, int ind) { } indent(out, ind); if (lc != null) { - fields.append(" private static PyType ").append(k).append(";\n"); + // Package-visible: another module's build-time-bound constructor + // call tests that it still calls this class (Emitter.boundInit). + fields.append(" static PyType ").append(k).append(";\n"); out.append(k); } else { out.append("final PyType ").append(k); @@ -1612,13 +2494,7 @@ private void classDef(ClassDef c, StringBuilder out, int ind) { out.append(k).append(".define(\"__module__\", G[0]);\n"); indent(out, ind); out.append(k).append(".define(\"__qualname__\", Py.str(").append(javaString(c.name)).append("));\n"); - boolean anns = false; - for (Stmt s : c.body) { - if (s instanceof AnnAssign && ((AnnAssign) s).target instanceof Name) { - anns = true; - } - } - if (anns) { + if (annotatesName(c.body)) { indent(out, ind); out.append(k).append(".define(\"__annotations__\", new PyDict());\n"); } @@ -1646,12 +2522,23 @@ private void classDef(ClassDef c, StringBuilder out, int ind) { } else { out.append(", new String[] {").append(kwNames).append("}, new Object[] {").append(kwValues).append("});\n"); } + if (lc != null && infer != null) { + classStatics(lc, k, out, ind); + } for (int i = decos.size() - 1; i >= 0; i--) { v = "Py.call(" + decos.get(i) + ", " + v + ")"; } + if (classValue != null) { + classValue[0] = v; + return; + } storeName(c.name, v, out, ind); } + /// Set by [#genericClass]: classDef answers the class here instead of + /// storing it. + private String[] classValue; + // ---- functions ------------------------------------------------------- /// `__qualname__`: the enclosing classes and functions, as CPython @@ -1669,10 +2556,164 @@ private static String qualname(Scope fs) { } /// A `new PyFunction(...)` expression. `exprBody` is set for a lambda. + /// The parameters of a lambda being expanded in place, each to the temporary + /// that holds its argument; read by load() while `sc` is that lambda's scope. + private Map inlineParams; + private Scope inlineScope; + + /// `(lambda x, y: body)(a, b)` as `body` itself, in the caller: the arguments + /// go to temporaries of the caller's frame, and Py.seq orders those stores + /// before the body (Java evaluates arguments left to right). Null when the + /// body could see the difference: a parameter a nested scope captures, a + /// nested scope at all, or a walrus, which binds in the caller. + private String inlineLambda(Lambda l, Call c) { + if (gen != null || inlineParams != null) { + return null; + } + for (Arg a : l.args.positional) { + if (l.scope.cells.contains(a.name)) { + return null; + } + } + boolean[] plain = {true}; + Infer.Visit[] v = new Infer.Visit[1]; + v[0] = x -> { + if (x instanceof Lambda || x instanceof Comp || x instanceof NamedExpr || x instanceof Yield + || x instanceof Await) { + plain[0] = false; + } else if (plain[0]) { + Infer.children(x, v[0]); + } + }; + v[0].on(l.body); + if (!plain[0]) { + return null; + } + List stores = new ArrayList(); + Map map = new HashMap(); + for (int i = 0; i < c.args.size(); i++) { + String t = temp(); + stores.add(t + " = " + expr(c.args.get(i))); + map.put(l.args.positional.get(i).name, t); + } + Scope saved = sc; + sc = l.scope; + inlineParams = map; + inlineScope = l.scope; + String body; + try { + body = expr(l.body); + } finally { + sc = saved; + inlineParams = null; + inlineScope = null; + } + StringBuilder r = new StringBuilder(); + for (String st : stores) { + r.append("Py.seq(").append(st).append(", "); + } + r.append(body); + for (int k = stores.size(); k > 0; k--) { + r.append(')'); + } + return r.toString(); + } + + /// Lambda `l` as a function object, for the typed code: one that reads + /// nothing of the frame it is made in (`TypedEmit.closedLambda`). + /// The function object of nested `def f`, for TypedEmit: the body is + /// generic code, and reads the enclosing function's captured + /// parameters through the cells TypedEmit names with [#cellName]. + String nestedDef(FunctionDef f) { + nextAsync = f.isAsync; + return withMetadata(f, function(f.name, f.args, f.scope, f.body, null)); + } + + /// The Java name of cell `n` of function scope `s`. + String cellName(Scope s, String n) { + return cellVar(s, n); + } + + String lambdaValue(Lambda l) { + return function("", l.args, l.scope, null, l.body); + } + + /// Whether `s` is a comprehension inside `o` with only comprehensions + /// between them. + private static boolean inlinedIn(Scope s, Scope o) { + Scope c = s; + while (c != null && c != o && c.kind == Scope.Kind.COMPREHENSION) { //NOPMD CompareObjectsWithEquals - identity is meant + c = c.parent; + } + return c == o; //NOPMD CompareObjectsWithEquals - identity is meant + } + + /// Whether cell `n` of `o` is bound for as long as anything can read + /// it: a parameter (bound on entry) that `o` never assigns or deletes and + /// no nested scope rebinds through `nonlocal`. Its reads skip the + /// unbound check. + private static boolean boundCell(Scope o, String n) { + return o != null && o.params.contains(n) && !o.assigned.contains(n) && !o.deleted.contains(n) + && !rebinds(o, o, n); + } + + private static boolean rebinds(Scope s, Scope owner, String n) { + for (Scope c : s.children) { + if (c.nonlocals.contains(n) && c.owner(n) == owner || rebinds(c, owner, n)) { //NOPMD CompareObjectsWithEquals - identity is meant + return true; + } + } + return false; + } + + /// Set by call() for a lambda it calls in place: function() then answers the + /// bare body lambda, with no PyFunction around it. + private boolean inlineCalled; + private int paramNames; + + /// Set by the statement of a function nothing in the program reaches, + /// for [#function] to emit in place of its body: the message it raises + /// with when something calls it after all. + private String removedBody; + + private String removedNote(FunctionDef f) { + String q = (sc.kind == Scope.Kind.CLASS && sc.name != null ? sc.name + "." : "") + f.name; + return moduleName + "." + q + " was left out of this build: nothing in the program calls it or" + + " takes it as a value. If it is reached in a way the build cannot see (by a computed name," + + " or from Java), add the line keep=" + moduleName + "." + q + " to cn1-python.properties"; + } + + /// `Py.TRUE` or `Py.FALSE` for a function of one plain parameter whose + /// body (after a docstring) is only `return True` or `return False`; + /// null for any other (see PyFunction#constant). + static String constantBool(Arguments args, List body) { + if (body == null || args.positional.size() != 1 || !args.defaults.isEmpty() || args.vararg != null + || args.kwarg != null || !args.kwonly.isEmpty()) { + return null; + } + int i = !body.isEmpty() && isDocstring(body.get(0)) ? 1 : 0; + if (body.size() != i + 1 || !(body.get(i) instanceof Return)) { + return null; + } + Expr v = ((Return) body.get(i)).value; + if (!(v instanceof Constant)) { + return null; + } + Constant.Kind ck = ((Constant) v).kind; + return ck == Constant.Kind.TRUE ? "Py.TRUE" : ck == Constant.Kind.FALSE ? "Py.FALSE" : null; + } + private String function(String name, Arguments args, Scope fs, List body, Expr exprBody) { + String removed = removedBody; + removedBody = null; + if (removed != null && body != null) { + body = java.util.Collections.emptyList(); + } + boolean bodyOnly = inlineCalled; + inlineCalled = false; boolean async = nextAsync; nextAsync = false; - boolean generator = body != null && (async || fs.hasYield); + boolean generator = body != null && removed == null && (async || fs.hasYield); GenLowering savedGen = gen; gen = null; if (body != null) { @@ -1680,8 +2721,10 @@ private String function(String name, Arguments args, Scope fs, List body, } String asStatic = staticBody; Layouts.Cls asClass = staticClass; + Layouts.Cls asReceiver = receiverHint; staticBody = null; staticClass = null; + receiverHint = null; String savedSelfLocal = selfLocal; Layouts.Cls savedSelfCls = selfCls; String savedSelfTyped = selfTyped; @@ -1694,20 +2737,28 @@ private String function(String name, Arguments args, Scope fs, List body, selfTyped = null; StringBuilder sig = new StringBuilder(); List names = args.names(); - sig.append("new PyFunction(").append(javaString(name)).append(", new String[] {"); + // The parameter names are a constant: a nested def or lambda is a new PyFunction + // every time it is evaluated, and the table was a new array each time with it. + // One table for every function of the module with these names, and + // made by one call: an array literal is a store an element. + StringBuilder joined = new StringBuilder(); for (int i = 0; i < names.size(); i++) { - sig.append(i == 0 ? "" : ", ").append(javaString(names.get(i))); + joined.append(i == 0 ? "" : "\n").append(names.get(i)); + } + String pn = paramTables.get(joined.toString()); + if (pn == null) { + pn = "PN" + paramNames++; + paramTables.put(joined.toString(), pn); + fields.append(" private static final String[] ").append(pn).append(" = ") + .append(names.isEmpty() ? "Py.NO_NAMES" : "Py.names(" + javaString(joined.toString()) + ")") + .append(";\n"); } - sig.append("}, ").append(args.positional.size()).append(", ").append(args.vararg != null).append(", ") + sig.append("new PyFunction(").append(javaString(name)).append(", ").append(pn).append(", ").append(args.positional.size()).append(", ").append(args.vararg != null).append(", ") .append(args.kwonly.size()).append(", ").append(args.kwarg != null).append(", "); if (args.defaults.isEmpty()) { sig.append("Py.NO_ARGS, "); } else { - sig.append("new Object[] {"); - for (int i = 0; i < args.defaults.size(); i++) { - sig.append(i == 0 ? "" : ", ").append(expr(args.defaults.get(i))); - } - sig.append("}, "); + sig.append(defaultArray(args.defaults)).append(", "); } boolean anyKwDefault = false; for (Expr e : args.kwDefaults) { @@ -1716,12 +2767,7 @@ private String function(String name, Arguments args, Scope fs, List body, if (!anyKwDefault) { sig.append("null, "); } else { - sig.append("new Object[] {"); - for (int i = 0; i < args.kwDefaults.size(); i++) { - Expr e = args.kwDefaults.get(i); - sig.append(i == 0 ? "" : ", ").append(e == null ? "null" : expr(e)); - } - sig.append("}, "); + sig.append(defaultArray(args.kwDefaults)).append(", "); } Frame savedFrame = frame; @@ -1741,15 +2787,16 @@ private String function(String name, Arguments args, Scope fs, List body, Set savedRecycled = recycled; recycled = body != null ? ListRecycling.find(body, names, fs) : java.util.Collections.emptySet(); List pnames = args.names(); - boolean directParams = args.vararg == null && args.kwarg == null && args.kwonly.isEmpty() && pnames.size() <= 6; + boolean directParams = args.vararg == null && args.kwarg == null && (args.kwonly.isEmpty() || asStatic != null) + && pnames.size() <= 14; if (asStatic != null && asClass != null && directParams && !pnames.isEmpty() && !fs.assigned.contains(pnames.get(0)) && !fs.cells.contains(pnames.get(0))) { selfLocal = localVar(fs, pnames.get(0)); selfCls = asClass; selfTyped = "k" + frame.id; } - if (body != null && !generator && !layouts.fieldOwners.isEmpty()) { - for (Map.Entry e : ShadowTypes.of(body, layouts).entrySet()) { + if (body != null && !generator && !allOwners.isEmpty()) { + for (Map.Entry e : ShadowTypes.of(body, allOwners).entrySet()) { String n = e.getKey(); if (fs.resolve(n) != Scope.Binding.LOCAL || fs.cells.contains(n)) { continue; @@ -1758,8 +2805,13 @@ private String function(String name, Arguments args, Scope fs, List body, if (v.equals(selfLocal)) { continue; } + // The receiver of a method is its own class: counting which + // class declares the fields it reads picks an unrelated class + // that happens to share their names. + Layouts.Cls k = asReceiver != null && !pnames.isEmpty() && n.equals(pnames.get(0)) + && !fs.assigned.contains(n) ? asReceiver : e.getValue(); shadowVar.put(v, "h" + frame.id + "_" + mangle(n)); - shadowCls.put(v, e.getValue()); + shadowCls.put(v, k); } } StringBuilder b = new StringBuilder(); @@ -1769,10 +2821,15 @@ private String function(String name, Arguments args, Scope fs, List body, indent(b, ind); b.append("return ").append(e).append(";\n"); } else if (generator) { - gen = new GenLowering(this, file, fs); + gen = new GenLowering(genTarget(), file, fs); gen.asyncGen = async && fs.yields; + gen.plain = !async; b.append(resolveRegions(gen.step(body))); } else { + if (removed != null) { + indent(b, ind); + b.append("if (true) throw Py.runtimeError(").append(javaString(removed)).append(");\n"); + } block(body, b, ind); indent(b, ind); b.append("return Py.NONE;\n"); @@ -1784,7 +2841,9 @@ private String function(String name, Arguments args, Scope fs, List body, // Enter the typed version (TypedEmit) when the arguments fit. List locals = new ArrayList(); for (String n : names) { - locals.add(localVar(fs, n)); + // A parameter only comprehensions capture is a cell here + // and a plain local in the typed version. + locals.add(fs.cells.contains(n) ? cellVar(fs, n) + "[0]" : localVar(fs, n)); } StringBuilder g = new StringBuilder(); for (String line : typedEmit.entry(tf, locals).split("\n")) { @@ -1796,9 +2855,12 @@ private String function(String name, Arguments args, Scope fs, List body, } String a = "a" + frame.id; // Only positional parameters, at most six: the body takes them as - // Java parameters (PyFunction.Body0..Body6), so a call allocates no + // Java parameters (PyFunction.Body0..Body14), so a call allocates no // argument array. - boolean direct = args.vararg == null && args.kwarg == null && args.kwonly.isEmpty() && names.size() <= 6; + // A static entry takes keyword-only parameters as Java ones too; the + // function's own body then adapts the bound array to it. + boolean direct = args.vararg == null && args.kwarg == null && (args.kwonly.isEmpty() || asStatic != null) + && names.size() <= 14; StringBuilder pro = new StringBuilder(); Set declared = new LinkedHashSet(); for (int i = 0; i < names.size(); i++) { @@ -1832,7 +2894,7 @@ private String function(String name, Arguments args, Scope fs, List body, .append(selfLocal).append(" : null;\n"); } for (Map.Entry e : shadowVar.entrySet()) { - String k = shadowCls.get(e.getKey()).javaName; + String k = shadowCls.get(e.getKey()).ref; indent(pro, ind); // Every local is declared above (parameters with their value, // the rest null), so testing it here is right for both. @@ -1870,6 +2932,18 @@ private String function(String name, Arguments args, Scope fs, List body, g.append("};\n"); pro.setLength(0); b.setLength(0); + Infer.Fn tf = typedEmit != null && !async ? typedEmit.fnFor(fs) : null; + if (tf != null && direct) { + // Make the typed generator (TypedEmit) when the arguments fit. + List given = new ArrayList(); + for (int i = 0; i < names.size(); i++) { + given.add(param(a, i, true)); + } + for (String line : typedEmit.entry(tf, given).split("\n")) { + indent(b, ind); + b.append(line).append('\n'); + } + } b.append(g); } else if (temps != null) { indent(pro, ind); @@ -1886,7 +2960,7 @@ private String function(String name, Arguments args, Scope fs, List body, handlers.clear(); handlers.addAll(savedHandlers); - StringBuilder r = new StringBuilder(sig); + StringBuilder r = new StringBuilder(bodyOnly ? "" : sig); r.append('('); StringBuilder plist = new StringBuilder(); StringBuilder alist = new StringBuilder(); @@ -1899,18 +2973,31 @@ private String function(String name, Arguments args, Scope fs, List body, plist.append("Object[] ").append(a); alist.append(a); } - r.append(plist); if (asStatic != null && direct) { // A compiled method: the body is a static method the class // layout's dispatch calls directly (see Layouts). fields.append(" static Object ").append(asStatic).append("(").append(plist).append(") {\n") .append(pro).append(b).append(" }\n"); + r.append(plist); r.append(") -> ").append(asStatic).append("(").append(alist).append("))"); } else { - r.append(") -> {\n").append(pro).append(b); + // An anonymous class rather than a lambda: ParparVM makes a + // lambda a class whose run() only forwards to a synthetic + // method, so every call of the function paid two frames. + r.setLength(r.length() - 1); + r.append("new PyFunction.Body").append(direct ? String.valueOf(names.size()) : "") + .append("() { public Object run(").append(plist).append(") {\n").append(pro).append(b); indent(r, ind - 1); - r.append("})"); + r.append("}})"); + } + if (bodyOnly) { + // Without the PyFunction( this opened, its closing parenthesis goes too. + return r.substring(0, r.length() - 1); } + // The field a module-level fused function is kept in. The assignment + // is wrapped around the finished expression: its type is Object, so + // nothing can be chained after it. + String defField = null; Expr ret = generator ? null : pureReturn(args, names, body, exprBody); if (ret != null) { String pure = pureVariant(names, ret); @@ -1932,7 +3019,7 @@ private String function(String name, Arguments args, Scope fs, List body, .append(") -> ").append(method).append("(").append(lcall).append("))"); if (module) { fields.append(" private static Object DEF_").append(mangle(name)).append(";\n"); - r.insert(0, "(DEF_" + mangle(name) + " = ").append(")"); + defField = "DEF_" + mangle(name); } } } @@ -1941,14 +3028,58 @@ private String function(String name, Arguments args, Scope fs, List body, if (!q.equals(name)) { r.append(".qual(").append(javaString(q)).append(")"); } + if (args.kwarg != null && kwForwardOnly(args.kwarg.name, body != null ? body : exprBody)) { + r.append(".kwShared()"); + } + r.append(".inModule(G[0])"); + String k = constantBool(args, body); + if (k != null) { + r.append(".constant(").append(k).append(")"); + } + if (args.positionalOnly > 0) { + r.append(".positionalOnly(").append(args.positionalOnly).append(")"); + } if (generator) { // co_flags' CO_GENERATOR, CO_COROUTINE or CO_ASYNC_GENERATOR, // which inspect reads. r.append(".kind(").append(async && fs.yields ? 0x200 : async ? 0x80 : 0x20).append(")"); } + if (defField != null) { + r.insert(0, "(" + defField + " = ").append(")"); + } return r.toString(); } + /// Whether the only uses of `**name` in a body pass it on as `**name` in a + /// call: never read, stored, deleted or captured otherwise, and nothing + /// in the body can reach a frame's locals. A call without keywords can + /// then hand such a function one shared empty dict (PyFunction.kwShared). + private static boolean kwForwardOnly(String name, Object body) { + boolean[] ok = {true}; + kwScan(name, body, ok); + return ok[0]; + } + + private static void kwScan(String name, Object o, boolean[] ok) { + if (!ok[0]) { + return; + } + if (o instanceof Keyword) { + Keyword k = (Keyword) o; + if (k.arg == null && k.value instanceof Name && name.equals(((Name) k.value).id)) { + return; + } + } else if (o instanceof Name) { + String id = ((Name) o).id; + if (name.equals(id) || "locals".equals(id) || "vars".equals(id) || "exec".equals(id) + || "eval".equals(id)) { + ok[0] = false; + return; + } + } + Infer.children(o, x -> kwScan(name, x, ok)); + } + /// Parameter `i` of a function body: its own Java parameter, or an /// element of the argument array. private static String param(String a, int i, boolean direct) { @@ -1957,6 +3088,93 @@ private static String param(String a, int i, boolean direct) { // ---- expressions ----------------------------------------------------- + /// `"a %s b %d" % (x, y)`: a literal format of bare `%s`, `%d`, `%i` + /// and `%%`, and a literal tuple of one to four values with as many + /// conversions, is split here and formatted by `Py.pct` without + /// a tuple or a parse. Anything else -- a width, a mapping key, a + /// starred value, a count that does not match -- keeps `Py.mod`. Answers + /// the call up to its first value: the caller appends ", value" for each + /// element of the tuple and the closing parenthesis. + private String percentLiteral(BinOp b) { + if (!"%".equals(b.op) || !(b.left instanceof Constant) || !(b.right instanceof TupleExpr)) { + return null; + } + List vals = ((TupleExpr) b.right).elts; + for (Expr v : vals) { + if (v instanceof Starred) { + return null; + } + } + return percentHead((Constant) b.left, vals.size()); + } + + /// [#percentLiteral] of format `f` and `count` values, for a caller that + /// knows how many values there are: TypedEmit, for `"<%s>" % x` with `x` + /// typed as a str or a number, which is one value and never a tuple to + /// spread. Null when the format is not one `Py.pct` takes. + String percentHead(Constant f, int count) { + if (count > 4) { + return null; + } + List lits = percentParts(f, count); + if (lits == null) { + return null; + } + String convs = lits.remove(lits.size() - 1); + StringBuilder arr = new StringBuilder("new String[] {"); + for (int i = 0; i < lits.size(); i++) { + arr.append(i == 0 ? "" : ", ").append(javaString(lits.get(i))); + } + String l = hoist("String[]", arr.append("}").toString()); + return "Py.pct(" + l + ", " + javaString(convs); + } + + /// The literal format `f` of bare `%s`, `%d`, `%i` and `%%` split for + /// `count` values: the text around the conversions (one more than + /// there are values), then the conversion letters as one last element. + /// Null for any other format or a count that does not match. + List percentParts(Constant f, int count) { + if (f.kind != Constant.Kind.STR || count < 1) { + return null; + } + List lits = new ArrayList<>(); + StringBuilder convs = new StringBuilder(); + StringBuilder lit = new StringBuilder(); + String t = f.text; + for (int i = 0; i < t.length(); i++) { + char c = t.charAt(i); + if (c != '%') { + lit.append(c); + continue; + } + i++; + if (i >= t.length()) { + return null; + } + char k = t.charAt(i); + if (k == '%') { + lit.append('%'); + } else if (k == 's' || k == 'd' || k == 'i') { + convs.append(k); + lits.add(lit.toString()); + lit.setLength(0); + } else { + return null; + } + } + lits.add(lit.toString()); + if (convs.length() != count) { + return null; + } + lits.add(convs.toString()); + return lits; + } + + /// [#percentLiteral] for TypedEmit, which appends the values itself. + String percentHead(BinOp b) { + return percentLiteral(b); + } + private String temp() { return "t" + frame.id + "_" + (frame.temps++); } @@ -1997,15 +3215,65 @@ private String intConst(long l) { private String longOf(String v, String t) { Long c = constLongs.get(v); - return c != null ? c.longValue() + "L" : "((Long) " + t + ").longValue()"; + // Through Object: a reused name (operandTemps) may be declared as some + // other type, a PyBytes constant say, and javac rejects that cast. + return c != null ? c.longValue() + "L" : "((Long) (Object) " + t + ").longValue()"; } /// `(t = v) instanceof Long`, or true for an int constant (still /// assigned, for the slow path). private String isLong(String v, String t) { + if (t.equals(v)) { + // No temporary (see operandTemps): the name is read where it is used. + return constLongs.containsKey(v) ? "true" : "((Object) " + v + ") instanceof Long"; + } return constLongs.containsKey(v) ? "(" + t + " = " + v + ") != null" : "(" + t + " = " + v + ") instanceof Long"; } + private static final java.util.regex.Pattern PLAIN_NAME = java.util.regex.Pattern.compile("[A-Za-z_$][A-Za-z0-9_$]*"); + + /// The operands themselves when BOTH are plain Java names (a local, a field + /// of the generator, a hoisted constant), else two fresh temporaries. A + /// temporary exists so each operand is evaluated once and in order; a name + /// has no effect to repeat and nothing can change it between the two reads + /// when the other operand is a name too. Without one the int fast path is + /// `v instanceof Long` rather than `(t = v) instanceof Long`, which the + /// ParparVM translator compiles to C expressions instead of operand-stack + /// DUP/ASTORE traffic -- that was a third of a generator's step(). + /// A Java string literal as the emitter writes a str constant. + private static final java.util.regex.Pattern STR_LITERAL = + java.util.regex.Pattern.compile("\"(?:[^\"\\\\]|\\\\.)*\""); + + private String[] operandTemps(String l, String r) { + if (PLAIN_NAME.matcher(l).matches() && PLAIN_NAME.matcher(r).matches()) { + return new String[] {l, r}; + } + return new String[] {temp(), temp()}; + } + + /// The head of one comprehension loop. A list is walked by index, re-reading its + /// length every step as its own iterator does, so the comprehension allocates no + /// iterator for it; anything else goes through `Py.iter`. + private void compLoopHead(StringBuilder b, int depth, String src, String it, String x) { + String sq = fresh("sq"); + String ls = fresh("ls"); + String li = fresh("li"); + indent(b, depth); + b.append("final Object ").append(sq).append(" = ").append(src).append(";\n"); + indent(b, depth); + b.append("final PyList ").append(ls).append(" = ").append(sq).append(" instanceof PyList ? (PyList) ") + .append(sq).append(" : null;\n"); + indent(b, depth); + b.append("final PyObject ").append(it).append(" = ").append(ls).append(" != null ? null : Py.iter(") + .append(sq).append(");\n"); + indent(b, depth); + b.append("int ").append(li).append(" = 0;\n"); + indent(b, depth); + b.append("for (Object ").append(x).append("; (").append(x).append(" = ").append(it).append(" != null ? ") + .append(it).append(".next() : ").append(li).append(" < ").append(ls).append(".size() ? ") + .append(ls).append(".get(").append(li).append("++) : null) != null;) {\n"); + } + private String ltemp() { return "j" + frame.id + "_" + (frame.ltemps++); } @@ -2050,8 +3318,20 @@ private String inlineCmp(String op, String l, String r) { default: return null; } - String t = temp(); - String u = temp(); + if ("==".equals(op) || "!=".equals(op)) { + // Against a str literal the int test can never pass: compare as + // strings, the literal having no effects to keep in order. + String neg = "==".equals(op) ? "" : "!"; + if (STR_LITERAL.matcher(r).matches()) { + return "(" + neg + "Py.eqStr(" + l + ", " + r + "))"; + } + if (STR_LITERAL.matcher(l).matches()) { + return "(" + neg + "Py.eqStr(" + r + ", " + l + "))"; + } + } + String[] tu = operandTemps(l, r); + String t = tu[0]; + String u = tu[1]; String close = slow.startsWith("Py.isTrue") ? "))" : ")"; return "((" + isLong(l, t) + " & " + isLong(r, u) + ") ? " + longOf(l, t) + " " + jop + " " + longOf(r, u) + " : " + slow + t + ", " + u + close + ")"; @@ -2063,8 +3343,13 @@ private String inlineArith(String op, String l, String r, boolean inPlace) { if (!"+".equals(op) && !"-".equals(op)) { return null; } - String t = temp(); - String u = temp(); + if (STR_LITERAL.matcher(l).matches() || STR_LITERAL.matcher(r).matches()) { + // A str literal is never an int: no int test, no temporaries. + return "Py." + (inPlace ? "i" : "") + BIN.get(op) + "(" + l + ", " + r + ")"; + } + String[] tu = operandTemps(l, r); + String t = tu[0]; + String u = tu[1]; String x = ltemp(); String y = ltemp(); String z = ltemp(); @@ -2079,6 +3364,9 @@ private String inlineArith(String op, String l, String r, boolean inPlace) { /// A Java boolean expression for a Python condition. String cond(Expr e) { + if (e instanceof Call && ((Call) e).func instanceof Name && "$ismiss".equals(((Name) ((Call) e).func).id)) { + return missTest((Call) e); + } if (e instanceof Constant && ((Constant) e).kind == Constant.Kind.TRUE) { // Not the literal: javac would then reject the code after a // `while True` it cannot see a break out of. @@ -2100,6 +3388,10 @@ String cond(Expr e) { } if (e instanceof Compare) { Compare c = (Compare) e; + String lit = inLiteral(c); + if (lit != null) { + return lit; + } StringBuilder sb = new StringBuilder("("); String left = expr(c.left); for (int i = 0; i < c.ops.size(); i++) { @@ -2124,7 +3416,52 @@ String cond(Expr e) { return "Py.isTrue(Py.FALSE)"; } } - return truth(expr(e)); + if (e instanceof Call && isinstanceCall((Call) e) && !(((Call) e).args.get(1) instanceof TupleExpr)) { + // As the typed code does: the builtin's answer as a Java boolean, + // with no bool boxed and then tested three ways. + Call c = (Call) e; + return "Py.isinstanceB(" + expr(c.func) + ", " + expr(c.args.get(0)) + ", " + expr(c.args.get(1)) + ")"; + } + String x = expr(e); + if (x.startsWith("Py.isinstanceAny(") && x.endsWith(")")) { + // Answers Py.TRUE or Py.FALSE, which isTrue checks first: the + // inline chain of truth() would only add tests that never hit. + return "Py.isTrue(" + x + ")"; + } + return truth(x); + } + + /// `isinstance(x, t)` with the builtin's name, two plain arguments and no + /// keywords: the call [#cond] answers as a Java boolean. + private boolean isinstanceCall(Call c) { + return c.func instanceof Name && "isinstance".equals(((Name) c.func).id) && c.keywords.isEmpty() + && c.args.size() == 2 && !Infer.hasStarred(c.args) + && sc.resolve("isinstance") == Scope.Binding.BUILTIN; + } + + /// The items of `x in (a, b, ...)` / `x not in (...)` with the tuple + /// written out (two to eight items, none starred), or null. + static List inTuple(Compare c) { + if (c.ops.size() != 1 || !("in".equals(c.ops.get(0)) || "not in".equals(c.ops.get(0))) + || !(c.comparators.get(0) instanceof TupleExpr)) { + return null; + } + List ts = ((TupleExpr) c.comparators.get(0)).elts; + return ts.size() >= 2 && ts.size() <= 8 && !Infer.hasStarred(ts) ? ts : null; + } + + /// [#inTuple] as a Java condition, with no tuple built (`Py.inOf`). + private String inLiteral(Compare c) { + List ts = inTuple(c); + if (ts == null) { + return null; + } + StringBuilder r = new StringBuilder("not in".equals(c.ops.get(0)) ? "(!" : "(").append("Py.inOf(") + .append(expr(c.left)); + for (Expr t : ts) { + r.append(", ").append(expr(t)); + } + return r.append("))").toString(); } private String cmpBool(String op, String l, String r) { @@ -2139,6 +3476,10 @@ private String cmpBool(String op, String l, String r) { return "!Py.eqBool(" + l + ", " + r + ")"; case "<": return "Py.ltBool(" + l + ", " + r + ")"; + case "in": + return "Py.inBool(" + l + ", " + r + ")"; + case "not in": + return "!Py.inBool(" + l + ", " + r + ")"; case "is": return "(" + l + " == " + r + ")"; case "is not": @@ -2157,6 +3498,14 @@ String expr(Expr e) { } if (e instanceof BinOp) { BinOp b = (BinOp) e; + String pf = percentLiteral(b); + if (pf != null) { + StringBuilder sb = new StringBuilder(pf); + for (Expr v : ((TupleExpr) b.right).elts) { + sb.append(", ").append(expr(v)); + } + return sb.append(')').toString(); + } String f = fused(e); if (f != null) { return f; @@ -2210,7 +3559,7 @@ String expr(Expr e) { } if (e instanceof Compare) { Compare c = (Compare) e; - if (c.ops.size() == 1 && boolValued(e)) { + if (c.ops.size() == 1 && (boolValued(e) || inTuple(c) != null)) { return "(" + cond(e) + " ? Py.TRUE : Py.FALSE)"; } if (c.ops.size() == 1) { @@ -2251,12 +3600,16 @@ String expr(Expr e) { if (e instanceof Attribute) { Attribute a = (Attribute) e; if (FRAME_HOOKS.contains(a.attr) && a.value instanceof Name && "sys".equals(((Name) a.value).id)) { - throw dynamicCode(a, "sys." + a.attr); + return dynamicCodeAtRuntime(a, "sys." + a.attr); } - if (layouts.fieldOwners.containsKey(a.attr)) { + if (allOwners.containsKey(a.attr)) { return fieldGet(a.attr, expr(a.value), site(a.attr)); } - return site(a.attr) + ".get(" + expr(a.value) + ")"; + String recv = expr(a.value); + String raw = rawLocal(recv); + // A class constant is no field: nothing stores it. + String folded = raw != null ? classConstantGet(a.attr, raw, site(a.attr), recv) : null; + return folded != null ? folded : site(a.attr) + ".get(" + recv + ")"; } if (e instanceof Subscript) { Subscript s = (Subscript) e; @@ -2269,7 +3622,11 @@ String expr(Expr e) { if (ci != null) { return "Py.getitem(" + expr(s.value) + ", " + ci + ")"; } - return "Py.getitem(" + expr(s.value) + ", " + expr(s.index) + ")"; + String key = expr(s.index); + if (isStrLiteral(key)) { + return keyRead(expr(s.value), key); + } + return "Py.getitem(" + expr(s.value) + ", " + key + ")"; } if (e instanceof Slice) { Slice s = (Slice) e; @@ -2286,10 +3643,14 @@ String expr(Expr e) { if (elts.isEmpty()) { return "PyTuple.EMPTY"; } - return display("new PyTuple(", elts, ")", "Py.tuple("); + String d = display("new PyTuple(", elts, ")", "Py.tuple("); + return foldable(elts) ? hoist("PyTuple", d) : d; } if (e instanceof SetExpr) { List elts = ((SetExpr) e).elts; + if (((SetExpr) e).frozenConstant && foldable(elts)) { + return hoist("PySet", display("PySet.frozenConstants(", elts, ")", "PySet.frozenConstants(")); + } if (elts.size() >= 3 && allConstant(elts)) { return display("PySet.ofConstants(", elts, ")", "PySet.ofConstants("); } @@ -2301,7 +3662,18 @@ String expr(Expr e) { for (Expr k : d.keys) { spread |= k == null; } - StringBuilder sb = new StringBuilder(spread ? "Py.dictSpread(" : "Py.dict("); + if (!spread && d.keys.size() * 2 > BIG_LITERAL && allConstant(d.keys) && allConstant(d.values)) { + List flat = new ArrayList(d.keys.size() * 2); + for (int i = 0; i < d.keys.size(); i++) { + flat.add(d.keys.get(i)); + flat.add(d.values.get(i)); + } + return "Py.dict(" + bigLiteral(flat) + ")"; + } + if (!spread) { + return dictLiteral(d.keys, d.values); + } + StringBuilder sb = new StringBuilder("Py.dictSpread("); for (int i = 0; i < d.keys.size(); i++) { Expr k = d.keys.get(i); sb.append(i == 0 ? "" : ", ").append(k == null ? "null" : expr(k)).append(", ") @@ -2341,11 +3713,46 @@ private String exprOrNone(Expr e) { } /// A list/tuple/set display; one with `*x` items goes through Py.spread. + /// A literal of more constants than this is filled by helper methods of + /// its own: written inline, a table such as pdfminer's 4,500-entry glyph + /// list would exceed the JVM's 64 KB limit on one method's bytecode. + private static final int BIG_LITERAL = 512; + private static final int BIG_LITERAL_CHUNK = 256; + private int bigLiterals; + + /// Emits static methods that build the array of `elts` in chunks and + /// answers a call to the one that returns it. Only constants qualify, + /// so evaluating them outside the current scope changes nothing. + private String bigLiteral(List elts) { + String name = "BIG" + bigLiterals++; + int chunks = (elts.size() + BIG_LITERAL_CHUNK - 1) / BIG_LITERAL_CHUNK; + StringBuilder m = new StringBuilder(); + m.append(" private static Object[] ").append(name).append("() {\n Object[] a = new Object[") + .append(elts.size()).append("];\n"); + for (int c = 0; c < chunks; c++) { + m.append(" ").append(name).append('_').append(c).append("(a);\n"); + } + m.append(" return a;\n }\n"); + for (int c = 0; c < chunks; c++) { + m.append(" private static void ").append(name).append('_').append(c).append("(Object[] a) {\n"); + int end = Math.min(elts.size(), (c + 1) * BIG_LITERAL_CHUNK); + for (int i = c * BIG_LITERAL_CHUNK; i < end; i++) { + m.append(" a[").append(i).append("] = ").append(expr(elts.get(i))).append(";\n"); + } + m.append(" }\n"); + } + fields.append(m); + return name + "()"; + } + private String display(String open, List elts, String close, String varargsOpen) { boolean star = false; for (Expr x : elts) { star |= x instanceof Starred; } + if (!star && elts.size() > BIG_LITERAL && allConstant(elts)) { + return varargsOpen + bigLiteral(elts) + ")"; + } if (!star) { StringBuilder sb = new StringBuilder(varargsOpen); for (int i = 0; i < elts.size(); i++) { @@ -2395,6 +3802,10 @@ private String joined(JoinedStr j) { if (parts.size() == 1) { return parts.get(0); } + String built = Emitter.stringBuilderChain(parts); + if (built != null) { + return built; + } StringBuilder sb = new StringBuilder("Py.concat("); for (int i = 0; i < parts.size(); i++) { sb.append(i == 0 ? "" : ", ").append(parts.get(i)); @@ -2402,12 +3813,30 @@ private String joined(JoinedStr j) { return sb.append(")").toString(); } + /// An f-string of string literals and `Py.format` pieces as one builder + /// chain of Java strings: no varargs array, and each piece goes through + /// [Py#fmt], which hands an exact str back as it is. Null when a part is + /// anything else, which then joins through `Py.concat`. + static String stringBuilderChain(List parts) { + StringBuilder sb = new StringBuilder("new StringBuilder()"); + for (String p : parts) { + if (p.startsWith("\"")) { + sb.append(".append(").append(p).append(')'); + } else if (p.startsWith("Py.format(")) { + sb.append(".append(Py.fmt(").append(p, "Py.format(".length(), p.length()).append(')'); + } else { + return null; + } + } + return sb.append(".toString()").toString(); + } + private static final Set CLASS_FACTORIES = new HashSet(Arrays.asList( "namedtuple", "NamedTuple", "TypedDict", "make_dataclass", "Enum", "IntEnum", "StrEnum", "Flag", "IntFlag")); /// A call of a functional class factory that names its class after the /// caller's module, without an explicit `module=`. - private static boolean isClassFactory(Call c) { + static boolean isClassFactory(Call c) { String n = c.func instanceof Name ? ((Name) c.func).id : c.func instanceof Attribute ? ((Attribute) c.func).attr : null; if (n == null || !CLASS_FACTORIES.contains(n) || c.args.isEmpty()) { @@ -2421,7 +3850,153 @@ private static boolean isClassFactory(Call c) { return true; } + /// The hidden calls of a miss probe (`Parser.missProbe`); null for any + /// other call. `$` cannot start a Python name, so none is user code. + /// The re-read in `$unmiss` takes the operands directly: they are names + /// and constants, and only the lookup itself may run twice -- when it + /// ran no code the first time (`Py.MISS`). + private String missIntrinsic(Call c) { + if (!(c.func instanceof Name) || !((Name) c.func).id.startsWith("$")) { + return null; + } + String fn = ((Name) c.func).id; + if ("$probe".equals(fn)) { + return probeRead(c.args.get(0), true); + } + if ("$unmiss".equals(fn)) { + String m = expr(c.args.get(0)); + return "(" + m + " == Py.MISS ? " + probeRead(c.args.get(1), false) + " : Py.unmissed(" + m + "))"; + } + if ("$ismiss".equals(fn)) { + return "(" + missTest(c) + " ? Py.TRUE : Py.FALSE)"; + } + return null; + } + + /// `getattr(obj, "name", default)` with a literal name and a default that + /// is a name or constant, so reading it after the lookup changes nothing: + /// the attribute site's miss probe instead of a generic call that walks + /// the class on every miss. + static boolean getattrDefault(Call c) { + return c.func instanceof Name && "getattr".equals(((Name) c.func).id) && c.args.size() == 3 + && c.keywords.isEmpty() && c.args.get(1) instanceof Constant + && ((Constant) c.args.get(1)).kind == Constant.Kind.STR + && (c.args.get(2) instanceof Name || c.args.get(2) instanceof Constant) + && !(c.args.get(0) instanceof Starred); + } + + String missTest(Call c) { + return "Py.isMiss(" + expr(c.args.get(0)) + ", " + expr(c.args.get(1)) + ", " + + ("AttributeError".equals(((Name) c.args.get(1)).id) ? "Py.ATTRIBUTE_ERROR" : "Py.KEY_ERROR") + ")"; + } + + /// `o["k"]` for a str literal: through an inline cache of the dict + /// layout (the runtime's `KeySite`) when the key can name a table entry, else + /// `Py.getitemS`. + String keyRead(String o, String literal) { + String raw = literal.substring(1, literal.length() - 1); + if (raw.indexOf('\\') >= 0 || raw.isEmpty()) { + return "Py.getitemS(" + o + ", " + literal + ")"; + } + return tabled(keySites, "SK", raw) + ".get(" + o + ")"; + } + + private final List keySites = new ArrayList(); + + /// Whether generated code is exactly one Java string literal: a subscript + /// by one (`ch["top"]`) reads a dict through [Py#getitemS]. + static boolean isStrLiteral(String code) { + int n = code.length(); + if (n < 2 || code.charAt(0) != '"' || code.charAt(n - 1) != '"') { + return false; + } + for (int i = 1; i < n - 1; i++) { + char c = code.charAt(i); + if (c == '\\') { + i++; + } else if (c == '"') { + return false; + } + } + return true; + } + + private String probeRead(Expr e, boolean probe) { + if (e instanceof Attribute) { + Attribute a = (Attribute) e; + return site(a.attr) + (probe ? ".getOrMiss(" : ".get(") + expr(a.value) + ")"; + } + Subscript s = (Subscript) e; + return (probe ? "Py.getitemOrMiss(" : "Py.getitem(") + expr(s.value) + ", " + expr(s.index) + ")"; + } + + /// Whether `c` is the desugar's `__cn1_next_or_stop__(next, it)` + /// (analyze.Desugar): a reserved name, called directly. + static boolean nextOrStop(Call c) { + return c.func instanceof Name && "__cn1_next_or_stop__".equals(((Name) c.func).id) && c.args.size() == 2 + && c.keywords.isEmpty() && !Infer.hasStarred(c.args); + } + private String call(Call c) { + if (nextOrStop(c)) { + return "Builtins.nextOrStop(" + expr(c.args.get(0)) + ", " + expr(c.args.get(1)) + ")"; + } + String miss = missIntrinsic(c); + if (miss != null) { + return miss; + } + if (!inCast && castCall(c)) { + // `cast(T, v)`: when the callee is typing's, v alone; T is a plain + // type expression, so skipping it is not observable. Anything + // else bound to the name is called as written. + String f = temp(); + inCast = true; + try { + return "((" + f + " = " + expr(c.func) + ") == StdModules.CAST ? " + expr(c.args.get(1)) + + " : Py.call(" + f + ", " + expr(c.args.get(0)) + ", " + expr(c.args.get(1)) + "))"; + } finally { + inCast = false; + } + } + String bound = boundInit(c); + if (bound != null) { + return bound; + } + if (getattrDefault(c) && sc.resolve("getattr") == Scope.Binding.BUILTIN) { + return "Py.orDefault(" + site(((Constant) c.args.get(1)).text) + ".getOrMiss(" + expr(c.args.get(0)) + "), " + + expr(c.args.get(2)) + ")"; + } + if (c.func instanceof Lambda && c.keywords.isEmpty()) { + Lambda l = (Lambda) c.func; + Arguments la = l.args; + boolean starred = false; + for (Expr x : c.args) { + starred |= x instanceof Starred; + } + if (!starred && !l.scope.hasYield && la.vararg == null && la.kwarg == null && la.kwonly.isEmpty() + && la.defaults.isEmpty() && la.positional.size() == c.args.size() && c.args.size() <= 14) { + String inl = inlineLambda(l, c); + if (inl != null) { + return inl; + } + // `(lambda x, y: ...)(a, b)`: the function object is never seen, so the + // body runs as a bare PyFunction.BodyN. A PyFunction a call (its name, + // parameter table, qualname and module) cost three times what CPython + // spends on the whole expression. + StringBuilder r = new StringBuilder("((PyFunction.Body").append(c.args.size()).append(") "); + inlineCalled = true; + r.append(function("", la, l.scope, null, l.body)); + r.append(").run("); + for (int i = 0; i < c.args.size(); i++) { + r.append(i == 0 ? "" : ", ").append(expr(c.args.get(i))); + } + return r.append(')').toString(); + } + } + Comp eager = eagerArgument(c); + if (eager != null) { + eagerGenerators.add(eager); + } if (!inTypeCall && c.func instanceof Name && "type".equals(((Name) c.func).id) && c.args.size() == 3 && c.keywords.isEmpty() && sc.resolve("type") == Scope.Binding.BUILTIN) { // `type(name, bases, ns)` takes __module__ from the caller's @@ -2452,7 +4027,7 @@ private String call(Call c) { // namespace to hand out. throw unsupported(c, "locals() inside a function or class"); } - // A snapshot: the module's globals are fields, not a dict. + // The module's globals are fields; the dict writes through. return "M.globals()"; } } @@ -2467,6 +4042,39 @@ private String call(Call c) { // rebinds `len` later gets its own function. return "Py.len(" + expr(c.func) + ", " + expr(c.args.get(0)) + ")"; } + if (c.func instanceof Name && c.keywords.isEmpty() && !Infer.hasStarred(c.args)) { + String fn = ((Name) c.func).id; + boolean builtin = sc.resolve(fn) == Scope.Binding.BUILTIN; + if (builtin && "isinstance".equals(fn) && c.args.size() == 2 && c.args.get(1) instanceof TupleExpr) { + // `isinstance(x, (A, B))`: the types are checked one by one, + // as the builtin walks the tuple, and no tuple is built for a + // call that is often on a hot path (pdfplumber's resolve_all). + List ts = ((TupleExpr) c.args.get(1)).elts; + if (ts.size() >= 2 && ts.size() <= 8 && !Infer.hasStarred(ts)) { + StringBuilder r = new StringBuilder("Py.isinstanceAny(").append(expr(c.func)).append(", ") + .append(expr(c.args.get(0))); + for (Expr t : ts) { + r.append(", ").append(expr(t)); + } + return r.append(")").toString(); + } + } + if (builtin && "isinstance".equals(fn) && c.args.size() == 2) { + return "Py.isinstance(" + expr(c.func) + ", " + expr(c.args.get(0)) + ", " + expr(c.args.get(1)) + ")"; + } + if (builtin && "next".equals(fn) && (c.args.size() == 1 || c.args.size() == 2)) { + // The iterator's own next, with no argument array and no + // builtin dispatch between them. + return "Py.nextB(" + expr(c.func) + ", " + expr(c.args.get(0)) + + (c.args.size() == 2 ? ", " + expr(c.args.get(1)) : "") + ")"; + } + if (builtin && "ord".equals(fn) && c.args.size() == 1) { + return "Py.ord(" + expr(c.func) + ", " + expr(c.args.get(0)) + ")"; + } + if (builtin && "dict".equals(fn) && c.args.size() == 1) { + return "Py.dict1(" + expr(c.func) + ", " + expr(c.args.get(0)) + ")"; + } + } boolean spread = false; for (Expr a : c.args) { spread |= a instanceof Starred; @@ -2492,7 +4100,10 @@ private String call(Call c) { names.append(i == 0 ? "" : ", ").append(k.arg == null ? "null" : javaString(k.arg)); i++; } - return "Py.callSpread(" + expr(c.func) + ", " + parts + "}, " + kinds + "}, " + names + "})"; + // The kinds and names never change, so they are one static per site. + return "Py.callSpread(" + expr(c.func) + ", " + parts + "}, " + + hoist("int[]", kinds.append("}").toString()) + ", " + + hoist("String[]", names.append("}").toString()) + ")"; } StringBuilder args = new StringBuilder(); for (Expr a : c.args) { @@ -2506,13 +4117,29 @@ private String call(Call c) { kw.append(i == 0 ? "" : ", ").append(javaString(k.arg)); } String w = hoist("String[]", kw.append("}").toString()); + if (c.func instanceof Attribute && !(FRAME_HOOKS.contains(((Attribute) c.func).attr) + && ((Attribute) c.func).value instanceof Name + && "sys".equals(((Name) ((Attribute) c.func).value).id))) { + // A method call: the site puts the receiver in the first slot. + Attribute a = (Attribute) c.func; + int n = c.args.size() + c.keywords.size(); + if (n <= 13) { + // Fixed arity: the receiver and arguments travel as + // parameters, so the call builds no argument array. + return site(a.attr) + ".callKwF(" + expr(a.value) + ", " + w + args + ")"; + } + return site(a.attr) + ".callKw(" + expr(a.value) + ", new Object[] {null" + args + "}, " + w + ")"; + } + if (c.args.size() + c.keywords.size() <= 14) { + return "Py.callKwF(" + expr(c.func) + ", " + w + args + ")"; + } String arr = args.length() == 0 ? "Py.NO_ARGS" : "new Object[] {" + args.substring(2) + "}"; return "Py.callKw(" + expr(c.func) + ", " + arr + ", " + w + ")"; } if (c.func instanceof Attribute) { Attribute fa = (Attribute) c.func; if (FRAME_HOOKS.contains(fa.attr) && fa.value instanceof Name && "sys".equals(((Name) fa.value).id)) { - throw dynamicCode(fa, "sys." + fa.attr); + return dynamicCodeAtRuntime(fa, "sys." + fa.attr); } Attribute a = (Attribute) c.func; int n = c.args.size(); @@ -2523,7 +4150,14 @@ private String call(Call c) { String direct = directCall(a.attr, n, recv, args.toString(), helper, site(a.attr)); return direct != null ? direct : helper + recv + args + ", " + site(a.attr) + ")"; } - if (n <= 6) { + if (n <= 3 && selfLocal != null && selfTyped != null && layouts.fieldOwners.containsKey(a.attr) + && selfLocal.equals(rawLocal(recv)) && selfOwner(a.attr) != null) { + // A field of self holding a callable: read it as a field and + // call it, the site only when it is unset (AttrSite.callF2). + return site(a.attr) + ".callF" + n + "(" + selfTyped + " != null ? " + selfTyped + ".f_" + + mangle(a.attr) + " : null, " + recv + args + ")"; + } + if (n <= 13) { return site(a.attr) + ".call" + n + "(" + recv + args + ")"; } return site(a.attr) + ".callN(" + recv + ", new Object[] {null, " + args.substring(2) + "})"; @@ -2543,16 +4177,77 @@ private String zeroArgSuper(Call c) { Name n = new Name(first); n.line = c.line; n.col = c.col; - return "new PySuper(" + f.enclosingClass.classVar + ", " + load(n) + ")"; + return "new PySuper(" + superClass(f.enclosingClass) + ", " + load(n) + ")"; + } + + /// The variable holding the class `super()` in a method of class scope + /// `cs` names: set once the class statement is emitted, and before that + /// (a typed body, emitted first) the static field of its layout, or + /// null when it has none. + String superClass(Scope cs) { + if (cs.classVar != null) { + return cs.classVar; + } + for (Layouts.Cls k : layouts.classes.values()) { + if (k.def.scope == cs) { //NOPMD CompareObjectsWithEquals - identity is meant + return k.typeVar; + } + } + return null; + } + + /// Generator expressions whose only consumer drains them at once (see `eagerArgument`), so + /// they are built as a list instead of a suspended generator. Keyed by identity. + private final Set eagerGenerators = + java.util.Collections.newSetFromMap(new java.util.IdentityHashMap()); + + /// The generator expression a call drains completely before it returns, or null. + /// + /// `"sep".join(g)`, and `list`, `tuple`, `sorted`, `set` and `frozenset` while they are the + /// builtins: each materializes its argument before using any of it (CPython's join turns a + /// generator into a list first), so building that list directly yields the same values in + /// the same order, with the same exceptions, and skips a suspend and resume per item. Not + /// `sum`, `min`, `max`, `any` or `all`: those run in constant space, or stop early. + Comp eagerArgument(Call c) { + if (c.args.size() != 1 || !c.keywords.isEmpty() || !(c.args.get(0) instanceof Comp)) { + return null; + } + Comp g = (Comp) c.args.get(0); + if (g.kind != Comp.Kind.GENERATOR || Linearize.isAsync(g) || Linearize.awaited(g)) { + return null; + } + for (Comprehension q : g.generators) { + if (q.isAsync) { + return null; + } + } + if (c.func instanceof Attribute) { + Attribute f = (Attribute) c.func; + return "join".equals(f.attr) && f.value instanceof Constant + && ((Constant) f.value).kind == Constant.Kind.STR ? g : null; + } + if (c.func instanceof Name) { + String fn = ((Name) c.func).id; + boolean drains = "list".equals(fn) || "tuple".equals(fn) || "sorted".equals(fn) + || "set".equals(fn) || "frozenset".equals(fn); + return drains && sc.resolve(fn) == Scope.Binding.BUILTIN ? g : null; + } + return null; } private String comprehension(Comp c) { - if (c.kind == Comp.Kind.GENERATOR || Linearize.awaited(c)) { + if ((c.kind == Comp.Kind.GENERATOR && !eagerGenerators.contains(c)) || Linearize.awaited(c)) { return generatorExpression(c); } + if (helperShape(c.scope)) { + // An eager generator expression too: it is drained into a list + // here. What it reads stays a cell ([#uncell] does not count it), + // and the method takes the cell. + return helperComprehension(c); + } Frame savedFrame = frame; Scope savedScope = sc; - String first = expr(c.generators.get(0).iter); + String first = loopSource(c.generators.get(0).iter, c.generators.get(0).target); Scope cs = c.scope; frame = new Frame(id(cs), cs); sc = cs; @@ -2568,12 +4263,7 @@ private String comprehension(Comp c) { } String it = fresh("i"); String x = fresh("x"); - indent(b, depth); - b.append("final PyObject ").append(it).append(" = Py.iter(").append(i == 0 ? a + "[0]" : expr(g.iter)) - .append(");\n"); - indent(b, depth); - b.append("for (Object ").append(x).append("; (").append(x).append(" = ").append(it) - .append(".next()) != null;) {\n"); + compLoopHead(b, depth, i == 0 ? a : loopSource(g.iter, g.target), it, x); depth++; store(g.target, x, b, depth); for (Expr cond : g.ifs) { @@ -2633,16 +4323,240 @@ private String comprehension(Comp c) { frame = savedFrame; sc = savedScope; StringBuilder out = new StringBuilder(); - out.append("((PyFunction.Body) (Object[] ").append(a).append(") -> {\n").append(pro).append(b); + // One parameter, the first iterable: a Body1, so the call builds no + // argument array. + out.append("((PyFunction.Body1) (Object ").append(a).append(") -> {\n").append(pro).append(b); indent(out, ind); - // Generator expressions are evaluated eagerly for now: an iterator - // over the materialised list. - out.append("return ").append(c.kind == Comp.Kind.GENERATOR ? "Py.iter(" + r + ")" : r).append(";\n"); + // A generator expression gets here only for a consumer that drains it (eagerArgument), + // which is handed the list itself. + out.append("return ").append(r).append(";\n"); indent(out, ind - 1); - out.append("}).run(new Object[] {").append(first).append("})"); + out.append("}).run(").append(first).append(")"); return out.toString(); } + /// What a comprehension emitted as a method reads for each name it + /// takes from enclosing scopes: the parameter, or its cell's slot. + private Map compParams; + /// The [#helperComprehension] methods written so far. + private final Set emittedComps = new HashSet(); + + /// Whether comprehension scope `cs` is emitted as a static method of the + /// module class, as CPython inlines it (PEP 709): an eager list, set or + /// dict comprehension with no scope inside it and no walrus. Such a + /// call makes no function object and no argument array, and the locals + /// it reads are passed by value, so they need no cells ([#uncell]). + static boolean helperComp(Scope cs) { + return helperShape(cs) && cs.comp.kind != Comp.Kind.GENERATOR; + } + + /// Whether `c` is emitted as a helper method run on the spot: an eager + /// comprehension, or a generator expression a consumer drains at once. + /// Whether generator expression `c` is plain enough to be written as a + /// lazy generator object over values captured when it is made. + static boolean capturable(Comp c) { + return c.kind == Comp.Kind.GENERATOR && helperShape(c.scope); + } + + boolean helperNow(Comp c, Set drained) { + return helperShape(c.scope) && (c.kind != Comp.Kind.GENERATOR || drained.contains(c)); + } + + /// [#helperComp] without the kind: true of a generator expression too. + private static boolean helperShape(Scope cs) { + Comp c = cs == null ? null : cs.comp; + if (c == null || !cs.children.isEmpty() || !cs.nonlocals.isEmpty() + || !cs.globals.isEmpty() || Linearize.awaited(c)) { + return false; + } + for (Comprehension g : c.generators) { + if (g.isAsync) { + return false; + } + } + return true; + } + + /// Drops from each function's cells the names only [#helperComp] + /// comprehensions capture: those read the value they are handed. + static void uncell(Scope s) { + for (Scope c : s.children) { + uncell(c); + } + if (s.kind != Scope.Kind.FUNCTION || s.cells.isEmpty()) { + return; + } + for (String n : new ArrayList(s.cells)) { + boolean onlyHelpers = true; + for (Scope c : s.children) { + if (captures(c, s, n) && !helperComp(c)) { + onlyHelpers = false; + break; + } + } + if (onlyHelpers) { + s.cells.remove(n); + } + } + } + + private static boolean captures(Scope s, Scope owner, String n) { + if ((s.used.contains(n) || s.nonlocals.contains(n)) && s.resolve(n) == Scope.Binding.FREE + && s.owner(n) == owner) { //NOPMD CompareObjectsWithEquals - identity is meant + return true; + } + for (Scope c : s.children) { + if (captures(c, owner, n)) { + return true; + } + } + return false; + } + + /// A [#helperComp] comprehension: its loops become a static method of + /// the module class, called with the first iterable and the value (or, + /// for a name that is a cell anyway, the cell) of every name it reads + /// from enclosing functions. + private String helperComprehension(Comp c) { + String first = loopSource(c.generators.get(0).iter, c.generators.get(0).target); + Scope cs = c.scope; + StringBuilder call = new StringBuilder(); + StringBuilder sig = new StringBuilder(); + Map params = new HashMap(); + String it0 = "a" + id(cs) + "_0"; + sig.append("Object ").append(it0); + call.append(first); + int k = 0; + for (String n : cs.used) { + if (cs.resolve(n) != Scope.Binding.FREE) { + continue; + } + Scope o = cs.owner(n); + String p = "f" + id(cs) + "_" + k++; + // Inside a typed function's generic expression (genericExpr) the + // local is the typed version's, passed by value: the comprehension + // runs now and binds nothing outside. + String mapped = inlineParams != null && o == inlineScope ? inlineParams.get(n) : null; //NOPMD CompareObjectsWithEquals - identity is meant + if (o != null && !o.cells.contains(n)) { + sig.append(", Object ").append(p); + call.append(", ").append(mapped != null ? mapped : localVar(o, n)); + params.put(n, p); + } else { + sig.append(", Object[] ").append(p); + call.append(", ").append(mapped != null ? "new Object[] {" + mapped + "}" : cellVar(o, n)); + params.put(n, p + "[0]"); + } + } + Frame savedFrame = frame; + Scope savedScope = sc; + Map savedParams = compParams; + GenLowering savedGen = gen; + String savedSelfLocal = selfLocal; + Layouts.Cls savedSelfCls = selfCls; + String savedSelfTyped = selfTyped; + Map savedShadowVar = shadowVar; + Map savedShadowCls = shadowCls; + Set savedRecycled = recycled; + Map savedCarried = carried; + String[] savedLazy = lazyIndex; + boolean savedFast = inRegionFast; + Map savedHoist = hoist; + frame = new Frame(id(cs), cs); + sc = cs; + compParams = params; + gen = null; + selfLocal = null; + selfCls = null; + selfTyped = null; + shadowVar = new HashMap(); + shadowCls = new HashMap(); + recycled = java.util.Collections.emptySet(); + carried = null; + lazyIndex = null; + inRegionFast = false; + hoist = null; + String r = fresh("r"); + StringBuilder b = new StringBuilder(); + int ind = 2; + int depth = ind; + for (int i = 0; i < c.generators.size(); i++) { + Comprehension g = c.generators.get(i); + String it = fresh("i"); + String x = fresh("x"); + compLoopHead(b, depth, i == 0 ? it0 : loopSource(g.iter, g.target), it, x); + depth++; + store(g.target, x, b, depth); + for (Expr cond : g.ifs) { + indent(b, depth); + b.append("if (").append(cond(cond)).append(") {\n"); + depth++; + } + } + indent(b, depth); + String type; + switch (c.kind) { + case DICT: + type = "PyDict"; + b.append(r).append(".setItem(").append(expr(c.elt)).append(", ").append(expr(c.value)) + .append(");\n"); + break; + case SET: + type = "PySet"; + b.append(r).append(".addItem(").append(expr(c.elt)).append(");\n"); + break; + default: + type = "PyList"; + b.append(r).append(".append(").append(expr(c.elt)).append(");\n"); + break; + } + while (depth > ind) { + depth--; + indent(b, depth); + b.append("}\n"); + } + String name = "comp" + id(cs); + if (!emittedComps.add(name)) { + // Emitted already: some expressions are emitted more than once. + b.setLength(0); + } + StringBuilder m = new StringBuilder(); + m.append("\n private static ").append(type).append(' ').append(name).append('(').append(sig).append(") {\n"); + for (String n : cs.assigned) { + if (!cs.isLocal(n)) { + continue; + } + indent(m, ind); + m.append("Object ").append(localVar(cs, n)).append(" = null;\n"); + } + if (frame.temps > 0 || frame.ltemps > 0) { + indent(m, ind); + m.append(tempDecls()).append("\n"); + } + indent(m, ind); + m.append("final ").append(type).append(' ').append(r).append(" = new ").append(type).append("();\n"); + m.append(b); + indent(m, ind); + m.append("return ").append(r).append(";\n }\n"); + if (b.length() > 0) { + fields.append(m); + } + frame = savedFrame; + sc = savedScope; + compParams = savedParams; + gen = savedGen; + selfLocal = savedSelfLocal; + selfCls = savedSelfCls; + selfTyped = savedSelfTyped; + shadowVar = savedShadowVar; + shadowCls = savedShadowCls; + recycled = savedRecycled; + carried = savedCarried; + lazyIndex = savedLazy; + inRegionFast = savedFast; + hoist = savedHoist; + return name + "(" + call + ")"; + } + /// A generator expression: a generator whose body is the loops of the /// comprehension around `yield elt`, lazy as in Python. The first /// iterable is evaluated here, in the enclosing scope, and handed in as @@ -2653,7 +4567,7 @@ private String generatorExpression(Comp c) { GenLowering savedGen = gen; boolean async = Linearize.isAsync(c); boolean genexp = c.kind == Comp.Kind.GENERATOR; - String first = expr(c.generators.get(0).iter); + String first = loopSource(c.generators.get(0).iter, c.generators.get(0).target); Scope cs = c.scope; frame = new Frame(id(cs), cs); sc = cs; @@ -2687,12 +4601,13 @@ private String generatorExpression(Comp c) { if (!genexp) { body.add(new Return(acc).at(c.line, c.col)); } - gen = new GenLowering(this, file, cs); + gen = new GenLowering(genTarget(), file, cs); gen.asyncGen = async && genexp; + gen.plain = !async; String step = resolveRegions(gen.step(body)); String a = "a" + frame.id; StringBuilder r = new StringBuilder(); - r.append("((PyFunction.Body) (Object[] ").append(a).append(") -> {\n"); + r.append("((PyFunction.Body1) (Object ").append(a).append(") -> {\n"); indent(r, 3); if (!genexp) { r.append("return new PyGenerator(\"<").append(c.kind.name().toLowerCase(java.util.Locale.ROOT)) @@ -2707,7 +4622,7 @@ private String generatorExpression(Comp c) { if (!cs.isLocal(n)) { continue; } - String init = ".0".equals(n) ? a + "[0]" : ".r".equals(n) ? empty : null; + String init = ".0".equals(n) ? a : ".r".equals(n) ? empty : null; if (cs.cells.contains(n)) { r.append(" final Object[] ").append(cellVar(cs, n)).append(" = new Object[] {") .append(init == null ? "null" : init).append("};\n"); @@ -2729,7 +4644,7 @@ private String generatorExpression(Comp c) { r.append("};\n"); indent(r, 2); String firstIter = c.generators.get(0).isAsync ? first : "Py.iter(" + first + ")"; - r.append("}).run(new Object[] {").append(firstIter).append("})"); + r.append("}).run(").append(firstIter).append(")"); gen = savedGen; frame = savedFrame; sc = savedScope; @@ -2743,19 +4658,23 @@ private String generatorExpression(Comp c) { // ---- compiled class layouts (see Layouts) ----------------------------- private Layouts layouts = new Layouts(); - /// Whole-program types, when the program is closed (see `Closed`). + /// The typed code of the module; null until it is emitted. private TypedEmit typedEmit; - private boolean closed; + private WholeProgram.Module facts = new WholeProgram.Module(); - /// Whether the program this module belongs to passed `Closed.check`. - public Emitter closed(boolean c) { - closed = c; + /// What the rest of the program does to this module (see + /// `WholeProgram`). Without it the module is taken to be the whole + /// program. + public Emitter facts(WholeProgram.Module f) { + facts = f; return this; } /// The static method name the next `function` call puts its body in. private String staticBody; /// The class of the compiled method `staticBody` names. private Layouts.Cls staticClass; + /// The class of the next compiled function's receiver, if it is a method. + private Layouts.Cls receiverHint; /// In a compiled method whose receiver parameter is never rebound: that /// parameter's Java local, its class, and the local holding it cast to /// that class, or null when it is not an instance of it. The receiver's @@ -2776,9 +4695,33 @@ public Emitter closed(boolean c) { private void registerLayout(Layouts.Cls lc, StringBuilder out, int ind) { indent(out, ind); out.append("if ("); - if (lc.parent != null) { + if (!lc.excBases.isEmpty()) { + // Builtin exception bases: the runtime confirms the bases are + // still the compiled parent (if any) and those builtins. + out.append(lc.typeVar).append(".exceptionBased(").append(lc.parent != null ? parentTypeVar(lc) : "null") + .append(", new String[] {"); + int j = 0; + for (String e : lc.excBases) { + out.append(j++ == 0 ? "" : ", ").append(javaString(e)); + } + out.append("})"); + } else if (lc.builtinOwn) { + out.append(lc.typeVar).append(".builtinBased(").append(TypedEmit.builtinType(lc.builtin)).append(", ") + .append(lc.parent != null ? parentTypeVar(lc) : "null").append(")"); + } else if (lc.extraBases) { + // Bases besides the compiled parent: the runtime confirms they + // come after the compiled chain in the MRO and add nothing an + // instance or a typed operation depends on. + out.append(lc.typeVar).append(".neutralExtraBases(").append(lc.parent != null ? parentTypeVar(lc) : "null") + .append(", new String[] {"); + int j = 0; + for (String f : lc.allFields) { + out.append(j++ == 0 ? "" : ", ").append(javaString(f)); + } + out.append("})"); + } else if (lc.parent != null) { out.append(lc.typeVar).append(".bases.length == 1 && ").append(lc.typeVar).append(".bases[0] == ") - .append(lc.parent.typeVar).append(" && ").append(lc.parent.typeVar).append(".hasLayout()"); + .append(parentTypeVar(lc)).append(" && ").append(parentTypeVar(lc)).append(".hasLayout()"); } else { out.append("true"); } @@ -2794,11 +4737,126 @@ private void registerLayout(Layouts.Cls lc, StringBuilder out, int ind) { for (String f : lc.allFields) { out.append(i++ == 0 ? "" : ", ").append(javaString(f)); } - out.append("});\n"); + out.append("})").append(lc.def.dataclassFrozen ? ".storesThroughSetattr()" : "").append(";\n"); indent(out, ind); out.append("}\n"); } + /// The type variable of `lc`'s base, qualified by its module's class + /// when the base was compiled in another module. + /// Declares and fills the typed static fields of `lc`'s once-bound class + /// attributes (Infer#classStatic): read once from the finished class, + /// whose dict keeps the value for introspection, and from then on read + /// directly, typed, wherever the program names `Cls.attr`. + private void classStatics(Layouts.Cls lc, String k, StringBuilder out, int ind) { + for (String n : new java.util.TreeSet(lc.bodyNames)) { + classStatic(lc, k, n, out, ind); + } + } + + /// After a trailing class attribute store (Layouts#scanTrailing), the + /// fill of the typed static it binds, if it has one. + private void trailingStatic(Assign a, StringBuilder out, int ind) { + if (infer == null || layouts == null) { + return; + } + Attribute t = (Attribute) a.targets.get(0); + for (Layouts.Cls lc : layouts.classes.values()) { + if (lc.def.name.equals(((Name) t.value).id) && Layouts.trailing(lc.def).get(t.attr) == a.value) { //NOPMD CompareObjectsWithEquals - identity is meant + classStatic(lc, typeVarRef(lc), t.attr, out, ind); + return; + } + } + } + + /// Declares the typed static of `lc`'s class attribute `n`, when it has + /// one, and fills it from the class `k` names. + private void classStatic(Layouts.Cls lc, String k, String n, StringBuilder out, int ind) { + Ty t = infer.classStatic(lc, n); + if (t == null) { + return; + } + String f = classStaticName(lc, n); + if (t.k == Ty.K.INT) { + // The two-part int (TypedEmit#dual): a long, and the int + // object replacing it when it is not null (a big int). + fields.append(" static long ").append(f).append("_l;\n static Object ").append(f).append("_b;\n"); + indent(out, ind); + out.append("{ Object cs_v = ").append(k).append(".lookup(").append(javaString(n)).append("); if (cs_v instanceof Long) { ") + .append(f).append("_l = ((Long) cs_v).longValue(); ").append(f).append("_b = null; } else { ") + .append(f).append("_b = cs_v; } }\n"); + return; + } + String jt = TypedEmit.jt(t); + fields.append(" static ").append(jt).append(' ').append(f).append(";\n"); + String got = k + ".lookup(" + javaString(n) + ")"; + String un; + switch (t.k) { + case STR: + un = "Typed.asStr(" + got + ")"; + break; + case FLOAT: + un = "Typed.asFloat(" + got + ")"; + break; + case BOOL: + un = "Typed.asBool(" + got + ")"; + break; + default: + un = "(" + jt + ") " + got; + break; + } + indent(out, ind); + out.append(f).append(" = ").append(un).append(";\n"); + } + + /// The type variable of `k`, read from this module. + String typeVarRef(Layouts.Cls k) { + if (k.home == layouts) { //NOPMD CompareObjectsWithEquals - identity is meant + return k.typeVar; + } + return k.ref.substring(0, k.ref.length() - k.javaName.length() - 1) + "." + k.typeVar; + } + + static String classStaticName(Layouts.Cls k, String attr) { + return "cs_" + k.typeVar + "_" + mangle(attr); + } + + /// The Java expression reading `k`'s typed static for `attr` from this + /// module. + String classStaticRef(Layouts.Cls k, String attr) { + if (k.home == layouts) { //NOPMD CompareObjectsWithEquals - identity is meant + return classStaticName(k, attr); + } + return k.ref.substring(0, k.ref.length() - k.javaName.length() - 1) + "." + classStaticName(k, attr); + } + + private String parentTypeVar(Layouts.Cls lc) { + Layouts.Cls p = lc.parent; + if (p.home == layouts) { //NOPMD CompareObjectsWithEquals - identity is meant + return p.typeVar; + } + return p.ref.substring(0, p.ref.length() - p.javaName.length() - 1) + "." + p.typeVar; + } + + /// The topmost compiled ancestor of `k`, whose module's `LB` declares the + /// virtual methods `k` overrides. + private static Layouts.Cls rootOf(Layouts.Cls k) { + Layouts.Cls r = k; + while (r.parent != null) { + r = r.parent; + } + return r; + } + + private static List dispatchOf(Layouts l) { + List disp = new ArrayList(); + for (String d : l.dispatch) { + int at = d.lastIndexOf('/'); + disp.add(new String[] {d.substring(0, at), d.substring(at + 1)}); + } + return disp; + } + private String layoutCode() { if (layouts.classes.isEmpty()) { return ""; @@ -2820,7 +4878,9 @@ private String layoutCode() { } o.append(" }\n"); for (Layouts.Cls k : layouts.classes.values()) { - String sup = k.parent != null ? k.parent.javaName : "LB"; + Layouts.Cls root = rootOf(k); + boolean foreign = root.home != layouts; //NOPMD CompareObjectsWithEquals - identity is meant + String sup = k.parent == null ? "LB" : k.parent.home == layouts ? k.parent.javaName : k.parent.ref; //NOPMD CompareObjectsWithEquals - identity is meant int base = k.allFields.size() - k.fields.size(); o.append("\n static class ").append(k.javaName).append(" extends ").append(sup).append(" {\n"); for (String f : k.fields) { @@ -2833,7 +4893,7 @@ private String layoutCode() { } o.append("};\n"); o.append(" ").append(k.javaName).append("(PyType t) {\n super(t);\n }\n"); - String pc = typedEmit != null ? typedEmit.plainCtor(k) : null; + String pc = typedEmit != null && !foreign ? typedEmit.plainCtor(k) : null; if (pc != null) { o.append(pc); } @@ -2852,6 +4912,20 @@ private String layoutCode() { .append(t ? typedEmit.fieldGetCase(k, f) : "f_" + mangle(f)).append(";\n"); } o.append(" default:\n return super.getField(i);\n }\n }\n"); + // Every field in one call, for a pass that reads them all (an + // instance __dict__'s refresh): getField is a virtual call and + // a switch per field. + o.append(" @Override\n protected void copyFields(Object[] d) {\n"); + if (base > 0) { + o.append(" super.copyFields(d);\n"); + } + for (int i = 0; i < k.fields.size(); i++) { + String f = k.fields.get(i); + boolean t = typedEmit != null && typedEmit.typedField(k, f) != null; + o.append(" d[").append(base + i).append("] = ") + .append(t ? typedEmit.fieldGetCase(k, f) : "f_" + mangle(f)).append(";\n"); + } + o.append(" }\n"); o.append(" @Override\n protected void setField(int i, Object v) {\n switch (i) {\n"); for (int i = 0; i < k.fields.size(); i++) { String f = k.fields.get(i); @@ -2863,7 +4937,7 @@ private String layoutCode() { o.append(" default:\n super.setField(i, v);\n }\n }\n"); o.append(" @Override\n protected String[] fieldNames() {\n return FN;\n }\n"); } - for (String[] d : disp) { + for (String[] d : foreign ? dispatchOf(root.home) : disp) { Layouts.Cls r = Layouts.resolver(k, d[0]); Layouts.Cls rp = k.parent == null ? null : Layouts.resolver(k.parent, d[0]); if (r == rp) { //NOPMD CompareObjectsWithEquals - identity is meant @@ -2873,7 +4947,7 @@ private String layoutCode() { o.append(" @Override\n Object m_").append(mangle(d[0])).append("(").append(dparams(ar)) .append(") {\n"); FunctionDef f = r == null ? null : r.methods.get(d[0]); - if (f != null && f.args.names().size() - 1 == ar) { + if (f != null && f.args.names().size() - 1 == ar && r.home == layouts) { //NOPMD CompareObjectsWithEquals - identity is meant o.append(" if (cls.patched || extra) {\n return null;\n }\n"); o.append(" return ").append(layouts.staticNames.get(f)).append("(this"); for (int i = 0; i < ar; i++) { @@ -2885,7 +4959,7 @@ private String layoutCode() { } o.append(" }\n"); } - if (typedEmit != null) { + if (typedEmit != null && !foreign) { o.append(typedEmit.layoutMembers(k)); } o.append(" }\n"); @@ -2912,6 +4986,10 @@ private String layoutCode() { /// is of a class that declares it and the field is set, else the site. private String fieldGet(String name, String recv, String site) { String raw = rawLocal(recv); + String folded = raw != null ? classConstantGet(name, raw, site, recv) : null; + if (folded != null) { + return folded; + } Layouts.Cls own = raw != null && raw.equals(selfLocal) ? selfOwner(name) : null; if (own != null) { String f = selfTyped + ".f_" + mangle(name); @@ -2924,31 +5002,195 @@ private String fieldGet(String name, String recv, String site) { // field is read twice, a load, and an unbound local fails every // instanceof and raises from the generic path. StringBuilder sb = new StringBuilder("("); - if (hk != null) { + String tf = hk != null && hk.typed != null ? hk.typed.foreignGet(hk, name, h) : null; + if (tf != null) { + // A typed field is set on every instance of its class. + sb.append(h).append(" != null && ").append(h).append(" == ").append(raw).append(" ? ").append(tf) + .append(" : "); + } else if (hk != null) { String f = h + ".f_" + mangle(name); sb.append(h).append(" == ").append(raw).append(" && ").append(f).append(" != null ? ").append(f) .append(" : "); } - for (Layouts.Cls k : layouts.fieldOwners.get(name)) { - String f = "((" + k.javaName + ") " + raw + ").f_" + mangle(name); - sb.append(raw).append(" instanceof ").append(k.javaName).append(" && ").append(f) + List mine = guardOwners(name); + if (hk == null && mine == null) { + return site + ".get(" + recv + ")"; + } + for (Layouts.Cls k : mine != null ? mine : java.util.Collections.emptyList()) { + String cast = "((" + k.ref + ") " + raw + ")"; + String typedF = k.typed != null ? k.typed.foreignGet(k, name, cast) : null; + if (typedF != null) { + // A typed field is set on every instance of its class. + sb.append(raw).append(" instanceof ").append(k.ref).append(" ? ").append(typedF).append(" : "); + continue; + } + String f = cast + ".f_" + mangle(name); + sb.append(raw).append(" instanceof ").append(k.ref).append(" && ").append(f) .append(" != null ? ").append(f).append(" : "); } return sb.append(site).append(".get(").append(recv).append("))").toString(); } + List owners = guardOwners(name); + if (owners == null) { + return site + ".get(" + recv + ")"; + } String t = temp(); String u = temp(); StringBuilder sb = new StringBuilder("("); String first = "(" + t + " = " + recv + ")"; - for (Layouts.Cls k : layouts.fieldOwners.get(name)) { - sb.append(first).append(" instanceof ").append(k.javaName).append(" && (").append(u).append(" = ((") - .append(k.javaName).append(") ").append(t).append(").f_").append(mangle(name)).append(") != null ? ") + for (Layouts.Cls k : owners) { + String typedF = k.typed != null ? k.typed.foreignGet(k, name, "((" + k.ref + ") " + t + ")") : null; + if (typedF != null) { + sb.append(first).append(" instanceof ").append(k.ref).append(" ? ").append(typedF).append(" : "); + first = t; + continue; + } + sb.append(first).append(" instanceof ").append(k.ref).append(" && (").append(u).append(" = ((") + .append(k.ref).append(") ").append(t).append(").f_").append(mangle(name)).append(") != null ? ") .append(u).append(" : "); first = t; } return sb.append(site).append(".get(").append(t).append("))").toString(); } + /// The classes of the whole program declaring plain field `name`, the + /// ones a read of it on an object of no known class tests for, or null + /// when there are none or too many: past a handful of `instanceof` + /// tests the chain costs more than the site it stands in front of. + /// Classes of other modules are named by their `ref`, as the shadow + /// locals are, so a module reading a field another module's class + /// stores (`tag.name` outside `bs4.element`) reads it directly too. + private List guardOwners(String name) { + List o = allOwners.get(name); + return o == null || o.isEmpty() || o.size() > MAX_FIELD_GUARDS ? null : o; + } + + private static final int MAX_FIELD_GUARDS = 4; + + /// Reads typed code makes of `recv.name` on a value of no known class: + /// name -> the site the guard falls back to (`g_` helpers). + private final Map usedGet = new java.util.TreeMap(); + /// The same for stores (`s_` helpers). + private final Map usedSet = new java.util.TreeMap(); + /// The guarded classes of each `g_`/`s_` helper, as they were when the + /// helper was first asked for: the program's table may shrink later. + private final Map> getGuards = new HashMap>(); + private final Map> setGuards = new HashMap>(); + + /// `recv.name` for typed code holding `recv` as a plain Object: the + /// field guard `fieldGet` puts in front of the site, inline when the + /// receiver is a local, else through a helper evaluating it once. + String guardedGet(String name, String recv) { + String site = site(name); + List owners = guardOwners(name); + if (owners == null) { + return site + ".get(" + recv + ")"; + } + if (!isJavaIdent(recv)) { + usedGet.put(name, site); + if (!getGuards.containsKey(name)) { + getGuards.put(name, new ArrayList(owners)); + } + return "g_" + mangle(name) + "(" + recv + ")"; + } + StringBuilder sb = new StringBuilder("("); + for (Layouts.Cls k : owners) { + String cast = "((" + k.ref + ") " + recv + ")"; + String typedF = k.typed != null ? k.typed.foreignGet(k, name, cast) : null; + if (typedF != null) { + sb.append(recv).append(" instanceof ").append(k.ref).append(" ? ").append(typedF).append(" : "); + continue; + } + String f = cast + ".f_" + mangle(name); + sb.append(recv).append(" instanceof ").append(k.ref).append(" && ").append(f).append(" != null ? ") + .append(f).append(" : "); + } + return sb.append(site).append(".get(").append(recv).append("))").toString(); + } + + /// `o.name = v` for typed code holding `o` as a plain Object: the plain + /// field when `o` is of a class declaring it and the store cannot need + /// the instance dict (`fieldSet`), else the site. Both are evaluated once. + String guardedSet(String name, String o, String v) { + String site = storeSite(name); + List so = setGuards.containsKey(name) ? setGuards.get(name) : setOwners(name); + if (so.isEmpty()) { + return site + ".set(" + o + ", " + v + ");"; + } + usedSet.put(name, site); + setGuards.put(name, so); + return "s_" + mangle(name) + "(" + o + ", " + v + ");"; + } + + private List setOwners(String name) { + List r = new ArrayList(); + List o = guardOwners(name); + if (o != null) { + for (Layouts.Cls k : o) { + if (!k.frozenStores() && (k.typed == null || k.typed.typedField(k, name) == null)) { + r.add(k); + } + } + } + return r; + } + + /// `recv.attr(args)` through the module's `c_` dispatch helper, as the + /// generic code calls it, or null when the module dispatches no such + /// method. `args` is empty or starts with ", ". + String dispatchCall(String attr, int n, String recv, String args) { + if (n > 3 || !layouts.dispatch.contains(attr + "/" + n)) { + return null; + } + usedCall.add(attr + "/" + n); + return "c_" + mangle(attr) + "_" + n + "(" + recv + args + ", " + site(attr) + ")"; + } + + private static boolean isJavaIdent(String s) { + if (s.isEmpty() || !Character.isJavaIdentifierStart(s.charAt(0))) { + return false; + } + for (int i = 1; i < s.length(); i++) { + if (!Character.isJavaIdentifierPart(s.charAt(i))) { + return false; + } + } + return true; + } + + private String guardHelpers() { + StringBuilder o = new StringBuilder(); + for (Map.Entry e : usedGet.entrySet()) { + String m = mangle(e.getKey()); + o.append("\n private static Object g_").append(m).append("(Object o) {\n"); + for (Layouts.Cls k : getGuards.get(e.getKey())) { + String cast = "((" + k.ref + ") o)"; + String typedF = k.typed != null ? k.typed.foreignGet(k, e.getKey(), cast) : null; + if (typedF != null) { + o.append(" if (o instanceof ").append(k.ref).append(") {\n return ").append(typedF) + .append(";\n }\n"); + continue; + } + o.append(" if (o instanceof ").append(k.ref).append(") {\n Object v = ").append(cast) + .append(".f_").append(m).append(";\n if (v != null) {\n return v;\n") + .append(" }\n }\n"); + } + o.append(" return ").append(e.getValue()).append(".get(o);\n }\n"); + } + for (Map.Entry e : usedSet.entrySet()) { + String m = mangle(e.getKey()); + o.append("\n private static void s_").append(m).append("(Object o, Object v) {\n"); + for (Layouts.Cls k : setGuards.get(e.getKey())) { + o.append(" if (o instanceof ").append(k.ref).append(") {\n ").append(k.ref) + .append(" k = (").append(k.ref).append(") o;\n if (k.f_").append(m) + .append(" != null || !k.extra) {\n k.f_").append(m) + .append(" = v;\n return;\n }\n }\n"); + } + o.append(" ").append(e.getValue()).append(".set(o, v);\n }\n"); + } + return o.toString(); + } + private static final java.util.regex.Pattern RAW_LOCAL = java.util.regex.Pattern.compile("\\(?([a-z][A-Za-z0-9_]*) != null \\? \\1 : ul\\(\"[^\"]*\"\\)\\)|[a-z][A-Za-z0-9_]*"); @@ -2962,18 +5204,208 @@ private static String rawLocal(String e) { return m.group(1) != null ? m.group(1) : e; } + /// `K(args, kw=v)` where `K` is a compiled class the whole program + /// resolves (this module's, or another's by import), its `__init__` has + /// a static entry and the arguments bind to its parameters at build + /// time: positionally, by keyword names written in the call, and with + /// constant defaults for the rest. A door in this module evaluates the + /// callee and the arguments in Python's order, then makes the instance + /// and calls the entry with every parameter -- no argument array, no + /// defaults copied, none cleared. Only while the callee is that class + /// and nothing wrote to it since it was built (`PyType.classWritten`), + /// which is what makes its `__init__` and `__new__` the ones bound here; + /// otherwise the door makes the generic call with the same values. A + /// function's `__defaults__` written at run time changes nothing about + /// how its parameters bind (PyFunction.setAttr), so constants stand in. + private String boundInit(Call c) { + if (infer == null || c.args.size() + c.keywords.size() > 14) { + return null; + } + Layouts.Cls k = infer.calledClass(c.func, sc); + Layouts home = k == null ? null : infer.layoutsOf(k); + if (home == null || k.ref == null || Layouts.resolver(k, "__new__") != null || k.builtin != null || k.callConstructed()) { + // A builtin's value is made by its __new__, which newInstance + // does not run. + return null; + } + Layouts.Cls o = Layouts.resolver(k, "__init__"); + FunctionDef init = null; + if (o != null) { + for (Stmt s : o.def.body) { + if (s instanceof FunctionDef && "__init__".equals(((FunctionDef) s).name)) { + init = (FunctionDef) s; + } + } + } + String entry = init == null ? null : home.staticNames.get(init); + if (entry == null) { + return null; + } + Arguments a = init.args; + int np = a.positional.size() - 1; + int nk = a.kwonly.size(); + if (np < 0 || c.args.size() > np) { + return null; + } + // Parameter (after self) -> index of the argument that fills it. + int[] from = new int[np + nk]; + Arrays.fill(from, -1); + for (int i = 0; i < c.args.size(); i++) { + if (c.args.get(i) instanceof Starred) { + return null; + } + from[i] = i; + } + String[] kwNames = new String[c.keywords.size()]; + for (int i = 0; i < c.keywords.size(); i++) { + Keyword kw = c.keywords.get(i); + if (kw.arg == null) { + return null; + } + kwNames[i] = kw.arg; + int at = -1; + for (int j = Math.max(1, a.positionalOnly); j < a.positional.size(); j++) { + if (a.positional.get(j).name.equals(kw.arg)) { + at = j - 1; + } + } + for (int j = 0; j < nk && at < 0; j++) { + if (a.kwonly.get(j).name.equals(kw.arg)) { + at = np + j; + } + } + if (at < 0 || from[at] >= 0) { + return null; + } + from[at] = c.args.size() + i; + } + String[] fill = new String[np + nk]; + int firstDefault = a.positional.size() - a.defaults.size(); + for (int j = 0; j < np + nk; j++) { + if (from[j] >= 0) { + fill[j] = "x" + from[j]; + continue; + } + Expr d = j < np ? (j + 1 >= firstDefault ? a.defaults.get(j + 1 - firstDefault) : null) : a.kwDefaults.get(j - np); + if (!(d instanceof Constant)) { + return null; + } + fill[j] = expr(d); + } + String homeClass = k.ref.substring(0, k.ref.length() - k.javaName.length() - 1); + String t = homeClass + "." + k.typeVar; + String door = "CB" + (++boundDoors); + int n = c.args.size() + c.keywords.size(); + StringBuilder d = new StringBuilder(); + d.append(" private static Object ").append(door).append("(Object f"); + StringBuilder xs = new StringBuilder(); + for (int i = 0; i < n; i++) { + d.append(", Object x").append(i); + xs.append(i == 0 ? "" : ", ").append('x').append(i); + } + d.append(") {\n if (f == ").append(t).append(" && !").append(t).append(".classWritten) {\n") + .append(" Object o = ").append(t).append(".newInstance();\n") + .append(" PyType.initReturned(").append(homeClass).append('.').append(entry).append("(o"); + for (String s : fill) { + d.append(", ").append(s); + } + d.append("));\n return o;\n }\n return Py.obj(f).call(new Object[] {").append(xs) + .append("}, "); + if (kwNames.length == 0) { + d.append("Py.NO_KW"); + } else { + StringBuilder j = new StringBuilder(); + for (int i = 0; i < kwNames.length; i++) { + j.append(i == 0 ? "" : "\n").append(kwNames[i]); + } + d.append("Py.names(").append(javaString(j.toString())).append(")"); + } + d.append(");\n }\n"); + StringBuilder call = new StringBuilder(door).append('(').append(expr(c.func)); + for (Expr e : c.args) { + call.append(", ").append(expr(e)); + } + for (Keyword kw : c.keywords) { + call.append(", ").append(expr(kw.value)); + } + fields.append(d); + return call.append(')').toString(); + } + + private int boundDoors; + + /// `recv.name` folded to the class constant, when `recv` is a local + /// typed as a compiled class of this module. Each compiled class at or + /// below the typed one is tested by its exact type, so a class built at + /// run time that borrows the layout takes the generic read, and only + /// while nothing wrote to the class after it was built + /// (`PyType.classWritten`). The instance must not hold `name` itself: + /// where the whole program proves that -- no module stores it by name, + /// no computed store reaches the class -- nothing more is tested; + /// elsewhere `PyInstance.extra` is, which is clear while the instance + /// holds nothing outside its compiled fields. Null when it does not fold. + private String classConstantGet(String name, String raw, String site, String recv) { + if (infer == null || facts == null) { + return null; + } + boolean stored = facts.attrStored(name); + String t; + Layouts.Cls k; + if (raw.equals(selfLocal) && selfTyped != null) { + t = selfTyped; + k = selfCls; + } else { + t = shadowVar.get(raw); + k = t != null ? shadowCls.get(raw) : null; + } + if (k == null || !layouts.classes.containsValue(k)) { + return null; + } + StringBuilder sb = new StringBuilder(); + for (Layouts.Cls c : layouts.classes.values()) { + if (!Infer.isSelfOrAncestor(k, c)) { + continue; + } + Constant v = Layouts.classConstant(c, name); + if (v == null || c.allFields.contains(name)) { + continue; + } + boolean proven = !stored && infer.instanceAttrsClosed(c); + sb.append(t).append(".cls == ").append(c.typeVar).append(" && !").append(c.typeVar).append(".classWritten"); + if (!proven) { + sb.append(" && !").append(t).append(".extra"); + } + sb.append(" ? ").append(expr(v)).append(" : "); + } + if (sb.length() == 0) { + return null; + } + // The guard wraps the whole chain: `&&` binds tighter than `?:`, so + // written inline it guarded only the first test and every later one + // read `.cls` of a null copy. + String g = site + ".get(" + recv + ")"; + return "(" + t + " != null && " + t + " == " + recv + " ? (" + sb + g + ") : " + g + ")"; + } + /// The class declaring field `name` that the compiled method's receiver /// class is or extends, or null when there is none (or no such method). private Layouts.Cls selfOwner(String name) { - return ownerFor(name, selfCls); + return ownerFor(name, selfCls, layouts.fieldOwners); } /// The class declaring field `name` that `cls` is or extends, or null. private Layouts.Cls ownerFor(String name, Layouts.Cls cls) { + return ownerFor(name, cls, allOwners); + } + + private static Layouts.Cls ownerFor(String name, Layouts.Cls cls, Map> all) { if (cls == null) { return null; } - List owners = layouts.fieldOwners.get(name); + List owners = all.get(name); + if (owners == null) { + return null; + } for (Layouts.Cls c = cls; c != null; c = c.parent) { if (owners.contains(c)) { return c; @@ -2985,7 +5417,7 @@ private Layouts.Cls ownerFor(String name, Layouts.Cls cls) { /// `o.name = v` for a compiled field; `o` and `v` are already evaluated. private void fieldSet(String name, String o, String v, String site, StringBuilder out, int ind) { indent(out, ind); - if (o.equals(selfLocal) && selfOwner(name) != null) { + if (o.equals(selfLocal) && selfOwner(name) != null && !selfCls.frozenStores()) { String f = selfTyped + ".f_" + mangle(name); out.append("if (").append(selfTyped).append(" != null && (").append(f).append(" != null || !") .append(selfTyped).append(".extra)) {\n"); @@ -3000,7 +5432,8 @@ private void fieldSet(String name, String o, String v, String site, StringBuilde return; } String h = shadowVar.get(o); - if (h != null && ownerFor(name, shadowCls.get(o)) != null) { + Layouts.Cls hs = h != null ? ownerFor(name, shadowCls.get(o)) : null; + if (hs != null && !shadowCls.get(o).frozenStores() && (hs.typed == null || hs.typed.typedField(hs, name) == null)) { String f = h + ".f_" + mangle(name); out.append("if (").append(h).append(" == ").append(o).append(" && (").append(f).append(" != null || !") .append(h).append(".extra)) {\n"); @@ -3010,6 +5443,9 @@ private void fieldSet(String name, String o, String v, String site, StringBuilde out.append("} else "); } for (Layouts.Cls k : layouts.fieldOwners.get(name)) { + if (k.frozenStores()) { + continue; + } out.append("if (").append(o).append(" instanceof ").append(k.javaName).append(" && (((") .append(k.javaName).append(") ").append(o).append(").f_").append(mangle(name)) .append(" != null || !((").append(k.javaName).append(") ").append(o).append(").extra)) {\n"); @@ -3120,7 +5556,7 @@ private String directCall(String name, int n, String recv, String args, String h continue; } FunctionDef f = r.methods.get(name); - if (f == null || f.args.names().size() - 1 != n || branches >= 3) { + if (f == null || f.args.names().size() - 1 != n || branches >= 3 || overriddenElsewhere(k, name)) { return null; } branches++; @@ -3137,6 +5573,20 @@ private String directCall(String name, int n, String recv, String args, String h .toString(); } + /// Whether a compiled class of another module, below `k`, defines `name` + /// itself: the branch for `k` would then answer its instances wrongly. + private boolean overriddenElsewhere(Layouts.Cls k, String name) { + if (infer == null) { + return false; + } + for (Layouts.Cls c : infer.selfAndBelow(k)) { + if (c.home != layouts && c.bodyNames.contains(name)) { //NOPMD CompareObjectsWithEquals - identity is meant + return true; + } + } + return false; + } + private static String dparams(int n) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < n; i++) { @@ -3152,13 +5602,79 @@ String attrSite(String attr) { } private String site(String attr) { + if (attr.indexOf('\n') < 0) { + return tabled(readSites, "SA", attr); + } String f = "S" + (++sites); fields.append(" private static final AttrSite ").append(f).append(" = new AttrSite(") .append(javaString(attr)).append(");\n"); return f; } - private String hoist(String type, String init) { + /// A fresh inline cache for one attribute store. + String storeSite(String attr) { + if (attr.indexOf('\n') < 0) { + return tabled(storeSites, "SS", attr); + } + String f = "S" + (++sites); + fields.append(" private static final StoreSite ").append(f).append(" = new StoreSite(") + .append(javaString(attr)).append(");\n"); + return f; + } + + /// The sites of the module, by table: the names of each table's sites + /// joined by newlines. A module has thousands of sites, and a static + /// field each was a store and an accessor each in the translated + /// program, most of it for code that never runs; a table is one call. + private final List readSites = new ArrayList(); + private final List storeSites = new ArrayList(); + + /// At most this many names to a table and this many chars: a string + /// constant of a class file holds 65535 bytes. + private static final int TABLE_NAMES = 1024; + private static final int TABLE_CHARS = 16000; + + private String tabled(List tables, String prefix, String attr) { + StringBuilder t = tables.isEmpty() ? null : tables.get(tables.size() - 1); + int n = t == null ? 0 : count(t); + if (t == null || n == TABLE_NAMES || t.length() + attr.length() > TABLE_CHARS) { + t = new StringBuilder(); + tables.add(t); + n = 0; + } + if (n > 0) { + t.append('\n'); + } + t.append(attr); + return prefix + (tables.size() - 1) + "[" + n + "]"; + } + + private static int count(StringBuilder t) { + int n = 1; + for (int i = 0; i < t.length(); i++) { + if (t.charAt(i) == '\n') { + n++; + } + } + return n; + } + + private void siteTables(StringBuilder out) { + for (int i = 0; i < readSites.size(); i++) { + out.append(" private static final AttrSite[] SA").append(i).append(" = AttrSite.table(") + .append(javaString(readSites.get(i).toString())).append(");\n"); + } + for (int i = 0; i < keySites.size(); i++) { + out.append(" private static final KeySite[] SK").append(i).append(" = KeySite.table(") + .append(javaString(keySites.get(i).toString())).append(");\n"); + } + for (int i = 0; i < storeSites.size(); i++) { + out.append(" private static final StoreSite[] SS").append(i).append(" = StoreSite.table(") + .append(javaString(storeSites.get(i).toString())).append(");\n"); + } + } + + String hoist(String type, String init) { String key = type + " " + init; String f = constants.get(key); if (f == null) { @@ -3282,6 +5798,26 @@ private static String javaComment(String s) { /// Whether CPython's optimizer folds every element to a constant, which /// turns a set display of three or more into a frozenset constant. + /// A tuple of constants is one constant per module, as CPython folds it: + /// immutable, so every evaluation may share it. Capped so the static + /// initializer every hoisted constant lands in stays far from the JVM's + /// method size limit. + /// Only literal constants: an emitter writes `-1` with the temporaries of + /// the function it is in, which a static initializer does not have. + static boolean foldable(List elts) { + if (elts.isEmpty() || elts.size() > FOLD_LIMIT) { + return false; + } + for (Expr x : elts) { + if (!(x instanceof Constant)) { + return false; + } + } + return true; + } + + private static final int FOLD_LIMIT = 64; + private static boolean allConstant(List elts) { for (Expr x : elts) { if (!isConstant(x)) { @@ -3365,6 +5901,12 @@ private String fused(Expr root) { } private String fused(Expr root, String current) { + return fused(root, current, this::expr); + } + + /// [#fused(Expr, String)] with the leaves written by `leafCode`: the typed + /// emitter names locals its own way. + String fused(Expr root, String current, java.util.function.Function leafCode) { if (numOps(root) < 2) { return null; } @@ -3406,6 +5948,9 @@ private String fused(Expr root, String current) { numPath(root, leaves, ints, "ints", m); } } + if (anyFloat) { + mixedPath(root, leaves, m); + } int[] counters = new int[2]; String boxed = fuseBoxed(root, counters); if (current != null) { @@ -3416,7 +5961,7 @@ private String fused(Expr root, String current) { StringBuilder call = new StringBuilder(name).append("("); for (int i = 0; i < leaves.size(); i++) { Expr leaf = leaves.get(i); - call.append(i == 0 ? "" : ", ").append(leaf == AUG_CURRENT ? current : expr(leaf)); + call.append(i == 0 ? "" : ", ").append(leaf == AUG_CURRENT ? current : leafCode.apply(leaf)); } return call.append(")").toString(); } @@ -3545,7 +6090,7 @@ private static boolean numNode(Expr e) { return e instanceof UnaryOp && ("-".equals(((UnaryOp) e).op) || "~".equals(((UnaryOp) e).op)); } - private static int numOps(Expr e) { + static int numOps(Expr e) { if (!numNode(e)) { return 0; } @@ -3555,7 +6100,7 @@ private static int numOps(Expr e) { return 1 + numOps(((BinOp) e).left) + numOps(((BinOp) e).right); } - private static void numLeaves(Expr e, List out) { + static void numLeaves(Expr e, List out) { if (numNode(e)) { if (e instanceof UnaryOp) { numLeaves(((UnaryOp) e).operand, out); @@ -3698,6 +6243,88 @@ private void numPath(Expr root, List leaves, Map types, S } } + /// The bits an int value of the tree can need when every int leaf has + /// at most `k` bits (a literal its own); -1 when the tree has an + /// operator other than `+`, `-`, `*` or unary minus. + private static int mixedBits(Expr e, int k) { + if (!numNode(e)) { + if (e instanceof Constant) { + Long v = intLiteral(e); + if (v != null) { + return 64 - Long.numberOfLeadingZeros(Math.abs(v.longValue())); + } + return floatConst(e) ? 0 : -1; + } + return k; + } + if (e instanceof UnaryOp) { + return "-".equals(((UnaryOp) e).op) ? mixedBits(((UnaryOp) e).operand, k) : -1; + } + BinOp b = (BinOp) e; + int l = mixedBits(b.left, k); + int r = mixedBits(b.right, k); + if (l < 0 || r < 0) { + return -1; + } + if ("*".equals(b.op)) { + return l + r; + } + return "+".equals(b.op) || "-".equals(b.op) ? Math.max(l, r) + 1 : -1; + } + + /// Leaves that are a mix of floats and small ints, as a PDF matrix of + /// `(1, 0, 0, 1, 0, 0)` applied to a float point is: every leaf taken + /// as a double, which is exactly Python's answer when no int part of + /// the tree can pass 2**53 (each int leaf is bounded so that it cannot) + /// and the result is not zero -- the one value whose sign an int part + /// computed in doubles could get wrong (`0 * -1` is the int 0, not + /// -0.0). Before this, one int leaf sent the whole tree to one boxed + /// operation per operator. + private void mixedPath(Expr root, List leaves, StringBuilder m) { + int k = 31; + while (k >= 8 && (mixedBits(root, k) < 0 || mixedBits(root, k) > 53)) { + k--; + } + if (k < 8) { + return; + } + long lim = 1L << k; + StringBuilder guard = new StringBuilder(); + StringBuilder any = new StringBuilder(); + StringBuilder unbox = new StringBuilder(); + Map types = new java.util.IdentityHashMap(); + Set none = java.util.Collections.newSetFromMap(new java.util.IdentityHashMap()); + numType(root, none, new HashSet(), types); + for (int i = 0; i < leaves.size(); i++) { + types.put(leaves.get(i), Character.valueOf('f')); + guard.append(i == 0 ? "" : " && ").append("(p").append(i).append(" instanceof Double || p").append(i) + .append(" instanceof Long && ((Long) p").append(i).append(").longValue() > -").append(lim) + .append("L && ((Long) p").append(i).append(").longValue() < ").append(lim).append("L)"); + any.append(i == 0 ? "" : " || ").append("p").append(i).append(" instanceof Double"); + unbox.append(" double d").append(i).append(" = p").append(i).append(" instanceof Double ? ((Double) p") + .append(i).append(").doubleValue() : (double) ((Long) p").append(i).append(").longValue();\n"); + } + retypeFloat(root, types); + m.append(" mixed: if (").append(guard).append(" && (").append(any).append(")) {\n").append(unbox); + int[] counters = new int[2]; + String r = numPrim(root, types, "mixed", m, counters); + bail(m, r + " == 0.0", "mixed"); + m.append(" return Double.valueOf(").append(r).append(");\n }\n"); + } + + /// Every node of the tree float, for [#mixedPath]. + private static void retypeFloat(Expr e, Map types) { + types.put(e, Character.valueOf('f')); + if (numNode(e)) { + if (e instanceof UnaryOp) { + retypeFloat(((UnaryOp) e).operand, types); + } else { + retypeFloat(((BinOp) e).left, types); + retypeFloat(((BinOp) e).right, types); + } + } + } + private static String asDouble(String v, char t) { return t == 'i' ? "((double) " + v + ")" : v; } @@ -5015,4 +7642,59 @@ private static boolean isConstant(Expr x) { return false; } + + /// The static [PyDict.Literal] field for a display whose keys are two or + /// more distinct str constants with no newline in them, or null. One + /// field per distinct key list in the module, so two displays of the + /// same keys share it. A display of other keys -- a variable, a + /// duplicate, a number -- keeps the put per pair, which is what Python + /// means by it: a duplicate key's later value wins in its first place. + String dictShape(List keys) { + if (keys.size() < 2 || keys.size() > 48) { + return null; + } + Set seen = new HashSet(); + StringBuilder joined = new StringBuilder(); + for (Expr k : keys) { + if (!(k instanceof Constant) || ((Constant) k).kind != Constant.Kind.STR) { + return null; + } + String t = ((Constant) k).text; + if (t.indexOf('\n') >= 0 || !seen.add(t)) { + return null; + } + joined.append(joined.length() == 0 ? "" : "\n").append(t); + } + String key = joined.toString(); + String f = dictShapes.get(key); + if (f == null) { + f = "DS" + (++sites); + dictShapes.put(key, f); + fields.append(" private static final PyDict.Literal ").append(f).append(" = PyDict.Literal.of(") + .append(javaString(key)).append(");\n"); + } + return f; + } + + private final Map dictShapes = new HashMap(); + + /// A dict display as `new PyDict(n).put(k, v)...`: made at its final size, with no + /// array of its pairs built for the call, as CPython's BUILD_MAP builds it. + private String dictLiteral(List keys, List values) { + String shape = dictShape(keys); + if (shape != null) { + StringBuilder sb = new StringBuilder("PyDict.literal(").append(shape).append(", new Object[] {"); + for (int i = 0; i < values.size(); i++) { + sb.append(i == 0 ? "" : ", ").append(expr(values.get(i))); + } + return sb.append("})").toString(); + } + StringBuilder sb = new StringBuilder("new PyDict(").append(keys.size()).append(')'); + for (int i = 0; i < keys.size(); i++) { + String k = expr(keys.get(i)); + String v = expr(values.get(i)); + sb.append(".put(").append(k).append(", ").append(v).append(')'); + } + return sb.toString(); + } } diff --git a/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/EntryPointTable.java b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/EntryPointTable.java new file mode 100644 index 00000000000..a007a1cebc4 --- /dev/null +++ b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/EntryPointTable.java @@ -0,0 +1,176 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.python.transpiler.codegen; + +import com.codename1.python.transpiler.ast.Node.Assign; +import com.codename1.python.transpiler.ast.Node.Constant; +import com.codename1.python.transpiler.ast.Node.Expr; +import com.codename1.python.transpiler.ast.Node.Name; +import com.codename1.python.transpiler.ast.Node.Stmt; +import com.codename1.python.transpiler.ast.Node.Subscript; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/// Writes `_cn1_entry_points`, the module `EntryPoint.load` resolves an +/// entry point through: for every group the bundled distributions' metadata +/// declares, a function that imports each of its targets by a literal +/// import, and one statement `GROUPS["group"] = _gN` registering it. A +/// target is reached by name only through that table, so loading is plain +/// imports and attribute reads, never a computed `getattr`. +/// +/// The registrations are not kept for their effect (Liveness): the one of a +/// group is kept only once live code spells that group's name, so a program +/// that loads its `llm` plugins does not keep every console script. +public final class EntryPointTable { + /// The module's name, and the file it is compiled from. + public static final String MODULE = "_cn1_entry_points"; + public static final String PATH = MODULE + ".py"; + /// The table's name in the module. + public static final String TABLE = "GROUPS"; + + private EntryPointTable() { + } + + /// The module's source for the `entry_points.txt` texts in + /// `distributions` (the parsed `_cn1_distributions`), naming only + /// targets whose module is one of `modules`. + public static String source(Object distributions, final Set modules) { + final Map> groups = new LinkedHashMap>(); + Infer.children(distributions, new Infer.Visit() { + @Override + public void on(Object o) { + if (o instanceof Constant && ((Constant) o).kind == Constant.Kind.STR) { + read(((Constant) o).text, groups, modules); + } else { + Infer.children(o, this); + } + } + }); + StringBuilder b = new StringBuilder(); + b.append("\"\"\"Entry point targets by group, generated for importlib.metadata.\"\"\"\n"); + b.append(TABLE).append(" = {}\n"); + int n = 0; + for (Map.Entry> e : groups.entrySet()) { + String fn = "_g" + n++; + b.append("\n\ndef ").append(fn).append("(target):\n"); + int i = 0; + for (String t : e.getValue()) { + int colon = t.indexOf(':'); + String mod = colon < 0 ? t : t.substring(0, colon); + b.append(" if target == ").append(literal(t)).append(":\n"); + if (colon < 0) { + b.append(" import ").append(mod).append(" as _m").append(i).append('\n'); + b.append(" return _m").append(i).append('\n'); + } else { + String attr = t.substring(colon + 1); + int dot = attr.indexOf('.'); + String first = dot < 0 ? attr : attr.substring(0, dot); + b.append(" from ").append(mod).append(" import ").append(first).append(" as _a") + .append(i).append('\n'); + b.append(" return _a").append(i).append(dot < 0 ? "" : attr.substring(dot)).append('\n'); + } + i++; + } + b.append(" return None\n\n\n"); + b.append(TABLE).append('[').append(literal(e.getKey())).append("] = ").append(fn).append('\n'); + } + return b.toString(); + } + + /// The group a statement of the module registers, or null when it is + /// not a registration. + public static String registers(Stmt s) { + if (!(s instanceof Assign) || ((Assign) s).targets.size() != 1 + || !(((Assign) s).targets.get(0) instanceof Subscript)) { + return null; + } + Subscript t = (Subscript) ((Assign) s).targets.get(0); + Expr k = t.index; + if (!(t.value instanceof Name) || !TABLE.equals(((Name) t.value).id) || !(k instanceof Constant) + || ((Constant) k).kind != Constant.Kind.STR) { + return null; + } + return ((Constant) k).text; + } + + private static void read(String text, Map> groups, Set modules) { + String group = null; + for (String line : text.split("\n")) { + String t = line.trim(); + if (t.startsWith("[") && t.endsWith("]")) { + group = t.substring(1, t.length() - 1).trim(); + } else if (group != null && t.indexOf('=') > 0) { + String target = t.substring(t.indexOf('=') + 1).trim(); + int cut = target.indexOf('['); + target = (cut < 0 ? target : target.substring(0, cut)).replace(" ", ""); + int colon = target.indexOf(':'); + String mod = colon < 0 ? target : target.substring(0, colon); + if (!dotted(mod) || colon >= 0 && !dotted(target.substring(colon + 1)) || !modules.contains(mod)) { + continue; + } + List l = groups.get(group); + if (l == null) { + l = new ArrayList(); + groups.put(group, l); + } + if (!l.contains(target)) { + l.add(target); + } + } + } + } + + private static boolean dotted(String s) { + if (s.isEmpty()) { + return false; + } + for (String p : s.split("\\.", -1)) { + if (p.isEmpty() || !Character.isJavaIdentifierStart(p.charAt(0)) || p.charAt(0) == '$') { + return false; + } + for (int i = 1; i < p.length(); i++) { + char c = p.charAt(i); + if (c > 0x7e || !Character.isJavaIdentifierPart(c) || c == '$') { + return false; + } + } + } + return true; + } + + private static String literal(String s) { + StringBuilder b = new StringBuilder("\""); + for (int i = 0; i < s.length(); i++) { + char c = s.charAt(i); + if (c == '\\' || c == '"') { + b.append('\\'); + } + b.append(c < 0x20 || c > 0x7e ? '_' : c); + } + return b.append('"').toString(); + } +} diff --git a/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/EnumLowering.java b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/EnumLowering.java new file mode 100644 index 00000000000..11a00f56c17 --- /dev/null +++ b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/EnumLowering.java @@ -0,0 +1,527 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.python.transpiler.codegen; + +import com.codename1.python.transpiler.ast.Node.Alias; +import com.codename1.python.transpiler.ast.Node.AnnAssign; +import com.codename1.python.transpiler.ast.Node.Assign; +import com.codename1.python.transpiler.ast.Node.Attribute; +import com.codename1.python.transpiler.ast.Node.BinOp; +import com.codename1.python.transpiler.ast.Node.Call; +import com.codename1.python.transpiler.ast.Node.ClassDef; +import com.codename1.python.transpiler.ast.Node.Constant; +import com.codename1.python.transpiler.ast.Node.Expr; +import com.codename1.python.transpiler.ast.Node.ExprStmt; +import com.codename1.python.transpiler.ast.Node.FunctionDef; +import com.codename1.python.transpiler.ast.Node.If; +import com.codename1.python.transpiler.ast.Node.Import; +import com.codename1.python.transpiler.ast.Node.ImportFrom; +import com.codename1.python.transpiler.ast.Node.Keyword; +import com.codename1.python.transpiler.ast.Node.Lambda; +import com.codename1.python.transpiler.ast.Node.ListExpr; +import com.codename1.python.transpiler.ast.Node.Module; +import com.codename1.python.transpiler.ast.Node.Name; +import com.codename1.python.transpiler.ast.Node.Stmt; +import com.codename1.python.transpiler.ast.Node.Try; +import com.codename1.python.transpiler.ast.Node.TupleExpr; +import com.codename1.python.transpiler.ast.Node.UnaryOp; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; +import java.util.IdentityHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/// The members of every enumeration, defined by the compiler instead of by +/// a metaclass reading the class body. +/// +/// CPython's `EnumType.__new__` walks the class namespace and turns each +/// plain value into a member, by name, with `setattr`. Nothing of that can +/// be typed or resolved ahead of time. This pass finds every class deriving +/// from `enum.Enum` (through bases in any module: pptx's `BaseEnum(int, +/// Enum)` and its subclasses) and rewrites the class statement so the body +/// keeps only its methods, followed by one statement per member, in +/// definition order, each naming the member with a build-time string: +/// +/// ```python +/// class Color(Enum): +/// def describe(self): ... +/// Color.RED = _cn1_enum._member(Color, "RED", 1) +/// Color.GREEN = _cn1_enum._member(Color, "GREEN", 2) +/// ``` +/// +/// `_member` makes the member once (the class's own `__new__`/`__init__` +/// included), resolves aliases and `auto()`, and records it in the value +/// and name tables the class's lookups read. Decorators (`@unique`) move +/// after the members, which is when CPython's run. The inference reads the +/// member names back ([#members]) so `Color.RED` is a `Color`, and the +/// stores are trailing class attributes, so each member is a typed static +/// of the class (Layouts#scanTrailing). +/// +/// The functional API, `Color = Enum("Color", "RED GREEN")` (or a list of +/// name literals) at the top of a module, becomes the class statement it +/// stands for, each member an `auto()`; the runtime refuses every other +/// form of it. +public final class EnumLowering { + /// The enumeration bases the library itself defines. + private static final Set ROOTS = new HashSet(Arrays.asList("Enum", "IntEnum", "StrEnum", + "Flag", "IntFlag", "ReprEnum")); + private static final String ENUM_PATH = "enum.py"; + private static final String HELPER = "_cn1_enum"; + + /// Member names of each lowered class, in definition order. + private static final Map> MEMBERS = Collections.synchronizedMap( + new IdentityHashMap>()); + + private final Map trees; + private final Set enums = new HashSet(); + + private EnumLowering(Map trees) { + this.trees = trees; + } + + /// The members the pass defined for `c`, or null when `c` is no + /// lowered enumeration. + public static List members(ClassDef c) { + return MEMBERS.get(c); + } + + /// Lowers every enumeration of the program `trees` (path to module). + public static void rewrite(Map trees) { + EnumLowering l = new EnumLowering(trees); + for (String r : ROOTS) { + l.enums.add(ENUM_PATH + ":" + r); + } + for (Map.Entry e : trees.entrySet()) { + if (!ENUM_PATH.equals(e.getKey())) { + l.functional(e.getKey(), e.getValue().body); + } + } + boolean changed = true; + while (changed) { + changed = false; + for (Map.Entry e : trees.entrySet()) { + for (Stmt s : e.getValue().body) { + if (s instanceof ClassDef && !l.enums.contains(e.getKey() + ":" + ((ClassDef) s).name) + && l.derives(e.getKey(), (ClassDef) s)) { + l.enums.add(e.getKey() + ":" + ((ClassDef) s).name); + changed = true; + } + } + } + } + for (Map.Entry e : trees.entrySet()) { + boolean[] used = new boolean[1]; + l.walk(e.getKey(), e.getValue().body, used, true); + if (used[0] && !ENUM_PATH.equals(e.getKey())) { + List a = new ArrayList(); + a.add(new Alias("enum", HELPER)); + e.getValue().body.add(firstAfterFuture(e.getValue().body), new Import(a)); + } + } + // The members just written, and every other class attribute bound + // right after its class, become typed statics (Layouts#scanTrailing). + for (Module m : trees.values()) { + Layouts.scanTrailing(m); + } + } + + /// Rewrites each top-level `Name = Enum("Name", names)` of `body` + /// (`names` a string of names or a list or tuple of name literals) to + /// `class Name(Enum)` with one `auto()` member per name. + private void functional(String path, List body) { + for (int i = 0; i < body.size(); i++) { + if (!(body.get(i) instanceof Assign)) { + continue; + } + Assign a = (Assign) body.get(i); + if (a.targets.size() != 1 || !(a.targets.get(0) instanceof Name) || !(a.value instanceof Call)) { + continue; + } + Call c = (Call) a.value; + String target = ((Name) a.targets.get(0)).id; + String root = resolve(path, c.func, 0); + if (root == null || !root.startsWith(ENUM_PATH + ":") || !ROOTS.contains(root.substring(ENUM_PATH.length() + 1)) + || c.args.size() != 2 || !c.keywords.isEmpty() || !(c.args.get(0) instanceof Constant) + || !target.equals(((Constant) c.args.get(0)).text)) { + continue; + } + List names = new ArrayList(); + Expr n = c.args.get(1); + if (n instanceof Constant && ((Constant) n).kind == Constant.Kind.STR) { + for (String x : ((Constant) n).text.replace(',', ' ').split(" ")) { + if (!x.isEmpty()) { + names.add(x); + } + } + } else if (n instanceof ListExpr || n instanceof TupleExpr) { + for (Expr x : n instanceof ListExpr ? ((ListExpr) n).elts : ((TupleExpr) n).elts) { + if (!(x instanceof Constant) || ((Constant) x).kind != Constant.Kind.STR) { + names = null; + break; + } + names.add(((Constant) x).text); + } + } else { + names = null; + } + if (names == null || names.isEmpty()) { + continue; + } + List members = new ArrayList(); + for (String x : names) { + List t = new ArrayList(); + t.add(new Name(x)); + members.add(new Assign(t, new Call(new Attribute(new Name(HELPER), "auto"))).at(a.line, a.col)); + } + List bases = new ArrayList(); + bases.add(c.func); + body.set(i, new ClassDef(target, bases, new ArrayList(), + members, new ArrayList()).at(a.line, a.col)); + } + } + + private static int firstAfterFuture(List body) { + int i = 0; + if (!body.isEmpty() && body.get(0) instanceof ExprStmt && ((ExprStmt) body.get(0)).value instanceof Constant) { + i = 1; + } + while (i < body.size() && body.get(i) instanceof ImportFrom + && "__future__".equals(((ImportFrom) body.get(i)).module)) { + i++; + } + return i; + } + + private boolean derives(String path, ClassDef c) { + if (ENUM_PATH.equals(path) && ROOTS.contains(c.name)) { + return false; + } + for (Expr b : c.bases) { + String k = resolve(path, b, 0); + if (k != null && enums.contains(k)) { + return true; + } + } + return false; + } + + /// `path:Class` for the class base `b` names in module `path`, or null. + private String resolve(String path, Expr b, int depth) { + if (depth > 8) { + return null; + } + if (b instanceof Name) { + return resolveName(path, ((Name) b).id, depth); + } + if (b instanceof Attribute && ((Attribute) b).value instanceof Name) { + String m = moduleBound(path, ((Name) ((Attribute) b).value).id); + return m == null ? null : resolveName(m, ((Attribute) b).attr, depth + 1); + } + return null; + } + + /// What `name`, bound at the top of module `path`, is as `path:Class`. + private String resolveName(String path, String name, int depth) { + if (ENUM_PATH.equals(path) && ROOTS.contains(name)) { + return path + ":" + name; + } + Module m = trees.get(path); + if (m == null || depth > 8) { + return null; + } + for (Stmt s : m.body) { + if (s instanceof ClassDef && ((ClassDef) s).name.equals(name)) { + return path + ":" + name; + } + } + for (Stmt s : m.body) { + if (s instanceof ImportFrom) { + ImportFrom f = (ImportFrom) s; + for (Alias a : f.names) { + if (name.equals(a.asname != null ? a.asname : a.name)) { + String mp = modulePath(path, f.module, f.level); + return mp == null ? null : resolveName(mp, a.name, depth + 1); + } + if ("*".equals(a.name)) { + String mp = modulePath(path, f.module, f.level); + String r = mp == null ? null : resolveName(mp, name, depth + 1); + if (r != null) { + return r; + } + } + } + } + } + return null; + } + + /// The module path `local` names after `import x [as local]` in `path`. + private String moduleBound(String path, String local) { + Module m = trees.get(path); + if (m == null) { + return null; + } + for (Stmt s : m.body) { + if (s instanceof Import) { + for (Alias a : ((Import) s).names) { + if (local.equals(a.asname != null ? a.asname : a.name)) { + return modulePath(path, a.name, 0); + } + } + } + if (s instanceof ImportFrom) { + ImportFrom f = (ImportFrom) s; + for (Alias a : f.names) { + if (local.equals(a.asname != null ? a.asname : a.name)) { + String base = f.module == null ? a.name : f.module + "." + a.name; + String mp = modulePath(path, base, f.level); + if (mp != null) { + return mp; + } + } + } + } + } + return null; + } + + private String modulePath(String from, String module, int level) { + String dotted = module == null ? "" : module; + if (level > 0) { + String pkg = from.endsWith("/__init__.py") ? from.substring(0, from.length() - "/__init__.py".length()) + : from.lastIndexOf('/') < 0 ? "" : from.substring(0, from.lastIndexOf('/')); + for (int i = 1; i < level; i++) { + pkg = pkg.lastIndexOf('/') < 0 ? "" : pkg.substring(0, pkg.lastIndexOf('/')); + } + String rest = dotted.replace('.', '/'); + dotted = pkg.isEmpty() ? rest : rest.isEmpty() ? pkg : pkg + "/" + rest; + } else { + dotted = dotted.replace('.', '/'); + } + if ("enum".equals(dotted)) { + return ENUM_PATH; + } + if (trees.containsKey(dotted + ".py")) { + return dotted + ".py"; + } + if (trees.containsKey(dotted + "/__init__.py")) { + return dotted + "/__init__.py"; + } + return null; + } + + private void walk(String path, List body, boolean[] used, boolean top) { + for (int i = 0; i < body.size(); i++) { + Stmt s = body.get(i); + if (s instanceof ClassDef) { + ClassDef c = (ClassDef) s; + walk(path, c.body, used, false); + boolean isEnum = top ? enums.contains(path + ":" + c.name) : localEnum(path, c); + if (isEnum && !(ENUM_PATH.equals(path) && ROOTS.contains(c.name))) { + List after = lower(path, c); + if (!after.isEmpty()) { + used[0] = true; + body.addAll(i + 1, after); + i += after.size(); + } + } + } else if (s instanceof FunctionDef) { + walk(path, ((FunctionDef) s).body, used, false); + } else if (s instanceof If) { + walk(path, ((If) s).body, used, false); + walk(path, ((If) s).orelse, used, false); + } else if (s instanceof Try) { + walk(path, ((Try) s).body, used, false); + } + } + } + + private boolean localEnum(String path, ClassDef c) { + for (Expr b : c.bases) { + String k = resolve(path, b, 0); + if (k != null && enums.contains(k)) { + return true; + } + } + return false; + } + + private List lower(String path, ClassDef c) { + if (MEMBERS.containsKey(c)) { + return new ArrayList(); + } + List names = new ArrayList(); + List values = new ArrayList(); + List isMember = new ArrayList(); + Set bodyNames = new HashSet(); + Set memberSoFar = new HashSet(); + List kept = new ArrayList(); + for (Stmt s : c.body) { + String n = null; + Expr v = null; + if (s instanceof Assign && ((Assign) s).targets.size() == 1 && ((Assign) s).targets.get(0) instanceof Name) { + n = ((Name) ((Assign) s).targets.get(0)).id; + v = ((Assign) s).value; + } else if (s instanceof AnnAssign && ((AnnAssign) s).value != null + && ((AnnAssign) s).target instanceof Name) { + n = ((Name) ((AnnAssign) s).target).id; + v = ((AnnAssign) s).value; + } else if (s instanceof Assign) { + for (Expr t : ((Assign) s).targets) { + if (t instanceof Name && !excluded(c.name, ((Name) t).id)) { + throw new IllegalStateException(path + ": enum " + c.name + + " defines member " + ((Name) t).id + " in a statement the compiler cannot lower"); + } + } + } + if (s instanceof FunctionDef) { + bodyNames.add(((FunctionDef) s).name); + } + if (n == null || excluded(c.name, n) || v instanceof Lambda) { + if (n != null) { + bodyNames.add(n); + } + kept.add(s); + continue; + } + boolean member = true; + if (v instanceof Call && ((Call) v).func instanceof Name && ((Call) v).args.size() == 1) { + String f = ((Name) ((Call) v).func).id; + if ("nonmember".equals(f)) { + member = false; + v = ((Call) v).args.get(0); + } else if ("member".equals(f)) { + v = ((Call) v).args.get(0); + } + } + names.add(n); + values.add(rebind(v, c.name, bodyNames, memberSoFar, path)); + isMember.add(member); + bodyNames.add(n); + if (member) { + memberSoFar.add(n); + } + } + List out = new ArrayList(); + if (names.isEmpty() && c.decorators.isEmpty()) { + MEMBERS.put(c, new ArrayList()); + return out; + } + c.body.clear(); + c.body.addAll(kept); + if (c.body.isEmpty()) { + c.body.add(new ExprStmt(new Constant(Constant.Kind.NONE, "None"))); + } + List mem = new ArrayList(); + boolean self = ENUM_PATH.equals(path); + for (int i = 0; i < names.size(); i++) { + Expr v = values.get(i); + if (isMember.get(i)) { + Call m = new Call(self ? new Name("_member") : new Attribute(new Name(HELPER), "_member")); + m.args.add(new Name(c.name)); + m.args.add(new Constant(Constant.Kind.STR, names.get(i))); + m.args.add(v); + v = m; + mem.add(names.get(i)); + } + List t = new ArrayList(); + t.add(new Attribute(new Name(c.name), names.get(i))); + out.add(new Assign(t, v)); + } + List decos = new ArrayList(c.decorators); + c.decorators.clear(); + for (int i = decos.size() - 1; i >= 0; i--) { + Call d = new Call(decos.get(i)); + d.args.add(new Name(c.name)); + List t = new ArrayList(); + t.add(new Name(c.name)); + out.add(new Assign(t, d)); + } + MEMBERS.put(c, mem); + return out; + } + + /// Dunders, sunders and private names are never members. + private static boolean excluded(String cls, String n) { + boolean dunder = n.length() > 4 && n.startsWith("__") && n.endsWith("__"); + boolean sunder = n.length() > 2 && n.charAt(0) == '_' && n.charAt(n.length() - 1) == '_' + && n.charAt(1) != '_' && n.charAt(n.length() - 2) != '_'; + boolean priv = n.startsWith("_" + cls + "__"); + return dunder || sunder || priv; + } + + /// `value` as it reads outside the class body: a name the body bound + /// earlier is that attribute of the class (a member's raw value). + private static Expr rebind(Expr v, String cls, Set body, Set members, String path) { + if (v instanceof Name) { + String n = ((Name) v).id; + if (members.contains(n)) { + return new Attribute(new Attribute(new Name(cls), n), "_value_"); + } + return body.contains(n) ? new Attribute(new Name(cls), n) : v; + } + if (v instanceof BinOp) { + BinOp b = (BinOp) v; + return new BinOp(rebind(b.left, cls, body, members, path), b.op, rebind(b.right, cls, body, members, path)); + } + if (v instanceof UnaryOp) { + return new UnaryOp(((UnaryOp) v).op, rebind(((UnaryOp) v).operand, cls, body, members, path)); + } + if (v instanceof TupleExpr || v instanceof ListExpr) { + List src = v instanceof TupleExpr ? ((TupleExpr) v).elts : ((ListExpr) v).elts; + List e = new ArrayList(); + for (Expr x : src) { + e.add(rebind(x, cls, body, members, path)); + } + return v instanceof TupleExpr ? new TupleExpr(e) : new ListExpr(e); + } + if (v instanceof Call) { + Call c = (Call) v; + Call r = new Call(rebind(c.func, cls, body, members, path)); + for (Expr x : c.args) { + r.args.add(rebind(x, cls, body, members, path)); + } + r.keywords.addAll(c.keywords); + return r; + } + if (mentions(v, body)) { + throw new IllegalStateException(path + ": enum " + cls + + " computes a member from a name of its own body in an expression the compiler cannot lower"); + } + return v; + } + + private static boolean mentions(Object o, Set names) { + if (o instanceof Name) { + return names.contains(((Name) o).id); + } + if (o instanceof Attribute) { + return mentions(((Attribute) o).value, names); + } + return false; + } +} diff --git a/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/FlaskProxyLowering.java b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/FlaskProxyLowering.java new file mode 100644 index 00000000000..c79226d77df --- /dev/null +++ b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/FlaskProxyLowering.java @@ -0,0 +1,284 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.python.transpiler.codegen; + +import com.codename1.python.transpiler.ast.Node; +import com.codename1.python.transpiler.ast.Node.Alias; +import com.codename1.python.transpiler.ast.Node.Assign; +import com.codename1.python.transpiler.ast.Node.Attribute; +import com.codename1.python.transpiler.ast.Node.Call; +import com.codename1.python.transpiler.ast.Node.Constant; +import com.codename1.python.transpiler.ast.Node.Delete; +import com.codename1.python.transpiler.ast.Node.Expr; +import com.codename1.python.transpiler.ast.Node.Import; +import com.codename1.python.transpiler.ast.Node.ImportFrom; +import com.codename1.python.transpiler.ast.Node.Name; +import com.codename1.python.transpiler.ast.Node.Stmt; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeSet; + +/// Flask's `request`, `g`, `session` and `current_app` are proxies that +/// forward any attribute, by name, to the current request context's +/// object. The bundled `flask._Proxy` keeps only the item, container and +/// truth protocols; here the attribute names the program uses on each +/// proxy -- `request.` read, stored or deleted, and +/// `hasattr`/`getattr`/`setattr`/`delattr` with a literal name -- become +/// properties of a generated subclass, one module `_cn1_flask_proxies` +/// for the program, and each `from flask import request` imports that +/// module's instance instead. Every name is literal, so nothing is looked +/// up by name at run time. +/// +/// A proxy that escapes where the build cannot follow its attribute uses +/// -- passed to a call, stored, returned, read as `flask.request`, or read +/// with a computed name -- is refused in strict mode, naming the line. +public final class FlaskProxyLowering { + /// The path of the generated module. + public static final String PATH = "_cn1_flask_proxies.py"; + + private static final String[] PROXIES = {"request", "g", "session", "current_app"}; + private static final Map WHAT = new HashMap(); + private static final Set REFLECT = new HashSet(Arrays.asList("hasattr", "getattr", "setattr", + "delattr")); + /// Builtins whose argument the proxy answers through a protocol it keeps. + private static final Set PROTOCOL = new HashSet(Arrays.asList("len", "bool", "iter", "repr", + "str", "list", "dict", "sorted", "tuple", "set")); + + static { + WHAT.put("request", "request"); + WHAT.put("g", "g"); + WHAT.put("session", "session"); + WHAT.put("current_app", "app"); + } + + private FlaskProxyLowering() { + } + + private static final class Use { + final Set names = new TreeSet(); + final Set stored = new HashSet(); + final Set deleted = new HashSet(); + } + + /// Lowers the flask proxies of the program's modules; the source of the + /// generated module, or null when no module imports a proxy. + public static String rewrite(Map trees) { + Map uses = new LinkedHashMap(); + for (String p : PROXIES) { + uses.put(p, new Use()); + } + boolean any = false; + for (Map.Entry e : trees.entrySet()) { + String path = e.getKey().replace('\\', '/'); + if (path.startsWith("flask/") || PATH.equals(path)) { + continue; + } + any |= module(e.getValue(), uses); + } + if (!any) { + return null; + } + StringBuilder src = new StringBuilder("import flask as _cn1_f\n"); + for (String p : PROXIES) { + Use u = uses.get(p); + String k = "_cn1_" + p + "_proxy"; + src.append("\n\nclass ").append(k).append("(_cn1_f._Proxy):\n pass\n"); + for (String n : u.names) { + src.append("\n @property\n def ").append(n).append("(self):\n return self._get().") + .append(n).append("\n"); + if (u.stored.contains(n)) { + src.append("\n @").append(n).append(".setter\n def ").append(n) + .append("(self, v):\n self._get().").append(n).append(" = v\n"); + } + if (u.deleted.contains(n)) { + src.append("\n @").append(n).append(".deleter\n def ").append(n) + .append("(self):\n del self._get().").append(n).append("\n"); + } + } + src.append("\n\n").append(p).append(" = ").append(k).append("(\"").append(WHAT.get(p)).append("\")\n"); + } + return src.toString(); + } + + /// Redirects the proxy imports of one module and collects their uses. + private static boolean module(Node.Module tree, Map uses) { + Map bound = new HashMap(); + Set flaskMods = new HashSet(); + for (Stmt s : tree.body) { + if (s instanceof Import) { + for (Alias a : ((Import) s).names) { + if ("flask".equals(a.name)) { + flaskMods.add(a.asname != null ? a.asname : a.name); + } + } + } + } + boolean any = false; + for (int i = 0; i < tree.body.size(); i++) { + Stmt s = tree.body.get(i); + if (!(s instanceof ImportFrom) || ((ImportFrom) s).level != 0 + || !"flask".equals(((ImportFrom) s).module)) { + continue; + } + List keep = new ArrayList(); + List moved = new ArrayList(); + for (Alias a : ((ImportFrom) s).names) { + if (WHAT.containsKey(a.name)) { + moved.add(a); + bound.put(a.asname != null ? a.asname : a.name, a.name); + } else { + keep.add(a); + } + } + if (moved.isEmpty()) { + continue; + } + any = true; + ImportFrom gen = new ImportFrom(PATH.substring(0, PATH.length() - 3), 0, moved); + DataclassInit.atLine(gen, s.line); + if (keep.isEmpty()) { + tree.body.set(i, gen); + } else { + ImportFrom rest = new ImportFrom("flask", 0, keep); + DataclassInit.atLine(rest, s.line); + tree.body.set(i, rest); + tree.body.add(++i, gen); + } + } + if (bound.isEmpty() && flaskMods.isEmpty()) { + return false; + } + Map bindings = new HashMap(); + for (Stmt s : tree.body) { + DataclassInit.count(s, bindings); + } + for (Map.Entry b : bound.entrySet()) { + if (bindings.getOrDefault(b.getKey(), 0) != 1) { + // Rebound somewhere: refuse every use rather than guess. + walk(tree.body, null, b.getKey(), null, null); + } else { + walk(tree.body, null, b.getKey(), uses.get(b.getValue()), null); + } + } + for (String m : flaskMods) { + walk(tree.body, null, m, null, m); + } + return any; + } + + private static final String ESCAPE = "a flask proxy used other than by a literal attribute, an item, a" + + " container test or its truth cannot be lowered at build time; read the attribute you need here" + + " (request.) instead of passing the proxy on"; + + /// Walks `o` for uses of the proxy bound to `name` (`use` null refuses + /// every one), or, with `module` set, for `module.` reads. + private static void walk(Object o, Object parent, String name, Use use, String module) { + if (o instanceof Node.FunctionDef && binds(((Node.FunctionDef) o).args, name) + || o instanceof Node.Lambda && binds(((Node.Lambda) o).args, name)) { + // A parameter of that name shadows the proxy. + return; + } + if (module != null) { + if (o instanceof Attribute && ((Attribute) o).value instanceof Name + && module.equals(((Name) ((Attribute) o).value).id) && WHAT.containsKey(((Attribute) o).attr)) { + ((Node) o).refusal = module + "." + ((Attribute) o).attr + " cannot be lowered at build time;" + + " import it with from flask import " + ((Attribute) o).attr; + return; + } + Infer.children(o, c -> walk(c, o, name, use, module)); + return; + } + if (o instanceof Attribute && isName(((Attribute) o).value, name)) { + String a = ((Attribute) o).attr; + if (use == null || a.startsWith("_")) { + ((Node) o).refusal = ESCAPE; + } else { + use.names.add(a); + if (parent instanceof Assign && ((Assign) parent).targets.contains(o) + || parent instanceof Node.AugAssign) { + use.stored.add(a); + } + if (parent instanceof Delete) { + use.deleted.add(a); + } + } + return; + } + if (o instanceof Call && ((Call) o).func instanceof Name && REFLECT.contains(((Name) ((Call) o).func).id) + && !((Call) o).args.isEmpty() && isName(((Call) o).args.get(0), name)) { + Call c = (Call) o; + String f = ((Name) c.func).id; + if (use == null || c.args.size() < 2 || !(c.args.get(1) instanceof Constant) + || ((Constant) c.args.get(1)).kind != Constant.Kind.STR + || !((Constant) c.args.get(1)).text.matches("[A-Za-z][A-Za-z0-9_]*")) { + c.refusal = f + " of a flask proxy with a computed name is reflection; use a literal name"; + return; + } + String a = ((Constant) c.args.get(1)).text; + use.names.add(a); + if ("setattr".equals(f)) { + use.stored.add(a); + } else if ("delattr".equals(f)) { + use.deleted.add(a); + } + for (int i = 2; i < c.args.size(); i++) { + walk(c.args.get(i), c, name, use, null); + } + return; + } + if (o instanceof Name && name.equals(((Name) o).id)) { + boolean ok = use != null && (parent instanceof Node.Subscript && ((Node.Subscript) parent).value == o //NOPMD CompareObjectsWithEquals - identity is meant + || parent instanceof Node.Compare + || parent instanceof Node.If || parent instanceof Node.While || parent instanceof Node.IfExp + || parent instanceof Node.BoolOp || parent instanceof Node.UnaryOp + || parent instanceof Call && ((Call) parent).func instanceof Name + && PROTOCOL.contains(((Name) ((Call) parent).func).id) && ((Call) parent).args.contains(o)); + if (!ok) { + ((Node) o).refusal = ESCAPE; + } + return; + } + Infer.children(o, c -> walk(c, o, name, use, null)); + } + + private static boolean isName(Expr e, String name) { + return e instanceof Name && name.equals(((Name) e).id); + } + + private static boolean binds(Node.Arguments args, String name) { + boolean[] hit = {false}; + Infer.children(args, c -> { + if (c instanceof Node.Arg && name.equals(((Node.Arg) c).name)) { + hit[0] = true; + } + }); + return hit[0]; + } +} diff --git a/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/GenLowering.java b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/GenLowering.java index ce4c5c21fdf..0cfc808e67b 100644 --- a/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/GenLowering.java +++ b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/GenLowering.java @@ -27,6 +27,7 @@ import com.codename1.python.transpiler.ast.Node.Assign; import com.codename1.python.transpiler.ast.Node.Await; import com.codename1.python.transpiler.ast.Node.Break; +import com.codename1.python.transpiler.ast.Node.Call; import com.codename1.python.transpiler.ast.Node.ClassDef; import com.codename1.python.transpiler.ast.Node.Continue; import com.codename1.python.transpiler.ast.Node.ExceptHandler; @@ -45,14 +46,16 @@ import com.codename1.python.transpiler.ast.Node.Yield; import com.codename1.python.transpiler.ast.Scope; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; +import java.util.Map; /// Lowers the body of a generator or coroutine into the `step` method of a /// `PyGenerator` subclass: a `switch (pc)` whose cases are the stretches of /// the body between suspension points. /// /// A statement that cannot suspend (and does not jump out of a lowered loop -/// or `finally`) is emitted by the [Emitter] as it would be anywhere else; the +/// or `finally`) is emitted by the [GenTarget] as it would be anywhere else; the /// rest become states. Exceptions are routed by a table: every state records /// the state that handles an exception raised in it (an `except` dispatch, a /// `finally`, or none), and the `catch` around the `switch` jumps there with @@ -69,7 +72,7 @@ final class GenLowering { private static final int IND = 5; - private final Emitter em; + private final GenTarget em; private final String file; private final Linearize lin; private final StringBuilder fields = new StringBuilder(); //NOPMD AvoidStringBufferField - the generator's output @@ -111,8 +114,11 @@ private static final class Fin { /// Whether this is an async generator, whose yields are wrapped. boolean asyncGen; + /// Whether this is a plain (not async) generator, whose body may resume + /// another generator flat outside a handler (see `PyGenerator.nextFlat`). + boolean plain; - GenLowering(Emitter em, String file, Scope scope) { + GenLowering(GenTarget em, String file, Scope scope) { this.em = em; this.file = file; this.lin = new Linearize(file, scope); @@ -131,19 +137,7 @@ String step(List body) { line(" pc = -1;"); line(" return Py.NONE;"); line("}"); - StringBuilder r = new StringBuilder(); - r.append(" d$: while (true) {\n"); - r.append(" try {\n"); - r.append(" switch (pc) {\n"); - r.append(out); - r.append(" }\n"); - r.append(" default:\n"); - r.append(" throw new IllegalStateException();\n"); - r.append(" }\n"); - r.append(" } catch (Throwable t$) {\n"); - r.append(" final PyException x$ = Py.convert(t$);\n"); - r.append(" switch (pc) {\n"); - boolean any = false; + StringBuilder handlers = new StringBuilder(); for (int h = 0; h < handlerOf.size(); h++) { StringBuilder labels = new StringBuilder(); for (int s = 0; s < handlerOf.size(); s++) { @@ -152,19 +146,130 @@ String step(List body) { } } if (labels.length() > 0) { - any = true; - r.append(labels).append(" pc = ").append(h).append(";\n") + handlers.append(labels).append(" pc = ").append(h).append(";\n") .append(" break;\n"); } } + StringBuilder r = new StringBuilder(); + // A body with no except or finally has nothing to route an exception + // to, and gets no try: on ParparVM every try costs a setjmp on entry, + // which a generator pays on every resumption. What escapes is a Java + // exception only where a call raised one, and resume() and the caller + // see it exactly as they see one from any other call. + boolean any = handlers.length() > 0; + if (any) { + // The try is outside the dispatch loop, not inside it: every jump + // between states is a `continue d$`, and with the try in the loop + // each one entered it again -- a setjmp per state transition, + // several per resumption of a loop with an except in it. Here it + // is entered once per resumption and once more after each caught + // exception, which the outer loop routes back to the dispatch. + // The store before the dispatch loop is not idle: javac starts the + // try range at the loop head when nothing precedes it, and + // ParparVM sets the handler up at the range's first instruction, + // so every `continue d$` would jump back over the setjmp again. + r.append(" int entry$ = 0;\n"); + r.append(" while (true) {\n"); + r.append(" try {\n"); + r.append(" entry$++;\n"); + } + r.append(" d$: while (true) {\n"); + r.append(" switch (pc) {\n"); + r.append(threadJumps(out.toString())); + r.append(" }\n"); r.append(" default:\n"); - r.append(" throw x$;\n"); + r.append(" throw new IllegalStateException();\n"); r.append(" }\n"); + r.append(" }\n"); if (any) { + r.append(" } catch (Throwable t$) {\n"); + r.append(" final PyException x$ = Py.convert(t$);\n"); + r.append(" switch (pc) {\n"); + r.append(handlers); + r.append(" default:\n"); + r.append(" throw x$;\n"); + r.append(" }\n"); r.append(" exc = x$;\n"); + r.append(" }\n"); + r.append(" }\n"); + } + return r.toString(); + } + + /// `True`, whose test the lowering need not emit: `while True:` and the + /// `if True:` the linearizer writes for a `try` it removed. + private static boolean alwaysTrue(Expr e) { + return e instanceof com.codename1.python.transpiler.ast.Node.Constant + && ((com.codename1.python.transpiler.ast.Node.Constant) e).kind + == com.codename1.python.transpiler.ast.Node.Constant.Kind.TRUE; + } + + private static final String CASE = " case "; + private static final String JUMP = "if (true) { pc = "; + private static final String JUMP_END = "; continue d$; }"; + + /// Retargets every jump through the states whose whole body is one + /// unconditional jump, and drops the jumps behind a test that is never + /// false (`if (!(true)) ...`). The lowering opens a state per join point, + /// so a loop's back edge went through two or three of them, a trip round + /// the dispatch switch each (bs4's `ElementFilter.filter` took four per + /// element). Every state is kept: resumption and the handlers enter + /// states by number, and a state no jump names any more is just never + /// entered that way. + static String threadJumps(String out) { + String[] lines = out.split("\n", -1); + Map forward = new HashMap(); + int state = -1; + int target = -1; + int body = 0; + for (String l : lines) { + if (l.startsWith(CASE) && l.endsWith(": {")) { + if (state >= 0 && body == 1 && target >= 0) { + forward.put(Integer.valueOf(state), Integer.valueOf(target)); + } + state = Integer.parseInt(l.substring(CASE.length(), l.length() - 3)); + target = -1; + body = 0; + continue; + } + String t = l.trim(); + // The case's own closing brace, which begin() writes before the + // next case, is not part of its body. + if (t.isEmpty() || t.startsWith("/* line ") || " }".equals(l) + || t.startsWith("if (!(true)) ")) { + continue; + } + body++; + target = t.startsWith(JUMP) && t.endsWith(JUMP_END) ? Integer.parseInt(t.substring(JUMP.length(), + t.length() - JUMP_END.length())) : -1; + } + StringBuilder r = new StringBuilder(out.length()); + for (int i = 0; i < lines.length; i++) { + String l = lines[i]; + if (l.trim().startsWith("if (!(true)) ")) { + continue; + } + int at = l.indexOf("pc = "); + int end = at < 0 ? -1 : l.indexOf("; continue d$;", at); + if (end > 0) { + String n = l.substring(at + 5, end); + if (!n.isEmpty() && Character.isDigit(n.charAt(0)) && n.chars().allMatch(Character::isDigit)) { + int s = Integer.parseInt(n); + for (int k = 0; k < forward.size() + 1; k++) { + Integer f = forward.get(Integer.valueOf(s)); + if (f == null) { + break; + } + s = f.intValue(); + } + l = l.substring(0, at + 5) + s + l.substring(end); + } + } + r.append(l); + if (i < lines.length - 1) { + r.append('\n'); + } } - r.append(" }\n"); - r.append(" }\n"); return r.toString(); } @@ -277,6 +382,17 @@ private static boolean jumpsOutOfElse(List orelse) { private void stmt(Stmt s) { if (!lowered(s)) { + if (flat() && s instanceof Assign && ((Assign) s).targets.size() == 1 + && ((Assign) s).value instanceof Call && Emitter.nextOrStop((Call) ((Assign) s).value)) { + // The same flat resumption as the suspending form below, for + // the `x = next(it)` a generator's own loop makes without a + // yield in it (bs4's ElementFilter.filter): it went through + // Builtins.nextOrStop and the inner generator's setjmp. + Call c = (Call) ((Assign) s).value; + em.store(((Assign) s).targets.get(0), "nextOrStopFlat(" + em.expr(c.args.get(0)) + ", " + + em.expr(c.args.get(1)) + ")", out, IND + 2); + return; + } em.stmt(s, out, IND + 2); return; } @@ -287,11 +403,29 @@ private void stmt(Stmt s) { } if (s instanceof ExprStmt) { suspend(((ExprStmt) s).value); - line("noop(" + result(((ExprStmt) s).value) + ");"); + Expr ev = ((ExprStmt) s).value; + if (ev instanceof Yield && !((Yield) ev).from) { + // A yield whose value is unused: resumed() only matters when + // something was sent or thrown in, so test that inline first. + line("if (thrown != null || sent != Py.NONE) noop(resumed());"); + } else { + line("noop(" + result(ev) + ");"); + } } else if (s instanceof Assign) { Assign a = (Assign) s; suspend(a.value); - String r = result(a.value); + String r; + if (flat() && a.value instanceof Call && Emitter.nextOrStop((Call) a.value)) { + // The desugared `try: x = next(it) except StopIteration` + // outside any handler: a plain generator is resumed flat, as a + // for loop over it would be, instead of through resume()'s + // setjmp. bs4's ElementFilter.filter does this for every + // element find_parent looks at. + Call c = (Call) a.value; + r = "nextOrStopFlat(" + em.expr(c.args.get(0)) + ", " + em.expr(c.args.get(1)) + ")"; + } else { + r = result(a.value); + } if (a.targets.size() == 1) { em.store(a.targets.get(0), r, out, IND + 2); } else { @@ -367,12 +501,19 @@ private void delegate(String iterator) { int k = newState(); jump(k); begin(k); - line("final Object r$ = delegateStep();"); + line("final Object r$ = " + (flat() ? "delegateStepFlat();" : "delegateStep();")); line("if (r$ != null) {"); line(" return r$;"); line("}"); } + /// Whether a generator resumed here may skip its own handler: nothing in + /// this body catches what it raises, so it reaches the `resume` that + /// finishes it. + private boolean flat() { + return plain && handler < 0; + } + /// Awaits `java`, an awaitable, inside the current state sequence; the /// result is then `delegateResult`. private void await(String java) { @@ -417,7 +558,9 @@ private void jumpTo(int target, int depth) { private void ifStmt(If s) { int end = newState(); int els = s.orelse.isEmpty() ? end : newState(); - line("if (!(" + em.cond(s.test) + ")) " + goTo(els)); + if (!alwaysTrue(s.test)) { + line("if (!(" + em.cond(s.test) + ")) " + goTo(els)); + } block(s.body); jump(end); if (!s.orelse.isEmpty()) { @@ -434,7 +577,9 @@ private void whileStmt(While w) { int els = w.orelse.isEmpty() ? end : newState(); jump(top); begin(top); - line("if (!(" + em.cond(w.test) + ")) " + goTo(els)); + if (!alwaysTrue(w.test)) { + line("if (!(" + em.cond(w.test) + ")) " + goTo(els)); + } loops.add(new Loop(end, top, fins.size())); block(w.body); loops.remove(loops.size() - 1); @@ -476,7 +621,7 @@ private void forStmt(For f) { line(it + " = Py.iter(" + em.expr(f.iter) + ");"); jump(top); begin(top); - line("final Object " + x + " = " + it + ".next();"); + line("final Object " + x + " = " + (flat() ? "nextFlat(" + it + ")" : it + ".next()") + ";"); line("if (" + x + " == null) " + goTo(els)); } em.store(f.target, x, out, IND + 2); @@ -580,9 +725,9 @@ private void tryStmt(Try t) { if (h.name != null) { em.storeName(h.name, e + ".value", out, IND + 2); } - em.handlers.add(e); + em.handlers().add(e); block(h.body); - em.handlers.remove(em.handlers.size() - 1); + em.handlers().remove(em.handlers().size() - 1); if (h.name != null) { line(em.nameLvalue(h.name) + " = null;"); } diff --git a/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/GenTarget.java b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/GenTarget.java new file mode 100644 index 00000000000..ac551fd74de --- /dev/null +++ b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/GenTarget.java @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.python.transpiler.codegen; + +import com.codename1.python.transpiler.ast.Node; +import com.codename1.python.transpiler.ast.Node.Expr; +import com.codename1.python.transpiler.ast.Node.Stmt; +import java.util.List; + +/// What [GenLowering] asks of the emitter whose statements fill its states: +/// the generic [Emitter], or [TypedEmit] for a generator whose locals have +/// Java types. Values pass as Java expressions of type Object. +interface GenTarget { + /// Emits `s`, which cannot suspend, as Java statements. + void stmt(Stmt s, StringBuilder out, int ind); + + /// Stores `value` into the target `t`. + void store(Expr t, String value, StringBuilder out, int ind); + + /// Stores `value` into the name `n`. + void storeName(String n, String value, StringBuilder out, int ind); + + /// The Java lvalue that holds the name `n`. + String nameLvalue(String n); + + /// `e`, which cannot suspend, as a Java expression of type Object. + String expr(Expr e); + + /// `e` as a Java boolean expression: its truth. + String cond(Expr e); + + /// A fresh Java identifier starting with `prefix`. + String fresh(String prefix); + + /// The error for a construct the lowering cannot take. + RuntimeException unsupported(Node n, String what); + + /// The exceptions of the enclosing handlers, innermost last; a bare + /// `raise` re-raises the last. + List handlers(); +} diff --git a/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/ImmutableSlots.java b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/ImmutableSlots.java new file mode 100644 index 00000000000..2e2d747070c --- /dev/null +++ b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/ImmutableSlots.java @@ -0,0 +1,565 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.python.transpiler.codegen; + +import com.codename1.python.transpiler.api.PythonSyntaxError; +import com.codename1.python.transpiler.ast.Node; +import com.codename1.python.transpiler.ast.Node.AnnAssign; +import com.codename1.python.transpiler.ast.Node.Assign; +import com.codename1.python.transpiler.ast.Node.AugAssign; +import com.codename1.python.transpiler.ast.Node.Attribute; +import com.codename1.python.transpiler.ast.Node.Call; +import com.codename1.python.transpiler.ast.Node.ClassDef; +import com.codename1.python.transpiler.ast.Node.Comp; +import com.codename1.python.transpiler.ast.Node.Constant; +import com.codename1.python.transpiler.ast.Node.Expr; +import com.codename1.python.transpiler.ast.Node.ExprStmt; +import com.codename1.python.transpiler.ast.Node.For; +import com.codename1.python.transpiler.ast.Node.FunctionDef; +import com.codename1.python.transpiler.ast.Node.If; +import com.codename1.python.transpiler.ast.Node.Keyword; +import com.codename1.python.transpiler.ast.Node.Name; +import com.codename1.python.transpiler.ast.Node.Raise; +import com.codename1.python.transpiler.ast.Node.Stmt; +import com.codename1.python.transpiler.ast.Node.TupleExpr; +import com.codename1.python.transpiler.ast.Node.While; +import com.codename1.python.transpiler.parser.Parser; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.IdentityHashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/// Lowers soupsieve-style immutable slot classes at build time. +/// +/// ```python +/// class Immutable: +/// __slots__ = ('_hash',) +/// def __init__(self, **kwargs): +/// ... super().__setattr__(k, v) for every keyword, then _hash ... +/// def __setattr__(self, name, value): +/// raise AttributeError(...) +/// class SelectorTag(Immutable): +/// __slots__ = ("name", "prefix", "_hash") +/// def __init__(self, name, prefix): +/// super().__init__(name=name, prefix=prefix) +/// ``` +/// +/// The root stores keyword names through `__setattr__` and reads the slots +/// back with `getattr` over `__slots__` in `__eq__`, `__repr__` and the +/// pickle reducer: reflection, and the bound `__setattr__` leaves every +/// class without a layout. Here each subclass's `super().__init__(...)` +/// becomes the stores it makes, by name and in the call's order, followed by +/// `_hash` computed exactly as the root computes it; each subclass gains +/// `_cn1_names` and `_cn1_values`, which name and read its slots directly; +/// the root's `__eq__`, `__repr__` and the module's `getattr` over +/// `__slots__` read those instead; and the root's `__init__` and +/// `__setattr__` are dropped. +/// +/// Immutability is then the compiler's to enforce: an attribute store on +/// `self` in any method of these classes other than the generated +/// constructors, or a store anywhere of a slot name that no other class +/// stores as its own field, is a build error. +/// +/// Anything outside that shape leaves every class alone. +public final class ImmutableSlots { + private final List report = new ArrayList(); + + private ImmutableSlots() { + } + + /// Lowers the immutable slot classes among `trees` (by path) and answers + /// what it did. + public static List rewrite(Map trees) { + ImmutableSlots d = new ImmutableSlots(); + for (Map.Entry e : trees.entrySet()) { + if (e.getKey().endsWith(".py")) { + d.module(e.getKey(), e.getValue(), trees); + } + } + if (Boolean.getBoolean("cn1.python.immutable.report")) { + for (String r : d.report) { + System.err.println("immutable: " + r); //NOPMD SystemPrintln - opt-in diagnostics + } + } + return new ArrayList(d.report); + } + + private void module(String path, Node.Module m, Map trees) { + for (Stmt s : m.body) { + if (s instanceof ClassDef && isRoot((ClassDef) s)) { + lower(path, m, (ClassDef) s, trees); + return; + } + } + } + + private static boolean isRoot(ClassDef c) { + if (!c.bases.isEmpty() || !c.keywords.isEmpty() || !c.decorators.isEmpty()) { + return false; + } + List slots = slots(c); + if (slots == null || slots.size() != 1 || !"_hash".equals(slots.get(0))) { + return false; + } + FunctionDef set = method(c, "__setattr__"); + FunctionDef init = method(c, "__init__"); + return set != null && init != null && init.args.kwarg != null && init.args.positional.size() == 1 + && raisesOnly(set) && method(c, "__eq__") != null && method(c, "__repr__") != null; + } + + private static boolean raisesOnly(FunctionDef f) { + for (Stmt s : f.body) { + if (!(s instanceof Raise) && !(s instanceof ExprStmt && ((ExprStmt) s).value instanceof Constant)) { + return false; + } + } + return true; + } + + private void lower(String path, Node.Module rootModule, ClassDef root, Map trees) { + Map subs = new LinkedHashMap(); + Set subNames = new HashSet(); + for (Map.Entry e : trees.entrySet()) { + for (Stmt s : e.getValue().body) { + if (s instanceof ClassDef && extendsName((ClassDef) s, root.name)) { + subs.put((ClassDef) s, e.getKey()); + subNames.add(((ClassDef) s).name); + } + } + } + Map supers = new IdentityHashMap(); + for (Map.Entry e : subs.entrySet()) { + String why = shape(e.getKey(), supers); + if (why != null) { + report.add("left " + root.name + " alone: " + e.getKey().name + " " + why); + return; + } + } + for (Node.Module m : trees.values()) { + for (Stmt s : m.body) { + if (s instanceof ClassDef && !subs.containsKey(s)) { + for (String n : subNames) { + if (extendsName((ClassDef) s, n)) { + report.add("left " + root.name + " alone: " + ((ClassDef) s).name + " extends " + n); + return; + } + } + } + } + } + FunctionDef pickler = null; + int[] at = null; + for (Stmt s : rootModule.body) { + if (s instanceof FunctionDef) { + int[] where = slotsComp(((FunctionDef) s).body); + if (where.length > 0) { + if (pickler != null) { + report.add("left " + root.name + " alone: two module functions read __slots__"); + return; + } + pickler = (FunctionDef) s; + at = where; + } + } + } + Set slotNames = new HashSet(); + for (Map.Entry e : subs.entrySet()) { + ClassDef c = e.getKey(); + slotNames.addAll(slots(c)); + Call sup = supers.get(c); + FunctionDef init = method(c, "__init__"); + init.dataclassInit = true; + replaceSuper(init.body, sup, e.getValue()); + List names = slots(c); + names = names.subList(0, names.size() - 1); + StringBuilder b = new StringBuilder(); + b.append("def _cn1_names(self) -> tuple:\n return ("); + for (String n : names) { + b.append('\'').append(n).append("', "); + } + b.append(")\n"); + b.append("def _cn1_values(self) -> tuple:\n return ("); + for (String n : names) { + b.append("self.").append(n).append(", "); + } + b.append(")\n"); + Node.Module gen = Parser.parse(b.toString(), e.getValue()); + DataclassInit.atLine(gen, c.line); + c.body.addAll(gen.body); + } + rewriteRoot(path, root); + if (pickler != null) { + rewritePickler(path, pickler, at); + } + Set all = new HashSet(subs.keySet()); + all.add(root); + enforce(trees, all, slotNames); + report.add("lowered " + root.name + " and " + subs.size() + " subclasses"); + } + + private static boolean extendsName(ClassDef c, String name) { + if (c.bases.size() != 1) { + return false; + } + Expr b = c.bases.get(0); + return b instanceof Name && name.equals(((Name) b).id) + || b instanceof Attribute && name.equals(((Attribute) b).attr) && ((Attribute) b).value instanceof Name; + } + + /// Why `c` cannot be lowered, or null; records its `super().__init__`. + private static String shape(ClassDef c, Map supers) { + if (!c.keywords.isEmpty() || !c.decorators.isEmpty()) { + return "has class keywords or decorators"; + } + List s = slots(c); + if (s == null || s.isEmpty() || !"_hash".equals(s.get(s.size() - 1))) { + return "has no literal __slots__ ending in _hash"; + } + // Its own __repr__ is its own business; the root's reads nested + // instances through _cn1_names and _cn1_values either way. + if (method(c, "__setattr__") != null || method(c, "__eq__") != null || method(c, "__ne__") != null) { + return "overrides a lowered method"; + } + FunctionDef init = method(c, "__init__"); + if (init == null) { + return "has no __init__"; + } + Call found = null; + int count = 0; + for (Stmt st : init.body) { + if (st instanceof ExprStmt && isSuperInit(((ExprStmt) st).value)) { + found = (Call) ((ExprStmt) st).value; + count++; + } + } + if (count != 1 || !found.args.isEmpty()) { + return "does not call super().__init__ once with keywords"; + } + Set kw = new HashSet(); + for (Keyword k : found.keywords) { + if (k.arg == null || !kw.add(k.arg)) { + return "passes ** or a repeated keyword"; + } + } + if (!kw.equals(new HashSet(s.subList(0, s.size() - 1)))) { + return "passes keywords other than its slots"; + } + supers.put(c, found); + return null; + } + + private static boolean isSuperInit(Expr e) { + if (!(e instanceof Call) || !(((Call) e).func instanceof Attribute)) { + return false; + } + Attribute f = (Attribute) ((Call) e).func; + return "__init__".equals(f.attr) && f.value instanceof Call && ((Call) f.value).func instanceof Name + && "super".equals(((Name) ((Call) f.value).func).id) && ((Call) f.value).args.isEmpty(); + } + + /// The `super().__init__(k=v, ...)` statement becomes `self.k = v` for + /// each keyword, in order, then `_hash` over `(type(v), v, ...)` as the + /// root computed it. + private static void replaceSuper(List body, Call sup, String path) { + for (int i = 0; i < body.size(); i++) { + Stmt st = body.get(i); + if (st instanceof ExprStmt && ((ExprStmt) st).value == sup) { //NOPMD CompareObjectsWithEquals - this very call node + List out = new ArrayList(); + StringBuilder h = new StringBuilder("self._hash = hash(("); + for (Keyword k : sup.keywords) { + Node.Module one = Parser.parse("self." + k.arg + " = 0\n", path); + Assign a = (Assign) one.body.get(0); + Assign store = new Assign(a.targets, k.value); + DataclassInit.atLine(a.targets, st.line); + store.line = st.line; + out.add(store); + h.append("type(self.").append(k.arg).append("), self.").append(k.arg).append(", "); + } + h.append("))\n"); + Node.Module hm = Parser.parse(h.toString(), path); + DataclassInit.atLine(hm, st.line); + out.addAll(hm.body); + body.remove(i); + body.addAll(i, out); + return; + } + } + } + + private static final String EQ = "" + + "def __eq__(self, other: Any) -> bool:\n" + + " stack: list[tuple[Immutable, Any]] = [(self, other)]\n" + + " while stack:\n" + + " a, b = stack.pop()\n" + + " if a is b:\n" + + " continue\n" + + " if not isinstance(b, a.__base__()) or a._hash != b._hash:\n" + + " return False\n" + + " for x, y in zip(a._cn1_values(), b._cn1_values()):\n" + + " if isinstance(x, Immutable):\n" + + " stack.append((x, y))\n" + + " elif x.__class__ is tuple and y.__class__ is tuple:\n" + + " if len(x) != len(y):\n" + + " return False\n" + + " for i, j in zip(x, y):\n" + + " if isinstance(i, Immutable):\n" + + " stack.append((i, j))\n" + + " elif i != j:\n" + + " return False\n" + + " elif x != y:\n" + + " return False\n" + + " return True\n"; + + private static final String REPR = "" + + "def __repr__(self) -> str:\n" + + " output: list[str] = []\n" + + " stack: list[Any] = [self]\n" + + " while stack:\n" + + " item = stack.pop()\n" + + " if item.__class__ is str:\n" + + " output.append(item)\n" + + " elif isinstance(item, Immutable):\n" + + " stack.append(')')\n" + + " keys = item._cn1_names()\n" + + " values = item._cn1_values()\n" + + " for index in range(len(keys) - 1, -1, -1):\n" + + " stack.append(_repr_value(values[index]))\n" + + " stack.append(f'{keys[index]}=' if index == 0 else f', {keys[index]}=')\n" + + " stack.append(f'{item.__class__.__name__}(')\n" + + " else:\n" + + " stack.append(',)' if len(item) == 1 else ')')\n" + + " for index in range(len(item) - 1, -1, -1):\n" + + " stack.append(_repr_value(item[index]))\n" + + " if index:\n" + + " stack.append(', ')\n" + + " stack.append('(')\n" + + " return ''.join(output)\n" + + "def _cn1_names(self) -> tuple[str, ...]:\n" + + " return ()\n" + + "def _cn1_values(self) -> tuple[Any, ...]:\n" + + " return ()\n"; + + /// Drops the root's `__init__` and `__setattr__` and makes its `__eq__` + /// and `__repr__` read the slots through the per-class methods. They are + /// the root's own algorithms (an explicit stack, never recursion), with + /// `getattr` over `__slots__` replaced. + private static void rewriteRoot(String path, ClassDef root) { + String eq = EQ.replace("Immutable", root.name); + String repr = REPR.replace("Immutable", root.name); + for (int i = root.body.size() - 1; i >= 0; i--) { + Stmt s = root.body.get(i); + if (s instanceof FunctionDef) { + String n = ((FunctionDef) s).name; + if ("__init__".equals(n) || "__setattr__".equals(n)) { + root.body.remove(i); + } else if ("__eq__".equals(n) || "__repr__".equals(n)) { + Node.Module g = Parser.parse("__eq__".equals(n) ? eq : repr, path); + DataclassInit.atLine(g, s.line); + root.body.remove(i); + root.body.addAll(i, g.body); + } + } + } + } + + /// Where, under `body`, an assignment's value is a list comprehension + /// over `X.__slots__`: the path of statement indexes, or empty. + private static int[] slotsComp(List body) { + for (int i = 0; i < body.size(); i++) { + Stmt s = body.get(i); + if (s instanceof Assign && ((Assign) s).targets.size() == 1 && ((Assign) s).value instanceof Comp + && slotsOwner(((Assign) s).value) != null) { + return new int[] {i}; + } + for (List inner : blocks(s)) { + int[] r = slotsComp(inner); + if (r.length > 0) { + int[] p = new int[r.length + 1]; + p[0] = i; + System.arraycopy(r, 0, p, 1, r.length); + return p; + } + } + } + return new int[0]; + } + + private static List> blocks(Stmt s) { + List> r = new ArrayList>(); + if (s instanceof While) { + r.add(((While) s).body); + } else if (s instanceof If) { + r.add(((If) s).body); + r.add(((If) s).orelse); + } else if (s instanceof For) { + r.add(((For) s).body); + } + return r; + } + + /// The name `X` of an `X.__slots__` under `e`, or null. + private static String slotsOwner(Object e) { + if (e instanceof Attribute && "__slots__".equals(((Attribute) e).attr) && ((Attribute) e).value instanceof Name) { + return ((Name) ((Attribute) e).value).id; + } + String[] found = new String[1]; + Infer.children(e, x -> { + if (found[0] == null) { + found[0] = slotsOwner(x); + } + }); + return found[0]; + } + + /// `values = [getattr(obj, s) for s in obj.__slots__[:-1]]` becomes + /// `values = list(obj._cn1_values())`. + private static void rewritePickler(String path, FunctionDef f, int[] at) { + List body = f.body; + for (int k = 0; k < at.length - 1; k++) { + Stmt s = body.get(at[k]); + List> bs = blocks(s); + List next = null; + for (List b : bs) { + if (slotsComp(b).length > 0 && next == null) { + next = b; + } + } + body = next; + } + Assign a = (Assign) body.get(at[at.length - 1]); + String owner = slotsOwner(a.value); + Node.Module g = Parser.parse("_ = list(" + owner + "._cn1_values())\n", path); + Assign repl = new Assign(a.targets, ((Assign) g.body.get(0)).value); + DataclassInit.atLine(repl, a.line); + body.set(at[at.length - 1], repl); + } + + /// The build error for a store that would mutate an immutable instance. + private static void enforce(Map trees, Set classes, Set slotNames) { + Set foreignFields = new HashSet(); + for (Map.Entry e : trees.entrySet()) { + for (Stmt s : e.getValue().body) { + if (s instanceof ClassDef) { + if (classes.contains(s)) { + for (Stmt m : ((ClassDef) s).body) { + if (m instanceof FunctionDef && !((FunctionDef) m).dataclassInit) { + selfStores(e.getKey(), (FunctionDef) m); + } + } + } else { + Set own = new HashSet(); + WholeProgram.attrStores(s, own); + foreignFields.addAll(own); + } + } + } + } + for (Map.Entry e : trees.entrySet()) { + for (Stmt s : e.getValue().body) { + if (s instanceof ClassDef) { + continue; + } + anyStore(e.getKey(), s, slotNames, foreignFields); + } + for (Stmt s : e.getValue().body) { + if (s instanceof ClassDef && !classes.contains(s)) { + anyStore(e.getKey(), s, slotNames, foreignFields); + } + } + } + } + + private static void selfStores(String path, FunctionDef f) { + if (f.args.positional.isEmpty()) { + return; + } + String self = f.args.positional.get(0).name; + storesOn(path, f, self); + } + + private static void storesOn(String path, Object o, String self) { + Expr t = o instanceof Assign && ((Assign) o).targets.size() == 1 ? ((Assign) o).targets.get(0) + : o instanceof AugAssign ? ((AugAssign) o).target + : o instanceof AnnAssign ? ((AnnAssign) o).target : null; + if (t instanceof Attribute && ((Attribute) t).value instanceof Name && self.equals(((Name) ((Attribute) t).value).id)) { + throw new PythonSyntaxError(path, ((Node) o).line, 1, "store of '" + ((Attribute) t).attr + + "' on an immutable instance outside its constructor"); + } + if (o instanceof Call && ((Call) o).func instanceof Attribute + && ("__setattr__".equals(((Attribute) ((Call) o).func).attr) + || "__delattr__".equals(((Attribute) ((Call) o).func).attr))) { + throw new PythonSyntaxError(path, ((Node) o).line, 1, "__setattr__ on an immutable instance"); + } + Infer.children(o, x -> storesOn(path, x, self)); + } + + /// A store anywhere of a slot name that no other class stores as its + /// own: only an immutable instance can be its receiver. + private static void anyStore(String path, Stmt s, Set slotNames, Set foreignFields) { + Set out = new HashSet(); + WholeProgram.attrStores(s, out); + for (String n : out) { + if (slotNames.contains(n) && !foreignFields.contains(n)) { + throw new PythonSyntaxError(path, s.line, 1, "store of '" + n + + "', a field of an immutable class, outside its constructor"); + } + } + } + + private static FunctionDef method(ClassDef c, String name) { + for (Stmt s : c.body) { + if (s instanceof FunctionDef && name.equals(((FunctionDef) s).name)) { + return (FunctionDef) s; + } + } + return null; + } + + /// The literal `__slots__` of `c`, or null. + private static List slots(ClassDef c) { + for (Stmt s : c.body) { + Expr t = s instanceof Assign && ((Assign) s).targets.size() == 1 ? ((Assign) s).targets.get(0) + : s instanceof AnnAssign ? ((AnnAssign) s).target : null; + Expr v = s instanceof Assign ? ((Assign) s).value : s instanceof AnnAssign ? ((AnnAssign) s).value : null; + if (t instanceof Name && "__slots__".equals(((Name) t).id)) { + if (!(v instanceof TupleExpr)) { + return null; + } + List r = new ArrayList(); + for (Expr e : ((TupleExpr) v).elts) { + if (!(e instanceof Constant) || ((Constant) e).kind != Constant.Kind.STR) { + return null; + } + r.add(((Constant) e).text); + } + return r; + } + } + return null; + } +} diff --git a/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/Infer.java b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/Infer.java index fe8c392889f..b72e2caa28e 100644 --- a/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/Infer.java +++ b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/Infer.java @@ -34,31 +34,60 @@ import java.util.HashSet; import java.util.IdentityHashMap; import java.util.LinkedHashMap; +import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; -/// Whole-module type inference over a closed program. +/// Whole-module type inference, for every module of every program. /// -/// Runs only when `Closed` found nothing in the application that could -/// change a class, an instance's attributes or a module global behind the -/// compiler's back. Then every value that reaches a parameter, a field, a -/// list element or a global is one this pass sees, and the types it gives -/// are sound: typed code never needs to check them again, and a function -/// is entered typed after one check of its arguments at the door. +/// The transpiler compiles the whole application, so what other modules +/// do to this one is known: `WholeProgram` hands in the attribute names +/// stored from outside and whether the module's namespace is read as a +/// dict, and those names are left untyped. Every other value that reaches +/// a parameter, a field, a list element or a global is one this pass +/// sees, and the types it gives are sound: typed code never needs to +/// check them again, and a function is entered typed after one check of +/// its arguments at the door. /// /// It is a flow-insensitive fixpoint. Each round walks the whole module -- /// nested functions, lambdas and class bodies included, where names are -/// simply `DYN` -- joining the type of every stored value into where it is +/// simply `OBJECT` -- joining the type of every stored value into where it is /// stored: a local of a compiled function, a parameter at each call site /// that names its callee statically, a field, the elements of the lists /// created at an allocation site, a global. A value that reaches somewhere /// the pass cannot follow escapes: a function or class used as a value gets -/// `DYN` parameters, and a list that escapes gets `DYN` elements. +/// `OBJECT` parameters, and a list that escapes gets `OBJECT` elements. final class Infer { + /// `cn1.python.strict`: the closed-world build errors (a computed + /// attribute name, a class with no layout) fail the build; the property + /// only narrows them to some module prefixes. See [#strictErrors]. + static final String[] STRICT = strictPrefixes(System.getProperty("cn1.python.strict")); + + /// Strict mode is always on. The property only narrows the report to some modules while one is + /// being worked on; unset, every module of the program is held to it. + private static String[] strictPrefixes(String v) { + if (v == null || v.trim().isEmpty()) { + return new String[0]; + } + String[] s = v.split(","); + for (int i = 0; i < s.length; i++) { + s[i] = s[i].trim(); + } + return s; + } + + /// The Python line the pass is walking, for [#cause]. + private int line; /// Strict mode: the expressions that make untyped values from typed /// Strict mode: reflection found in this module (an attribute named by + /// a string the build cannot enumerate), reported by [#strictErrors]. + private final Set reflective = new LinkedHashSet(); + /// A function the pass types: a compiled method, or a plain function at /// the top of the module with a stable name. static final class Fn { + /// A method of an analysed class (Layouts#analysed): walked and + /// typed like any other, never emitted (see [Infer#emitFns]). + boolean analysisOnly; final FunctionDef def; /// The class, for a method. final Layouts.Cls cls; @@ -66,7 +95,23 @@ static final class Fn { final Ty[] params; final Map locals = new LinkedHashMap(); Ty ret = Ty.BOT; + /// The type a function that may return a guessed value (see + /// [Program#guessedReturns]) returns when every guess holds; its + /// `ret` is then an object, so that one that does not can return + /// too, and the caller takes the typed form back (TypedEmit). + Ty guessRet; + /// What iterating a call of this function gives, as far as its body + /// says: the values a generator yields, or the elements of the + /// generator expression a plain function returns (bs4's + /// `Tag.children`, `(x for x in self.contents)`). Only ever read as + /// a guess ([Infer#iterElem]): the generic code may hand the loop any + /// iterator, and every element is checked as it arrives. + Ty yields = Ty.BOT; boolean escapes; + /// A method of an open class: its `self` may be an instance of a + /// class the planner rejected, so `self` as a value is of no class + /// the pass can tell (see [Infer#selfRecv]). + boolean openSelf; Fn(FunctionDef def, Layouts.Cls cls) { this.def = def; @@ -76,6 +121,10 @@ static final class Fn { for (int i = 0; i < params.length; i++) { params[i] = Ty.BOT; } + if (def.scope.hasYield) { + // A call answers the generator object, whatever the body returns. + ret = Ty.OBJECT; + } } Ty param(String n) { @@ -84,8 +133,722 @@ Ty param(String n) { } } - final Layouts layouts; + /// What every module's pass shares: one heap for the whole program. A + /// field, a list site or a parameter has one type, whichever module + /// stores into it or calls it, and the fixpoint is over all of them. + /// One place where reached code reads or writes an attribute the build + /// cannot name on an object it cannot tell the class of. + static final class Problem { + final String module; + final int line; + /// `function` or `Class.method`, or null at module level. + final String function; + final String what; + /// Whether it is a store: that costs typed fields, where a read + /// only makes more functions reachable. + final boolean store; + + Problem(String module, int line, String function, String what) { + this.module = module; + this.line = line; + this.function = function; + this.what = what; + this.store = !what.startsWith("reads"); + } + } + + static final boolean WHY_LIVE = System.getProperty("cn1.python.whyLive") != null; + + static final class Program { + /// Every compiled class a `CLS` type has named, by id (see + /// [Ty#cls]). + final List clsById = new ArrayList(); + final Map clsId = new IdentityHashMap(); + /// Every compiled method a `METH` type has named, by id (see + /// [Ty#meth]). + final List methById = new ArrayList(); + /// The functions a `FUNC` type names, by id. + final List funcById = new ArrayList(); + final Map funcId = new IdentityHashMap(); + /// Each closure variable's type, by the scope that owns it: every + /// store to it, from that scope or a function nested in it, joins + /// here, and every read answers it. + final Map> cells = new IdentityHashMap>(); + /// Container sites a value went into that the pass does not keep + /// (see [#siteJoin]): what is read there may be anything. + final Set lostSites = new HashSet(); + /// What a class body binds to each name, by class scope: the + /// functions `getattr` finds there ([#methodsNamed]). A name not + /// here yet has not been walked. + final Map> classVals = new IdentityHashMap>(); + private Map fnByScope; + private int fnByScopeSize = -1; + + /// The function whose own scope is `sc`, or null when it has none. + Fn fnOf(Scope sc) { + if (fnByScopeSize != fns.size()) { + fnByScope = new IdentityHashMap(); + for (Fn f : fns.values()) { + fnByScope.put(f.def.scope, f); + } + fnByScopeSize = fns.size(); + } + return fnByScope.get(sc); + } + final Map methId = new IdentityHashMap(); + /// Dotted module name -> its view. + final Map modules = new LinkedHashMap(); + /// See [Infer#registeredNames]; null until first asked. + Set registered; + final Map fns = new IdentityHashMap(); + /// The methods of [#fns] by name, for [#escapeMethods], which runs + /// per attribute read; rebuilt when [#fns], which only grows, has. + private final Map> methodsByName = new HashMap>(); + private int methodsIndexed = -1; + + List methodsNamed(String name) { + if (methodsIndexed != fns.size()) { + methodsByName.clear(); + for (Fn f : fns.values()) { + if (f.cls != null) { + methodsByName.computeIfAbsent(f.def.name, x -> new ArrayList()).add(f); + } + } + methodsIndexed = fns.size(); + } + List l = methodsByName.get(name); + return l == null ? java.util.Collections.emptyList() : l; + } /// `super().m(...)` calls resolved to the one method they run + /// ([#superTarget]), for the emitter to call directly. + final Map superCalls = new IdentityHashMap(); + /// The method names [#escapeMethods] let go: a method of that name + /// escapes when its class becomes live. + final Set escapedNames = new HashSet(); + /// The names of the program's functions and classes, at any depth, + /// and whether a class of it answers attributes it does not define + /// (a `__getattr__` that returns): see [Infer#closedName]. Null + /// until first asked; the set of functions is fixed by then. + Set defNames; + /// The `__getattr__`/`__getattribute__` methods that answer a name + /// with something other than the same name read off another object. + List answering; + /// The calls typed through a method slot (see [Infer#closedName]): + /// their value is what the program's methods of the name return. + final Set slotCalls = java.util.Collections.newSetFromMap(new IdentityHashMap()); + /// Classes the program constructs, or calls a method on through the + /// class itself (a classmethod's `cls(...)`): see [#classLive]. + final Set constructed = java.util.Collections.newSetFromMap( + new IdentityHashMap()); + /// The module each compiled class and each typed function is in. + final Map home = new IdentityHashMap(); + final Map fnHome = new IdentityHashMap(); + /// Field name -> every compiled class of the program declaring it. + final Map> fieldOwners = new HashMap>(); + final Map> fields = new LinkedHashMap>(); + final Map> definite = new HashMap>(); + final Set open = new HashSet(); + /// Every name the body of a class the planner rejected binds, by + /// each compiled class it derives from (and their ancestors): on an + /// instance of such an open class the name may answer what the + /// rejected class defines instead of the compiled one. Kept per + /// class because one program-wide set made bs4's + /// `self.filter(...)` generic -- and every field of SoupStrainer + /// untyped -- when some unrelated rejected class defined `filter`. + final Map> rejectedNames = new HashMap>(); + /// The names of a rejected class whose base names no class the pass + /// can find: it may derive from any open class. + final Set rejectedAnywhere = new HashSet(); + final Map siteOf = new IdentityHashMap(); + /// The sites the generic versions' walks give a function's private + /// lists (see Infer#privateLiterals), apart from the typed ones'. + final Map shadowSiteOf = new IdentityHashMap(); + /// The literals of lists no code but their own function's sees, and + /// the tuple literals put in them (Infer#privateLiterals). + Set privateLits; + /// What calls from generic bodies pass a function whose guard they + /// miss, by parameter: its generic version is walked with these + /// (see [#genericView]) instead of the arguments being let go. + final Map missed = new IdentityHashMap(); + final List siteElem = new ArrayList(); + final List siteKey = new ArrayList(); + final Set escapedSites = new HashSet(); + final Map siteSlots = new HashMap(); + final Set unslotted = new HashSet(); + final Map siteRet = new HashMap(); + /// Calls of a known function that go through its door (`callFn`). + final Set doors = new HashSet(); + final Map generic = new IdentityHashMap(); + /// The compiled functions something in the program reaches: by a + /// direct call, as a value, or by a name the rest of the program + /// or the runtime may look up. The body of any other is never + /// walked -- what it would store or call does not happen -- and + /// never emitted (see [Infer#removed]). + /// Method names read off a class nobody can name [#anyClassAttr]: + /// each loose class's methods of the name escape, including a class + /// loosened later [#loosen]. + final Set anyClassNames = new HashSet(); + final Set reached = java.util.Collections.newSetFromMap(new IdentityHashMap()); + /// Every name the Java side of the program may look up in a + /// module or on an instance: the identifiers among the strings of + /// the runtime's classes. Null when the runtime was not at hand + /// to read, and then every function counts as reached. + Set runtimeNames; + /// Functions the build was told to keep although nothing in the + /// Python sources reaches them: `module.function` and + /// `module.Class.method`. + final Set keep = new HashSet(); + /// What reached code does that the build cannot hold to the types + /// it computed, by the place it happens: each is a build error + /// unless the function is replaced (see [Problem]). + final Map problems = new IdentityHashMap(); + /// The classes an instance of which is held somewhere as a value + /// of no known class, with the classes related to them (see + /// [Infer#loosen]); and the ones the first set was built from. + final Set loose = java.util.Collections.newSetFromMap(new IdentityHashMap()); + final Set looseRoots = java.util.Collections.newSetFromMap(new IdentityHashMap()); + /// Classes whose hierarchy [Infer#loosen] made loose. + final Set loosened = java.util.Collections.newSetFromMap(new IdentityHashMap()); + /// The modules held somewhere as a value, and whether reached code + /// can get at any module (`sys.modules`). + final Set looseModules = java.util.Collections.newSetFromMap(new IdentityHashMap()); + boolean allModulesLoose; + /// Whether reached code reads an attribute by a computed name from + /// an object of no known class: a method of a loose class, or a + /// function of a loose module, may be what it finds and calls. + boolean anyRead; + /// Whether reached code takes the class of an object of no known + /// class (`type(x)`, `x.__class__`) to do more with than name or + /// compare it: any loose class may then be constructed there. + boolean anyClassOf; + /// Classes an instance store with a computed name (`setattr`, an + /// attribute dict handed on) may reach, and whether one was on an + /// object of no class the build can tell -- which, as for the + /// field types, reaches the loose classes. For [#classConstant]. + final Set computedOn = new HashSet(); + boolean computedOnAny; + /// The scopes of methods of classes without a compiled layout: + /// their first parameter is never a compiled instance. + final Set plainSelf = java.util.Collections.newSetFromMap(new IdentityHashMap()); + /// The guarded fields, per class: a store the pass cannot type reaches + /// them -- a value nothing knows, a receiver of no known class, a + /// computed name, the generic body of a function -- or a store of a + /// guessed value (see [Infer#guessed]). Such a store does not widen + /// the field: it keeps what the typed stores put there, as a guess, + /// in a typed slot beside an object that replaces it when a value + /// arrives that does not fit (TypedEmit). Reads of it are guessed. + final Map> unknownStores = new IdentityHashMap>(); + /// The expressions whose value is a guess: the typed value the pass + /// gives them holds only while every guessed value they are made of + /// fits its guess. Typed code keeps such a value as its typed form + /// beside the object that replaces it, and computes it twice, the + /// typed way and the generic way, picking by the guesses it read. + final Set guessedExprs = java.util.Collections.newSetFromMap(new IdentityHashMap()); + /// Locals that may be bound to a guessed value, per function. + final Map> guessedLocals = new IdentityHashMap>(); + /// Functions that may return a guessed value. + final Set guessedReturns = java.util.Collections.newSetFromMap(new IdentityHashMap()); + /// The parameters a call passed a value of no evidence (Ty#UNSEEN): + /// one the source says takes several kinds ([#declared]) is then + /// held as an object, since what that call passes is not known. + final Map unseenArgs = new IdentityHashMap(); + + /// The functions a guarded call passed a value of no known type: + /// called, though no parameter has a type from it. + final Set objectArgs = java.util.Collections.newSetFromMap(new IdentityHashMap()); + /// Module globals that may be bound to a guessed value, per module. + final Map> guessedGlobals = new IdentityHashMap>(); + /// List, tuple and dict sites whose elements may be guessed values: + /// a guessed value went in, or a guessed value of the site was read + /// (a guarded field may hold a list of any site that passes for it). + final Set guessedSites = new HashSet(); + /// The scopes of methods of compiled classes that the pass walks + /// without a typed view (`**kwargs`, too many parameters...), with + /// their class: the first parameter is an instance of it or of a + /// subclass, as it is for a typed method, so a store through it + /// reaches that hierarchy's fields and not every field of the name. + final Map untypedSelf = new IdentityHashMap(); + final Map> compCells = new IdentityHashMap>(); + boolean allListsEscape; + /// The modules whose bodies run: the main module, what the Java + /// side imports by name, and every module reached code imports. + /// Only their bodies are walked and only they are emitted; the + /// rest of the sources never run (see [#markLive]). With + /// `allLive` set (a library build, or no main module) every + /// module counts. + final Set live = java.util.Collections.newSetFromMap(new IdentityHashMap()); + boolean allLive = true; + /// Set when every module of the program is in it ([WholeProgram]): + /// a store from another module is then walked here like any other + /// and reaches the field through [Infer#storeField], so a field + /// name another module stores needs no blanket widening. + boolean closed; + /// Set once a module that imports by a computed name is live: from + /// then on a string of a live module that names a module, or a + /// constant prefix of a formatted one, makes it live too. + boolean computedImports; + /// What made the next module live, for `-Dcn1.python.whyLive`. + String cause = "root"; + + /// Makes module `name` and each package above it live. + void markLive(String name) { + if (name == null) { + return; + } + int from = 0; + while (true) { + int dot = name.indexOf('.', from); + Infer m = modules.get(dot < 0 ? name : name.substring(0, dot)); + if (m != null && live.add(m)) { + changed = true; + if (WHY_LIVE) { + System.err.println("live " + m.moduleName + " <- " + cause); + } + if ("importlib".equals(m.moduleName) || "_cn1imp".equals(m.moduleName)) { + computedImports = true; + for (Infer l : new ArrayList(live)) { + l.scanStrings(); + } + } else if (computedImports) { + m.scanStrings(); + } + } + if (dot < 0) { + return; + } + from = dot + 1; + } + } + + /// Makes live every module whose name starts with `prefix`. + void markPrefix(String prefix) { + for (String n : new ArrayList(modules.keySet())) { + if (n.startsWith(prefix)) { + markLive(n); + } + } + } + + boolean isLive(Infer m) { + return allLive || live.contains(m); + } + + /// Methods taken out of their class's typed dispatch because a store + /// reaches them ([#patchedFound]), by class: shared by every run of + /// the program, and only ever grown. + Map> patched = new IdentityHashMap>(); + /// Attribute names stored on a value of no known class. + final Set dynStored = new HashSet(); + /// Names a setattr takes from a known set of strings that is no + /// literal argument (a loop over a tuple of names). + final Set computedStoredNames = new HashSet(); + /// Attribute names stored on an instance of a known class, by class. + final Map> clsStored = new IdentityHashMap>(); + + /// Every typed method a store of this run may replace: a store on a + /// value of no known class reaches the classes whose instances or + /// class object went where the pass does not follow (the loose + /// ones; [Infer#escapeClass] loosens a class whose object escapes); + /// one on an instance of a known class reaches that class, its + /// ancestors and the classes below it. + Map> patchedFound() { + Map> r = new IdentityHashMap>(); + for (Map.Entry h : home.entrySet()) { + Layouts.Cls k = h.getKey(); + for (String m : k.typable.keySet()) { + // Only a name the program stores by name somewhere but + // on its own `self` can be replaced at all: that test + // reads the source, this one the types, and a store + // that reaches the method passes both. + boolean named = h.getValue().facts.patched(m) || computedStoredNames.contains(m); + boolean hit = named && loose.contains(k) && dynStored.contains(m); + for (Map.Entry> e : clsStored.entrySet()) { + if (hit) { + break; + } + hit = e.getValue().contains(m) && named + && (isSelfOrAncestor(e.getKey(), k) || isSelfOrAncestor(k, e.getKey())); + } + if (hit) { + Set s = r.get(k.def); + if (s == null) { + s = new HashSet(); + r.put(k.def, s); + } + s.add(m); + } + } + } + return r; + } + + /// Adds what this run found to [#patched]; whether any of it is new. + boolean morePatched() { + boolean grew = false; + for (Map.Entry> e : patchedFound().entrySet()) { + Set s = patched.get(e.getKey()); + if (s == null) { + s = new HashSet(); + patched.put(e.getKey(), s); + } + grew |= s.addAll(e.getValue()); + } + return grew; + } + + /// A program over the same modules, as they were entered, to run + /// again with [#patched] taken out. + Program fresh() { + Program n = new Program(); + n.closed = closed; + n.runtimeNames = runtimeNames; + n.keep.addAll(keep); + n.patched = patched; + n.allLive = allLive; + for (Infer in : modules.values()) { + Infer c = n.add(in.moduleName, in.pkg, in.body, in.initialLayouts, in.moduleScope, in.facts); + c.replanner = in.replanner; + } + if (!allLive) { + for (Infer in : live) { + n.live.add(n.modules.get(in.moduleName)); + } + } + return n; + } + + boolean changed; + /// Set once the fixpoint holds: the emitters then only read the + /// result (see [Infer#escape]). + boolean done; + int rounds; + + /// Adds a module; every module is added before [#run]. + Infer add(String name, boolean pkg, List body, Layouts layouts, Scope moduleScope, + WholeProgram.Module facts) { + Infer in = new Infer(this, name, pkg, body, layouts, moduleScope, facts); + modules.put(name, in); + return in; + } + + /// Compiled class -> the compiled classes of the whole program below + /// it, in module and plan order; built on first use, once every + /// module is collected. + private Map> below; + + private static boolean javaBelow(Layouts.Cls c, Layouts.Cls k) { + for (Layouts.Cls d = c; d != null; d = d.parent) { + if (d == k) { //NOPMD CompareObjectsWithEquals - identity is meant + return true; + } + } + return false; + } + + List below(Layouts.Cls k) { + if (below == null) { + below = new IdentityHashMap>(); + for (Infer in : modules.values()) { + for (Layouts.Cls c : in.layouts.all().values()) { + // Above c: its Java chain, and every class merged + // into c or a class of that chain + // (Layouts#mergeExtras) with its own chain -- typed + // code of a merged class runs over c's instances. + Set above = java.util.Collections.newSetFromMap( + new IdentityHashMap()); + List todo = new ArrayList(); + for (Layouts.Cls d = c; d != null; d = d.parent) { + todo.addAll(d.mixedFrom); + above.add(d); + } + while (!todo.isEmpty()) { + Layouts.Cls x = todo.remove(todo.size() - 1); + for (Layouts.Cls d = x; d != null; d = d.parent) { + if (above.add(d)) { + todo.addAll(d.mixedFrom); + } + } + } + above.remove(c); + for (Layouts.Cls a : above) { + List l = below.get(a); + if (l == null) { + l = new ArrayList(); + below.put(a, l); + } + l.add(c); + } + } + } + } + List l = below.get(k); + return l == null ? java.util.Collections.emptyList() : l; + } + + /// Plans again every module with a class whose base is a compiled + /// class of another module, so that class is compiled as that + /// class's subclass ([Layouts#plan]). A base must be final before + /// a class extends it, so modules go in the order their bases + /// allow; a module in a cycle of such bases takes what is final by + /// then, and a base that is not stays generic, as before. + private void adoptForeignBases() { + Map byLayouts = new IdentityHashMap(); + List pending = new ArrayList(); + Map> excluded = new IdentityHashMap>(); + Set mixing = java.util.Collections.newSetFromMap(new IdentityHashMap()); + Set mixins = foreignMixins(excluded, mixing); + for (Infer in : modules.values()) { + byLayouts.put(in.layouts, in); + if (in.replanner != null && (in.mayExtendForeign() || excluded.containsKey(in) || mixing.contains(in))) { + pending.add(in); + } + } + Set waiting = java.util.Collections.newSetFromMap(new IdentityHashMap()); + waiting.addAll(pending); + boolean progress = true; + while (!pending.isEmpty()) { + boolean force = !progress; + progress = false; + for (java.util.Iterator it = pending.iterator(); it.hasNext();) { + Infer in = it.next(); + if (!force && in.waitsOn(waiting)) { + continue; + } + Layouts before = in.layouts; + Set mine = excluded.get(in); + Layouts after = in.replanner.plan(b -> { + Layouts.Cls k = in.foreignClass(b); + Infer h = k == null ? null : byLayouts.get(k.home); + return h == null || waiting.contains(h) ? null : k; + }, mine == null ? java.util.Collections.emptySet() : mine, b -> { + ClassDef m = in.foreignClassDef(b); + return m != null && mixins.contains(m) ? m : null; + }); + byLayouts.remove(before); + byLayouts.put(after, in); + in.layouts = after; + // The classes are new objects: what was below the old ones + // is asked again. + below = null; + waiting.remove(in); + it.remove(); + progress = true; + if (force) { + // One module of the cycle planned with what is final + // is enough to break it; the rest wait again for + // the bases that plan just made final. + break; + } + } + } + } + + /// The classes mixed in, as a later base, by a class of another + /// module, and fit to stay uncompiled under it + /// ([Layouts#foreignMixin]); `excluded` gets each one's name under + /// its module and `mixing` every module with a class mixing one in. + /// A class any module also uses as a first base keeps its compiled + /// layout: its subclasses extend it. + private Set foreignMixins(Map> excluded, Set mixing) { + Set superNames = new HashSet(); + Set first = java.util.Collections.newSetFromMap(new IdentityHashMap()); + for (Infer in : modules.values()) { + Layouts.superAttrs(in.body, superNames); + for (Stmt s : in.body) { + if (s instanceof ClassDef && !((ClassDef) s).bases.isEmpty()) { + Expr b0 = ((ClassDef) s).bases.get(0); + ClassDef d = b0 instanceof Name ? Layouts.classNamed(in.body, ((Name) b0).id) : null; + if (d == null) { + d = in.foreignClassDef(b0); + } + if (d != null) { + first.add(d); + } + } + } + } + Set r = java.util.Collections.newSetFromMap(new IdentityHashMap()); + for (Infer in : modules.values()) { + for (Stmt s : in.body) { + if (!(s instanceof ClassDef)) { + continue; + } + List bases = ((ClassDef) s).bases; + for (int i = 1; i < bases.size(); i++) { + Expr b = bases.get(i); + if (b instanceof Name && Layouts.classNamed(in.body, ((Name) b).id) != null) { + continue; + } + ClassDef m = in.foreignClassDef(b); + Infer h = in.classHome(b); + if (m == null || h == null || h == in || h.replanner == null || first.contains(m) //NOPMD CompareObjectsWithEquals - identity is meant + || !Layouts.foreignMixin(m, superNames)) { + continue; + } + r.add(m); + excluded.computeIfAbsent(h, x -> new HashSet()).add(m.name); + mixing.add(in); + } + } + } + return r; + } + + /// Runs the pass over every module, to the fixpoint. The types only + /// ever widen and there are finitely many, so it ends; the bound is + /// there for a fault in the pass, which is reported, never worked + /// around by leaving the program untyped. + void run() { + for (Infer in : modules.values()) { + in.countGlobals(in.body); + } + for (Infer in : modules.values()) { + in.bindImports(); + } + adoptForeignBases(); + for (Infer in : modules.values()) { + in.collect(in.body); + } + for (Infer in : modules.values()) { + in.markOpenForeign(in.body); + } + // A method of an open class also runs for instances of a class + // the planner rejected, whose `self` is no instance of a + // compiled class: its stores of `self` hold that, so `self` is + // typed as what it may be. (The typed copy's entry admits only + // the compiled class, but the generic copy stores too.) + for (Fn f : fns.values()) { + if (f.cls != null && open.contains(f.cls) && f.params.length > 0) { + f.openSelf = true; + } + } + // A method of a class merged into others' layouts + // (Layouts#mergeExtras) runs over their instances too, which + // are no Java subclass of it: its `self` is the union of the + // class and every class that merges it (below() counts them), + // whichever path enters it -- a typed call, or its door from a + // computed attribute name. + for (Fn f : fns.values()) { + if (f.cls == null || f.params.length == 0 || f.params[0].k != Ty.K.INST || f.params[0].cls != f.cls) { //NOPMD CompareObjectsWithEquals - identity is meant + continue; + } + // A Java subclass is already an instance of f.cls; joining it + // would only widen a precise `self` into a union and cost + // every typed path below. Only a class that merges f.cls + // without extending it is added. + Ty self = f.params[0]; + boolean merged = false; + for (Layouts.Cls c : below(f.cls)) { + if (!javaBelow(c, f.cls)) { + self = Ty.join(self, Ty.inst(c, false)); + merged = true; + } + } + if (merged) { + f.params[0] = self; + } + } + // An analysed class was refused a layout for what makes its + // dispatch dynamic (a metaclass, a decorator, a builtin base): its + // methods are run from where the analysis cannot see, so each is + // entered as by an unknown caller. Their bodies are still typed. + // A nested function or a lambda is analysisOnly too, but is + // entered only through the values the pass follows. + for (Fn f : new ArrayList(fns.values())) { + if (f.analysisOnly && f.cls != null) { + fnHome.get(f).escapeFn(f); + } + } + for (rounds = 0; rounds < 2000; rounds++) { + changed = false; + for (Infer in : new ArrayList(modules.values())) { + if (isLive(in)) { + in.walkBlock(in.body, null, in.moduleScope); + in.unify(); + } + } + if (computedImports) { + for (Infer l : new ArrayList(live)) { + l.scanStrings(); + } + } + if (!modules.isEmpty()) { + modules.values().iterator().next().sweep(); + } + if (!escapedNames.isEmpty() && !modules.isEmpty()) { + modules.values().iterator().next().deadMethods(); + } + // What a function entered from an unseen caller returns goes + // back to that caller: a function it returns is called there. + // A call the pass walks (a duck call by the same name) joins + // the result where it is made instead, and a join that + // loses it escapes it there (see [#mix]). + for (Fn f : new ArrayList(fns.values())) { + if (f.ret != null && fnHome.get(f).unseenCaller(f)) { + fnHome.get(f).escapeFuncs(f.ret); + } + } + if (!changed) { + for (Infer in : modules.values()) { + if (isLive(in)) { + in.uncalled(); + } + } + } + if (!changed) { + done = true; + for (Fn f : guessedReturns) { + if (f.ret.k != Ty.K.INT && guessable(f.ret)) { + f.guessRet = f.ret; + f.ret = Ty.OBJECT; + } + } + if (System.getProperty("cn1.python.dumpProblems") != null) { + for (Problem q : problems.values()) { + System.err.println("problem " + q.module + ":" + q.line + " " + q.function + ": " + q.what); + } + System.err.println("live " + (allLive ? modules.size() : live.size()) + " of " + modules.size() + " modules"); + System.err.println("reached " + reached.size() + " of " + fns.size() + " functions; loose " + loose.size() + " of " + home.size() + " classes, " + looseModules.size() + " modules"); + } + for (Infer in : modules.values()) { + in.localize(); + } + return; + } + } + throw new IllegalStateException("the Python type inference did not settle after " + rounds + + " rounds; this is a fault in the transpiler"); + } + } + + final Program p; + final String moduleName; + /// Whether the module is a package's `__init__`. + final boolean pkg; + final List body; + Layouts layouts; + /// `k` and every compiled class of the program below it. + List selfAndBelow(Layouts.Cls k) { + List r = new ArrayList(); + r.add(k); + r.addAll(p.below(k)); + return r; + } + + /// Plans the module's layouts again with the compiled classes of other + /// modules its classes may extend (set by the emitter that planned + /// them); null when the module cannot be planned again. + Replanner replanner; + + /// Plans a module again: `foreignBase` and `foreignMixin` resolve a base + /// expression to a compiled class or a mixed-in class of another module + /// (or null), and `excluded` names the module's own classes another + /// module mixes in. See [Layouts#plan]. + interface Replanner { + Layouts plan(java.util.function.Function foreignBase, Set excluded, + java.util.function.Function foreignMixin); + } final Scope moduleScope; + /// This module's own typed functions; `p.fns` has every module's. final Map fns = new LinkedHashMap(); /// Stable global name -> the function or class it is bound to, once. final Map globalFns = new HashMap(); @@ -93,12 +856,37 @@ Ty param(String n) { /// The type a call of an expression function (see `exprBody`) has at /// that call site, from the argument types there; where it is narrower /// than the function's own return type, typed code relabels the result. - final Map siteRet = new HashMap(); + final Map siteRet; + final Set doors; /// Globals bound once, by `import math`: calls of its functions on /// numbers are typed (see `MATH_FNS`) and run as `PyMath` directly. final Set mathNames = new HashSet(); /// The globals only `import struct` binds. final Set structNames = new HashSet(); + /// Global names bound by `import` to a module of [#NATIVE_RET], to the + /// module's dotted name. + final Map nativeMods = new HashMap(); + /// Calls of [#NATIVE_RET] functions and what each answers, as the last + /// pass typed them (TypedEmit reads it). + final Map nativeCalls = new IdentityHashMap(); + /// What library functions answer, by dotted name: the runtime's own + /// (StdModules) and the stdlib's path and environment helpers. The + /// value is the type when every argument is a `str` (the functions + /// that take one); a call with any other argument stays untyped. + static final Map NATIVE_RET = new HashMap(); + static { + for (String f : new String[] {"perf_counter", "time", "monotonic", "process_time"}) { + NATIVE_RET.put("time." + f, Ty.FLOAT); + } + String[] paths = {"join", "basename", "dirname", "abspath", "normpath", "expanduser", "realpath", "normcase"}; + for (String f : paths) { + NATIVE_RET.put("os.path." + f, Ty.STR); + } + NATIVE_RET.put("os.getcwd", Ty.STR); + // One argument: the value or None; a str default: always a str. + NATIVE_RET.put("os.environ.get", Ty.STR.orNone()); + NATIVE_RET.put("os.getenv", Ty.STR.orNone()); + } /// `math` functions typed code calls, with their arity. static final Map MATH_FNS = new HashMap(); /// `math` constants, all floats. @@ -117,1642 +905,11559 @@ Ty param(String n) { } final Map globals = new HashMap(); /// Field name -> type, per declaring class. - final Map> fields = new LinkedHashMap>(); + final Map> fields; /// Fields every instance has set once its `__init__` returned. - final Map> definite = new HashMap>(); + final Map> definite; /// Classes something the pass cannot see may subclass or patch. - final Set open = new HashSet(); - final Map siteOf = new IdentityHashMap(); - final List siteElem = new ArrayList(); - final Set escapedSites = new HashSet(); - boolean allListsEscape; + final Set open; + final Map siteOf; + final List siteElem; + /// The keys a dict site holds; `siteElem` holds its values. + final List siteKey; + final Set escapedSites; + /// The type of each position of a tuple or list display, by allocation + /// site (see [#slot]). A tuple's never change once made; a list's hold + /// only while nothing reorders or resizes it -- anything but a store at + /// a constant index puts its site in [#unslotted]. + final Map siteSlots; + final Set unslotted; - private boolean changed; private final Map moduleBindings = new HashMap(); - private Infer(Layouts layouts, Scope moduleScope) { + private final WholeProgram.Module facts; + + /// The plan the module was entered with, before a base in another + /// module replanned it: what a run again starts from ([Program#fresh]). + private final Layouts initialLayouts; + + private Infer(Program p, String moduleName, boolean pkg, List body, Layouts layouts, + Scope moduleScope, WholeProgram.Module facts) { + this.p = p; + this.moduleName = moduleName; + this.pkg = pkg; + this.body = body; this.layouts = layouts; + this.initialLayouts = layouts; this.moduleScope = moduleScope; + this.facts = facts; + this.siteRet = p.siteRet; + this.doors = p.doors; + this.fields = p.fields; + this.definite = p.definite; + this.open = p.open; + this.siteOf = p.siteOf; + this.siteElem = p.siteElem; + this.siteKey = p.siteKey; + this.escapedSites = p.escapedSites; + this.siteSlots = p.siteSlots; + this.unslotted = p.unslotted; + this.generic = p.generic; + this.compCells = p.compCells; + } + + /// Infers one module on its own: a program of that module alone. + static Infer run(List body, Layouts layouts, Scope moduleScope, WholeProgram.Module facts) { + Program p = new Program(); + Infer in = p.add("", false, body, layouts, moduleScope, facts); + p.run(); + return in; } - /// Infers the module, or returns null when it gives up (no fixpoint). - static Infer run(List body, Layouts layouts, Scope moduleScope) { - Infer in = new Infer(layouts, moduleScope); - in.collect(body); - for (int round = 0; round < 60; round++) { - in.changed = false; - in.walkBlock(body, null, moduleScope); - in.unify(); - if (!in.changed) { - return in; + /// Gives a type to every parameter no call in the module reaches. The + /// function is still called: from another module, or through a value. + /// Those calls enter through the guard that checks every argument + /// (TypedEmit.entry), which is what makes a parameter's type sound + /// whoever calls -- but only a parameter that has a type is checked, so + /// one left without would take whatever arrives as whatever its uses + /// went on to assume. + private void uncalled() { + for (Fn f : fns.values()) { + if (p.closed && f.cls != null && !f.escapes && !f.openSelf && !classLive(f.cls)) { + // A method of a class no instance of which can exist, in a + // program nothing outside extends: it never runs. Walking + // it as entered by anyone let bs4's never-built + // BeautifulStoneSoup loosen BeautifulSoup through its + // `super().__init__(*args, **kwargs)`. + continue; + } + if (p.closed && f.cls != null && !f.escapes && !f.openSelf && !p.loose.contains(f.cls) + && !open.contains(f.cls) && noCallReached(f) && f.def.decorators.isEmpty()) { + // A method nothing calls, of a class whose every instance + // the pass follows: a call of it on one would be seen, and + // one through a value or by the runtime escapes it. It + // never runs. Walked as entered by anyone, warnings' + // `deprecated.__call__` read `arg.__init__` off an untyped + // `arg` and every `__init__` of the program lost its types. + continue; + } + for (int i = f.cls != null ? 1 : 0; i < f.params.length; i++) { + if (f.params[i].k == Ty.K.BOT) { + Ty pin = pin(f, i); + f.params[i] = joinInto(f.params[i], seed(f, i, pin)); + } else if (!f.params[i].wide() && widen(f, i)) { + f.params[i] = joinInto(f.params[i], Ty.OBJECT); + } } } - return null; } - // ---- setup ----------------------------------------------------------- + /// Whether no call has reached `f`: a parameter past the receiver, and + /// every such one still without a type. + private boolean noCallReached(Fn f) { + if (f.params.length < 2 || p.unseenArgs.containsKey(f) || p.objectArgs.contains(f)) { + // A call passing values of no known type reached it. + return false; + } + if (f.params.length < 2) { + return false; + } + for (int i = 1; i < f.params.length; i++) { + if (f.params[i].k != Ty.K.BOT) { + return false; + } + } + return true; + } - private void collect(List body) { - countBindings(body); - intConstants(body); - for (Layouts.Cls k : layouts.classes.values()) { - fields.put(k, new LinkedHashMap()); - for (String f : k.fields) { - fields.get(k).put(f, Ty.BOT); + /// Whether parameter `i` of `f`, which the visible calls gave a type, + /// is better left untyped. When the source says it takes several kinds + /// ([#declared]): the calls supplied a default and nothing more -- + /// `__get__(self, obj, type: Any = None)` held `type: None`, and the + /// interpreter, calling it with the owner class, missed the guard on + /// every access. And when the calls a function entered through its + /// guard can see pass only None: a parameter that is always None buys + /// typed code nothing, and every other caller misses. + private boolean widen(Fn f, int i) { + Ty d = declared(f, i); + return d != null && d.wide() || f.escapes && f.params[i].k == Ty.K.NONE; + } + + /// Set while a function body is walked as its generic version runs it + /// (see [#genericView]). + private boolean shadow; + private boolean shadowMiss; + /// [#localModule]'s answers, by function scope. + private final Map> localModules = new IdentityHashMap>(); + private final Map generic; + + /// Whether `f` is called from code the pass does not walk: it escaped, + /// or its instances reached code that reads attributes by computed name. + private boolean unseenCaller(Fn f) { + return f.escapes || p.anyRead && (f.cls != null ? p.loose.contains(f.cls) + : p.allModulesLoose || p.looseModules.contains(p.fnHome.get(f))); + } + + /// Whether `f` can be entered by a call this pass does not see: one + /// through a value, or one from another module. Such a call goes + /// through the guard at the door, and when its arguments are not what + /// the direct calls pass, the generic version of the body runs. + private boolean entered(Fn f) { + if (f.escapes) { + return true; + } + if (p.anyRead && (f.cls != null ? p.loose.contains(f.cls) + : p.allModulesLoose || p.looseModules.contains(p.fnHome.get(f)))) { + return true; + } + String n = f.def.name; + if (f.cls == null) { + return facts.reachable(n); + } + if ("__init__".equals(n)) { + // Constructed by whoever can name the class or get at it. + if (facts.classValues) { + for (Layouts.Cls k : layouts.all().values()) { + if (isSelfOrAncestor(f.cls, k) && facts.namedOutside(k.def.name)) { + return true; + } + } + return false; } - for (FunctionDef f : k.typable.values()) { - Fn fn = new Fn(f, k); - fn.params[0] = Ty.inst(k, false); - fns.put(f, fn); + for (Layouts.Cls k : layouts.all().values()) { + if (isSelfOrAncestor(f.cls, k) && facts.reachable(k.def.name)) { + return true; + } } + return false; + } + if ("__call__".equals(n) && followedCall(f)) { + // Every call of it the pass sees. Walked as entered with + // anything, warnings' `deprecated.__call__` read `arg.__init__` + // off an untyped `arg` and every `__init__` of the program lost + // its types. Taken off the class as a value (`K.__call__`), it + // escapes and is entered above. + return false; + } + // The runtime calls a special method itself, with anything. + return n.startsWith("__") || facts.calledByName(n); + } + + /// Walks the body of `f` as its generic version runs it: with + /// parameters that hold anything. The typed version is sound whatever + /// reaches the door, since the guard there sends what does not fit to + /// the generic one -- which then stores those values into fields, lists + /// and globals all the same. This walk is what puts them there. + private void genericView(Fn f) { + Fn g = generic.get(f.def); + if (g == null) { + g = new Fn(f.def, f.cls); + generic.put(f.def, g); + } + // Entered from where the pass cannot see, a parameter holds + // anything; entered only by generic bodies this pass walked, it + // holds what those passed. + boolean outside = entered(f); + Ty[] m = p.missed.get(f.def); + for (int i = 0; i < g.params.length; i++) { + g.params[i] = i == 0 && f.cls != null ? f.params[0] + : outside || m == null ? Ty.OBJECT : Ty.join(g.params[i], m[i]); + } + for (int i = 0; i < g.params.length; i++) { + g.locals.put(g.names.get(i), mix(g.locals.get(g.names.get(i)), g.params[i])); + } + shadow = true; + try { + walkBlock(f.def.body, g, f.def.scope); + } finally { + shadow = false; + } + } + + // ---- other modules ---------------------------------------------------- + + /// A global of another module, read through an import. + static final class Extern { + final Infer module; + final String name; + + Extern(Infer module, String name) { + this.module = module; + this.name = name; + } + } + + /// Stable globals an `import` binds to a module of the program. + private final Map moduleNames = new HashMap(); + /// Stable globals `from m import n` binds: the module, and the name there. + private final Map importedNames = new HashMap(); + + /// Records what the imports at the top of the module bind. A name bound + /// once here, to a name bound once there, is that module's function, + /// class or value for good: a call through it is a call of that + /// function, as direct as one inside its own module. + private void bindImports() { + Set star = moduleScope.hasStarImport ? starBound() : java.util.Collections.emptySet(); + if (star == null) { + // A star import of a module the build cannot see may bind any + // name again. + return; } for (Stmt s : body) { - if (s instanceof FunctionDef) { - FunctionDef f = (FunctionDef) s; - if (stable(f.name) && f.decorators.isEmpty() && !f.isAsync && !f.scope.hasYield - && f.args.vararg == null && f.args.kwarg == null && f.args.kwonly.isEmpty() - && f.scope.cells.isEmpty() && f.args.names().size() <= 8) { - Fn fn = new Fn(f, null); - fns.put(f, fn); - globalFns.put(f.name, fn); + if (s instanceof Import) { + for (Alias a : ((Import) s).names) { + int dot = a.name.indexOf('.'); + String n = a.asname != null ? a.asname : dot < 0 ? a.name : a.name.substring(0, dot); + Infer m = p.modules.get(a.asname != null || dot < 0 ? a.name : n); + if (m != null && stable(n)) { + moduleNames.put(n, m); + } } - } else if (s instanceof ClassDef) { - Layouts.Cls k = layouts.classes.get(s); - if (k != null && stable(((ClassDef) s).name)) { - globalClasses.put(((ClassDef) s).name, k); + } else if (s instanceof ImportFrom) { + ImportFrom f = (ImportFrom) s; + String from = f.level == 0 ? f.module : relative(f.level, f.module); + Infer m = from == null ? null : p.modules.get(from); + if (m == null) { + continue; } - } else if (s instanceof Import) { - for (Alias a : ((Import) s).names) { + for (Alias a : f.names) { String n = a.asname != null ? a.asname : a.name; - if ("math".equals(a.name) && stable(n)) { - mathNames.add(n); - } - if ("struct".equals(a.name) && stable(n)) { - structNames.add(n); + Infer sub = p.modules.get(from + "." + a.name); + if (sub != null && !m.moduleScope.assigned.contains(a.name) && stable(n)) { + // `from lxml import etree`: a submodule the package + // binds nothing over is that module, as `import + // lxml.etree as etree` would bind it. + moduleNames.put(n, sub); + } else if (!"*".equals(a.name) && stable(n) && (!star.contains(n) || sameStarBinding(n, m, a.name))) { + importedNames.put(n, new Extern(m, a.name)); } } } } - markOpen(body); - for (Layouts.Cls k : layouts.classes.values()) { - definite.put(k, initDefinite(k, new HashSet())); - } } - /// Whether `e` is the `struct` module, as `isMath` is for `math`. - boolean isStruct(Expr e, Scope sc) { - return e instanceof Name && structNames.contains(((Name) e).id) - && sc.resolve(((Name) e).id) == Scope.Binding.GLOBAL; + private Set starBoundCache; + private boolean starBoundDone; + + /// Every name this module's star imports may bind, or null when one of + /// them is of a module the build cannot see, or exports names it cannot + /// enumerate. A name outside it is bound by the module's own statements + /// alone, as in a module with no star import. + private Set starBound() { + if (!starBoundDone) { + starBoundDone = true; + Set r = new HashSet(); + for (Stmt st : body) { + Infer m = starSource(st); + Set e = m == this ? null : m == null ? r : m.starExports(0); //NOPMD CompareObjectsWithEquals - identity is meant + if (e == null) { + r = null; + break; + } + if (e != r) { //NOPMD CompareObjectsWithEquals - identity is meant + r.addAll(e); + } + } + starBoundCache = r; + } + return starBoundCache; } - /// Whether `e` is the `math` module, through a global only `import math` - /// binds. - boolean isMath(Expr e, Scope sc) { - return e instanceof Name && mathNames.contains(((Name) e).id) - && sc.resolve(((Name) e).id) == Scope.Binding.GLOBAL; + /// The module `from m import *` statement `st` imports, null when `st` + /// is no star import, and this module when it is of a module the build + /// cannot see. + private Infer starSource(Stmt st) { + if (!(st instanceof ImportFrom) || !starImport((ImportFrom) st)) { + return null; + } + ImportFrom f = (ImportFrom) st; + String from = f.level == 0 ? f.module : relative(f.level, f.module); + Infer m = from == null ? null : p.modules.get(from); + return m == null ? this : m; } - /// Whether `c` is a `math` function typed code runs, on the right number - /// of plain positional arguments. - boolean isMathCall(Call c, Scope sc) { - if (!(c.func instanceof Attribute) || !c.keywords.isEmpty() || anyStarred(c.args)) { + /// Whether every star import here that binds `n` binds it to the class + /// `from m import name` binds: openpyxl's chart modules import + /// `Serialisable` and then star-import modules that import it too. + private boolean sameStarBinding(String n, Infer m, String name) { + Infer home = n.equals(name) ? m.classSource(name, 0) : null; + if (home == null) { return false; } - Attribute a = (Attribute) c.func; - Integer n = MATH_FNS.get(a.attr); - return n != null && n.intValue() == c.args.size() && isMath(a.value, sc); + for (Stmt st : body) { + Infer src = starSource(st); + if (src != null && src.starExports(0).contains(n) && src.classSource(n, 0) != home) { //NOPMD CompareObjectsWithEquals - identity is meant + return false; + } + } + return true; } - /// The return type of expression function `f` called with `args`, or - /// null. Helpers such as `def i32(v): return ((v + B) & M) - B` are - /// shared by every caller, and one caller passing an untyped value - /// makes the parameter, and so the result, untyped for all of them. The - /// body is plain arithmetic on its parameters and global constants, so - /// its type at one call follows from that call's arguments alone. - private Ty siteType(Fn f, List args) { - Expr body = exprBody(f.def); - if (body == null) { + /// The module defining the class global `n` holds, read from the + /// statements alone (imports need not be bound yet): a class bound once + /// here, or one `from m import n` imports, followed; or null. + private Infer classSource(String n, int depth) { + if (depth > 8 || !stable(n)) { return null; } - for (Ty t : args) { - if (t.opt || t.k != Ty.K.INT && t.k != Ty.K.FLOAT && t.k != Ty.K.BOOL) { - return null; + for (Stmt st : body) { + if (st instanceof ClassDef && ((ClassDef) st).name.equals(n)) { + return moduleScope.hasStarImport && classAfterStars(n) == null ? null : this; + } + if (st instanceof ImportFrom && !starImport((ImportFrom) st)) { + ImportFrom f = (ImportFrom) st; + for (Alias a : f.names) { + if (n.equals(a.asname != null ? a.asname : a.name)) { + String from = f.level == 0 ? f.module : relative(f.level, f.module); + Infer m = from == null ? null : p.modules.get(from); + return m == null || p.modules.containsKey(from + "." + a.name) ? null : m.classSource(a.name, depth + 1); + } + } } } - Fn site = new Fn(f.def, null); - for (int i = 0; i < args.size(); i++) { - site.params[i] = args.get(i); - site.locals.put(site.names.get(i), args.get(i)); + return null; + } + + /// The module whose star import alone binds global `n` here: openpyxl's + /// `Typed`, which `openpyxl.descriptors` has from `from .base import *`. + /// Null when the module binds `n` itself, or a star import of a module + /// the build cannot see might. + private Infer starProvider(String n) { + if (!moduleScope.hasStarImport || moduleScope.assigned.contains(n) || starBound() == null || !starBound().contains(n)) { + return null; } - Ty t = type(body, site, f.def.scope); - return !t.opt && (t.k == Ty.K.INT || t.k == Ty.K.FLOAT || t.k == Ty.K.BOOL) ? t : null; + Infer last = null; + for (Stmt st : body) { + Infer m = starSource(st); + if (m != null && m.starExports(0).contains(n)) { + last = m; + } + } + return last; } - /// The returned expression of a function whose body is only `return - /// ` (after an optional docstring), the arithmetic made of - /// operators, constants, its parameters and global names; else null. - static Expr exprBody(FunctionDef d) { - List b = d.body; - int i = 0; - if (b.size() == 2 && b.get(0) instanceof ExprStmt && ((ExprStmt) b.get(0)).value instanceof Constant) { - i = 1; + /// The names `from import *` binds: a literal `__all__` + /// bound once, or else every public global, its own star imports' too; + /// null when they cannot be enumerated. + private Set starExports(int depth) { + if (depth > 8) { + return null; } - if (b.size() != i + 1 || !(b.get(i) instanceof Return) || ((Return) b.get(i)).value == null) { + if (moduleScope.assigned.contains("__all__")) { + if (!stable("__all__")) { + return null; + } + for (Stmt st : body) { + if (st instanceof Assign && ((Assign) st).targets.size() == 1 && ((Assign) st).targets.get(0) instanceof Name + && "__all__".equals(((Name) ((Assign) st).targets.get(0)).id)) { + Expr v = ((Assign) st).value; + List elts = v instanceof ListExpr ? ((ListExpr) v).elts : v instanceof TupleExpr ? ((TupleExpr) v).elts : null; + if (elts == null) { + return null; + } + Set r = new HashSet(); + for (Expr x : elts) { + if (!(x instanceof Constant) || ((Constant) x).kind != Constant.Kind.STR) { + return null; + } + r.add(((Constant) x).text); + } + return r; + } + } return null; } - Expr e = ((Return) b.get(i)).value; - return arithmetic(e, d.scope) ? e : null; + Set r = new HashSet(); + for (String n : moduleScope.assigned) { + if (!n.startsWith("_")) { + r.add(n); + } + } + for (Stmt st : body) { + Infer m = starSource(st); + if (m == this) { //NOPMD CompareObjectsWithEquals - identity is meant + return null; + } + if (m != null) { + Set e = m.starExports(depth + 1); + if (e == null) { + return null; + } + for (String n : e) { + if (!n.startsWith("_")) { + r.add(n); + } + } + } + } + return r; } - private static boolean arithmetic(Expr e, Scope sc) { - if (e instanceof Constant) { - return true; + /// Makes live what an import statement reached code runs imports. + private void liveImports(Stmt s) { + if (p.allLive || typeCheckingDepth > 0) { + return; } - if (e instanceof Name) { - Scope.Binding r = sc.resolve(((Name) e).id); - return r == Scope.Binding.GLOBAL || sc.params.contains(((Name) e).id); + p.cause = moduleName + ":" + s.line; + if (s instanceof Import) { + for (Alias a : ((Import) s).names) { + p.markLive(a.name); + } + return; } - if (e instanceof BinOp) { - return arithmetic(((BinOp) e).left, sc) && arithmetic(((BinOp) e).right, sc); + ImportFrom f = (ImportFrom) s; + p.cause = moduleName + ":" + s.line; + String base = f.level == 0 ? f.module : relative(f.level, f.module); + if (base == null) { + return; } - if (e instanceof UnaryOp) { - return arithmetic(((UnaryOp) e).operand, sc); + p.markLive(base); + for (Alias a : f.names) { + if ("*".equals(a.name)) { + // __all__ may name submodules, which the import then runs. + p.markPrefix(base + "."); + } else { + p.markLive(base + "." + a.name); + } } - return false; } - /// Module globals bound once, at the top level, to an int literal (`M32 = - /// 0xFFFFFFFF`): their value is known wherever a function reads them. - final Map intConsts = new HashMap(); + /// How many `if TYPE_CHECKING:` blocks the walk is inside. + private int typeCheckingDepth; - private void intConstants(List body) { - for (Stmt s : body) { - if (s instanceof Assign && ((Assign) s).targets.size() == 1 - && ((Assign) s).targets.get(0) instanceof Name) { - String n = ((Name) ((Assign) s).targets.get(0)).id; - java.math.BigInteger v = IntRanges.literal(((Assign) s).value); - if (v != null && stable(n)) { - intConsts.put(n, v); + /// Whether `test` is typing's `TYPE_CHECKING`, which is False when the + /// program runs: the name imported from typing (or typing_extensions) + /// and never rebound, or the attribute read off the module. + private boolean typeChecking(Expr test) { + if (test instanceof Name && "TYPE_CHECKING".equals(((Name) test).id)) { + Extern e = importedNames.get("TYPE_CHECKING"); + if (e != null) { + return "TYPE_CHECKING".equals(e.name) && typingModule(e.module.moduleName); + } + // A module with a star import records no import bindings (see + // bindImports); the one binding is then read off the body. A + // star import that bound it again would bind typing's False. + if (!stable("TYPE_CHECKING")) { + return false; + } + for (Stmt st : body) { + if (st instanceof ImportFrom && ((ImportFrom) st).level == 0 + && typingModule(((ImportFrom) st).module)) { + for (Alias a : ((ImportFrom) st).names) { + if ("TYPE_CHECKING".equals(a.name) && a.asname == null) { + return true; + } + } } } + return false; + } + if (test instanceof Attribute && "TYPE_CHECKING".equals(((Attribute) test).attr) + && ((Attribute) test).value instanceof Name) { + String n = ((Name) ((Attribute) test).value).id; + Infer m = moduleNames.get(n); + if (m != null) { + return typingModule(m.moduleName); + } + if (!typingModule(n) || !stable(n)) { + return false; + } + for (Stmt st : body) { + if (st instanceof Import) { + for (Alias a : ((Import) st).names) { + if (n.equals(a.name) && a.asname == null) { + return true; + } + } + } + } + return false; } + return false; } - private boolean stable(String n) { - Integer c = moduleBindings.get(n); - return c != null && c.intValue() == 1; + private static boolean typingModule(String name) { + return "typing".equals(name) || "typing_extensions".equals(name); } - /// Counts the bindings of each global at the top level, and every - /// `global` declaration in a function as one more (such a store is - /// invisible to a module-level count). - private void countBindings(List body) { - for (Stmt s : body) { - List names = new ArrayList(); - if (s instanceof FunctionDef) { - names.add(((FunctionDef) s).name); - } else if (s instanceof ClassDef) { - names.add(((ClassDef) s).name); - } else if (s instanceof Assign) { - for (Expr t : ((Assign) s).targets) { - targetNames(t, names); + /// The parts of this module [#scanStrings] has read: statements of + /// the body and functions, each once. + private final Set pendingExact = new LinkedHashSet(); + private final Set pendingPrefixes = new LinkedHashSet(); + /// Whether reached code of this module imports by a computed name. + private boolean importsByName; + private final Set stringsSeen = java.util.Collections.newSetFromMap(new IdentityHashMap()); + + /// What a computed import in this module may name: every string that + /// is a module's name (absolute, or relative with leading dots), and + /// the constant start of a formatted string or a concatenation, which + /// keeps every module under it. Only code that runs is read: the body, + /// and each function once it is reached. Called again every round, + /// it reads what was reached since. + void scanStrings() { + StringScan v = new StringScan(p, stringsSeen); + v.on(body); + pendingExact.addAll(v.exact); + pendingPrefixes.addAll(v.prefixes); + importsByName |= v.importsByName; + // A string names a module to import only where the module imports + // by a name it computes, or (the entry points importlib.metadata + // loads) in the table of installed distributions. + boolean applies = importsByName || "_cn1_distributions".equals(moduleName) + && p.modules.containsKey("importlib.metadata") && p.live.contains(p.modules.get("importlib.metadata")); + if (!applies) { + return; + } + List exact = new ArrayList(pendingExact); + List prefixes = new ArrayList(pendingPrefixes); + pendingExact.clear(); + pendingPrefixes.clear(); + p.cause = "a string of " + moduleName; + for (String t : exact) { + for (String tok : tokens(t)) { + String n = absolute(tok); + if (n != null && p.modules.containsKey(n)) { + p.markLive(n); } - } else if (s instanceof AugAssign) { - targetNames(((AugAssign) s).target, names); - targetNames(((AugAssign) s).target, names); - } else if (s instanceof AnnAssign) { - targetNames(((AnnAssign) s).target, names); - } else if (s instanceof Import) { - for (Alias a : ((Import) s).names) { - String n = a.asname != null ? a.asname : a.name; - int dot = n.indexOf('.'); - names.add(dot < 0 ? n : n.substring(0, dot)); + } + } + for (String t : prefixes) { + List toks = tokens(t); + if (toks.isEmpty() || !t.endsWith(toks.get(toks.size() - 1))) { + continue; + } + String n = absolute(toks.get(toks.size() - 1)); + if (n != null && n.indexOf('.') > 0) { + p.markPrefix(n); + } + } + } + + /// Gathers the strings [#scanStrings] reads. + private static final class StringScan implements Visit { + final List exact = new ArrayList(); + final List prefixes = new ArrayList(); + boolean importsByName; + private final Program p; + private final Set seen; + + StringScan(Program p, Set seen) { + this.p = p; + this.seen = seen; + } + + @Override + public void on(Object o) { + if (o instanceof Stmt || o instanceof Lambda) { + if (seen.contains(o) || o instanceof FunctionDef && p.fns.containsKey(o) && !p.reached.contains(o)) { + // Read already, or a function nothing reaches yet. + return; } - } else if (s instanceof ImportFrom) { - for (Alias a : ((ImportFrom) s).names) { - names.add(a.asname != null ? a.asname : a.name); + if (o instanceof FunctionDef) { + seen.add(o); } - } else { - // A compound statement: everything it binds counts twice, - // since it may run any number of times. - for (String n : moduleScope.assigned) { - if (binds(s, n)) { - names.add(n); - names.add(n); - } + } + if (o instanceof Name && importer(((Name) o).id) + || o instanceof Attribute && importer(((Attribute) o).attr)) { + importsByName = true; + } + if (o instanceof Call && ((Call) o).args.size() == 2 && isStr(((Call) o).args.get(0)) + && isStr(((Call) o).args.get(1))) { + // import_module(".name", "package"): relative to the + // package named, not to this module. + String rel = ((Constant) ((Call) o).args.get(0)).text; + String base = ((Constant) ((Call) o).args.get(1)).text; + int level = 0; + while (level < rel.length() && rel.charAt(level) == '.') { + level++; + } + for (int i = 1; i < level && base.lastIndexOf('.') > 0; i++) { + base = base.substring(0, base.lastIndexOf('.')); + } + if (level > 0) { + exact.add(level == rel.length() ? base : base + "." + rel.substring(level)); } } - for (String n : names) { - Integer c = moduleBindings.get(n); - moduleBindings.put(n, Integer.valueOf(c == null ? 1 : c.intValue() + 1)); + if (o instanceof Constant && ((Constant) o).kind == Constant.Kind.STR) { + exact.add(((Constant) o).text); + } else if (o instanceof JoinedStr && !((JoinedStr) o).parts.isEmpty() + && ((JoinedStr) o).parts.get(0) instanceof Constant) { + prefixes.add(((Constant) ((JoinedStr) o).parts.get(0)).text); + } else if (o instanceof BinOp && "+".equals(((BinOp) o).op) && ((BinOp) o).left instanceof Constant + && ((Constant) ((BinOp) o).left).kind == Constant.Kind.STR) { + prefixes.add(((Constant) ((BinOp) o).left).text); } + children(o, this); } - globalDecls(body); } - private void globalDecls(Object o) { - if (o instanceof Global && !((Global) o).nonlocal) { - for (String n : ((Global) o).names) { - moduleBindings.put(n, Integer.valueOf(99)); - } + /// The names through which Python code imports by a computed name: + /// importlib's, the builtin, and the registry's own (`_cn1imp.load`). + private static boolean importer(String n) { + return "import_module".equals(n) || "__import__".equals(n) || "_cn1imp".equals(n); + } + + private static boolean isStr(Expr e) { + return e instanceof Constant && ((Constant) e).kind == Constant.Kind.STR; + } + + /// A dotted token of a string resolved as an import of this module + /// would resolve it: leading dots climb from its package. + private String absolute(String tok) { + int level = 0; + while (level < tok.length() && tok.charAt(level) == '.') { + level++; } - children(o, x -> globalDecls(x)); + if (level == 0) { + return tok; + } + String rest = tok.substring(level); + return relative(level, rest.isEmpty() ? null : rest); } - private static boolean binds(Stmt s, String n) { + /// The runs of identifier characters and dots in `s`. + private static List tokens(String s) { List out = new ArrayList(); - boundIn(s, out); - return out.contains(n); + int start = -1; + for (int i = 0; i <= s.length(); i++) { + char c = i < s.length() ? s.charAt(i) : ' '; + boolean id = c == '.' || c == '_' || c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9'; + if (id && start < 0) { + start = i; + } else if (!id && start >= 0) { + out.add(s.substring(start, i)); + start = -1; + } + } + return out; } - /// The names a statement stores into, outside nested scopes. - private static void boundIn(Object o, List out) { - if (o instanceof Lambda || o instanceof Comp) { - return; + /// The absolute name of `from import`, or null when it + /// climbs out of the top-level package. + private String relative(int level, String module) { + String base = moduleName; + int up = pkg ? level - 1 : level; + for (int i = 0; i < up; i++) { + int dot = base.lastIndexOf('.'); + if (dot < 0) { + return null; + } + base = base.substring(0, dot); } - if (o instanceof FunctionDef) { - out.add(((FunctionDef) o).name); - return; + if (module == null) { + return base; } - if (o instanceof ClassDef) { - out.add(((ClassDef) o).name); - return; + return base.isEmpty() ? module : base + "." + module; + } + + /// What stable global `n` of this module is: an `Fn`, a `Layouts.Cls`, + /// an `Infer` (a module), a `Extern` (a value of another module's), or + /// null for a value of this module's own or one nothing is known of. + private Object resolve(String n, int depth) { + Fn f = globalFns.get(n); + if (f != null) { + return f; } - if (o instanceof Assign) { - for (Expr t : ((Assign) o).targets) { - targetNames(t, out); - } - } else if (o instanceof AugAssign) { - targetNames(((AugAssign) o).target, out); - } else if (o instanceof AnnAssign) { - targetNames(((AnnAssign) o).target, out); - } else if (o instanceof For) { - targetNames(((For) o).target, out); - } else if (o instanceof WithItem && ((WithItem) o).vars != null) { - targetNames(((WithItem) o).vars, out); - } else if (o instanceof NamedExpr) { - out.add(((NamedExpr) o).target.id); - } else if (o instanceof ExceptHandler && ((ExceptHandler) o).name != null) { - out.add(((ExceptHandler) o).name); - } else if (o instanceof Import) { - for (Alias a : ((Import) o).names) { - String n = a.asname != null ? a.asname : a.name; - int dot = n.indexOf('.'); - out.add(dot < 0 ? n : n.substring(0, dot)); - } - } else if (o instanceof ImportFrom) { - for (Alias a : ((ImportFrom) o).names) { - out.add(a.asname != null ? a.asname : a.name); + Layouts.Cls k = globalClasses.get(n); + if (k != null) { + return k; + } + Infer m = moduleNames.get(n); + if (m != null) { + return m; + } + Extern g = importedNames.get(n); + if (g != null && g.module == this) { //NOPMD CompareObjectsWithEquals - identity is meant + // `from . import m` in a package's own `__init__`: its module m, + // not the name m of the package, which this import is. + Infer sub = p.modules.get(moduleName.isEmpty() ? g.name : moduleName + "." + g.name); + if (sub != null) { + return sub; } - } else if (o instanceof Delete) { - for (Expr t : ((Delete) o).targets) { - targetNames(t, out); + } + return g == null || depth > 8 ? null : g.module.export(g.name, depth + 1); + } + + /// What attribute `n` of this module is, to another module. + private Object export(String n, int depth) { + if (moduleScope.assigned.contains(n)) { + if (!stable(n) || moduleScope.hasStarImport) { + return null; } + Object r = resolve(n, depth); + return r != null ? r : new Extern(this, n); } - children(o, x -> boundIn(x, out)); + // Not a global of the package: a module in it. + return moduleScope.hasStarImport ? null : p.modules.get(moduleName.isEmpty() ? n : moduleName + "." + n); } - private static void targetNames(Expr t, List out) { - if (t instanceof Name) { - out.add(((Name) t).id); - } else if (t instanceof TupleExpr) { - for (Expr e : ((TupleExpr) t).elts) { - targetNames(e, out); + /// What `e` names in another module, when `e` is an imported name or an + /// attribute of an imported module; otherwise null. + private Object foreign(Expr e, Scope sc) { + if (e instanceof Name && sc.resolve(((Name) e).id) == Scope.Binding.LOCAL) { + return localModule(((Name) e).id, sc); + } + if (e instanceof Name) { + String n = ((Name) e).id; + if (sc.resolve(n) != Scope.Binding.GLOBAL || !importedNames.containsKey(n) && !moduleNames.containsKey(n)) { + return null; } - } else if (t instanceof ListExpr) { - for (Expr e : ((ListExpr) t).elts) { - targetNames(e, out); + return resolve(n, 0); + } + if (e instanceof Attribute) { + Object o = foreign(((Attribute) e).value, sc); + return o instanceof Infer ? ((Infer) o).export(((Attribute) e).attr, 0) : null; + } + return null; + } + + /// The module a local of function scope `sc` names: one bound once in + /// the body, by an `import` of a module the program has, and nowhere + /// else (`import functools as _ft` inside typing_extensions' + /// `deprecated.__call__`). Null otherwise. + private Infer localModule(String n, Scope sc) { + Map m = localModules.get(sc); + if (m == null) { + m = new HashMap(); + localModules.put(sc, m); + Fn f = p.fnOf(sc); + if (f != null) { + List bound = new ArrayList(); + Map imported = new HashMap(); + for (Stmt s : f.def.body) { + boundIn(s, bound); + collectImports(s, imported); + } + for (Map.Entry en : imported.entrySet()) { + String k = en.getKey(); + if (bound.indexOf(k) == bound.lastIndexOf(k) && !sc.params.contains(k) + && !sc.globals.contains(k) && !sc.nonlocals.contains(k) && !rebound(sc, k)) { + m.put(k, en.getValue()); + } + } } - } else if (t instanceof Starred) { - targetNames(((Starred) t).value, out); } + return m.get(n); } - /// A class some class the layout planner rejected derives from: its - /// instances may run methods this pass does not see, so neither it nor - /// its ancestors are typed. - private void markOpen(Object o) { - if (o instanceof ClassDef) { - ClassDef c = (ClassDef) o; - if (!layouts.classes.containsKey(c)) { - for (Expr b : c.bases) { - if (b instanceof Name) { - Layouts.Cls k = byName(((Name) b).id); - for (; k != null; k = k.parent) { - open.add(k); - } - } - } + /// Whether a scope nested in `sc` stores into its `n` (`nonlocal n`). + private static boolean rebound(Scope sc, String n) { + for (Scope c : sc.children) { + if (c.nonlocals.contains(n) || !c.assigned.contains(n) && rebound(c, n)) { + return true; } } - children(o, x -> markOpen(x)); + return false; } - private Layouts.Cls byName(String n) { - for (Layouts.Cls k : layouts.classes.values()) { - if (k.def.name.equals(n)) { - return k; + /// The modules the `import` statements under `o` bind, by local name, + /// outside nested scopes. + private void collectImports(Object o, Map out) { + if (o instanceof FunctionDef || o instanceof ClassDef || o instanceof Lambda || o instanceof Comp) { + return; + } + if (o instanceof Import) { + for (Alias a : ((Import) o).names) { + int dot = a.name.indexOf('.'); + String n = a.asname != null ? a.asname : dot < 0 ? a.name : a.name.substring(0, dot); + Infer im = p.modules.get(a.asname != null || dot < 0 ? a.name : n); + if (im != null) { + out.put(n, im); + } } + return; } - return null; + children(o, x -> collectImports(x, out)); } - // ---- definite assignment of fields ------------------------------------ - - private Set initDefinite(Layouts.Cls k, Set seen) { - Set r = new HashSet(); - Layouts.Cls owner = Layouts.resolver(k, "__init__"); - if (owner == null || !seen.add(owner)) { - return r; - } - FunctionDef f = owner.typable.get("__init__"); - if (f == null || f.args.names().isEmpty()) { - return r; - } - String self = f.args.names().get(0); - if (f.scope.assigned.contains(self)) { - return r; + /// `t` as this module's code holds it. An instance of a class another + /// module compiled is typed like one of this module's: typed code names + /// that class by its qualified Java name and reads its typed fields as + /// their own module holds them (TypedEmit.typedField). Only a class of a + /// module nothing live imports, which is never emitted, is held as any + /// object. bs4's `Tag` is compiled in `bs4.element` and walked by + /// `bs4.filter`, `bs4.builder` and markdownify: held as any object there, + /// every `tag.name` went through an attribute cache. + private Ty loc(Ty t) { + if (!p.done || t == null) { + return t; } - for (Stmt s : f.body) { - if (s instanceof Pass || s instanceof ExprStmt && ((ExprStmt) s).value instanceof Constant) { - continue; - } - if (s instanceof Assign && ((Assign) s).targets.size() == 1) { - Assign a = (Assign) s; - Expr t = a.targets.get(0); - if (t instanceof Attribute && ((Attribute) t).value instanceof Name - && ((Name) ((Attribute) t).value).id.equals(self) && !mentions(a.value, self)) { - r.add(((Attribute) t).attr); - continue; + if (t.k == Ty.K.UNION) { + for (Ty m : t.members()) { + if (loc(m).k == Ty.K.OBJECT) { + return Ty.OBJECT; } } - if (s instanceof ExprStmt && ((ExprStmt) s).value instanceof Call) { - Call c = (Call) ((ExprStmt) s).value; - if (c.func instanceof Attribute && "__init__".equals(((Attribute) c.func).attr) - && ((Attribute) c.func).value instanceof Name && c.keywords.isEmpty() && !c.args.isEmpty() - && c.args.get(0) instanceof Name && ((Name) c.args.get(0)).id.equals(self)) { - Layouts.Cls base = globalClasses.get(((Name) ((Attribute) c.func).value).id); - boolean clean = base != null && isAncestor(base, owner); - for (int i = 1; i < c.args.size() && clean; i++) { - clean = !mentions(c.args.get(i), self); - } - if (clean) { - r.addAll(initDefinite(base, seen)); - continue; - } + return t; + } + if (t.k == Ty.K.CLS) { + for (int s : t.sites) { + if (!p.clsById.get(s).compiled) { + return Ty.OBJECT; } } - if (mentions(s, self)) { - break; - } + return t; } - return r; - } - - private static boolean isAncestor(Layouts.Cls a, Layouts.Cls k) { - for (Layouts.Cls x = k.parent; x != null; x = x.parent) { - if (x == a) { //NOPMD CompareObjectsWithEquals - identity is meant - return true; + if (t.k == Ty.K.METH) { + for (int s : t.sites) { + if (p.methById.get(s).analysisOnly) { + return Ty.OBJECT; + } } + return t; } - return false; - } - - static boolean mentions(Object o, String n) { - boolean[] r = new boolean[1]; - mentionsIn(o, n, r); - return r[0]; - } - - private static void mentionsIn(Object o, String n, boolean[] r) { - if (r[0]) { - return; + if (t.k == Ty.K.FUNC) { + // The inference's own: generated code holds a function as an + // object, and calls it generically. + return Ty.OBJECT; } - if (o instanceof Name && ((Name) o).id.equals(n)) { - r[0] = true; - return; + if (t.k != Ty.K.INST) { + return t; } - children(o, x -> mentionsIn(x, n, r)); + Infer h = p.home.get(t.cls); + // An analysed class has no Java class: generated code holds its + // instances as objects. + return h == null || !p.isLive(h) || !t.cls.compiled ? Ty.OBJECT : t; } - /// Whether field `f` of class `k` (declared there or inherited) is set - /// on every instance of `k` and of all its subclasses. - boolean definitelySet(Layouts.Cls owner, String f) { - for (Layouts.Cls k : layouts.classes.values()) { - if (isSelfOrAncestor(owner, k) && !definite.get(k).contains(f)) { - return false; + /// Rewrites what this module's own code declares -- parameters, locals, + /// results, fields, globals -- as that code holds it (see [#loc]). + private void localize() { + for (Fn f : fns.values()) { + for (int i = 0; i < f.params.length; i++) { + f.params[i] = loc(f.params[i]); } - } - return true; - } - - static boolean isSelfOrAncestor(Layouts.Cls a, Layouts.Cls k) { - for (Layouts.Cls x = k; x != null; x = x.parent) { - if (x == a) { //NOPMD CompareObjectsWithEquals - identity is meant - return true; + f.ret = loc(f.ret); + for (Map.Entry e : f.locals.entrySet()) { + e.setValue(loc(e.getValue())); } } - return false; - } - - // ---- joins ----------------------------------------------------------- - - private Ty joinInto(Ty cur, Ty v) { - Ty r = Ty.join(cur, v); - if (!r.equals(cur)) { - changed = true; + for (Layouts.Cls k : layouts.all().values()) { + for (Map.Entry e : fields.get(k).entrySet()) { + e.setValue(loc(e.getValue())); + } } - if (r.k != Ty.K.LIST) { - escape(v); + for (Map.Entry e : globals.entrySet()) { + e.setValue(loc(e.getValue())); } - return r; } - /// A value went somewhere the pass does not follow. - void escape(Ty v) { - if (v != null && v.k == Ty.K.LIST) { - if (v.sites.length == 0) { - if (!allListsEscape) { - allListsEscape = true; - changed = true; - } - } else { - for (int s : v.sites) { - if (escapedSites.add(Integer.valueOf(s))) { - changed = true; - } - } + // ---- setup ----------------------------------------------------------- + + /// How often each global is bound, which decides what the imports may + /// follow ([#stable]); before any module's classes are collected. + private void countGlobals(List body) { + countBindings(body); + for (String n : moduleScope.assigned) { + // A global another module stores (`mod.n = v`), or any global + // of a module that hands its namespace out as a dict, is bound + // more often than this module shows and holds anything. + if (facts.namespace || facts.patched(n)) { + moduleBindings.put(n, Integer.valueOf(99)); + globals.put(n, Ty.OBJECT); } } } - private void escapeFn(Fn f) { - if (f != null && !f.escapes) { - f.escapes = true; - changed = true; - } - if (f != null) { - // Callers through a value are unknown, but the typed version - // is entered from the generic one only through a guard that - // checks every argument (TypedEmit.entry): a parameter keeps - // what its direct callers pass, and one nobody calls directly - // takes the type its uses suggest. A wrong guess costs the - // guard, never correctness. - for (int i = f.cls != null ? 1 : 0; i < f.params.length; i++) { - if (f.params[i].k == Ty.K.BOT) { - f.params[i] = joinInto(f.params[i], guess(f.def, f.names.get(i))); - } + /// Every function nested in another, and every lambda, gets a Fn of + /// the inference's own (see [#nested]). + private void nestedFns(Object o, boolean inFunction) { + if (o instanceof Lambda) { + Lambda l = (Lambda) o; + if (l.scope != null && !lambdaDefs.containsKey(l)) { + List body = new ArrayList(); + Return r = new Return(l.body); + r.line = l.line; + body.add(r); + FunctionDef d = new FunctionDef("", l.args, body, new ArrayList(), null, false); + d.scope = l.scope; + d.line = l.line; + lambdaDefs.put(l, d); + addNested(d); } + } else if (o instanceof FunctionDef && inFunction && !fns.containsKey(o)) { + addNested((FunctionDef) o); } + boolean in = o instanceof FunctionDef || o instanceof Lambda || inFunction && !(o instanceof ClassDef); + children(o, x -> nestedFns(x, in)); } - /// The type the uses of parameter `p` in `def` suggest: INT when it is - /// a `range` bound, a list repeat count or an operand next to an int - /// constant; FLOAT next to a float constant; DYN when the uses say - /// nothing or disagree. - static Ty guess(FunctionDef def, String p) { - Ty[] g = {null}; - boolean[] bad = {false}; - for (Stmt s : def.body) { - guessIn(s, p, g, bad); + private void addNested(FunctionDef d) { + if (d.scope == null || !doorOnly(d)) { + return; } - return bad[0] || g[0] == null ? Ty.DYN : g[0]; + compCells.put(d.scope, compOnlyCells(d)); + Fn fn = new Fn(d, null); + fn.analysisOnly = true; + starParams(fn); + fns.put(d, fn); + p.fns.put(d, fn); + p.fnHome.put(fn, this); } - private static void guessIn(Object o, String p, Ty[] g, boolean[] bad) { - if (o instanceof Call && ((Call) o).func instanceof Name && "range".equals(((Name) ((Call) o).func).id)) { - for (Expr a : ((Call) o).args) { - if (isName(a, p)) { - vote(Ty.INT, g, bad); + private final Map lambdaDefs = new IdentityHashMap(); + + private void collect(List body) { + intConstants(body); + nestedFns(body, false); + for (Layouts.Cls k : layouts.all().values()) { + // A method a store may replace is looked up per call, as one + // the class's own methods store on `self` is (Layouts.plan): + // one named to setattr or deleted, and one an earlier run of + // the pass found a store reaching (Program#patchedFound). + Set pk = p.patched.get(k.def); + for (java.util.Iterator it = k.typable.keySet().iterator(); it.hasNext();) { + String pn = it.next(); + if (facts.methodPatched(pn) || pk != null && pk.contains(pn)) { + it.remove(); } } - } else if (o instanceof BinOp) { - BinOp b = (BinOp) o; - if ("*".equals(b.op) && (b.left instanceof ListExpr && isName(b.right, p))) { - vote(Ty.INT, g, bad); - } else if (isName(b.left, p) || isName(b.right, p)) { - Ty c = constType(isName(b.left, p) ? b.right : b.left); - if (c != null) { - vote(c, g, bad); + } + for (Layouts.Cls k : layouts.all().values()) { + fields.put(k, new LinkedHashMap()); + p.home.put(k, this); + for (String f : k.fields) { + List o = p.fieldOwners.get(f); + if (o == null) { + o = new ArrayList(); + p.fieldOwners.put(f, o); } + o.add(k); } - } else if (o instanceof Compare && ((Compare) o).ops.size() == 1) { - Compare c = (Compare) o; - Expr r = c.comparators.get(0); - if (isName(c.left, p) || isName(r, p)) { - Ty t = constType(isName(c.left, p) ? r : c.left); - if (t != null) { - vote(t, g, bad); + for (String f : k.fields) { + // A field stored from another module holds what that + // module puts there, which a pass without that module does + // not see. + fields.get(k).put(f, !p.closed && facts.foreign(f) ? Ty.OBJECT : Ty.BOT); + } + for (FunctionDef f : k.typable.values()) { + compCells.put(f.scope, compOnlyCells(f)); + Fn fn = new Fn(f, k); + fn.analysisOnly = !k.compiled; + fn.params[0] = Ty.inst(k, false); + fns.put(f, fn); + p.fns.put(f, fn); + p.fnHome.put(fn, this); + } + for (Stmt st : k.def.body) { + // Every other method with a fixed parameter list -- a + // property, a class or static method, one shadowed or + // defined twice -- gets a typed body too, entered only by the + // door in its generic body, which checks every argument: no + // call site binds it directly, so what the decorator or the + // lookup does with it changes nothing. + if (st instanceof FunctionDef && !fns.containsKey(st) && doorOnly((FunctionDef) st) + && !((FunctionDef) st).args.names().isEmpty()) { + FunctionDef f = (FunctionDef) st; + compCells.put(f.scope, compOnlyCells(f)); + Fn fn = new Fn(f, k); + fn.analysisOnly = !k.compiled; + // `__new__` takes the class: what each construction + // passes it ([#callKnown]). + fn.params[0] = "__new__".equals(f.name) ? Ty.BOT : plainDecorators(f) ? Ty.inst(k, false) : Ty.OBJECT; + starParams(fn); + fns.put(f, fn); + p.fns.put(f, fn); + p.fnHome.put(fn, this); } } - } else if (o instanceof Assign) { - // Rebinding the parameter: its later uses say nothing of the - // argument. - for (Expr t : ((Assign) o).targets) { - if (isName(t, p)) { - bad[0] = true; + } + for (Stmt s : body) { + if (s instanceof FunctionDef) { + FunctionDef f = (FunctionDef) s; + Set cc = compOnlyCells(f); + if (stable(f.name) && f.decorators.isEmpty() && !f.isAsync + && f.args.vararg == null && f.args.kwarg == null + && f.args.names().size() <= Layouts.MAX_TYPED_PARAMS) { + compCells.put(f.scope, cc); + Fn fn = new Fn(f, null); + fns.put(f, fn); + p.fns.put(f, fn); + p.fnHome.put(fn, this); + globalFns.put(f.name, fn); + } else if (doorOnly(f)) { + // Rebound or decorated: a typed body behind its door only. + compCells.put(f.scope, cc); + Fn fn = new Fn(f, null); + starParams(fn); + fns.put(f, fn); + p.fns.put(f, fn); + p.fnHome.put(fn, this); + } + } else if (s instanceof ClassDef) { + Layouts.Cls k = layouts.all().get(s); + if (k != null && stable(((ClassDef) s).name)) { + globalClasses.put(((ClassDef) s).name, k); + } + } else if (s instanceof Import) { + for (Alias a : ((Import) s).names) { + String n = a.asname != null ? a.asname : a.name; + if ("math".equals(a.name) && stable(n)) { + mathNames.add(n); + } + String root = a.asname != null ? a.name : a.name.split("\\.")[0]; + if (("time".equals(root) || "os".equals(root)) && stable(n)) { + nativeMods.put(n, root); + } + if ("struct".equals(a.name) && stable(n)) { + structNames.add(n); + } } } } - Infer.children(o, x -> guessIn(x, p, g, bad)); + markOpen(body); + for (Layouts.Cls k : layouts.all().values()) { + definite.put(k, initDefinite(k, new HashSet())); + } } - private static boolean isName(Expr e, String p) { - return e instanceof Name && ((Name) e).id.equals(p); + /// Whether `f` may have a typed body entered only by its door: a + /// bounded number of parameters of any kind (the door hands over what the generic + /// body bound, `*args` and `**kwargs` included), and no cell a closure + /// shares. + private static boolean doorOnly(FunctionDef f) { + // A Java method takes at most 255 slots, and an int parameter + // takes three (a long and its object). + return !f.isAsync && f.args.names().size() <= 60; } - private static Ty constType(Expr e) { - if (e instanceof Constant) { - Constant c = (Constant) e; - if (c.kind == Constant.Kind.INT) { - return Ty.INT; - } - if (c.kind == Constant.Kind.FLOAT && !c.text.matches(".*[jJ]")) { - return Ty.FLOAT; - } + /// A door-only function's `*args` and `**kwargs`: a tuple and a dict + /// the generic body made, of no type a call site settles. + private static void starParams(Fn fn) { + Arguments a = fn.def.args; + if (a.vararg != null) { + fn.params[fn.names.indexOf(a.vararg.name)] = Ty.OBJECT; + } + if (a.kwarg != null) { + fn.params[fn.names.indexOf(a.kwarg.name)] = Ty.OBJECT; } - return null; } - private static void vote(Ty t, Ty[] g, boolean[] bad) { - if (g[0] != null && !g[0].equals(t)) { - bad[0] = true; + /// Whether every decorator of method `f` hands the function the instance + /// as its first argument: none, a property's getter, setter or deleter, + /// and the descriptors modelled on it. With any other the first parameter + /// is typed unknown, and the door checks it like any other. + private static boolean plainDecorators(FunctionDef f) { + for (Expr d : f.decorators) { + boolean ok = d instanceof Name && ("property".equals(((Name) d).id) || PROPERTY_ALIAS.equals(((Name) d).id) || "lazyproperty".equals(((Name) d).id) + || "cached_property".equals(((Name) d).id)) + || d instanceof Attribute && ("setter".equals(((Attribute) d).attr) + || "deleter".equals(((Attribute) d).attr)); + if (!ok) { + return false; + } } - g[0] = t; + return true; } - private void escapeClass(Layouts.Cls k) { - Layouts.Cls o = Layouts.resolver(k, "__init__"); - if (o != null && o.typable.get("__init__") != null) { - escapeFn(fns.get(o.typable.get("__init__"))); - } + /// Whether `e` is the `struct` module, as `isMath` is for `math`. + boolean isStruct(Expr e, Scope sc) { + return e instanceof Name && structNames.contains(((Name) e).id) + && sc.resolve(((Name) e).id) == Scope.Binding.GLOBAL; } - /// Every compiled method `name` may be reached with arguments the pass - /// cannot type. - private void escapeMethods(String name) { - for (Fn f : fns.values()) { - if (f.cls != null && f.def.name.equals(name)) { - escapeFn(f); - } - } + /// Whether `e` is the `math` module, through a global only `import math` + /// binds. + boolean isMath(Expr e, Scope sc) { + return e instanceof Name && mathNames.contains(((Name) e).id) + && sc.resolve(((Name) e).id) == Scope.Binding.GLOBAL; } - Ty elem(Ty list) { - if (list.k != Ty.K.LIST || allListsEscape || list.sites.length == 0) { - return Ty.DYN; + /// The type a call of a [#NATIVE_RET] function answers with these + /// argument types, or null when `c` is not one or an argument is not a + /// plain `str`. + Ty nativeRet(Call c, List args, Scope sc) { + if (!c.keywords.isEmpty() || anyStarred(c.args) || c.args.size() > 2) { + return null; } - Ty r = Ty.BOT; - for (int s : list.sites) { - if (escapedSites.contains(Integer.valueOf(s))) { - return Ty.DYN; + StringBuilder d = new StringBuilder(); + Expr e = c.func; + while (e instanceof Attribute) { + d.insert(0, "." + ((Attribute) e).attr); + e = ((Attribute) e).value; + } + if (!(e instanceof Name) || sc.resolve(((Name) e).id) != Scope.Binding.GLOBAL) { + return null; + } + String m = nativeMods.get(((Name) e).id); + Ty r = m == null ? null : NATIVE_RET.get(m + d); + if (r == null) { + return null; + } + for (Ty t : args) { + if (t.k != Ty.K.STR || t.opt) { + return null; } - r = Ty.join(r, siteElem.get(s)); } - return r; + if (r.opt && args.size() == 2) { + return Ty.STR; + } + return r.k == Ty.K.FLOAT ? (args.isEmpty() ? r : null) : args.isEmpty() && !"os.getcwd".equals(m + d) ? null : r; } - private void storeElem(Ty list, Ty v) { - if (list.k != Ty.K.LIST || list.sites.length == 0) { - escape(v); - return; + /// Whether `c` is a `math` function typed code runs, on the right number + /// of plain positional arguments. + boolean isMathCall(Call c, Scope sc) { + if (!(c.func instanceof Attribute) || !c.keywords.isEmpty() || anyStarred(c.args)) { + return false; } - for (int s : list.sites) { - siteElem.set(s, joinInto(siteElem.get(s), v)); + Attribute a = (Attribute) c.func; + Integer n = MATH_FNS.get(a.attr); + return n != null && n.intValue() == c.args.size() && isMath(a.value, sc); + } + + /// The return type of expression function `f` called with `args`, or + /// null. Helpers such as `def i32(v): return ((v + B) & M) - B` are + /// shared by every caller, and one caller passing an untyped value + /// makes the parameter, and so the result, untyped for all of them. The + /// body is plain arithmetic on its parameters and global constants, so + /// its type at one call follows from that call's arguments alone. + private Ty siteType(Fn f, List args) { + Expr body = exprBody(f.def); + if (body == null) { + return null; + } + for (Ty t : args) { + if (t.opt || t.k != Ty.K.INT && t.k != Ty.K.FLOAT && t.k != Ty.K.BOOL) { + return null; + } + } + Fn site = new Fn(f.def, null); + for (int i = 0; i < args.size(); i++) { + site.params[i] = args.get(i); + site.locals.put(site.names.get(i), args.get(i)); } + Ty t = type(body, site, f.def.scope); + return !t.opt && (t.k == Ty.K.INT || t.k == Ty.K.FLOAT || t.k == Ty.K.BOOL) ? t : null; } - private int site(Expr e) { - Integer s = siteOf.get(e); - if (s == null) { - s = Integer.valueOf(siteElem.size()); - siteElem.add(Ty.BOT); - siteOf.put(e, s); + /// The returned expression of a function whose body is only `return + /// ` (after an optional docstring), the arithmetic made of + /// operators, constants, its parameters and global names; else null. + static Expr exprBody(FunctionDef d) { + List b = d.body; + int i = 0; + if (b.size() == 2 && b.get(0) instanceof ExprStmt && ((ExprStmt) b.get(0)).value instanceof Constant) { + i = 1; } - return s.intValue(); + if (b.size() != i + 1 || !(b.get(i) instanceof Return) || ((Return) b.get(i)).value == null) { + return null; + } + Expr e = ((Return) b.get(i)).value; + return arithmetic(e, d.scope) ? e : null; } - private void unify() { - // Methods of one name and arity are called through one virtual - // signature (TypedEmit), so they share their parameter types. - Map> groups = new LinkedHashMap>(); - for (Fn f : fns.values()) { - if (f.cls != null && !f.def.name.equals("__init__")) { - String key = f.def.name + "/" + f.params.length; - List g = groups.get(key); - if (g == null) { - g = new ArrayList(); - groups.put(key, g); - } - g.add(f); - } + private static boolean arithmetic(Expr e, Scope sc) { + if (e instanceof Constant) { + return true; } - for (List g : groups.values()) { - if (g.size() < 2) { - continue; - } - int n = g.get(0).params.length; - for (int i = 1; i < n; i++) { - Ty j = Ty.BOT; - for (Fn f : g) { - j = Ty.join(j, f.params[i]); - } - for (Fn f : g) { - f.params[i] = joinInto(f.params[i], j); - } - } - Ty r = Ty.BOT; - for (Fn f : g) { - r = Ty.join(r, f.ret); - } - for (Fn f : g) { - f.ret = joinInto(f.ret, r); - } + if (e instanceof Name) { + Scope.Binding r = sc.resolve(((Name) e).id); + return r == Scope.Binding.GLOBAL || sc.params.contains(((Name) e).id); + } + if (e instanceof BinOp) { + return arithmetic(((BinOp) e).left, sc) && arithmetic(((BinOp) e).right, sc); } + if (e instanceof UnaryOp) { + return arithmetic(((UnaryOp) e).operand, sc); + } + return false; } - // ---- walking --------------------------------------------------------- + /// Module globals bound once, at the top level, to an int literal (`M32 = + /// 0xFFFFFFFF`): their value is known wherever a function reads them. + final Map intConsts = new HashMap(); - /// `fn` is the compiled function being walked, or null where names are - /// not tracked (the module body tracks globals instead). - private void walkBlock(List body, Fn fn, Scope sc) { + private void intConstants(List body) { for (Stmt s : body) { - walk(s, fn, sc); + if (s instanceof Assign && ((Assign) s).targets.size() == 1 + && ((Assign) s).targets.get(0) instanceof Name) { + String n = ((Name) ((Assign) s).targets.get(0)).id; + java.math.BigInteger v = IntRanges.literal(((Assign) s).value); + if (v != null && stable(n)) { + intConsts.put(n, v); + } + } } } - private void walk(Stmt s, Fn fn, Scope sc) { - if (s instanceof ExprStmt) { - type(((ExprStmt) s).value, fn, sc); - } else if (s instanceof Assign) { - Assign a = (Assign) s; - Ty v = type(a.value, fn, sc); - for (Expr t : a.targets) { - store(t, v, a.value, fn, sc); - } - } else if (s instanceof AnnAssign) { - AnnAssign a = (AnnAssign) s; - if (a.value != null) { - store(a.target, type(a.value, fn, sc), a.value, fn, sc); - } else if (!(a.target instanceof Name)) { - type(a.target, fn, sc); - } - } else if (s instanceof AugAssign) { - AugAssign a = (AugAssign) s; - Ty cur = type(a.target, fn, sc); - Ty v = type(a.value, fn, sc); - Ty r = binop(a.op, cur, v, a.value); - if (cur.k == Ty.K.LIST && "+".equals(a.op)) { - storeElem(cur, elem(v)); - r = cur; - } - store(a.target, r, null, fn, sc); - } else if (s instanceof Return) { - Return r = (Return) s; - Ty v = r.value == null ? Ty.NONE : type(r.value, fn, sc); - if (fn != null && sc == fn.def.scope) { //NOPMD CompareObjectsWithEquals - identity is meant - fn.ret = joinInto(fn.ret, v); - } else { - escape(v); - } - } else if (s instanceof If) { - If i = (If) s; - type(i.test, fn, sc); - walkBlock(i.body, fn, sc); - walkBlock(i.orelse, fn, sc); - } else if (s instanceof While) { - While w = (While) s; - type(w.test, fn, sc); - walkBlock(w.body, fn, sc); - walkBlock(w.orelse, fn, sc); - } else if (s instanceof For) { - For f = (For) s; - Ty it = iterElem(f.iter, fn, sc); - store(f.target, it, null, fn, sc); - walkBlock(f.body, fn, sc); - walkBlock(f.orelse, fn, sc); - } else if (s instanceof FunctionDef) { - FunctionDef d = (FunctionDef) s; - for (Expr e : d.decorators) { - type(e, fn, sc); - } - for (Expr e : d.args.defaults) { - type(e, fn, sc); - } - for (Expr e : d.args.kwDefaults) { - if (e != null) { - type(e, fn, sc); - } - } - Fn inner = fns.get(d); - if (inner != null) { - // Defaults fill parameters the call leaves out. - int first = inner.params.length - d.args.defaults.size(); - for (int i = 0; i < d.args.defaults.size(); i++) { - inner.params[first + i] = joinInto(inner.params[first + i], type(d.args.defaults.get(i), fn, sc)); - } - if (!d.decorators.isEmpty() || inner.cls == null && !globalFns.containsValue(inner)) { - escapeFn(inner); - } - for (int i = 0; i < inner.params.length; i++) { - inner.locals.put(inner.names.get(i), Ty.join(inner.locals.get(inner.names.get(i)), inner.params[i])); - } - walkBlock(d.body, inner, d.scope); - if (!endsAbruptly(d.body)) { - inner.ret = joinInto(inner.ret, Ty.NONE); - } - if (inner.def.name.startsWith("__") && !"__init__".equals(inner.def.name)) { - // The runtime calls these itself, with anything. - escapeFn(inner); - inner.ret = joinInto(inner.ret, Ty.DYN); - } - } else { - walkBlock(d.body, null, d.scope); - } - if (sc.kind == Scope.Kind.MODULE && fns.get(d) == null) { - storeName(d.name, Ty.DYN, fn, sc); - } - } else if (s instanceof ClassDef) { - ClassDef c = (ClassDef) s; - for (Expr b : c.bases) { - if (!(b instanceof Name && globalClasses.containsKey(((Name) b).id))) { - type(b, fn, sc); - } - } - for (Expr d : c.decorators) { - type(d, fn, sc); - } - walkBlock(c.body, null, c.scope); - } else if (s instanceof Try) { - Try t = (Try) s; - walkBlock(t.body, fn, sc); - for (ExceptHandler h : t.handlers) { - if (h.type != null) { - type(h.type, fn, sc); - } - if (h.name != null) { - storeName(h.name, Ty.DYN, fn, sc); - } - walkBlock(h.body, fn, sc); - } - walkBlock(t.orelse, fn, sc); - walkBlock(t.finalbody, fn, sc); - } else if (s instanceof With) { - With w = (With) s; - for (WithItem i : w.items) { - type(i.context, fn, sc); - if (i.vars != null) { - store(i.vars, Ty.DYN, null, fn, sc); - } - } - walkBlock(w.body, fn, sc); - } else if (s instanceof Import || s instanceof ImportFrom) { + private boolean stable(String n) { + Integer c = moduleBindings.get(n); + return c != null && c.intValue() == 1; + } + + /// Counts the bindings of each global at the top level, and every + /// `global` declaration in a function as one more (such a store is + /// invisible to a module-level count). + private final Set topImported = new HashSet(); + + private void countBindings(List body) { + for (Stmt s : body) { List names = new ArrayList(); - if (s instanceof Import) { + if (s instanceof FunctionDef) { + names.add(((FunctionDef) s).name); + } else if (s instanceof ClassDef) { + names.add(((ClassDef) s).name); + } else if (s instanceof Assign) { + for (Expr t : ((Assign) s).targets) { + targetNames(t, names); + } + } else if (s instanceof AugAssign) { + targetNames(((AugAssign) s).target, names); + targetNames(((AugAssign) s).target, names); + } else if (s instanceof AnnAssign) { + targetNames(((AnnAssign) s).target, names); + } else if (s instanceof Import) { for (Alias a : ((Import) s).names) { String n = a.asname != null ? a.asname : a.name; int dot = n.indexOf('.'); - names.add(dot < 0 ? n : n.substring(0, dot)); + String top = dot < 0 ? n : n.substring(0, dot); + // `import xml.sax` then `import xml.sax.handler`: each + // binds `xml` to the one package, so it is one binding. + if (a.asname != null || topImported.add(top)) { + names.add(top); + } } - } else { + } else if (s instanceof ImportFrom) { for (Alias a : ((ImportFrom) s).names) { names.add(a.asname != null ? a.asname : a.name); } - } - for (String n : names) { - storeName(n, Ty.DYN, fn, sc); - } - } else { - // Raise, Assert, Delete, Match, Global, Pass, Break, Continue: - // whatever they evaluate escapes. - anyChildren(s, fn, sc); + } else { + // A compound statement: everything it binds counts twice, + // since it may run any number of times. + for (String n : moduleScope.assigned) { + if (binds(s, n)) { + names.add(n); + names.add(n); + } + } + } + for (String n : names) { + Integer c = moduleBindings.get(n); + moduleBindings.put(n, Integer.valueOf(c == null ? 1 : c.intValue() + 1)); + } } + globalDecls(body); } - private static boolean endsAbruptly(List body) { - if (body.isEmpty()) { - return false; + private void globalDecls(Object o) { + if (o instanceof Global && !((Global) o).nonlocal) { + for (String n : ((Global) o).names) { + moduleBindings.put(n, Integer.valueOf(99)); + } } - Stmt s = body.get(body.size() - 1); - if (s instanceof Return || s instanceof Raise) { - return true; + children(o, x -> globalDecls(x)); + } + + private static boolean binds(Stmt s, String n) { + List out = new ArrayList(); + boundIn(s, out); + return out.contains(n); + } + + /// The names a statement stores into, outside nested scopes. + private static void boundIn(Object o, List out) { + if (o instanceof Lambda || o instanceof Comp) { + return; } - if (s instanceof If) { - If i = (If) s; - return endsAbruptly(i.body) && endsAbruptly(i.orelse); + if (o instanceof FunctionDef) { + out.add(((FunctionDef) o).name); + return; } - if (s instanceof While) { - While w = (While) s; - return w.test instanceof Constant && ((Constant) w.test).kind == Constant.Kind.TRUE && !hasBreak(w.body); + if (o instanceof ClassDef) { + out.add(((ClassDef) o).name); + return; } - return false; - } - - static boolean hasBreak(List body) { - for (Stmt s : body) { - if (s instanceof Break) { - return true; + if (o instanceof Assign) { + for (Expr t : ((Assign) o).targets) { + targetNames(t, out); } - if (s instanceof If && (hasBreak(((If) s).body) || hasBreak(((If) s).orelse))) { - return true; + } else if (o instanceof AugAssign) { + targetNames(((AugAssign) o).target, out); + } else if (o instanceof AnnAssign) { + targetNames(((AnnAssign) o).target, out); + } else if (o instanceof For) { + targetNames(((For) o).target, out); + } else if (o instanceof WithItem && ((WithItem) o).vars != null) { + targetNames(((WithItem) o).vars, out); + } else if (o instanceof NamedExpr) { + out.add(((NamedExpr) o).target.id); + } else if (o instanceof ExceptHandler && ((ExceptHandler) o).name != null) { + out.add(((ExceptHandler) o).name); + } else if (o instanceof Import) { + for (Alias a : ((Import) o).names) { + String n = a.asname != null ? a.asname : a.name; + int dot = n.indexOf('.'); + out.add(dot < 0 ? n : n.substring(0, dot)); } - if (s instanceof Try) { - Try t = (Try) s; - if (hasBreak(t.body) || hasBreak(t.orelse) || hasBreak(t.finalbody)) { - return true; - } - for (ExceptHandler h : t.handlers) { - if (hasBreak(h.body)) { - return true; - } - } + } else if (o instanceof ImportFrom) { + for (Alias a : ((ImportFrom) o).names) { + out.add(a.asname != null ? a.asname : a.name); } - if (s instanceof With && hasBreak(((With) s).body)) { - return true; + } else if (o instanceof Delete) { + for (Expr t : ((Delete) o).targets) { + targetNames(t, out); } } - return false; + children(o, x -> boundIn(x, out)); } - /// The type of the items `for x in it` binds. - Ty iterElem(Expr it, Fn fn, Scope sc) { - if (rangeCall(it, sc)) { - for (Expr a : ((Call) it).args) { - type(a, fn, sc); - } - return Ty.INT; + /// Whether function `f` binds `n` itself -- a parameter, or a store + /// in its body outside nested scopes -- and declares it neither + /// `global` nor `nonlocal`. For passes that run before the scopes are + /// built. + static boolean bindsLocally(FunctionDef f, String n) { + if (f.args.names().contains(n)) { + return true; } - Ty t = type(it, fn, sc); - if (t.k == Ty.K.LIST) { - return elem(t); + List out = new ArrayList(); + boolean[] declared = new boolean[1]; + for (Stmt s : f.body) { + boundIn(s, out); + declaresIn(s, n, declared); } - if (t.k == Ty.K.STR && !t.opt) { - // A str yields one-character strs. - return Ty.STR; + return out.contains(n) && !declared[0]; + } + + private static void declaresIn(Object o, String n, boolean[] r) { + if (o instanceof FunctionDef || o instanceof ClassDef || o instanceof Lambda || o instanceof Comp) { + return; } - if (t.k == Ty.K.BOT) { - // Nothing reaches the iterable yet; a later pass decides. - return Ty.BOT; + if (o instanceof Global && ((Global) o).names.contains(n)) { + r[0] = true; } - escape(t); - return Ty.DYN; + children(o, x -> declaresIn(x, n, r)); } - boolean rangeCall(Expr e, Scope sc) { - if (!(e instanceof Call)) { - return false; + private static void targetNames(Expr t, List out) { + if (t instanceof Name) { + out.add(((Name) t).id); + } else if (t instanceof TupleExpr) { + for (Expr e : ((TupleExpr) t).elts) { + targetNames(e, out); + } + } else if (t instanceof ListExpr) { + for (Expr e : ((ListExpr) t).elts) { + targetNames(e, out); + } + } else if (t instanceof Starred) { + targetNames(((Starred) t).value, out); } - Call c = (Call) e; - return c.func instanceof Name && "range".equals(((Name) c.func).id) && c.keywords.isEmpty() - && c.args.size() >= 1 && c.args.size() <= 3 && sc.resolve("range") == Scope.Binding.BUILTIN - && !moduleScope.hasStarImport && !anyStarred(c.args); } - private static boolean anyStarred(List l) { - for (Expr e : l) { - if (e instanceof Starred) { - return true; + /// A class some class the layout planner rejected derives from: its + /// instances may run methods this pass does not see, so neither it nor + /// its ancestors are typed. + private void markOpen(Object o) { + if (o instanceof ClassDef) { + ClassDef c = (ClassDef) o; + if (!layouts.classes.containsKey(c)) { + for (Expr b : c.bases) { + if (b instanceof Name) { + Layouts.Cls k = byName(((Name) b).id); + for (; k != null; k = k.parent) { + open.add(k); + } + } + } } } - return false; + children(o, x -> markOpen(x)); } - private void store(Expr t, Ty v, Expr value, Fn fn, Scope sc) { - if (t instanceof Name) { - storeName(((Name) t).id, v, fn, sc); - } else if (t instanceof Attribute) { - Attribute a = (Attribute) t; - Ty r = type(a.value, fn, sc); - storeField(r, a.attr, v); - } else if (t instanceof Subscript) { - Subscript s = (Subscript) t; - Ty r = type(s.value, fn, sc); - if (s.index instanceof Slice) { - anyChildren(s.index, fn, sc); - if (r.k == Ty.K.LIST) { - storeElem(r, elem(v)); - } else { - escape(v); - } - } else { - type(s.index, fn, sc); - if (r.k == Ty.K.LIST) { - storeElem(r, v); - } else if (r.k != Ty.K.BOT) { - escape(v); - } + /// Whether a top-level class here the planner rejected has one base + /// that another module defines. + boolean mayExtendForeign() { + for (Stmt s : body) { + // Any base may be another module's: the compiled parent, a + // mixin ([Layouts#foreignMixin]) or the class after a builtin + // first base (`class BaseEnum(int, enum.Enum)`). + if (s instanceof ClassDef && !((ClassDef) s).decorators.isEmpty() && layouts.refused.containsKey(s)) { + // A decorated class is planned again once the globals are + // known for good: a decorator that answers its argument + // (Layouts#returnsItsClass) keeps the layout. + return true; } - } else if (t instanceof TupleExpr || t instanceof ListExpr) { - List elts = t instanceof TupleExpr ? ((TupleExpr) t).elts : ((ListExpr) t).elts; - List src = value instanceof TupleExpr ? ((TupleExpr) value).elts - : value instanceof ListExpr ? ((ListExpr) value).elts : null; - boolean starred = anyStarred(elts); - if (src != null && src.size() == elts.size() && !starred && !anyStarred(src)) { - // `a, b = x, y` pairs each target with its own value. - for (int i = 0; i < elts.size(); i++) { - store(elts.get(i), type(src.get(i), fn, sc), null, fn, sc); + if (s instanceof ClassDef && !layouts.classes.containsKey(s)) { + for (Expr b : ((ClassDef) s).bases) { + Infer h = classHome(b); + if (h != null && h != this) { //NOPMD CompareObjectsWithEquals - identity is meant + return true; + } } - return; } - Ty each = Ty.DYN; - if (value != null && rangeCall(value, sc)) { - each = Ty.INT; - } else if (v.k == Ty.K.LIST) { - each = elem(v); - } else { - escape(v); + } + return false; + } + + /// Why the build found no class of another module that base `b` names + /// for good, for the strict report; null when it found one (the base + /// then has no layout of its own) or `b` is not a module's name. + private String noHomeWhy(Expr base) { + Expr b = Layouts.origin(base); + Infer m; + String n; + if (b instanceof Attribute) { + m = moduleOf(((Attribute) b).value, 0); + n = ((Attribute) b).attr; + if (m == null) { + return Layouts.text(((Attribute) b).value) + " is not a module the build resolves for good"; } - for (Expr e : elts) { - store(e instanceof Starred ? ((Starred) e).value : e, e instanceof Starred ? Ty.DYN : each, null, fn, - sc); + } else if (b instanceof Name) { + Extern g = moduleScope.resolve(((Name) b).id) == Scope.Binding.GLOBAL ? importedNames.get(((Name) b).id) : null; + if (g == null) { + return null; } - } else if (t instanceof Starred) { - store(((Starred) t).value, Ty.DYN, null, fn, sc); + m = g.module; + n = g.name; } else { - anyChildren(t, fn, sc); - escape(v); + return null; + } + if (m.definer(n, 0) != null) { + return null; } + if (!m.moduleScope.assigned.contains(n)) { + return m.moduleName + " binds no global " + n; + } + Integer c = m.moduleBindings.get(n); + if (c != null && c.intValue() == 99) { + return m.facts.namespace ? m.moduleName + " hands its namespace out, so " + n + " may be rebound" + : m.moduleName + "." + n + " may be rebound: the program stores an attribute named " + n + + " on a value the build cannot tell from the module"; + } + if (c != null && c.intValue() > 1) { + return m.moduleName + " binds " + n + " " + c + " times"; + } + return m.moduleName + "." + n + " is not a class the build can follow there"; } - private void storeName(String n, Ty v, Fn fn, Scope sc) { - switch (sc.resolve(n)) { - case LOCAL: - if (fn != null && sc == fn.def.scope) { //NOPMD CompareObjectsWithEquals - identity is meant - fn.locals.put(n, joinInto(fn.locals.get(n), v)); - } else { - escape(v); + /// Whether a base [#mayExtendForeign] found is in a module still to be + /// planned again. + boolean waitsOn(Set waiting) { + for (Stmt s : body) { + if (s instanceof ClassDef) { + for (Expr b : ((ClassDef) s).bases) { + Infer h = classHome(b); + if (h != null && h != this && waiting.contains(h)) { //NOPMD CompareObjectsWithEquals - identity is meant + return true; + } } - return; - case GLOBAL: - globals.put(n, joinInto(globals.get(n), v)); - return; - default: - escape(v); + } } + return false; } - void storeField(Ty recv, String attr, Ty v) { - if (recv.k == Ty.K.BOT || recv.k == Ty.K.NONE) { - return; + /// The module whose body defines the class base expression `b` names, + /// by the same rules as [#foreignClass], or null. + private Infer classHome(Expr base) { + Expr b = Layouts.origin(base); + if (b instanceof Name) { + String n = ((Name) b).id; + Extern g = moduleScope.resolve(n) == Scope.Binding.GLOBAL ? importedNames.get(n) : null; + if (g == null) { + // A star import binds it, as in [#foreignClass]. + Infer sp = starProvider(n); + return sp == null ? null : sp.definer(n, 0); + } + return g.module.definer(g.name, 0); } - List owners = layouts.fieldOwners.get(attr); - if (owners == null) { - escape(v); - return; + if (b instanceof Attribute) { + Infer m = moduleOf(((Attribute) b).value, 0); + return m == null ? null : m.definer(((Attribute) b).attr, 0); } - boolean any = false; - for (Layouts.Cls o : owners) { - boolean reach = recv.k != Ty.K.INST || isSelfOrAncestor(o, recv.cls) || isSelfOrAncestor(recv.cls, o); - if (reach) { - Map m = fields.get(o); - m.put(attr, joinInto(m.get(attr), v)); - any = true; + return null; + } + + /// The module of the program expression `e` names for good, or null: a + /// global an `import` binds to a module, or a dotted attribute of one + /// (`xml.sax.handler` in `class X(xml.sax.handler.ContentHandler)`) + /// naming a submodule of the build whose package binds nothing over that + /// name and whose name no statement of the program stores as an + /// attribute, so the attribute is the submodule whenever it is read. + private Infer moduleOf(Expr e, int depth) { + if (e instanceof Name) { + String n = ((Name) e).id; + return moduleScope.resolve(n) == Scope.Binding.GLOBAL ? moduleNames.get(n) : null; + } + if (!(e instanceof Attribute) || depth > 8) { + return null; + } + String a = ((Attribute) e).attr; + Infer pkg = moduleOf(((Attribute) e).value, depth + 1); + if (pkg == null || pkg.moduleScope.assigned.contains(a) || pkg.moduleScope.hasStarImport + || facts.attrStored(a)) { + return null; + } + return p.modules.get(pkg.moduleName + "." + a); + } + + /// The top-level class `n` this module defines after its last star + /// import, or null. + private ClassDef classAfterStars(String n) { + ClassDef d = null; + for (Stmt s : body) { + if (s instanceof ImportFrom && starImport((ImportFrom) s)) { + d = null; + } else if (s instanceof ClassDef && ((ClassDef) s).name.equals(n)) { + d = (ClassDef) s; } } - if (!any) { - escape(v); + return d; + } + + private static boolean starImport(ImportFrom s) { + for (Node.Alias a : s.names) { + if ("*".equals(a.name)) { + return true; + } } + return false; } - /// The declaring class of field `attr` for an instance of `k`. - static Layouts.Cls fieldOwner(Layouts.Cls k, String attr) { - for (Layouts.Cls c = k; c != null; c = c.parent) { - if (c.fields.contains(attr)) { - return c; + private Infer definer(String n, int depth) { + Infer via = depth > 8 ? null : starProvider(n); + if (via != null) { + return via.definer(n, depth + 1); + } + if (depth > 8 || !moduleScope.assigned.contains(n) || !stable(n)) { + return null; + } + if (moduleScope.hasStarImport) { + // A star import may bind any name, but not over a class + // defined after it: the definition binds the name last. + ClassDef d = classAfterStars(n); + if (d != null) { + return this; + } + Extern si = importedNames.get(n); + return si == null ? null : si.module.definer(si.name, depth + 1); + } + for (Stmt s : body) { + if (s instanceof ClassDef && ((ClassDef) s).name.equals(n)) { + return this; + } + } + Expr alias = specialAliasExpr(n); + if (alias != null) { + return classHome(alias); + } + Extern g = importedNames.get(n); + return g == null ? null : g.module.definer(g.name, depth + 1); + } + + /// The compiled class of another module base expression `b` of a + /// top-level class names, or null: an imported name, or an attribute + /// of an imported module, bound once on each side. Needs the imports + /// bound, and none of the classes collected. + Layouts.Cls foreignClass(Expr base) { + Expr b = Layouts.origin(base); + if (b instanceof Name) { + String n = ((Name) b).id; + Extern g = moduleScope.resolve(n) == Scope.Binding.GLOBAL ? importedNames.get(n) : null; + if (g == null) { + // `from enum import *` then `class C(Enum)`: the last star + // import exporting the name binds it, when the module binds + // it nowhere itself ([#starProvider]). + Infer sp = starProvider(n); + return sp == null ? null : sp.exportedClass(n, 0); } + return g.module.exportedClass(g.name, 0); + } + if (b instanceof Attribute) { + Infer m = moduleOf(((Attribute) b).value, 0); + return m == null ? null : m.exportedClass(((Attribute) b).attr, 0); } return null; } - Ty fieldType(Layouts.Cls owner, String attr) { - Ty t = fields.get(owner).get(attr); - return t == null ? Ty.DYN : t; + /// Whether global `n` of this module holds a constant literal for the + /// whole run: bound once, here to a [#constantExpr] or by a from-import of such + /// a global of another module, never stored as an attribute by name + /// anywhere in the program, and no star import that could rebind it. + /// openpyxl's `Relation(String)` binds `namespace = REL_NS`, imported + /// from `openpyxl.xml.constants` ([Layouts#plainDefault]). + /// Whether global `n` is bound once, at the top level of this module, + /// and no module stores it as an attribute or through a namespace. + boolean fixedGlobal(String n) { + return moduleScope.resolve(n) == Scope.Binding.GLOBAL && !moduleScope.hasStarImport + && moduleScope.assigned.contains(n) && stable(n) && !facts.attrStored(n); } - /// Compiled methods a call `recv.m(...)` on an instance of `k` may run: - /// the one `k` resolves, and every override in a subclass of `k`. Null - /// when the name may resolve to anything else (a field, a class - /// attribute that is not a compiled method). - List candidates(Layouts.Cls k, String m) { - if (layouts.fieldOwners.containsKey(m)) { + boolean constantGlobal(String n) { + return moduleScope.resolve(n) == Scope.Binding.GLOBAL && constantGlobal(n, 0); + } + + private boolean constantGlobal(String n, int depth) { + if (depth > 8 || moduleScope.hasStarImport || !moduleScope.assigned.contains(n) || !stable(n) + || facts.attrStored(n)) { + return false; + } + for (Stmt s : body) { + if (s instanceof Assign && ((Assign) s).targets.size() == 1 && ((Assign) s).targets.get(0) instanceof Name + && ((Name) ((Assign) s).targets.get(0)).id.equals(n)) { + return constantExpr(((Assign) s).value, depth); + } + } + Extern g = importedNames.get(n); + return g != null && g.module.constantGlobal(g.name, depth + 1); + } + + /// The one string `e` is at build time: a str constant, a local + /// [#constString], a [#constantGlobal] of this module bound to such a + /// string, or `+` of two such; null when it is not one known string. + String foldedString(Expr e, Fn fn, Scope sc, int depth) { + if (depth > 8) { return null; } - List r = new ArrayList(); - Layouts.Cls res = Layouts.resolver(k, m); - if (res != null) { - FunctionDef f = res.typable.get(m); - if (f == null) { + String one = constString(e, fn, sc); + if (one != null) { + return one; + } + if (e instanceof BinOp && "+".equals(((BinOp) e).op)) { + String l = foldedString(((BinOp) e).left, fn, sc, depth + 1); + String r = l == null ? null : foldedString(((BinOp) e).right, fn, sc, depth + 1); + return r == null ? null : l + r; + } + if (e instanceof Call) { + return foldedCall((Call) e, fn, sc, depth); + } + if (!(e instanceof Name) || sc == null || sc.resolve(((Name) e).id) != Scope.Binding.GLOBAL + || !constantGlobal(((Name) e).id)) { + return null; + } + String n = ((Name) e).id; + for (Stmt s : body) { + if (s instanceof Assign && ((Assign) s).targets.size() == 1 && isName(((Assign) s).targets.get(0), n)) { + return foldedString(((Assign) s).value, null, moduleScope, depth + 1); + } + } + return null; + } + + /// `g(a, b)`, a call of a function this module defines once at its top + /// level, undecorated, whose whole body returns a string made of its + /// parameters, literals, `+` and `"sep".join(args)` of its `*args`, + /// with arguments that fold to strings: the string it returns, computed + /// at build time. Null for anything else. + private String foldedCall(Call c, Fn fn, Scope sc, int depth) { + if (!(c.func instanceof Name) || !c.keywords.isEmpty() || sc == null + || sc.resolve(((Name) c.func).id) != Scope.Binding.GLOBAL || !stable(((Name) c.func).id)) { + return null; + } + String g = ((Name) c.func).id; + FunctionDef d = null; + for (Stmt s : body) { + if (s instanceof FunctionDef && ((FunctionDef) s).name.equals(g)) { + d = (FunctionDef) s; + } + } + if (d == null || !d.decorators.isEmpty() || d.isAsync || d.body.size() != 1 || !(d.body.get(0) instanceof Return) + || ((Return) d.body.get(0)).value == null || !d.args.kwonly.isEmpty() || d.args.kwarg != null + || !d.args.defaults.isEmpty() || c.args.size() < d.args.positional.size() + || d.args.vararg == null && c.args.size() != d.args.positional.size()) { + return null; + } + Map env = new HashMap(); + List rest = new ArrayList(); + for (int i = 0; i < c.args.size(); i++) { + if (c.args.get(i) instanceof Starred) { return null; } - r.add(f); + String v = foldedString(c.args.get(i), fn, sc, depth + 1); + if (v == null) { + return null; + } + if (i < d.args.positional.size()) { + env.put(d.args.positional.get(i).name, v); + } else { + rest.add(v); + } } - for (Layouts.Cls c : layouts.classes.values()) { - if (c != k && isSelfOrAncestor(k, c) && c.bodyNames.contains(m)) { //NOPMD CompareObjectsWithEquals - identity is meant - FunctionDef f = c.typable.get(m); - if (f == null) { + return evalString(((Return) d.body.get(0)).value, env, d.args.vararg == null ? null : d.args.vararg.name, rest); + } + + private static String evalString(Expr e, Map env, String vararg, List rest) { + if (e instanceof Constant && ((Constant) e).kind == Constant.Kind.STR) { + return ((Constant) e).text; + } + if (e instanceof Name) { + return env.get(((Name) e).id); + } + if (e instanceof BinOp && "+".equals(((BinOp) e).op)) { + String l = evalString(((BinOp) e).left, env, vararg, rest); + String r = l == null ? null : evalString(((BinOp) e).right, env, vararg, rest); + return r == null ? null : l + r; + } + if (e instanceof Call && ((Call) e).func instanceof Attribute && ((Call) e).keywords.isEmpty() + && ((Call) e).args.size() == 1 && vararg != null && isName(((Call) e).args.get(0), vararg) + && "join".equals(((Attribute) ((Call) e).func).attr) + && ((Attribute) ((Call) e).func).value instanceof Constant + && ((Constant) ((Attribute) ((Call) e).func).value).kind == Constant.Kind.STR) { + return String.join(((Constant) ((Attribute) ((Call) e).func).value).text, rest); + } + return null; + } + + /// A literal, a [#constantGlobal] of this module, or `+` of two such + /// (openpyxl's `REL_NS = DOC_NS + "relationships"`): its value is one + /// immutable literal, computed once at import. + private boolean constantExpr(Expr e, int depth) { + if (e instanceof Constant) { + return true; + } + if (e instanceof Name) { + return constantGlobal(((Name) e).id, depth + 1); + } + return e instanceof BinOp && "+".equals(((BinOp) e).op) && depth < 8 + && constantExpr(((BinOp) e).left, depth + 1) && constantExpr(((BinOp) e).right, depth + 1); + } + + /// The class statement of another module a base expression names, as + /// [#foreignClass] finds it, whether or not it was compiled; or null. + ClassDef foreignClassDef(Expr base) { + Expr b = Layouts.origin(base); + if (b instanceof Name) { + String n = ((Name) b).id; + Extern g = moduleScope.resolve(n) == Scope.Binding.GLOBAL ? importedNames.get(n) : null; + return g == null ? null : g.module.exportedDef(g.name, 0); + } + if (b instanceof Attribute) { + Infer m = moduleOf(((Attribute) b).value, 0); + return m == null ? null : m.exportedDef(((Attribute) b).attr, 0); + } + return null; + } + + private ClassDef exportedDef(String n, int depth) { + Infer via = depth > 8 ? null : starProvider(n); + if (via != null) { + return via.exportedDef(n, depth + 1); + } + if (depth > 8 || !moduleScope.assigned.contains(n) || !stable(n)) { + return null; + } + if (moduleScope.hasStarImport) { + // A star import may bind any name, but not over a class + // defined after it: the definition binds the name last. + ClassDef d = classAfterStars(n); + Extern si = d == null ? importedNames.get(n) : null; + return si == null ? d : si.module.exportedDef(si.name, depth + 1); + } + for (Stmt s : body) { + if (s instanceof ClassDef && ((ClassDef) s).name.equals(n)) { + return (ClassDef) s; + } + } + Extern g = importedNames.get(n); + return g == null ? null : g.module.exportedDef(g.name, depth + 1); + } + + private Layouts.Cls exportedClass(String n, int depth) { + Infer via = depth > 8 ? null : starProvider(n); + if (via != null) { + return via.exportedClass(n, depth + 1); + } + if (depth > 8 || !moduleScope.assigned.contains(n) || !stable(n)) { + return null; + } + if (moduleScope.hasStarImport) { + // As [#exportedDef]: openpyxl's `Strict`, defined after + // `from .base import *`, is the class the name holds. + // A from-import [#bindImports] kept is the name's one binding: + // no star import can bind it (openpyxl.descriptors' `from + // .sequence import Sequence` beside `from .base import *`). + ClassDef d = classAfterStars(n); + Extern si = d == null ? importedNames.get(n) : null; + return si != null ? si.module.exportedClass(si.name, depth + 1) : d == null ? null : layouts.all().get(d); + } + for (Stmt s : body) { + if (s instanceof ClassDef && ((ClassDef) s).name.equals(n)) { + return layouts.all().get(s); + } + } + Layouts.Cls alias = specialAliasOrigin(n); + if (alias != null) { + return alias; + } + Extern g = importedNames.get(n); + return g == null ? null : g.module.exportedClass(g.name, depth + 1); + } + + /// `typing`'s `Mapping = _SpecialGenericAlias(_abc.Mapping, "Mapping", 2)`: + /// the alias's `__mro_entries__` answers its origin alone, so a class + /// deriving from `Mapping[K, V]` has the `collections.abc` class as its + /// only base. The runtime confirms that base before it gives the + /// subclass its layout (`bases[0] == parent`), so nothing is assumed. + private Layouts.Cls specialAliasOrigin(String n) { + Expr e = specialAliasExpr(n); + return e == null ? null : foreignClass(e); + } + + /// The origin expression (`_abc.Mapping`) of [#specialAliasOrigin], or null. + private Expr specialAliasExpr(String n) { + if (!"typing".equals(moduleName)) { + return null; + } + for (Stmt s : body) { + if (s instanceof Assign && ((Assign) s).targets.size() == 1 && ((Assign) s).targets.get(0) instanceof Name + && ((Name) ((Assign) s).targets.get(0)).id.equals(n) && ((Assign) s).value instanceof Call) { + Call c = (Call) ((Assign) s).value; + if (c.func instanceof Name && "_SpecialGenericAlias".equals(((Name) c.func).id) && !c.args.isEmpty() + && c.args.get(0) instanceof Attribute) { + return c.args.get(0); + } + return null; + } + } + return null; + } + + /// [#markOpen] for a base another module compiled: a class here the + /// planner rejected (or one built inside a function) that derives from + /// it makes it and its ancestors open just the same. Its instances run + /// the compiled methods through the generic path with a `self` of no + /// compiled class, which then reaches every field those methods store. + /// Needs the imports bound, so it runs after them. + void markOpenForeign(Object o) { + if (o instanceof ClassDef) { + ClassDef c = (ClassDef) o; + if (!layouts.classes.containsKey(c)) { + Scope bsc = c.scope != null && c.scope.parent != null ? c.scope.parent : moduleScope; + Scope at = c.scope != null && c.scope.parent != null ? c.scope.parent : moduleScope; + // Only a class deriving from a class of the program can be + // an instance of a compiled class's subclass: the compiled + // classes its bases lead to take its names, followed through + // bases the planner rejected too, in this module or another. + // Only a base that cannot be followed may be any class, and + // poisons its names everywhere. Exceptions, a str subclass + // (bs4's NavigableString) and their own subclasses lead to + // no compiled class; 2,090 such classes had put `name`, + // `prefix` and every other name their bodies bind on the + // program-wide list, and no `self.name` of any class -- bs4's + // Tag among them -- was typed. + Set anc = new LinkedHashSet(); + boolean known = true; + for (Expr b : c.bases) { + known &= compiledBases(b, bsc, c, new HashSet(), anc); + } + if (known) { + for (Layouts.Cls k : anc) { + rejectedBelow(k, c.scope.assigned); + } + } else { + p.rejectedAnywhere.addAll(c.scope.assigned); + } + for (Expr b : c.bases) { + Object f = foreign(b, at); + if (f instanceof Layouts.Cls) { + openWithAncestors((Layouts.Cls) f); + continue; + } + // Not a name the pass can follow (a module whose globals + // are not stable, an alias): every compiled class of the + // program by that name may be the base. + String n = b instanceof Name ? ((Name) b).id : b instanceof Attribute ? ((Attribute) b).attr : null; + if (n != null && !(b instanceof Name && byName(n) != null)) { + for (Layouts.Cls k : p.home.keySet()) { + if (k.def.name.equals(n)) { + openWithAncestors(k); + } + } + } + } + } + } + children(o, x -> markOpenForeign(x)); + } + + /// Adds to `out` every compiled class an instance of a class deriving + /// from base `b` (written in scope `at` of this module) may be an + /// instance of; false when that cannot be told. + private boolean compiledBases(Expr b, Scope at, Stmt site, Set seen, Set out) { + Expr e = b instanceof Subscript ? ((Subscript) b).value : b; + if (e instanceof Name) { + String n = ((Name) e).id; + Scope.Binding bd = at.resolve(n); + if (bd == Scope.Binding.BUILTIN) { + return true; + } + if (bd != Scope.Binding.GLOBAL) { + return false; + } + ClassDef d = classBinding(n, site); + if (d != null) { + return classBases(d, seen, out); + } + Extern g = importedNames.get(n); + if (g != null && lastBinder(n, site) instanceof ImportFrom) { + return followBase(foreign(e, at), seen, out) + || g.module.localClassBases(g.name, seen, out); + } + return followBase(foreign(e, at), seen, out); + } + if (e instanceof Attribute) { + return followBase(foreign(e, at), seen, out); + } + return false; + } + + private static boolean followBase(Object f, Set seen, Set out) { + if (f instanceof Layouts.Cls) { + out.add((Layouts.Cls) f); + return true; + } + return f instanceof Extern && ((Extern) f).module.localClassBases(((Extern) f).name, seen, out); + } + + /// [#compiledBases] for top-level name `n` of this module as another + /// module imports it: the class statement that binds it last. + private boolean localClassBases(String n, Set seen, Set out) { + ClassDef d = classBinding(n, null); + if (d != null) { + return classBases(d, seen, out); + } + Extern g = importedNames.get(n); + return g != null && lastBinder(n, null) instanceof ImportFrom && seen.add(g) + && g.module.localClassBases(g.name, seen, out); + } + + private boolean classBases(ClassDef d, Set seen, Set out) { + Layouts.Cls k = layouts.all().get(d); + if (k != null) { + out.add(k); + return true; + } + if (!seen.add(d)) { + return true; + } + Scope bsc = d.scope != null && d.scope.parent != null ? d.scope.parent : moduleScope; + for (Expr b : d.bases) { + if (!compiledBases(b, bsc, d, seen, out)) { + return false; + } + } + return true; + } + + /// The class statement of this module's top level that `n` names just + /// before statement `upTo` runs (at the end of the module when `upTo` + /// is null or not a top-level statement), or null when that is not one + /// class statement or cannot be told. A name bound more than once + /// still resolves: minidom imports `Node` and then defines its own + /// `class Node`, which every later class derives from; openpyxl defines + /// `Strict` after a star import. Unknowable when a function declares + /// the name `global` or the module writes its namespace. + private ClassDef classBinding(String n, Stmt upTo) { + Stmt s = lastBinder(n, upTo); + return s instanceof ClassDef ? (ClassDef) s : null; + } + + /// The last top-level statement before `upTo` that may bind `n`; a star + /// import counts, and a compound one stands for what it may bind. + /// Null when there is none or it cannot be told. + private Stmt lastBinder(String n, Stmt upTo) { + Integer c = moduleBindings.get(n); + if (c == null || c.intValue() >= 99 || facts.namespace) { + return null; + } + Stmt last = null; + for (Stmt s : body) { + if (s == upTo) { //NOPMD CompareObjectsWithEquals - identity is meant + break; + } + if (s instanceof ImportFrom && isStar((ImportFrom) s) || binds(s, n)) { + last = s; + } + } + return last; + } + + private static boolean isStar(ImportFrom s) { + for (Alias a : s.names) { + if ("*".equals(a.name)) { + return true; + } + } + return false; + } + + private void rejectedBelow(Layouts.Cls k, Set names) { + for (Layouts.Cls a = k; a != null; a = a.parent) { + Set s = p.rejectedNames.get(a); + if (s == null) { + s = new HashSet(); + p.rejectedNames.put(a, s); + } + s.addAll(names); + } + } + + private boolean anyRejected(String attr) { + for (Set s : p.rejectedNames.values()) { + if (s.contains(attr)) { + return true; + } + } + return false; + } + + /// Whether a rejected class deriving from `k` may bind `attr`. + private boolean rejected(Layouts.Cls k, String attr) { + if (p.rejectedAnywhere.contains(attr)) { + return true; + } + Set s = k == null ? null : p.rejectedNames.get(k); + return s != null && s.contains(attr); + } + + private void openWithAncestors(Layouts.Cls k) { + for (; k != null; k = k.parent) { + p.open.add(k); + } + } + + private Layouts.Cls byName(String n) { + for (Layouts.Cls k : layouts.all().values()) { + if (k.def.name.equals(n)) { + return k; + } + } + return null; + } + + // ---- definite assignment of fields ------------------------------------ + + /// In the answer of `initDefinite`: the `__init__` went on to store an + /// attribute outside the fields. Not a name an attribute can have. + private static final String EXTRA = ""; + + private Set initDefinite(Layouts.Cls k, Set seen) { + Set r = new HashSet(); + Layouts.Cls owner = Layouts.resolver(k, "__init__"); + if (owner == null || !seen.add(owner)) { + return r; + } + FunctionDef f = owner.typable.get("__init__"); + if (f == null) { + // Not compiled typed -- bs4's Tag takes 17 parameters, its + // SoupStrainer **kwargs -- but what it sets is read off the + // statements alone: the one `__init__` the class body defines, + // undecorated, never shadowed by a store. + f = soleInit(owner); + } + if (f == null || f.args.names().isEmpty()) { + return r; + } + String self = f.args.names().get(0); + if (f.scope.assigned.contains(self) || f.args.vararg != null && f.args.vararg.name.equals(self)) { + return r; + } + definiteIn(f.body, new InitWalk(k, owner, self, seen), r); + return r; + } + + /// The `__init__` class `k`'s body defines once, without decorators, + /// or null. + private static FunctionDef soleInit(Layouts.Cls k) { + FunctionDef r = null; + for (Stmt st : k.def.body) { + if (st instanceof FunctionDef && "__init__".equals(((FunctionDef) st).name)) { + if (r != null || !((FunctionDef) st).decorators.isEmpty() || ((FunctionDef) st).isAsync) { + return null; + } + r = (FunctionDef) st; + } else if (!(st instanceof FunctionDef || st instanceof ClassDef)) { + List names = new ArrayList(); + if (st instanceof Assign) { + for (Expr t : ((Assign) st).targets) { + targetNames(t, names); + } + } else if (st instanceof AnnAssign) { + targetNames(((AnnAssign) st).target, names); + } + if (names.contains("__init__")) { return null; } - if (!r.contains(f)) { - r.add(f); + } + } + return r; + } + + /// How a run of `__init__` statements ended, for [#definiteIn]. + private enum InitEnd { + /// It fell through: later statements run after it. + ON, + /// It always raises: nothing after it runs on that path, so what + /// that path set is irrelevant to the fields the object ends with. + RAISES, + /// It reached code that may observe the object -- or ended the + /// constructor early: nothing set after it counts. + STOP + } + + /// What [#definiteIn] needs: the class, the `__init__`'s own class, + /// the name of its first parameter, and the initializers already + /// followed (a cycle of base `__init__` calls). + private static final class InitWalk { + final Layouts.Cls k; + final Layouts.Cls owner; + final String self; + final Set seen; + + InitWalk(Layouts.Cls k, Layouts.Cls owner, String self, Set seen) { + this.k = k; + this.owner = owner; + this.self = self; + this.seen = seen; + } + } + + /// Adds to `r` every field `body` sets on every path that falls + /// through, before anything may read the object. Structured, not + /// straight-line: a field both branches of an `if` set is set, a + /// branch that raises sets nothing anyone sees, and an expression may + /// read a field already set or call a classmethod or staticmethod + /// through the instance -- neither observes a field not yet set. bs4's + /// SoupStrainer sets `name_rules` on both branches of an `if`, from a + /// classmethod called through `self`, and Tag sets `name` and `prefix` + /// after an `if` and a branch that raises; a walk that stopped at the + /// first `if` left all of them untyped. What a path sets is only ever + /// counted when every path sets it, so a read of a field no path set + /// yet still stops the walk. + private InitEnd definiteIn(List body, InitWalk w, Set r) { + for (Stmt s : body) { + InitEnd e = definiteStmt(s, w, r); + if (e != InitEnd.ON) { + return e; + } + } + return InitEnd.ON; + } + + private InitEnd definiteStmt(Stmt s, InitWalk w, Set r) { + if (s instanceof Pass || s instanceof ExprStmt && ((ExprStmt) s).value instanceof Constant) { + return InitEnd.ON; + } + Expr target = null; + Expr value = null; + if (s instanceof Assign && ((Assign) s).targets.size() == 1) { + target = ((Assign) s).targets.get(0); + value = ((Assign) s).value; + } else if (s instanceof AnnAssign && ((AnnAssign) s).value != null) { + target = ((AnnAssign) s).target; + value = ((AnnAssign) s).value; + } + if (target instanceof Attribute && ((Attribute) target).value instanceof Name + && ((Name) ((Attribute) target).value).id.equals(w.self) && observesNothing(value, w, r)) { + if (!w.k.allFields.contains(((Attribute) target).attr)) { + // An attribute kept outside the fields. From here on the + // instance lists its attributes in the order they were + // set, and a field first set after this one is kept with + // them, not in the Java field (PyInstance.store): typed + // code, which reads the field without asking, must not + // count on it. + r.add(EXTRA); + return InitEnd.STOP; + } + r.add(((Attribute) target).attr); + return InitEnd.ON; + } + if (s instanceof Raise && observesNothing(s, w, r)) { + return InitEnd.RAISES; + } + if (s instanceof If && observesNothing(((If) s).test, w, r)) { + If i = (If) s; + Set a = new HashSet(r); + Set b = new HashSet(r); + InitEnd ea = definiteIn(i.body, w, a); + InitEnd eb = definiteIn(i.orelse, w, b); + if (a.contains(EXTRA) || b.contains(EXTRA)) { + // An attribute outside the fields on either path: what + // follows is ordered with it (see above). + r.add(EXTRA); + return InitEnd.STOP; + } + if (ea == InitEnd.RAISES && eb == InitEnd.RAISES) { + return InitEnd.RAISES; + } + if (ea == InitEnd.RAISES) { + r.addAll(b); + return eb; + } + if (eb == InitEnd.RAISES) { + r.addAll(a); + return ea; + } + a.retainAll(b); + r.addAll(a); + return ea == InitEnd.STOP || eb == InitEnd.STOP ? InitEnd.STOP : InitEnd.ON; + } + if (s instanceof ExprStmt && ((ExprStmt) s).value instanceof Call) { + Call c = (Call) ((ExprStmt) s).value; + if (c.func instanceof Attribute && "__init__".equals(((Attribute) c.func).attr) + && ((Attribute) c.func).value instanceof Name && c.keywords.isEmpty() && !c.args.isEmpty() + && c.args.get(0) instanceof Name && ((Name) c.args.get(0)).id.equals(w.self)) { + Layouts.Cls base = globalClasses.get(((Name) ((Attribute) c.func).value).id); + boolean clean = base != null && isAncestor(base, w.owner); + for (int i = 1; i < c.args.size() && clean; i++) { + clean = observesNothing(c.args.get(i), w, r); + } + if (clean) { + Set up = initDefinite(base, w.seen); + r.addAll(up); + return up.contains(EXTRA) ? InitEnd.STOP : InitEnd.ON; + } + } + } + if (!(s instanceof Return) && observesNothing(s, w, r)) { + return InitEnd.ON; + } + return InitEnd.STOP; + } + + /// Whether evaluating `o` cannot observe a field of the instance not + /// yet set: it names the instance only to read a field in `set`, or to + /// call, through it, a method every class it may be (the class, its + /// bases, its subclasses) binds as a classmethod or staticmethod. Any + /// other mention -- passing the instance on, reading another + /// attribute, calling an instance method -- may. + private boolean observesNothing(Object o, InitWalk w, Set set) { + if (o == null) { + return true; + } + if (o instanceof Attribute && ((Attribute) o).value instanceof Name + && ((Name) ((Attribute) o).value).id.equals(w.self)) { + return set.contains(((Attribute) o).attr); + } + if (o instanceof Call && ((Call) o).func instanceof Attribute + && ((Attribute) ((Call) o).func).value instanceof Name + && ((Name) ((Attribute) ((Call) o).func).value).id.equals(w.self) + && notBoundToInstance(w.k, ((Attribute) ((Call) o).func).attr)) { + Call c = (Call) o; + for (Expr a : c.args) { + if (!observesNothing(a, w, set)) { + return false; + } + } + for (Keyword kw : c.keywords) { + if (!observesNothing(kw.value, w, set)) { + return false; + } + } + return true; + } + if (o instanceof Name) { + return !((Name) o).id.equals(w.self); + } + if (o instanceof FunctionDef || o instanceof Lambda || o instanceof ClassDef) { + // A nested function may run later and read anything. + return !mentions(o, w.self); + } + boolean[] ok = {true}; + children(o, x -> ok[0] &= observesNothing(x, w, set)); + return ok[0]; + } + + /// Whether `m`, looked up on an instance of `k` or of any subclass, + /// is always a classmethod or staticmethod a class body defines: + /// no instance field or computed attribute may carry the name, and no + /// class in the way has a base the program does not compile. + private boolean notBoundToInstance(Layouts.Cls k, String m) { + List all = new ArrayList(p.below(k)); + for (Layouts.Cls c = k; c != null; c = c.parent) { + all.add(c); + } + boolean found = false; + for (Layouts.Cls c : all) { + if (c.extraBases || c.allFields.contains(m) || c.bodyNames.contains("__getattribute__")) { + return false; + } + for (Stmt st : c.def.body) { + if (st instanceof FunctionDef && ((FunctionDef) st).name.equals(m)) { + if (!classOrStatic((FunctionDef) st, c)) { + return false; + } + found = true; + } else if (st instanceof Assign || st instanceof AnnAssign) { + List names = new ArrayList(); + targetNames(st instanceof Assign ? ((Assign) st).targets.get(0) : ((AnnAssign) st).target, + names); + if (names.contains(m)) { + return false; + } + } + } + } + return found; + } + + /// Whether method `f` of class `c` is decorated with nothing but the + /// builtin `classmethod` or `staticmethod`: the name must still mean the + /// builtin where the class body runs, since a module may rebind it. + private static boolean classOrStatic(FunctionDef f, Layouts.Cls c) { + if (f.decorators.size() != 1 || !(f.decorators.get(0) instanceof Name)) { + return false; + } + String d = ((Name) f.decorators.get(0)).id; + return ("classmethod".equals(d) || "staticmethod".equals(d)) + && c.def.scope.parent.resolve(d) == Scope.Binding.BUILTIN; + } + + private static boolean isAncestor(Layouts.Cls a, Layouts.Cls k) { + for (Layouts.Cls x = k.parent; x != null; x = x.parent) { + if (x == a) { //NOPMD CompareObjectsWithEquals - identity is meant + return true; + } + } + return false; + } + + static boolean mentions(Object o, String n) { + boolean[] r = new boolean[1]; + mentionsIn(o, n, r); + return r[0]; + } + + private static void mentionsIn(Object o, String n, boolean[] r) { + if (r[0]) { + return; + } + if (o instanceof Name && ((Name) o).id.equals(n)) { + r[0] = true; + return; + } + children(o, x -> mentionsIn(x, n, r)); + } + + /// Whether field `f` of class `k` (declared there or inherited) is set + /// on every instance of `k` and of all its subclasses. + boolean definitelySet(Layouts.Cls owner, String f) { + Infer h = p.home.get(owner); + if (h.facts.dictViews || h.facts.deleted.contains(f)) { + return false; + } + if (!definite.get(owner).contains(f)) { + return false; + } + for (Layouts.Cls k : p.below(owner)) { + { + Infer kh = p.home.get(k); + if (kh.facts.dictViews || kh.facts.deleted.contains(f) || !definite.get(k).contains(f)) { + return false; + } + } + } + return true; + } + + /// Whether field `f` of `owner`, which no constructor is known to set + /// on every instance, may still be held typed as `t`: a reference type, + /// whose slot holds no value of its own when absent, kept as a guarded + /// pair whose object half starts as Typed.UNSET (TypedEmit#openField). + /// Not a field any module deletes, nor one of a class whose `__dict__` + /// code may take: those change the field behind both halves. bs4's + /// BeautifulSoup is a Tag whose constructor reaches Tag.__init__ only + /// through `self.reset()`, which left `name` and `prefix` of every Tag + /// held as plain objects behind an attribute cache. + boolean openable(Layouts.Cls owner, String f, Ty t) { + if (t.k != Ty.K.STR && t.k != Ty.K.LIST && t.k != Ty.K.INST) { + return false; + } + for (Infer m : p.modules.values()) { + if (m.facts.deleted.contains(f)) { + return false; + } + } + if (p.home.get(owner).facts.dictViews) { + return false; + } + for (Layouts.Cls k : p.below(owner)) { + if (p.home.get(k).facts.dictViews) { + return false; + } + } + return true; + } + + /// Whether every instance `isinstance(x, o)` passes is of `o`'s Java + /// class. Not when a class derives from `o` through a base besides its + /// compiled parent: python-pptx's `_BaseSlidePlaceholder( + /// _InheritsDimensions, Shape)` is a `BaseShape` to Python and an + /// `_InheritsDimensions` to Java, and the cast a narrowing makes fails. + /// A refused class counts too: its instances are made of the Java class + /// of its analysed parent. A base is matched by name, which may refuse + /// more than it must. + private boolean layoutHolds(Layouts.Cls o) { + if (ProtocolChecks.isProtocol(o.def)) { + // A protocol passes any instance with its members + // (ProtocolChecks), of whatever Java class. + return false; + } + if (o.enumMeta) { + // A member of an enumeration with a builtin mixin (IntEnum, + // `class Role(str, Enum)`) is made by the builtin's __new__, + // which need not extend the class's Java class; so is one of a + // class below it. Every other member is made once, after the + // class statement, as an instance of exactly its class + // (EnumLowering). + for (Layouts.Cls c : selfAndBelow(o)) { + if (c.builtin != null || !c.compiled) { + return false; + } + } + } + Set reg = registeredNames(); + for (Layouts.Cls c : p.home.keySet()) { + if (reg.contains(c.def.name) && isSelfOrAncestor(o, c)) { + // `Integral.register(int)`: an int passes isinstance for + // Integral and every class above it, with no layout at all. + return false; + } + } + for (Layouts.Cls c : p.home.keySet()) { + if (c.def.bases.size() < 2 || isSelfOrAncestor(o, c)) { + continue; + } + for (Expr be : c.def.bases) { + // `Generic[T]`, `Base[int]`: the class subscripted is the base. + Expr bx = be instanceof Subscript ? ((Subscript) be).value : be; + String bn = bx instanceof Name ? ((Name) bx).id : bx instanceof Attribute ? ((Attribute) bx).attr : null; + if (bn == null) { + return false; + } + for (Layouts.Cls d : p.home.keySet()) { + if (d.def.name.equals(bn) && isSelfOrAncestor(o, d)) { + return false; + } + } + } + } + return true; + } + + /// The names `X.register(...)` (an ABC's virtual subclass) is called + /// on, or decorates with, anywhere in the program. + private Set registeredNames() { + if (p.registered == null) { + Set r = new HashSet(); + for (Infer m : p.modules.values()) { + for (Stmt st : m.body) { + registerCalls(st, r); + } + } + p.registered = r; + } + return p.registered; + } + + private static void registerCalls(Object o, Set r) { + Expr f = o instanceof Call ? ((Call) o).func : o instanceof Attribute ? (Expr) o : null; + if (f instanceof Attribute && "register".equals(((Attribute) f).attr) && ((Attribute) f).value instanceof Name) { + r.add(((Name) ((Attribute) f).value).id); + } + Infer.children(o, x -> registerCalls(x, r)); + } + + static boolean isSelfOrAncestor(Layouts.Cls a, Layouts.Cls k) { + for (Layouts.Cls x = k; x != null; x = x.parent) { + if (x == a) { //NOPMD CompareObjectsWithEquals - identity is meant + return true; + } + } + return false; + } + + // ---- joins ----------------------------------------------------------- + + private Ty joinInto(Ty cur, Ty v) { + Ty r = mix(cur, v); + if (!r.equals(cur)) { + p.changed = true; + } + if (r.k != Ty.K.LIST && r.k != Ty.K.TUPLE && r.k != Ty.K.DICT && r.k != Ty.K.INST && r.k != Ty.K.CLS + && r.k != Ty.K.UNION && r.k != Ty.K.METH && r.k != Ty.K.FUNC) { + // A callable keeps its trail: the calls made through what it + // is stored in are followed to it. + escape(v); + } + return r; + } + + /// The join of two types. An instance that joins into a value of no + /// one class is from then on held where the pass does not follow it. + private Ty mix(Ty a, Ty b) { + Ty r = Ty.join(a, b); + if (r.k == Ty.K.OBJECT && !p.done) { + if (a != null && a.k == Ty.K.INST) { + loosen(a.cls); + } + if (b != null && b.k == Ty.K.INST) { + loosen(b.cls); + } + if (a != null && a.k == Ty.K.CLS) { + escape(a); + } + if (b != null && b.k == Ty.K.CLS) { + escape(b); + } + // A function either may be is from here on called where the + // pass does not follow it. Not so in the generic view of a body, + // where every value is an object by construction: the typed walk + // of the same code follows the function, and a generic call + // enters it through the door's guard. + if (a != null && !shadow) { + escapeFuncs(a); + } + if (b != null && !shadow) { + escapeFuncs(b); + } + } + return r; + } + + /// An instance of `k` reached code that holds it as a value of no + /// known class. What such code does to an object it cannot name the + /// class of -- read or store an attribute by a computed name -- it may + /// do to this one: to a field or a method of `k`, of a class it + /// derives from, or of one that derives from it. + /// What an escaped list or dict holds is read back as a value of no + /// known class. + private void sweep() { + // A compiled class merged into another's layout as an extra base + // (Layouts#mergeExtras) has its methods reached through that + // class's MRO, generically and with arguments nobody tracks. + for (Layouts.Cls k : new ArrayList(p.home.keySet())) { + for (Layouts.Cls x : k.mixedFrom) { + for (Stmt st : x.def.body) { + if (st instanceof FunctionDef) { + escapeFn(p.fns.get((FunctionDef) st)); + } + } + } + } + if (p.anyClassOf) { + for (Layouts.Cls k : new ArrayList(p.loose)) { + Infer in = p.home.get(k); + // A call of a class nobody can name reaches k only through + // an instance of k (`type(x)(...)`) or k's class object held + // as a value. With neither -- never constructed, never a + // class value, its module never read by a computed name -- + // its constructor is not one: bs4's deprecated + // BeautifulStoneSoup, never built, forwarded *args into + // BeautifulSoup.__init__ and widened every parameter. A + // class value counts only when it escaped (#looseRoot): one + // merely named -- `isinstance(x, Tag)`, or held by typing's + // TypeVar (#callKnown) -- is not a value unknown code holds. + if (in != null && !p.constructed.contains(k) && !p.looseRoots.contains(k) + && !p.allModulesLoose && !p.looseModules.contains(in)) { + continue; + } + if (in != null) { + in.escapeClass(k); + } + } + } + if (p.anyRead) { + // A computed read from a module held as a value finds its + // classes and what its globals hold, not only its functions. + for (Map.Entry e : p.home.entrySet()) { + if (p.allModulesLoose || p.looseModules.contains(e.getValue())) { + e.getValue().escapeClass(e.getKey()); + } + } + for (Infer in : p.modules.values()) { + if (p.allModulesLoose || p.looseModules.contains(in)) { + for (Ty g : in.globals.values()) { + in.escape(g); + } + } + } + } + for (int s = 0; s < siteElem.size(); s++) { + if (p.allListsEscape || escapedSites.contains(Integer.valueOf(s))) { + Ty e = siteElem.get(s); + if (e != null && e.k == Ty.K.INST) { + loosen(e.cls); + } + Ty k = s < siteKey.size() ? siteKey.get(s) : null; + if (k != null && k.k == Ty.K.INST) { + loosen(k.cls); + } + } + } + } + + /// Whether an instance of compiled class `k` can never hold an + /// attribute of its own under a name no module stores by name: no + /// computed-name store reaches it. The caller checks the names + /// ([WholeProgram.Module#attrStored]) and, at run time, that nothing + /// wrote to the class (`PyType.classWritten`). + /// Whether `e` is certainly a class object, not an instance: a store + /// through it changes a class, which `PyType.classWritten` answers for + /// at run time, and no instance's own attributes. + private boolean classReceiver(Expr e, Fn fn, Scope sc) { + if (e == null) { + return false; + } + if (classOwner(e, sc) != null) { + return true; + } + if (!(e instanceof Name)) { + return false; + } + String n = ((Name) e).id; + if (globalClasses.containsKey(n) && sc.resolve(n) == Scope.Binding.GLOBAL && !moduleScope.hasStarImport) { + return true; + } + // A decorated function is no typed Fn: found by its scope. + FunctionDef def = fn != null && fn.def != null ? fn.def : defOf(sc); + if (def == null || def.scope != sc || sc.assigned.contains(n) || sc.resolve(n) != Scope.Binding.LOCAL) { //NOPMD CompareObjectsWithEquals - identity is meant + return false; + } + List params = def.args.names(); + if (params.isEmpty() || !params.get(0).equals(n)) { + return false; + } + for (Expr d : def.decorators) { + if (d instanceof Name && "classmethod".equals(((Name) d).id) + && sc.resolve("classmethod") == Scope.Binding.BUILTIN) { + return true; + } + } + return false; + } + + /// The compiled class `func` names when called in scope `sc`: a global + /// of this module, a name imported from another, or `module.Cls`; and + /// only where the module never rebinds it. Null otherwise. + Layouts.Cls calledClass(Expr func, Scope sc) { + Layouts.Cls k = calledClassOrEnum(func, sc); + // Calling an enum class looks a member up (EnumType.__call__), and + // its attributes are the members the metaclass made of the body's + // values: neither is what the class statement says. + return k == null || k.enumMeta ? null : k; + } + + private Layouts.Cls calledClassOrEnum(Expr func, Scope sc) { + if (func instanceof Name && sc.resolve(((Name) func).id) == Scope.Binding.GLOBAL) { + Layouts.Cls k = globalClasses.get(((Name) func).id); + if (k != null) { + return k; + } + Object o = foreign(func, sc); + return o instanceof Layouts.Cls ? (Layouts.Cls) o : null; + } + if (func instanceof Attribute && foreign(((Attribute) func).value, sc) instanceof Infer) { + Object o = foreign(func, sc); + return o instanceof Layouts.Cls ? (Layouts.Cls) o : null; + } + return null; + } + + /// The module's class named `n` if generated code has a Java class for + /// it, or null: an analysed class is held as a plain object. + Layouts.Cls emitClass(String n) { + Layouts.Cls k = globalClasses.get(n); + return k == null || !k.compiled ? null : k; + } + + /// [#calledClass], for generated code: null for an analysed class. + Layouts.Cls emitCalledClass(Expr func, Scope sc) { + Layouts.Cls k = calledClass(func, sc); + return k == null || !k.compiled ? null : k; + } + + /// Every compiled class of the program below `k`. + List subclasses(Layouts.Cls k) { + return p.below(k); + } + + /// The layouts of the module that compiled `k`, or null. + Layouts layoutsOf(Layouts.Cls k) { + Infer m = p.home.get(k); + return m == null ? null : m.layouts; + } + + private Map scopeDefs; + + /// The function whose own scope is `sc`, or null. + private FunctionDef defOf(Scope sc) { + if (scopeDefs == null) { + scopeDefs = new IdentityHashMap(); + collectDefs(body); + } + return scopeDefs.get(sc); + } + + private void collectDefs(Object o) { + if (o instanceof FunctionDef) { + scopeDefs.put(((FunctionDef) o).scope, (FunctionDef) o); + } + children(o, this::collectDefs); + } + + boolean instanceAttrsClosed(Layouts.Cls k) { + for (Layouts.Cls o : p.computedOn) { + if (isSelfOrAncestor(o, k) || isSelfOrAncestor(k, o)) { + return false; + } + } + if (p.computedOnAny) { + for (Layouts.Cls o : p.loose) { + if (isSelfOrAncestor(o, k) || isSelfOrAncestor(k, o)) { + return false; + } + } + } + return true; + } + + /// Whether every call of the `__call__` method `f` is one the pass + /// sees: a call of an instance typed as its class [#call0] binds it + /// like any method, and only an instance that went where the pass does + /// not follow -- its class loose, which [#loosen] spreads up and down + /// the parent chain -- can be called unseen. A class that is a later + /// base of another is reached off that chain, so it is not followed. + private boolean followedCall(Fn f) { + if (f.cls == null || p.loose.contains(f.cls) || open.contains(f.cls) || !f.def.decorators.isEmpty()) { + return false; + } + String name = f.cls.def.name; + Infer home = p.fnHome.get(f); + if (home == null || home.globalClasses.get(name) != f.cls) { //NOPMD CompareObjectsWithEquals - identity is meant + // A class its module does not bind once at top level with a + // layout: a call of it is not a construction the pass follows, + // so its instances are never typed and every call of one is + // unseen (dateutil's `weekday`, made in a comprehension). + return false; + } + if (!facts.mayBeBase(name, p.reached)) { + return true; + } + for (Infer in : p.modules.values()) { + for (Stmt s : in.body) { + if (!(s instanceof ClassDef)) { + continue; + } + List bases = ((ClassDef) s).bases; + for (int i = 1; i < bases.size(); i++) { + Expr x = bases.get(i); + ClassDef d = x instanceof Name ? Layouts.classNamed(in.body, ((Name) x).id) : null; + if (d == null) { + d = in.foreignClassDef(x); + } + if (d == f.cls.def) { //NOPMD CompareObjectsWithEquals - identity is meant + return false; + } + String last = x instanceof Name ? ((Name) x).id : x instanceof Attribute ? ((Attribute) x).attr : null; + if (d == null && (last == null || last.equals(name))) { + // Unresolved, and may be this class: only a base + // spelled with another last name is surely not. + return false; + } + } + } + } + return true; + } + + /// An instance of k went where the pass does not follow it: what is + /// done with it there is not seen, so k's hierarchy is loose. It makes + /// no class live as itself -- what holds an instance makes more only of + /// the class it already has (`type(x)(...)`, a copy), and that class is + /// live. Only a class held as a value is a root of instances the pass + /// does not see ([#escapeClass], [#exactLive]). When the escape made a + /// root, bs4 passing `self._most_recent_element` to a tag factory made + /// PageElement live as itself, and every `else` of an isinstance test + /// on one read a PageElement. + private void loosen(Layouts.Cls k) { + if (k != null && p.loosened.add(k)) { + looseHierarchy(k); + } + } + + /// k is held as a value: whoever holds it makes instances of it. + private void looseRoot(Layouts.Cls k) { + if (k != null && p.looseRoots.add(k)) { + p.changed = true; + loosen(k); + } + } + + private void looseHierarchy(Layouts.Cls k) { + for (Layouts.Cls o : p.home.keySet()) { + if ((isSelfOrAncestor(o, k) || isSelfOrAncestor(k, o)) && p.loose.add(o)) { + p.changed = true; + if (!p.anyClassNames.isEmpty()) { + for (Fn f : new ArrayList(p.fns.values())) { + if (f.cls == o && p.anyClassNames.contains(f.def.name)) { //NOPMD CompareObjectsWithEquals - identity is meant + escapeFn(f); + } + } + } + } + } + } + + /// A value went somewhere the pass does not follow. + + void escape(Ty v) { + if (p.done) { + return; + } + if (v != null && v.k == Ty.K.UNION) { + for (Ty m : v.members()) { + escape(m); + } + return; + } + if (v != null && v.k == Ty.K.METH) { + noMeth(v); + return; + } + if (v != null && v.k == Ty.K.FUNC) { + // Called from where the pass cannot see. + for (Fn f : funcsOf(v)) { + escapeFn(f); + } + return; + } + if (v != null && v.k == Ty.K.INST) { + loosen(v.cls); + return; + } + if (v != null && v.k == Ty.K.CLS) { + if (v.sites.length == 0) { + anyClass(); + } + for (Layouts.Cls k : classesOf(v)) { + if (typingHeld) { + loosen(k); + } else { + escapeClass(k); + } + } + return; + } + if (v != null && v.k == Ty.K.TUPLE) { + // The tuple itself cannot change; what it holds now goes where + // the pass does not follow. + for (int s : v.sites) { + if (escapedSites.add(Integer.valueOf(s))) { + p.changed = true; + Ty[] sl = siteSlots.get(Integer.valueOf(s)); + if (sl != null) { + for (Ty x : sl) { + escape(x); + } + } + } + } + return; + } + if (v != null && (v.k == Ty.K.LIST || v.k == Ty.K.DICT)) { + if (v.sites.length == 0) { + if (!p.allListsEscape) { + p.allListsEscape = true; + p.changed = true; + } + } else { + for (int s : v.sites) { + if (escapedSites.add(Integer.valueOf(s))) { + p.changed = true; + Ty[] sl = siteSlots.get(Integer.valueOf(s)); + if (sl != null) { + for (Ty x : sl) { + escape(x); + } + } + } + } + } + } + } + + // ---- attributes named at run time ----------------------------------- + + private void problem(Node at, Fn fn, Scope sc, String what) { + if (p.problems.containsKey(at)) { + return; + } + String q = null; + if (fn != null) { + q = (fn.cls != null ? fn.cls.def.name + "." : "") + fn.def.name; + } else if (sc != null && sc.kind != Scope.Kind.MODULE) { + q = (sc.enclosingClass != null && sc.enclosingClass.name != null ? sc.enclosingClass.name + "." : "") + sc.name; + } + p.problems.put(at, new Problem(moduleName, at.line, q, what)); + } + + /// Whether `e` is the receiver of a method of a class without a + /// compiled layout: an instance of such a class has no typed field. + private boolean plainReceiver(Expr e, Scope sc) { + if (!(e instanceof Name) || !p.plainSelf.contains(sc) || sc.params.isEmpty()) { + return false; + } + return sc.params.iterator().next().equals(((Name) e).id) && sc.resolve(((Name) e).id) == Scope.Binding.LOCAL; + } + + /// The start every value of the str `e` has, when `e` is built on a + /// literal: `"visit_" + n`, an f-string, `"do_%s" % n`. Null otherwise, + /// and for an empty start. + private static String prefix(Expr e) { + String r = null; + if (e instanceof BinOp && ("+".equals(((BinOp) e).op) || "%".equals(((BinOp) e).op)) + && ((BinOp) e).left instanceof Constant && ((Constant) ((BinOp) e).left).kind == Constant.Kind.STR) { + r = ((Constant) ((BinOp) e).left).text; + if ("%".equals(((BinOp) e).op)) { + int i = r.indexOf('%'); + r = i < 0 ? r : r.substring(0, i); + } + } else if (e instanceof JoinedStr && !((JoinedStr) e).parts.isEmpty() + && ((JoinedStr) e).parts.get(0) instanceof Constant) { + r = ((Constant) ((JoinedStr) e).parts.get(0)).text; + } else if (e instanceof Call && ((Call) e).func instanceof Attribute + && "format".equals(((Attribute) ((Call) e).func).attr) + && ((Attribute) ((Call) e).func).value instanceof Constant + && ((Constant) ((Attribute) ((Call) e).func).value).kind == Constant.Kind.STR) { + // `"do_{}".format(n)`: the text before the first field. + r = ((Constant) ((Attribute) ((Call) e).func).value).text; + int i = r.indexOf('{'); + r = i < 0 || r.startsWith("{{", i) ? null : r.substring(0, i); + } + return r == null || r.isEmpty() ? null : r; + } + + /// Builtins that read the lists they are given and never store into + /// them, nor hand out anything that can. + private static final Set READ_ONLY_BUILTINS = new HashSet(java.util.Arrays.asList("reversed", + "enumerate", "iter", "sorted", "tuple", "set", "frozenset", "sum", "min", "max", "any", "all", "zip", + "len", "map", "filter", "repr", "str", "bool", "print", "dict")); + private static final Set DICT_READS = new HashSet(java.util.Arrays.asList("items", "keys", + "values", "get", "copy", "__contains__", "__len__", "__iter__", "__getitem__")); + private static final Set CLASS_FACTS = new HashSet(java.util.Arrays.asList("__name__", + "__qualname__", "__module__", "__doc__")); + + /// `x` when `e` is the attribute dict of `x` -- `x.__dict__` or + /// `vars(x)` -- and null otherwise. A store through it is a store of an + /// attribute by a computed name. + private Expr dictOwner(Expr e, Scope sc) { + if (e instanceof Attribute && "__dict__".equals(((Attribute) e).attr)) { + return ((Attribute) e).value; + } + if (e instanceof Call && ((Call) e).func instanceof Name && "vars".equals(((Name) ((Call) e).func).id) + && ((Call) e).args.size() == 1 && ((Call) e).keywords.isEmpty() + && !(((Call) e).args.get(0) instanceof Starred) + && sc.resolve("vars") == Scope.Binding.BUILTIN && !moduleScope.hasStarImport) { + return ((Call) e).args.get(0); + } + return null; + } + + /// `x` when `e` is the class of `x`, `type(x)` or `x.__class__`. + private Expr classOwner(Expr e, Scope sc) { + if (e instanceof Attribute && "__class__".equals(((Attribute) e).attr)) { + return ((Attribute) e).value; + } + if (e instanceof Call && ((Call) e).func instanceof Name && "type".equals(((Name) ((Call) e).func).id) + && ((Call) e).args.size() == 1 && ((Call) e).keywords.isEmpty() + && !(((Call) e).args.get(0) instanceof Starred) + && sc.resolve("type") == Scope.Binding.BUILTIN && !moduleScope.hasStarImport) { + return ((Call) e).args.get(0); + } + return null; + } + + private static boolean classOp(String op) { + return "is".equals(op) || "is not".equals(op) || "==".equals(op) || "!=".equals(op) || "in".equals(op) + || "not in".equals(op); + } + + /// The uses of a class taken off an object that make nothing with it + /// -- its name, and a comparison -- and the comparisons of an attribute + /// dict, which only read it. + private final Set classFacts = java.util.Collections.newSetFromMap(new IdentityHashMap()); + + /// The builtins whose subscription makes a `types.GenericAlias`. + private static final Set GENERIC_BUILTINS = new HashSet(java.util.Arrays.asList("list", "dict", + "tuple", "set", "frozenset", "type")); + + /// Attribute `attr` read off a class nobody can name. A method read so + /// is called with arguments nobody tracks; a class method is handed the + /// class too, and only then is the class let go. + private Ty anyClassAttr(String attr) { + for (Layouts.Cls k : new ArrayList(p.home.keySet())) { + if (k.bodyNames.contains(attr)) { + FunctionDef d = methodOrAlias(k, attr); + if (d == null || classOrStatic(d, k) || Layouts.IMPLICIT_CLASS_LEVEL.contains(attr) + || !d.decorators.isEmpty()) { + anyClass(); + break; + } + } + } + // A class nobody can name is one that went where the pass does not + // follow: a loose one (a class whose instance is followed is named, + // [#classesBelow], or loosened where it is not). + p.anyClassNames.add(attr); + for (Fn f : new ArrayList(p.fns.values())) { + if (f.cls != null && f.def.name.equals(attr) && p.loose.contains(f.cls)) { + escapeFn(f); + } + } + return Ty.UNSEEN; + } + + /// The method `attr` names in `k`'s body: its def, or the def of the + /// one name it is bound to there (`__copy__ = copy`). Null otherwise. + private static FunctionDef methodOrAlias(Layouts.Cls k, String attr) { + FunctionDef d = bodyDef(k, attr); + if (d != null) { + return d; + } + String to = null; + for (Stmt st : k.def.body) { + if (st instanceof Assign && ((Assign) st).targets.size() == 1 && ((Assign) st).targets.get(0) instanceof Name + && ((Name) ((Assign) st).targets.get(0)).id.equals(attr)) { + if (to != null || !(((Assign) st).value instanceof Name)) { + return null; + } + to = ((Name) ((Assign) st).value).id; + } + } + return to == null || to.equals(attr) ? null : bodyDef(k, to); + } + + /// A class nobody can name was called or let go: whatever is loose may + /// be made, with arguments nobody tracks ([#sweep]). + private void anyClass() { + if (!p.anyClassOf) { + p.anyClassOf = true; + p.changed = true; + } + } + + /// The class value of an instance of `t`: every compiled class at or + /// below its static class. Null when that is not known -- an optional + /// or untyped value, or a program another module may extend. + private Ty classesBelow(Ty t) { + if (t.k != Ty.K.INST || t.opt || !p.closed) { + return null; + } + Ty r = Ty.BOT; + for (Layouts.Cls k : new ArrayList(p.home.keySet())) { + // Only a class an instance can be of: one constructed, or let + // go where the pass stops following it. bs4's `type(self)(...)` + // otherwise counted the never-built BeautifulStoneSoup, whose + // `*args` forwarding widened every BeautifulSoup parameter. + if (isSelfOrAncestor(t.cls, k) && exactLive(k)) { + r = Ty.join(r, classValue(k)); + } + } + // None yet: nothing so far, until a construction makes one. + return r.k == Ty.K.CLS || r.k == Ty.K.BOT && !p.done ? r : null; + } + + /// The class of an object, held as a value: whoever holds it may make + /// instances of it, with arguments nobody tracks. `owner` is the object. + private void classOf(Expr at, Expr owner, Fn fn, Scope sc) { + if (classFacts.contains(at) || plainReceiver(owner, sc)) { + return; + } + Ty r = type(owner, fn, sc); + if (r.k == Ty.K.INST) { + for (Map.Entry e : new ArrayList>(p.home.entrySet())) { + if (isSelfOrAncestor(e.getKey(), r.cls) || isSelfOrAncestor(r.cls, e.getKey())) { + e.getValue().escapeClass(e.getKey()); + } + } + } + if (r.wide() && !p.anyClassOf) { + // Whatever is loose by the end: the sweep asks again each round. + p.anyClassOf = true; + p.changed = true; + } + } + + /// The `x.__dict__` reads of this module that only read the dict: the + /// receiver of `.items()`, `.keys()`, `.values()`, `.get(...)` or + /// `.copy()`, the right side of `in`/`not in`, the iterable of a `for`, + /// or the argument of `len` or of a copying builtin. None of them can store an attribute, so the + /// fields of the program keep their types (enum's `_finish` iterating + /// a class's dict guarded every field of every class). + private Set readDicts() { + if (readDicts == null) { + Set r = java.util.Collections.newSetFromMap(new IdentityHashMap()); + if (body != null) { + for (Stmt st : body) { + findReadDicts(st, r); + } + } + readDicts = r; + } + return readDicts; + } + + private Set readDicts; + + private static boolean isDictRead(Expr e) { + return e instanceof Attribute && "__dict__".equals(((Attribute) e).attr); + } + + private static void findReadDicts(Object o, Set r) { + if (o instanceof Call) { + Call c = (Call) o; + if (c.func instanceof Attribute && isDictRead(((Attribute) c.func).value) + && READ_DICT_METHODS.contains(((Attribute) c.func).attr)) { + r.add(((Attribute) c.func).value); + } + if (c.func instanceof Attribute && "update".equals(((Attribute) c.func).attr) && c.args.size() == 1 + && c.keywords.isEmpty() && isDictRead(c.args.get(0))) { + // Copied into another dict (logging's `values.update(record.__dict__)`). + r.add(c.args.get(0)); + } + if (c.func instanceof Name && READ_DICT_FUNCS.contains(((Name) c.func).id) && c.args.size() == 1 + && c.keywords.isEmpty() && isDictRead(c.args.get(0))) { + r.add(c.args.get(0)); + } + } else if (o instanceof Compare) { + Compare c = (Compare) o; + for (int i = 0; i < c.ops.size(); i++) { + if (("in".equals(c.ops.get(i)) || "not in".equals(c.ops.get(i))) && isDictRead(c.comparators.get(i))) { + r.add(c.comparators.get(i)); + } + } + } else if (o instanceof For && isDictRead(((For) o).iter)) { + r.add(((For) o).iter); + } + children(o, x -> findReadDicts(x, r)); + } + + private static final Set READ_DICT_METHODS = new HashSet(java.util.Arrays.asList("items", "keys", "values", "get", "copy", + // These only remove: no value reaches a field (bs4's decompose + // clears every element's dict). + "clear", "pop", "popitem")); + + /// Builtins whose one argument is only read: `dict(x.__dict__)` is a + /// copy (bs4's `__getstate__`), and writing the copy sets nothing on `x`. + private static final Set READ_DICT_FUNCS = new HashSet(java.util.Arrays.asList("len", "dict", "list", "sorted", "set", "tuple")); + + /// The attribute dict of `owner` used for anything but a read: handed + /// on, it may be written under any name. + private void dictOf(Expr at, Expr owner, Fn fn, Scope sc) { + if (classFacts.contains(at) || readDicts().contains(at)) { + if (readDicts().contains(at)) { + type(owner, fn, sc); + } + return; + } + if (owner instanceof Name && globalClasses.containsKey(((Name) owner).id) + && sc.resolve(((Name) owner).id) == Scope.Binding.GLOBAL) { + // A class's own dict is read-only, and holds no instance's + // attributes. + return; + } + computedStore(type(owner, fn, sc), owner, null, Ty.OBJECT, at, fn, sc, + "hands on the attribute dict of an object of no class the build can tell, through which any" + + " attribute may be set"); + } + + /// `setattr(recv, name, v)` and its other spellings. A literal name is + /// a store like `recv.name = v`. A computed one on an instance of a + /// known class may be any field of that class or of one related to it. + /// On an object of no known class it could be any field of the + /// program, and typing them all for that would type none: that is a + /// problem the build reports. + private void computedStore(Ty recv, Expr recvExpr, Expr name, Ty v, Node at, Fn fn, Scope sc) { + computedStore(recv, recvExpr, name, v, at, fn, sc, + "stores an attribute whose name is computed, on an object of no class the build can tell"); + } + + private void computedStore(Ty recv, Expr recvExpr, Expr name, Ty v, Node at, Fn fn, Scope sc, String what) { + if (recv.k == Ty.K.UNION) { + for (Ty m : recv.members()) { + computedStore(m.nonNone(), recvExpr, name, v, at, fn, sc, what); + } + return; + } + if (recv.k == Ty.K.INST && name instanceof Constant && !plainReceiver(recvExpr, sc)) { + // `object.__setattr__(self, "a", v)` on an instance of a known + // class (a frozen dataclass's constructor): the store `self.a + // = v` is, past the class's own __setattr__, and v goes no + // further than that field. + List named = constStrings(name, fn, sc); + if (named != null) { + for (String k : named) { + storeField(recv, k, v); + } + return; + } + } + escape(v); + if (recv.k != Ty.K.INST && !recv.wide() || plainReceiver(recvExpr, sc)) { + return; + } + List known = name == null ? null : constStrings(name, fn, sc); + if (known != null) { + if (!(name instanceof Constant)) { + // Names the source does not spell as a setattr argument, + // which WholeProgram's facts read: counted here instead. + p.computedStoredNames.addAll(known); + } + for (String k : known) { + storeField(recv, k, v); + } + return; + } + String pre = name == null ? null : prefix(name); + computing = true; + try { + computedFields(recv, recvExpr, pre, v, at, fn, sc, what); + } finally { + computing = false; + } + } + + /// Whether the stores being joined are a computed store's (see + /// [#storeOne]). + private boolean computing; + + private void computedFields(Ty recv, Expr recvExpr, String pre, Ty v, Node at, Fn fn, Scope sc, String what) { + if (recv.k == Ty.K.INST) { + p.computedOn.add(recv.cls); + } else if (!classReceiver(recvExpr, fn, sc)) { + p.computedOnAny = true; + } + { + boolean cost = false; + for (Map.Entry> e : fields.entrySet()) { + Layouts.Cls o = e.getKey(); + if (recv.k == Ty.K.INST && !isSelfOrAncestor(o, recv.cls) && !isSelfOrAncestor(recv.cls, o)) { + continue; + } + // A receiver of no known class may be an instance of any + // class, loosened or not: an unseen value is no evidence + // against one (Ty#UNSEEN). The store guards the fields it + // may reach (#storeOne), which keeps them typed. + cost |= recv.k != Ty.K.INST && pre == null && !e.getValue().isEmpty() && p.loose.contains(o); + for (String f : new ArrayList(e.getValue().keySet())) { + if (pre == null || f.startsWith(pre)) { + storeOne(o, f, v, recv); + } + } + } + if (cost) { + problem(at, fn, sc, what); + } + } + } + + /// `getattr(recv, name)` with a computed name: what it finds may be + /// called, with anything. On an instance of a known class that is a + /// method of the class or of one related to it; with a name built on a + /// literal start, whatever is named so. Anything else could be every + /// function of the program. + private void computedRead(Ty recv, Expr recvExpr, Expr name, Node at, Fn fn, Scope sc) { + if (recv.k == Ty.K.UNION) { + for (Ty m : recv.members()) { + computedRead(m.nonNone(), recvExpr, name, at, fn, sc); + } + return; + } + if (recv.k != Ty.K.INST && !recv.wide() || plainReceiver(recvExpr, sc)) { + return; + } + List known = recv.k == Ty.K.INST ? constStrings(name, fn, sc) : null; + if (known != null) { + // Each name the read can be, as `pre` narrows below. Only on an + // instance: a read from a module, or from a value of no known + // class, also reaches globals and classes ([#sweep]). + for (Fn f : new ArrayList(p.fns.values())) { + if (known.contains(f.def.name) && (recv.k != Ty.K.INST || f.cls != null + && (isSelfOrAncestor(f.cls, recv.cls) || isSelfOrAncestor(recv.cls, f.cls)))) { + escapeFn(f); + } + } + return; + } + String pre = prefix(name); + if (pre == null) { + // markdownify's `convert_fn_name = "convert_%s" % ...` and then + // `getattr(self, convert_fn_name, None)`: without following the + // name, every method of the converter escaped -- `process_tag`, + // `process_element` and the rest took and returned only objects. + Expr v = soleValue(name, fn, sc); + pre = v == null ? null : prefix(v); + } + if (recv.k != Ty.K.INST && pre == null) { + // Whatever is loose by the end: `entered` asks again each round. + if (!p.anyRead) { + p.anyRead = true; + p.changed = true; + } + problem(at, fn, sc, "reads an attribute whose name is computed, on an object of no class the build can tell"); + return; + } + for (Fn f : new ArrayList(p.fns.values())) { + if (pre != null && !f.def.name.startsWith(pre)) { + continue; + } + if (recv.k == Ty.K.INST && (f.cls == null || !isSelfOrAncestor(f.cls, recv.cls) && !isSelfOrAncestor(recv.cls, f.cls))) { + continue; + } + escapeFn(f); + } + } + + /// `getattr(obj, name)` on an instance of `k`, the name computed: + /// the bound methods of `k`'s class tree that the name can be -- one of + /// the strings it is seen to hold, or any name starting with the + /// literal it is built on. Null when the read could find something + /// else: a field, a static or class method or property, an attribute + /// stored under a computed name, or a class answering `__getattr__`. + private Ty methodsNamed(Layouts.Cls k, Expr name, Fn fn, Scope sc) { + List known = constStrings(name, fn, sc); + String pre = null; + if (known == null) { + pre = prefix(name); + if (pre == null) { + Expr v = soleValue(name, fn, sc); + pre = v == null ? null : prefix(v); + } + if (pre == null || pre.isEmpty()) { + return null; + } + } + return attrsNamed(k, known, pre); + } + + /// What reading one of `known` -- or, when that is null, any name + /// starting with `pre` -- on an instance of `k` finds: the bound + /// methods and functions the class tree binds to it, joined with the + /// fields of that name. Null when the read could find something the + /// pass does not follow; BOT while a class body is not walked yet. + private Ty attrsNamed(Layouts.Cls k, List known, String pre) { + List tree = new ArrayList(); + for (Layouts.Cls c = k; c != null; c = c.parent) { + tree.add(c); + } + tree.addAll(p.below(k)); + for (Layouts.Cls c : tree) { + if (!c.compiled || c.bodyNames.contains("__getattr__") || c.bodyNames.contains("__getattribute__")) { + return null; + } + Set u = p.unknownStores.get(c); + if (u != null) { + for (String s : u) { + if ((known != null ? known.contains(s) : s.startsWith(pre)) && !c.allFields.contains(s)) { + // Stored where the pass cannot see what: it may + // shadow a method of that name. + return null; + } + } + } + } + Ty fields = Ty.BOT; + for (Layouts.Cls c : tree) { + for (String f : c.allFields) { + if (known != null ? known.contains(f) : f.startsWith(pre)) { + // A field the name can be as well: its value joins in. + Layouts.Cls o = fieldOwner(c, f); + // As the field keeps it: what a store the pass could not + // type put there went wide, and any function in it with + // it (see [#mix]). + Ty ft = o == null ? null : this.fields.get(o).get(f); + fields = mix(fields, ft == null ? Ty.OBJECT : loc(ft)); + } + } + } + for (String s : p.dynStored) { + if (known != null ? known.contains(s) : s.startsWith(pre)) { + return null; + } + } + List defs = new ArrayList(); + for (Fn f : p.fns.values()) { + if (f.cls == null || f.analysisOnly || !(known != null ? known.contains(f.def.name) : f.def.name.startsWith(pre)) + || !tree.contains(f.cls)) { + continue; + } + if (!plainMethod(f.def) || !f.def.decorators.isEmpty()) { + return null; + } + defs.add(f.def); + } + List bound = new ArrayList(); + for (Fn f : p.fns.values()) { + if (defs.contains(f.def)) { + bound.add(f); + } + } + for (Layouts.Cls c : tree) { + for (Stmt s : c.def.body) { + if (!(s instanceof Assign)) { + continue; + } + for (Expr t : ((Assign) s).targets) { + if (!(t instanceof Name && (known != null ? known.contains(((Name) t).id) : ((Name) t).id.startsWith(pre)))) { + continue; + } + // A class attribute of that name: another method of the + // tree under a second name (`convert_kbd = convert_code`), + // or a function a call made (markdownify's + // `abstract_inline_conversion(...)`), bound to the + // instance when read through it. + Expr v = ((Assign) s).value; + Fn alias = v instanceof Name ? methodOf(tree, ((Name) v).id) : null; + if (alias != null) { + bound.add(alias); + continue; + } + Map cv = p.classVals.get(c.def.scope); + String vn = ((Name) t).id; + Ty val = cv == null ? null : cv.get(vn); + for (int hop = 0; val == null && cv != null && v instanceof Name && hop < 8; hop++) { + // `convert_i = convert_em`, itself a stored function. + vn = ((Name) v).id; + val = cv.get(vn); + v = valueOf(c.def.body, vn); + } + List fs = new ArrayList(); + List fr = new ArrayList(); + if (val == null || val.k == Ty.K.BOT) { + // The class body is not walked yet: nothing is + // known, so nothing is given up. + return Ty.BOT; + } + if (!callables(val.nonNone(), fs, fr)) { + return null; + } + for (int i = 0; i < fs.size(); i++) { + if (fr.get(i).intValue() != 0 || fs.get(i).params.length == 0) { + return null; + } + bound.add(fs.get(i)); + } + } + } + } + Ty r = methValueOf(bound); + // Not every instance has every name: the rest raise, or take the + // default. + if (r == null) { + return fields.k == Ty.K.BOT ? null : fields; + } + return mix(r, fields); + } + + private static boolean plainMethod(FunctionDef m) { + for (Expr d : m.decorators) { + if (d instanceof Name && "staticmethod".equals(((Name) d).id)) { + return false; + } + } + return true; + } + + private void reach(Fn f) { + if (p.reached.add(f.def)) { + p.changed = true; + } + } + + /// Whether `f` is reached by something this pass cannot follow to it: + /// a name another module or the Java runtime may look up, or the + /// build's own list. + private boolean rooted(Fn f) { + if (p.runtimeNames == null || entered(f)) { + return true; + } + if (p.runtimeNames.contains(f.def.name) && (f.cls == null || classLive(f.cls))) { + // A method the runtime calls by name (`__init__`, `__eq__`) + // runs only on an instance, so only once something makes one: + // bs4's deprecated BeautifulStoneSoup, which nothing + // constructs, forwarded `*args` to BeautifulSoup.__init__. + return true; + } + return p.keep.contains(moduleName + "." + (f.cls == null ? "" : f.cls.def.name + ".") + f.def.name); + } + + /// Whether an instance of exactly `k` can exist: it is constructed, it + /// went where the pass stops following (a class held as a value is + /// constructed by whoever holds it), or the runtime makes it. + private boolean exactLive(Layouts.Cls k) { + Infer home = p.home.get(k); + return home == null || RUNTIME_MODULES.contains(home.moduleName) + || p.runtimeNames != null && p.runtimeNames.contains(home.moduleName) + || p.constructed.contains(k) || p.looseRoots.contains(k); + } + + /// Whether an instance of `k` can exist: it, or a class below it, is + /// live ([#exactLive]). + private boolean classLive(Layouts.Cls k) { + Infer home = p.home.get(k); + if (home == null || RUNTIME_MODULES.contains(home.moduleName) + || p.runtimeNames != null && p.runtimeNames.contains(home.moduleName)) { + // The runtime makes these itself (`open()` builds io's file + // classes, `sys.stdout` is one), where no call site shows it. + return true; + } + boolean named = false; + for (Layouts.Cls c : selfAndBelow(k)) { + Infer h = p.home.get(c); + named |= h == null || h.facts == null || h.facts.namedOutside(c.def.name); + } + if (!named) { + // Named nowhere but in their own bodies: nothing makes one, or + // holds one as a value (WholeProgram.Module#namedOutside). + return false; + } + for (Layouts.Cls c : selfAndBelow(k)) { + if (p.constructed.contains(c) || p.looseRoots.contains(c) || p.clsId.containsKey(c)) { + // Made, let go, or held as a class value: whoever holds it + // may call it. + return true; + } + } + return false; + } + + /// The modules the runtime imports by name (WholeProgram#infer). + private static final Set RUNTIME_MODULES = new HashSet( + java.util.Arrays.asList("builtins", "copyreg", "io")); + + private void constructs(Layouts.Cls k) { + if (k != null && p.constructed.add(k)) { + p.changed = true; + } + } + + /// Whether `d` is a compiled function nothing in the program reaches. + /// Its body is not emitted: the function raises, naming itself, if a + /// path this pass has no way to see calls it after all. + boolean removed(FunctionDef d) { + Fn f = p.fns.get(d); + return p.done && f != null && !f.analysisOnly && !p.reached.contains(d); + } + + private void escapeFn(Fn f) { + if (f != null && !f.escapes) { + f.escapes = true; + p.changed = true; + } + if (f != null) { + reach(f); + } + // Callers through a value are unknown, but the typed version is + // entered from the generic one only through a guard that checks + // every argument (TypedEmit.entry): a parameter keeps what its + // direct callers pass, and one nobody calls directly takes the type + // its uses suggest, once the pass has settled [#uncalled]. Guessed + // here, at the escape, a guess of OBJECT came before the direct calls + // were seen and every typed argument they passed then joined into + // it (MarkItDown's `ConverterRegistration.__init__`). + } + + /// The type the uses of parameter `p` in `def` suggest: INT when it is + /// a `range` bound, a list repeat count or an operand next to an int + /// constant; FLOAT next to a float constant; OBJECT when the uses say + /// nothing or disagree. + static Ty guess(FunctionDef def, String p) { + Ty[] g = {null}; + boolean[] bad = {false}; + for (Stmt s : def.body) { + guessIn(s, p, g, bad); + } + return bad[0] || g[0] == null ? Ty.OBJECT : g[0]; + } + + private static void guessIn(Object o, String p, Ty[] g, boolean[] bad) { + if (o instanceof Call && ((Call) o).func instanceof Name && "range".equals(((Name) ((Call) o).func).id)) { + for (Expr a : ((Call) o).args) { + if (isName(a, p)) { + vote(Ty.INT, g, bad); + } + } + } else if (o instanceof BinOp) { + BinOp b = (BinOp) o; + if ("*".equals(b.op) && (b.left instanceof ListExpr && isName(b.right, p))) { + vote(Ty.INT, g, bad); + } else if (isName(b.left, p) || isName(b.right, p)) { + Ty c = constType(isName(b.left, p) ? b.right : b.left); + if (c != null) { + vote(c, g, bad); + } + } + } else if (o instanceof Compare && ((Compare) o).ops.size() == 1) { + Compare c = (Compare) o; + Expr r = c.comparators.get(0); + if (isName(c.left, p) || isName(r, p)) { + Ty t = constType(isName(c.left, p) ? r : c.left); + if (t != null) { + vote(t, g, bad); + } + } + } else if (o instanceof Assign) { + // Rebinding the parameter: its later uses say nothing of the + // argument. + for (Expr t : ((Assign) o).targets) { + if (isName(t, p)) { + bad[0] = true; + } + } + } + Infer.children(o, x -> guessIn(x, p, g, bad)); + } + + private static boolean isName(Expr e, String p) { + return e instanceof Name && ((Name) e).id.equals(p); + } + + private static Ty constType(Expr e) { + if (e instanceof Constant) { + Constant c = (Constant) e; + if (c.kind == Constant.Kind.INT) { + return Ty.INT; + } + if (c.kind == Constant.Kind.FLOAT && !c.text.matches(".*[jJ]")) { + return Ty.FLOAT; + } + } + return null; + } + + private static void vote(Ty t, Ty[] g, boolean[] bad) { + if (g[0] != null && !g[0].equals(t)) { + bad[0] = true; + } + g[0] = t; + } + + /// The compiled `__new__` constructing `k` runs, or null when it runs + /// the builtin one. + Fn newMethod(Layouts.Cls k) { + for (Layouts.Cls c = k; c != null; c = c.parent) { + if (c.bodyNames.contains("__new__")) { + FunctionDef d = bodyDef(c, "__new__"); + return d == null ? null : p.fns.get(d); + } + } + return null; + } + + /// `X.__new__(cls, ...)` for a builtin `X` or `object`, or + /// `super().__new__(cls, ...)` reaching one: a new instance of the + /// class `cls` is, made without running its `__init__`. Null when `c` + /// is no such call. + private Ty builtinNew(Call c, Fn fn, Scope sc) { + if (!(c.func instanceof Attribute) || !"__new__".equals(((Attribute) c.func).attr) || c.args.isEmpty() + || c.args.get(0) instanceof Starred) { + return null; + } + Expr owner = ((Attribute) c.func).value; + boolean builtin = owner instanceof Name && sc.resolve(((Name) owner).id) == Scope.Binding.BUILTIN + && !moduleScope.hasStarImport + && (Layouts.BUILTIN_NAMES.containsKey(((Name) owner).id) || "object".equals(((Name) owner).id)); + boolean sup = owner instanceof Call && ((Call) owner).func instanceof Name + && "super".equals(((Name) ((Call) owner).func).id) && sc.resolve("super") == Scope.Binding.BUILTIN + && fn != null && fn.cls != null && newMethod(fn.cls.parent) == null; + if (!builtin && !sup && !inheritedNew(owner, fn, sc)) { + return null; + } + Ty ct = type(c.args.get(0), fn, sc); + for (int i = 1; i < c.args.size(); i++) { + Expr x = c.args.get(i); + escape(type(x instanceof Starred ? ((Starred) x).value : x, fn, sc)); + } + for (Keyword kw : c.keywords) { + escape(type(kw.value, fn, sc)); + } + if (ct.k != Ty.K.CLS || ct.opt || ct.sites.length == 0) { + escape(ct); + return Ty.UNSEEN; + } + Ty r = Ty.BOT; + for (Layouts.Cls k : classesOf(ct)) { + r = mix(r, Ty.inst(k, false)); + } + return r; + } + + /// Whether `owner.__new__` is the builtin one whatever `owner` holds: + /// `owner` is an instance or class of compiled classes none of which, + /// nor any subclass, defines or may be given a `__new__` + /// (`self.__new__(self.__class__)` in a `__copy__`). + private boolean inheritedNew(Expr owner, Fn fn, Scope sc) { + if (!(owner instanceof Name) && !(owner instanceof Attribute)) { + return false; + } + Ty o = type(owner, fn, sc); + List ks = new ArrayList(); + if (o.k == Ty.K.INST && !o.opt) { + ks.add(o.cls); + } else if (o.k == Ty.K.CLS && !o.opt && o.sites.length > 0) { + ks.addAll(classesOf(o)); + } else { + return false; + } + for (Layouts.Cls k : ks) { + if (newMethod(k) != null || !closedFor(k, "__new__")) { + return false; + } + for (Layouts.Cls s : p.below(k)) { + if (newMethod(s) != null || !closedFor(s, "__new__")) { + return false; + } + } + } + return true; + } + + /// The type of the class object `k`. + Ty classValue(Layouts.Cls k) { + Integer id = p.clsId.get(k); + if (id == null) { + id = Integer.valueOf(p.clsById.size()); + p.clsById.add(k); + p.clsId.put(k, id); + } + return Ty.cls(new int[] {id.intValue()}); + } + + /// Whether `k`, a class above it or one below it defines `__class__`. + private boolean ownClassAttr(Layouts.Cls k) { + for (Layouts.Cls c = k; c != null; c = c.parent) { + if (c.bodyNames.contains("__class__")) { + return true; + } + } + for (Layouts.Cls c : selfAndBelow(k)) { + if (c.bodyNames.contains("__class__")) { + return true; + } + } + return false; + } + + /// The type of class attribute `attr` of `k` when it compiles to a typed + /// static field (Emitter#classStatics): `k`'s own body binds it exactly + /// once, the whole program never stores the name as an attribute (strict + /// mode refuses the computed stores that could), nothing between `type` + /// and `k` can change how the class answers a read (no metaclass, no + /// class decorator, one compiled base chain), and the value's type is + /// known from the expression alone. Null otherwise. + Ty classStatic(Layouts.Cls k, String attr) { + // A computed store (`setattr(o, name, v)`) could rebind it unseen + // when it may reach `k`, a class `k` inherits from or one below it + // ([WholeProgram.Module#computedStoreReaches]); decided from the + // closed world, whether or not strict mode refuses such stores. + if (facts == null || k == null || !k.compiled || facts.attrStored(attr) || attr.startsWith("__") + || k.def.decorators.size() > 0) { + return null; + } + if (k.enumMeta) { + // A member the compiler defined (EnumLowering): stored once, + // right after the class, as an instance of exactly the class. + List mem = EnumLowering.members(k.def); + return mem != null && mem.contains(attr) && Layouts.trailing(k.def).containsKey(attr) && !k.builtinOwn + && layoutHolds(k) ? Ty.inst(k, false) : null; + } + for (Layouts.Cls c = k; c != null; c = c.parent) { + if (!c.def.keywords.isEmpty() || c.def.bases.size() > 1 || c.builtin != null || c.extraBases + || c.parent == null && !c.def.bases.isEmpty() && !isName(c.def.bases.get(0), "object")) { + return null; + } + } + for (Layouts.Cls c : selfAndBelow(k)) { + if (facts.computedStoreReaches(c.def)) { + return null; + } + } + for (Layouts.Cls c = k; c != null; c = c.parent) { + if (facts.computedStoreReaches(c.def)) { + return null; + } + } + Expr v = Layouts.onceValue(k, attr); + if (v instanceof Constant) { + Constant cv = (Constant) v; + switch (cv.kind) { + case STR: + return Ty.STR; + case FLOAT: + return Ty.FLOAT; + case TRUE: + case FALSE: + return Ty.BOOL; + default: + // An int stays on the class-constant fold + // (Layouts#classConstant): typed code holds an int in + // two parts, which one static field does not. + return null; + } + } + if (v instanceof Call && ((Call) v).func instanceof Name && !k.bodyNames.contains(((Name) ((Call) v).func).id)) { + Layouts.Cls o = calledClass(((Call) v).func, moduleScope); + if (o != null && o.compiled && o.builtin == null && layoutHolds(o) && Layouts.resolver(o, "__get__") == null + && Layouts.resolver(o, "__new__") == null) { + return Ty.inst(o, false); + } + } + return v == null || v instanceof Constant ? null : staticExprType(k, v); + } + + /// Class statics whose value expression is being typed, against a + /// value that names another class's static naming this one. + private final Set typingStatic = java.util.Collections.newSetFromMap(new IdentityHashMap()); + + /// The type of once-bound class attribute value `v` when the inference + /// knows it from the module's scope: it names nothing of the class body + /// (whose scope the module's is not), and is a str, float, bool, int or + /// an instance of a compiled class that is no descriptor. Null otherwise. + private Ty staticExprType(Layouts.Cls k, Expr v) { + boolean[] local = new boolean[1]; + namesIn(v, k.bodyNames, local); + if (local[0] || !typingStatic.add(v)) { + return null; + } + try { + Ty t = type(v, null, moduleScope); + if (t == null || t.opt) { + return null; + } + switch (t.k) { + case STR: + case FLOAT: + case BOOL: + case INT: + return t.k == Ty.K.INT ? Ty.INT : t; + case INST: + Layouts.Cls o = t.cls; + return o != null && o.compiled && o.builtin == null && !o.builtinOwn && layoutHolds(o) + && Layouts.resolver(o, "__get__") == null ? t : null; + default: + return null; + } + } finally { + typingStatic.remove(v); + } + } + + private static void namesIn(Object o, Set names, boolean[] hit) { + if (o instanceof Name && names.contains(((Name) o).id) || o instanceof Lambda || o instanceof Comp) { + hit[0] = true; + return; + } + children(o, x -> namesIn(x, names, hit)); + } + + /// The compiled class `recv` names when `recv.attr` reads one of its + /// typed static fields ([#classStatic]), or null. + Layouts.Cls classStaticOf(Expr recv, String attr, Scope sc) { + Layouts.Cls k = calledClassOrEnum(recv, sc); + return k != null && classStatic(k, attr) != null ? k : null; + } + + /// Whether the class body that binds `m` nearest up from `k` binds it + /// by an assignment, not a `def`. + private static boolean classAttr(Layouts.Cls k, String m) { + Layouts.Cls res = Layouts.resolver(k, m); + if (res == null) { + return false; + } + for (Stmt s : res.def.body) { + if (s instanceof FunctionDef && ((FunctionDef) s).name.equals(m)) { + return false; + } + } + return valueOf(res.def.body, m) != null; + } + + /// What the last plain `n = value` of a class body assigns, or null. + private static Expr valueOf(List body, String n) { + Expr r = null; + for (Stmt s : body) { + if (s instanceof Assign && ((Assign) s).targets.size() == 1 && ((Assign) s).targets.get(0) instanceof Name + && ((Name) ((Assign) s).targets.get(0)).id.equals(n)) { + r = ((Assign) s).value; + } + } + return r; + } + + /// The method of one of the classes of `tree` named `n`, or null. + private Fn methodOf(List tree, String n) { + for (Layouts.Cls c : tree) { + for (Stmt s : c.def.body) { + if (s instanceof FunctionDef && ((FunctionDef) s).name.equals(n) && plainMethod((FunctionDef) s) + && ((FunctionDef) s).decorators.isEmpty()) { + Fn f = p.fns.get(s); + return f == null || f.analysisOnly ? null : f; + } + } + } + return null; + } + + /// A bound method of one of `fs` -- a method, or a function stored in a + /// class body, which reading it through an instance binds the same + /// way -- or null when there is none. + private Ty methValueOf(List fs) { + if (fs.isEmpty()) { + return null; + } + Set ids = new java.util.TreeSet(); + for (Fn f : fs) { + Integer id = p.methId.get(f); + if (id == null) { + id = Integer.valueOf(p.methById.size()); + p.methById.add(f); + p.methId.put(f, id); + } + ids.add(id); + } + int[] r = new int[ids.size()]; + int i = 0; + for (Integer id : ids) { + r[i++] = id.intValue(); + } + return Ty.meth(r); + } + + /// A bound method of one of `fs`, or null when one has no id to give. + private Ty methValue(List defs) { + int[] ids = new int[defs.size()]; + for (int i = 0; i < ids.length; i++) { + Fn f = p.fns.get(defs.get(i)); + if (f == null || f.cls == null) { + return null; + } + Integer id = p.methId.get(f); + if (id == null) { + id = Integer.valueOf(p.methById.size()); + p.methById.add(f); + p.methId.put(f, id); + } + ids[i] = id.intValue(); + } + java.util.Arrays.sort(ids); + return Ty.meth(ids); + } + + /// Parameter `i` of `f` as its body reads it. The guard at the door + /// cannot test which function a value is -- every one is an object to + /// it -- so a body entered through it holds a function parameter as + /// the generic object, and the functions it was seen to be are called + /// from there. + private Ty paramIn(Fn f, int i) { + Ty t = f.params[i]; + if (entered(f) && hasFunc(t)) { + escapeFuncs(t); + return Ty.OBJECT; + } + return t; + } + + private static boolean hasFunc(Ty t) { + if (t.k == Ty.K.FUNC || t.k == Ty.K.METH) { + return true; + } + if (t.k == Ty.K.UNION) { + for (Ty m : t.members()) { + if (m.k == Ty.K.FUNC || m.k == Ty.K.METH) { + return true; + } + } + } + return false; + } + + /// A call of a value that is one of some functions or bound methods: + /// each takes the arguments bound to its own parameters. Null when the + /// value may be anything else, or the call is starred. + private Ty callThrough(Call c, Ty ft, Fn fn, Scope sc) { + List callees = new ArrayList(); + List froms = new ArrayList(); + if (!anyStarred(c.args) && callables(ft.nonNone(), callees, froms)) { + // One of these functions or bound methods: each takes the + // arguments bound to its own parameters, keywords by name, as a + // direct call of it would. A None the value may also be raises. + Ty ret = Ty.BOT; + boolean bound = false; + boolean door = false; + for (int i = 0; i < callees.size(); i++) { + Fn f = callees.get(i); + int from = froms.get(i).intValue(); + if (raises(c, f.def, from)) { + // This one cannot take these arguments: the call raises + // TypeError before it runs. + continue; + } + bound |= from == 1; + List given = staticArgs(c, f.def, from); + if (given == null) { + for (Expr x : c.args) { + escape(type(x, fn, sc)); + } + for (Keyword kw : c.keywords) { + escape(type(kw.value, fn, sc)); + } + escapeFn(f); + } else { + List args = new ArrayList(); + for (Expr x : given) { + args.add(type(x, fn, sc)); + } + if (!callFn(f, args, from, binds(f, args.size() + from), true)) { + // An argument the typed version cannot be sure of: + // its guard picks the version that runs. + door = true; + } + } + ret = mix(ret, retOf(f, f.ret)); + } + if (bound || door) { + // Made generically: the bound method's guard picks the + // version that runs. + doors.add(c); + } + return ret; + } + return null; + } + + /// The functions (from 0) and bound methods (from 1) `t` may be, into + /// `fs` and `froms`; false when it may be anything else. + private boolean callables(Ty t, List fs, List froms) { + Ty[] ms = t.k == Ty.K.UNION ? t.members() : new Ty[] {t}; + for (Ty m : ms) { + if (noCall(m)) { + // Calling it raises: nothing runs. + continue; + } + if (m.k == Ty.K.FUNC) { + for (Fn f : funcsOf(m)) { + fs.add(f); + froms.add(Integer.valueOf(0)); + } + } else if (m.k == Ty.K.METH) { + for (Fn f : methsOf(m)) { + fs.add(f); + froms.add(Integer.valueOf(1)); + } + } else { + return false; + } + } + return !fs.isEmpty(); + } + + /// Whether `t` is one of some functions or bound methods, or a value + /// never called (None, a dict the same name reads): a + /// container keeps it as it is, and a call through what it reads is + /// followed to each (generated code holds it as an object; see + /// [#loc]). + private boolean callableSet(Ty t) { + if (t == null || t.k == Ty.K.BOT) { + return false; + } + Ty[] ms = t.k == Ty.K.UNION ? t.members() : new Ty[] {t}; + boolean any = false; + for (Ty m : ms) { + if (m.k == Ty.K.FUNC || m.k == Ty.K.METH) { + any = true; + } else if (!noCall(m)) { + return false; + } + } + return any; + } + + /// Whether a value of `t` is never callable: calling one raises. + private static boolean noCall(Ty t) { + switch (t.k) { + case NONE: + case INT: + case BOOL: + case FLOAT: + case STR: + case BYTES: + case LIST: + case TUPLE: + case DICT: + return true; + default: + return false; + } + } + + /// Escapes the functions `t` may be, and nothing else of it. + private void escapeFuncs(Ty t) { + if (t.k == Ty.K.FUNC || t.k == Ty.K.METH) { + escape(t); + } else if (t.k == Ty.K.UNION) { + for (Ty m : t.members()) { + escapeFuncs(m); + } + } + } + + /// Function `f` as a value. + private Ty funcValue(Fn f) { + Integer id = p.funcId.get(f); + if (id == null) { + id = Integer.valueOf(p.funcById.size()); + p.funcById.add(f); + p.funcId.put(f, id); + } + return Ty.func(new int[] {id.intValue()}); + } + + /// The functions a `FUNC` type may be. + private List funcsOf(Ty t) { + List r = new ArrayList(); + for (int id : t.sites) { + r.add(p.funcById.get(id)); + } + return r; + } + + /// Whether `f` is a function nested in another or a lambda: analysed, + /// entered only by the calls its value reaches. + private static boolean nested(Fn f) { + return f.analysisOnly && f.cls == null; + } + + /// The scope owning closure variable `n` read or stored in `sc`, or null. + private static Scope cellOwner(String n, Scope sc, Scope.Binding b) { + Scope o = b == Scope.Binding.CELL ? sc : sc.owner(n); + return o != null && (o.kind == Scope.Kind.FUNCTION || o.kind == Scope.Kind.LAMBDA) ? o : null; + } + + /// The methods a `METH` type may be. + private List methsOf(Ty t) { + List r = new ArrayList(); + for (int id : t.sites) { + r.add(p.methById.get(id)); + } + return r; + } + + /// `v`, unless it is a bound method: those stay in locals and results, + /// and one that would go further lets its methods go and is an object + /// from there on. + private Ty noMeth(Ty v) { + if (v != null && v.k == Ty.K.METH) { + for (Fn f : methsOf(v)) { + escapeFn(f); + } + return Ty.UNSEEN; + } + return v; + } + + /// The classes a `CLS` type may be. + List classesOf(Ty t) { + List r = new ArrayList(); + for (int s : t.sites) { + r.add(p.clsById.get(s)); + } + return r; + } + + /// A call of a class object of type `t`: it constructs one of those + /// classes, each as a direct call would. + private Ty constructAny(Call c, Ty t, Fn fn, Scope sc, boolean simple) { + Ty r = Ty.BOT; + for (Layouts.Cls k : classesOf(t)) { + r = mix(r, callKnown(c, null, k, fn, sc, simple)); + } + return r; + } + + private void escapeClass(Layouts.Cls k) { + // Whoever holds the class makes instances of it. + looseRoot(k); + Layouts.Cls o = Layouts.resolver(k, "__init__"); + if (o != null && o.typable.get("__init__") != null) { + escapeFn(p.fns.get(o.typable.get("__init__"))); + } + } + + /// The one compiled method `super().m` / `super(K, self).m` runs in a + /// method of compiled class K, or null. Static only where the MRO is + /// the parent chain: K and every compiled class below it have at most + /// one base (a subclass `S(K, Mixin)` would put Mixin after K), the + /// method is the parent chain's own and its class is not open (a + /// store could replace it). Unresolved, every `super().__init__(...)` + /// was a dynamic call and the parent's constructor took only objects. + private Fn superTarget(Attribute a, Fn fn, Scope sc) { + if (fn == null || fn.cls == null || sc != fn.def.scope || fn.names.isEmpty() //NOPMD CompareObjectsWithEquals - identity is meant + || !(a.value instanceof Call) || !(((Call) a.value).func instanceof Name) + || !"super".equals(((Name) ((Call) a.value).func).id) + || sc.resolve("super") != Scope.Binding.BUILTIN) { + return null; + } + Call s = (Call) a.value; + if (!s.keywords.isEmpty() || !(s.args.isEmpty() || s.args.size() == 2 + && s.args.get(0) instanceof Name && calledClass(s.args.get(0), sc) == fn.cls //NOPMD CompareObjectsWithEquals - identity is meant + && s.args.get(1) instanceof Name && ((Name) s.args.get(1)).id.equals(fn.names.get(0)))) { + return null; + } + if (!singleChain(fn.cls)) { + return mroSuperTarget(a.attr, fn.cls); + } + Layouts.Cls k = fn.cls; + if (k.parent == null) { + return null; + } + Layouts.Cls o = Layouts.resolver(k.parent, a.attr); + FunctionDef m = o == null ? null : o.typable.get(a.attr); + if (m == null || open.contains(o) || open.contains(k.parent)) { + return null; + } + // The chain from the parent to the method's class is compiled and + // single-based too, or the MRO could leave it. + for (Layouts.Cls c = k.parent; c != o; c = c.parent) { //NOPMD CompareObjectsWithEquals - identity is meant + if (c == null || c.def.bases.size() > 1) { + return null; + } + } + return p.fns.get(m); + } + + /// `super().name` in a method of K where some class at or below K has + /// several bases, so the MRO is not the parent chain. Every compiled + /// class whose Java chain holds K has a C3 MRO known here; when the + /// first class after K in each of them that binds `name` is one and + /// the same O, on K's own Java chain, every instance that can run the + /// method reaches O's method, and the call is made to it directly. + /// Null where they differ, where an MRO holds a base that is not + /// compiled (it could bind the name), where a class below K holds K + /// only as a merged base (its instance is no Java K), or where a class + /// between K and O, or O itself, is open to stores (a patch could + /// rebind the name, as for the parent-chain case). + private Fn mroSuperTarget(String name, Layouts.Cls k) { + List cs = new ArrayList(); + cs.add(k); + cs.addAll(p.below(k)); + Layouts.Cls target = null; + for (Layouts.Cls c : cs) { + boolean onChain = false; + for (Layouts.Cls d = c; d != null && !onChain; d = d.parent) { + onChain = d == k; //NOPMD CompareObjectsWithEquals - identity is meant + } + if (!onChain) { + return null; + } + List bs = new ArrayList(); + bs.add(c); + List mro = Layouts.c3(bs); + if (mro == null) { + return null; + } + for (Layouts.Cls x : mro) { + if (compiledBases(x.def) != x.bases.size()) { + return null; + } + } + int i = mro.indexOf(k); + Layouts.Cls o = null; + for (int j = i + 1; j < mro.size() && o == null; j++) { + Layouts.Cls x = mro.get(j); + if (open.contains(x)) { + return null; + } + if (Layouts.bodyBindings(x.def).contains(name)) { + o = x; + } + } + if (o == null || target != null && target != o) { //NOPMD CompareObjectsWithEquals - identity is meant + return null; + } + target = o; + } + boolean onK = false; + for (Layouts.Cls d = k.parent; d != null && !onK; d = d.parent) { + onK = d == target; //NOPMD CompareObjectsWithEquals - identity is meant + } + FunctionDef m = onK ? target.typable.get(name) : null; + return m == null ? null : p.fns.get(m); + } + + /// The bases of `d` that put a class in its MRO which binds names: + /// every one but a typing marker and `object`. + private static int compiledBases(ClassDef d) { + int n = 0; + for (Expr e : d.bases) { + if (!Layouts.typingBase(e) && !(e instanceof Name && "object".equals(((Name) e).id))) { + n++; + } + } + return n; + } + + /// Whether K's MRO is its parent chain for every instance: K, each + /// class above it and each compiled class below it has one base. + /// The bases of `d` that take part in its MRO at run time: + /// `Generic[T]` adds only `typing.Generic`, which binds no method a + /// compiled class could reach. + private static int realBases(ClassDef d) { + int n = 0; + for (Expr e : d.bases) { + if (!Layouts.typingBase(e)) { + n++; + } + } + return n; + } + + /// The first base of `d` that is not a typing marker, or null. + private static Expr firstRealBase(ClassDef d) { + for (Expr e : d.bases) { + if (!Layouts.typingBase(e)) { + return e; + } + } + return null; + } + + /// What the builtin `n` answers whatever it is given, when that is + /// one type; the emitter unboxes the generic call's result to it. + /// Whether `t` is a value the runtime compares and adds as a primitive: + /// a bool, an int, a float or a str, never None. + private static boolean primitive(Ty t) { + return !t.opt && (t.k == Ty.K.BOOL || t.k == Ty.K.INT || t.k == Ty.K.FLOAT || t.k == Ty.K.STR); + } + + /// Whether every keyword of `c` is one of `names`. + private static boolean keywordsAmong(Call c, String... names) { + for (Keyword kw : c.keywords) { + if (kw.arg == null || !java.util.Arrays.asList(names).contains(kw.arg)) { + return false; + } + } + return true; + } + + /// What a builtin answers over values it handles as primitives: + /// `sorted`, `min`, `max`, `sum` and `round` of bools, ints, floats and + /// strs, which the runtime orders and adds with no method call. Null + /// for anything else, which takes the general path. + private Ty builtinValue(String n, Call c, List args, Fn fn, Scope sc) { + switch (n) { + case "sorted": { + if (args.size() != 1 || !keywordsAmong(c, "key", "reverse")) { + return null; + } + Ty a0 = args.get(0); + Ty e = a0.k == Ty.K.LIST && !a0.opt ? elem(a0) : a0.k == Ty.K.STR && !a0.opt ? Ty.STR + : a0.k == Ty.K.DICT && !a0.opt && a0.sites.length > 0 ? dictKeyOf(a0) : null; + if (e == null || e.k == Ty.K.BOT) { + return null; + } + for (Keyword kw : c.keywords) { + // The key function is called with each element. + escape(type(kw.value, fn, sc)); + } + if (!primitive(e) && (c.keywords.isEmpty() || !"key".equals(c.keywords.get(0).arg) + || c.keywords.size() != 1)) { + // Ordered by their own comparison methods. + escape(e); + } + int s = site(c); + siteJoin(s, e); + return Ty.list(new int[] {s}, false); + } + case "min": + case "max": { + if (args.isEmpty() || !c.keywords.isEmpty()) { + return null; + } + Ty r = Ty.BOT; + if (args.size() == 1) { + Ty a0 = args.get(0); + r = a0.k == Ty.K.LIST && !a0.opt ? elem(a0) : a0.k == Ty.K.STR && !a0.opt ? Ty.STR : null; + } else { + for (Ty t : args) { + r = primitive(t) ? mix(r, t) : null; + if (r == null) { + break; + } + } + } + return r != null && primitive(r) ? r : null; + } + case "sum": { + if (args.isEmpty() || args.size() > 2 || !c.keywords.isEmpty()) { + return null; + } + Ty a0 = args.get(0); + Ty e = a0.k == Ty.K.LIST && !a0.opt ? elem(a0) : null; + Ty start = args.size() == 2 ? args.get(1) : Ty.INT; + if (e == null || !numeric(e) || !numeric(start)) { + return null; + } + return e.k == Ty.K.FLOAT || start.k == Ty.K.FLOAT ? Ty.FLOAT : Ty.INT; + } + case "round": { + if (args.isEmpty() || args.size() > 2 || !c.keywords.isEmpty() || !numeric(args.get(0))) { + return null; + } + if (args.size() == 1) { + return Ty.INT; + } + return args.get(1).k == Ty.K.INT && !args.get(1).opt + ? (args.get(0).k == Ty.K.FLOAT ? Ty.FLOAT : Ty.INT) : null; + } + default: + return null; + } + } + + /// A bool, an int or a float, never None. + private static boolean numeric(Ty t) { + return !t.opt && (t.k == Ty.K.BOOL || t.k == Ty.K.INT || t.k == Ty.K.FLOAT); + } + + static Ty fixedReturn(String n) { + switch (n) { + case "hasattr": + case "callable": + case "issubclass": + case "isinstance": + case "all": + case "any": + case "bool": + return Ty.BOOL; + case "print": + return Ty.NONE; + case "len": + case "hash": + case "id": + case "ord": + case "int": + // Each answers an int or raises: `__len__`, `__hash__`, + // `__index__` and `__int__` must return one. + return Ty.INT; + case "float": + return Ty.FLOAT; + case "str": + // `str(x)` calls `__str__`, which must return a str. + case "repr": + case "ascii": + case "chr": + case "format": + case "hex": + case "oct": + case "bin": + return Ty.STR; + default: + return null; + } + } + + private boolean singleChain(Layouts.Cls k) { + for (Layouts.Cls c = k; c != null; c = c.parent) { + if (realBases(c.def) > 1) { + return false; + } + } + for (Layouts.Cls c : p.below(k)) { + if (realBases(c.def) > 1) { + return false; + } + } + return true; + } + + /// Whether `super().m` in `fn` runs no compiled method: the MRO is the + /// parent chain and nothing compiled on it binds `m`, so it is the + /// builtin base's (`type.__call__` under abc's ABCMeta, `object`'s). + /// Treated as an unknown receiver, it reached every compiled `m` of the + /// program: ABCMeta's `super().__call__(*args)` took Tag.__call__'s + /// parameters with it. + private boolean superBuiltin(Attribute a, Fn fn, Scope sc) { + if ((fn == null || fn.cls == null) && sc.kind == Scope.Kind.FUNCTION && sc.parent != null + && sc.parent.kind == Scope.Kind.CLASS && sc.parent.parent != null + && sc.parent.parent.kind == Scope.Kind.MODULE && a.value instanceof Call + && ((Call) a.value).func instanceof Name && "super".equals(((Name) ((Call) a.value).func).id) + && sc.resolve("super") == Scope.Binding.BUILTIN) { + // A class the build does not lay out (abc's ABCMeta, a + // metaclass): builtin when every base is a builtin name. + for (Stmt s : body) { + if (s instanceof ClassDef && ((ClassDef) s).name.equals(sc.parent.name)) { + boolean builtin = ((ClassDef) s).keywords.isEmpty(); + for (Expr e : ((ClassDef) s).bases) { + builtin &= e instanceof Name && moduleScope.resolve(((Name) e).id) == Scope.Binding.BUILTIN; + } + return builtin; + } + } + return false; + } + if (fn == null || fn.cls == null || sc != fn.def.scope || !(a.value instanceof Call) //NOPMD CompareObjectsWithEquals - identity is meant + || !(((Call) a.value).func instanceof Name) || !"super".equals(((Name) ((Call) a.value).func).id) + || sc.resolve("super") != Scope.Binding.BUILTIN || !singleChain(fn.cls)) { + return false; + } + return fn.cls.parent == null && realBases(fn.cls.def) <= 1 + && (firstRealBase(fn.cls.def) == null || calledClass(firstRealBase(fn.cls.def), sc) == null) + || fn.cls.parent != null && Layouts.resolver(fn.cls.parent, a.attr) == null + && rootIsBuiltin(fn.cls.parent); + } + + private boolean rootIsBuiltin(Layouts.Cls k) { + Layouts.Cls c = k; + while (c.parent != null) { + c = c.parent; + } + return firstRealBase(c.def) == null + || p.home.get(c).calledClass(firstRealBase(c.def), p.home.get(c).moduleScope) == null; + } + + /// The method a `super()` call `c` was resolved to, for the emitter. + Fn superCall(Call c) { + return p.superCalls.get(c); + } + + /// `r.name(args)` on a receiver the pass cannot name: a call through + /// the interface every compiled method `name` implements. Each one a + /// receiver of that class could reach takes the arguments into its + /// parameters, as a resolved call's callee does, so a caller reaching it + /// through its door passes the guard into the typed body. Escaping all + /// of them instead (what this replaced) left every method of a common + /// name -- bs4's `get`, `find`, `append` -- taking and returning only + /// objects, and their objects made the next receiver unknown in turn. + /// The arguments still escape (the caller did that): the receiver may + /// be no compiled class at all, a list whose `append` keeps them. + /// Set while [#duckCall] runs for `super().m(...)` in a method of + /// this class (see [#superOf]). + private Layouts.Cls superClass; + /// Whether the duck call being made is `super().m(...)`: it reaches a + /// class only after the caller's in the MRO of `type(self)`, a class + /// that derives from the target, so never one no class derives from. + private boolean superCall; + /// While [#duckCall] runs for a receiver known to be an instance of a + /// class with no layout or of a subclass [#receiverBound]: the class + /// definitions whose methods it can run. Null when nothing is known. + private Set duckBound; + + /// The compiled class K of `super().m` / `super(K, self).m` in one of + /// K's methods, or null. Such a call never runs K's own `m` or one of a + /// class below K: an MRO puts every subclass before its bases. + private Layouts.Cls superOf(Attribute a, Fn fn, Scope sc) { + if (fn == null || fn.cls == null || !(a.value instanceof Call) || !(((Call) a.value).func instanceof Name) + || !"super".equals(((Name) ((Call) a.value).func).id) + || sc.resolve("super") != Scope.Binding.BUILTIN) { + return null; + } + Call s = (Call) a.value; + if (s.args.isEmpty() && sc == fn.def.scope //NOPMD CompareObjectsWithEquals - identity is meant + || s.args.size() == 2 && s.args.get(0) instanceof Name && calledClass(s.args.get(0), sc) == fn.cls) { //NOPMD CompareObjectsWithEquals - identity is meant + return fn.cls; + } + return null; + } + + /// Whether `super().m(...)` in a method of K runs only methods of K's + /// compiled ancestors: every class above K is compiled, with no base + /// besides its compiled parent, up to one deriving from object alone. + /// The receiver then binds the first parameter of a method the pass + /// knows, and goes nowhere else: escaping it made K and every class + /// with it loose (bs4's `super(BeautifulStoneSoup, self).__init__( + /// *args, **kwargs)` loosened BeautifulSoup). + private boolean superWithin(Attribute a, Fn fn, Scope sc) { + Layouts.Cls k = superOf(a, fn, sc); + return k != null && chainKnown(k); + } + + /// Whether `k` and every class above it are compiled, with no base + /// besides the compiled parent and no attribute hook, up to a class + /// deriving from object alone: every method an MRO walk from `k` can + /// find is one the pass knows. + private static boolean chainKnown(Layouts.Cls k) { + for (Layouts.Cls c = k; c != null; c = c.parent) { + if (!c.compiled || c.extraBases || !c.def.keywords.isEmpty() + || c.bodyNames.contains("__getattr__") || c.bodyNames.contains("__getattribute__")) { + return false; + } + if (c.parent == null && !(c.def.bases.isEmpty() || c.def.bases.size() == 1 + && c.def.bases.get(0) instanceof Name && "object".equals(((Name) c.def.bases.get(0)).id))) { + return false; + } + } + return true; + } + + /// Every name a string literal of the Java runtime spells + /// (runtime-names.txt): the only methods a runtime object can answer. + private static Set runtimeNames; + + private static synchronized Set runtimeMethodNames() { + if (runtimeNames == null) { + Set s = new HashSet(); + try (java.io.InputStream in = Infer.class.getResourceAsStream("/com/codename1/python/transpiler/runtime-names.txt")) { + if (in == null) { + throw new IllegalStateException("runtime-names.txt is missing"); + } + try (java.io.BufferedReader r = new java.io.BufferedReader( + new java.io.InputStreamReader(in, java.nio.charset.StandardCharsets.UTF_8))) { + for (String l = r.readLine(); l != null; l = r.readLine()) { + if (!l.isEmpty()) { + s.add(l); + } + } + } + } catch (java.io.IOException e) { + throw new IllegalStateException(e); + } + runtimeNames = s; + } + return runtimeNames; + } + + /// Whether a method called `n` can only be one of the program's own + /// methods -- or what an answering `__getattr__` returns, called + /// ([#answeredCall]) -- whatever object it is called on. Every object then has it + /// as a slot of one interface: the program's methods of that name are + /// its implementations, and the default -- the generic lookup -- raises + /// AttributeError. So the call reaches those methods and nothing else: + /// its arguments go to their parameters, its result is theirs. Not so + /// when a runtime object may answer the name (a string literal of the + /// runtime spells it), when Java classes are imported (their objects + /// answer anything), when a module function or class of that name may + /// be what a module value hands out, when an attribute of that name is + /// stored (it may hold any callable), or when a class answers names it + /// does not define. + /// Whether `c` was typed through a method slot ([#closedName]). + boolean slotCall(Call c) { + return p.slotCalls.contains(c); + } + + boolean closedName(String n) { + if (!p.closed || facts == null || facts.javaAnswers(n) || runtimeMethodNames().contains(n) + || facts.attrStored(n) || facts.methodPatched(n)) { + return false; + } + if (p.defNames == null) { + Set names = new HashSet(); + List answering = new ArrayList(); + for (Fn f : p.fns.values()) { + if (f.cls == null) { + names.add(f.def.name); + } else if (("__getattr__".equals(f.def.name) || "__getattribute__".equals(f.def.name)) + && answers(f.def)) { + answering.add(f); + } + } + // A module attribute that is not a function may hold any + // callable (`mod.handler()`): every name a module's own + // statements mention is open, as a class body's are. + for (Infer m : p.modules.values()) { + if (m.body != null) { + for (Stmt s : m.body) { + classBodyNames(s, names); + } + } + } + for (Layouts.Cls k : p.home.keySet()) { + names.add(k.def.name); + // A class attribute that is not a method (`suiteClass = + // TestSuite`) may hold any callable: every name the class + // body's own statements mention is open. + for (Stmt s : k.def.body) { + classBodyNames(s, names); + } + } + p.answering = answering; + p.defNames = names; + } + return !p.defNames.contains(n); + } + + /// What a closed-name call returns on an object whose class answers + /// names it lacks: each answering `__getattr__` of a live class + /// returns a value that is then called with the arguments. A function + /// or bound method is followed; an instance runs its `__call__`; a + /// value no call accepts raises; anything else is not known, and its + /// arguments go where they please. + private Ty answeredCall(Ty recv, List args, boolean positional, Fn fn, Scope sc) { + Ty ret = Ty.BOT; + for (Fn g : p.answering) { + if (g.cls == null || !classLive(g.cls) || !mayBe(recv, g.cls)) { + continue; + } + Ty t = retOf(g, g.ret); + if (t == null || t.k == Ty.K.BOT) { + continue; + } + for (Ty m : t.k == Ty.K.UNION ? t.members() : new Ty[] {t}) { + List fs = new ArrayList(); + List froms = new ArrayList(); + if (noCall(m)) { + continue; + } + if (m.k == Ty.K.INST) { + ret = mix(ret, duckCall(m, "__call__", args, positional, null, fn, sc)); + } else if (callables(m, fs, froms)) { + for (int i = 0; i < fs.size(); i++) { + Fn f = fs.get(i); + int from = froms.get(i).intValue(); + callFn(f, args, from, positional && binds(f, args.size() + from), true); + ret = mix(ret, retOf(f, f.ret)); + } + } else { + for (Ty a : args) { + escape(a); + } + return Ty.UNSEEN; + } + } + } + return ret; + } + + /// Whether a value of type `t` may be an instance of `k` or of a class + /// derived from it: only then can `k`'s `__getattr__` answer for it. A + /// value of no known class may be anything; a builtin value (a str, a + /// list) is never an instance of a compiled class. + private boolean mayBe(Ty t, Layouts.Cls k) { + for (Ty m : t.members()) { + if (m.k == Ty.K.OBJECT || m.k == Ty.K.INST && (m.cls == null || isSelfOrAncestor(k, m.cls) + || isSelfOrAncestor(m.cls, k))) { + return true; + } + } + return false; + } + + /// Whether a live class answers names it lacks ([#answeredCall]). + private boolean answeringLive(Ty recv) { + for (Fn g : p.answering) { + if (g.cls != null && classLive(g.cls) && mayBe(recv, g.cls)) { + return true; + } + } + return false; + } + + /// Whether `__getattr__` `d` returns anything but `getattr(x, name)` + /// of its own name parameter: such a return forwards the same slot to + /// another object, which adds no method to it. + private static boolean answers(FunctionDef d) { + if (d.args.positional.size() < 2) { + return returnsValue(d.body); + } + String nameParam = d.args.positional.get(1).name; + boolean[] r = {false}; + for (Stmt s : d.body) { + answers(s, nameParam, r); + } + return r[0]; + } + + private static void answers(Object o, String nameParam, boolean[] r) { + if (o instanceof Return && ((Return) o).value != null) { + Expr v = ((Return) o).value; + if (!(v instanceof Call && ((Call) v).func instanceof Name + && "getattr".equals(((Name) ((Call) v).func).id) && ((Call) v).args.size() == 2 + && ((Call) v).keywords.isEmpty() && ((Call) v).args.get(1) instanceof Name + && nameParam.equals(((Name) ((Call) v).args.get(1)).id))) { + r[0] = true; + } + return; + } + if (o instanceof FunctionDef || o instanceof ClassDef || o instanceof Lambda) { + return; + } + Infer.children(o, x -> answers(x, nameParam, r)); + } + + /// Whether a statement of the class body `sc` (not a nested function's + /// body) mentions `n`. + private boolean classBodyReads(Scope sc, String n) { + Set names = classBodyMentions.get(sc); + return names != null && names.contains(n); + } + + /// The attribute read each literal `getattr(x, "name")` is typed as. + private final Map literalGetattr = new IdentityHashMap(); + + /// What each class body's own statements mention, by class scope. + private final Map> classBodyMentions = new IdentityHashMap>(); + + /// Every name `o` mentions or imports, nested functions and classes + /// not looked into. + private static void classBodyNames(Object o, Set names) { + if (o instanceof FunctionDef || o instanceof ClassDef || o instanceof Lambda) { + return; + } + if (o instanceof Name) { + names.add(((Name) o).id); + } else if (o instanceof Import) { + for (Alias a : ((Import) o).names) { + names.add(a.asname != null ? a.asname : a.name); + } + } else if (o instanceof ImportFrom) { + for (Alias a : ((ImportFrom) o).names) { + names.add(a.asname != null ? a.asname : a.name); + } + } + Infer.children(o, x -> classBodyNames(x, names)); + } + + /// Whether a `return` with a value is among `body`'s statements, nested + /// functions and classes not counted. + private static boolean returnsValue(List body) { + boolean[] r = {false}; + for (Stmt s : body) { + returnsValue(s, r); + } + return r[0]; + } + + private static void returnsValue(Object o, boolean[] r) { + if (o instanceof Return && ((Return) o).value != null) { + r[0] = true; + return; + } + if (o instanceof FunctionDef || o instanceof ClassDef || o instanceof Lambda) { + return; + } + Infer.children(o, x -> returnsValue(x, r)); + } + + /// The class definitions an instance `recv` holds may take a method + /// from, when `recv` is known to be an instance of the class `C` whose + /// method `fn` is, or of a subclass of `C`: `C`'s own definition and + /// every ancestor's, plus whatever derives from `C` [#derivesFrom]. That + /// holds for `fn`'s first parameter when nothing rebinds it, and for a + /// local bound once, to `X.__new__(self.__class__)`. Null when not + /// known, or when an ancestor is not a class definition of the program. + private Set receiverBound(Expr recv, Fn fn) { + if (!(recv instanceof Name) || fn == null || fn.cls == null || fn.def.args.positional.isEmpty() + || !fn.def.decorators.isEmpty() || fn.def.scope.parent == null + || fn.def.scope.parent.kind != Scope.Kind.CLASS || fn.def.scope.parent.parent != moduleScope) { //NOPMD CompareObjectsWithEquals - identity is meant + return null; + } + String self = fn.def.args.positional.get(0).name; + Map n = new HashMap(); + for (Stmt s : fn.def.body) { + DataclassInit.count(s, n); + } + String r = ((Name) recv).id; + if (n.containsKey(self) || fn.def.scope.cells.contains(self)) { + return null; + } + if (!r.equals(self)) { + if (n.getOrDefault(r, 0) != 1 || fn.def.scope.cells.contains(r) || !newOfSelfClass(fn.def.body, r, self)) { + return null; + } + } + String cn = fn.def.scope.parent.name; + if (!stable(cn)) { + return null; + } + ClassDef c = Layouts.classNamed(body, cn); + if (c == null) { + return null; + } + Set out = java.util.Collections.newSetFromMap(new IdentityHashMap()); + return ancestors(c, this, out, 0) ? out : null; + } + + /// Whether operand `i` of `c` (-1 the left one) is `Cls.attr`, a + /// class of this module's attribute, compared only by identity: enum's + /// `init is not Enum.__init__` calls nothing, where reading the method + /// as a value escapes every `__init__` that may be it. + private boolean identityOperand(Compare c, int i, Scope sc) { + Expr x = i < 0 ? c.left : c.comparators.get(i); + if (!(x instanceof Attribute) || !(((Attribute) x).value instanceof Name)) { + return false; + } + String id = ((Name) ((Attribute) x).value).id; + if (!globalClasses.containsKey(id) || sc.resolve(id) != Scope.Binding.GLOBAL) { + return false; + } + for (int j = i < 0 ? 0 : i; j <= i + 1 && j < c.ops.size(); j++) { + String op = c.ops.get(j); + if (!"is".equals(op) && !"is not".equals(op)) { + return false; + } + } + return true; + } + + /// Whether the body of class `d` defines a function named `name`. + private static boolean definesFunction(ClassDef d, String name) { + for (Stmt s : d.body) { + if (s instanceof FunctionDef && ((FunctionDef) s).name.equals(name)) { + return true; + } + } + return false; + } + + /// Whether `k` and every class up its parent chain name one base at + /// most: nothing off that chain is in its MRO. + private static boolean singleBased(Layouts.Cls k) { + for (Layouts.Cls c = k; c != null; c = c.parent) { + if (c.def.bases.size() > 1 || !c.def.keywords.isEmpty()) { + return false; + } + } + return true; + } + + private final Map> sharedBelowSeen = + new IdentityHashMap>(); + + /// Whether some class of the program derives from both `a` and `b`, so + /// that an instance typed `a` can resolve a method of `b` through its + /// MRO although neither is on the other's compiled chain: a mixin + /// sibling (itsdangerous' `URLSafeTimedSerializer(URLSafeSerializerMixin, + /// TimedSerializer)` reaches the mixin's `load_payload` from + /// `Serializer.loads`). + private boolean sharedBelow(Layouts.Cls a, Layouts.Cls b) { + Map m = sharedBelowSeen.computeIfAbsent(a, + x -> new IdentityHashMap()); + Boolean r = m.get(b); + if (r == null) { + r = Boolean.FALSE; + for (Layouts.Cls k : new ArrayList(p.home.keySet())) { + if (k != a && k != b && derivesFrom(k, a.def) && derivesFrom(k, b.def)) { //NOPMD CompareObjectsWithEquals - identity is meant + r = Boolean.TRUE; + break; + } + } + m.put(b, r); + } + return r; + } + + /// Whether `k`'s class derives from `c`, or may: true too when one of + /// its ancestors is not a class definition this program resolves. + private boolean derivesFrom(Layouts.Cls k, ClassDef c) { + Set a = java.util.Collections.newSetFromMap(new IdentityHashMap()); + Infer h = p.home.get(k); + return h == null || !ancestors(k.def, h, a, 0) || a.contains(c); + } + + /// `K.m(self, ...)` on a class `K` of this module whose name the pass + /// does not type (a class without a layout): the call is unbound, so + /// every argument is the method's own, the first one included. Bound + /// as `K`'s instance method it put `self` in the first parameter of + /// every `m` of the program, and `Text.__init__(self)` typed another + /// class's `__init__(self, v)` parameter as the caller's class. The + /// one method `K` resolves is called when nothing can replace it; + /// otherwise every method of the name is entered with anything. + private Ty unboundCall(Call c, Attribute a, List args, boolean simple, Fn fn, Scope sc) { + Ty viaBase = baseCall(c, a, args, fn, sc); + if (viaBase != null) { + return viaBase; + } + if (!(a.value instanceof Name) || sc.resolve(((Name) a.value).id) != Scope.Binding.GLOBAL + || globalClasses.containsKey(((Name) a.value).id) || !stable(((Name) a.value).id)) { + return null; + } + ClassDef d = Layouts.classNamed(body, ((Name) a.value).id); + if (d == null) { + return null; + } + for (Keyword kw : c.keywords) { + escape(type(kw.value, fn, sc)); + } + Layouts.Cls k = layouts.all().get(d); + if (k == null && "__init__".equals(a.attr) && d.decorators.isEmpty() && d.keywords.isEmpty() + && (d.bases.isEmpty() || d.bases.size() == 1 && d.bases.get(0) instanceof Name + && "object".equals(((Name) d.bases.get(0)).id)) + && !Layouts.bodyBindings(d).contains("__init__") && !classValueRead(d.name)) { + // A class without a layout (pdfminer's `LTText`, a mixin) that + // derives from object alone and binds no `__init__`, and whose + // class object nothing holds as a value, so nothing can give it + // one: `LTText.__init__(self)` is object's. + for (Ty t : args) { + escape(t); + } + return Ty.NONE; + } + if (k != null && simple && c.keywords.isEmpty() && closedFor(k, a.attr) && (singleBased(k) || definesFunction(d, a.attr)) + && !layouts.fieldOwners.containsKey(a.attr)) { + Layouts.Cls o = Layouts.resolver(k, a.attr); + FunctionDef m = o == null ? null : o.typable.get(a.attr); + Fn f = m == null ? null : p.fns.get(m); + if (f != null && !classLevel(o, a.attr)) { + callFn(f, args, 0, binds(f, args.size()), true); + return retOf(f, f.ret); + } + if (o == null && "__init__".equals(a.attr) && singleBased(k) && fromObject(k) && !chainInitStored(k)) { + // Nothing up the chain binds it: object's, which does + // nothing with its arguments (pdfminer's + // `LTText.__init__(self)`). + for (Ty t : args) { + escape(t); + } + return Ty.NONE; + } + } + for (Ty t : args) { + escape(t); + } + escapeMethods(a.attr); + return Ty.OBJECT; + } + + /// Whether any module may hold the class named `n` as a value: it is + /// named anywhere but as a base, as the receiver of an attribute read + /// or call, or as the class `isinstance`/`issubclass` tests against; + /// imported under another name; or read off a module (`m.n`). A store + /// to one of its attributes counts as holding it. + private boolean classValueRead(String n) { + boolean[] hit = {false}; + for (Infer in : p.modules.values()) { + starFrom = in; + for (Stmt s : in.body) { + classValue(s, n, hit, false); + } + } + starFrom = null; + return hit[0]; + } + + private void classValue(Object o, String n, boolean[] hit, boolean storing) { + if (hit[0]) { + return; + } + if (o instanceof Assign || o instanceof AugAssign || o instanceof AnnAssign || o instanceof Node.Delete) { + List targets = o instanceof Assign ? ((Assign) o).targets + : o instanceof AnnAssign ? java.util.Collections.singletonList(((AnnAssign) o).target) + : o instanceof AugAssign ? java.util.Collections.singletonList(((AugAssign) o).target) + : ((Node.Delete) o).targets; + for (Expr t : targets) { + classValue(t, n, hit, true); + } + Expr v = o instanceof Assign ? ((Assign) o).value : o instanceof AnnAssign ? ((AnnAssign) o).value + : o instanceof AugAssign ? ((AugAssign) o).value : null; + if (v != null) { + classValue(v, n, hit, false); + } + return; + } + if (o instanceof ImportFrom) { + for (Alias al : ((ImportFrom) o).names) { + if (n.equals(al.name) && al.asname != null && !n.equals(al.asname) || "*".equals(al.name) && starBinds((ImportFrom) o, n)) { + hit[0] = true; + } + } + return; + } + if (o instanceof Attribute) { + Attribute a = (Attribute) o; + if (n.equals(a.attr) || storing && a.value instanceof Name && n.equals(((Name) a.value).id)) { + hit[0] = true; + return; + } + if (a.value instanceof Name && n.equals(((Name) a.value).id)) { + return; + } + classValue(a.value, n, hit, false); + return; + } + if (o instanceof Call && ((Call) o).args.size() == 2 && ((Call) o).args.get(0) instanceof Name + && (((Call) o).func instanceof Name && "cast".equals(((Name) ((Call) o).func).id) + || ((Call) o).func instanceof Attribute && "cast".equals(((Attribute) ((Call) o).func).attr))) { + // `typing.cast(K, x)` only names the type. + classValue(((Call) o).func, n, hit, false); + classValue(((Call) o).args.get(1), n, hit, false); + return; + } + if (o instanceof Call && ((Call) o).func instanceof Name && ((Call) o).args.size() == 2 + && ("isinstance".equals(((Name) ((Call) o).func).id) || "issubclass".equals(((Name) ((Call) o).func).id))) { + Call c = (Call) o; + classValue(c.args.get(0), n, hit, false); + Expr t = c.args.get(1); + List ks = t instanceof TupleExpr ? ((TupleExpr) t).elts : java.util.Collections.singletonList(t); + for (Expr x : ks) { + if (!(x instanceof Name)) { + classValue(x, n, hit, false); + } + } + for (Keyword kw : c.keywords) { + classValue(kw.value, n, hit, false); + } + return; + } + if (o instanceof ClassDef) { + ClassDef d = (ClassDef) o; + for (Expr x : d.bases) { + if (!(x instanceof Name)) { + classValue(x, n, hit, false); + } + } + for (Keyword kw : d.keywords) { + classValue(kw.value, n, hit, false); + } + for (Expr x : d.decorators) { + classValue(x, n, hit, false); + } + for (Stmt s : d.body) { + classValue(s, n, hit, false); + } + return; + } + if (o instanceof Name) { + if (n.equals(((Name) o).id)) { + hit[0] = true; + } + return; + } + Infer.children(o, x -> classValue(x, n, hit, false)); + } + + /// Whether `from m import *` may bring in `n`: `m` is a module of the + /// program that binds it at its top level, or star-imports in turn. A + /// module outside the program cannot hold one of its classes. + private boolean starBinds(ImportFrom f, String n) { + return starFrom == null || starBinds(starFrom, f, n, + java.util.Collections.newSetFromMap(new IdentityHashMap())); + } + + private boolean starBinds(Infer from, ImportFrom f, String n, Set seen) { + List targets = new ArrayList(); + if (f.level == 0) { + targets.add(p.modules.get(f.module)); + } else { + // Relative: against the importer's package, which is the module + // itself when it is a package's `__init__` -- both are tried. + String[] parts = from.moduleName.split("\\."); + for (int drop = f.level - 1; drop <= f.level; drop++) { + if (drop > parts.length) { + continue; + } + StringBuilder q = new StringBuilder(); + for (int i = 0; i < parts.length - drop; i++) { + q.append(q.length() == 0 ? "" : ".").append(parts[i]); + } + if (f.module != null) { + q.append(q.length() == 0 ? "" : ".").append(f.module); + } + targets.add(p.modules.get(q.toString())); + } + } + for (Infer m : targets) { + if (m == null || !seen.add(m)) { + continue; + } + if (m.moduleScope.assigned.contains(n)) { + return true; + } + List stars = new ArrayList(); + for (Stmt s : m.body) { + stars(s, stars); + } + for (ImportFrom s : stars) { + if (starBinds(m, s, n, seen)) { + return true; + } + } + } + return false; + } + + /// Adds every `from x import *` under `o` to `out`. + private static void stars(Object o, List out) { + if (o instanceof ImportFrom) { + for (Alias a : ((ImportFrom) o).names) { + if ("*".equals(a.name)) { + out.add((ImportFrom) o); + } + } + return; + } + Infer.children(o, x -> stars(x, out)); + } + + /// The module [#classValueRead] is scanning. + private Infer starFrom; + + /// Whether some module stores or deletes `X.__init__` by name for a + /// class `X` on the parent chain of `k` ([#initStore]). + private boolean chainInitStored(Layouts.Cls k) { + Set names = new HashSet(); + for (Layouts.Cls c = k; c != null; c = c.parent) { + names.add(c.def.name); + } + for (Infer in : p.modules.values()) { + boolean[] hit = {false}; + for (Stmt s : in.body) { + initStore(s, names, hit); + } + if (hit[0]) { + return true; + } + } + return false; + } + + /// Whether the parent chain of `k` ends in a class whose only base is + /// `object`, written or implied, and no class on it has a decorator. + private static boolean fromObject(Layouts.Cls k) { + Layouts.Cls c = k; + while (true) { + if (!c.def.decorators.isEmpty()) { + return false; + } + if (c.parent == null) { + break; + } + c = c.parent; + } + List bases = c.def.bases; + return bases.isEmpty() || bases.size() == 1 && bases.get(0) instanceof Name + && "object".equals(((Name) bases.get(0)).id); + } + + /// Whether `k.__init__` is object's: `k` names, once, a class this + /// module defines with no decorator, every ancestor a class definition + /// of the program none of which binds `__init__`, and no store anywhere + /// in the program can give one an `__init__` by name. + private boolean objectInit(Expr k, Scope sc) { + if (!(k instanceof Name) || sc.resolve(((Name) k).id) != Scope.Binding.GLOBAL || moduleScope.hasStarImport + || !stable(((Name) k).id) || p.dynStored.contains("__init__") + || p.computedStoredNames.contains("__init__")) { + return false; + } + ClassDef c = Layouts.classNamed(body, ((Name) k).id); + Set all = java.util.Collections.newSetFromMap(new IdentityHashMap()); + if (c == null || !ancestors(c, this, all, 0)) { + return false; + } + Set names = new HashSet(); + for (ClassDef d : all) { + if (!d.decorators.isEmpty() || Layouts.bodyBindings(d).contains("__init__")) { + return false; + } + names.add(d.name); + } + for (Infer in : p.modules.values()) { + boolean[] hit = {false}; + for (Stmt s : in.body) { + initStore(s, names, hit); + } + if (hit[0]) { + return false; + } + } + return true; + } + + /// Whether `o` stores `X.__init__` (or deletes it) for a name `X` in + /// `names`: a class object read by its name, which no type records. + private static void initStore(Object o, Set names, boolean[] hit) { + if (hit[0]) { + return; + } + List targets = o instanceof Assign ? ((Assign) o).targets + : o instanceof AnnAssign ? java.util.Collections.singletonList(((AnnAssign) o).target) + : o instanceof AugAssign ? java.util.Collections.singletonList(((AugAssign) o).target) + : o instanceof Node.Delete ? ((Node.Delete) o).targets : null; + if (targets != null) { + for (Expr t : targets) { + if (t instanceof Attribute && "__init__".equals(((Attribute) t).attr) + && ((Attribute) t).value instanceof Name && names.contains(((Name) ((Attribute) t).value).id)) { + hit[0] = true; + return; + } + } + } + Infer.children(o, x -> initStore(x, names, hit)); + } + + /// Whether `body` binds `r`, at its top level, as + /// `r = X.__new__(self.__class__)`. + private static boolean newOfSelfClass(List body, String r, String self) { + for (Stmt s : body) { + if (s instanceof Assign && ((Assign) s).targets.size() == 1 && ((Assign) s).targets.get(0) instanceof Name + && r.equals(((Name) ((Assign) s).targets.get(0)).id) && ((Assign) s).value instanceof Call) { + Call c = (Call) ((Assign) s).value; + return c.func instanceof Attribute && "__new__".equals(((Attribute) c.func).attr) + && c.args.size() == 1 && c.keywords.isEmpty() && c.args.get(0) instanceof Attribute + && "__class__".equals(((Attribute) c.args.get(0)).attr) + && ((Attribute) c.args.get(0)).value instanceof Name + && self.equals(((Name) ((Attribute) c.args.get(0)).value).id); + } + } + return false; + } + + /// Adds `c` and every class it derives from to `out`; false when a base + /// is not a class definition this program resolves. + private static boolean ancestors(ClassDef c, Infer home, Set out, int depth) { + if (depth > 32 || !c.keywords.isEmpty() && !home.keepsBases(c)) { + return false; + } + if (!out.add(c)) { + return true; + } + for (Expr b : c.bases) { + if (b instanceof Name && "object".equals(((Name) b).id) + && home.moduleScope.resolve("object") == Scope.Binding.BUILTIN) { + continue; + } + ClassDef d = null; + Infer h = null; + if (b instanceof Name && home.stable(((Name) b).id)) { + d = Layouts.classNamed(home.body, ((Name) b).id); + h = d == null ? null : home; + } + if (d == null) { + d = home.foreignClassDef(b); + h = home.classHome(b); + } + if (d == null || h == null || !ancestors(d, h, out, depth + 1)) { + return false; + } + } + return true; + } + + /// Whether the keywords of `c` leave its bases as written: only a + /// `metaclass=` naming a class of the program that derives from `type` + /// alone, defines no `mro`, and whose `__new__`, if any, hands its own + /// bases parameter unchanged to every `__new__` it returns (openpyxl's + /// `MetaStrict`). + private boolean keepsBases(ClassDef c) { + for (Keyword k : c.keywords) { + if (!"metaclass".equals(k.arg)) { + return false; + } + ClassDef m = null; + if (k.value instanceof Name && stable(((Name) k.value).id)) { + m = Layouts.classNamed(body, ((Name) k.value).id); + } + if (m == null) { + m = foreignClassDef(k.value); + } + if (m == null || !m.keywords.isEmpty() || m.bases.size() != 1 || !(m.bases.get(0) instanceof Name) + || !"type".equals(((Name) m.bases.get(0)).id)) { + return false; + } + for (Stmt s : m.body) { + if (s instanceof FunctionDef && "mro".equals(((FunctionDef) s).name)) { + return false; + } + if (s instanceof FunctionDef && "__new__".equals(((FunctionDef) s).name) + && !forwardsBases((FunctionDef) s)) { + return false; + } + } + } + return true; + } + + private static boolean forwardsBases(FunctionDef f) { + if (f.args.positional.size() < 3 || !f.decorators.isEmpty()) { + return false; + } + String bases = f.args.positional.get(2).name; + Map n = new HashMap(); + for (Stmt s : f.body) { + DataclassInit.count(s, n); + } + if (n.containsKey(bases)) { + return false; + } + boolean[] ok = {true}; + forwardsBases(f.body, bases, ok); + return ok[0]; + } + + private static void forwardsBases(Object o, String bases, boolean[] ok) { + if (o instanceof FunctionDef || o instanceof ClassDef || o instanceof Lambda) { + return; + } + if (o instanceof Return) { + Expr v = ((Return) o).value; + ok[0] &= v instanceof Call && ((Call) v).func instanceof Attribute + && "__new__".equals(((Attribute) ((Call) v).func).attr) && ((Call) v).args.size() >= 3 + && ((Call) v).args.get(2) instanceof Name && bases.equals(((Name) ((Call) v).args.get(2)).id); + return; + } + Infer.children(o, x -> forwardsBases(x, bases, ok)); + } + + private Ty duckCall(Ty r, String name, List args0, boolean positional, Call kwCall, Fn fn, Scope sc) { + Ty ret = Ty.BOT; + Layouts.Cls sup = superClass; + boolean chain = sup != null && singleChain(sup); + for (Fn f : new ArrayList(p.fns.values())) { + if (f.cls == null || !f.def.name.equals(name) || r.k == Ty.K.INST + && !isSelfOrAncestor(f.cls, r.cls) && !isSelfOrAncestor(r.cls, f.cls) + && !sharedBelow(r.cls, f.cls)) { + continue; + } + if (kwCall != null && raises(kwCall, f.def, 1) && raises(kwCall, f.def, 0)) { + // These arguments bind to this method neither on an instance + // nor through its class (`K.m(obj, ...)`): the call raises + // TypeError before its body runs, so it is not a target. + continue; + } + if (duckBound != null && !duckBound.contains(f.cls.def) && !derivesFrom(f.cls, fn.cls.def) + && !sharedBelow(fn.cls, f.cls)) { + // The receiver is an instance of a class (or a subclass of + // it) whose MRO this method's class is not on. + continue; + } + if (superCall && !facts.mayBeBase(f.cls.def.name, p.reached)) { + // Nothing in the program derives from the method's class, + // so no MRO has it after another class. + continue; + } + if (sup != null && (isSelfOrAncestor(sup, f.cls) || chain && !isSelfOrAncestor(f.cls, sup))) { + // Not where super() goes: K itself or below it, or, when + // the MRO is K's parent chain, anything off that chain. + continue; + } + if (p.closed && !classLive(f.cls)) { + // No instance can be the receiver: nothing at or below the + // method's class is made. A later round that makes one + // makes this call again. + continue; + } + List args = args0; + boolean bound = positional; + if (!positional && kwCall != null && !kwCall.keywords.isEmpty()) { + // Keywords bind to this candidate's parameters by name, + // as a resolved call's do (see [#staticArgs]). + List given = staticArgs(kwCall, f.def, 1); + if (given != null) { + args = new ArrayList(); + for (Expr e : given) { + args.add(type(e, fn, sc)); + } + bound = true; + } + } + int np = f.def.args.positional.size(); + if (slotDuck && r.wide()) { + // A closed-name call types its value from its targets, so + // the receiver being the class itself counts too: + // `K.m(obj, ...)` passes `obj` as self. + unboundCall(f, args0, positional, kwCall, fn, sc); + ret = mix(ret, retOf(f, f.ret)); + } + if (positional && f.def.args.vararg == null + && (args.size() + 1 > np || args.size() + 1 < np - f.def.args.defaults.size())) { + // These arguments cannot bind to this method: a call of it + // raises before its body runs, so it is not what the call + // reaches. + continue; + } + // A receiver of no one type is any object, called through the + // method's virtual slot (TypedEmit `tv_`), whose default runs the + // generic lookup, and the method's guard picks the version that + // runs. Every method of the name is a target. An argument is + // evidence for a parameter nothing else says anything of; one + // that would widen what the parameter already holds is not -- + // the guard sends a call it does not fit to the generic body, + // where joining it in untyped the method for every caller. + if (r.wide() && !shadow) { + List kept = new ArrayList(args.size()); + for (int i = 0; i < args.size(); i++) { + Ty a = args.get(i); + Ty prm = i + 1 < f.params.length ? f.params[i + 1] : null; + if (prm == null || prm.k == Ty.K.BOT || prm.unseen() || Ty.join(prm, a).equals(prm)) { + kept.add(a); + } else { + // Not followed into this method: it reaches it as + // any object, and is entered from there. + escape(a); + kept.add(Ty.UNSEEN); + } + } + args = kept; + } + callFn(f, args, 1, bound && binds(f, args.size() + 1), true); + ret = mix(ret, retOf(f, f.ret)); + } + return ret; + } + + /// Set while [#duckCall] types a closed-name call ([#closedName]). + private boolean slotDuck; + + /// `f` called through its class, the arguments from its first + /// parameter on, when they can bind there. + private void unboundCall(Fn f, List args0, boolean positional, Call kwCall, Fn fn, Scope sc) { + List args = args0; + boolean bound = positional; + if (!positional && kwCall != null && !kwCall.keywords.isEmpty()) { + List given = staticArgs(kwCall, f.def, 0); + if (given == null) { + callFn(f, args, 0, false, true); + return; + } + args = new ArrayList(); + for (Expr e : given) { + args.add(type(e, fn, sc)); + } + bound = true; + } + int np = f.def.args.positional.size(); + if (positional && f.def.args.vararg == null + && (args.size() > np || args.size() < np - f.def.args.defaults.size())) { + return; + } + callFn(f, args, 0, bound && binds(f, args.size()), true); + } + + /// The methods of the names [#escapeMethods] let go whose class has + /// become live since: each escapes as the others did. + private void deadMethods() { + for (Fn f : new ArrayList(p.fns.values())) { + if (f.cls != null && !f.escapes && p.escapedNames.contains(f.def.name) && classLive(f.cls)) { + p.fnHome.get(f).escapeFn(f); + } + } + } + + /// `Base.m(self, ...)` in a method of class `C` that names `Base` as + /// one of its bases, the class not known here (defusedxml's + /// `_XMLParser.__init__(self, ...)`, `_XMLParser` taken from a module + /// imported by a computed name): `m` is found in `C`'s ancestors, never + /// in another class. Each compiled one in the chain is followed as an + /// unbound call, and when the method is past what the build knows of + /// the chain, the arguments go there and nothing else does -- that + /// method is entered through its guard like any call the pass does not + /// follow. As a duck call, every `__init__` of the program escaped. + /// Null when the call is not of that shape. + private Ty baseCall(Call c, Attribute a, List args, Fn fn, Scope sc) { + if (fn == null || !(a.value instanceof Name) || c.args.isEmpty() || anyStarred(c.args) + || !(c.args.get(0) instanceof Name) || fn.def.args.positional.isEmpty() + || !((Name) c.args.get(0)).id.equals(fn.def.args.positional.get(0).name) + || !fn.def.decorators.isEmpty() || shadow) { + return null; + } + String base = ((Name) a.value).id; + if (sc.resolve(base) != Scope.Binding.GLOBAL || globalClasses.containsKey(base)) { + return null; + } + Ty bt = type(a.value, fn, sc); + if (!(bt.wide() || bt.k == Ty.K.CLS && bt.sites.length == 0)) { + // A class the pass knows: its method is followed as it is. + return null; + } + ClassDef owner = enclosingClass(fn.def); + if (owner == null || !owner.decorators.isEmpty() || !owner.keywords.isEmpty()) { + return null; + } + boolean named = false; + for (Expr e : owner.bases) { + named |= e instanceof Name && base.equals(((Name) e).id); + } + if (!named || owner.bases.size() != 1 || Layouts.bodyBindings(owner).contains(base)) { + return null; + } + // The first argument is the receiver of the method being walked, + // never rebound in it. + if (fn.def.scope.assigned.contains(((Name) c.args.get(0)).id)) { + return null; + } + for (Keyword kw : c.keywords) { + escape(type(kw.value, fn, sc)); + } + for (Ty t : args) { + escape(t); + } + return "__init__".equals(a.attr) ? Ty.NONE : Ty.OBJECT; + } + + /// The class whose body defines method `d` at module level, or null. + private ClassDef enclosingClass(FunctionDef d) { + for (Stmt s : body) { + if (s instanceof ClassDef) { + for (Stmt m : ((ClassDef) s).body) { + if (m == d) { //NOPMD CompareObjectsWithEquals - identity is meant + return (ClassDef) s; + } + } + } + } + return null; + } + + /// Every compiled method `name` may be reached with arguments the pass + /// cannot type. + private void escapeMethods(String name) { + for (Fn f : p.methodsNamed(name)) { + if (!p.closed || classLive(f.cls)) { + escapeFn(f); + } + } + if (p.closed) { + // A method of a class nothing makes yet escapes once something + // does (see [#deadMethods]). + p.escapedNames.add(name); + } + } + + /// Set once the fixpoint holds: the emitters then only read the result. + /// An escape from a read of theirs would change types the pass already + /// handed out, after the code using them was decided. + Ty elem(Ty list) { + return loc(elem0(list)); + } + + private Ty elem0(Ty list) { + if (list.k != Ty.K.LIST || list.sites.length == 0) { + return Ty.UNSEEN; + } + Ty r = Ty.BOT; + // A list generic code may have filled holds what typed code put in + // it as a guess: the rest replace it (see [#siteJoin]). + boolean g = p.allListsEscape; + for (int s : list.sites) { + Integer key = Integer.valueOf(s); + g |= escapedSites.contains(key) || p.guessedSites.contains(key); + r = mix(r, siteElem.get(s)); + } + r = loc(r); + if (g) { + r = guessRead(r); + } + if (r.wide() && !p.done) { + // A display's mixed positions read as one dynamic element: what + // they hold is no longer followed. + for (int s : list.sites) { + Ty[] sl = siteSlots.get(Integer.valueOf(s)); + if (sl != null) { + for (Ty x : sl) { + escape(x); + } + } + // And what the elements were joined to: the read hands it + // out untyped, where a call of it is not seen (dateutil's + // `MO, TU, ... = [weekday(i) ...]` called `MO(+2)`). + Ty e = siteElem.get(s); + if (e != null && !e.wide()) { + escape(e); + } + } + } + return r; + } + + /// `d[k] = v` on a dict of these sites. + private void storeDict(Ty d, Ty k0, Ty v0) { + Ty k = noMeth(k0); + Ty v = noMeth(v0); + if (d.sites.length == 0) { + escape(d); + escape(k); + escape(v); + return; + } + for (int s : d.sites) { + siteKey.set(s, joinInto(siteKey.get(s), k)); + siteJoin(s, v); + } + } + + /// What a read of a dict of these sites answers. + Ty dictVal(Ty d) { + return loc(dictVal0(d)); + } + + private Ty dictVal0(Ty d) { + if (d.k != Ty.K.DICT || d.sites.length == 0) { + return Ty.UNSEEN; + } + Ty r = Ty.BOT; + boolean g = p.allListsEscape; + for (int s : d.sites) { + Integer key = Integer.valueOf(s); + g |= escapedSites.contains(key) || p.guessedSites.contains(key); + r = mix(r, siteElem.get(s)); + } + r = loc(r); + if (g && exactRead(r, d.sites) && !guessedAny(d.sites)) { + // (A guessed dict may be any dict: what was seen stored into + // this one is no answer for its elements. inspect's + // `ann = getattr(f, "__annotations__", {}) or {}` is a guess + // of the literal's dict, and `ann.get(n, _empty)` typed every + // annotation `_empty`.) + return r; + } + return g ? guessRead(r) : r; + } + + /// What a read of the keys of a dict of these sites answers. + Ty dictKeyOf(Ty d) { + if (d.k != Ty.K.DICT || d.sites.length == 0) { + return Ty.UNSEEN; + } + Ty r = Ty.BOT; + for (int s : d.sites) { + r = mix(r, siteKey.get(s)); + } + return loc(r); + } + + /// The builtin type a call of the builtin `n` makes, when it is a type + /// whose instances the pass has no richer kind for; null otherwise. + static String madeBuiltin(String n) { + if ("set".equals(n) || "frozenset".equals(n) || "object".equals(n) || "bytearray".equals(n) + || "range".equals(n) || "slice".equals(n) || "property".equals(n) || "staticmethod".equals(n) + || "classmethod".equals(n)) { + return n; + } + return n.endsWith("Error") || n.endsWith("Exception") || n.endsWith("Warning") || "StopIteration".equals(n) + || "KeyboardInterrupt".equals(n) || "SystemExit".equals(n) || "GeneratorExit".equals(n) + || "StopAsyncIteration".equals(n) ? n : null; + } + + /// A key a dict only looks up: hashed and compared, never kept. A + /// compiled class compares and hashes as `type` does, by identity (its + /// metaclass is `type` or one without comparisons, see + /// Layouts#plainMetaclass), so it goes nowhere; anything else may run + /// its own `__eq__` or `__hash__`. bs4's + /// `self.element_classes.get(Tag, Tag)` let `Tag` be constructed from + /// anywhere, and every subclass -- `BeautifulSoup` among them -- went + /// loose with it. + private void lookupKey(Ty k) { + if (k.k == Ty.K.CLS && !k.opt && k.sites.length > 0) { + return; + } + escape(k); + } + + /// The dict methods that keep the values followed, or null for any + /// other, which lets the dict go. + private Ty dictMethod(Ty d, String m, List args) { + switch (m) { + case "get": + if (args.size() == 1 || args.size() == 2) { + lookupKey(args.get(0)); + Ty dflt = args.size() == 2 ? args.get(1) : Ty.NONE; + Ty r = mix(dictVal(d), dflt); + if (r.wide()) { + escape(dflt); + } + return r; + } + return null; + case "setdefault": + if (args.size() == 2) { + storeDict(d, args.get(0), args.get(1)); + return dictVal(d); + } + return null; + default: + return null; + } + } + + /// Joins `v` into what the elements of `site` hold. A value nothing + /// knows, or one a generic body puts there, does not widen them: it + /// makes their reads guesses (see [Program#guessedSites]). + private void siteJoin(int site, Ty v0) { + Ty v = callableSet(v0) ? v0 : noMeth(v0); + // The generic view (shadow) stores what it still knows like any + // other code: those are values the container really gets. + if (v.wide() && !callableSet(v) || guessSeen) { + if (p.guessedSites.add(Integer.valueOf(site))) { + p.changed = true; + } + if (v.wide() && !callableSet(v)) { + // Not kept: a function it may be is entered from where the + // pass no longer follows it. + if (p.lostSites.add(Integer.valueOf(site))) { + p.changed = true; + } + escapeFuncs(v); + // What it held before is read through the lost site too, + // and called from where the pass no longer follows it. + Ty had = siteElem.get(site); + if (had != null) { + escapeFuncs(had); + } + return; + } + } + siteElem.set(site, joinInto(siteElem.get(site), v)); + } + + /// Whether a guessed container read may answer what its sites hold, as + /// it is: no store into them was lost, and what they hold so far is + /// nothing, None, or functions a call through it is followed to -- + /// none of which typed code keeps in a slot of its own. Answering OBJECT + /// for it in an early round would stick for good. + private boolean exactRead(Ty t, int[] sites) { + if (p.done || p.allListsEscape || t == null || anyLost(sites)) { + return false; + } + return t.k == Ty.K.BOT || t.k == Ty.K.NONE || callableSet(t); + } + + private boolean guessedAny(int[] sites) { + for (int s : sites) { + if (p.guessedSites.contains(Integer.valueOf(s))) { + return true; + } + } + return false; + } + + private boolean anyLost(int[] sites) { + for (int s : sites) { + Integer k = Integer.valueOf(s); + if (p.lostSites.contains(k) || escapedSites.contains(k)) { + return true; + } + } + return false; + } + + private void storeElem(Ty list, Ty v) { + if (list.k != Ty.K.LIST || list.sites.length == 0) { + escape(v); + return; + } + unslot(list); + for (int s : list.sites) { + siteJoin(s, v); + } + } + + /// The list may since have been reordered or resized: its positions no + /// longer say what is where. + private void unslot(Ty list) { + if (list.k != Ty.K.LIST) { + return; + } + for (int s : list.sites) { + if (unslotted.add(Integer.valueOf(s))) { + p.changed = true; + } + } + } + + /// A display's position `i` takes `v`. + private void joinSlot(int site, int n, int i, Ty v0, boolean tuple) { + Ty v = noMeth(v0); + Integer key = Integer.valueOf(site); + Ty[] sl = siteSlots.get(key); + if (sl == null || sl.length != n) { + if (sl != null) { + unslotted.add(key); + } + sl = new Ty[n]; + java.util.Arrays.fill(sl, Ty.BOT); + siteSlots.put(key, sl); + } + Ty r = mix(sl[i], v); + if (!r.equals(sl[i])) { + sl[i] = r; + p.changed = true; + } + if (tuple ? escapedSites.contains(key) : r.k != Ty.K.LIST && r.k != Ty.K.TUPLE) { + escape(v); + } + } + + /// What position `i` of a tuple or list holds; for a list whose + /// positions are not known, its elements. + Ty slot(Ty t, int i) { + if (t.k == Ty.K.LIST && slotCount(t) <= i) { + return elem(t); + } + if (t.k != Ty.K.TUPLE && t.k != Ty.K.LIST || t.sites.length == 0 || i < 0) { + return Ty.UNSEEN; + } + Ty r = Ty.BOT; + for (int s : t.sites) { + Ty[] sl = siteSlots.get(Integer.valueOf(s)); + if (sl == null || i >= sl.length) { + return t.k == Ty.K.LIST ? elem(t) : Ty.UNSEEN; + } + r = mix(r, sl[i]); + } + return siteRead(loc(r), t.sites); + } + + /// How many positions every site of `t` has, when they agree and are + /// known; otherwise -1. + int slotCount(Ty t) { + if (t.k != Ty.K.TUPLE && t.k != Ty.K.LIST || t.sites.length == 0 + || t.k == Ty.K.LIST && p.allListsEscape) { + return -1; + } + int n = -1; + for (int s : t.sites) { + Integer key = Integer.valueOf(s); + Ty[] sl = siteSlots.get(key); + if (sl == null || t.k == Ty.K.LIST && (unslotted.contains(key) || escapedSites.contains(key)) + || n >= 0 && n != sl.length) { + return -1; + } + n = sl.length; + } + return n; + } + + /// Every position of a tuple, joined: what iterating it or a variable + /// index yields. + Ty tupleElem(Ty t) { + int n = slotCount(t); + if (n < 0) { + return Ty.UNSEEN; + } + Ty r = Ty.BOT; + for (int i = 0; i < n; i++) { + r = mix(r, slot(t, i)); + } + return r; + } + + private int site(Expr e) { + // A generic version's own private list is a different object at + // run time from the typed version's, and no typed code ever reads + // it: what the generic walk puts in it stays out of the typed one. + Map of = shadow && privateLiterals().contains(e) ? p.shadowSiteOf : siteOf; + Integer s = of.get(e); + if (s == null) { + s = Integer.valueOf(siteElem.size()); + siteElem.add(Ty.BOT); + siteKey.add(Ty.BOT); + of.put(e, s); + } + return s.intValue(); + } + + /// The list literals assigned to a local the function uses only + /// through the list's own methods, `len`, a truth test or a `for` -- + /// none of which hands the list itself to other code -- and the tuple + /// literals put into those lists, over every function. + private Set privateLiterals() { + if (p.privateLits == null) { + Set out = java.util.Collections.newSetFromMap(new IdentityHashMap()); + for (FunctionDef d : p.fns.keySet()) { + Set names = new HashSet(); + for (Stmt s : d.body) { + listAssigns(s, names); + } + for (String n : names) { + boolean[] ok = {true}; + List lits = new ArrayList(); + for (Stmt s : d.body) { + privateUse(s, n, ok, lits); + } + if (ok[0]) { + out.addAll(lits); + } + } + } + p.privateLits = out; + } + return p.privateLits; + } + + private static void listAssigns(Object o, Set names) { + if (o instanceof FunctionDef || o instanceof ClassDef || o instanceof Lambda) { + return; + } + if (o instanceof Assign && ((Assign) o).targets.size() == 1 && ((Assign) o).targets.get(0) instanceof Name + && ((Assign) o).value instanceof ListExpr) { + names.add(((Name) ((Assign) o).targets.get(0)).id); + } else if (o instanceof AnnAssign && ((AnnAssign) o).target instanceof Name + && ((AnnAssign) o).value instanceof ListExpr) { + names.add(((Name) ((AnnAssign) o).target).id); + } + Infer.children(o, x -> listAssigns(x, names)); + } + + /// The list methods that neither return the list nor a new list of + /// its elements. + private static final Set PRIVATE_LIST_METHODS = new HashSet(java.util.Arrays.asList( + "append", "extend", "pop", "insert", "clear", "reverse", "remove", "index", "count")); + + private static void privateUse(Object o, String n, boolean[] ok, List lits) { + if (!ok[0]) { + return; + } + if (o instanceof FunctionDef || o instanceof ClassDef || o instanceof Lambda) { + // A nested scope sees the list too: give up on it. + boolean[] seen = {false}; + mentions(o, n, seen); + ok[0] &= !seen[0]; + return; + } + Expr made = o instanceof Assign && ((Assign) o).targets.size() == 1 && ((Assign) o).targets.get(0) instanceof Name + && n.equals(((Name) ((Assign) o).targets.get(0)).id) ? ((Assign) o).value + : o instanceof AnnAssign && ((AnnAssign) o).target instanceof Name + && n.equals(((Name) ((AnnAssign) o).target).id) ? ((AnnAssign) o).value : null; + if (made != null || o instanceof AnnAssign && ((AnnAssign) o).target instanceof Name + && n.equals(((Name) ((AnnAssign) o).target).id)) { + if (!(made instanceof ListExpr)) { + ok[0] = false; + return; + } + lits.add(made); + for (Expr x : ((ListExpr) made).elts) { + if (x instanceof TupleExpr) { + lits.add(x); + } + } + privateUse(made, n, ok, lits); + return; + } + if (o instanceof Call && ((Call) o).func instanceof Attribute + && ((Attribute) ((Call) o).func).value instanceof Name + && n.equals(((Name) ((Attribute) ((Call) o).func).value).id)) { + String m = ((Attribute) ((Call) o).func).attr; + if (!PRIVATE_LIST_METHODS.contains(m)) { + ok[0] = false; + return; + } + for (Expr a : ((Call) o).args) { + if (("append".equals(m) || "insert".equals(m)) && a instanceof TupleExpr) { + lits.add(a); + } else if ("extend".equals(m) && a instanceof Comp && ((Comp) a).kind == Comp.Kind.GENERATOR + && ((Comp) a).elt instanceof TupleExpr) { + lits.add(((Comp) a).elt); + } + privateUse(a, n, ok, lits); + } + for (Keyword k : ((Call) o).keywords) { + privateUse(k.value, n, ok, lits); + } + return; + } + if (o instanceof Call && ((Call) o).func instanceof Name && "len".equals(((Name) ((Call) o).func).id) + && ((Call) o).args.size() == 1 && ((Call) o).args.get(0) instanceof Name + && n.equals(((Name) ((Call) o).args.get(0)).id)) { + return; + } + if ((o instanceof While || o instanceof If) && (o instanceof While ? ((While) o).test : ((If) o).test) instanceof Name + && n.equals(((Name) (o instanceof While ? ((While) o).test : ((If) o).test)).id)) { + for (Stmt s : o instanceof While ? ((While) o).body : ((If) o).body) { + privateUse(s, n, ok, lits); + } + for (Stmt s : o instanceof While ? ((While) o).orelse : ((If) o).orelse) { + privateUse(s, n, ok, lits); + } + return; + } + if (o instanceof For && ((For) o).iter instanceof Name && n.equals(((Name) ((For) o).iter).id)) { + privateUse(((For) o).target, n, ok, lits); + for (Stmt s : ((For) o).body) { + privateUse(s, n, ok, lits); + } + for (Stmt s : ((For) o).orelse) { + privateUse(s, n, ok, lits); + } + return; + } + if (o instanceof Name && n.equals(((Name) o).id)) { + // The list itself, handed on or rebound. + ok[0] = false; + return; + } + Infer.children(o, x -> privateUse(x, n, ok, lits)); + } + + private void unify() { + // Methods of one name and arity are called through one virtual + // signature (TypedEmit), so they share their parameter types. + Map> groups = new LinkedHashMap>(); + for (Fn f : fns.values()) { + if (f.cls != null && !f.def.name.equals("__init__")) { + String key = f.def.name + "/" + f.params.length; + List g = groups.get(key); + if (g == null) { + g = new ArrayList(); + groups.put(key, g); + } + g.add(f); + } + } + for (List g : groups.values()) { + if (g.size() < 2) { + continue; + } + int n = g.get(0).params.length; + for (int i = 1; i < n; i++) { + Ty j = Ty.BOT; + for (Fn f : g) { + j = mix(j, f.params[i]); + } + for (Fn f : g) { + f.params[i] = joinInto(f.params[i], j); + } + } + Ty r = Ty.BOT; + boolean guess = false; + for (Fn f : g) { + r = mix(r, f.ret); + guess |= p.guessedReturns.contains(f); + } + for (Fn f : g) { + f.ret = joinInto(f.ret, r); + // One way of returning for the group: a virtual call + // reads each the same. + if (guess && p.guessedReturns.add(f)) { + p.changed = true; + } + } + } + } + + // ---- walking --------------------------------------------------------- + + /// `fn` is the compiled function being walked, or null where names are + /// not tracked (the module body tracks globals instead). + private void walkBlock(List body, Fn fn, Scope sc) { + Map, Ty> saved = null; + try { + for (int i = 0; i < body.size(); i++) { + Stmt s = body.get(i); + walk(s, fn, sc); + // `if not isinstance(x, K): raise ...` -- below, x is a K. + if (s instanceof If && ((If) s).orelse.isEmpty() && endsAbruptly(((If) s).body)) { + Map.Entry t = isinstanceTest(((If) s).test, true, fn, sc); + if (t != null && !storesIn(body.subList(i + 1, body.size()), t.getKey())) { + if (saved == null) { + saved = new HashMap, Ty>(narrowing); + } + narrowing.put(nk(sc, t.getKey()), t.getValue()); + } + } + } + } finally { + if (saved != null) { + narrowing.clear(); + narrowing.putAll(saved); + } + } + } + + /// Walks `body`, the branch of `test` taken when it holds (fails, when + /// `negated`), with what the test proves of a local in force. + private void narrowed(Expr test, boolean negated, List body, Fn fn, Scope sc) { + List> ts = new ArrayList>(); + if (!negated && test instanceof BoolOp && ((BoolOp) test).isAnd) { + for (Expr v : ((BoolOp) test).values) { + Map.Entry t = isinstanceTest(v, false, fn, sc); + if (t != null) { + ts.add(t); + } + } + } else { + Map.Entry t = isinstanceTest(test, negated, fn, sc); + if (t != null) { + ts.add(t); + } + } + Map, Ty> saved = new HashMap, Ty>(narrowing); + try { + for (Map.Entry t : ts) { + if (!storesIn(body, t.getKey())) { + narrowing.put(nk(sc, t.getKey()), t.getValue()); + } + } + walkBlock(body, fn, sc); + } finally { + narrowing.clear(); + narrowing.putAll(saved); + } + } + + /// The local names narrowed by an enclosing `isinstance` test, and to + /// what ([#isinstanceTest]); only while their region is walked. + private final Map, Ty> narrowing = new HashMap, Ty>(); + + private static Map.Entry nk(Scope sc, String n) { + return new java.util.AbstractMap.SimpleImmutableEntry(sc, n); + } + /// Each read of a narrowed name and the type it has there, kept for + /// the emitters, which read types after the walk. + final Map narrowedAt = new IdentityHashMap(); + + /// For `isinstance(x, K)` (or, with `negated`, `not isinstance(x, K)`) + /// on a plain local x of this function: x and what it is when the + /// test holds (fails, when negated). K must be compiled classes, or a + /// builtin that x holds among values of no compiled class -- a str + /// subclass instance is a str, but not a Java String. Null otherwise. + private Map.Entry isinstanceTest(Expr test, boolean negated, Fn fn, Scope sc) { + if (negated) { + if (!(test instanceof UnaryOp) || !"not".equals(((UnaryOp) test).op)) { + return failedIsinstance(test, fn, sc); + } + test = ((UnaryOp) test).operand; + } + if (fn == null || sc != fn.def.scope || !(test instanceof Call)) { //NOPMD CompareObjectsWithEquals - identity is meant + return null; + } + Call c = (Call) test; + if (!isName(c.func, "isinstance") || sc.resolve("isinstance") == Scope.Binding.LOCAL + || moduleScope.assigned.contains("isinstance") || c.args.size() != 2 || !c.keywords.isEmpty() + || !(c.args.get(0) instanceof Name)) { + return null; + } + String x = ((Name) c.args.get(0)).id; + if (sc.resolve(x) != Scope.Binding.LOCAL || fn.openSelf && fn.names.get(0).equals(x)) { + return null; + } + Ty k = type(c.args.get(1), fn, sc); + if (k.k == Ty.K.CLS && !k.opt && k.sites.length > 0) { + Ty r = Ty.BOT; + for (Layouts.Cls o : classesOf(k)) { + if (!layoutHolds(o)) { + // An instance the test passes may not be of o's Java + // class: held as it was. + return null; + } + r = Ty.join(r, Ty.inst(o, false)); + } + if (r.k == Ty.K.INST) { + tested(fn, x, r); + } + // A class with no Java layout is held as a plain object. + return r.k == Ty.K.INST && r.cls.compiled ? new java.util.AbstractMap.SimpleImmutableEntry(x, r) : null; + } + Ty cur = fn.locals.get(x); + if (cur == null) { + int pi = fn.names.indexOf(x); + cur = pi >= 0 && pi < fn.params.length ? fn.params[pi] : null; + } + if (cur == null || cur.k == Ty.K.OBJECT || !(c.args.get(1) instanceof Name) + || sc.resolve(((Name) c.args.get(1)).id) != Scope.Binding.GLOBAL + || moduleScope.assigned.contains(((Name) c.args.get(1)).id)) { + return null; + } + String bn = ((Name) c.args.get(1)).id; + Ty hit = null; + for (Ty m : cur.members()) { + if (m.k == Ty.K.INST || m.k == Ty.K.OBJECT) { + return null; + } + if ("str".equals(bn) && m.k == Ty.K.STR || "list".equals(bn) && m.k == Ty.K.LIST) { + hit = m.nonNone(); + } + } + return hit == null ? null : new java.util.AbstractMap.SimpleImmutableEntry(x, hit); + } + + /// Where `isinstance(x, K)` failed, x a plain local of compiled class C: + /// x is of a live class at or below C and not at or below K, so it is + /// the join of those -- the program is closed, every class is known. + /// markdownify's `process_element` hands the `else` of + /// `isinstance(node, NavigableString)` to `process_tag`, which then + /// reads a `Tag`, not a `PageElement` that has no `children`. Null when + /// that is no narrower than C, or a class involved has no Java layout. + private Map.Entry failedIsinstance(Expr test, Fn fn, Scope sc) { + if (fn == null || sc != fn.def.scope || !(test instanceof Call)) { //NOPMD CompareObjectsWithEquals - identity is meant + return null; + } + Call c = (Call) test; + if (!isName(c.func, "isinstance") || sc.resolve("isinstance") == Scope.Binding.LOCAL + || moduleScope.assigned.contains("isinstance") || c.args.size() != 2 || !c.keywords.isEmpty() + || !(c.args.get(0) instanceof Name)) { + return null; + } + String x = ((Name) c.args.get(0)).id; + if (sc.resolve(x) != Scope.Binding.LOCAL || fn.openSelf && fn.names.get(0).equals(x)) { + return null; + } + Ty cur = fn.locals.get(x); + if (cur == null) { + int pi = fn.names.indexOf(x); + cur = pi >= 0 && pi < fn.params.length ? fn.params[pi] : null; + } + if (cur != null && cur.k != Ty.K.INST && cur.k != Ty.K.OBJECT && cur.k != Ty.K.BOT) { + return failedBuiltin(x, cur, c.args.get(1), sc); + } + if (cur == null || cur.k != Ty.K.INST || !cur.cls.compiled) { + return null; + } + Ty k = type(c.args.get(1), fn, sc); + if (k.k != Ty.K.CLS || k.opt || k.sites.length == 0) { + return null; + } + Set out = java.util.Collections.newSetFromMap(new IdentityHashMap()); + for (Layouts.Cls o : classesOf(k)) { + // Only what is left is read as a Java class: the classes the + // test passes need no layout of their own. + out.add(o); + out.addAll(p.below(o)); + } + List all = new ArrayList(); + all.add(cur.cls); + all.addAll(p.below(cur.cls)); + Ty r = Ty.BOT; + for (Layouts.Cls o : all) { + if (out.contains(o) || !exactLive(o)) { + continue; + } + if (!layoutHolds(o)) { + return null; + } + r = Ty.join(r, Ty.inst(o, false)); + } + if (r.k == Ty.K.BOT && !cur.opt && !p.done) { + // No live class gets there yet: what reaches it so far is no + // evidence for what it is passed. Otherwise the first pass's + // guess sticks -- markdownify's children read as Comment, + // process_tag widened to PageElement, whose `children` resolves + // to nothing, and nothing ever grows past it. + return new java.util.AbstractMap.SimpleImmutableEntry(x, Ty.BOT); + } + if (r.k != Ty.K.INST || r.cls == cur.cls || !r.cls.compiled) { //NOPMD CompareObjectsWithEquals - identity is meant + return null; + } + return new java.util.AbstractMap.SimpleImmutableEntry(x, cur.opt ? Ty.inst(r.cls, true) : r); + } + + /// [#failedIsinstance] for a local of builtin kinds and a test naming + /// builtin types: what is left are the members the test does not + /// match -- a Java String is always a str, a PyList a list. With none + /// left, nothing typed reaches the `else` yet. itsdangerous's + /// `_secret_keys` iterated its key after `isinstance(secret_key, (str, + /// bytes))` returned, and an early pass's str yielded the str that + /// typed every later key, bytes included. + private Map.Entry failedBuiltin(String x, Ty cur, Expr kinds, Scope sc) { + Set hit = java.util.EnumSet.noneOf(Ty.K.class); + for (Expr e : kinds instanceof TupleExpr ? ((TupleExpr) kinds).elts : java.util.Collections.singletonList(kinds)) { + if (!(e instanceof Name) || sc.resolve(((Name) e).id) != Scope.Binding.GLOBAL + && sc.resolve(((Name) e).id) != Scope.Binding.BUILTIN + || moduleScope.assigned.contains(((Name) e).id)) { + return null; + } + Ty.K kk = BUILTIN_KINDS.get(((Name) e).id); + if (kk != null) { + hit.add(kk); + } + } + Ty r = Ty.BOT; + for (Ty m : cur.members()) { + if (!BUILTIN_KINDS.containsValue(m.k)) { + return null; + } + if (!hit.contains(m.k)) { + r = Ty.join(r, m.nonNone()); + } + } + if (r.k == Ty.K.BOT) { + return cur.opt || p.done ? null : new java.util.AbstractMap.SimpleImmutableEntry(x, Ty.BOT); + } + if (cur.opt) { + r = r.orNone(); + } + return r.equals(cur) ? null : new java.util.AbstractMap.SimpleImmutableEntry(x, r); + } + + /// The builtin types whose every instance is held as one Java kind; + /// int and bool are not among them (a bool is an int). + private static final Map BUILTIN_KINDS = new HashMap(); + + static { + BUILTIN_KINDS.put("str", Ty.K.STR); + BUILTIN_KINDS.put("bytes", Ty.K.BYTES); + BUILTIN_KINDS.put("list", Ty.K.LIST); + BUILTIN_KINDS.put("tuple", Ty.K.TUPLE); + BUILTIN_KINDS.put("dict", Ty.K.DICT); + } + + /// `isinstance(x, K)` is evidence about `x` as much as a store is: the + /// code expects a K there, from callers or sources the pass may not + /// see, so K joins the parameter's or local's type. + private void tested(Fn fn, String x, Ty k) { + int pi = fn.names.indexOf(x); + if (pi >= 0 && pi < fn.params.length) { + if (!fn.params[pi].unseen() && fn.params[pi].k != Ty.K.BOT) { + fn.params[pi] = joinInto(fn.params[pi], k); + } + } else { + Ty cur = fn.locals.get(x); + if (cur != null && cur.k != Ty.K.BOT && !cur.unseen()) { + fn.locals.put(x, joinInto(cur, k)); + } + } + } + + private static boolean storesIn(List body, String n) { + List out = new ArrayList(); + for (Stmt s : body) { + boundIn(s, out); + if (deletes(s, n)) { + return true; + } + } + return out.contains(n); + } + + private static boolean deletes(Object o, String n) { + if (o instanceof Delete) { + for (Expr t : ((Delete) o).targets) { + if (t instanceof Name && ((Name) t).id.equals(n)) { + return true; + } + } + } + boolean[] r = {false}; + children(o, x -> r[0] |= deletes(x, n)); + return r[0]; + } + + private void walk(Stmt s, Fn fn, Scope sc) { + line = s.line; + // What a statement stores is a guess only by what it read itself. + guessSeen = false; + if (s instanceof ExprStmt) { + type(((ExprStmt) s).value, fn, sc); + } else if (s instanceof Assign) { + Assign a = (Assign) s; + Ty v = type(a.value, fn, sc); + for (Expr t : a.targets) { + store(t, v, a.value, fn, sc); + } + } else if (s instanceof AnnAssign) { + AnnAssign a = (AnnAssign) s; + if (a.value != null) { + store(a.target, type(a.value, fn, sc), a.value, fn, sc); + } else if (!(a.target instanceof Name)) { + type(a.target, fn, sc); + } + } else if (s instanceof AugAssign) { + AugAssign a = (AugAssign) s; + Ty cur = type(a.target, fn, sc); + Ty v = type(a.value, fn, sc); + // As for a plain operator: an operand nothing reaches yet leaves + // the result to a later pass, where OBJECT now would stay for good. + Ty r = v.k == Ty.K.BOT || cur.k == Ty.K.BOT && !(a.target instanceof Name) ? Ty.BOT + : binop(a.op, cur, v, a.value); + if (cur.k == Ty.K.LIST && "+".equals(a.op)) { + storeElem(cur, elem(v)); + r = cur; + } + store(a.target, r, null, fn, sc); + } else if (s instanceof Return) { + Return r = (Return) s; + Ty v = r.value == null ? Ty.NONE : type(r.value, fn, sc); + if (fn != null && sc == fn.def.scope) { //NOPMD CompareObjectsWithEquals - identity is meant + Ty ge = !(r.value instanceof Comp) ? null : shadow ? Ty.OBJECT : genElems.get(r.value); + if (ge != null) { + yieldInto(fn, ge); + } + fn.ret = joinInto(fn.ret, v); + if (guessSeen && !shadow && p.guessedReturns.add(fn)) { + p.changed = true; + } + } else { + escape(v); + } + } else if (s instanceof If) { + If i = (If) s; + type(i.test, fn, sc); + boolean typeOnly = typeChecking(i.test); + if (typeOnly) { + // Imports for annotations only: they never run, so they + // keep no module live. The block is still typed. + typeCheckingDepth++; + } + try { + narrowed(i.test, false, i.body, fn, sc); + } finally { + if (typeOnly) { + typeCheckingDepth--; + } + } + narrowed(i.test, true, i.orelse, fn, sc); + } else if (s instanceof While) { + While w = (While) s; + type(w.test, fn, sc); + walkBlock(w.body, fn, sc); + walkBlock(w.orelse, fn, sc); + } else if (s instanceof For) { + For f = (For) s; + Ty it = iterElem(f.iter, fn, sc); + // An element of an iterable nothing knows is unseen: the target + // holds what its other stores say, as a guess (see #type). + guessSeen |= it.unseen() && !shadow; + store(f.target, it, null, fn, sc); + walkBlock(f.body, fn, sc); + walkBlock(f.orelse, fn, sc); + } else if (s instanceof FunctionDef) { + FunctionDef d = (FunctionDef) s; + for (Expr e : d.decorators) { + // Called with the function, where the pass does not follow. + escape(type(e, fn, sc)); + } + for (Expr e : d.args.defaults) { + type(e, fn, sc); + } + for (Expr e : d.args.kwDefaults) { + if (e != null) { + type(e, fn, sc); + } + } + Fn inner = fns.get(d); + if (inner != null) { + // Defaults fill parameters the call leaves out. + int first = inner.params.length - d.args.defaults.size(); + for (int i = 0; i < d.args.defaults.size(); i++) { + inner.params[first + i] = joinInto(inner.params[first + i], type(d.args.defaults.get(i), fn, sc)); + } + if (!d.decorators.isEmpty() && !followedDescriptor(inner, sc) + || inner.cls == null && !globalFns.containsValue(inner) && !nested(inner)) { + escapeFn(inner); + } + if (!d.decorators.isEmpty() && followedDescriptor(inner, sc) && !p.reached.contains(d)) { + // Not escaped, but reachable as an escaped one was: a + // read or call of the name on any object may run it. + reach(inner); + } + if (inner.def.name.startsWith("__") && !"__init__".equals(inner.def.name) + && !("__call__".equals(inner.def.name) && followedCall(inner))) { + // The runtime calls these itself (an operator on an + // instance), through the door: the guard checks what + // it passes. What the body returns is still what it + // returns -- the door boxes it -- so the return keeps + // its type; forcing it to an object made every + // `__contains__`, `__getitem__` and `__eq__` caller + // untyped. + escapeFn(inner); + } + if (!p.reached.contains(d) && rooted(inner)) { + reach(inner); + } + if (p.reached.contains(d)) { + for (int i = 0; i < inner.params.length; i++) { + inner.locals.put(inner.names.get(i), mix(inner.locals.get(inner.names.get(i)), paramIn(inner, i))); + } + walkBlock(d.body, inner, d.scope); + if (!endsAbruptly(d.body)) { + inner.ret = joinInto(inner.ret, Ty.NONE); + } + if (!shadow && !nested(inner) && (entered(inner) || p.missed.containsKey(d))) { + genericView(inner); + } + } + } else { + walkBlock(d.body, null, d.scope); + } + boolean asValue = inner != null && d.decorators.isEmpty() && !p.done + && (nested(inner) || inner.cls == null && sc.kind == Scope.Kind.MODULE); + if (inner != null && fn == null && sc.kind == Scope.Kind.CLASS && !p.reached.contains(d) + && classBodyReads(sc, d.name)) { + // A name the class body itself reads back, as fractions' + // `__add__, __radd__ = _operator_fallbacks(_add, operator.add)` + // does: what it calls or passes there is not followed, so it + // escapes. + escapeFn(inner); + } + if (sc.kind == Scope.Kind.MODULE && (fns.get(d) == null || !globalFns.containsValue(inner)) + || fn != null && sc.kind != Scope.Kind.MODULE || inner != null && nested(inner)) { + storeName(d.name, asValue ? funcValue(inner) : Ty.OBJECT, fn, sc); + } + } else if (s instanceof ClassDef) { + ClassDef c = (ClassDef) s; + for (Expr b : c.bases) { + if (!(b instanceof Name && globalClasses.containsKey(((Name) b).id))) { + type(b, fn, sc); + } + } + for (Expr d : c.decorators) { + escape(type(d, fn, sc)); + } + Layouts.Cls ck = layouts.all().get(c); + if (ck != null && ck.compiled) { + for (Stmt m : c.body) { + if (m instanceof FunctionDef && layouts.receiverClass.get(m) == ck //NOPMD CompareObjectsWithEquals - identity is meant + && !((FunctionDef) m).args.names().isEmpty()) { + Scope ms = ((FunctionDef) m).scope; + String self = ((FunctionDef) m).args.names().get(0); + if (!ms.assigned.contains(self) && !ms.deleted.contains(self) && !ms.cells.contains(self)) { + p.untypedSelf.put(ms, ck); + } + } + } + } else { + for (Stmt m : c.body) { + if (m instanceof FunctionDef && plainMethod((FunctionDef) m)) { + p.plainSelf.add(((FunctionDef) m).scope); + } + } + } + if (!classBodyMentions.containsKey(c.scope)) { + Set names = new HashSet(); + for (Stmt m : c.body) { + classBodyNames(m, names); + } + classBodyMentions.put(c.scope, names); + } + walkBlock(c.body, null, c.scope); + if (sc.kind == Scope.Kind.MODULE && !globalClasses.containsKey(c.name) + || sc.kind == Scope.Kind.FUNCTION) { + // A class without a layout, or one a function makes, is a + // value like any other. + storeName(c.name, Ty.OBJECT, fn, sc); + } + } else if (s instanceof Try) { + Try t = (Try) s; + walkBlock(t.body, fn, sc); + for (ExceptHandler h : t.handlers) { + Ty ht = h.type == null ? null : type(h.type, fn, sc); + if (h.name != null) { + storeName(h.name, caught(ht), fn, sc); + } + walkBlock(h.body, fn, sc); + } + walkBlock(t.orelse, fn, sc); + walkBlock(t.finalbody, fn, sc); + } else if (s instanceof With) { + With w = (With) s; + for (WithItem i : w.items) { + type(i.context, fn, sc); + if (i.vars != null) { + store(i.vars, Ty.OBJECT, null, fn, sc); + } + } + walkBlock(w.body, fn, sc); + } else if (s instanceof Import || s instanceof ImportFrom) { + liveImports(s); + // `import m` always binds a module, and `from p import m` does + // when m is a module of the program. A package that rebinds the + // name loses nothing: a module value is only an object here. + if (s instanceof Import) { + for (Alias a : ((Import) s).names) { + String n = a.asname != null ? a.asname : a.name; + int dot = n.indexOf('.'); + storeName(dot < 0 ? n : n.substring(0, dot), Ty.obj("module"), fn, sc); + } + } else { + ImportFrom f = (ImportFrom) s; + String base = f.level == 0 ? f.module : relative(f.level, f.module); + for (Alias a : f.names) { + boolean module = base != null && p.modules.containsKey(base + "." + a.name); + storeName(a.asname != null ? a.asname : a.name, module ? Ty.obj("module") : Ty.OBJECT, fn, sc); + } + } + } else { + // Raise, Assert, Delete, Match, Global, Pass, Break, Continue: + // whatever they evaluate escapes. + anyChildren(s, fn, sc); + } + } + + private static boolean endsAbruptly(List body) { + if (body.isEmpty()) { + return false; + } + Stmt s = body.get(body.size() - 1); + if (s instanceof Return || s instanceof Raise) { + return true; + } + if (s instanceof If) { + If i = (If) s; + return endsAbruptly(i.body) && endsAbruptly(i.orelse); + } + if (s instanceof While) { + While w = (While) s; + return w.test instanceof Constant && ((Constant) w.test).kind == Constant.Kind.TRUE && !hasBreak(w.body); + } + return false; + } + + static boolean hasBreak(List body) { + for (Stmt s : body) { + if (s instanceof Break) { + return true; + } + if (s instanceof If && (hasBreak(((If) s).body) || hasBreak(((If) s).orelse))) { + return true; + } + if (s instanceof Try) { + Try t = (Try) s; + if (hasBreak(t.body) || hasBreak(t.orelse) || hasBreak(t.finalbody)) { + return true; + } + for (ExceptHandler h : t.handlers) { + if (hasBreak(h.body)) { + return true; + } + } + } + if (s instanceof With && hasBreak(((With) s).body)) { + return true; + } + } + return false; + } + + /// The type of the items `for x in it` binds. + Ty iterElem(Expr it, Fn fn, Scope sc) { + if (rangeCall(it, sc)) { + for (Expr a : ((Call) it).args) { + type(a, fn, sc); + } + return Ty.INT; + } + Ty lowered = builtinIter(it, fn, sc); + if (lowered != null) { + return lowered; + } + Ty t = type(it, fn, sc); + if (t.k == Ty.K.LIST) { + return elem(t); + } + if (t.k == Ty.K.TUPLE) { + return tupleElem(t); + } + if (t.k == Ty.K.STR && !t.opt) { + // A str yields one-character strs. + return Ty.STR; + } + if (t.k == Ty.K.BOT) { + // Nothing reaches the iterable yet; a later pass decides. + return Ty.BOT; + } + escape(t); + if (t.wide()) { + List src = iterSources(it, fn, sc); + if (src != null) { + Ty y = Ty.BOT; + for (Fn f : src) { + y = Ty.join(y, f.yields); + } + if (y.k == Ty.K.BOT) { + return Ty.BOT; + } + return guessRead(y); + } + } + return Ty.UNSEEN; + } + + /// What a sequence yields when iterated, for a list, a tuple or a str; + /// null for anything else. + private Ty seqElem(Ty t) { + if (t.opt) { + return null; + } + switch (t.k) { + case LIST: + return elem(t); + case TUPLE: + return tupleElem(t); + case STR: + return Ty.STR; + default: + return null; + } + } + + /// What a loop over `enumerate`, `zip` or `reversed` of sequences, or + /// over a dict's `keys()`, `values()` or `items()`, gets: the runtime + /// walks them as it walks the sequences, and the elements keep their + /// types. Null for any other iterable. + private Ty builtinIter(Expr it, Fn fn, Scope sc) { + if (!(it instanceof Call) || !((Call) it).keywords.isEmpty() || anyStarred(((Call) it).args)) { + return null; + } + Call c = (Call) it; + if (c.func instanceof Attribute && c.args.isEmpty()) { + String m = ((Attribute) c.func).attr; + if (!"keys".equals(m) && !"values".equals(m) && !"items".equals(m)) { + return null; + } + Expr recv = ((Attribute) c.func).value; + if (dictOwner(recv, sc) != null) { + return null; + } + Ty d = type(recv, fn, sc); + if (d.k != Ty.K.DICT || d.opt || d.sites.length == 0) { + return null; + } + if ("keys".equals(m)) { + return dictKeyOf(d); + } + if ("values".equals(m)) { + return dictVal(d); + } + int s = site(c); + joinSlot(s, 2, 0, dictKeyOf(d), true); + joinSlot(s, 2, 1, dictVal(d), true); + return Ty.tuple(new int[] {s}); + } + if (!(c.func instanceof Name) || sc.resolve(((Name) c.func).id) != Scope.Binding.BUILTIN + || moduleScope.hasStarImport) { + return null; + } + String n = ((Name) c.func).id; + List args = new ArrayList(); + for (Expr x : c.args) { + args.add(type(x, fn, sc)); + } + switch (n) { + case "reversed": + return args.size() == 1 && args.get(0).k != Ty.K.STR ? seqElem(args.get(0)) : null; + case "enumerate": { + if (args.isEmpty() || args.size() > 2 || args.size() == 2 && !numeric(args.get(1))) { + return null; + } + Ty e = seqElem(args.get(0)); + if (e == null) { + return null; + } + int s = site(c); + joinSlot(s, 2, 0, Ty.INT, true); + joinSlot(s, 2, 1, e, true); + return Ty.tuple(new int[] {s}); + } + case "zip": { + if (args.isEmpty()) { + return null; + } + Ty[] es = new Ty[args.size()]; + for (int i = 0; i < es.length; i++) { + es[i] = seqElem(args.get(i)); + if (es[i] == null) { + return null; + } + } + int s = site(c); + for (int i = 0; i < es.length; i++) { + joinSlot(s, es.length, i, es[i], true); + } + return Ty.tuple(new int[] {s}); + } + default: + return null; + } + } + + boolean rangeCall(Expr e, Scope sc) { + if (!(e instanceof Call)) { + return false; + } + Call c = (Call) e; + return c.func instanceof Name && "range".equals(((Name) c.func).id) && c.keywords.isEmpty() + && c.args.size() >= 1 && c.args.size() <= 3 && sc.resolve("range") == Scope.Binding.BUILTIN + && !moduleScope.hasStarImport && !anyStarred(c.args); + } + + /// A literal int index (`x[2]`, `x[-1]`) as an int; Integer.MIN_VALUE + /// for anything else. + static int constIndex(Expr e) { + boolean neg = false; + if (e instanceof UnaryOp && "-".equals(((UnaryOp) e).op)) { + neg = true; + e = ((UnaryOp) e).operand; + } + if (!(e instanceof Constant) || ((Constant) e).kind != Constant.Kind.INT) { + return Integer.MIN_VALUE; + } + String t = ((Constant) e).text.replace("_", ""); + if (t.length() > 6 || !t.matches("[0-9]+")) { + return Integer.MIN_VALUE; + } + int v = Integer.parseInt(t); + return neg ? -v : v; + } + + /// The type an argument of a call passes on: a starred one is spread + /// into parameters the pass cannot match, so OBJECT -- but its value is + /// still walked and escaped. Answering OBJECT without walking it left + /// every call inside unreached, and the dead-code pass dropped a method + /// whose only caller was `f(*self.m(...))` (SQLAlchemy's + /// `Session._pk_where`); and its elements reach a callee that sees them + /// as OBJECT, which may store into them. + private Ty starArg(Expr x, Fn fn, Scope sc) { + if (x instanceof Starred) { + escape(type(((Starred) x).value, fn, sc)); + return Ty.OBJECT; + } + return type(x, fn, sc); + } + + private static boolean anyStarred(List l) { + for (Expr e : l) { + if (e instanceof Starred) { + return true; + } + } + return false; + } + + private static final Set MODULE_KEY_METHODS = new HashSet(); + + static { + MODULE_KEY_METHODS.add("pop"); + MODULE_KEY_METHODS.add("get"); + MODULE_KEY_METHODS.add("setdefault"); + MODULE_KEY_METHODS.add("__contains__"); + } + + /// The strings `e` can be: a str constant; or a local of `fn` (not a + /// parameter), read in `fn`'s own scope, that its body binds exactly + /// once -- to a str constant, or as the target of a `for` over a + /// literal tuple or list of str constants (bs4's + /// `for attr in ("can_be_empty_element", "hidden"): setattr(...)`). + /// Null when that is not known. Inside a comprehension or a nested + /// function the same name is another variable, which is why the scope + /// must be `fn`'s and the name a plain local there. + static List constStrings(Expr e, Fn fn, Scope sc) { + if (e instanceof Constant && ((Constant) e).kind == Constant.Kind.STR) { + return java.util.Collections.singletonList(((Constant) e).text); + } + if (e instanceof Name && fn != null && sc == fn.def.scope && !fn.names.contains(((Name) e).id) //NOPMD CompareObjectsWithEquals - identity is meant + && sc.resolve(((Name) e).id) == Scope.Binding.CELL) { + String one = cellString(fn.def, ((Name) e).id, e); + return one == null ? null : java.util.Collections.singletonList(one); + } + if (!(e instanceof Name) || fn == null || sc != fn.def.scope || fn.names.contains(((Name) e).id) //NOPMD CompareObjectsWithEquals - identity is meant + || sc.resolve(((Name) e).id) != Scope.Binding.LOCAL) { + return null; + } + String n = ((Name) e).id; + List> r = new ArrayList>(); + r.add(null); + int[] binds = {0}; + constBinds(fn.def.body, n, r, binds); + return binds[0] == 1 ? r.get(0) : null; + } + + /// The string the cell `n` holds where `use` reads it, when that is + /// settled by the straight-line statements of `f` before the one + /// holding `use`: the nearest earlier one is `n = "lit"`, or a call + /// `g()` of a function `f` defines whose whole body is `nonlocal n` and + /// assignments of string literals to `n`, and every statement between + /// them leaves `n` alone. Every function that names `n` must be such a + /// `g`, defined once and used only as such a call statement, so nothing + /// else can run its store. Null otherwise. + private static String cellString(FunctionDef f, String n, Expr use) { + List body = f.body; + int at = -1; + for (int i = 0; i < body.size() && at < 0; i++) { + if (holds(body.get(i), use)) { + at = i; + } + } + if (at < 0 || !(body.get(at) instanceof ExprStmt || body.get(at) instanceof Assign + || body.get(at) instanceof Return)) { + return null; + } + Map setters = new HashMap(); + for (Stmt s : body) { + if (s instanceof FunctionDef && cellMentions(s, n)) { + String v = setterValue((FunctionDef) s, n); + if (v == null || setters.put(((FunctionDef) s).name, v) != null) { + return null; + } + } + } + if (nestedMentions(body, n, setters)) { + return null; + } + for (String g : setters.keySet()) { + int[] uses = {0}; + int calls = 0; + countName(f.body, g, uses); + for (Stmt s : body) { + if (callOf(s, g)) { + calls++; + } + } + if (uses[0] != calls) { + return null; + } + } + if (mentionsAny(body.get(at), setters.keySet()) || hasWalrus(body.get(at))) { + return null; + } + for (int i = at - 1; i >= 0; i--) { + Stmt s = body.get(i); + if (s instanceof Assign && ((Assign) s).targets.size() == 1 && isName(((Assign) s).targets.get(0), n)) { + Expr v = ((Assign) s).value; + return v instanceof Constant && ((Constant) v).kind == Constant.Kind.STR ? ((Constant) v).text : null; + } + for (Map.Entry g : setters.entrySet()) { + if (callOf(s, g.getKey())) { + return g.getValue(); + } + } + if (s instanceof FunctionDef && setters.containsKey(((FunctionDef) s).name)) { + continue; + } + if (cellMentions(s, n) || mentionsAny(s, setters.keySet())) { + return null; + } + } + return null; + } + + private static boolean holds(Object o, Object target) { + if (o == target) { //NOPMD CompareObjectsWithEquals - identity is meant + return true; + } + boolean[] r = {false}; + Infer.children(o, x -> { + if (!r[0] && holds(x, target)) { + r[0] = true; + } + }); + return r[0]; + } + + private static boolean cellMentions(Object o, String n) { + if (o instanceof Name && ((Name) o).id.equals(n) + || o instanceof Node.Global && ((Node.Global) o).names.contains(n) + || o instanceof Arg && ((Arg) o).name.equals(n) + || o instanceof FunctionDef && ((FunctionDef) o).name.equals(n) + || o instanceof ClassDef && ((ClassDef) o).name.equals(n)) { + return true; + } + boolean[] r = {false}; + Infer.children(o, x -> { + if (!r[0] && cellMentions(x, n)) { + r[0] = true; + } + }); + return r[0]; + } + + private static boolean mentionsAny(Object o, Set ns) { + for (String n : ns) { + if (cellMentions(o, n)) { + return true; + } + } + return false; + } + + /// Whether a function, class or lambda nested in `body`, other than a + /// top-level setter, names `n`. + private static boolean nestedMentions(List body, String n, Map setters) { + for (Stmt s : body) { + if (s instanceof FunctionDef && setters.containsKey(((FunctionDef) s).name)) { + continue; + } + if (nestedMention(s, n, false)) { + return true; + } + } + return false; + } + + private static boolean nestedMention(Object o, String n, boolean inner) { + boolean nest = inner || o instanceof FunctionDef || o instanceof ClassDef || o instanceof Lambda + || o instanceof Node.Comprehension; + if (nest && cellMentions(o, n)) { + return true; + } + boolean[] r = {false}; + Infer.children(o, x -> { + if (!r[0] && nestedMention(x, n, nest)) { + r[0] = true; + } + }); + return r[0]; + } + + private static String setterValue(FunctionDef g, String n) { + if (!g.decorators.isEmpty() || g.isAsync || !g.args.names().isEmpty() || g.body.size() < 2 + || !(g.body.get(0) instanceof Node.Global) || !((Node.Global) g.body.get(0)).nonlocal + || !((Node.Global) g.body.get(0)).names.equals(java.util.Collections.singletonList(n))) { + return null; + } + String v = null; + for (int i = 1; i < g.body.size(); i++) { + Stmt s = g.body.get(i); + if (!(s instanceof Assign) || ((Assign) s).targets.size() != 1 || !isName(((Assign) s).targets.get(0), n) + || !(((Assign) s).value instanceof Constant) + || ((Constant) ((Assign) s).value).kind != Constant.Kind.STR) { + return null; + } + v = ((Constant) ((Assign) s).value).text; + } + return v; + } + + private static boolean callOf(Stmt s, String g) { + return s instanceof ExprStmt && ((ExprStmt) s).value instanceof Call + && isName(((Call) ((ExprStmt) s).value).func, g) && ((Call) ((ExprStmt) s).value).args.isEmpty() + && ((Call) ((ExprStmt) s).value).keywords.isEmpty(); + } + + private static void countName(Object o, String n, int[] c) { + if (o instanceof Name && ((Name) o).id.equals(n)) { + c[0]++; + } + Infer.children(o, x -> countName(x, n, c)); + } + + private static boolean hasWalrus(Object o) { + if (o instanceof Node.NamedExpr) { + return true; + } + boolean[] r = {false}; + Infer.children(o, x -> { + if (!r[0] && hasWalrus(x)) { + r[0] = true; + } + }); + return r[0]; + } + + /// The expression local `e` is bound to when one plain assignment in the + /// function binds it and nothing else does, or null. + static Expr soleValue(Expr e, Fn fn, Scope sc) { + if (!(e instanceof Name) || fn == null || sc != fn.def.scope || fn.names.contains(((Name) e).id) //NOPMD CompareObjectsWithEquals - identity is meant + || sc.resolve(((Name) e).id) != Scope.Binding.LOCAL) { + return null; + } + String n = ((Name) e).id; + List> ignored = new ArrayList>(); + ignored.add(null); + int[] binds = {0}; + constBinds(fn.def.body, n, ignored, binds); + if (binds[0] != 1) { + return null; + } + Expr[] r = {null}; + assignedValue(fn.def.body, n, r); + return r[0]; + } + + private static void assignedValue(Object o, String n, Expr[] r) { + if (o instanceof Assign) { + for (Expr t : ((Assign) o).targets) { + if (isName(t, n)) { + r[0] = ((Assign) o).value; + } + } + } + if (o instanceof FunctionDef || o instanceof ClassDef || o instanceof Lambda) { + return; + } + Infer.children(o, x -> assignedValue(x, n, r)); + } + + /// Whether every bound of slice `sl` is absent, `None` or an int. + private boolean sliceOfInts(Slice sl, Fn fn, Scope sc) { + for (Expr x : new Expr[] {sl.lower, sl.upper, sl.step}) { + if (x == null) { + continue; + } + Ty t = type(x, fn, sc); + if (t.k != Ty.K.INT && t.k != Ty.K.BOOL && t.k != Ty.K.NONE && t.k != Ty.K.BOT) { + return false; + } + } + return true; + } + + /// The one string [#constStrings] knows `e` to be, or null. + static String constString(Expr e, Fn fn, Scope sc) { + List r = constStrings(e, fn, sc); + return r != null && r.size() == 1 ? r.get(0) : null; + } + + private static List literalStrings(Expr e) { + List elts = e instanceof TupleExpr ? ((TupleExpr) e).elts : e instanceof ListExpr ? ((ListExpr) e).elts : null; + if (elts == null || elts.isEmpty()) { + return null; + } + List r = new ArrayList(); + for (Expr x : elts) { + if (!(x instanceof Constant) || ((Constant) x).kind != Constant.Kind.STR) { + return null; + } + r.add(((Constant) x).text); + } + return r; + } + + private static void constBinds(Object o, String n, List> r, int[] binds) { + if (o instanceof Assign) { + Assign a = (Assign) o; + for (Expr t : a.targets) { + if (isName(t, n)) { + binds[0]++; + r.set(0, a.value instanceof Constant && ((Constant) a.value).kind == Constant.Kind.STR + ? java.util.Collections.singletonList(((Constant) a.value).text) : null); + } else if (!(t instanceof Name || t instanceof Attribute || t instanceof Subscript)) { + // A tuple or starred target binds it too when it names it + // (pdfminer's `(_, obj) = parser.nextobject()` does not). + boolean[] in = {false}; + nameIn(t, n, in); + if (in[0]) { + binds[0] += 2; + } + } + } + } else if (o instanceof For && isName(((For) o).target, n)) { + binds[0]++; + r.set(0, ((For) o).isAsync ? null : literalStrings(((For) o).iter)); + } else { + Object target = o instanceof AugAssign ? ((AugAssign) o).target + : o instanceof AnnAssign ? ((AnnAssign) o).target + : o instanceof For ? ((For) o).target + : o instanceof NamedExpr ? ((NamedExpr) o).target + : o instanceof Delete ? ((Delete) o).targets + : o instanceof WithItem ? ((WithItem) o).vars : null; + boolean[] names = {false}; + if (target != null) { + nameIn(target, n, names); + } + if (names[0] || o instanceof ExceptHandler && n.equals(((ExceptHandler) o).name) + || o instanceof Global && ((Global) o).names.contains(n) + || o instanceof Import && importBinds(((Import) o).names, n) + || o instanceof ImportFrom && importBinds(((ImportFrom) o).names, n)) { + // Bound another way, or maybe: not a constant. + binds[0] += 2; + } + } + if (o instanceof FunctionDef || o instanceof ClassDef || o instanceof Lambda) { + return; + } + Infer.children(o, x -> constBinds(x, n, r, binds)); + } + + private static boolean importBinds(List names, String n) { + for (Alias a : names) { + String b = a.asname != null ? a.asname : a.name.indexOf('.') < 0 ? a.name : a.name.substring(0, a.name.indexOf('.')); + if (b.equals(n) || "*".equals(a.name)) { + return true; + } + } + return false; + } + + private static void nameIn(Object o, String n, boolean[] r) { + if (o instanceof Name && ((Name) o).id.equals(n)) { + r[0] = true; + return; + } + Infer.children(o, x -> nameIn(x, n, r)); + } + + private static boolean sysModules(Expr e, Scope sc) { + return e instanceof Attribute && "modules".equals(((Attribute) e).attr) && ((Attribute) e).value instanceof Name + && "sys".equals(((Name) ((Attribute) e).value).id) + && sc.resolve("sys") == Scope.Binding.GLOBAL; + } + + private void store(Expr t, Ty v, Expr value, Fn fn, Scope sc) { + if (t instanceof Name) { + storeName(((Name) t).id, v, fn, sc); + } else if (t instanceof Attribute) { + Attribute a = (Attribute) t; + Ty r = selfRecv(a.value, a.attr, fn, sc); + Layouts.Cls us = fn == null && a.value instanceof Name ? p.untypedSelf.get(sc) : null; + if (us != null && r.wide() && sc.params.iterator().next().equals(((Name) a.value).id) + && closedFor(us, a.attr)) { + r = Ty.inst(us, false); + } + if (!p.done && r.k == Ty.K.CLS && r.sites != null) { + // `K.__init__ = f` on the class object itself replaces what + // its instances and its subclasses' resolve. Only the written + // name: a computed `setattr(cls, name, v)` (a class + // decorator's) is the dynamic stores' concern. + for (int id : r.sites) { + p.clsStored.computeIfAbsent(p.clsById.get(id), x -> new HashSet()).add(a.attr); + } + } + storeField(r, a.attr, v); + } else if (t instanceof Subscript && !(((Subscript) t).index instanceof Slice) + && dictOwner(((Subscript) t).value, sc) != null) { + // `x.__dict__[k] = v`: setattr(x, k, v). + Expr owner = dictOwner(((Subscript) t).value, sc); + type(((Subscript) t).index, fn, sc); + computedStore(type(owner, fn, sc), owner, ((Subscript) t).index, v, t, fn, sc); + } else if (t instanceof Subscript && sysModules(((Subscript) t).value, sc)) { + // `sys.modules[name] = m` registers one module under a name; it + // reads no module out, as a read of `sys.modules` does. + // pptx's `sys.modules["pptx.exceptions"] = exceptions` made every + // module of the program loose. + type(((Subscript) t).index, fn, sc); + escape(v); + } else if (t instanceof Subscript) { + Subscript s = (Subscript) t; + Ty r = type(s.value, fn, sc); + if (s.index instanceof Slice) { + anyChildren(s.index, fn, sc); + if (r.k == Ty.K.LIST) { + storeElem(r, elem(v)); + } else { + escape(v); + } + } else { + Ty kt = type(s.index, fn, sc); + int ci = constIndex(s.index); + if (r.k == Ty.K.DICT) { + storeDict(r, kt, v); + } else if (r.k == Ty.K.LIST && ci >= 0 && slotCount(r) > ci) { + // Same position, same length: the positions still hold. + for (int site : r.sites) { + siteJoin(site, v); + joinSlot(site, slotCount(r), ci, v, false); + } + } else if (r.k == Ty.K.LIST) { + storeElem(r, v); + } else if (r.k != Ty.K.BOT && !(shadow && callableSet(v))) { + // The generic view of a body sees every receiver as an + // object; the typed walk of the same statement records + // the functions for the container its receiver is, and + // a call through any other container enters them + // through the door's guard. Escaping them here made + // every one of markdownify's convert_* methods untyped. + escape(v); + } + } + } else if (t instanceof TupleExpr || t instanceof ListExpr) { + List elts = t instanceof TupleExpr ? ((TupleExpr) t).elts : ((ListExpr) t).elts; + List src = value instanceof TupleExpr ? ((TupleExpr) value).elts + : value instanceof ListExpr ? ((ListExpr) value).elts : null; + boolean starred = anyStarred(elts); + if (src != null && src.size() == elts.size() && !starred && !anyStarred(src)) { + // `a, b = x, y` pairs each target with its own value. + for (int i = 0; i < elts.size(); i++) { + store(elts.get(i), type(src.get(i), fn, sc), null, fn, sc); + } + return; + } + if (!starred && (v.k == Ty.K.TUPLE || v.k == Ty.K.LIST) && slotCount(v) == elts.size()) { + // Each target takes its own position (a length that does + // not match raises when unpacking). + for (int i = 0; i < elts.size(); i++) { + store(elts.get(i), slot(v, i), null, fn, sc); + } + return; + } + Ty each = Ty.OBJECT; + if (value != null && rangeCall(value, sc)) { + each = Ty.INT; + } else if (v.k == Ty.K.BOT) { + // Nothing reaches the value yet: a later pass decides, where + // OBJECT now would stay OBJECT for good. + each = Ty.BOT; + } else if (v.k == Ty.K.TUPLE) { + each = tupleElem(v); + } else if (v.k == Ty.K.LIST) { + each = elem(v); + } else { + escape(v); + } + for (Expr e : elts) { + store(e instanceof Starred ? ((Starred) e).value : e, e instanceof Starred ? Ty.OBJECT : each, null, fn, + sc); + } + } else if (t instanceof Starred) { + store(((Starred) t).value, Ty.OBJECT, null, fn, sc); + } else { + anyChildren(t, fn, sc); + escape(v); + } + } + + private void storeName(String n, Ty v, Fn fn, Scope sc) { + Scope.Binding b = sc.resolve(n); + if (b == Scope.Binding.CELL && compOnlyCell(sc, n)) { + b = Scope.Binding.LOCAL; + } + switch (b) { + case LOCAL: + if (fn != null && sc == fn.def.scope) { //NOPMD CompareObjectsWithEquals - identity is meant + fn.locals.put(n, joinInto(fn.locals.get(n), v)); + if (guessSeen && !shadow) { + Set gl = p.guessedLocals.get(fn); + if (gl == null) { + gl = new HashSet(); + p.guessedLocals.put(fn, gl); + } + if (gl.add(n)) { + p.changed = true; + } + } + } else { + classVal(n, v, sc); + escape(v); + } + return; + case GLOBAL: + globals.put(n, joinInto(globals.get(n), v)); + if (guessSeen && !shadow) { + Set gg = p.guessedGlobals.get(this); + if (gg == null) { + gg = new HashSet(); + p.guessedGlobals.put(this, gg); + } + if (gg.add(n)) { + p.changed = true; + } + } + return; + case CELL: + case FREE: { + Scope o = cellOwner(n, sc, b); + if (o != null && p.fnOf(o) != null) { + Map m = p.cells.get(o); + if (m == null) { + m = new HashMap(); + p.cells.put(o, m); + } + Ty old = m.get(n); + Ty j = joinInto(old, v); + if (!j.equals(old)) { + m.put(n, j); + p.changed = true; + } + return; + } + escape(v); + return; + } + default: + classVal(n, v, sc); + escape(v); + } + } + + /// Records a function a class body binds to `n` (see + /// [Program#classVals]). + private void classVal(String n, Ty v, Scope sc) { + if (sc.kind != Scope.Kind.CLASS || v == null) { + return; + } + Map m = p.classVals.get(sc); + if (m == null) { + m = new HashMap(); + p.classVals.put(sc, m); + } + Ty j = Ty.join(m.get(n), v); + if (!j.equals(m.get(n))) { + m.put(n, j); + p.changed = true; + } + } + + /// Joins a store of `v` into field `attr` of `o`. A store the pass + /// cannot type -- of a value nothing knows, through a receiver of no + /// known class, under a computed name, or made by a generic body -- + /// does not widen the field: it guards it (see [Program#unknownStores]), + /// and the slot takes the value when it fits the guess, the object + /// beside it when not. A guessed value (see [#guessSeen]) is typed for + /// the typed way of computing it, and guards the field for the other. + private void storeOne(Layouts.Cls o, String attr, Ty v0, Ty recv) { + Ty v = noMeth(v0); + Map m = fields.get(o); + // The generic view (shadow) runs the same body with untyped + // parameters: a value it still knows is one the field really gets. + boolean slow = recv.k != Ty.K.INST || computing || v.wide(); + if (slow || guessSeen) { + Set u = p.unknownStores.get(o); + if (u == null) { + u = new HashSet(); + p.unknownStores.put(o, u); + } + if (u.add(attr)) { + p.changed = true; + } + } + Ty cur = m.get(attr); + if (!slow) { + cur = joinInto(cur, v); + } + m.put(attr, cur); + } + + void storeField(Ty recv, String attr, Ty v) { + if (recv.k == Ty.K.UNION) { + for (Ty m : recv.members()) { + storeField(m.nonNone(), attr, v); + } + return; + } + if (recv.k == Ty.K.BOT || recv.k == Ty.K.NONE) { + return; + } + if (!p.done) { + // What the store may replace if `attr` names a method + // ([Program#patchedFound]). + if (recv.k == Ty.K.INST) { + Set s = p.clsStored.get(recv.cls); + if (s == null) { + s = new HashSet(); + p.clsStored.put(recv.cls, s); + } + s.add(attr); + } else if (p.dynStored.add(attr)) { + // [#objectInit] reads it. + p.changed = true; + } + } + List owners = p.fieldOwners.get(attr); + if (owners == null) { + escape(v); + return; + } + boolean any = false; + for (Layouts.Cls o : owners) { + boolean reach = recv.k != Ty.K.INST || isSelfOrAncestor(o, recv.cls) || isSelfOrAncestor(recv.cls, o); + if (reach) { + storeOne(o, attr, v, recv); + any = true; + } + } + if (!any) { + escape(v); + } + } + + /// The declaring class of field `attr` for an instance of `k`. + static Layouts.Cls fieldOwner(Layouts.Cls k, String attr) { + for (Layouts.Cls c = k; c != null; c = c.parent) { + if (c.fields.contains(attr)) { + return c; + } + } + return null; + } + + /// A field `k` does not have but classes below it store + /// (`ParserBase.updatepos` reading `self.rawdata`, which only + /// HTMLParser sets): what those stores put there, joined. An instance + /// that has none raises on the read, which is no value. Null when no + /// class below stores it, or `k`'s chain binds the name to anything. + private Ty subclassField(Layouts.Cls k, String attr) { + if (Layouts.resolver(k, attr) != null) { + return null; + } + Ty t = null; + for (Layouts.Cls s : p.below(k)) { + if (s == k || !s.fields.contains(attr) || fieldOwner(s.parent, attr) != null) { //NOPMD CompareObjectsWithEquals - identity is meant + continue; + } + if (Layouts.resolver(s, attr) != null) { + return null; + } + Ty ft = fieldType(s, attr); + if (guarded(s, attr)) { + ft = guessRead(ft); + } + t = t == null ? ft : mix(t, ft); + } + return t; + } + + Ty fieldType(Layouts.Cls owner, String attr) { + Ty t = fields.get(owner).get(attr); + if (t == null && !p.done && !guarded(owner, attr)) { + // Not stored yet, by any store: nothing so far. A OBJECT given in + // an early round, before the constructor is walked, would stick. + return Ty.BOT; + } + if (t == null || guarded(owner, attr) && !guessable(t) && !guessedDict(t)) { + return Ty.UNSEEN; + } + if (!p.done && guessedDict(t) && guarded(owner, attr)) { + // Whoever reads it reads its elements as guesses, by every path + // a field is read (a constant getattr, a subclass's field...). + // The field may hold another dict altogether, filled by stores + // the pass never saw: what its sites hold is no answer yet. + guessSites(t.sites); + for (int st : t.sites) { + if (p.lostSites.add(Integer.valueOf(st))) { + p.changed = true; + } + } + } + return loc(t); + } + + /// Whether a guarded field may keep dict `t` as it is: typed code holds + /// a dict as an object, and every typed dict operation checks that it + /// has one (`Typed.dgetv` and the rest fall back to the generic + /// protocol), so what it may really be is only a question for its + /// elements, which [#guessRead] makes guesses. Every computed setattr + /// on an object of no known class guards every field of every class: + /// markdownify's converter cache read as an object, and every + /// `convert_*` method it holds went with it. + private static boolean guessedDict(Ty t) { + return t.k == Ty.K.DICT && !t.opt && t.sites.length > 0; + } + + /// Whether a guarded field may keep `t` as its guess: a type typed code + /// holds in a slot of its own, beside the object that replaces it. + static boolean guessable(Ty t) { + switch (t.k) { + case INT: + case BOOL: + case FLOAT: + case STR: + case LIST: + return true; + case INST: + // An analysed class has no Java class to hold a guess in. + return t.cls.compiled; + default: + return false; + } + } + + /// Compiled methods a call `recv.m(...)` on an instance of `k` may run: + /// the one `k` resolves, and every override in a subclass of `k`. Null + /// when the name may resolve to anything else (a field, a class + /// attribute that is not a compiled method). + List candidates(Layouts.Cls k, String m) { + Layouts home = p.home.get(k).layouts; + if (home.fieldOwners.containsKey(m)) { + return null; + } + List r = new ArrayList(); + Layouts.Cls res = Layouts.resolver(k, m); + if (res != null) { + FunctionDef f = res.typable.get(m); + if (f == null) { + return null; + } + if (res.home != home) { //NOPMD CompareObjectsWithEquals - identity is meant + // A method of a base in another module: typed code calls + // that module's typed copy (TypedEmit#foreignCall) when it + // is the only one an instance can run -- html.parser's + // `self.updatepos(i, j)` of `_markupbase`, bs4's parser on + // `Tag` -- and that module's own field of the name would + // shadow it on an instance. + if (res.home.fieldOwners.containsKey(m)) { + return null; + } + for (Layouts.Cls c : p.below(k)) { + if (c.bodyNames.contains(m)) { + return null; + } + } + for (Layouts.Cls c = k; c != res; c = c.parent) { //NOPMD CompareObjectsWithEquals - identity is meant + if (c.bodyNames.contains(m)) { + return null; + } + } + return java.util.Collections.singletonList(f); + } + r.add(f); + } + for (Layouts.Cls c : p.below(k)) { + if (c.bodyNames.contains(m)) { + if (c.home != home) { //NOPMD CompareObjectsWithEquals - identity is meant + // Overridden in a subclass of another module, which + // this module's typed code cannot dispatch to. + return null; + } + FunctionDef f = c.typable.get(m); + if (f == null) { + return null; + } + if (!r.contains(f)) { + r.add(f); + } + } + } + return r.isEmpty() ? null : r; + } + + /// What `except K as e` binds `e` to: an instance of `K` when `K` is + /// one of the compiled classes, since the handler runs only for a value + /// that is one; anything else is not known. Classes with no common + /// base are not joined (that would loosen them): the binding is then + /// simply not known. + private Ty caught(Ty ht) { + if (ht == null || ht.k != Ty.K.CLS || ht.opt || ht.sites.length == 0) { + return Ty.UNSEEN; + } + Ty r = Ty.BOT; + for (Layouts.Cls k : classesOf(ht)) { + r = Ty.join(r, Ty.inst(k, false)); + } + return r.k == Ty.K.INST ? r : Ty.OBJECT; + } + + private void anyChildren(Object o, Fn fn, Scope sc) { + children(o, x -> { + if (x instanceof Expr) { + escape(type((Expr) x, fn, sc)); + } else if (x instanceof Stmt) { + walk((Stmt) x, fn, sc); + } else { + anyChildren(x, fn, sc); + } + }); + } + + // ---- expressions ----------------------------------------------------- + + /// The type of `module.attr` read by name, when `a.value` names a module + /// of the program; null otherwise. Only the attribute goes where the + /// pass does not follow, never the module: a read by a fixed name + /// cannot reach the module's other globals or classes. Treating the + /// module as a value made every class of `bs4.element` loose because + /// soupsieve reads `bs4.element.NavigableString`, and every class of a + /// module escaped the same way wherever `module.function(...)` named a + /// function no direct call resolved. + private Ty moduleMember(Attribute a, Scope sc) { + Object m = foreign(a.value, sc); + if (!(m instanceof Infer)) { + return null; + } + Ty t = valueOf(foreign(a, sc)); + if (t != null) { + return t; + } + // Not stable, or not known: whatever the global holds escapes. + Infer mod = (Infer) m; + Ty g = mod.globals.get(a.attr); + if (g != null) { + mod.escape(g); + } + Layouts.Cls k = mod.globalClasses.get(a.attr); + if (k != null) { + mod.escapeClass(k); + } + Fn f = mod.globalFns.get(a.attr); + if (f != null) { + mod.escapeFn(f); + } + Infer sub = p.modules.get(mod.moduleName.isEmpty() ? a.attr : mod.moduleName + "." + a.attr); + if (sub != null && p.looseModules.add(sub)) { + p.changed = true; + } + return Ty.UNSEEN; + } + + /// The type of `v` as the receiver of `.attr`. The `self` of an open + /// class's method is its class there, unless a rejected class binds + /// `attr`: an instance of one finds the compiled fields and methods + /// for every other name, and a rejected class's own stores reach the + /// compiled fields by name, as any store on an unknown object does. + + private Ty selfRecv(Expr v, String attr, Fn fn, Scope sc) { + if (v instanceof Name && fn != null && fn.openSelf && sc == fn.def.scope //NOPMD CompareObjectsWithEquals - identity is meant + && fn.names.get(0).equals(((Name) v).id)) { + Ty t = nameType(((Name) v).id, fn, sc); + return t.k == Ty.K.INST ? rejected(t.cls, attr) ? Ty.OBJECT : loc(t) + : p.rejectedAnywhere.contains(attr) || !p.rejectedNames.isEmpty() && anyRejected(attr) ? Ty.OBJECT : loc(t); + } + return type(v, fn, sc); + } + + /// Whether a call of `attr` on an instance of `k` runs a compiled + /// method the pass sees: `k` is not open, or no rejected class binds + /// `attr` (an instance typed `k` is one of `k`'s Java class). + /// Whether `m`, read on an instance of `k`, is a method that never + /// receives the instance: the class body that binds it nearest up the + /// chain binds it once, as a function decorated with nothing but the + /// builtin `classmethod` or `staticmethod`, no compiled class below + /// `k` binds the name again, and no instance holds it as a field. + private boolean classLevel(Layouts.Cls k, String m) { + Layouts.Cls res = Layouts.resolver(k, m); + if (res == null || p.home.get(k).layouts.fieldOwners.containsKey(m)) { + return false; + } + for (Layouts.Cls c : p.below(k)) { + if (c.bodyNames.contains(m)) { + return false; + } + } + FunctionDef d = null; + for (Stmt st : res.def.body) { + if (st instanceof FunctionDef && ((FunctionDef) st).name.equals(m)) { + if (d != null) { + return false; + } + d = (FunctionDef) st; + } else if (Layouts.bodyBindingsOf(st) == null || Layouts.bodyBindingsOf(st).contains(m)) { + return false; + } + } + return d != null && classOrStatic(d, res); + } + + /// The pass's function for `d`, of whichever module defines it. + Fn anyFn(FunctionDef d) { + Fn f = p.fns.get(d); + return f == null || f.analysisOnly ? null : f; + } + + /// This module's functions that generated code has a typed body for: + /// [#fns] without the analysed classes' methods. + Map emitFns() { + if (emitFns == null) { + emitFns = new LinkedHashMap(); + for (Map.Entry e : fns.entrySet()) { + if (!e.getValue().analysisOnly) { + emitFns.put(e.getKey(), e.getValue()); + } + } + } + return emitFns; + } + + private Map emitFns; + + private boolean closedFor(Layouts.Cls k, String attr) { + return !open.contains(k) || !rejected(k, attr); + } + + Ty nameType(String n, Fn fn, Scope sc) { + Scope.Binding b = sc.resolve(n); + if (b == Scope.Binding.CELL && compOnlyCell(sc, n)) { + b = Scope.Binding.LOCAL; + } + switch (b) { + case LOCAL: + if (fn != null && sc == fn.def.scope) { //NOPMD CompareObjectsWithEquals - identity is meant + Ty t = fn.locals.get(n); + return t == null ? Ty.BOT : guessedLocal(fn, n) ? guessRead(t) : t; + } + if (sc.kind == Scope.Kind.COMPREHENSION) { + Ty t = compLocal(sc, n); + if (t != null) { + return shadow ? Ty.OBJECT : guessedCompVar(sc, n) ? guessRead(t) : t; + } + } + return classRead(n, sc); + case FREE: + case CELL: { + // A local of the function a comprehension (or one nested in + // it) runs in: read where it stands, as its own type. What the + // comprehension does with it is typed like any other use. + Fn o = compOuter; + if (o != null && sc.kind == Scope.Kind.COMPREHENSION && sc.owner(n) == o.def.scope //NOPMD CompareObjectsWithEquals - identity is meant + && !(o.def.scope.cells.contains(n) && !compOnlyCell(o.def.scope, n))) { + // A cell a closure shares is any value: read as OBJECT below. + Ty t = o.locals.get(n); + if (t == null) { + return Ty.BOT; + } + return guessedLocal(o, n) ? guessRead(t) : t; + } + Scope ow = sc.owner(n); + if (b == Scope.Binding.FREE && ow != null && ow.kind == Scope.Kind.COMPREHENSION) { + // A target of a comprehension this one is nested in. + Ty t = compLocal(ow, n); + if (t != null) { + return shadow ? Ty.OBJECT : guessedCompVar(ow, n) ? guessRead(t) : t; + } + } + Scope co = cellOwner(n, sc, b); + Fn of = co == null ? null : p.fnOf(co); + if (of != null && !p.done) { + // Every store to the variable, wherever it is made, and + // what the calls pass when it is a parameter. + Map m = p.cells.get(co); + Ty t = m == null ? null : m.get(n); + int pi = of.names.indexOf(n); + Ty pt = pi < 0 || pi >= of.params.length ? null : paramIn(of, pi); + if (pt != null) { + t = Ty.join(t, pt); + } + if (t != null && pt != null && pt.unseen()) { + // A parameter whose callers are unseen, shared by a + // closure: the join ignored it, but a cell has no + // guard at the door, so what the stores say is not + // even a guess. Read as anything (csv's + // `_Dialect.__init__` passed a dialect's name on to + // `get_dialect` as a `_Frozen`). + escapeFuncs(t); + return Ty.OBJECT; + } + return t == null ? Ty.BOT : t; + } + return Ty.OBJECT; + } + case GLOBAL: { + Fn f = globalFns.get(n); + if (f != null) { + if (sc.kind == Scope.Kind.MODULE) { + // Module code runs in order: the read may come + // before the def, while the name is still a builtin. + escapeFn(f); + return Ty.OBJECT; + } + // Followed to where it is called (see [#funcValue]). + return p.done ? Ty.OBJECT : funcValue(f); + } + Layouts.Cls k = globalClasses.get(n); + if (k != null && k.enumMeta) { + // The class protocol of an enumeration (iteration, item + // lookup, `in`) is EnumType's, which no layout holds. + return Ty.OBJECT; + } + if (k != null) { + return classValue(k); + } + if (importedNames.containsKey(n)) { + Ty t = valueOf(resolve(n, 0)); + if (t != null) { + return t; + } + } + Ty t = globals.get(n); + return t == null ? Ty.BOT : guessedGlobal(n) ? guessRead(t) : t; + } + default: + return classRead(n, sc); + } + } + + /// A name read in a class body: a function the body bound to it + /// earlier (`convert_i = convert_em`) is the value it is. + private Ty classRead(String n, Scope sc) { + if (sc.kind == Scope.Kind.CLASS) { + Map cv = p.classVals.get(sc); + Ty t = cv == null ? null : cv.get(n); + if (t != null && (t.k == Ty.K.BOT || callables(t.nonNone(), new ArrayList(), new ArrayList()))) { + // Nothing yet (a factory whose result is not known) stays + // nothing until it is. + return t; + } + } + return Ty.UNSEEN; + } + + Ty type(Expr e, Fn fn, Scope sc) { + if (shadow || p.done) { + return loc(type0(e, fn, sc)); + } + boolean saved = guessSeen; + guessSeen = false; + Ty t = loc(type0(e, fn, sc)); + boolean g = guessSeen && !construction(e, t, sc); + // An unseen value is no evidence of a slot's type (Ty#UNSEEN), but + // it is a value the slot really gets: whatever it lands in holds + // what the other sources say as a guess, guarded, the generic way + // of computing it taking over when the guess misses. + guessSeen = saved || g || t.unseen() && !shadow; + if (g) { + p.guessedExprs.add(e); + if ((t.k == Ty.K.LIST || t.k == Ty.K.TUPLE || t.k == Ty.K.DICT) && t.sites.length > 0) { + guessSites(t.sites); + } + // The generic way of computing it, which runs when a guess + // fails: as the generic code does, over values of no known type. + shadow = true; + try { + type0(e, fn, sc); + } finally { + shadow = false; + } + } + return t; + } + + /// Whether `e`, of type `t`, constructs a known class: its type is that + /// class whatever its arguments were, so a guess among them (each + /// still checked where it is read) does not make the result one. + private boolean construction(Expr e, Ty t, Scope sc) { + if (!(e instanceof Call) || t.k != Ty.K.INST || t.opt) { + return false; + } + Expr f = ((Call) e).func; + Object k = null; + if (f instanceof Name && sc.resolve(((Name) f).id) == Scope.Binding.GLOBAL) { + k = globalClasses.get(((Name) f).id); + if (k == null) { + k = foreign(f, sc); + } + } else if (f instanceof Attribute && foreign(((Attribute) f).value, sc) instanceof Infer) { + k = foreign(f, sc); + } + return k == t.cls; //NOPMD CompareObjectsWithEquals - identity is meant + } + + /// Whether a guessed value was read since the statement began (see + /// [#guessed]). + private boolean guessSeen; + + /// A guessed value read: the value itself (`t`) in typed code, which + /// keeps the typed form; nothing known in the generic code. + private Ty guessRead(Ty t) { + // Only a type typed code holds in a slot of its own is a guess: + // with nothing typed known, or a value of another kind, any value + // may be there. + if (callableSet(t)) { + // Never in a typed slot of its own (see [#loc]): what it may be + // is what a call through it is followed to. + return t; + } + if (!shadow && guessedDict(t)) { + guessSites(t.sites); + return t; + } + if (shadow || !guessable(t)) { + // Read as anything: a function it may be is called where the + // pass does not follow it. + if (t != null) { + escapeFuncs(t); + } + return Ty.OBJECT; + } + guessSeen = true; + return t; + } + + private void guessSites(int[] sites) { + for (int st : sites) { + if (p.guessedSites.add(Integer.valueOf(st))) { + p.changed = true; + } + } + } + + /// An element of a container of these sites read as `t`. + private Ty siteRead(Ty t, int[] sites) { + if (exactRead(t, sites)) { + return t; + } + for (int st : sites) { + if (p.guessedSites.contains(Integer.valueOf(st))) { + return guessRead(t); + } + } + return t; + } + + /// Whether `e`, as typed code computes it, is a guess (see + /// [Program#guessedExprs]). + boolean guessed(Expr e) { + return p.guessedExprs.contains(e); + } + + /// Whether the elements of a container of type `t` may be values + /// typed code did not put there: read as guesses. + boolean guessedSite(Ty t) { + if (p.allListsEscape) { + return true; + } + for (int st : t.sites) { + Integer key = Integer.valueOf(st); + if (escapedSites.contains(key) || p.guessedSites.contains(key)) { + return true; + } + } + return false; + } + + boolean guessedLocal(Fn f, String n) { + Set s = p.guessedLocals.get(f); + return s != null && s.contains(n); + } + + boolean guessedReturn(Fn f) { + return p.guessedReturns.contains(f); + } + + boolean guessedGlobal(String n) { + Set s = p.guessedGlobals.get(this); + return s != null && s.contains(n); + } + + /// Whether field `attr` of `owner` is guarded (see + /// [Program#unknownStores]). + boolean guarded(Layouts.Cls owner, String attr) { + Set u = p.unknownStores.get(owner); + return u != null && u.contains(attr); + } + + /// The result of a call that runs `f`. + private Ty retOf(Fn f, Ty t) { + // Either version may run, the guard picks: the generic one's + // result joins in (see [#call]). + Infer h = p.fnHome.get(f); + Fn g = h == null ? null : h.generic.get(f.def); + Ty r = g == null || g == f ? t : mix(t, g.ret); //NOPMD CompareObjectsWithEquals - identity is meant + return p.guessedReturns.contains(f) ? guessRead(r) : r; + } + + /// The type of a read of `o` (see [#resolve]) as a value, or null when + /// `o` says nothing. A function or a class read as a value goes where + /// the pass does not follow. + private Ty valueOf(Object o) { + if (o instanceof Fn) { + escapeFn((Fn) o); + return Ty.UNSEEN; + } + if (o instanceof Layouts.Cls) { + // The class as a value: followed to where it is called, which + // constructs it, or to where the pass stops following it, which + // lets it go then ([#escape]). + return classValue((Layouts.Cls) o); + } + if (o instanceof Infer && p.looseModules.add((Infer) o)) { + p.changed = true; + } + if (o instanceof Extern) { + Extern g = (Extern) o; + Ty t = g.module.globals.get(g.name); + return t == null ? Ty.BOT : g.module.guessedGlobal(g.name) ? guessRead(loc(t)) : loc(t); + } + return null; + } + + private Ty type0(Expr e, Fn fn, Scope sc) { + if (e instanceof Constant) { + switch (((Constant) e).kind) { + case NONE: + return Ty.NONE; + case TRUE: + case FALSE: + return Ty.BOOL; + case INT: + return Ty.INT; + case FLOAT: + return ((Constant) e).text.endsWith("j") || ((Constant) e).text.endsWith("J") ? Ty.obj("complex") + : Ty.FLOAT; + case STR: + return Ty.STR; + case BYTES: + return Ty.BYTES; + case ELLIPSIS: + return Ty.obj("ellipsis"); + default: + return Ty.OBJECT; + } + } + if (e instanceof Name) { + if (fn != null && fn.openSelf && sc == fn.def.scope && fn.names.get(0).equals(((Name) e).id)) { //NOPMD CompareObjectsWithEquals - identity is meant + // An instance of a rejected class, perhaps: as a value it + // reaches wherever this may go, so it is of no known class. + return Ty.OBJECT; + } + Ty nt = narrowedAt.get(e); + if (fn != null && sc == fn.def.scope && narrowing.containsKey(nk(sc, ((Name) e).id))) { //NOPMD CompareObjectsWithEquals - identity is meant + nt = narrowing.get(nk(sc, ((Name) e).id)); + narrowedAt.put((Name) e, nt); + } + if (nt != null) { + // Still typed as the local is, so its stores stay joined; + // but the test checked the value, so whether that type was + // a guess (a cache's `get`) no longer matters. + boolean g = guessSeen; + nameType(((Name) e).id, fn, sc); + guessSeen = g; + return nt; + } + return nameType(((Name) e).id, fn, sc); + } + if (e instanceof Subscript && sysModules(((Subscript) e).value, sc) && (((Subscript) e).index instanceof Constant + && ((Constant) ((Subscript) e).index).kind == Constant.Kind.STR || isName(((Subscript) e).index, "__name__") + && sc.resolve("__name__") != Scope.Binding.LOCAL && !moduleScope.assigned.contains("__name__"))) { + // `sys.modules["warnings"]`: that one module, as a value; + // `sys.modules[__name__]` this one (bs4.builder). + Infer m = ((Subscript) e).index instanceof Name ? this + : p.modules.get(((Constant) ((Subscript) e).index).text); + if (m != null && !p.done && p.looseModules.add(m)) { + p.changed = true; + } + // A module, as `import` binds one: a computed store on it sets + // a global (loosened above), never a field of an instance. As + // unseen, bs4's `setattr(this_module, name, obj)` guarded every + // field of the program. + return m != null ? Ty.obj("module") : Ty.UNSEEN; + } + if (e instanceof Attribute) { + Layouts.Cls sk = classStaticOf(((Attribute) e).value, ((Attribute) e).attr, sc); + if (sk != null) { + return classStatic(sk, ((Attribute) e).attr); + } + } + if (e instanceof Attribute) { + // `Color.RED`: a member the compiler defined (EnumLowering), + // one instance of the class itself. + Layouts.Cls ek = calledClassOrEnum(((Attribute) e).value, sc); + List mem = ek == null ? null : EnumLowering.members(ek.def); + if (mem != null && mem.contains(((Attribute) e).attr) && ek.compiled && !ek.builtinOwn) { + return Ty.inst(ek, false); + } + } + if (e instanceof Attribute && "modules".equals(((Attribute) e).attr) && !p.allModulesLoose && !p.done) { + // `sys.modules`: every module of the program, as a value. + p.allModulesLoose = true; + p.changed = true; + } + if (e instanceof Attribute && CLASS_FACTS.contains(((Attribute) e).attr) + && classOwner(((Attribute) e).value, sc) != null) { + classFacts.add(((Attribute) e).value); + } + if (e instanceof Attribute && "__dict__".equals(((Attribute) e).attr)) { + dictOf(e, ((Attribute) e).value, fn, sc); + } else if (e instanceof Attribute && "__class__".equals(((Attribute) e).attr)) { + // As `type(x)` (#call1). + Ty o = type(((Attribute) e).value, fn, sc); + Ty known = classesBelow(o); + if (known != null) { + return known; + } + if (o.wide() || o.k == Ty.K.INST) { + if (o.k == Ty.K.INST) { + // Not one class this pass names: let go, so the + // nameless class it becomes [#anyClassAttr] covers it. + loosen(o.cls); + } + return Ty.cls(new int[0]); + } + classOf(e, ((Attribute) e).value, fn, sc); + } + if (e instanceof Attribute) { + Attribute a = (Attribute) e; + if (MATH_CONSTS.contains(a.attr) && isMath(a.value, sc)) { + return Ty.FLOAT; + } + if (a.value instanceof Name && globalClasses.containsKey(((Name) a.value).id) + && sc.resolve(((Name) a.value).id) == Scope.Binding.GLOBAL) { + // `Cls.attr` as a value: a method taken off the class runs + // with arguments nobody tracks. It is the one method the + // class resolves, when nothing can replace it. + Layouts.Cls k = globalClasses.get(((Name) a.value).id); + if (k != null && closedFor(k, a.attr) && !p.home.get(k).layouts.fieldOwners.containsKey(a.attr)) { + Layouts.Cls o = Layouts.resolver(k, a.attr); + FunctionDef m = o == null ? null : o.typable.get(a.attr); + boolean first = o == k || singleBased(k); //NOPMD CompareObjectsWithEquals - identity is meant + if (first && (o == null || m != null && p.fns.get(m) != null + || m == null && definesFunction(o.def, a.attr))) { + // (An untyped method, `Element.__init__(self, tag, + // attrib={}, **extra)`, takes anything already.) + if (m != null) { + escapeFn(p.fns.get(m)); + } + return Ty.OBJECT; + } + } + escapeMethods(a.attr); + return Ty.OBJECT; + } + Ty mm = moduleMember(a, sc); + if (mm != null) { + return mm; + } + Ty r = selfRecv(a.value, a.attr, fn, sc); + if (r.wide() && a.value instanceof Name && sc.resolve(((Name) a.value).id) == Scope.Binding.BUILTIN + && !moduleScope.hasStarImport && !moduleScope.assigned.contains(((Name) a.value).id) + && (Layouts.BUILTIN_NAMES.containsKey(((Name) a.value).id) || "object".equals(((Name) a.value).id) + || "type".equals(((Name) a.value).id))) { + // An attribute of a builtin class (`object.__init__`, + // `str.join`): the builtin's own, never a method of the + // program. + return Ty.OBJECT; + } + return attrType(r, a.attr); + } + if (e instanceof Call) { + return call((Call) e, fn, sc); + } + if (e instanceof BinOp) { + BinOp b = (BinOp) e; + Ty l = type(b.left, fn, sc); + Ty r = type(b.right, fn, sc); + if ("*".equals(b.op) && b.left instanceof ListExpr && l.k == Ty.K.LIST) { + unslot(l); + return Ty.list(l.sites, false); + } + if ("+".equals(b.op) && l.k == Ty.K.LIST && r.k == Ty.K.LIST) { + int s = site(b); + siteJoin(s, mix(elem(l), elem(r))); + return Ty.list(new int[] {s}, false); + } + if (l.k == Ty.K.BOT || r.k == Ty.K.BOT) { + return Ty.BOT; + } + Ty t = realPow(b, l, r) ? Ty.FLOAT : binop(b.op, l, r, b.right); + if (t.wide()) { + escape(l); + escape(r); + } + return t; + } + if (e instanceof UnaryOp) { + UnaryOp u = (UnaryOp) e; + Ty t = type(u.operand, fn, sc); + if ("not".equals(u.op)) { + return Ty.BOOL; + } + if (t.k == Ty.K.BOT) { + return Ty.BOT; + } + if (t.k == Ty.K.FLOAT && !t.opt) { + return Ty.FLOAT; + } + if ((t.k == Ty.K.INT || t.k == Ty.K.BOOL) && !"+".equals(u.op)) { + return Ty.INT; + } + if (t.k == Ty.K.INT && "+".equals(u.op)) { + return Ty.INT; + } + escape(t); + return Ty.OBJECT; + } + if (e instanceof BoolOp) { + Ty r = Ty.BOT; + for (Expr v : ((BoolOp) e).values) { + r = mix(r, type(v, fn, sc)); + } + return r; + } + if (e instanceof Compare) { + Compare c = (Compare) e; + for (int i = -1; i < c.ops.size(); i++) { + // `type(a) is B`, `type(a) == type(b)`: nothing is made. + Expr side = i < 0 ? c.left : c.comparators.get(i); + String op = c.ops.get(i < 0 ? 0 : i); + String next = i + 1 < c.ops.size() ? c.ops.get(i + 1) : op; + if (classOwner(side, sc) != null && classOp(op) && classOp(next) || dictOwner(side, sc) != null) { + // A dict compared is a dict read. + classFacts.add(side); + } + } + Ty l = identityOperand(c, -1, sc) ? Ty.OBJECT : type(c.left, fn, sc); + boolean plain = true; + for (int i = 0; i < c.ops.size(); i++) { + Ty r = identityOperand(c, i, sc) ? Ty.OBJECT : type(c.comparators.get(i), fn, sc); + String op = c.ops.get(i); + if (!("is".equals(op) || "is not".equals(op) || "in".equals(op) || "not in".equals(op) + || plainCompare(l) && plainCompare(r))) { + plain = false; + } + if ("in".equals(op) || "not in".equals(op)) { + if (r.k == Ty.K.LIST) { + // A list's `in` compares its elements and stores + // nothing: they leave (to `__eq__`), the list does + // not. bs4's `Tag.__contains__` escaped every tag's + // `contents` this way. + escape(elem(r)); + } else if (r.k == Ty.K.TUPLE && slotCount(r) >= 0) { + // Each element compares itself with the left side + // and keeps nothing; a class does so by identity. + for (int si = 0; si < slotCount(r); si++) { + Ty st = slot(r, si); + if (st.k != Ty.K.CLS) { + escape(st); + } + } + } else if (r.k != Ty.K.DICT) { + // A dict's `in` reads its keys and keeps nothing. + escape(r); + } + if (l.k != Ty.K.CLS) { + // A compiled class compares as `type` compares + // it, by identity: its metaclass is `type` or one + // without comparisons (Layouts#plainMetaclass). + escape(l); + } + } + l = r; + } + return plain ? Ty.BOOL : Ty.OBJECT; + } + if (e instanceof IfExp) { + IfExp i = (IfExp) e; + type(i.test, fn, sc); + Ty a = type(i.body, fn, sc); + Ty b = type(i.orelse, fn, sc); + Ty r = mix(a, b); + if (r.wide()) { + // Neither side is followed past here. + escape(a); + escape(b); + } + return r; + } + if (e instanceof Subscript && !(((Subscript) e).index instanceof Slice) + && dictOwner(((Subscript) e).value, sc) != null) { + // `x.__dict__[k]`: a read, which changes no attribute. + type(dictOwner(((Subscript) e).value, sc), fn, sc); + type(((Subscript) e).index, fn, sc); + return Ty.UNSEEN; + } + if (e instanceof Subscript && ((Subscript) e).value instanceof Name + && GENERIC_BUILTINS.contains(((Name) ((Subscript) e).value).id) + && sc.resolve(((Name) ((Subscript) e).value).id) == Scope.Binding.BUILTIN && !moduleScope.hasStarImport) { + // `list[int]`: a `types.GenericAlias`, whatever the parameters. + escape(type(((Subscript) e).index, fn, sc)); + return Ty.obj("types.GenericAlias"); + } + if (e instanceof Subscript) { + Subscript s = (Subscript) e; + Ty r = type(s.value, fn, sc); + if (s.index instanceof Slice) { + anyChildren(s.index, fn, sc); + if (r.k == Ty.K.LIST && !r.opt) { + // The slice shares the sites but not the positions. + unslot(r); + return Ty.list(r.sites, false); + } + if (r.k == Ty.K.STR && !r.opt) { + // A str's slice is a str, whatever the bounds (a bad + // bound raises). + return Ty.STR; + } + if (r.k == Ty.K.BYTES) { + return Ty.BYTES; + } + escape(r); + return Ty.UNSEEN; + } + Ty i = type(s.index, fn, sc); + if (r.k == Ty.K.BOT || r.k == Ty.K.NONE || i.k == Ty.K.BOT) { + return Ty.BOT; + } + int ci = constIndex(s.index); + if (r.k == Ty.K.LIST && (i.k == Ty.K.INT || i.k == Ty.K.BOOL)) { + return ci >= 0 ? slot(r, ci) : elem(r); + } + if (r.k == Ty.K.TUPLE && (i.k == Ty.K.INT || i.k == Ty.K.BOOL)) { + int n = slotCount(r); + if (ci < 0 && ci != Integer.MIN_VALUE && n > 0 && n + ci >= 0) { + ci = n + ci; + } + return ci >= 0 ? slot(r, ci) : tupleElem(r); + } + if (r.k == Ty.K.BYTES && (i.k == Ty.K.INT || i.k == Ty.K.BOOL)) { + // A byte is an int; a bad index raises. + return Ty.INT; + } + if (r.k == Ty.K.STR && !r.opt && (i.k == Ty.K.INT || i.k == Ty.K.BOOL)) { + // A character is a str; a bad index raises. + return Ty.STR; + } + if (r.k == Ty.K.DICT) { + // A key that is not there raises: the read is of the values. + escape(i); + return dictVal(r); + } + if (r.k == Ty.K.LIST && s.index instanceof Slice && sliceOfInts((Slice) s.index, fn, sc)) { + // A new list of the same elements. Typed as one from the same + // sites, a store into the copy widens the original's + // elements, which is sound. Escaping the list instead made + // bs4's `self.contents[i:]` turn every tag's `contents` -- + // and so every child, every `node` markdownify walks -- into + // untyped objects. + return Ty.list(r.sites, false); + } + if (r.k == Ty.K.LIST) { + // A read never writes the list: what leaves is its elements. + escape(elem(r)); + escape(i); + return Ty.UNSEEN; + } + escape(r); + escape(i); + return Ty.UNSEEN; + } + if (e instanceof DictExpr && !((DictExpr) e).keys.contains(null)) { + DictExpr d = (DictExpr) e; + Ty t = Ty.dict(new int[] {site(d)}); + for (int i = 0; i < d.keys.size(); i++) { + storeDict(t, type(d.keys.get(i), fn, sc), type(d.values.get(i), fn, sc)); + } + return t; + } + if (e instanceof ListExpr) { + ListExpr l = (ListExpr) e; + int s = site(l); + boolean starred = anyStarred(l.elts); + if (starred && unslotted.add(Integer.valueOf(s))) { + p.changed = true; + } + for (int i = 0; i < l.elts.size(); i++) { + Expr x = l.elts.get(i); + if (x instanceof Starred) { + Ty t = type(((Starred) x).value, fn, sc); + siteJoin(s, t.k == Ty.K.LIST ? elem(t) : Ty.OBJECT); + escape(t); + } else { + Ty t = type(x, fn, sc); + if (starred) { + siteJoin(s, t); + } else { + // The position follows the value; a read of the + // joined elements escapes it if they lose it (elem). + Ty j = mix(siteElem.get(s), t); + if (!j.equals(siteElem.get(s))) { + siteElem.set(s, j); + p.changed = true; + } + joinSlot(s, l.elts.size(), i, t, false); + } + } + } + return Ty.list(new int[] {s}, false); + } + if (e instanceof TupleExpr && !anyStarred(((TupleExpr) e).elts)) { + TupleExpr tu = (TupleExpr) e; + int s = site(tu); + for (int i = 0; i < tu.elts.size(); i++) { + joinSlot(s, tu.elts.size(), i, type(tu.elts.get(i), fn, sc), true); + } + return Ty.tuple(new int[] {s}); + } + if (e instanceof NamedExpr) { + NamedExpr n = (NamedExpr) e; + Ty v = type(n.value, fn, sc); + storeName(n.target.id, v, fn, sc); + return v; + } + if (e instanceof Lambda) { + Lambda l = (Lambda) e; + FunctionDef d = lambdaDefs.get(l); + Fn inner = d == null ? null : fns.get(d); + if (inner == null) { + for (Expr x : l.args.defaults) { + escape(type(x, fn, sc)); + } + escape(type(l.body, null, l.scope)); + return Ty.OBJECT; + } + int first = inner.params.length - l.args.defaults.size(); + for (int i = 0; i < l.args.defaults.size(); i++) { + inner.params[first + i] = joinInto(inner.params[first + i], + type(l.args.defaults.get(i), fn, sc)); + } + if (p.reached.contains(d)) { + for (int i = 0; i < inner.params.length; i++) { + inner.locals.put(inner.names.get(i), mix(inner.locals.get(inner.names.get(i)), paramIn(inner, i))); + } + inner.ret = joinInto(inner.ret, type(l.body, inner, l.scope)); + } + return p.done ? Ty.OBJECT : funcValue(inner); + } + if (e instanceof Comp) { + Comp c = (Comp) e; + Fn savedOuter = compOuter; + if (fn != null) { + compOuter = fn; + } + try { + return comp(c, fn, sc); + } finally { + compOuter = savedOuter; + } + } + if (e instanceof JoinedStr) { + // An f-string: a str, whatever its fields format. + for (Expr x : ((JoinedStr) e).parts) { + type(x, fn, sc); + } + return Ty.STR; + } + if (e instanceof FormattedValue) { + // One field: its value goes to format(), which takes anything. + FormattedValue f = (FormattedValue) e; + escape(type(f.value, fn, sc)); + if (f.spec != null) { + type(f.spec, fn, sc); + } + return Ty.STR; + } + if (e instanceof Node.SetExpr) { + // A set, as `set(...)` makes one (see [#madeBuiltin]): its + // elements are hashed and compared, and go where a set's go. + for (Expr x : ((Node.SetExpr) e).elts) { + escape(type(x, fn, sc)); + } + return Ty.obj("set"); + } + if (e instanceof Yield && fn != null && sc == fn.def.scope) { //NOPMD CompareObjectsWithEquals - identity is meant + Yield y = (Yield) e; + Ty v = y.value == null ? Ty.NONE : type(y.value, fn, sc); + escape(v); + yieldInto(fn, y.from ? Ty.OBJECT : v); + return Ty.UNSEEN; + } + anyChildren(e, fn, sc); + return Ty.UNSEEN; + } + + /// The element type of each generator expression, as its last pass + /// typed it (see [Fn#yields]). + private final Map genElems = new IdentityHashMap(); + + private void yieldInto(Fn fn, Ty v) { + Ty r = Ty.join(fn.yields, v); + if (!r.equals(fn.yields)) { + fn.yields = r; + p.changed = true; + } + } + + /// The functions iterating `it` runs the body of: a method called on, + /// or a property read off, a name of one known class whose every + /// candidate is compiled here. Null when that is not known. + private List iterSources(Expr it, Fn fn, Scope sc) { + Expr recv; + String attr; + boolean call; + if (it instanceof Call && ((Call) it).func instanceof Name) { + String n = ((Name) ((Call) it).func).id; + Fn g = sc.resolve(n) == Scope.Binding.GLOBAL ? globalFns.get(n) : null; + // Only a generator's yields are what the loop gets: any other + // function returns an iterable of its own. + return g == null || !yieldsItems(g.def) ? null : java.util.Collections.singletonList(g); + } + if (it instanceof Call && ((Call) it).func instanceof Attribute) { + recv = ((Attribute) ((Call) it).func).value; + attr = ((Attribute) ((Call) it).func).attr; + call = true; + } else if (it instanceof Attribute) { + recv = ((Attribute) it).value; + attr = ((Attribute) it).attr; + call = false; + } else { + return null; + } + if (!(recv instanceof Name)) { + return null; + } + Ty r = selfRecv(recv, attr, fn, sc); + if (r.k != Ty.K.INST || r.opt || !closedFor(r.cls, attr)) { + return null; + } + List owners = new ArrayList(); + Layouts.Cls res = Layouts.resolver(r.cls, attr); + if (res == null) { + return null; + } + owners.add(res); + for (Layouts.Cls c : p.below(r.cls)) { + if (c.bodyNames.contains(attr)) { + owners.add(c); + } + } + List out = new ArrayList(); + for (Layouts.Cls c : owners) { + FunctionDef d = bodyDef(c, attr); + Fn f = d == null ? null : p.fns.get(d); + if (f == null || isProperty(d) == call || !yieldsItems(d)) { + return null; + } + out.add(f); + } + return out; + } + + /// Whether what `d` returns is a generator of its own yields: it is a + /// generator, or it returns only generator expressions. Any other + /// function returns an iterable whose items its yields do not say. + private static boolean yieldsItems(FunctionDef d) { + if (d.isAsync) { + return false; + } + if (d.scope.hasYield) { + return true; + } + boolean[] r = {false, false}; + genReturns(d.body, r); + return r[0] && !r[1]; + } + + /// Sets `r[0]` for a return of a generator expression, `r[1]` for any + /// other return, outside nested functions and classes. + private static void genReturns(Object o, boolean[] r) { + if (o instanceof Return) { + Expr v = ((Return) o).value; + if (v instanceof Comp && ((Comp) v).kind == Comp.Kind.GENERATOR) { + r[0] = true; + } else { + r[1] = true; + } + return; + } + if (o instanceof FunctionDef || o instanceof ClassDef || o instanceof Lambda) { + return; + } + Infer.children(o, x -> genReturns(x, r)); + } + + /// The function class `c`'s body binds `name` to, when its only binding + /// of the name is one `def` (a property's setter beside its getter is + /// left out); null for any other binding. + private static FunctionDef bodyDef(Layouts.Cls c, String name) { + FunctionDef r = null; + for (Stmt st : c.def.body) { + if (st instanceof FunctionDef && ((FunctionDef) st).name.equals(name)) { + FunctionDef d = (FunctionDef) st; + if (setterOrDeleter(d)) { + continue; + } + if (r != null) { + return null; + } + r = d; + } else if (binds(st, name)) { + return null; + } + } + return r; + } + + private static boolean setterOrDeleter(FunctionDef d) { + for (Expr x : d.decorators) { + if (x instanceof Attribute && ("setter".equals(((Attribute) x).attr) + || "deleter".equals(((Attribute) x).attr))) { + return true; + } + } + return false; + } + + /// The getter a read of property `attr` off a non-None `r` runs, when + /// it is one this module compiles and no compiled subclass of `r`'s + /// class overrides the name; null otherwise. + Fn propertyGetter(Ty r, String attr) { + if (r.k != Ty.K.INST || r.opt || !closedFor(r.cls, attr)) { + return null; + } + Layouts.Cls res = Layouts.resolver(r.cls, attr); + if (res == null || res.home != p.home.get(r.cls).layouts) { //NOPMD CompareObjectsWithEquals - identity is meant + return null; + } + for (Layouts.Cls c : p.below(r.cls)) { + if (c.bodyNames.contains(attr)) { + return null; + } + } + FunctionDef d = bodyDef(res, attr); + if (d == null || !isProperty(d) || d.decorators.size() != 1 + || !propertyBinding(((Name) d.decorators.get(0)).id, res.def.scope.parent)) { + return null; + } + return p.fns.get(d); + } + + /// Whether method `f`'s one decorator is the builtin `property` or + /// `classmethod` and its name is closed ([#closedName]): every call then + /// reaches it through a path that follows it -- a property read hands + /// the getter an instance of its class, a call of the name binds its + /// arguments to each method of that name (see [#duckCall]) -- and a read + /// of it as a value lets it go where that read is typed. + private boolean followedDescriptor(Fn f, Scope sc) { + if (f.cls == null || f.def.decorators.size() != 1 || !(f.def.decorators.get(0) instanceof Name)) { + return false; + } + String d = ((Name) f.def.decorators.get(0)).id; + return ("classmethod".equals(d) && sc.resolve(d) == Scope.Binding.BUILTIN || propertyBinding(d, sc)) + && closedName(f.def.name); + } + + /// The module-level alias of the builtin `property` a lowering + /// decorates with when the class body binds `property` itself + /// ([DeclarativeMap]); the alias is a module global no class body can + /// shadow, and the name is reserved to the compiler. + static final String PROPERTY_ALIAS = "_cn1_property"; + + /// Whether decorator name `d`, read in scope `sc`, is the builtin + /// `property`: the builtin itself, or the compiler's module-level alias. + private static boolean propertyBinding(String d, Scope sc) { + return "property".equals(d) ? sc.resolve(d) == Scope.Binding.BUILTIN + : PROPERTY_ALIAS.equals(d) && sc.resolve(d) == Scope.Binding.GLOBAL; + } + + private static boolean isProperty(FunctionDef d) { + for (Expr x : d.decorators) { + if (x instanceof Name && ("property".equals(((Name) x).id) || PROPERTY_ALIAS.equals(((Name) x).id))) { + return true; + } + } + return false; + } + + /// The function the comprehension being typed runs in, or null. + private Fn compOuter; + + /// The type of each name target of a comprehension, per comprehension + /// scope: what its iterable yields, joined over every pass. A target + /// only ever holds what its own clause binds, so this is exact; an + /// iterable whose elements are guesses binds OBJECT instead. + private final Map> compLocals = new IdentityHashMap>(); + + /// The type of comprehension target `n` of comprehension scope `sc`, or + /// null when `n` is not one. + Ty compLocal(Scope sc, String n) { + Map m = compLocals.get(sc); + return m == null ? null : loc(m.get(n)); + } + + /// The comprehension targets bound from guessed elements (see [#comp]), + /// by comprehension scope. + private final Map> guessedComp = new IdentityHashMap>(); + + /// Whether target `n` of comprehension scope `sc` holds a guess. + boolean guessedCompVar(Scope sc, String n) { + Set s = guessedComp.get(sc); + return s != null && s.contains(n); + } + + private final Map> compCells; + + /// Whether `n`, a cell of function scope `sc`, is captured only by + /// comprehensions: those run where they stand and cannot rebind it, so + /// it is a plain local as far as types go. + boolean compOnlyCell(Scope sc, String n) { + Set s = compCells.get(sc); + return s != null && s.contains(n); + } + + /// The cells of `d` that only comprehensions capture: every cell but + /// those a name inside a nested function, lambda or class mentions. + static Set compOnlyCells(FunctionDef d) { + Set out = new LinkedHashSet(d.scope.cells); + for (Stmt s : d.body) { + dropCaptured(s, out, false); + } + out.addAll(paramCells(d)); + return out; + } + + /// The cells of `d` that are positional parameters nothing ever stores + /// into -- not the body, not a nested scope through `nonlocal`, not + /// `del`. A closure reads one; its value is the argument for the whole + /// call, so as far as types go it is a plain local, and TypedEmit + /// keeps the cell beside it. + static Set paramCells(FunctionDef d) { + Set out = new LinkedHashSet(); + if (d.args.vararg != null || d.args.kwarg != null || !d.args.kwonly.isEmpty()) { + return out; + } + Map stores = TypedEmit.storeCounts(d.body); + for (String n : d.scope.cells) { + if (d.args.names().contains(n) && !stores.containsKey(n)) { + out.add(n); + } + } + return out; + } + + private static void dropCaptured(Object o, Set out, boolean inside) { + if (o instanceof Name && inside) { + out.remove(((Name) o).id); + } + if (o instanceof NamedExpr && !inside) { + // A walrus in a comprehension binds in the function. + out.remove(((NamedExpr) o).target.id); + } + boolean in = inside || o instanceof Lambda || o instanceof FunctionDef || o instanceof ClassDef; + children(o, x -> dropCaptured(x, out, in)); + } + + /// Generator expressions a typed list's `extend` runs to their end on + /// the spot (see [#extendedGenerator]): lowered as list comprehensions, + /// their elements are the list's, not escaped. + private final Set extendGens = java.util.Collections.newSetFromMap(new IdentityHashMap()); + + /// Whether the emitter lowers `g` as a list comprehension. + boolean extendsEagerly(Comp g) { + return extendGens.contains(g); + } + + /// The generator expression of `name.extend()`, when the + /// generator does not mention `name`: list.extend consumes it before + /// returning, so only a generator that reads the list being grown could + /// tell it from a list of the same items. Null otherwise. + static Comp extendedGenerator(Call c) { + if (!(c.func instanceof Attribute) || !"extend".equals(((Attribute) c.func).attr) + || !(((Attribute) c.func).value instanceof Name) || c.args.size() != 1 || !c.keywords.isEmpty() + || !(c.args.get(0) instanceof Comp) || ((Comp) c.args.get(0)).kind != Comp.Kind.GENERATOR) { + return null; + } + String n = ((Name) ((Attribute) c.func).value).id; + boolean[] seen = {false}; + mentions(c.args.get(0), n, seen); + return seen[0] ? null : (Comp) c.args.get(0); + } + + private static void mentions(Object o, String n, boolean[] seen) { + if (o instanceof Name && n.equals(((Name) o).id)) { + seen[0] = true; + return; + } + Infer.children(o, x -> mentions(x, n, seen)); + } + + private final Map narrowed = new IdentityHashMap(); + + /// The class the target of `g` is narrowed to by a filter + /// `isinstance(target, C)` of its own, or null. The emitter skips any + /// other element before binding the target (TypedEmit#compStore). + Layouts.Cls narrowedBy(Comprehension g) { + Layouts.Cls k = narrowed.get(g); + return k == null || !k.compiled ? null : k; + } + + /// The one compiled class `isinstance(n, C)` among the filters of `g` + /// names, or null. + private Layouts.Cls isinstanceFilter(Comprehension g, String n, Scope sc) { + for (Expr x : g.ifs) { + if (x instanceof Call && ((Call) x).func instanceof Name + && "isinstance".equals(((Name) ((Call) x).func).id) && ((Call) x).args.size() == 2 + && ((Call) x).keywords.isEmpty() && ((Call) x).args.get(0) instanceof Name + && n.equals(((Name) ((Call) x).args.get(0)).id) + && sc.resolve("isinstance") == Scope.Binding.BUILTIN) { + Ty ct = type(((Call) x).args.get(1), null, sc); + if (ct.k == Ty.K.CLS && !ct.opt && ct.sites.length == 1 && layoutHolds(classesOf(ct).get(0))) { + // Not for an extra base of another class, whose + // instances the filter passes and its Java class lacks. + return classesOf(ct).get(0); + } + } + } + return null; + } + + private Ty comp(Comp c, Fn fn, Scope sc) { + { + boolean first = true; + for (Comprehension g : c.generators) { + // The first iterable is evaluated in the enclosing scope. + boolean seen = guessSeen; + guessSeen = false; + Ty el = iterElem(g.iter, first ? fn : null, first ? sc : c.scope); + if (guessSeen) { + if (identityComp(c) && c.kind != Comp.Kind.DICT && c.kind != Comp.Kind.SET) { + // `(x for x in xs)` over a guessed list: what it + // yields is that guess, and every read of it checks + // one (a generator's yields are read as guesses, a + // list's site is marked below). bs4's Tag.children + // yielded objects, and markdownify's walk was untyped. + guessElt = el; + } else { + guessElt = null; + } + if (!shadow && el.k == Ty.K.INST && !el.opt && guessable(el) && g.target instanceof Name) { + // Held as a guess, as a for loop's target is: the + // typed slot while the element is of the class, the + // object beside it when not, and the expressions + // over it written both ways (TypedEmit#split). + // markdownify's `[self.process_element(el, ...) for + // el in children_to_convert]` was a generic call. + if (guessedComp.computeIfAbsent(c.scope, x -> new HashSet()) + .add(((Name) g.target).id)) { + p.changed = true; + } + } else { + escape(el); + el = Ty.OBJECT; + } + } + guessSeen |= seen; + first = false; + if (g.target instanceof Name && !g.isAsync) { + Map m = compLocals.computeIfAbsent(c.scope, x -> new HashMap()); + String n = ((Name) g.target).id; + Layouts.Cls nk = isinstanceFilter(g, n, c.scope); + if (nk != null && (el.wide() || el.k == Ty.K.INST)) { + // Only elements of that class get past the filter. + if (el.wide()) { + el = Ty.inst(nk, false); + } else { + Ty j = Ty.join(el, Ty.inst(nk, false)); + el = j.k == Ty.K.INST && j.cls == el.cls ? Ty.inst(nk, false) : el; //NOPMD CompareObjectsWithEquals - identity is meant + } + if (el.k == Ty.K.INST && el.cls == nk && narrowed.put(g, nk) == null) { //NOPMD CompareObjectsWithEquals - identity is meant + p.changed = true; + } + } + Ty was = m.get(n); + // The generic view holds every target as an object (see + // the reads in #nameType): what it meets is no evidence + // for the typed one's. + Ty now = shadow ? (was == null ? Ty.BOT : was) : joinInto(was, el); + if (shadow) { + escape(el); + } + if (!now.equals(was)) { + m.put(n, now); + p.changed = true; + } + } else { + escape(el); + } + store(g.target, Ty.OBJECT, null, null, c.scope); + for (Expr x : g.ifs) { + type(x, null, c.scope); + } + } + Ty elt = c.elt != null ? type(c.elt, null, c.scope) : Ty.OBJECT; + Ty ge = guessElt; + guessElt = null; + if (ge != null && !shadow && elt.wide()) { + elt = ge; + } + Set gc = guessedComp.get(c.scope); + if ((ge != null || gc != null && !gc.isEmpty()) && !shadow && c.kind != Comp.Kind.GENERATOR) { + // What the generic half puts there is whatever it met: a + // target that missed its guess computes the element over an + // object. + guessSites(new int[] {site(c)}); + } + if (c.kind != Comp.Kind.LIST && !extendGens.contains(c)) { + // A list comprehension's elements are its site's (below), + // an eagerly extended generator's the list's. + escape(elt); + } + if (c.value != null) { + escape(type(c.value, null, c.scope)); + } + if (c.kind == Comp.Kind.GENERATOR && !shadow) { + // The typed walk's: the generic view's yields are its own + // function's (see the Return in [#walk]). + Ty was = genElems.get(c); + genElems.put(c, was == null ? elt : Ty.join(was, elt)); + } + if (c.kind != Comp.Kind.LIST) { + return Ty.OBJECT; + } + // A list of the element type, its length unknown (unslotted). + int s = site(c); + if (unslotted.add(Integer.valueOf(s))) { + p.changed = true; + } + if (shadow && elt.wide()) { + // The generic view's elements are objects by construction: + // the site holds guesses, every read of it checked, rather + // than objects the typed view never puts there. + guessSites(new int[] {s}); + return Ty.list(new int[] {s}, false); + } + Ty j = joinInto(siteElem.get(s), elt); + if (!j.equals(siteElem.get(s))) { + siteElem.set(s, j); + p.changed = true; + } + return Ty.list(new int[] {s}, false); + } + } + + /// What a comprehension over a guessed iterable passes on unchanged + /// (see [#comp]), while its generators are walked. + private Ty guessElt; + + /// `[x for x in xs if c]` or `(x for x in xs)`: one generator, a name + /// target, the element itself (a filter only drops some). + private static boolean identityComp(Comp c) { + if (c.generators.size() != 1 || c.value != null) { + return false; + } + Comprehension g = c.generators.get(0); + return !g.isAsync && g.target instanceof Name && c.elt instanceof Name + && ((Name) g.target).id.equals(((Name) c.elt).id); + } + + /// Kinds whose comparisons always answer a bool: no user `__eq__`. + private boolean plainCompare(Ty t) { + switch (t.k) { + case BOT: + case NONE: + case BOOL: + case INT: + case FLOAT: + case STR: + return true; + case INST: + for (Layouts.Cls c = t.cls; c != null; c = c.parent) { + for (String d : new String[] {"__eq__", "__ne__", "__lt__", "__le__", "__gt__", "__ge__"}) { + if (c.bodyNames.contains(d)) { + return false; + } + } + } + return !anySubclassDefinesCompare(t.cls); + default: + return false; + } + } + + private boolean anySubclassDefinesCompare(Layouts.Cls k) { + for (Layouts.Cls c : selfAndBelow(k)) { + { + for (String d : new String[] {"__eq__", "__ne__", "__lt__", "__le__", "__gt__", "__ge__"}) { + if (c.bodyNames.contains(d)) { + return true; + } + } + } + } + return false; + } + + Ty attrType(Ty r, String attr) { + if (r.k == Ty.K.UNION) { + // Each type it may be answers for itself; None raises. + Ty t = Ty.BOT; + for (Ty m : r.members()) { + t = mix(t, attrType(m.nonNone(), attr)); + } + return t; + } + if (r.k == Ty.K.BOT || r.k == Ty.K.NONE) { + // Nothing reached the receiver yet, or None (which raises): no value. + // Nothing reached the receiver yet: a later round decides. + return Ty.BOT; + } + if (r.k == Ty.K.INST) { + Layouts.Cls o = fieldOwner(r.cls, attr); + if (o != null) { + Ty ft = fieldType(o, attr); + if (guarded(o, attr)) { + ft = guessRead(ft); + if (ft.k == Ty.K.LIST && ft.sites.length > 0 && !shadow) { + // Any list may be there, of whatever elements. + guessSites(ft.sites); + } + } + return ft; + } + Ty below = subclassField(r.cls, attr); + if (below != null) { + return below; + } + // A bound method, or something only a subclass has. + if (!r.opt && closedFor(r.cls, attr) && !classLevel(r.cls, attr)) { + List cand = candidates(r.cls, attr); + if (cand == null || cand.isEmpty()) { + // Overridden in another module: a call of the value goes + // through each one's door all the same. + cand = doorCandidates(r.cls, attr); + } + Ty mt = cand == null || cand.isEmpty() ? null : methValue(cand); + if (mt != null) { + return mt; + } + } + escapeMethods(attr); + return Ty.UNSEEN; + } + if (r.k == Ty.K.OBJ && !r.opt && "module".equals(r.name) && "__name__".equals(attr)) { + // Every module has its dotted name. + return Ty.STR; + } + // On None the read raises, so an optional class reads the same. + if (r.k == Ty.K.CLS && ("__name__".equals(attr) || "__qualname__".equals(attr) + || "__module__".equals(attr))) { + // What `type` keeps for every class; a layout's metaclass + // defines none of them (Layouts#plainMetaclass). + return Ty.STR; + } + if (r.k == Ty.K.CLS && !r.opt && r.sites.length == 0) { + return anyClassAttr(attr); + } + escape(r); + if (r.wide()) { + escapeMethods(attr); + } + return Ty.UNSEEN; + } + + /// A float `**` whose answer is real: `binop` cannot see the operands, + /// and a negative base to a fractional power answers a complex. The + /// exponent is integral, or the base is a sum of squares (`dx * dx + ...`) + /// or a non-negative constant. + static boolean realPow(BinOp b, Ty l, Ty r) { + boolean ln = l.k == Ty.K.FLOAT || l.k == Ty.K.INT || l.k == Ty.K.BOOL; + boolean rn = r.k == Ty.K.FLOAT || r.k == Ty.K.INT || r.k == Ty.K.BOOL; + if (!"**".equals(b.op) || l.opt || r.opt || !ln || !rn || l.k != Ty.K.FLOAT && r.k != Ty.K.FLOAT) { + return false; + } + return r.k != Ty.K.FLOAT && r.k != Ty.K.BOT || nonNegative(b.left); + } + + private static boolean nonNegative(Expr e) { + if (e instanceof Constant) { + Constant c = (Constant) e; + return (c.kind == Constant.Kind.INT || c.kind == Constant.Kind.FLOAT) && !c.text.startsWith("-"); + } + if (e instanceof BinOp) { + BinOp b = (BinOp) e; + if ("+".equals(b.op)) { + return nonNegative(b.left) && nonNegative(b.right); + } + if ("*".equals(b.op)) { + return b.left instanceof Name && b.right instanceof Name + && ((Name) b.left).id.equals(((Name) b.right).id) + || nonNegative(b.left) && nonNegative(b.right); + } + } + return false; + } + + static Ty binop(String op, Ty l, Ty r, Expr right) { + if (l.k == Ty.K.BOT || r.k == Ty.K.BOT) { + return Ty.BOT; + } + if (l.opt || r.opt) { + return Ty.UNSEEN; + } + boolean li = l.k == Ty.K.INT || l.k == Ty.K.BOOL; + boolean ri = r.k == Ty.K.INT || r.k == Ty.K.BOOL; + boolean lf = l.k == Ty.K.FLOAT; + boolean rf = r.k == Ty.K.FLOAT; + if (li && ri) { + switch (op) { + case "+": + case "-": + case "*": + case "//": + case "%": + case "&": + case "|": + case "^": + case "<<": + case ">>": + return Ty.INT; + case "/": + return Ty.FLOAT; + case "**": + // A negative exponent answers a float. + return right instanceof Constant && ((Constant) right).kind == Constant.Kind.INT ? Ty.INT + : Ty.OBJECT; + default: + return Ty.UNSEEN; + } + } + if ((lf || li) && (rf || ri)) { + switch (op) { + case "+": + case "-": + case "*": + case "/": + case "//": + case "%": + return Ty.FLOAT; + default: + // `**` of a negative float answers a complex. + return Ty.UNSEEN; + } + } + if (l.k == Ty.K.STR && r.k == Ty.K.STR && "+".equals(op)) { + return Ty.STR; + } + if ("*".equals(op) && (l.k == Ty.K.STR && (r.k == Ty.K.INT || r.k == Ty.K.BOOL) + || r.k == Ty.K.STR && (l.k == Ty.K.INT || l.k == Ty.K.BOOL))) { + // A str repeated is a str; a count too big for memory raises. + return Ty.STR; + } + if ((l.k == Ty.K.STR || l.k == Ty.K.BYTES) && "%".equals(op) && (right instanceof TupleExpr + || builtinOperand(r))) { + // str % value formats, or raises: no builtin type has an + // __rmod__ that takes a str. + return l.k == Ty.K.STR ? Ty.STR : Ty.BYTES; + } + return Ty.UNSEEN; + } + + /// Whether every type `t` may be is a builtin one, none of which has a + /// reflected operator taking a str or bytes on the left. + private static boolean builtinOperand(Ty t) { + switch (t.k) { + case NONE: + case INT: + case BOOL: + case FLOAT: + case STR: + case BYTES: + case LIST: + case TUPLE: + case DICT: + return true; + case UNION: + for (Ty m : t.members()) { + if (!builtinOperand(m)) { + return false; + } + } + return true; + default: + return false; + } + } + + private Ty call(Call c, Fn fn, Scope sc) { + if (!shadow) { + return builtinSig(c, call0(c, fn, sc), fn, sc); + } + boolean saved = shadowMiss; + shadowMiss = false; + Ty t = call0(c, fn, sc); + boolean miss = shadowMiss; + shadowMiss = saved; + // A call the guard sends to the callee's generic version has that + // version's result, which the result of a call of a known callee + // already joins (see [#retOf]). Anything else is not known. + return builtinSig(c, miss && !fnCallee(c, fn, sc) ? Ty.UNSEEN : t, fn, sc); + } + + /// Calls whose result [BuiltinSigs] types: the emitters convert the + /// generic result to that type. + final Set builtinCalls = java.util.Collections.newSetFromMap(new IdentityHashMap()); + + /// `t`, the type the pass gave call `c`, or what [BuiltinSigs] says the + /// Java builtin it calls returns when the pass knew nothing: a function + /// of a module the runtime writes in Java (`_cn1re.sub(...)`), a method + /// a class binds to one (`search = _cn1re.pattern_search`), or a + /// method of a builtin object (a match's `group`). + private Ty builtinSig(Call c, Ty t, Fn fn, Scope sc) { + if (t.k != Ty.K.OBJECT || !(c.func instanceof Attribute) || !c.keywords.isEmpty() + || sysModules(((Attribute) c.func).value, sc)) { + // `sys.modules.pop(name)` reads one module out by name (see + // [#call0]); typing its receiver here would read them all. + return t; + } + Attribute a = (Attribute) c.func; + List args = new ArrayList(); + for (Expr x : c.args) { + if (x instanceof Starred) { + return t; + } + args.add(type(x, fn, sc)); + } + String q = null; + if (a.value instanceof Name) { + String m = importedModule(((Name) a.value).id, sc); + if (m != null && p.modules.get(m) == null) { + q = m + "." + a.attr; + } + } + if (q == null) { + Ty r = type(a.value, fn, sc); + if (r.k == Ty.K.INST && !r.opt) { + q = classBuiltin(r.cls, a.attr); + args.add(0, r); + } else if (r.k == Ty.K.OBJ && !r.opt) { + q = r.name + "." + a.attr; + } + } + Ty s = q == null ? null : BuiltinSigs.ret(q, args, c); + if (s == null) { + return t; + } + builtinCalls.add(c); + return s; + } + + /// The module that `import m` (or `import m as n`) at the top of this + /// module binds to the global `n`, when nothing else binds it. + private String importedModule(String n, Scope sc) { + if (sc.resolve(n) != Scope.Binding.GLOBAL || body == null) { + return null; + } + String found = null; + for (Stmt s : body) { + if (s instanceof Import) { + for (Alias al : ((Import) s).names) { + if (n.equals(al.asname) || al.asname == null && n.equals(al.name)) { + if (found != null) { + return null; + } + found = al.name; + } + } + } else { + List bound = new ArrayList(); + boundIn(s, bound); + if (bound.contains(n)) { + return null; + } + } + } + return found; + } + + /// `module.function` when every instance of `k` finds `name` as a class + /// attribute bound to that function of a Java module + /// (`search = _cn1re.pattern_search`), so calling it on one calls the + /// function with the instance first. Null when a subclass may bind it + /// otherwise, or it is anything else. + private String classBuiltin(Layouts.Cls k, String name) { + Layouts.Cls o = Layouts.resolver(k, name); + if (o == null) { + return null; + } + for (Layouts.Cls s : p.home.keySet()) { + if (s != o && isSelfOrAncestor(k, s) && s.bodyNames.contains(name)) { //NOPMD CompareObjectsWithEquals - identity is meant + return null; + } + } + Infer home = p.home.get(o); + String q = null; + for (Stmt st : o.def.body) { + List bound = new ArrayList(); + boundIn(st, bound); + if (!bound.contains(name)) { + continue; + } + if (q != null || !(st instanceof Assign) || ((Assign) st).targets.size() != 1 + || !(((Assign) st).value instanceof Attribute) + || !(((Attribute) ((Assign) st).value).value instanceof Name) || home == null) { + return null; + } + Attribute v = (Attribute) ((Assign) st).value; + String m = home.importedModule(((Name) v.value).id, home.moduleScope); + if (m == null || p.modules.get(m) != null) { + return null; + } + q = m + "." + v.attr; + } + return q; + } + + /// Whether `c` runs only functions the pass knows: a method of a known + /// instance, or a function or bound method value, every result of + /// which is [#retOf]'s. + private boolean fnCallee(Call c, Fn fn, Scope sc) { + boolean saved = shadowMiss; + try { + if (c.func instanceof Attribute) { + Ty r = type(((Attribute) c.func).value, fn, sc); + String a = ((Attribute) c.func).attr; + if (r.k != Ty.K.INST || r.opt || !closedFor(r.cls, a) || classLevel(r.cls, a)) { + return false; + } + List cand = candidates(r.cls, a); + return cand != null && !cand.isEmpty(); + } + if (c.func instanceof Name) { + Ty ft = type(c.func, fn, sc); + return callableSet(ft); + } + return false; + } finally { + shadowMiss = saved; + } + } + + /// Whether `c` is `typing.cast(T, value)` -- imported from `typing` + /// by name or reached as `typing.cast`, bound once -- with a type + /// written as a name, attribute, subscript or string: the call answers + /// `value`, and typed code gives it `value`'s own type instead of what + /// every cast of the program joins to. Evaluating `T` has no effect + /// worth keeping, so it is not evaluated. bs4's `name_rules = + /// cast(List[TagNameMatchRule], list(...))` left the field untyped. + boolean isCast(Call c, Scope sc) { + if (c.args.size() != 2 || !c.keywords.isEmpty() || anyStarred(c.args)) { + return false; + } + Expr t = c.args.get(0); + if (!(t instanceof Name || t instanceof Attribute || t instanceof Subscript + || t instanceof Constant && ((Constant) t).kind == Constant.Kind.STR)) { + return false; + } + if (c.func instanceof Name) { + String n = ((Name) c.func).id; + Extern g = sc.resolve(n) == Scope.Binding.GLOBAL && stable(n) ? importedNames.get(n) : null; + return g != null && "cast".equals(g.name) && "typing".equals(g.module.moduleName); + } + if (c.func instanceof Attribute && ((Attribute) c.func).value instanceof Name + && "cast".equals(((Attribute) c.func).attr)) { + String n = ((Name) ((Attribute) c.func).value).id; + Infer m = sc.resolve(n) == Scope.Binding.GLOBAL ? moduleNames.get(n) : null; + return m != null && "typing".equals(m.moduleName); + } + return false; + } + + /// The compiled class `typing.cast(T, v)` names as `T`, when every + /// instance passing `isinstance(_, T)` has its Java layout, or null. + /// The typed emitter guards such a cast with that `isinstance` test + /// (Py.castChecked, TypeError on a mismatch), so the call answers a `T` + /// -- or None -- whatever `v` was inferred to be. + Layouts.Cls castClass(Call c, Scope sc) { + if (!isCast(c, sc) || !(c.args.get(0) instanceof Name)) { + return null; + } + Ty k = type(c.args.get(0), null, sc); + if (k.k != Ty.K.CLS || k.opt || k.sites.length != 1) { + return null; + } + Layouts.Cls o = classesOf(k).get(0); + // typing's classes (BinaryIO, TextIO, IO) describe a value, they + // are not what it is made as: markitdown's `cast(BinaryIO, + // BytesIO(...))` is a promise CPython never checks. + Infer home = p.home.get(o); + if (home != null && "typing".equals(home.moduleName)) { + return null; + } + return o.compiled && layoutHolds(o) ? o : null; + } + + /// The call [#call0] is typing, so [#callFn] can tell which argument + /// was a guess: no evidence of what the call passes there. + private Call curCall; + + private Ty call0(Call c, Fn fn, Scope sc) { + Call savedCall = curCall; + curCall = c; + try { + return call00(c, fn, sc); + } finally { + curCall = savedCall; + } + } + + private Ty call00(Call c, Fn fn, Scope sc) { + if (isCast(c, sc)) { + Ty v = type(c.args.get(1), fn, sc); + Layouts.Cls o = castClass(c, sc); + return o == null ? v : Ty.inst(o, v.nullable()); + } + if (c.func instanceof Attribute && sysModules(((Attribute) c.func).value, sc) && c.keywords.isEmpty() + && !c.args.isEmpty() && !anyStarred(c.args) + && MODULE_KEY_METHODS.contains(((Attribute) c.func).attr)) { + // `sys.modules.pop(name, None)`, `.get(name)`: the one module + // named, when the name is known (defusedxml's _get_py3_cls); + // every module when it is not. + String key = constString(c.args.get(0), fn, sc); + for (int i = 1; i < c.args.size(); i++) { + escape(type(c.args.get(i), fn, sc)); + } + type(c.args.get(0), fn, sc); + if (key == null) { + if (!p.allModulesLoose && !p.done) { + p.allModulesLoose = true; + p.changed = true; + } + } else { + Infer m = p.modules.get(key); + if (m != null && !p.done && p.looseModules.add(m)) { + p.changed = true; + } + } + return Ty.UNSEEN; + } + boolean simple = c.keywords.isEmpty() && !anyStarred(c.args); + if (c.func instanceof Name && ((Name) c.func).id.startsWith("$")) { + Ty t = missIntrinsic(((Name) c.func).id, c, fn, sc); + if (t != null) { + return t; + } + } + if (c.func instanceof Name && sc.resolve(((Name) c.func).id) == Scope.Binding.GLOBAL) { + String n = ((Name) c.func).id; + Fn f = globalFns.get(n); + Layouts.Cls k = globalClasses.get(n); + if (f == null && k == null) { + Object o = foreign(c.func, sc); + f = o instanceof Fn ? (Fn) o : null; + k = o instanceof Layouts.Cls ? (Layouts.Cls) o : null; + } + if (f != null || k != null) { + return callKnown(c, f, k, fn, sc, simple); + } + } + if (c.func instanceof Attribute && foreign(((Attribute) c.func).value, sc) instanceof Infer) { + // `module.f(...)`, `module.Cls(...)`. + Object o = foreign(c.func, sc); + if (o instanceof Fn || o instanceof Layouts.Cls) { + return callKnown(c, o instanceof Fn ? (Fn) o : null, + o instanceof Layouts.Cls ? (Layouts.Cls) o : null, fn, sc, simple); + } + } + return call1(c, fn, sc, simple); + } + + /// `c`'s arguments as one positional list for `d`'s parameters from + /// `from` on, its keywords bound to the parameters they name, or null + /// when they cannot be bound before the call runs. The list stops at + /// the last parameter given; a gap before it takes the parameter's + /// default, which must be a constant. Keywords must name parameters in + /// the order they are written, so the list evaluates in source order. + static List staticArgs(Call c, FunctionDef d, int from) { + return staticArgs(c, d, from, false); + } + + /// Whether calling `d` (from parameter `from` on) as `c` does always + /// raises TypeError: more positional arguments than parameters, a + /// keyword naming none, or a parameter without a default left out. + /// Whether every argument of `c` binds to a parameter at build time: no + /// `*` or `**` argument. Its keywords then bind by name, per callee. + private static boolean bindable(Call c) { + if (anyStarred(c.args)) { + return false; + } + for (Keyword kw : c.keywords) { + if (kw.arg == null) { + return false; + } + } + return true; + } + + static boolean raises(Call c, FunctionDef d, int from) { + Node.Arguments a = d.args; + if (hasStarred(c.args)) { + return false; + } + for (Keyword kw : c.keywords) { + if (kw.arg == null) { + return false; + } + } + int n = a.positional.size() - from; + if (n < 0) { + return true; + } + int k = c.args.size(); + if (k > n && a.vararg == null) { + return true; + } + Set given = new HashSet(); + for (Keyword kw : c.keywords) { + int idx = -1; + for (int j = Math.max(a.positionalOnly - from, 0); j < n; j++) { + if (a.positional.get(from + j).name.equals(kw.arg)) { + idx = j; + } + } + boolean kwOnly = false; + for (Node.Arg x : a.kwonly) { + kwOnly |= x.name.equals(kw.arg); + } + if (idx < 0 && !kwOnly && a.kwarg == null || idx >= 0 && idx < k) { + // Names nothing, or a parameter a positional one filled. + return true; + } + given.add(kw.arg); + } + int firstDefault = a.positional.size() - a.defaults.size(); + for (int j = k; j < n; j++) { + if (from + j < firstDefault && !given.contains(a.positional.get(from + j).name)) { + return true; + } + } + for (int j = 0; j < a.kwonly.size(); j++) { + if (a.kwDefaults.get(j) == null && !given.contains(a.kwonly.get(j).name)) { + return true; + } + } + return false; + } + + /// [#staticArgs], with `full` running the list to the last parameter. + static List staticArgs(Call c, FunctionDef d, int from, boolean full) { + if (c.keywords.isEmpty() && d.args.kwonly.isEmpty()) { + return c.args; + } + Node.Arguments a = d.args; + if (a.vararg != null || a.kwarg != null || hasStarred(c.args)) { + return null; + } + // Keyword-only parameters follow the positional ones, as in + // Arguments#names; with any, the list is always complete. + int np = a.positional.size() - from; + int n = np + a.kwonly.size(); + int k = c.args.size(); + if (np < 0 || n <= 0 || k > np) { + return null; + } + if (!a.kwonly.isEmpty()) { + full = true; + } + Expr[] slot = new Expr[n]; + for (int i = 0; i < k; i++) { + slot[i] = c.args.get(i); + } + int last = k - 1; + int first = Math.max(a.positionalOnly - from, 0); + for (Keyword kw : c.keywords) { + if (kw.arg == null) { + return null; + } + int idx = -1; + for (int j = first; j < np; j++) { + if (a.positional.get(from + j).name.equals(kw.arg)) { + idx = j; + break; + } + } + for (int j = 0; j < a.kwonly.size() && idx < 0; j++) { + if (a.kwonly.get(j).name.equals(kw.arg)) { + idx = np + j; + } + } + if (idx < 0 || slot[idx] != null || idx < last) { + return null; + } + slot[idx] = kw.value; + last = idx; + } + int firstDefault = a.positional.size() - a.defaults.size(); + List r = new ArrayList(); + int end = full ? n - 1 : last; + for (int j = 0; j <= end; j++) { + Expr e = slot[j]; + if (e == null) { + Expr dv; + if (j >= np) { + dv = a.kwDefaults.get(j - np); + } else { + int di = from + j - firstDefault; + dv = di < 0 ? null : a.defaults.get(di); + } + if (!(dv instanceof Constant)) { + return null; + } + e = dv; + } + r.add(e); + } + return r; + } + + /// The methods named `m` an instance of `k` may run, each with no + /// decorator and a typed body behind its door; null when one is not. + private List doorCandidates(Layouts.Cls k, String m) { + List owners = new ArrayList(); + Layouts.Cls res = Layouts.resolver(k, m); + if (res == null) { + return null; + } + owners.add(res); + for (Layouts.Cls c : p.below(k)) { + if (c.bodyNames.contains(m)) { + owners.add(c); + } + } + List r = new ArrayList(); + for (Layouts.Cls c : owners) { + if (c.home.fieldOwners.containsKey(m)) { + return null; + } + FunctionDef d = bodyDef(c, m); + if (d == null || !d.decorators.isEmpty() || d.isAsync || p.fns.get(d) == null + || Layouts.IMPLICIT_CLASS_LEVEL.contains(m)) { + return null; + } + if (!r.contains(d)) { + r.add(d); + } + } + return r; + } + + /// The argument each parameter of `d` (by its index in `f.names`) + /// gets from call `c`, the receiver aside: a call argument, or the + /// parameter's constant default. Null at a parameter whose value is not + /// known here (a default that is not a constant, `*args`, `**kwargs`); + /// `extra` collects what goes into those. Returns null when the call + /// does not bind (a starred argument, a keyword twice). + /// [#bindByName] with the call's first argument at parameter `first`: + /// 0 for an explicit `Cls.method(obj, ...)`. + private static Expr[] bindByName(Call c, FunctionDef d, Fn f, List extra, int first) { + Node.Arguments a = d.args; + Expr[] slot = new Expr[f.names.size()]; + boolean[] unknown = new boolean[slot.length]; + int np = a.positional.size(); + boolean spread = false; + for (int i = 0; i < c.args.size(); i++) { + Expr x = c.args.get(i); + if (x instanceof Starred || spread) { + // A sequence of unknown length: from here on no positional + // parameter is known, and the rest may reach `*args`. + if (!spread) { + for (int j = first + i; j < np; j++) { + unknown[j] = true; + } + spread = true; + } + if (a.vararg == null && first + i >= np && !(x instanceof Starred)) { + return null; + } + extra.add(x instanceof Starred ? ((Starred) x).value : x); + } else if (first + i < np) { + slot[first + i] = x; + } else if (a.vararg != null) { + extra.add(x); + } else { + return null; + } + } + for (Keyword kw : c.keywords) { + if (kw.arg == null) { + // `**kwargs`: any keyword parameter not given may come + // from it. + for (int j = first; j < slot.length; j++) { + unknown[j] |= slot[j] == null; + } + extra.add(kw.value); + continue; + } + int idx = f.names.indexOf(kw.arg); + boolean named = idx >= first && (idx < np && idx >= a.positionalOnly || isKwOnly(a, kw.arg)); + if (named) { + if (slot[idx] != null) { + return null; + } + slot[idx] = kw.value; + } else if (a.kwarg != null) { + extra.add(kw.value); + } else { + return null; + } + } + int firstDefault = np - a.defaults.size(); + for (int j = first; j < np; j++) { + if (slot[j] == null && !unknown[j] && j >= firstDefault && a.defaults.get(j - firstDefault) instanceof Constant) { + slot[j] = a.defaults.get(j - firstDefault); + } + } + for (int j = 0; j < a.kwonly.size(); j++) { + int idx = f.names.indexOf(a.kwonly.get(j).name); + Expr dv = a.kwDefaults.get(j); + if (slot[idx] == null && !unknown[idx] && dv instanceof Constant) { + slot[idx] = dv; + } + } + return slot; + } + + private static boolean isKwOnly(Node.Arguments a, String n) { + for (Node.Arg x : a.kwonly) { + if (x.name.equals(n)) { + return true; + } + } + return false; + } + + /// A call of method `m` on an instance of `k` that is not plain -- it + /// passes keywords, or the method takes keyword-only parameters, + /// defaults or `*args` -- made through each method's door: generic + /// code makes the call (TypedEmit), and each guard picks the typed body + /// when the arguments fit. What the call passes is what the parameters + /// hold; the receiver is not escaped. Null when a method it may run has + /// no such door, or the call does not bind. + private Ty doorCall(Call c, Layouts.Cls k, String m, Fn fn, Scope sc) { + List cand = doorCandidates(k, m); + return cand == null ? null : doorBound(c, cand, 1, fn, sc); + } + + /// [#doorCall] once the methods are known: `first` is the parameter + /// the call's first argument binds to. + private Ty doorBound(Call c, List cand, int first, Fn fn, Scope sc) { + List binds = new ArrayList(); + List extra = new ArrayList(); + for (FunctionDef d : cand) { + Expr[] s = bindByName(c, d, p.fns.get(d), extra, first); + if (s == null) { + return null; + } + binds.add(s); + } + Map seen = new IdentityHashMap(); + for (Expr x : c.args) { + Expr v = x instanceof Starred ? ((Starred) x).value : x; + seen.put(v, type(v, fn, sc)); + } + for (Keyword kw : c.keywords) { + seen.put(kw.value, type(kw.value, fn, sc)); + } + for (Expr x : extra) { + escape(seen.get(x)); + } + Ty ret = Ty.BOT; + for (int i = 0; i < cand.size(); i++) { + Fn f = p.fns.get(cand.get(i)); + reach(f); + Expr[] s = binds.get(i); + for (int j = first; j < s.length; j++) { + if (f.def.args.vararg != null && f.names.get(j).equals(f.def.args.vararg.name) + || f.def.args.kwarg != null && f.names.get(j).equals(f.def.args.kwarg.name)) { + continue; + } + Ty t = s[j] == null ? Ty.OBJECT : seen.containsKey(s[j]) ? seen.get(s[j]) : type(s[j], fn, sc); + if (shadow) { + if (f.params[j].k != Ty.K.BOT && !Ty.join(f.params[j], t).equals(f.params[j])) { + shadowMiss = true; + escape(t); + } + } else if (t.k == Ty.K.OBJECT && !nested(f) && (f.params[j].k == Ty.K.BOT || f.params[j].k == Ty.K.INST)) { + // No evidence, as in [#callFn]: the call is a door's. + objectArg(f, j); + } else { + f.params[j] = joinInto(f.params[j], t); + } + } + Fn g = generic.get(f.def); + ret = mix(ret, retOf(f, g == null ? f.ret : mix(f.ret, g.ret))); + } + doors.add(c); + return ret; + } + + /// [#staticArgs] for a call any of methods `cand` may answer: the one + /// list they all bind it to, or null when there is none or two of them + /// bind it differently. A gap a default fills must take equal constants + /// in every one. bs4's `self.match(i, _known_rules=True)`, which + /// ElementFilter and SoupStrainer both declare with that parameter. + static List sharedArgs(Call c, List cand) { + if (cand == null || cand.isEmpty()) { + return null; + } + List r = staticArgs(c, cand.get(0), 1, true); + for (int i = 1; r != null && i < cand.size(); i++) { + List o = staticArgs(c, cand.get(i), 1, true); + if (o == null || o.size() != r.size()) { + return null; + } + for (int j = 0; j < r.size(); j++) { + if (!sameArg(r.get(j), o.get(j))) { + return null; + } + } + } + return r; + } + + /// Whether every one of `cand` takes only positional parameters. + private static boolean positionalOnly(List cand) { + for (FunctionDef m : cand) { + if (!m.args.kwonly.isEmpty() || m.args.vararg != null || m.args.kwarg != null) { + return false; + } + } + return true; + } + + private static boolean sameArg(Expr a, Expr b) { + if (a == b) { //NOPMD CompareObjectsWithEquals - identity is meant + return true; + } + return a instanceof Constant && b instanceof Constant && ((Constant) a).kind == ((Constant) b).kind + && java.util.Objects.equals(((Constant) a).text, ((Constant) b).text); + } + + /// The `__init__` a call of class `k` runs, when it is typable. + private static FunctionDef typableInit(Layouts.Cls k) { + Layouts.Cls o = Layouts.resolver(k, "__init__"); + return o == null ? null : o.typable.get("__init__"); + } + + /// Set while the arguments of a construction of a class of our own + /// `typing` module escape: see [#callKnown]. + private boolean typingHeld; + + /// A call of function `f` or of class `k`, whichever is not null. + /// `typing`'s classes (TypeVar's `bound` and constraints, NewType's + /// base) keep a class they are given and never call it -- the module + /// is ours, and says so where it stores them -- so a class escaping + /// into one is loose but no root of instances ([#looseRoot]). bs4's + /// `TypeVar("_PageElementT", bound=PageElement)` made PageElement live + /// as itself, and every `else` of an isinstance test on one read a + /// PageElement. typing never calls what it holds, so the class value + /// is no root of the sweep's calls of a class nobody names either. + private Ty callKnown(Call c, Fn f, Layouts.Cls k, Fn fn, Scope sc, boolean simple) { + boolean saved = typingHeld; + Infer home = k == null ? null : p.home.get(k); + typingHeld = f == null && home != null && "typing".equals(home.moduleName); + try { + return callKnown0(c, f, k, fn, sc, simple); + } finally { + typingHeld = saved; + } + } + + private Ty callKnown0(Call c, Fn f, Layouts.Cls k, Fn fn, Scope sc, boolean simple) { + if (f == null && k != null && k.enumMeta) { + // A member lookup (Enum's value table), not a construction: + // the result is a member of the class (a Flag pseudo-member + // included) or what _missing_ answers, which must be one. Only + // the functional API (more arguments) makes a class. + boolean lookup = c.args.size() == 1 && c.keywords.isEmpty() && !(c.args.get(0) instanceof Starred); + for (Expr x : c.args) { + escape(type(x instanceof Starred ? ((Starred) x).value : x, fn, sc)); + } + for (Keyword kw : c.keywords) { + escape(type(kw.value, fn, sc)); + } + return lookup && k.compiled && !k.builtinOwn ? Ty.inst(k, false) : Ty.OBJECT; + } + constructs(k); + List given = c.args; + FunctionDef d = f != null ? f.def : typableInit(k); + if (!c.keywords.isEmpty() || d != null && !d.args.kwonly.isEmpty()) { + List b = d == null ? null : staticArgs(c, d, f != null ? 0 : 1); + if (b != null) { + given = b; + simple = true; + } else if (c.keywords.isEmpty()) { + // A keyword-only parameter no positional call can fill. + simple = false; + } + } + List args = new ArrayList(); + for (Expr a : given) { + if (a instanceof Starred) { + // Unpacked into positions the call cannot see: walked, so + // what it calls is reached, and escaped. + escape(type(((Starred) a).value, fn, sc)); + args.add(Ty.OBJECT); + } else { + args.add(type(a, fn, sc)); + } + } + if (given == c.args) { //NOPMD CompareObjectsWithEquals - identity is meant + for (Keyword kw : c.keywords) { + escape(type(kw.value, fn, sc)); + } + } + if (f != null) { + if (!callFn(f, args, 0, simple && args.size() <= f.params.length + && args.size() >= f.params.length - f.def.args.defaults.size(), true)) { + // Through the door: the typed version's result when the + // arguments turn out to fit, the generic body's when not. + siteRet.remove(c); + doors.add(c); + Fn g = generic.get(f.def); + return retOf(f, g == null ? f.ret : mix(f.ret, g.ret)); + } + // An expression function of this module's: typed + // code relabels the call's result (TypedEmit). + Ty site = !shadow && simple && args.size() == f.params.length + && p.fnHome.get(f) == this ? siteType(f, args) : null; //NOPMD CompareObjectsWithEquals - identity is meant + if (site != null) { + siteRet.put(c, site); + return retOf(f, site); + } + if (!shadow) { + siteRet.remove(c); + } + return retOf(f, f.ret); + } + if (open.contains(k)) { + for (Ty a : args) { + escape(a); + } + escapeClass(k); + return Ty.UNSEEN; + } + if (k.callConstructed()) { + // Constructed by calling the class (TypedEmit#construct), so + // BaseException's `__new__` sets `args`: its `__init__` runs + // through its door, on arguments that escape. + for (Ty a : args) { + escape(a); + } + Layouts.Cls io = Layouts.resolver(k, "__init__"); + FunctionDef idef = io == null ? null : io.typable.get("__init__"); + if (idef != null) { + escapeFn(p.fns.get(idef)); + } + return Ty.OBJECT; + } + Fn made = newMethod(k); + if (made != null) { + // The class's `__new__` makes the object (the call goes through + // the class: TypedEmit#construct), and `__init__` runs on it + // when it is an instance of the class. + List na = new ArrayList(); + na.add(classValue(k)); + na.addAll(args); + callFn(made, na, 0, simple && na.size() <= made.params.length + && na.size() >= made.params.length - made.def.args.defaults.size(), true); + Fn g = generic.get(made.def); + Ty r = retOf(made, g == null ? made.ret : mix(made.ret, g.ret)); + Layouts.Cls io = Layouts.resolver(k, "__init__"); + FunctionDef idef = io == null ? null : io.typable.get("__init__"); + if (idef != null) { + Fn fi = p.fns.get(idef); + if (!shadow) { + fi.params[0] = joinInto(fi.params[0], Ty.inst(k, false)); + } + callFn(fi, args, 1, simple && args.size() + 1 <= fi.params.length + && args.size() + 1 >= fi.params.length - idef.args.defaults.size(), true); + } + return r; + } + Layouts.Cls o = Layouts.resolver(k, "__init__"); + FunctionDef init = o == null ? null : o.typable.get("__init__"); + if (o != null && init == null) { + for (Ty a : args) { + escape(a); + } + return Ty.inst(k, false); + } + if (init != null) { + Fn fi = p.fns.get(init); + if (!shadow) { + fi.params[0] = joinInto(fi.params[0], Ty.inst(k, false)); + } + if (!callFn(fi, args, 1, simple && args.size() + 1 <= fi.params.length + && args.size() + 1 >= fi.params.length - init.args.defaults.size(), true) && !shadow) { + // An argument the typed __init__ cannot be sure of: the + // class is called generically, through the guard. + doors.add(c); + } + } else { + for (Ty a : args) { + escape(a); + } + } + return Ty.inst(k, false); + } + + private Ty call1(Call c, Fn fn, Scope sc, boolean simple) { + Ty fresh = builtinNew(c, fn, sc); + if (fresh != null) { + return fresh; + } + if (isMathCall(c, sc)) { + boolean numbers = true; + for (Expr x : c.args) { + Ty t = type(x, fn, sc); + numbers &= (t.k == Ty.K.INT || t.k == Ty.K.FLOAT) && !t.opt; + } + return numbers ? Ty.FLOAT : Ty.OBJECT; + } + if (!c.args.isEmpty() || c.func instanceof Attribute) { + List na = new ArrayList(); + for (Expr x : c.args) { + na.add(starArg(x, fn, sc)); + } + Ty nr = nativeRet(c, na, sc); + if (nr != null) { + nativeCalls.put(c, nr); + return nr; + } + nativeCalls.remove(c); + } + if (c.func instanceof Attribute && dictOwner(((Attribute) c.func).value, sc) != null) { + // A method of `x.__dict__`: a read leaves the attributes as + // they are, anything else may set or remove any of them. + Attribute a = (Attribute) c.func; + Expr owner = dictOwner(a.value, sc); + List args = new ArrayList(); + for (Expr x : c.args) { + args.add(starArg(x, fn, sc)); + } + for (Keyword kw : c.keywords) { + escape(type(kw.value, fn, sc)); + } + for (Ty t : args) { + escape(t); + } + Ty r = type(owner, fn, sc); + // A removal stores no value: no field gets a type it did not + // have (bs4's decompose clears every element's dict). + if (!DICT_READS.contains(a.attr) && !"clear".equals(a.attr) && !"pop".equals(a.attr) + && !"popitem".equals(a.attr)) { + boolean named = ("setdefault".equals(a.attr) || "__setitem__".equals(a.attr)) && c.args.size() == 2 + && !(c.args.get(0) instanceof Starred) && c.keywords.isEmpty(); + computedStore(r, owner, named ? c.args.get(0) : null, named ? args.get(1) : Ty.OBJECT, c, fn, sc); + } + return Ty.UNSEEN; + } + if (c.func instanceof Attribute && ("__setattr__".equals(((Attribute) c.func).attr) + || "__delattr__".equals(((Attribute) c.func).attr)) && c.keywords.isEmpty() && !anyStarred(c.args)) { + // `object.__setattr__(x, n, v)` and `x.__setattr__(n, v)`: + // setattr, past whatever the class defines for it. The call + // itself is typed as any other, below. + boolean set = "__setattr__".equals(((Attribute) c.func).attr); + int n = set ? 2 : 1; + if (c.args.size() == n + 1) { + computedStore(type(c.args.get(0), fn, sc), c.args.get(0), c.args.get(1), + set ? type(c.args.get(2), fn, sc) : Ty.OBJECT, c, fn, sc); + Expr owner = ((Attribute) c.func).value; + if (owner instanceof Name && "object".equals(((Name) owner).id) + && sc.resolve("object") == Scope.Binding.BUILTIN && !moduleScope.assigned.contains("object")) { + // The builtin's own store, which runs none of the + // program's code: the receiver goes nowhere else. + return Ty.NONE; + } + } else if (c.args.size() == n) { + Expr owner = ((Attribute) c.func).value; + boolean viaSuper = owner instanceof Call && ((Call) owner).func instanceof Name + && "super".equals(((Name) ((Call) owner).func).id); + if (!(viaSuper && p.plainSelf.contains(sc))) { + computedStore(viaSuper ? Ty.OBJECT : type(owner, fn, sc), owner, c.args.get(0), + set ? type(c.args.get(1), fn, sc) : Ty.OBJECT, c, fn, sc); + } + } + } + if (c.func instanceof Attribute) { + Fn sup = superTarget((Attribute) c.func, fn, sc); + if (sup != null) { + // `super().m(args)`: the parent's `m`, with self first. + List args = new ArrayList(); + args.add(nameType(fn.names.get(0), fn, sc)); + for (Expr x : c.args) { + args.add(starArg(x, fn, sc)); + } + for (Keyword kw : c.keywords) { + escape(type(kw.value, fn, sc)); + } + boolean exact = simple && c.keywords.isEmpty() && args.size() <= sup.params.length + && args.size() >= sup.params.length - sup.def.args.defaults.size(); + callFn(sup, args, 0, exact, false); + boolean local = p.fnHome.get(sup) == this; //NOPMD CompareObjectsWithEquals - identity is meant + if (exact && local && !shadow) { + p.superCalls.put(c, sup); + } + // Another module's method is called generically (its typed + // copy is that module's), and the generic body answers + // when the arguments miss the guard. + Fn g = local ? null : generic.get(sup.def); + return retOf(sup, g == null ? sup.ret : mix(sup.ret, g.ret)); + } + } + if (c.func instanceof Attribute) { + Attribute a = (Attribute) c.func; + if (calledClass(a.value, sc) != null) { + // `Cls.method(obj, ...)`: an explicit call of a method, of a + // class of this module or one imported (bs4's + // `Tag.__init__(self, ...)` in BeautifulSoup, whose Tag is + // bs4.element's: unresolved, it escaped every `__init__`). + Layouts.Cls k = calledClass(a.value, sc); + constructs(k); + Layouts.Cls o = Layouts.resolver(k, a.attr); + FunctionDef m = o == null ? null : o.typable.get(a.attr); + boolean plainCall = m != null && simple && c.keywords.isEmpty() && !hasStarred(c.args); + if (!plainCall && o != null && !open.contains(k)) { + FunctionDef dd = bodyDef(o, a.attr); + Ty t = dd == null || !dd.decorators.isEmpty() || dd.isAsync || p.fns.get(dd) == null + || Layouts.IMPLICIT_CLASS_LEVEL.contains(a.attr) || o.home.fieldOwners.containsKey(a.attr) + ? null : doorBound(c, java.util.Collections.singletonList(dd), 0, fn, sc); + if (t != null) { + return t; + } + } + List args = new ArrayList(); + for (Expr x : c.args) { + args.add(starArg(x, fn, sc)); + } + for (Keyword kw : c.keywords) { + escape(type(kw.value, fn, sc)); + } + if (m != null && !open.contains(k)) { + Fn f = p.fns.get(m); + boolean d = !callFn(f, args, 0, simple && args.size() <= f.params.length + && args.size() >= f.params.length - m.args.defaults.size(), true); + if (d) { + // An argument the typed version cannot be sure of: + // called as generic code calls it, through the + // method's guard (TypedEmit). + doors.add(c); + } + // As for super(): another module's method is called + // generically, and its generic body may answer. + Fn g = !d && p.fnHome.get(f) == this ? null : generic.get(m); //NOPMD CompareObjectsWithEquals - identity is meant + return retOf(f, g == null ? f.ret : mix(f.ret, g.ret)); + } + for (Ty t : args) { + escape(t); + } + if (m != null) { + escapeFn(p.fns.get(m)); + } + return Ty.UNSEEN; + } + if (foreign(a.value, sc) instanceof Infer) { + // `module.name(...)` of a name no direct call resolved: the + // value is called as any value is. The module itself is not + // passed anywhere, so it does not escape. + moduleMember(a, sc); + for (Expr x : c.args) { + escape(x instanceof Starred ? type(((Starred) x).value, fn, sc) : type(x, fn, sc)); + } + for (Keyword kw : c.keywords) { + escape(type(kw.value, fn, sc)); + } + return Ty.UNSEEN; + } + Ty r = selfRecv(a.value, a.attr, fn, sc); + if (r.k == Ty.K.INST && closedFor(r.cls, a.attr) && candidates(r.cls, a.attr) == null) { + Ty t = doorCall(c, r.cls, a.attr, fn, sc); + if (t != null) { + return t; + } + } + Comp eg = r.k == Ty.K.LIST && !r.opt ? extendedGenerator(c) : null; + if (eg != null && extendGens.add(eg)) { + p.changed = true; + } + Comp was = eg == null ? extendedGenerator(c) : null; + if (was != null && extendGens.contains(was)) { + // The list is no longer one this pass follows: what the + // generator gave it goes where the list went. + escape(genElems.get(was)); + } + List given = c.args; + if ((!c.keywords.isEmpty() || kwOnlyCandidate(r, a.attr)) && r.k == Ty.K.INST && closedFor(r.cls, a.attr)) { + // One method it can be: keywords bound to its parameters, + // keyword-only ones to their defaults. + List b = sharedArgs(c, candidates(r.cls, a.attr)); + if (b != null) { + given = b; + simple = true; + } + } + List args = new ArrayList(); + for (Expr x : given) { + args.add(starArg(x, fn, sc)); + } + if (given == c.args) { //NOPMD CompareObjectsWithEquals - identity is meant + for (Keyword kw : c.keywords) { + escape(type(kw.value, fn, sc)); + } + } + if (r.k == Ty.K.BOT || r.k == Ty.K.NONE) { + return Ty.BOT; + } + if (r.k == Ty.K.UNION) { + Ty ret = unionCall(c, r, a.attr, args, simple); + if (ret != null) { + return ret; + } + } + if (r.k == Ty.K.INST && closedFor(r.cls, a.attr)) { + List cand = candidates(r.cls, a.attr); + if (cand != null) { + Ty ret = Ty.BOT; + boolean door = false; + for (FunctionDef m : cand) { + // A call with keywords binds them at build time, + // and can be made generically as bound when every + // parameter is positional (TypedEmit.inlineDoor). + boolean d = !callFn(p.fns.get(m), args, 1, + simple && binds(p.fns.get(m), args.size() + 1), + c.keywords.isEmpty() || positionalOnly(cand)); + door |= d; + } + if (door) { + // Through the doors: the call is made as generic + // code makes it, and each method's guard picks the + // version that runs (TypedEmit). + doors.add(c); + } + for (FunctionDef m : cand) { + Fn f = p.fns.get(m); + Fn g = door ? generic.get(m) : null; + ret = mix(ret, retOf(f, g == null ? f.ret : mix(f.ret, g.ret))); + } + if (Layouts.resolver(r.cls, a.attr) == null) { + // Not every instance has it: the rest raise. + ret = mix(ret, Ty.BOT); + } + return ret; + } + } + if (r.k == Ty.K.LIST && !r.opt) { + Comp g = extendedGenerator(c); + if (g != null && extendGens.contains(g)) { + Ty ge = genElems.get(g); + storeElem(r, ge == null ? Ty.BOT : ge); + return Ty.NONE; + } + return listMethod(r, a.attr, args); + } + if (r.k == Ty.K.DICT && simple) { + Ty t = dictMethod(r, a.attr, args); + if (t != null) { + return t; + } + } + if (r.k == Ty.K.STR && !r.opt && splitCall(a.attr, args, c)) { + // A fresh list of strs, from a site of its own: the call. + int s = site(c); + siteJoin(s, Ty.STR); + if (unslotted.add(Integer.valueOf(s))) { + p.changed = true; + } + return Ty.list(new int[] {s}, false); + } + if (codecCall(r, a.attr, args, c)) { + return "encode".equals(a.attr) ? Ty.BYTES : Ty.STR; + } + if (r.k == Ty.K.STR && !r.opt && c.keywords.isEmpty() && !hasStarred(c.args)) { + Ty t = strMethod(a.attr, args); + if (t != null) { + for (Ty x : args) { + escape(x); + } + return t; + } + } + if (r.k == Ty.K.STR && !r.opt) { + Ty t = strResult(a.attr); + if (t != null) { + // Any other str method: its result is the same type + // whatever the arguments, or it raises. + for (Ty x : args) { + escape(x); + } + for (Keyword kw : c.keywords) { + escape(type(kw.value, fn, sc)); + } + return t; + } + } + if (r.k == Ty.K.INST && !r.opt && closedFor(r.cls, a.attr) && !plainReceiver(a.value, sc)) { + // `self.convert_s(...)` where the class body binds + // `convert_s` to a function a call made, or to another + // method under a second name: each function it is runs, + // bound to the instance. + Ty v = Layouts.resolver(r.cls, a.attr) == null || classAttr(r.cls, a.attr) + ? attrsNamed(r.cls, java.util.Collections.singletonList(a.attr), null) : null; + if (v != null && v.k == Ty.K.BOT) { + return Ty.BOT; + } + List fs = new ArrayList(); + if (v != null && callables(v.nonNone(), fs, new ArrayList())) { + Ty t = callThrough(c, v, fn, sc); + if (t != null) { + return t; + } + // Starred: each is entered with what it is given. + for (Expr x : c.args) { + escape(type(x instanceof Starred ? ((Starred) x).value : x, fn, sc)); + } + for (Keyword kw : c.keywords) { + escape(type(kw.value, fn, sc)); + } + Ty ret = Ty.BOT; + for (Fn f : fs) { + escapeFn(f); + ret = mix(ret, retOf(f, f.ret)); + } + return ret; + } + } + if (r.k == Ty.K.INST && closedFor(r.cls, a.attr) && Layouts.resolver(r.cls, a.attr) == null + && p.home.get(r.cls).layouts.fieldOwners.containsKey(a.attr)) { + // `self.match_function(element)`: a function held in a + // field. The call gets the field's value, not the + // instance, so only the value and the arguments escape. + escape(attrType(r, a.attr)); + for (Ty t : args) { + escape(t); + } + return Ty.UNSEEN; + } + if (r.k == Ty.K.INST && closedFor(r.cls, a.attr) && classLevel(r.cls, a.attr)) { + // A classmethod or staticmethod: the instance is not + // passed, only its class (or nothing), so it does not + // escape. bs4's `self._make_match_rules(...)` in + // SoupStrainer.__init__ made every field of SoupStrainer + // untyped. + for (Ty t : args) { + escape(t); + } + return Ty.UNSEEN; + } + if (r.wide() && "__init__".equals(a.attr) && objectInit(a.value, sc)) { + // `LTText.__init__(self)` for a class of this module that + // nothing in its MRO gives an `__init__`: object's, which + // does nothing with its arguments. + for (Ty t : args) { + escape(t); + } + for (Keyword kw : c.keywords) { + escape(type(kw.value, fn, sc)); } + return Ty.NONE; } - } - return r.isEmpty() ? null : r; - } - - private void anyChildren(Object o, Fn fn, Scope sc) { - children(o, x -> { - if (x instanceof Expr) { - escape(type((Expr) x, fn, sc)); - } else if (x instanceof Stmt) { - walk((Stmt) x, fn, sc); - } else { - anyChildren(x, fn, sc); + Ty unbound = unboundCall(c, a, args, simple, fn, sc); + if (unbound != null) { + return unbound; } - }); - } - - // ---- expressions ----------------------------------------------------- - - Ty nameType(String n, Fn fn, Scope sc) { - switch (sc.resolve(n)) { - case LOCAL: - if (fn != null && sc == fn.def.scope) { //NOPMD CompareObjectsWithEquals - identity is meant - Ty t = fn.locals.get(n); - return t == null ? Ty.BOT : t; + // `ValueError.__init__(self, msg)`: a builtin, unshadowed, runs + // none of the program's methods, whatever its value is typed. + boolean builtinRecv = a.value instanceof Name && sc.resolve(((Name) a.value).id) == Scope.Binding.BUILTIN + && !moduleScope.assigned.contains(((Name) a.value).id); + boolean duck = (r.wide() || r.k == Ty.K.INST) && !superBuiltin(a, fn, sc) && !builtinRecv; + // A keyword reaches an answering __getattr__'s value unseen. + boolean slot = duck && closedName(a.attr) && bindable(c) && (c.keywords.isEmpty() || !answeringLive(r)); + if (!slot) { + if (!superWithin(a, fn, sc)) { + escape(r); } - return Ty.DYN; - case GLOBAL: { - Fn f = globalFns.get(n); - if (f != null) { - escapeFn(f); - return Ty.DYN; + for (Ty t : args) { + escape(t); } - Layouts.Cls k = globalClasses.get(n); - if (k != null) { - escapeClass(k); - return Ty.DYN; + } + Ty ret = Ty.OBJECT; + if (duck) { + superClass = superOf(a, fn, sc); + superCall = a.value instanceof Call && ((Call) a.value).func instanceof Name + && "super".equals(((Name) ((Call) a.value).func).id) + && sc.resolve("super") == Scope.Binding.BUILTIN && !moduleScope.assigned.contains("super"); + try { + slotDuck = slot; + duckBound = receiverBound(a.value, fn); + ret = duckCall(r, a.attr, args, simple && c.keywords.isEmpty(), bindable(c) ? c : null, fn, sc); + if (slot) { + ret = mix(ret, answeredCall(r, args, simple && c.keywords.isEmpty(), fn, sc)); + } + } finally { + superClass = null; + superCall = false; + slotDuck = false; + duckBound = null; } - Ty t = globals.get(n); - return t == null ? Ty.BOT : t; } - default: - return Ty.DYN; - } - } - - Ty type(Expr e, Fn fn, Scope sc) { - if (e instanceof Constant) { - switch (((Constant) e).kind) { - case NONE: - return Ty.NONE; - case TRUE: - case FALSE: - return Ty.BOOL; - case INT: - return Ty.INT; - case FLOAT: - return ((Constant) e).text.endsWith("j") || ((Constant) e).text.endsWith("J") ? Ty.DYN - : Ty.FLOAT; - case STR: - return Ty.STR; - default: - return Ty.DYN; + // Only the program's methods answer a closed name: the call's + // value is what they return (none: it raises AttributeError). + if (slot && p.slotCalls.add(c)) { + p.changed = true; } + return slot ? ret : Ty.UNSEEN; } - if (e instanceof Name) { - return nameType(((Name) e).id, fn, sc); - } - if (e instanceof Attribute) { - Attribute a = (Attribute) e; - if (MATH_CONSTS.contains(a.attr) && isMath(a.value, sc)) { - return Ty.FLOAT; + if (c.func instanceof Name && sc.resolve(((Name) c.func).id) == Scope.Binding.BUILTIN + && !moduleScope.hasStarImport) { + String n = ((Name) c.func).id; + List args = new ArrayList(); + for (Expr x : c.args) { + if ("super".equals(n) && args.isEmpty() && c.args.size() == 2 && x instanceof Name + && sc.resolve(((Name) x).id) == Scope.Binding.GLOBAL + && globalClasses.get(((Name) x).id) != null) { + // `super(K, obj)`'s K is looked up, never held: not a + // class value (see [#classValue]), which would make K + // constructible by whoever holds it. + args.add(Ty.cls(new int[0])); + continue; + } + args.add(starArg(x, fn, sc)); } - if (a.value instanceof Name && globalClasses.containsKey(((Name) a.value).id) - && sc.resolve(((Name) a.value).id) == Scope.Binding.GLOBAL) { - // `Cls.attr` as a value: a method taken off the class runs - // with arguments nobody tracks. - escapeMethods(a.attr); - return Ty.DYN; + for (Keyword kw : c.keywords) { + escape(type(kw.value, fn, sc)); } - Ty r = type(a.value, fn, sc); - return attrType(r, a.attr); - } - if (e instanceof Call) { - return call((Call) e, fn, sc); - } - if (e instanceof BinOp) { - BinOp b = (BinOp) e; - Ty l = type(b.left, fn, sc); - Ty r = type(b.right, fn, sc); - if ("*".equals(b.op) && b.left instanceof ListExpr && l.k == Ty.K.LIST) { - return Ty.list(l.sites, false); + if (("setattr".equals(n) || "delattr".equals(n) || "hasattr".equals(n)) && c.args.size() >= 2 + && !(c.args.get(1) instanceof Constant) + // `hasattr(self, "do_" + op)` asks the same table of the + // class's own methods a getattr through that name reads. + && !("hasattr".equals(n) && args.get(0).k == Ty.K.INST && !args.get(0).opt + && !plainReceiver(c.args.get(0), sc) + && methodsNamed(args.get(0).cls, c.args.get(1), fn, sc) != null)) { + reflection(n, c.args.get(1), fn, sc); } - if ("+".equals(b.op) && l.k == Ty.K.LIST && r.k == Ty.K.LIST) { - int s = site(b); - siteElem.set(s, joinInto(siteElem.get(s), Ty.join(elem(l), elem(r)))); - return Ty.list(new int[] {s}, false); + if ("setattr".equals(n) && c.args.size() == 3 && c.keywords.isEmpty()) { + computedStore(args.get(0), c.args.get(0), c.args.get(1), args.get(2), c, fn, sc); + } else if ("delattr".equals(n) && c.args.size() == 2 && c.keywords.isEmpty() + && !(c.args.get(1) instanceof Constant)) { + // Whichever attribute it was is gone: no type holds for it. + computedStore(args.get(0), c.args.get(0), c.args.get(1), Ty.OBJECT, c, fn, sc); + } else if ("vars".equals(n) && c.args.size() == 1 && c.keywords.isEmpty() + && !(c.args.get(0) instanceof Starred)) { + dictOf(c, c.args.get(0), fn, sc); + } else if ("type".equals(n) && c.args.size() == 1 && c.keywords.isEmpty() + && !(c.args.get(0) instanceof Starred)) { + Ty known = classesBelow(args.get(0)); + if (known != null) { + // One of the compiled classes at or below the static + // one: a construction through it is tracked + // (#constructAny), so nothing escapes. + return known; + } + if (args.get(0).wide() || args.get(0).k == Ty.K.INST) { + // Any class at all. Reading its name, comparing it and + // testing with it make nothing of it; what does -- a + // call, a store, passing it where it is not followed -- + // is an escape of it (#escape), and only then is every + // loose class taken to be constructible (#anyClass). + if (args.get(0).k == Ty.K.INST) { + // As for `x.__class__` above. + loosen(args.get(0).cls); + } + return Ty.cls(new int[0]); + } + classOf(c, c.args.get(0), fn, sc); + } else if ("getattr".equals(n) && c.args.size() >= 2 && c.keywords.isEmpty() + && !(c.args.get(1) instanceof Constant)) { + Ty found = args.get(0).k == Ty.K.INST && !args.get(0).opt && !plainReceiver(c.args.get(0), sc) + ? methodsNamed(args.get(0).cls, c.args.get(1), fn, sc) : null; + if (found == null) { + reflection("getattr", c.args.get(1), fn, sc); + } + if (found != null) { + // The methods the name can be, as bound methods: a call + // through the result is followed to each of them. + return args.size() == 3 ? mix(found, args.get(2)) : found; + } + computedRead(args.get(0), c.args.get(0), c.args.get(1), c, fn, sc); } - if (l.k == Ty.K.BOT || r.k == Ty.K.BOT) { - return Ty.BOT; + if (simple && args.size() == 1 && ("len".equals(n) || "isinstance".equals(n) && false)) { + // len reads its argument and keeps nothing. + if (args.get(0).k != Ty.K.LIST && args.get(0).k != Ty.K.TUPLE && args.get(0).k != Ty.K.DICT) { + escape(args.get(0)); + } + return Ty.INT; } - Ty t = binop(b.op, l, r, b.right); - if (t.k == Ty.K.DYN) { - escape(l); - escape(r); + if (simple && "float".equals(n) && args.size() == 1 + && (args.get(0).k == Ty.K.INT || args.get(0).k == Ty.K.FLOAT) && !args.get(0).opt) { + return Ty.FLOAT; } - return t; - } - if (e instanceof UnaryOp) { - UnaryOp u = (UnaryOp) e; - Ty t = type(u.operand, fn, sc); - if ("not".equals(u.op)) { - return Ty.BOOL; + if (simple && "str".equals(n) && args.size() == 1 && !args.get(0).opt + && (args.get(0).k == Ty.K.INT || args.get(0).k == Ty.K.FLOAT + || args.get(0).k == Ty.K.STR || args.get(0).k == Ty.K.BOOL)) { + return Ty.STR; } - if (t.k == Ty.K.BOT) { + if (simple && args.size() == 1 && args.get(0).k == Ty.K.BOT + && ("ord".equals(n) || "abs".equals(n) || "float".equals(n) || "str".equals(n))) { + // Nothing reaches the argument yet: a later pass decides, + // where OBJECT now would stay OBJECT for good. return Ty.BOT; } - if (t.k == Ty.K.FLOAT && !t.opt) { - return Ty.FLOAT; - } - if ((t.k == Ty.K.INT || t.k == Ty.K.BOOL) && !"+".equals(u.op)) { + if (simple && "ord".equals(n) && args.size() == 1 && args.get(0).k == Ty.K.STR && !args.get(0).opt) { return Ty.INT; } - if (t.k == Ty.K.INT && "+".equals(u.op)) { - return Ty.INT; + if (simple && "abs".equals(n) && args.size() == 1 && !args.get(0).opt + && (args.get(0).k == Ty.K.INT || args.get(0).k == Ty.K.FLOAT)) { + return args.get(0); } - escape(t); - return Ty.DYN; - } - if (e instanceof BoolOp) { - Ty r = Ty.BOT; - for (Expr v : ((BoolOp) e).values) { - r = Ty.join(r, type(v, fn, sc)); + if (simple && "list".equals(n) && args.size() == 1) { + int s = site(c); + Ty t = args.get(0); + boolean range = rangeCall(c.args.get(0), sc); + siteJoin(s, t.k == Ty.K.LIST ? elem(t) : range ? Ty.INT : Ty.OBJECT); + if (t.k != Ty.K.LIST && !rangeCall(c.args.get(0), sc)) { + escape(t); + } + return Ty.list(new int[] {s}, false); } - return r; - } - if (e instanceof Compare) { - Compare c = (Compare) e; - Ty l = type(c.left, fn, sc); - boolean plain = true; - for (int i = 0; i < c.ops.size(); i++) { - Ty r = type(c.comparators.get(i), fn, sc); - String op = c.ops.get(i); - if (!("is".equals(op) || "is not".equals(op) || "in".equals(op) || "not in".equals(op) - || plainCompare(l) && plainCompare(r))) { - plain = false; + if ("type".equals(n) && args.size() == 1 && simple) { + // type(x) reads x's class (classOf answers for the class); + // x itself goes nowhere. + return Ty.UNSEEN; + } + if ("dict".equals(n) && args.size() <= 1 && !anyStarred(c.args)) { + Ty t = Ty.dict(new int[] {site(c)}); + if (args.size() == 1) { + Ty a0 = args.get(0); + if (a0.k == Ty.K.DICT && a0.sites.length > 0) { + storeDict(t, dictKeyOf(a0), dictVal(a0)); + } else { + escape(a0); + storeDict(t, Ty.OBJECT, Ty.OBJECT); + } } - if ("in".equals(op) || "not in".equals(op)) { - escape(r); - escape(l); + for (Keyword kw : c.keywords) { + if (kw.arg == null) { + Ty kt = type(kw.value, fn, sc); + storeDict(t, kt.k == Ty.K.DICT ? dictKeyOf(kt) : Ty.OBJECT, kt.k == Ty.K.DICT ? dictVal(kt) : Ty.OBJECT); + } else { + storeDict(t, Ty.STR, type(kw.value, fn, sc)); + } } - l = r; + return t; } - return plain ? Ty.BOOL : Ty.DYN; - } - if (e instanceof IfExp) { - IfExp i = (IfExp) e; - type(i.test, fn, sc); - return Ty.join(type(i.body, fn, sc), type(i.orelse, fn, sc)); - } - if (e instanceof Subscript) { - Subscript s = (Subscript) e; - Ty r = type(s.value, fn, sc); - if (s.index instanceof Slice) { - anyChildren(s.index, fn, sc); - if (r.k == Ty.K.LIST && !r.opt) { - return Ty.list(r.sites, false); + String made = madeBuiltin(n); + if (made != null) { + boolean reads0 = READ_ONLY_BUILTINS.contains(n); + for (Ty t : args) { + escape(reads0 && t.k == Ty.K.LIST ? elem(t) : t); } - escape(r); - return Ty.DYN; + return Ty.obj(made); } - Ty i = type(s.index, fn, sc); - if (r.k == Ty.K.BOT || r.k == Ty.K.NONE || i.k == Ty.K.BOT) { - return Ty.BOT; + boolean reads = simple && READ_ONLY_BUILTINS.contains(n); + if ("hasattr".equals(n) && args.size() == 2 && c.keywords.isEmpty() + && args.get(0).k == Ty.K.CLS && !args.get(0).opt && args.get(0).sites.length == 0 + && c.args.get(1) instanceof Constant && ((Constant) c.args.get(1)).kind == Constant.Kind.STR) { + // `hasattr(cls, "__deepcopy__")` reads the attribute and + // drops it. + anyClassAttr(((Constant) c.args.get(1)).text); + return Ty.BOOL; } - if (r.k == Ty.K.LIST && (i.k == Ty.K.INT || i.k == Ty.K.BOOL)) { - return elem(r); + if ("getattr".equals(n) && args.size() == 2 && c.keywords.isEmpty() && args.get(0).k == Ty.K.INST + && c.args.get(1) instanceof Constant && ((Constant) c.args.get(1)).kind == Constant.Kind.STR + && ConstArgSpecialize.ident(((Constant) c.args.get(1)).text) + && !((Constant) c.args.get(1)).text.startsWith("__")) { + // `getattr(x, "name")` is `x.name`: typed as that read, so a + // list it answers and something appends to widens the field + // it came from, as `x.name.append(v)` does. + Attribute same = literalGetattr.get(c); + if (same == null) { + same = new Attribute(c.args.get(0), ((Constant) c.args.get(1)).text).at(c.line, c.col); + literalGetattr.put(c, same); + } + return type(same, fn, sc); } - escape(r); - escape(i); - return Ty.DYN; - } - if (e instanceof ListExpr) { - ListExpr l = (ListExpr) e; - int s = site(l); - for (Expr x : l.elts) { - if (x instanceof Starred) { - Ty t = type(((Starred) x).value, fn, sc); - siteElem.set(s, joinInto(siteElem.get(s), t.k == Ty.K.LIST ? elem(t) : Ty.DYN)); + if ("getattr".equals(n) && (args.size() == 2 || args.size() == 3) && c.keywords.isEmpty() + && args.get(0).k == Ty.K.CLS && !args.get(0).opt && args.get(0).sites.length == 0 + && c.args.get(1) instanceof Constant && ((Constant) c.args.get(1)).kind == Constant.Kind.STR) { + // `getattr(cls, "__copy__", None)`: an attribute read. + if (args.size() == 3) { + escape(args.get(2)); + } + return anyClassAttr(((Constant) c.args.get(1)).text); + } + if (("isinstance".equals(n) || "issubclass".equals(n)) && args.size() == 2) { + // The class only answers a test; nothing holds or calls it. + // An instance is only asked its type, unless a class it may + // be answers `__class__` itself. + if (args.get(0).k != Ty.K.CLS && !(args.get(0).k == Ty.K.INST && !ownClassAttr(args.get(0).cls))) { + escape(args.get(0)); + } + return Ty.BOOL; + } + if ("super".equals(n) && args.size() == 2 && args.get(0).k == Ty.K.CLS) { + // `super(K, obj)` only looks K up in obj's MRO: the class + // goes nowhere. Escaping it escaped K's own constructor + // from inside that constructor, and kept it walked. + // Neither does an instance of K when every class above K + // is known: a super object stores no attribute and reads + // none of the instance's, so all it can do with obj is run + // one of those classes' methods on it, each through its + // own guard when the pass does not follow the call. + Ty o = args.get(1); + List ks = classesOf(args.get(0)); + boolean known = o.k == Ty.K.INST && !o.opt && ks.size() == 1 + && isSelfOrAncestor(ks.get(0), o.cls) && chainKnown(ks.get(0)); + if (!known) { + escape(o); + } + return Ty.UNSEEN; + } + Ty lowered = anyStarred(c.args) ? null : builtinValue(n, c, args, fn, sc); + if (lowered != null) { + return lowered; + } + Ty fixed = fixedReturn(n); + if (fixed != null) { + for (Ty t : args) { escape(t); - } else { - siteElem.set(s, joinInto(siteElem.get(s), type(x, fn, sc))); } + return fixed; } - return Ty.list(new int[] {s}, false); + for (Ty t : args) { + // These iterate a list and never write it: only what it holds + // leaves. Escaping the list itself made bs4's + // `reversed(self.contents)` untype every tag's children. + escape(reads && t.k == Ty.K.LIST ? elem(t) : t); + } + return Ty.UNSEEN; } - if (e instanceof NamedExpr) { - NamedExpr n = (NamedExpr) e; - Ty v = type(n.value, fn, sc); - storeName(n.target.id, v, fn, sc); - return v; + Ty ft = type(c.func, fn, sc); + if (ft.k == Ty.K.CLS && !ft.opt && ft.sites.length > 0) { + return constructAny(c, ft, fn, sc, simple); } - if (e instanceof Lambda) { - Lambda l = (Lambda) e; - for (Expr d : l.args.defaults) { - escape(type(d, fn, sc)); - } - escape(type(l.body, null, l.scope)); - return Ty.DYN; + Ty through = callThrough(c, ft, fn, sc); + if (through != null) { + return through; } - if (e instanceof Comp) { - Comp c = (Comp) e; - boolean first = true; - for (Comprehension g : c.generators) { - // The first iterable is evaluated in the enclosing scope. - escape(type(g.iter, first ? fn : null, first ? sc : c.scope)); - first = false; - store(g.target, Ty.DYN, null, null, c.scope); - for (Expr x : g.ifs) { - type(x, null, c.scope); + // Called in a way the pass does not bind (starred arguments, a union + // of callables): the functions it may be are entered from anywhere. + escapeFuncs(ft); + if (ft.k == Ty.K.INST && !ft.opt && closedFor(ft.cls, "__call__") && !anyStarred(c.args)) { + // `soup(["script"])`: the class's `__call__`, as `soup.__call__(...)`. + List cand = candidates(ft.cls, "__call__"); + if (cand != null && !cand.isEmpty()) { + List args = new ArrayList(); + args.add(ft); + for (Expr x : c.args) { + args.add(type(x, fn, sc)); + } + for (Keyword kw : c.keywords) { + escape(type(kw.value, fn, sc)); + } + Ty ret = Ty.BOT; + for (FunctionDef m : cand) { + Fn f = p.fns.get(m); + callFn(f, args, 0, simple && c.keywords.isEmpty() && binds(f, args.size()), true); + ret = mix(ret, retOf(f, f.ret)); } + doors.add(c); + return ret; + } + Ty viaDoor = doorCall(c, ft.cls, "__call__", fn, sc); + if (viaDoor != null) { + return viaDoor; + } + } + escape(ft); + for (Expr x : c.args) { + escape(type(x instanceof Starred ? ((Starred) x).value : x, fn, sc)); + } + for (Keyword kw : c.keywords) { + escape(type(kw.value, fn, sc)); + } + return Ty.UNSEEN; + } + + /// The hidden calls of a miss probe (`Parser.missProbe`): the probe is + /// the lookup or a marker, the re-read is the lookup. + private Ty missIntrinsic(String n, Call c, Fn fn, Scope sc) { + switch (n) { + case "$probe": + escape(type(c.args.get(0), fn, sc)); + return Ty.OBJECT; + case "$unmiss": + type(c.args.get(0), fn, sc); + return type(c.args.get(1), fn, sc); + case "$ismiss": + type(c.args.get(0), fn, sc); + return Ty.BOOL; + default: + return null; + } + } + + /// `r.name(args)` on a receiver that is one of several types: each + /// member's own method takes the call, and the call is made as generic + /// code makes it (through the doors), which dispatches on the object + /// that arrives. Null when a member is one this cannot resolve the + /// method of. + private Ty unionCall(Call c, Ty r, String name, List args, boolean simple) { + Ty ret = Ty.BOT; + for (Ty m0 : r.members()) { + if (m0.k == Ty.K.NONE) { + // Calling a method of None raises. + continue; } - if (c.elt != null) { - escape(type(c.elt, null, c.scope)); + Ty m = m0.nonNone(); + Ty t = null; + if (m.k == Ty.K.INST && closedFor(m.cls, name)) { + List cand = candidates(m.cls, name); + if (cand != null) { + t = Layouts.resolver(m.cls, name) == null ? Ty.BOT : null; + for (FunctionDef d : cand) { + Fn f = p.fns.get(d); + callFn(f, args, 1, false, true); + Fn g = generic.get(d); + t = mix(t, retOf(f, g == null ? f.ret : mix(f.ret, g.ret))); + } + } + } else if (m.k == Ty.K.LIST) { + t = listMethod(m, name, args); + } else if (m.k == Ty.K.DICT && simple) { + t = dictMethod(m, name, args); + } else if (m.k == Ty.K.STR && c.keywords.isEmpty() && !hasStarred(c.args)) { + t = strMethod(name, args); } - if (c.value != null) { - escape(type(c.value, null, c.scope)); + if (t == null) { + return null; } - return Ty.DYN; + ret = mix(ret, t); } - anyChildren(e, fn, sc); - return Ty.DYN; + doors.add(c); + return ret; } - /// Kinds whose comparisons always answer a bool: no user `__eq__`. - private boolean plainCompare(Ty t) { - switch (t.k) { - case BOT: - case NONE: - case BOOL: - case INT: - case FLOAT: - case STR: - return true; - case INST: - for (Layouts.Cls c = t.cls; c != null; c = c.parent) { - for (String d : new String[] {"__eq__", "__ne__", "__lt__", "__le__", "__gt__", "__ge__"}) { - if (c.bodyNames.contains(d)) { - return false; - } + private Ty listMethod(Ty r, String m, List args) { + if (!"index".equals(m) && !"count".equals(m) && !"copy".equals(m)) { + unslot(r); + } + switch (m) { + case "append": + if (args.size() == 1) { + storeElem(r, args.get(0)); + return Ty.NONE; + } + break; + case "pop": + if (args.size() <= 1) { + return elem(r); + } + break; + case "extend": + if (args.size() == 1) { + storeElem(r, args.get(0).k == Ty.K.LIST ? elem(args.get(0)) : Ty.OBJECT); + if (args.get(0).k != Ty.K.LIST) { + escape(args.get(0)); } + return Ty.NONE; } - return !anySubclassDefinesCompare(t.cls); + break; + case "insert": + if (args.size() == 2) { + storeElem(r, args.get(1)); + return Ty.NONE; + } + break; + case "reverse": + case "clear": + return Ty.NONE; + case "copy": + return Ty.list(r.sites, false); + case "index": + case "count": + return Ty.INT; default: - return false; + break; + } + escape(r); + for (Ty t : args) { + escape(t); } + return Ty.UNSEEN; } - private boolean anySubclassDefinesCompare(Layouts.Cls k) { - for (Layouts.Cls c : layouts.classes.values()) { - if (isSelfOrAncestor(k, c)) { - for (String d : new String[] {"__eq__", "__ne__", "__lt__", "__le__", "__gt__", "__ge__"}) { - if (c.bodyNames.contains(d)) { - return true; - } - } + static boolean hasStarred(List args) { + for (Expr x : args) { + if (x instanceof Starred) { + return true; } } return false; } - Ty attrType(Ty r, String attr) { - if (r.k == Ty.K.BOT || r.k == Ty.K.NONE) { - // Nothing reached the receiver yet, or None (which raises): no value. - // Nothing reached the receiver yet: a later round decides. - return Ty.BOT; + /// `s.encode(...)` on a str or `b.decode(...)` on a bytes, with up to + /// two str arguments (the encoding and the error handler), positional: + /// TypedEmit calls the codec directly (see its `codecCall`). + static boolean codecCall(Ty r, String m, List args, Call c) { + if (r.opt || !c.keywords.isEmpty() || hasStarred(c.args) || args.size() > 2) { + return false; } - if (r.k == Ty.K.INST) { - Layouts.Cls o = fieldOwner(r.cls, attr); - if (o != null) { - return fieldType(o, attr); + for (Ty t : args) { + if (t.k != Ty.K.STR || t.opt) { + return false; } - // A bound method, or something only a subclass has. - escapeMethods(attr); - return Ty.DYN; } - escape(r); - if (r.k == Ty.K.DYN) { - escapeMethods(attr); + return r.k == Ty.K.STR && "encode".equals(m) || r.k == Ty.K.BYTES && "decode".equals(m); + } + + /// `s.split()` or `s.split(sep)` with a str separator. + static boolean splitCall(String m, List args, Call c) { + return "split".equals(m) && c.keywords.isEmpty() && !hasStarred(c.args) + && (args.isEmpty() || args.size() == 1 && args.get(0).k == Ty.K.STR && !args.get(0).opt); + } + + /// Which of the tests of every character `m` is (`Typed.isAll`), or -1. + static int isAllKind(String m) { + switch (m) { + case "isspace": + return 0; + case "isdigit": + return 1; + case "isdecimal": + return 2; + case "isnumeric": + return 3; + case "isalpha": + return 4; + case "isalnum": + return 5; + default: + return -1; } - return Ty.DYN; } - static Ty binop(String op, Ty l, Ty r, Expr right) { - if (l.k == Ty.K.BOT || r.k == Ty.K.BOT) { - return Ty.BOT; + /// The type of a str method TypedEmit calls directly (see its + /// `strMethod`, which must accept exactly these), or null. + /// The type every call of the str method `m` answers, whatever its + /// arguments, or null for a name that is not one. + static Ty strResult(String m) { + switch (m) { + case "format": + case "format_map": + case "capitalize": + case "casefold": + case "center": + case "expandtabs": + case "ljust": + case "lower": + case "lstrip": + case "removeprefix": + case "removesuffix": + case "replace": + case "rjust": + case "rstrip": + case "strip": + case "swapcase": + case "title": + case "translate": + case "upper": + case "zfill": + case "join": + return Ty.STR; + case "count": + case "find": + case "index": + case "rfind": + case "rindex": + return Ty.INT; + case "endswith": + case "isalnum": + case "isalpha": + case "isascii": + case "isdecimal": + case "isdigit": + case "isidentifier": + case "islower": + case "isnumeric": + case "isprintable": + case "isspace": + case "istitle": + case "isupper": + case "startswith": + return Ty.BOOL; + case "encode": + return Ty.BYTES; + default: + return null; } - if (l.opt || r.opt) { - return Ty.DYN; + } + + static Ty strMethod(String m, List args) { + int n = args.size(); + if (n == 0 && isAllKind(m) >= 0) { + return Ty.BOOL; } - boolean li = l.k == Ty.K.INT || l.k == Ty.K.BOOL; - boolean ri = r.k == Ty.K.INT || r.k == Ty.K.BOOL; - boolean lf = l.k == Ty.K.FLOAT; - boolean rf = r.k == Ty.K.FLOAT; - if (li && ri) { - switch (op) { - case "+": - case "-": - case "*": - case "//": - case "%": - case "&": - case "|": - case "^": - case "<<": - case ">>": + if ((n == 2 || n == 3) && args.get(0).k == Ty.K.STR && !args.get(0).opt && args.get(1).k == Ty.K.INT + && (n == 2 || args.get(2).k == Ty.K.INT)) { + // With a start, and an end: bounds that are ints, clamped as a + // slice's are, so nothing here raises. + switch (m) { + case "find": + case "rfind": return Ty.INT; - case "/": - return Ty.FLOAT; - case "**": - // A negative exponent answers a float. - return right instanceof Constant && ((Constant) right).kind == Constant.Kind.INT ? Ty.INT - : Ty.DYN; + case "startswith": + case "endswith": + return Ty.BOOL; default: - return Ty.DYN; + return null; } } - if ((lf || li) && (rf || ri)) { - switch (op) { - case "+": - case "-": - case "*": - case "/": - case "//": - case "%": - return Ty.FLOAT; - default: - // `**` of a negative float answers a complex. - return Ty.DYN; + for (int i = 0; i < n; i++) { + if (!"join".equals(m) && (args.get(i).k != Ty.K.STR || args.get(i).opt)) { + return null; } } - if (l.k == Ty.K.STR && r.k == Ty.K.STR && "+".equals(op)) { - return Ty.STR; + switch (m) { + case "strip": + case "lstrip": + case "rstrip": + return n <= 1 ? Ty.STR : null; + case "lower": + case "upper": + return n == 0 ? Ty.STR : null; + case "replace": + return n == 2 ? Ty.STR : null; + case "find": + case "rfind": + case "count": + return n == 1 ? Ty.INT : null; + case "startswith": + case "endswith": + return n == 1 ? Ty.BOOL : null; + case "join": + return n == 1 ? Ty.STR : null; + default: + return null; } - return Ty.DYN; } - private Ty call(Call c, Fn fn, Scope sc) { - boolean simple = c.keywords.isEmpty() && !anyStarred(c.args); - if (c.func instanceof Name && sc.resolve(((Name) c.func).id) == Scope.Binding.GLOBAL) { - String n = ((Name) c.func).id; - Fn f = globalFns.get(n); - Layouts.Cls k = globalClasses.get(n); - if (f != null || k != null) { - List args = new ArrayList(); - for (Expr a : c.args) { - args.add(a instanceof Starred ? Ty.DYN : type(a, fn, sc)); - } - for (Keyword kw : c.keywords) { - escape(type(kw.value, fn, sc)); - } - if (f != null) { - callFn(f, args, 0, simple && args.size() <= f.params.length - && args.size() >= f.params.length - f.def.args.defaults.size()); - Ty site = simple && args.size() == f.params.length ? siteType(f, args) : null; - if (site != null) { - siteRet.put(c, site); - return site; - } - siteRet.remove(c); - return f.ret; - } - if (open.contains(k)) { - for (Ty a : args) { - escape(a); - } - escapeClass(k); - return Ty.DYN; - } - Layouts.Cls o = Layouts.resolver(k, "__init__"); - FunctionDef init = o == null ? null : o.typable.get("__init__"); - if (o != null && init == null) { - for (Ty a : args) { - escape(a); - } - return Ty.inst(k, false); - } - if (init != null) { - Fn fi = fns.get(init); - fi.params[0] = joinInto(fi.params[0], Ty.inst(k, false)); - callFn(fi, args, 1, simple && args.size() + 1 <= fi.params.length - && args.size() + 1 >= fi.params.length - init.args.defaults.size()); - } else { - for (Ty a : args) { - escape(a); - } - } - return Ty.inst(k, false); - } + /// The type the annotation of parameter `i` of `f` names, when it is one + /// the guard at the door can test for and a plain function's: or null. + /// Nothing trusts the annotation. It decides which calls enter the typed + /// version directly, and the guard decides the rest as they arrive. + Ty pin(Fn f, int i) { + if (i >= f.def.args.positional.size() || f.cls != null && i == 0) { + return null; } - if (isMathCall(c, sc)) { - boolean numbers = true; - for (Expr x : c.args) { - Ty t = type(x, fn, sc); - numbers &= (t.k == Ty.K.INT || t.k == Ty.K.FLOAT) && !t.opt; + Infer h = p.fnHome.get(f); + return (h == null ? this : h).annotated(f.def.args.positional.get(i).annotation, f.def.scope.parent, 0); + } + + /// The type annotation `a` names, read in scope `sc` of this module, when + /// it is one the guard at the door can test: `str`, `int`, `bytes`, a + /// compiled class (imported or not), each also `Optional[...]`, + /// `... | None` or written as a string. Null otherwise. An annotation is + /// only a guess: nothing is unsound when it lies, only slower. + Ty annotated(Expr a, Scope sc, int depth) { + if (a == null || sc == null || depth > 4) { + return null; + } + if (a instanceof Constant && ((Constant) a).kind == Constant.Kind.STR) { + String t = ((Constant) a).text.trim(); + boolean opt = false; + if (t.endsWith("| None")) { + t = t.substring(0, t.length() - "| None".length()).trim(); + opt = true; + } else if (t.startsWith("Optional[") && t.endsWith("]")) { + t = t.substring("Optional[".length(), t.length() - 1).trim(); + opt = true; + } + if (!t.matches("[A-Za-z_][A-Za-z0-9_]*")) { + return null; } - return numbers ? Ty.FLOAT : Ty.DYN; + Ty r = annotated(new Name(t), sc, depth + 1); + return r == null || !opt ? r : r.orNone(); } - if (c.func instanceof Attribute) { - Attribute a = (Attribute) c.func; - if (a.value instanceof Name && globalClasses.containsKey(((Name) a.value).id) - && sc.resolve(((Name) a.value).id) == Scope.Binding.GLOBAL) { - // `Cls.method(obj, ...)`: an explicit call of a method. - Layouts.Cls k = globalClasses.get(((Name) a.value).id); - Layouts.Cls o = Layouts.resolver(k, a.attr); - FunctionDef m = o == null ? null : o.typable.get(a.attr); - List args = new ArrayList(); - for (Expr x : c.args) { - args.add(x instanceof Starred ? Ty.DYN : type(x, fn, sc)); - } - for (Keyword kw : c.keywords) { - escape(type(kw.value, fn, sc)); - } - if (m != null && !open.contains(k)) { - Fn f = fns.get(m); - callFn(f, args, 0, simple && args.size() <= f.params.length - && args.size() >= f.params.length - m.args.defaults.size()); - return f.ret; - } - for (Ty t : args) { - escape(t); + if (a instanceof Subscript && (isName(((Subscript) a).value, "Optional") + || ((Subscript) a).value instanceof Attribute && "Optional".equals(((Attribute) ((Subscript) a).value).attr))) { + Ty r = annotated(((Subscript) a).index, sc, depth + 1); + return r == null ? null : r.orNone(); + } + if (a instanceof BinOp && "|".equals(((BinOp) a).op)) { + Expr l = ((BinOp) a).left; + Expr r = ((BinOp) a).right; + Expr other = isNone(r) ? l : isNone(l) ? r : null; + Ty t = other == null ? null : annotated(other, sc, depth + 1); + return t == null ? null : t.orNone(); + } + if (a instanceof Name) { + String n = ((Name) a).id; + if (sc.resolve(n) == Scope.Binding.BUILTIN) { + switch (n) { + case "str": + return Ty.STR; + case "int": + return Ty.INT; + case "bytes": + return Ty.BYTES; + default: + break; } - if (m != null) { - escapeFn(fns.get(m)); + } + } + if (a instanceof Name || a instanceof Attribute) { + Layouts.Cls k = calledClass(a, sc); + return k == null ? null : Ty.inst(k, false); + } + return null; + } + + private static boolean isNone(Expr e) { + return e instanceof Constant && ((Constant) e).kind == Constant.Kind.NONE || isName(e, "None"); + } + + /// Joins a call's arguments into `f`'s parameters, from `from` on. False + /// when the call goes through the function's door instead, which only a + /// call site that can make that call asks for (`door`): an argument is + /// one nothing here knows (OBJECT), or is not what the parameter's + /// annotation says. Joining it would leave the parameter holding + /// anything for every caller; instead the parameter keeps what the + /// other calls pass -- or, when no call passes anything known, what its + /// uses suggest ([#uncalled]) -- and this call is checked as it + /// arrives. A wrong guess costs a guard, never correctness: the generic + /// version runs what does not fit, and [#genericView] walks it. + /// Whether `n` positional arguments (the receiver counted) bind every + /// parameter of `f` at build time: each one left out has a default, + /// whose type the definition already joined into the parameter. + /// Whether a method `attr` an instance typed `r` may run takes + /// keyword-only parameters. + private boolean kwOnlyCandidate(Ty r, String attr) { + if (r.k != Ty.K.INST) { + return false; + } + List cand = candidates(r.cls, attr); + if (cand != null) { + for (FunctionDef m : cand) { + if (!m.args.kwonly.isEmpty()) { + return true; } - return Ty.DYN; } - Ty r = type(a.value, fn, sc); - List args = new ArrayList(); - for (Expr x : c.args) { - args.add(x instanceof Starred ? Ty.DYN : type(x, fn, sc)); + } + return false; + } + + private static boolean binds(Fn f, int n) { + // `*args` and `**kwargs` are always bound (to what is left over, + // empty here), and a keyword-only parameter by its default. + Node.Arguments a = f.def.args; + if (!a.kwonly.isEmpty() && a.vararg == null && a.kwarg == null && n == f.params.length) { + // A list [#staticArgs] bound to every parameter, keyword-only + // ones included. + return true; + } + for (Expr d : a.kwDefaults) { + if (d == null) { + return false; } - for (Keyword kw : c.keywords) { - escape(type(kw.value, fn, sc)); + } + int np = a.positional.size(); + return n <= np && n >= np - a.defaults.size(); + } + + private boolean callFn(Fn f, List args0, int from, boolean exact, boolean door) { + if (exact && !f.def.args.kwonly.isEmpty() && args0.size() + from != f.params.length) { + // Positions past the positional parameters are keyword-only: + // only a list [#staticArgs] bound to every parameter binds them. + exact = false; + } + List args = new ArrayList(args0.size()); + for (Ty a : args0) { + // A bound method reaches the parameter as itself: the calls + // the body makes through it are followed (see [#paramIn]). + args.add(a); + } + reach(f); + if (p.done) { + // Asked again while the code is written: the parameters are + // settled (and localized), so this only answers whether the + // call fits them. + for (int i = 0; i < args.size() && from + i < f.params.length; i++) { + Ty a = args.get(i); + if (a.unseen() || !Ty.join(f.params[from + i], a).equals(f.params[from + i])) { + return false; + } } - if (r.k == Ty.K.BOT || r.k == Ty.K.NONE) { - return Ty.BOT; + return exact; + } + if (shadow) { + // A call the generic body makes goes through the callee's own + // guard: it adds nothing to the callee's parameters, and has + // the typed version's result only when its arguments fit it. + boolean fit = exact; + for (int i = 0; fit && i < args.size(); i++) { + // A probe: `mix` would loosen a class the call leaves alone. + // A parameter nothing has filled yet is no answer: the pass + // runs again once one has, and this call is checked then. + fit = f.params[from + i].k == Ty.K.BOT + || Ty.join(f.params[from + i], args.get(i)).equals(f.params[from + i]); } - if (r.k == Ty.K.INST && !open.contains(r.cls)) { - List cand = candidates(r.cls, a.attr); - if (cand != null) { - Ty ret = Ty.BOT; - for (FunctionDef m : cand) { - Fn f = fns.get(m); - callFn(f, args, 1, simple && args.size() + 1 == f.params.length); - ret = Ty.join(ret, f.ret); - } - if (Layouts.resolver(r.cls, a.attr) == null) { - // Not every instance has it: the rest raise. - ret = Ty.join(ret, Ty.BOT); + if (!fit && exact) { + // The guard sends the call to the generic version, which is + // walked with what reaches it (see [#genericView]). + shadowMiss = true; + Ty[] m = p.missed.get(f.def); + if (m == null) { + m = new Ty[f.params.length]; + java.util.Arrays.fill(m, Ty.BOT); + p.missed.put(f.def, m); + p.changed = true; + } + for (int i = 0; i < args.size(); i++) { + Ty j = Ty.join(m[from + i], args.get(i)); + if (!j.equals(m[from + i])) { + m[from + i] = j; + p.changed = true; } - return ret; } + return true; } - if (r.k == Ty.K.LIST && !r.opt) { - return listMethod(r, a.attr, args); + if (!fit) { + shadowMiss = true; + for (Ty t : args) { + escape(t); + } } - escape(r); + return true; + } + if (!exact) { + escapeFn(f); for (Ty t : args) { escape(t); } - if (r.k == Ty.K.DYN || r.k == Ty.K.INST) { - escapeMethods(a.attr); - } - return Ty.DYN; + return true; } - if (c.func instanceof Name && sc.resolve(((Name) c.func).id) == Scope.Binding.BUILTIN - && !moduleScope.hasStarImport) { - String n = ((Name) c.func).id; - List args = new ArrayList(); - for (Expr x : c.args) { - args.add(x instanceof Starred ? Ty.DYN : type(x, fn, sc)); - } - for (Keyword kw : c.keywords) { - escape(type(kw.value, fn, sc)); + if (door) { + boolean miss = false; + for (int i = 0; !miss && i < args.size(); i++) { + Ty pin = pin(f, from + i); + // A wide argument joins into its parameter (below): the set + // of types that reach it is what the body is typed for. + // Escaping the callee instead made every other parameter + // untyped too. Only an annotation the call contradicts + // still sends it to the guard. + miss = pin != null && Ty.join(pin, args.get(i)).k != pin.k; } - if (simple && args.size() == 1 && ("len".equals(n) || "isinstance".equals(n) && false)) { - // len reads its argument and keeps nothing. - if (args.get(0).k != Ty.K.LIST) { - escape(args.get(0)); + if (miss) { + for (int i = 0; i < f.params.length; i++) { + Ty pin = pin(f, i); + if (pin != null && f.params[i].k == Ty.K.BOT) { + f.params[i] = joinInto(f.params[i], pin); + } } - return Ty.INT; - } - if (simple && "float".equals(n) && args.size() == 1 - && (args.get(0).k == Ty.K.INT || args.get(0).k == Ty.K.FLOAT) && !args.get(0).opt) { - return Ty.FLOAT; + // Entered through the guard, but with nothing for the + // parameters yet: they are filled once nothing else does. + if (!f.escapes) { + f.escapes = true; + p.changed = true; + } + for (Ty t : args) { + escape(t); + } + return false; } - if (simple && "str".equals(n) && args.size() == 1 && !args.get(0).opt - && (args.get(0).k == Ty.K.INT || args.get(0).k == Ty.K.FLOAT - || args.get(0).k == Ty.K.STR || args.get(0).k == Ty.K.BOOL)) { - return Ty.STR; + } + boolean wideArg = false; + Call cc = curCall; + boolean aligned = cc != null && cc.keywords.isEmpty() && !anyStarred(cc.args) && cc.args.size() == args.size(); + for (int i = 0; i < args.size(); i++) { + // A guessed instance is checked where it is read (`instanceof`), + // so it is one of the kinds the parameter is typed for. + // Not BOT: nothing has reached that argument yet in this round, + // and the mark never comes off. + if (args.get(i).unseen() + || aligned && args.get(i).k != Ty.K.INST && guessed(cc.args.get(i))) { + boolean[] u = p.unseenArgs.computeIfAbsent(f, x -> new boolean[x.params.length]); + if (!u[from + i]) { + u[from + i] = true; + p.changed = true; + } } - if (simple && args.size() == 1 && args.get(0).k == Ty.K.BOT - && ("ord".equals(n) || "abs".equals(n) || "float".equals(n) || "str".equals(n))) { - // Nothing reaches the argument yet: a later pass decides, - // where DYN now would stay DYN for good. - return Ty.BOT; + Ty held = f.params[from + i]; + if (door && args.get(i).k == Ty.K.OBJECT && !nested(f) && (held.k == Ty.K.BOT || held.k == Ty.K.INST)) { + // (A nested function has no generic version walked: see + // the walk of a FunctionDef. Only a parameter of instances: + // yaml's Node.__init__, given `str | list` values and an + // untyped one, typed the field `value` a list, and the + // generic version's str reached a typed read of it.) + // A value of no known type is no more evidence than an + // unseen one: the call enters through the guard, which + // hands the typed version what fits and the generic one + // the rest. Joined, one such caller made a parameter every + // precise caller agrees on untyped (markdownify's + // process_tag, recursing over its own children). + objectArg(f, from + i); + wideArg = true; + continue; } - if (simple && "ord".equals(n) && args.size() == 1 && args.get(0).k == Ty.K.STR && !args.get(0).opt) { - return Ty.INT; + f.params[from + i] = joinInto(f.params[from + i], args.get(i)); + Ty d = declared(f, from + i); + if (d != null && !(d.wide() && f.params[from + i].k == Ty.K.INST + && forwardedOnly(f, from + i))) { + f.params[from + i] = joinInto(f.params[from + i], d); } - if (simple && "abs".equals(n) && args.size() == 1 && !args.get(0).opt - && (args.get(0).k == Ty.K.INT || args.get(0).k == Ty.K.FLOAT)) { - return args.get(0); + } + if (door) { + for (Ty a : args) { + if (a.unseen()) { + // No evidence for the parameter (Ty#UNSEEN), so it keeps + // what the other calls say; this call enters through + // the guard, which hands what does not fit to the + // generic version. + return false; + } } - if (simple && "list".equals(n) && args.size() == 1) { - int s = site(c); - Ty t = args.get(0); - boolean range = rangeCall(c.args.get(0), sc); - siteElem.set(s, joinInto(siteElem.get(s), t.k == Ty.K.LIST ? elem(t) : range ? Ty.INT : Ty.DYN)); - if (t.k != Ty.K.LIST && !rangeCall(c.args.get(0), sc)) { - escape(t); + if (wideArg) { + // Entered through the guard: the emitter writes it so only + // for a call listed here, and some callers of this method + // drop the answer (a method called on self, a duck call). + if (cc != null && !shadow) { + siteRet.remove(cc); + doors.add(cc); } - return Ty.list(new int[] {s}, false); + return false; } - for (Ty t : args) { - escape(t); + } + return true; + } + + /// Whether parameter `i` of `f` is declared untyped only because the + /// body hands it on ([#onlyForwarded]). That widening is for values + /// the callee also takes in other kinds; an instance the visible calls + /// pass keeps its class (markdownify's `convert_soup(self, soup)` + /// made BeautifulSoup loose), and any other caller meets the guard. + private boolean forwardedOnly(Fn f, int i) { + if (i >= f.names.size() || i >= f.def.args.positional.size()) { + return false; + } + String n = f.names.get(i); + Expr a = f.def.args.positional.get(i).annotation; + return !wideAnnotation(a) && !isinstanceTested(f.def.body, n) && onlyForwarded(f.def.body, n); + } + + /// What parameter `i` of `f` says it takes beyond what the calls this + /// pass sees pass it, joined into it at every call: the calls are only + /// the ones it can see, and the source often says more. A parameter + /// the body tests with `isinstance`, or annotated `object`, `Any` or a + /// union of different kinds, takes values of several types by design: + /// OBJECT, rather than the one type the visible calls happened to pass + /// (pdfminer's `resolve1(x: object)` was typed `x: None` from its + /// callers, and missed its guard on every int and dict). A parameter + /// annotated one testable type (`s: bytes`) has that type joined in: + /// calls seen passing only None make it `bytes | None`, not None. + /// Null when the source says nothing. Like every type of a parameter, + /// only a guess the door checks: never unsound, only slower or faster. + private Ty declared(Fn f, int i) { + Ty[] d = declaredCache.get(f); + if (d == null) { + d = new Ty[f.params.length]; + Infer h = p.fnHome.get(f); + Infer in = h == null ? this : h; + for (int k = f.cls != null ? 1 : 0; k < d.length; k++) { + String n = f.names.get(k); + Expr a = k < f.def.args.positional.size() ? f.def.args.positional.get(k).annotation : null; + Ty at = a == null || wideAnnotation(a) ? null : in.annotated(a, f.def.scope.parent, 0); + // A body that tests its parameter with isinstance, only + // forwards it, or annotates it `object` says it takes + // values of several kinds -- from callers the pass does not + // see. While every caller is seen, what they pass is the + // type (#declared): widening regardless made every wrapper + // (markdownify's process_element forwarding `node` to + // process_tag) untyped all the way down. + if (isinstanceTested(f.def.body, n) || wideAnnotation(a) + || onlyForwarded(f.def.body, n) && (at == null || at.k != Ty.K.INST)) { + d[k] = WIDE; + } else if (a != null) { + d[k] = at; + } } - return Ty.DYN; + declaredCache.put(f, d); } - escape(type(c.func, fn, sc)); - for (Expr x : c.args) { - escape(type(x instanceof Starred ? ((Starred) x).value : x, fn, sc)); + Ty r = i < d.length ? d[i] : null; + if (r == WIDE) { //NOPMD CompareObjectsWithEquals - identity is meant + boolean[] u = p.unseenArgs.get(f); + // Only a call that passes a value of no known type is evidence + // of the other kinds: a caller the pass does not see enters + // through the guard, which hands what does not fit to the + // generic version. + return u != null && i < u.length && u[i] ? Ty.OBJECT : null; } - for (Keyword kw : c.keywords) { - escape(type(kw.value, fn, sc)); + return r; + } + + /// [#declared]'s mark for a parameter the source says takes several + /// kinds: OBJECT once a call passes it a value of no known type. + private static final Ty WIDE = Ty.obj(""); + + /// The type a parameter no visible call fills starts from: OBJECT when + /// the source says it takes several kinds ([#declared]), else its + /// annotation, else what its uses suggest ([#guess]). + private Ty seed(Fn f, int i, Ty pin) { + Ty d = declared(f, i); + if (d != null && d.wide()) { + return Ty.UNSEEN; } - return Ty.DYN; + return pin != null ? pin : guess(f.def, f.names.get(i)); } - private Ty listMethod(Ty r, String m, List args) { - switch (m) { - case "append": - if (args.size() == 1) { - storeElem(r, args.get(0)); - return Ty.NONE; - } - break; - case "pop": - if (args.size() <= 1) { - return elem(r); - } - break; - case "extend": - if (args.size() == 1) { - storeElem(r, args.get(0).k == Ty.K.LIST ? elem(args.get(0)) : Ty.DYN); - if (args.get(0).k != Ty.K.LIST) { - escape(args.get(0)); - } - return Ty.NONE; - } - break; - case "insert": - if (args.size() == 2) { - storeElem(r, args.get(1)); - return Ty.NONE; - } - break; - case "reverse": - case "clear": - return Ty.NONE; - case "copy": - return Ty.list(r.sites, false); - case "index": - case "count": - return Ty.INT; - default: - break; + private final Map declaredCache = new IdentityHashMap(); + + /// Whether `a` names a type of several kinds: `object`, `Any`, or a + /// union of two or more members other than None. + static boolean wideAnnotation(Expr a) { + if (a == null) { + return false; } - escape(r); - for (Ty t : args) { - escape(t); + if (a instanceof Constant && ((Constant) a).kind == Constant.Kind.STR) { + String t = ((Constant) a).text.trim(); + return "object".equals(t) || "Any".equals(t) || t.startsWith("Union[") && t.indexOf(',') > 0 + || t.replace("| None", "").indexOf('|') >= 0; + } + if (isName(a, "object") || isName(a, "Any") + || a instanceof Attribute && "Any".equals(((Attribute) a).attr)) { + return true; + } + if (a instanceof Subscript && (isName(((Subscript) a).value, "Union") + || ((Subscript) a).value instanceof Attribute && "Union".equals(((Attribute) ((Subscript) a).value).attr))) { + Expr ix = ((Subscript) a).index; + if (!(ix instanceof TupleExpr)) { + return false; + } + int members = 0; + for (Expr e : ((TupleExpr) ix).elts) { + members += isNone(e) ? 0 : 1; + } + return members > 1; + } + if (a instanceof BinOp && "|".equals(((BinOp) a).op)) { + return !isNone(((BinOp) a).left) && !isNone(((BinOp) a).right); } - return Ty.DYN; + return false; } - /// Joins a call's arguments into `f`'s parameters, from `from` on. - private void callFn(Fn f, List args, int from, boolean exact) { - if (!exact) { - escapeFn(f); - for (Ty t : args) { - escape(t); + /// Whether every use of `n` in `body` hands it on as an argument of a + /// call, and nothing stores it: `re.sub(pattern, ...)` only passes + /// `pattern` to `_compile`, which takes a str or a compiled pattern. A + /// type for such a parameter buys the body nothing and its guard turns + /// away every caller passing what the callee also takes. + static boolean onlyForwarded(List body, String n) { + int[] c = {0, 0}; + for (Stmt st : body) { + forwardIn(st, n, c, false); + } + return c[0] > 0 && c[1] == 0; + } + + /// `c`: uses handed on, other uses (stores included). + private static void forwardIn(Object o, String n, int[] c, boolean asArg) { + if (o instanceof Name && ((Name) o).id.equals(n)) { + // A store target is reached with asArg false: it counts as a + // use that is not handed on. + c[asArg ? 0 : 1]++; + return; + } + if (o instanceof FunctionDef || o instanceof ClassDef || o instanceof Lambda) { + // A closure over it: a use this does not follow. + Infer.children(o, x -> forwardIn(x, n, c, false)); + return; + } + if (o instanceof Call) { + Call cl = (Call) o; + forwardIn(cl.func, n, c, false); + for (Expr a : cl.args) { + forwardIn(a, n, c, true); + } + for (Keyword k : cl.keywords) { + forwardIn(k.value, n, c, true); } return; } - for (int i = 0; i < args.size(); i++) { - f.params[from + i] = joinInto(f.params[from + i], args.get(i)); + Infer.children(o, x -> forwardIn(x, n, c, false)); + } + + /// Whether `body` (not counting nested functions and classes) calls + /// `isinstance(n, ...)` or `type(n)`. + static boolean isinstanceTested(List body, String n) { + boolean[] r = {false}; + for (Stmt st : body) { + isinstanceIn(st, n, r); + } + return r[0]; + } + + private static void isinstanceIn(Object o, String n, boolean[] r) { + if (r[0] || o instanceof FunctionDef || o instanceof ClassDef || o instanceof Lambda) { + return; + } + if (o instanceof Call && ((Call) o).func instanceof Name && !((Call) o).args.isEmpty() + && isName(((Call) o).args.get(0), n)) { + String fn = ((Name) ((Call) o).func).id; + if ("isinstance".equals(fn) || "type".equals(fn) && ((Call) o).args.size() == 1) { + r[0] = true; + return; + } } + Infer.children(o, x -> isinstanceIn(x, n, r)); } // ---- reflection-free traversal --------------------------------------- @@ -1762,6 +12467,28 @@ interface Visit { } /// Calls `v` for every AST child (node or list element) of `o`. + /// An argument of no known type reached parameter `i` of `f` through + /// its door: no evidence for the typed version, which the guard keeps + /// it out of. What does not fit runs the generic version, which stores + /// it into fields and lists all the same, so that is walked with it + /// (#genericView), as for a generic body's call that misses. + private void objectArg(Fn f, int i) { + if (p.objectArgs.add(f)) { + p.changed = true; + } + Ty[] m = p.missed.get(f.def); + if (m == null) { + m = new Ty[f.params.length]; + java.util.Arrays.fill(m, Ty.BOT); + p.missed.put(f.def, m); + p.changed = true; + } + if (i < m.length && m[i].k != Ty.K.OBJECT) { + m[i] = Ty.OBJECT; + p.changed = true; + } + } + static void children(Object o, Visit v) { if (o instanceof List) { for (Object x : (List) o) { @@ -1797,6 +12524,262 @@ static void children(Object o, Visit v) { } } + /// The build errors of this module: what a closed world cannot + /// compile. An attribute named by a string the build cannot enumerate + /// (a computed getattr/setattr/hasattr/delattr), and a class whose + /// instances cannot be given a layout. A value the analysis holds as + /// `Object` is not an error: `Object` is a type, the right one where a + /// value may be anything, and the generated code handles it as such. + List strictErrors() { + List out = new ArrayList(); + if (!strictModule(moduleName)) { + return out; + } + out.addAll(reflective); + refusals(body, out); + for (Map.Entry r : layouts.refused.entrySet()) { + if (protocol(r.getKey())) { + // A typing protocol: instantiating one raises, so no + // instance of it exists to lay out. + continue; + } + String why = r.getValue(); + String home = null; + for (Expr base : r.getKey().bases) { + if (home == null && why.equals("base " + Layouts.text(base) + " has no layout")) { + home = noHomeWhy(base); + } + } + why = home == null ? why : why + " (" + home + ")"; + out.add(moduleName + ":" + r.getKey().line + " class " + r.getKey().name + " has no layout: " + why); + } + return out; + } + + /// The refusals a lowering marked on the tree (Node#refusal). + private void refusals(Object o, List out) { + if (o instanceof Node && ((Node) o).refusal != null) { + out.add(moduleName + ":" + ((Node) o).line + " " + ((Node) o).refusal); + } + children(o, x -> refusals(x, out)); + } + + /// The builtins that take any object and only hash, compare, test or + /// print it: a value that reaches nothing else is Java's `Object` + /// passed to `equals`/`toString`, which costs nothing to leave open. + private static final Set SINKS = new HashSet(java.util.Arrays.asList( + "str", "repr", "print", "hash", "id", "isinstance", "type", "bool", "callable", "format", "ascii")); + + /// Whether every read of `n` in `body` is a generic sink: an argument + /// of one of [#SINKS], an operand of `==`, `!=`, `is` or `is not`, an + /// f-string field, the right operand of `%` formatting, or a truth + /// test -- or the receiver of a method of a closed name, called + /// through its slot. Strict mode allows such a value to stay untyped. + boolean sinkOnly(List body, String n) { + boolean[] bad = new boolean[1]; + for (Stmt s : body) { + sinkUses(s, n, bad); + } + return !bad[0]; + } + + private void sinkUses(Object o, String n, boolean[] bad) { + if (bad[0] || o == null) { + return; + } + if (o instanceof Name) { + bad[0] |= ((Name) o).id.equals(n); + return; + } + if (o instanceof Assign) { + for (Expr t : ((Assign) o).targets) { + if (!(t instanceof Name)) { + sinkUses(t, n, bad); + } + } + sinkUses(((Assign) o).value, n, bad); + return; + } + if (o instanceof For) { + For f = (For) o; + if (!(f.target instanceof Name)) { + sinkUses(f.target, n, bad); + } + sinkUses(f.iter, n, bad); + sinkUses(f.body, n, bad); + sinkUses(f.orelse, n, bad); + return; + } + if (o instanceof Call && ((Call) o).func instanceof Attribute + && ((Attribute) ((Call) o).func).value instanceof Name + && ((Name) ((Attribute) ((Call) o).func).value).id.equals(n) + && closedName(((Attribute) ((Call) o).func).attr)) { + // A method of a closed name called on it: every object has + // that slot, the program's methods implement it and the default + // raises AttributeError (see #closedName). The value is the + // slot interface's, used through it; what it is handed is + // still held to a type. + for (Expr a : ((Call) o).args) { + sinkUses(a, n, bad); + } + for (Keyword k : ((Call) o).keywords) { + sinkUses(k.value, n, bad); + } + return; + } + if (o instanceof Call && ((Call) o).func instanceof Name && SINKS.contains(((Name) ((Call) o).func).id)) { + for (Expr a : ((Call) o).args) { + sinkOperand(a, n, bad); + } + for (Keyword k : ((Call) o).keywords) { + sinkUses(k.value, n, bad); + } + return; + } + if (o instanceof Compare) { + Compare c = (Compare) o; + boolean eq = true; + for (String op : c.ops) { + eq &= "==".equals(op) || "!=".equals(op) || "is".equals(op) || "is not".equals(op); + } + if (eq) { + sinkOperand(c.left, n, bad); + for (Expr x : c.comparators) { + sinkOperand(x, n, bad); + } + return; + } + } + if (o instanceof FormattedValue) { + sinkOperand(((FormattedValue) o).value, n, bad); + sinkUses(((FormattedValue) o).spec, n, bad); + return; + } + if (o instanceof BinOp && "%".equals(((BinOp) o).op) && ((BinOp) o).left instanceof Constant) { + sinkOperand(((BinOp) o).right, n, bad); + return; + } + if (o instanceof If) { + sinkOperand(((If) o).test, n, bad); + sinkUses(((If) o).body, n, bad); + sinkUses(((If) o).orelse, n, bad); + return; + } + if (o instanceof While) { + sinkOperand(((While) o).test, n, bad); + sinkUses(((While) o).body, n, bad); + sinkUses(((While) o).orelse, n, bad); + return; + } + if (o instanceof IfExp) { + sinkOperand(((IfExp) o).test, n, bad); + sinkUses(((IfExp) o).body, n, bad); + sinkUses(((IfExp) o).orelse, n, bad); + return; + } + if (o instanceof UnaryOp && "not".equals(((UnaryOp) o).op)) { + sinkOperand(((UnaryOp) o).operand, n, bad); + return; + } + Infer.children(o, x -> sinkUses(x, n, bad)); + } + + /// `e` where its value only reaches a sink: `n` itself, or a tuple of + /// such operands, is fine there. + private void sinkOperand(Expr e, String n, boolean[] bad) { + if (e instanceof Name && ((Name) e).id.equals(n)) { + return; + } + if (e instanceof TupleExpr) { + for (Expr x : ((TupleExpr) e).elts) { + sinkOperand(x, n, bad); + } + return; + } + sinkUses(e, n, bad); + } + + /// Strict mode: `what(obj, name)` is allowed only when `name` is one + /// string known at build time, so the access compiles to a named field. + /// Several possible names would only become a switch over names at run + /// time, which is reflection again, so the build refuses it; the fix is + /// code that names the attribute, or an `override=` of the function. + private void reflection(String what, Expr name, Fn fn, Scope sc) { + if (STRICT == null || !strictModule(moduleName)) { + return; + } + java.util.Collection one = constStrings(name, fn, sc); + if (one != null && one.size() == 1 || foldedString(name, fn, sc, 0) != null) { + return; + } + String in = fn == null ? moduleName : moduleName + "." + (fn.cls == null ? "" : fn.cls.def.name + ".") + + fn.def.name; + reflective.add(moduleName + ":" + line + " " + what + " with a computed name is reflection; write" + + " override = " + in + " in " + Directives.FILE + " and its compliant body in " + + Directives.OVERRIDES + "/" + in + ".py"); + } + + /// Strict mode: every module function and method of `stmts` with no + /// typed body (no Fn), and why -- a body the pass does not type at all + /// is untyped through and through, and would otherwise not be counted. + private void untypedBodies(List stmts, ClassDef owner, List out) { + for (Stmt s : stmts) { + if (s instanceof ClassDef) { + untypedBodies(((ClassDef) s).body, (ClassDef) s, out); + } else if (s instanceof FunctionDef && fns.get(s) == null) { + FunctionDef d = (FunctionDef) s; + Arguments a = d.args; + String why = !d.decorators.isEmpty() ? "it is decorated" + : d.isAsync ? "it is async" + : a.vararg != null ? "it takes *" + a.vararg.name + : a.kwarg != null ? "it takes **" + a.kwarg.name + : !a.kwonly.isEmpty() ? "it takes keyword-only parameters" + : owner != null && layouts.all().get(owner) == null ? "its class has no layout" + : "the layout leaves it out"; + out.add(moduleName + ":" + d.line + " " + (owner == null ? "" : owner.name + ".") + d.name + + " has no typed body: " + why); + } + } + } + + private static boolean protocol(ClassDef c) { + for (Expr x : c.bases) { + Expr e = x instanceof Subscript ? ((Subscript) x).value : x; + if (e instanceof Name && "Protocol".equals(((Name) e).id) + || e instanceof Attribute && "Protocol".equals(((Attribute) e).attr)) { + return true; + } + } + return false; + } + + private static String describe(Expr e) { + if (e instanceof Call) { + return "call of " + describe(((Call) e).func); + } + if (e instanceof Attribute) { + Expr v = ((Attribute) e).value; + return (v instanceof Name ? ((Name) v).id : v instanceof Call ? describe(v) + " " : "...") + "." + + ((Attribute) e).attr; + } + if (e instanceof Name) { + return ((Name) e).id; + } + return e.getClass().getSimpleName(); + } + + static boolean strictModule(String m) { + if (STRICT.length == 0) { + return true; + } + for (String s : STRICT) { + if (m.equals(s) || m.startsWith(s + ".")) { + return true; + } + } + return false; + } + String dump() { StringBuilder b = new StringBuilder(); for (Fn f : fns.values()) { @@ -1804,7 +12787,7 @@ String dump() { for (int i = 0; i < f.params.length; i++) { b.append(i == 0 ? "" : ", ").append(f.names.get(i)).append(": ").append(f.params[i]); } - b.append(") -> ").append(f.ret).append(f.escapes ? " [escapes]" : "").append("\n ").append(f.locals) + b.append(") -> ").append(f.ret).append(f.escapes ? " [escapes]" : "").append(f.yields.k == Ty.K.BOT ? "" : " yields " + f.yields).append("\n ").append(f.locals) .append('\n'); } for (Map.Entry> e : fields.entrySet()) { @@ -1812,7 +12795,12 @@ String dump() { .append(definite.get(e.getKey())).append('\n'); } b.append("globals ").append(globals).append("\nsites ").append(siteElem).append(" escaped ") - .append(escapedSites).append(allListsEscape ? " ALL" : "").append('\n'); + .append(escapedSites).append(p.allListsEscape ? " ALL" : "").append(" unslotted ").append(unslotted) + .append('\n'); + for (Map.Entry e : siteSlots.entrySet()) { + b.append(" slots ").append(e.getKey()).append(' ').append(java.util.Arrays.toString(e.getValue())) + .append('\n'); + } return b.toString(); } } diff --git a/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/JavaInteropGenerator.java b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/JavaInteropGenerator.java index cbd670f326d..5b618cdb7d8 100644 --- a/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/JavaInteropGenerator.java +++ b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/JavaInteropGenerator.java @@ -101,9 +101,32 @@ private static boolean isJava(String module, int level) { /// Generates the bridge class source for `trees` (path to tree). public static String generate(Map trees, ClassPathReader cp, String pkg) { + return generate(trees, cp, pkg, new HashSet()); + } + + /// As [#generate], adding to `answered` every attribute name a Java + /// object of the program answers: a method or field of a class in the + /// universe that the Python code names. Only those names can reach + /// something other than the program's own methods -- a Python class + /// cannot extend a Java one, so Java calls back into Python only + /// through a callable it was handed. + public static String generate(Map trees, ClassPathReader cp, String pkg, + Set answered) { JavaInteropGenerator g = new JavaInteropGenerator(cp); g.collect(trees); g.close(); + for (String c : g.universe) { + for (Member m : g.visibleMethods(c)) { + if (g.names.contains(m.name)) { + answered.add(m.name); + } + } + for (Member f : g.visibleFields(c)) { + if (g.names.contains(f.name)) { + answered.add(f.name); + } + } + } return g.emit(pkg); } diff --git a/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/Jinja2Lowering.java b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/Jinja2Lowering.java new file mode 100644 index 00000000000..bf078112d74 --- /dev/null +++ b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/Jinja2Lowering.java @@ -0,0 +1,573 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.python.transpiler.codegen; + +import com.codename1.python.transpiler.ast.Node; +import com.codename1.python.transpiler.ast.Node.Attribute; +import com.codename1.python.transpiler.ast.Node.Call; +import com.codename1.python.transpiler.ast.Node.Constant; +import com.codename1.python.transpiler.ast.Node.Name; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/// Jinja reads `{{ user.name }}` by trying the attribute `name` and then +/// the item; with the name taken from template text that is a getattr with +/// a computed name. Here every literal template source of the program is +/// lexed and tokenized at build time exactly as the bundled `jinja2` does +/// (`_lex`, `_tokenize`), and each `.name` site and each `['literal']` site +/// gets an accessor function with the name written into its code. The +/// generated module `_cn1_jinja2_tables` maps a template source to one tuple +/// per lexed tag, holding that tag's accessors in token order; the runtime +/// tokenizer hands them out by position. Nothing is looked up by attribute +/// name. +/// +/// A template whose source is computed at run time has no accessors: a +/// `Template(...)`, `from_string(...)` or `render_template_string(...)` with +/// a source that is not a string literal is refused in strict mode, and a +/// template the build did not see that uses either access fails to parse. +public final class Jinja2Lowering { + /// The path of the generated module. + public static final String PATH = "_cn1_jinja2_tables.py"; + + private static final Set CONSTRUCTORS = new HashSet(Arrays.asList("Template", "from_string", + "render_template_string")); + private static final Set KEYWORDS = new HashSet(Arrays.asList("False", "None", "True", "and", + "as", "assert", "async", "await", "break", "class", "continue", "def", "del", "elif", "else", "except", + "finally", "for", "from", "global", "if", "import", "in", "is", "lambda", "nonlocal", "not", "or", "pass", + "raise", "return", "try", "while", "with", "yield")); + private static final String[] OPS2 = {"==", "!=", "<=", ">=", "//", "**"}; + + private Jinja2Lowering() { + } + + /// One accessor: an attribute site (attribute, then item) or a literal + /// item site (item, then attribute). + private static final class Site { + final boolean attr; + final String key; + + Site(boolean attr, String key) { + this.attr = attr; + this.key = key; + } + + String id() { + return (attr ? "a:" : "i:") + key; + } + } + + /// The generated module's source, or null when the program has no jinja2. + public static String rewrite(Map trees) { + return rewrite(trees, java.util.Collections.emptyMap()); + } + + /// Whether a project file is one jinja2's loaders may read, which the + /// build passes to the transpiler beside the modules. Must match + /// `PythonProjectBuilder.isTemplateFile`. + public static boolean isTemplateFile(String path) { + String[] kinds = {".html", ".htm", ".j2", ".jinja", ".jinja2", ".tmpl", ".tpl", ".xml", ".txt", ".md"}; + for (String k : kinds) { + if (path.endsWith(k)) { + return true; + } + } + return false; + } + + /// As [#rewrite(Map)], with `sources` the program's files by path: every + /// template file among them is lexed into the tables, as a literal + /// template is, so a `FileSystemLoader` or `PackageLoader` template is + /// compiled at build time. A loader over a literal directory the build + /// holds no template of, and a literal template name no file of the + /// program's loaders has, are refused in strict mode: they would + /// otherwise fail on the device. + public static String rewrite(Map trees, Map sources) { + if (!imports(trees)) { + return null; + } + Set literals = new java.util.LinkedHashSet(); + List files = new ArrayList(); + for (Map.Entry e : sources.entrySet()) { + String p = e.getKey().replace('\\', '/'); + if (isTemplateFile(p)) { + files.add(p); + String t = e.getValue(); + if (t.contains("{{") || t.contains("{%")) { + // Keyed by the whole text, as the loader reads it: raw, + // and with universal newlines as a text-mode open gives. + literals.add(t); + String u = t.replace("\r\n", "\n").replace('\r', '\n'); + if (!u.equals(t)) { + literals.add(u); + } + } + } + } + checkLoaders(trees, files); + for (Map.Entry e : trees.entrySet()) { + String path = e.getKey().replace('\\', '/'); + if (path.startsWith("jinja2/") || PATH.equals(path)) { + continue; + } + boolean site = path.startsWith("flask/"); + walk(e.getValue(), literals, site, literalNames(e.getValue())); + } + Map fns = new LinkedHashMap(); + StringBuilder fsrc = new StringBuilder(); + StringBuilder tables = new StringBuilder("\nTABLES = {\n"); + for (String src : literals) { + List> tags; + try { + tags = tags(src); + } catch (RuntimeException ex) { + // Not a template this lexer reads; jinja2 would refuse it too. + continue; + } + boolean any = false; + for (List t : tags) { + any |= !t.isEmpty(); + } + if (!any) { + continue; + } + tables.append(" ").append(str(src)).append(": ("); + for (List t : tags) { + tables.append('('); + for (Site s : t) { + String fn = fns.get(s.id()); + if (fn == null) { + fn = "_s" + fns.size(); + fns.put(s.id(), fn); + accessor(fsrc, fn, s); + } + tables.append(fn).append(", "); + } + tables.append("), "); + } + tables.append("),\n"); + } + tables.append("}\n"); + return "# Generated by Jinja2Lowering: one accessor per attribute or literal item site\n" + + "# of the program's literal templates.\n\nMISS = object()\n" + fsrc + tables; + } + + /// Refuses a loader over a literal directory without templates, and a + /// literal `get_template` name no such loader's directory has, when the + /// program's only loaders are file loaders with literal directories. + private static void checkLoaders(Map trees, final List files) { + final List dirs = new ArrayList(); + final List names = new ArrayList(); + final List loaders = new ArrayList(); + final boolean[] other = {false}; + for (Map.Entry e : trees.entrySet()) { + String path = e.getKey().replace('\\', '/'); + if (path.startsWith("jinja2/") || path.startsWith("flask/") || PATH.equals(path)) { + continue; + } + scanLoaders(e.getValue(), files, dirs, names, other, loaders); + } + if (other[0] || dirs.isEmpty()) { + return; + } + for (Call c : names) { + String n = ((Constant) c.args.get(0)).text; + boolean found = false; + for (String d : dirs) { + found |= files.contains(d + n); + } + if (!found && loaders.get(0).refusal == null) { + // On the loader: the call naming the template is rebuilt by + // later passes, and the loader is what cannot provide it. + loaders.get(0).refusal = "template " + n + " is in no directory of the program's template" + + " loaders; the build compiles only the templates it can see"; + } + } + } + + private static void scanLoaders(Object o, final List files, final List dirs, + final List names, final boolean[] other, final List loaders) { + if (o instanceof Call) { + Call c = (Call) o; + String f = c.func instanceof Name ? ((Name) c.func).id + : c.func instanceof Attribute ? ((Attribute) c.func).attr : null; + String dir = null; + boolean loader = false; + if ("FileSystemLoader".equals(f)) { + loader = true; + if (c.args.size() == 1 && isStr(c.args.get(0))) { + dir = ((Constant) c.args.get(0)).text; + } + } else if ("PackageLoader".equals(f)) { + loader = true; + if (!c.args.isEmpty() && c.args.size() <= 2 && isStr(c.args.get(0)) + && (c.args.size() == 1 || isStr(c.args.get(1))) && c.keywords.isEmpty()) { + dir = ((Constant) c.args.get(0)).text.replace('.', '/') + "/" + + (c.args.size() == 2 ? ((Constant) c.args.get(1)).text : "templates"); + } + } else if (f != null && f.endsWith("Loader")) { + other[0] = true; + } else if (("get_template".equals(f) || "render_template".equals(f)) && c.args.size() >= 1 + && isStr(c.args.get(0))) { + names.add(c); + } + if (loader && dir == null) { + // A computed directory: the build cannot tell which files + // it reads, so it checks no names against it. + other[0] = true; + } else if (dir != null) { + while (dir.startsWith("./")) { + dir = dir.substring(2); + } + if (!dir.endsWith("/")) { + dir = dir + "/"; + } + boolean any = false; + for (String p : files) { + any |= p.startsWith(dir); + } + if (!any) { + c.refusal = f + " reads " + dir + ", where the build sees no template file; templates are" + + " compiled at build time from the project's files"; + } + dirs.add(dir); + loaders.add(c); + } + } + Infer.children(o, x -> scanLoaders(x, files, dirs, names, other, loaders)); + } + + private static boolean isStr(Node.Expr e) { + return e instanceof Constant && ((Constant) e).kind == Constant.Kind.STR; + } + + /// True when a module of the program imports jinja2 or flask, which + /// imports the generated module. + private static boolean imports(Map trees) { + boolean[] hit = {false}; + for (Node.Module m : trees.values()) { + Infer.children(m, c -> scanImports(c, hit)); + } + return hit[0]; + } + + private static void scanImports(Object o, boolean[] hit) { + if (o instanceof Node.Import) { + for (Node.Alias a : ((Node.Import) o).names) { + hit[0] |= isJinja(a.name); + } + } else if (o instanceof Node.ImportFrom && ((Node.ImportFrom) o).level == 0) { + hit[0] |= isJinja(((Node.ImportFrom) o).module); + } + if (!hit[0]) { + Infer.children(o, c -> scanImports(c, hit)); + } + } + + private static boolean isJinja(String m) { + return m != null && (m.equals("jinja2") || m.startsWith("jinja2.") || m.equals("flask") + || m.startsWith("flask.")); + } + + private static void accessor(StringBuilder out, String fn, Site s) { + boolean ident = s.key.matches("[A-Za-z_][A-Za-z0-9_]*") && !KEYWORDS.contains(s.key); + String attr = " try:\n return o." + s.key + "\n except AttributeError:\n pass\n"; + String item = " try:\n return o[" + str(s.key) + "]\n" + + " except (TypeError, LookupError, AttributeError):\n pass\n"; + out.append("\n\ndef ").append(fn).append("(o):\n"); + if (s.attr) { + if (ident) { + out.append(attr); + } + out.append(item); + } else { + out.append(item); + if (ident) { + out.append(attr); + } + } + out.append(" return MISS\n"); + } + + /// Module names bound exactly once, to a string literal. + private static Set literalNames(Node.Module tree) { + Map bindings = new java.util.HashMap(); + for (Node.Stmt s : tree.body) { + DataclassInit.count(s, bindings); + } + Set out = new HashSet(); + for (Node.Stmt s : tree.body) { + if (s instanceof Node.Assign && ((Node.Assign) s).targets.size() == 1 + && ((Node.Assign) s).targets.get(0) instanceof Name + && ((Node.Assign) s).value instanceof Constant + && ((Constant) ((Node.Assign) s).value).kind == Constant.Kind.STR) { + String n = ((Name) ((Node.Assign) s).targets.get(0)).id; + if (bindings.getOrDefault(n, 0) == 1) { + out.add(n); + } + } + } + return out; + } + + private static void walk(Object o, Set literals, boolean site, Set names) { + if (o instanceof Constant && ((Constant) o).kind == Constant.Kind.STR) { + String t = ((Constant) o).text; + if (t.contains("{{") || t.contains("{%")) { + literals.add(t); + } + return; + } + if (!site && o instanceof Call) { + Call c = (Call) o; + String f = c.func instanceof Name ? ((Name) c.func).id + : c.func instanceof Attribute ? ((Attribute) c.func).attr : null; + Node.Expr src = c.args.isEmpty() ? null : c.args.get(0); + if (src == null) { + for (Node.Keyword k : c.keywords) { + if ("source".equals(k.arg)) { + src = k.value; + } + } + } + if (f != null && CONSTRUCTORS.contains(f) && src != null + && !(src instanceof Constant && ((Constant) src).kind == Constant.Kind.STR) + && !(src instanceof Name && names.contains(((Name) src).id))) { + c.refusal = f + " with a template source computed at run time cannot be compiled at build" + + " time; give the source as a string literal"; + } + } + Infer.children(o, c -> walk(c, literals, site, names)); + } + + /// The sites of each var/block tag, in the order `jinja2._lex` emits them. + static List> tags(String src) { + List> out = new ArrayList>(); + int i = 0; + int n = src.length(); + while (i < n) { + int j = -1; + int k = i; + while (true) { + k = src.indexOf('{', k); + if (k < 0 || k + 1 >= n) { + break; + } + char c = src.charAt(k + 1); + if (c == '{' || c == '%' || c == '#') { + j = k; + break; + } + k++; + } + if (j < 0) { + break; + } + char kind = src.charAt(j + 1); + int start = j + 2; + if (start < n && (src.charAt(start) == '-' || src.charAt(start) == '+')) { + start++; + } + String close = kind == '{' ? "}}" : kind == '%' ? "%}" : "#}"; + int e = findClose(src, start, close, kind == '#'); + if (e < 0) { + throw new IllegalArgumentException("unexpected end of template"); + } + String inner = src.substring(start, e); + if (inner.endsWith("-") || inner.endsWith("+")) { + inner = inner.substring(0, inner.length() - 1); + } + i = e + 2; + if (kind == '#') { + continue; + } + inner = inner.trim(); + if (kind == '%' && "raw".equals(inner)) { + int m = src.indexOf("{%", i); + while (m >= 0) { + int q = src.indexOf("%}", m); + if (q < 0) { + throw new IllegalArgumentException("unterminated raw"); + } + if ("endraw".equals(strip(src.substring(m + 2, q)))) { + i = q + 2; + break; + } + m = src.indexOf("{%", m + 2); + } + continue; + } + out.add(sites(inner)); + } + return out; + } + + private static String strip(String s) { + int a = 0; + int b = s.length(); + while (a < b && " -+\t\r\n".indexOf(s.charAt(a)) >= 0) { + a++; + } + while (b > a && " -+\t\r\n".indexOf(s.charAt(b - 1)) >= 0) { + b--; + } + return s.substring(a, b); + } + + private static int findClose(String src, int start, String close, boolean comment) { + int i = start; + char q = 0; + int n = src.length(); + while (i < n) { + char c = src.charAt(i); + if (!comment) { + if (q != 0) { + if (c == '\\') { + i += 2; + continue; + } + if (c == q) { + q = 0; + } + i++; + continue; + } + if (c == '\'' || c == '"') { + q = c; + i++; + continue; + } + } + if (src.startsWith(close, i)) { + return i; + } + i++; + } + return -1; + } + + /// Tokens as `jinja2._tokenize` makes them: kind ("num", "name", "str", + /// "op", "end") and text; then the accessor sites in token order. + private static List sites(String s) { + List toks = new ArrayList(); + int i = 0; + int n = s.length(); + while (i < n) { + char c = s.charAt(i); + if (Character.isWhitespace(c)) { + i++; + } else if (Character.isDigit(c)) { + int j = i; + while (j < n && (Character.isDigit(s.charAt(j)) || s.charAt(j) == '_')) { + j++; + } + if (j + 1 < n && s.charAt(j) == '.' && Character.isDigit(s.charAt(j + 1))) { + j++; + while (j < n && Character.isDigit(s.charAt(j))) { + j++; + } + toks.add(new String[]{"num", String.valueOf(Double.parseDouble(s.substring(i, j) + .replace("_", "")))}); + } else { + toks.add(new String[]{"num", new java.math.BigInteger(s.substring(i, j).replace("_", "")) + .toString()}); + } + i = j; + } else if (Character.isLetter(c) || c == '_') { + int j = i; + while (j < n && (Character.isLetterOrDigit(s.charAt(j)) || s.charAt(j) == '_')) { + j++; + } + toks.add(new String[]{"name", s.substring(i, j)}); + i = j; + } else if (c == '\'' || c == '"') { + int j = i + 1; + StringBuilder buf = new StringBuilder(); + while (j < n && s.charAt(j) != c) { + if (s.charAt(j) == '\\' && j + 1 < n) { + j++; + char x = s.charAt(j); + buf.append(x == 'n' ? '\n' : x == 't' ? '\t' : x == 'r' ? '\r' : x); + } else { + buf.append(s.charAt(j)); + } + j++; + } + toks.add(new String[]{"str", buf.toString()}); + i = j + 1; + } else { + String two = i + 2 <= n ? s.substring(i, i + 2) : null; + if (two != null && Arrays.asList(OPS2).contains(two)) { + toks.add(new String[]{"op", two}); + i += 2; + } else { + toks.add(new String[]{"op", String.valueOf(c)}); + i++; + } + } + } + toks.add(new String[]{"end", "None"}); + List out = new ArrayList(); + for (int t = 0; t < toks.size() - 1; t++) { + String[] tok = toks.get(t); + if (!"op".equals(tok[0])) { + continue; + } + if (".".equals(tok[1])) { + String[] nt = toks.get(t + 1); + out.add(new Site(true, "end".equals(nt[0]) ? "" : nt[1])); + } else if ("[".equals(tok[1]) && "str".equals(toks.get(t + 1)[0]) && t + 2 < toks.size() + && "op".equals(toks.get(t + 2)[0]) && "]".equals(toks.get(t + 2)[1])) { + out.add(new Site(false, toks.get(t + 1)[1])); + } + } + return out; + } + + /// A Python string literal for `s`, ASCII only. + private static String str(String s) { + StringBuilder b = new StringBuilder("'"); + for (int i = 0; i < s.length(); i++) { + char c = s.charAt(i); + if (c == '\\' || c == '\'') { + b.append('\\').append(c); + } else if (c == '\n') { + b.append("\\n"); + } else if (c == '\r') { + b.append("\\r"); + } else if (c == '\t') { + b.append("\\t"); + } else if (c < 0x20 || c > 0x7e) { + b.append('\\').append('u').append(String.format("%04x", (int) c)); + } else { + b.append(c); + } + } + return b.append('\'').toString(); + } +} diff --git a/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/KnownHelpers.java b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/KnownHelpers.java new file mode 100644 index 00000000000..4e8c7e757d9 --- /dev/null +++ b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/KnownHelpers.java @@ -0,0 +1,372 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.python.transpiler.codegen; + +import com.codename1.python.transpiler.ast.Node; +import com.codename1.python.transpiler.ast.Node.Alias; +import com.codename1.python.transpiler.ast.Node.Assign; +import com.codename1.python.transpiler.ast.Node.Call; +import com.codename1.python.transpiler.ast.Node.ClassDef; +import com.codename1.python.transpiler.ast.Node.Constant; +import com.codename1.python.transpiler.ast.Node.Expr; +import com.codename1.python.transpiler.ast.Node.ExprStmt; +import com.codename1.python.transpiler.ast.Node.FunctionDef; +import com.codename1.python.transpiler.ast.Node.ImportFrom; +import com.codename1.python.transpiler.ast.Node.Name; +import com.codename1.python.transpiler.ast.Node.Stmt; +import com.codename1.python.transpiler.parser.Parser; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.regex.Pattern; + +/// Third-party helpers whose behaviour Codename One provides itself, at +/// compile time, wherever a package uses them. +/// +/// Some packages route ordinary calls through plumbing that does nothing a +/// program can observe and that defeats typing: a decorator that wraps a +/// method in a `(*args, **kwargs)` closure to emit a warning nobody sees, an +/// alias whose body is `getattr(self, new_name)`. Every caller of such a +/// method then reaches a function of unknown type, and every class it is on +/// is loose. The helpers are rewritten where they are used, right after +/// parsing, into what they mean: +/// +/// - bs4's `@_deprecated(...)` (bs4._deprecation) leaves the method as it +/// is, with the warning the wrapper issued as its first statement. +/// - `X = _deprecated_alias("X", "y", v)` in a class body is a property that +/// warns and reads or writes `self.y`. +/// - `X = _deprecated_function_alias("X", "y", v)` is a method that warns and +/// calls `self.y` with what it was given. +/// +/// Each warning is the helper's own `DeprecationWarning`, issued with the +/// same message and stack level, so where Python shows one (a call from +/// `__main__`) it is shown here too. The method keeps its own `__name__`, +/// as `functools.wraps` made the wrapper report; an alias reports its own +/// name where bs4's said `alias`. +/// +/// A use that does not have this exact shape -- names that are not string +/// literals, the helper called anywhere but a class body -- is left alone +/// and compiled as the package wrote it. +public final class KnownHelpers { + private enum Kind { DROP_DECORATOR, PROPERTY_ALIAS, METHOD_ALIAS } + + /// Module and function name to what the helper is. + private static final Map HELPERS = new HashMap(); + + static { + HELPERS.put("bs4._deprecation._deprecated", Kind.DROP_DECORATOR); + HELPERS.put("bs4._deprecation._deprecated_alias", Kind.PROPERTY_ALIAS); + HELPERS.put("bs4._deprecation._deprecated_function_alias", Kind.METHOD_ALIAS); + } + + private static final Pattern IDENTIFIER = Pattern.compile("[A-Za-z_][A-Za-z0-9_]*"); + + private KnownHelpers() { + } + + /// Rewrites the uses in `tree`, the module at relative path `path`. + public static void rewrite(Node.Module tree, String path) { + Map local = imported(tree, path); + if (local.isEmpty()) { + return; + } + boolean[] used = {false}; + for (Stmt s : tree.body) { + visit(s, local, path, used); + } + if (used[0]) { + // The module the rewritten members warn through, after its + // docstring and `from __future__` imports. + int at = 0; + while (at < tree.body.size() && (docstring(tree.body.get(at)) + || tree.body.get(at) instanceof ImportFrom && "__future__".equals(((ImportFrom) tree.body.get(at)).module))) { + at++; + } + Stmt imp = Parser.parse("import warnings as " + WARNINGS + "\n", path).body.get(0); + at(imp, tree.body.isEmpty() ? 1 : tree.body.get(Math.min(at, tree.body.size() - 1)).line); + tree.body.add(at, imp); + } + dropImports(tree, path, local.keySet()); + } + + /// Takes the helpers out of the imports that bind them once nothing in + /// the module names them any more: a package `__init__` that imported + /// one would otherwise keep it, and everything it does, alive as one of + /// the package's attributes. + private static void dropImports(Node.Module tree, String path, java.util.Set helpers) { + java.util.Set named = new java.util.HashSet(); + for (Stmt s : tree.body) { + if (!(s instanceof ImportFrom)) { + names(s, named); + } + } + for (int i = tree.body.size() - 1; i >= 0; i--) { + Stmt s = tree.body.get(i); + if (!(s instanceof ImportFrom) || absolute((ImportFrom) s, path) == null) { + continue; + } + List keep = new ArrayList(); + for (Alias a : ((ImportFrom) s).names) { + String bound = a.asname != null ? a.asname : a.name; + if (!helpers.contains(bound) || named.contains(bound)) { + keep.add(a); + } + } + if (keep.size() == ((ImportFrom) s).names.size()) { + continue; + } + if (keep.isEmpty()) { + tree.body.remove(i); + } else { + ImportFrom f = new ImportFrom(((ImportFrom) s).module, ((ImportFrom) s).level, keep); + f.line = s.line; + tree.body.set(i, f); + } + } + } + + /// Every name `o` reads, and every string under it (an `__all__` entry + /// names an attribute too). + private static void names(Object o, java.util.Set out) { + if (o instanceof Name) { + out.add(((Name) o).id); + } else if (o instanceof Constant && ((Constant) o).kind == Constant.Kind.STR) { + out.add(((Constant) o).text); + } + Infer.children(o, x -> names(x, out)); + } + + /// The name the rewritten members reach `warnings` by: one no package + /// spells. + private static final String WARNINGS = "_cn1_warnings"; + + private static boolean docstring(Stmt s) { + return s instanceof ExprStmt && ((ExprStmt) s).value instanceof Constant + && ((Constant) ((ExprStmt) s).value).kind == Constant.Kind.STR; + } + + /// The helpers `tree` imports at module level, by the name it binds. + private static Map imported(Node.Module tree, String path) { + Map r = new HashMap(); + for (Stmt s : tree.body) { + if (!(s instanceof ImportFrom)) { + continue; + } + String module = absolute((ImportFrom) s, path); + if (module == null) { + continue; + } + for (Alias a : ((ImportFrom) s).names) { + Kind k = HELPERS.get(module + "." + a.name); + if (k != null) { + r.put(a.asname != null ? a.asname : a.name, k); + } + } + } + // A module that binds one of those names again (a def, an + // assignment) means something else by it. + for (Stmt s : tree.body) { + if (s instanceof FunctionDef) { + r.remove(((FunctionDef) s).name); + } else if (s instanceof ClassDef) { + r.remove(((ClassDef) s).name); + } else if (s instanceof Assign) { + for (Expr t : ((Assign) s).targets) { + if (t instanceof Name) { + r.remove(((Name) t).id); + } + } + } + } + return r; + } + + /// The dotted module an import names, relative ones resolved against + /// `path`; null when it climbs out of the tree. + private static String absolute(ImportFrom f, String path) { + if (f.level == 0) { + return f.module; + } + String[] parts = path.replace('\\', '/').split("/"); + // The package a module is in is its directory, `__init__.py` too. + int keep = parts.length - 1 - (f.level - 1); + if (keep < 0) { + return null; + } + StringBuilder b = new StringBuilder(); + for (int i = 0; i < keep; i++) { + b.append(b.length() == 0 ? "" : ".").append(parts[i]); + } + if (f.module != null) { + b.append(b.length() == 0 ? "" : ".").append(f.module); + } + return b.toString(); + } + + private static void visit(Stmt s, Map local, String path, boolean[] used) { + if (s instanceof FunctionDef) { + unwrap((FunctionDef) s, local, path, used); + } else if (s instanceof ClassDef) { + ClassDef c = (ClassDef) s; + for (int i = 0; i < c.body.size(); i++) { + Stmt m = c.body.get(i); + List with = alias(m, local, path); + if (with != null) { + used[0] = true; + c.body.remove(i); + c.body.addAll(i, with); + i += with.size() - 1; + } else { + visit(m, local, path, used); + } + } + } + } + + /// Takes a `@_deprecated(replaced_by, version)` off `f`, issuing its + /// warning as `f`'s first statement (after a docstring) instead. Only + /// with literal arguments: the message is built from them. + private static void unwrap(FunctionDef f, Map local, String path, boolean[] used) { + for (int i = f.decorators.size() - 1; i >= 0; i--) { + Expr d = f.decorators.get(i); + if (!(d instanceof Call) || !(((Call) d).func instanceof Name) + || local.get(((Name) ((Call) d).func).id) != Kind.DROP_DECORATOR) { + continue; + } + Call c = (Call) d; + String by = argument(c, 0, "replaced_by"); + String version = by != null ? argument(c, 1, "version") : null; + if (version == null) { + continue; + } + Stmt warn = Parser.parse(warn("Call to deprecated method " + f.name + ". (Replaced by " + by + + ") -- Deprecated since version " + version + ".") + "\n", path).body.get(0); + int line = f.body.isEmpty() ? f.line : f.body.get(0).line; + at(warn, line); + f.body.add(!f.body.isEmpty() && docstring(f.body.get(0)) ? 1 : 0, warn); + f.decorators.remove(i); + used[0] = true; + } + } + + /// A statement issuing a `DeprecationWarning` with message `m`, at the + /// stack level bs4's helpers use: the caller of the deprecated member. + private static String warn(String m) { + return WARNINGS + ".warn(" + pyStr(m) + ", DeprecationWarning, stacklevel=2)"; + } + + /// `s` as a Python string literal. + private static String pyStr(String s) { + StringBuilder b = new StringBuilder("\""); + for (int i = 0; i < s.length(); i++) { + char ch = s.charAt(i); + if (ch == '\\' || ch == '"') { + b.append('\\').append(ch); + } else if (ch < 0x20 || ch > 0x7e) { + b.append(String.format("\\U%08x", (int) ch)); + } else { + b.append(ch); + } + } + return b.append('"').toString(); + } + + /// What class-body statement `s` means when it binds an alias, or null. + private static List alias(Stmt s, Map local, String path) { + if (!(s instanceof Assign) || ((Assign) s).targets.size() != 1 + || !(((Assign) s).targets.get(0) instanceof Name) || !(((Assign) s).value instanceof Call)) { + return null; + } + Call c = (Call) ((Assign) s).value; + if (!(c.func instanceof Name) || !c.keywords.isEmpty() || c.args.size() < 2) { + return null; + } + Kind k = local.get(((Name) c.func).id); + String name = ((Name) ((Assign) s).targets.get(0)).id; + String old = literal(c.args.get(0)); + String to = literal(c.args.get(1)); + String version = c.args.size() == 3 ? literal(c.args.get(2)) : null; + if (k == null || k == Kind.DROP_DECORATOR || old == null || to == null || version == null + || !IDENTIFIER.matcher(to).matches()) { + return null; + } + String tail = ". (Replaced by " + to + ") -- Deprecated since version " + version + "."; + String src; + if (k == Kind.PROPERTY_ALIAS) { + src = "class _Alias:\n" + + " @property\n" + + " def " + name + "(self):\n" + + " " + warn("Access to deprecated property " + old + tail) + "\n" + + " return self." + to + "\n" + + " @" + name + ".setter\n" + + " def " + name + "(self, value):\n" + + " " + warn("Write to deprecated property " + old + tail) + "\n" + + " self." + to + " = value\n"; + } else { + src = "class _Alias:\n" + + " def " + name + "(self, *args, **kwargs):\n" + + " " + warn("Call to deprecated method " + old + tail) + "\n" + + " return self." + to + "(*args, **kwargs)\n"; + } + Node.Module m = Parser.parse(src, path); + List r = new ArrayList(((ClassDef) m.body.get(0)).body); + for (Stmt x : r) { + at(x, s.line); + } + return r; + } + + /// Puts `o` and everything under it on `line`: a message about the + /// alias names the package's own line. + private static void at(Object o, int line) { + if (o instanceof Node) { + ((Node) o).line = line; + } + Infer.children(o, x -> at(x, line)); + } + + /// The string literal passed as parameter `name`, at position `pos` + /// or by keyword, of a call taking exactly (replaced_by, version); + /// null for any other shape. + private static String argument(Call c, int pos, String name) { + if (c.args.size() + c.keywords.size() != 2) { + return null; + } + if (pos < c.args.size()) { + return literal(c.args.get(pos)); + } + for (Node.Keyword k : c.keywords) { + if (name.equals(k.arg)) { + return literal(k.value); + } + } + return null; + } + + private static String literal(Expr e) { + return e instanceof Constant && ((Constant) e).kind == Constant.Kind.STR ? ((Constant) e).text : null; + } +} diff --git a/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/KwAttrInit.java b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/KwAttrInit.java new file mode 100644 index 00000000000..eda4f251895 --- /dev/null +++ b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/KwAttrInit.java @@ -0,0 +1,1031 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.python.transpiler.codegen; + +import com.codename1.python.transpiler.ast.Node; +import com.codename1.python.transpiler.ast.Node.Attribute; +import com.codename1.python.transpiler.ast.Node.Call; +import com.codename1.python.transpiler.ast.Node.ClassDef; +import com.codename1.python.transpiler.ast.Node.Constant; +import com.codename1.python.transpiler.ast.Node.Expr; +import com.codename1.python.transpiler.ast.Node.FunctionDef; +import com.codename1.python.transpiler.ast.Node.Keyword; +import com.codename1.python.transpiler.ast.Node.Name; +import com.codename1.python.transpiler.ast.Node.Stmt; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.IdentityHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/// Lowers a constructor that stores its keyword arguments as attributes, +/// +/// ```python +/// class Descriptor: +/// def __init__(self, name=None, **kw): +/// self.name = name +/// for k, v in kw.items(): +/// setattr(self, k, v) +/// ``` +/// +/// to one literal store per keyword the closed program can pass: +/// +/// ```python +/// if "expected_type" in kw: +/// self.expected_type = kw["expected_type"] +/// if "allow_none" in kw: +/// self.allow_none = kw["allow_none"] +/// ``` +/// +/// The keys that can reach `kw` are the literal keywords of every call of +/// the class or of a subclass (openpyxl's `Typed(expected_type=X, +/// allow_none=True)` in class bodies), of every `super().__init__` and +/// `X.__init__` in the family, and the literal keys a subclass's own +/// `__init__` writes into its `**kw` before forwarding it (`Set` replaces +/// `kw['values']`). A key nobody passes simply finds its test false, so the +/// union over all sites is exact for every one of them. +/// +/// It refuses anything it cannot see: a family class name used other than +/// to call it, subclass it or test `isinstance` against it (an escaped class +/// object can be called with any keywords); a `**mapping` that is not the +/// enclosing family `__init__`'s own `**kw`; a family `__init__` using its +/// `**kw` other than forwarding it or reading and writing literal keys; a +/// `cls(...)`, `type(...)(...)` or `__class__` call in the family; a family +/// class that defines `__setattr__`, or binds one of the keys to a method or +/// to a family instance (a store there could run code, and the fixed order +/// of the tests would then be observable where the order of `kw` was). +public final class KwAttrInit { + + private KwAttrInit() { + } + + /// Lowers every qualifying constructor among `trees`; `libTrees` are the + /// bundled modules, read only so their uses count against the rewrite. + public static void rewrite(Map trees, Map libTrees) { + List all = new ArrayList(trees.values()); + all.addAll(libTrees.values()); + Map keyed = new HashMap(libTrees); + keyed.putAll(trees); + List classes = new ArrayList(); + for (Node.Module m : all) { + collect(m, classes); + } + for (Map.Entry e : trees.entrySet()) { + List mine = new ArrayList(); + collect(e.getValue(), mine); + for (ClassDef root : mine) { + FunctionDef init = method(root, "__init__"); + if (init == null || init.args.kwarg == null) { + continue; + } + Node.For loop = loop(init); + if (loop == null) { + continue; + } + lower(e.getKey(), root, init, loop, classes, all, keyed); + } + } + } + + private static void collect(Object o, final List out) { + if (o instanceof ClassDef) { + out.add((ClassDef) o); + } + Infer.children(o, x -> collect(x, out)); + } + + private static FunctionDef method(ClassDef c, String name) { + for (Stmt s : c.body) { + if (s instanceof FunctionDef && ((FunctionDef) s).name.equals(name)) { + return (FunctionDef) s; + } + } + return null; + } + + /// The `for k, v in kw.items(): setattr(self, k, v)` statement of `init`, + /// with `kw` used nowhere else in it, or null. + private static Node.For loop(FunctionDef init) { + if (init.args.positional.isEmpty()) { + return null; + } + String kw = init.args.kwarg.name; + String self = init.args.positional.get(0).name; + Node.For found = null; + for (Stmt s : init.body) { + if (!(s instanceof Node.For)) { + continue; + } + Node.For f = (Node.For) s; + if (f.isAsync || !f.orelse.isEmpty() || f.body.size() != 1 + || !(f.target instanceof Node.TupleExpr) || !(f.iter instanceof Call)) { + continue; + } + List t = ((Node.TupleExpr) f.target).elts; + Call it = (Call) f.iter; + if (t.size() != 2 || !(t.get(0) instanceof Name) || !(t.get(1) instanceof Name) + || !it.args.isEmpty() || !it.keywords.isEmpty() || !(it.func instanceof Attribute) + || !"items".equals(((Attribute) it.func).attr) + || !isName(((Attribute) it.func).value, kw)) { + continue; + } + Stmt b = f.body.get(0); + if (!(b instanceof Node.ExprStmt) || !(((Node.ExprStmt) b).value instanceof Call)) { + continue; + } + Call sa = (Call) ((Node.ExprStmt) b).value; + if (isName(sa.func, "setattr") && sa.args.size() == 3 && sa.keywords.isEmpty() + && isName(sa.args.get(0), self) && isName(sa.args.get(1), ((Name) t.get(0)).id) + && isName(sa.args.get(2), ((Name) t.get(1)).id)) { + found = f; + } + } + if (found == null || uses(init.body, kw) != 1 || uses(init.body, "setattr") != 1) { + return null; + } + return found; + } + + private static boolean isName(Object e, String id) { + return e instanceof Name && ((Name) e).id.equals(id); + } + + private static int uses(Object o, final String id) { + final int[] n = {0}; + countUses(o, id, n); + return n[0]; + } + + private static void countUses(Object o, final String id, final int[] n) { + if (isName(o, id)) { + n[0]++; + } + Infer.children(o, x -> countUses(x, id, n)); + } + + private static String nameOf(Expr e) { + if (e instanceof Name) { + return ((Name) e).id; + } + if (e instanceof Attribute) { + return ((Attribute) e).attr; + } + return null; + } + + /// Context of one family check. + private static final class Ctx { + final Set family = new LinkedHashSet(); + final Set keys = new LinkedHashSet(); + final IdentityHashMap allowed = new IdentityHashMap(); + final Set famIds = new HashSet(); + final IdentityHashMap famDefs = new IdentityHashMap(); + Resolver res; + String mod; + /// Attributes a family class object is stored in. + final Set escAttrs = new LinkedHashSet(); + final Set members = new HashSet(); + final IdentityHashMap escClasses = new IdentityHashMap(); + final Set mixAncestors = new HashSet(); + final IdentityHashMap shadowed = new IdentityHashMap(); + final Set classNames = new HashSet(); + ClassDef readCls; + String refusal; + + List famDefsList() { + return new ArrayList(famDefs.keySet()); + } + } + + private static String modName(String key) { + String k = key.replace('\\', '/'); + if (k.endsWith(".py")) { + k = k.substring(0, k.length() - 3); + } + if (k.endsWith("/__init__")) { + k = k.substring(0, k.length() - 9); + } + return k.replace('/', '.'); + } + + /// Resolves the global class a module-level name binds, `mod:Name`, by + /// following `from ... import` chains; null when it is not a class the + /// program defines at module level. + static final class Resolver { + final Map mods = new HashMap(); + final Set pkgs = new HashSet(); + + Resolver(Map trees) { + for (Map.Entry e : trees.entrySet()) { + String m = modName(e.getKey()); + mods.put(m, e.getValue()); + if (e.getKey().replace('\\', '/').endsWith("__init__.py")) { + pkgs.add(m); + } + } + } + + String target(String mod, Node.ImportFrom f) { + if (f.level == 0) { + return f.module; + } + String base = pkgs.contains(mod) ? mod : (mod.lastIndexOf('.') < 0 ? "" : mod.substring(0, mod.lastIndexOf('.'))); + for (int i = 1; i < f.level; i++) { + base = base.lastIndexOf('.') < 0 ? "" : base.substring(0, base.lastIndexOf('.')); + } + return f.module == null ? base : (base.isEmpty() ? f.module : base + "." + f.module); + } + + String resolve(String mod, String name, int depth) { + Node.Module m = mods.get(mod); + if (m == null || depth > 12) { + return null; + } + for (Stmt s : m.body) { + if (s instanceof ClassDef && ((ClassDef) s).name.equals(name)) { + return mod + ":" + name; + } + } + for (Stmt s : m.body) { + // `Coordinate = Integer`: a module-level alias of a class. + if (alias(s, name) != null) { + return resolve(mod, alias(s, name).id, depth + 1); + } + } + List froms = new ArrayList(); + gather(m, froms); + for (Node.ImportFrom f : froms) { + for (Node.Alias a : f.names) { + if (!"*".equals(a.name) && name.equals(a.asname != null ? a.asname : a.name)) { + String r = resolve(target(mod, f), a.name, depth + 1); + if (r != null) { + return r; + } + } + } + } + for (Node.ImportFrom f : froms) { + if (f.names.size() == 1 && "*".equals(f.names.get(0).name)) { + String r = resolve(target(mod, f), name, depth + 1); + if (r != null) { + return r; + } + } + } + return null; + } + + /// The module `e` names in `mod` (`import a.b as c`, `from a import b`, + /// `a.b`), or null. + String moduleOf(String mod, Expr e) { + if (e instanceof Attribute) { + String m = moduleOf(mod, ((Attribute) e).value); + String r = m == null ? null : m + "." + ((Attribute) e).attr; + return r != null && mods.containsKey(r) ? r : null; + } + if (!(e instanceof Name) || mods.get(mod) == null) { + return null; + } + String id = ((Name) e).id; + List froms = new ArrayList(); + List imps = new ArrayList(); + gather(mods.get(mod), froms); + gatherImports(mods.get(mod), imps); + for (Node.ImportFrom f : froms) { + for (Node.Alias a : f.names) { + if (id.equals(a.asname != null ? a.asname : a.name)) { + String r = target(mod, f) + "." + a.name; + if (mods.containsKey(r)) { + return r; + } + } + } + } + for (Node.Import i : imps) { + for (Node.Alias a : i.names) { + if (a.asname != null ? id.equals(a.asname) : id.equals(a.name.split("\\.")[0])) { + String r = a.asname != null ? a.name : id; + if (mods.containsKey(r)) { + return r; + } + } + } + } + return null; + } + + private static void gatherImports(Object o, final List out) { + if (o instanceof Node.Import) { + out.add((Node.Import) o); + } + Infer.children(o, x -> gatherImports(x, out)); + } + + /// The class name `s` binds `name` to, when it is `name = Other`. + static Name alias(Stmt s, String name) { + if (s instanceof Node.Assign && ((Node.Assign) s).targets.size() == 1 + && isName(((Node.Assign) s).targets.get(0), name) + && ((Node.Assign) s).value instanceof Name + && !((Name) ((Node.Assign) s).value).id.equals(name)) { + return (Name) ((Node.Assign) s).value; + } + return null; + } + + private static void gather(Object o, final List out) { + if (o instanceof Node.ImportFrom) { + out.add((Node.ImportFrom) o); + } + Infer.children(o, x -> gather(x, out)); + } + } + + private static boolean isFamily(Ctx c, Expr e) { + if (e instanceof Name) { + return c.famIds.contains(c.res.resolve(c.mod, ((Name) e).id, 0)); + } + if (e instanceof Attribute) { + // `base.Typed`: only a module's attribute can name a class + // without a Name having escaped first. + String m = c.res.moduleOf(c.mod, ((Attribute) e).value); + return m != null && c.famIds.contains(c.res.resolve(m, ((Attribute) e).attr, 0)); + } + return false; + } + + private static void lower(String path, ClassDef root, FunctionDef init, Node.For loop, + List classes, List all, Map trees) { + Ctx c = new Ctx(); + c.res = new Resolver(trees); + c.famIds.add(modName(path) + ":" + root.name); + c.family.add(root.name); + c.famDefs.put(root, Boolean.TRUE); + boolean grew = true; + while (grew) { + grew = false; + for (Map.Entry e : trees.entrySet()) { + c.mod = modName(e.getKey()); + for (Stmt s : e.getValue().body) { + if (!(s instanceof ClassDef) || c.famDefs.containsKey(s)) { + continue; + } + ClassDef k = (ClassDef) s; + for (Expr b : k.bases) { + if (isFamily(c, b)) { + c.famDefs.put(k, Boolean.TRUE); + c.famIds.add(c.mod + ":" + k.name); + c.family.add(k.name); + grew = true; + break; + } + } + } + } + } + for (ClassDef k : classes) { + if (!c.famDefs.containsKey(k)) { + for (Expr b : k.bases) { + if (!isTop(trees, k) && (b instanceof Name && c.family.contains(((Name) b).id) + || b instanceof Attribute && c.family.contains(((Attribute) b).attr))) { + // A base this pass cannot resolve to a module-level + // class might be one of the family. + c.refusal = k.name + " has an unresolved family base"; + } + } + } + } + for (ClassDef k : c.famDefsList()) { + for (Expr b : k.bases) { + c.allowed.put(b, Boolean.TRUE); + } + } + for (ClassDef k : classes) { + for (Expr b : k.bases) { + if (nameOf(b) != null) { + c.classNames.add(nameOf(b)); + } + } + } + String top = path.replace('\\', '/').split("[/.]")[0]; + for (Node.Module m : all) { + for (Stmt s : m.body) { + if (s instanceof Node.Assign && ((Node.Assign) s).targets.size() == 1 + && ((Node.Assign) s).targets.get(0) instanceof Name + && Resolver.alias(s, ((Name) ((Node.Assign) s).targets.get(0)).id) != null + && once(m, ((Name) ((Node.Assign) s).targets.get(0)).id)) { + c.allowed.put(((Node.Assign) s).value, Boolean.TRUE); + c.allowed.put(((Node.Assign) s).targets.get(0), Boolean.TRUE); + c.family.add(((Name) ((Node.Assign) s).targets.get(0)).id); + } + } + } + for (Node.Module m : all) { + if (relevant(m, top)) { + c.mod = null; + for (Map.Entry e : trees.entrySet()) { + if (e.getValue() == m) { //NOPMD CompareObjectsWithEquals - identity is meant + c.mod = modName(e.getKey()); + } + } + if (c.mod == null) { + c.refusal = "a bundled module imports " + top; + } + } else { + c.mod = null; + for (Map.Entry e : trees.entrySet()) { + if (e.getValue() == m && modName(e.getKey()).startsWith(top + ".")) { //NOPMD CompareObjectsWithEquals - identity is meant + c.mod = modName(e.getKey()); + } + } + if (c.mod == null) { + // Neither in the root's package nor importing from it: + // its `Sequence` is another one. + continue; + } + } + walk(m, c, null, null, loop); + } + // Every class an instance holding a stored class could also be: the + // ancestors of the family and of the classes storing one. + List holders = c.famDefsList(); + for (Object k : c.escClasses.keySet()) { + holders.add((ClassDef) k); + } + for (ClassDef k : holders) { + for (Expr b : k.bases) { + c.mixAncestors.add(nameOf(b)); + } + } + boolean more = true; + while (more) { + more = false; + for (ClassDef k : classes) { + if (c.mixAncestors.contains(k.name)) { + for (Expr b : k.bases) { + more |= nameOf(b) != null && c.mixAncestors.add(nameOf(b)); + } + } + } + } + for (Object k : c.shadowed.keySet()) { + if (c.refusal == null && (c.classNames.contains(((ClassDef) k).name) + || nameEscapes(all, ((ClassDef) k).name, c))) { + c.escAttrs.add(c.shadowed.get(k)); + } + } + if (c.refusal == null && !c.escAttrs.isEmpty()) { + for (ClassDef k : c.famDefsList()) { + for (Stmt st : k.body) { + if (st instanceof FunctionDef) { + c.members.add(((FunctionDef) st).name); + } else if (st instanceof Node.Assign) { + for (Expr t : ((Node.Assign) st).targets) { + if (t instanceof Name) { + c.members.add(((Name) t).id); + } + } + } + } + } + for (String a : c.escAttrs) { + if (c.keys.contains(a) && kwRead(all, a)) { + c.refusal = "a family __init__ reads " + a + " from its **kw"; + } + } + for (Map.Entry e : trees.entrySet()) { + c.mod = modName(e.getKey()); + reads(e.getValue(), c, null, new IdentityHashMap()); + } + } + if (c.refusal == null) { + for (ClassDef k : c.famDefsList()) { + for (Stmt s : k.body) { + // A plain def is not a data descriptor: `self.to_tree = f` + // only fills the instance dictionary. A decorated one + // (a property) would run code on the store. + if (s instanceof FunctionDef && ("__setattr__".equals(((FunctionDef) s).name) + || c.keys.contains(((FunctionDef) s).name) + && !((FunctionDef) s).decorators.isEmpty())) { + c.refusal = k.name + " binds " + ((FunctionDef) s).name; + } else if (s instanceof Node.Assign && ((Node.Assign) s).value instanceof Call + && c.family.contains(nameOf(((Call) ((Node.Assign) s).value).func))) { + // By simple name: a superset, so only ever a refusal too many. + for (Expr t : ((Node.Assign) s).targets) { + if (t instanceof Name && c.keys.contains(((Name) t).id)) { + c.refusal = k.name + " binds " + ((Name) t).id + " to a descriptor"; + } + } + } + } + } + } + if (c.refusal != null) { + if (System.getenv("CN1_PY_KWATTR_DEBUG") != null) { + System.err.println("KwAttrInit: " + root.name + " in " + path + " refused: " + c.refusal); + } + return; + } + String kw = init.args.kwarg.name; + String self = init.args.positional.get(0).name; + StringBuilder b = new StringBuilder("def _cn1_kw(" + self + ", **" + kw + "):\n"); + for (String k : c.keys) { + if (!ConstArgSpecialize.ident(k)) { + return; + } + b.append(" if \"").append(k).append("\" in ").append(kw).append(":\n ") + .append(self).append('.').append(k).append(" = ").append(kw) + .append("[\"").append(k).append("\"]\n"); + } + if (c.keys.isEmpty()) { + b.append(" pass\n"); + } + FunctionDef f = ConstArgSpecialize.parseMethod(b.toString(), loop.line, path); + int at = init.body.indexOf(loop); + init.body.remove(at); + init.body.addAll(at, f.body); + } + + /// True when some subscript or `get`/`pop` call reads the literal key `a`. + private static boolean kwRead(List all, final String a) { + final boolean[] r = {false}; + for (Node.Module m : all) { + keyRead(m, a, r); + } + return r[0]; + } + + private static void keyRead(Object o, final String a, final boolean[] r) { + if (o instanceof Node.Subscript && ((Node.Subscript) o).index instanceof Constant + && a.equals(((Constant) ((Node.Subscript) o).index).text) + || o instanceof Call && ((Call) o).func instanceof Attribute && !((Call) o).args.isEmpty() + && ((Call) o).args.get(0) instanceof Constant + && a.equals(((Constant) ((Call) o).args.get(0)).text)) { + r[0] = true; + } + Infer.children(o, x -> keyRead(x, a, r)); + } + + /// Whether `e` reads a stored family class: `x.`, or + /// the parameter `param` a checked function received one in. + private static boolean holds(Ctx c, Object e, String param) { + if (e instanceof Attribute && isName(((Attribute) e).value, "self") && c.readCls != null + && !c.famDefs.containsKey(c.readCls) && !c.escClasses.containsKey(c.readCls) + && !c.mixAncestors.contains(c.readCls.name) && !c.classNames.contains(c.readCls.name)) { + // `self` of a class no holder can be an instance of. + return false; + } + return e instanceof Attribute && c.escAttrs.contains(((Attribute) e).attr) + || param != null && isName(e, param); + } + + private static final Set INSPECT = new HashSet(java.util.Arrays.asList( + "isinstance", "issubclass", "hasattr", "str", "repr", "id", "callable", "print")); + + /// Checks every read of a stored family class in `o`. A read may test + /// it, format it, iterate it, read a member no family class defines, + /// call it with positional arguments only, or hand it positionally to a + /// module-level function whose parameter obeys the same rules; anything + /// else could reach a constructor with keywords no call site shows. + private static void reads(Object o, final Ctx c, final String param, final IdentityHashMap ok) { + if (c.refusal != null) { + return; + } + if (o instanceof Node.Assign) { + for (Expr t : ((Node.Assign) o).targets) { + ok.put(t, Boolean.TRUE); + } + } else if (o instanceof Node.Delete) { + for (Expr t : ((Node.Delete) o).targets) { + ok.put(t, Boolean.TRUE); + } + } else if (o instanceof Node.AugAssign) { + ok.put(((Node.AugAssign) o).target, Boolean.TRUE); + } else if (o instanceof Node.FormattedValue) { + ok.put(((Node.FormattedValue) o).value, Boolean.TRUE); + } else if (o instanceof Node.For) { + ok.put(((Node.For) o).iter, Boolean.TRUE); + } else if (o instanceof Node.Comprehension) { + ok.put(((Node.Comprehension) o).iter, Boolean.TRUE); + } else if (o instanceof Node.If) { + ok.put(((Node.If) o).test, Boolean.TRUE); + } else if (o instanceof Node.Compare) { + ok.put(((Node.Compare) o).left, Boolean.TRUE); + for (Expr x : ((Node.Compare) o).comparators) { + ok.put(x, Boolean.TRUE); + } + } else if (o instanceof Attribute && holds(c, ((Attribute) o).value, param)) { + String a = ((Attribute) o).attr; + // A member is a function or a value: calling a method unbound + // constructs nothing (a family body never calls `cls(...)`), so + // only `__init__`, `__call__` and the other dunders are refused. + if ((!a.startsWith("__") || "__name__".equals(a) || "__doc__".equals(a)) + && !c.shadowed.containsValue(a)) { + ok.put(((Attribute) o).value, Boolean.TRUE); + } + } else if (o instanceof Call) { + Call call = (Call) o; + String n = call.func instanceof Name ? ((Name) call.func).id : null; + if (holds(c, call.func, param) && call.keywords.isEmpty()) { + ok.put(call.func, Boolean.TRUE); + } + for (int i = 0; i < call.args.size(); i++) { + Expr x = call.args.get(i); + if (!holds(c, x, param)) { + continue; + } + if (n != null && INSPECT.contains(n) && c.res.resolve(c.mod, n, 0) == null) { + ok.put(x, Boolean.TRUE); + } else if (n != null && param == null) { + FunctionDef f = topFunction(c, n); + if (f != null && i < f.args.positional.size() && f.args.positional.size() >= call.args.size() + && f.decorators.isEmpty()) { + String p = f.args.positional.get(i).name; + if (bindCount(f.body, p) == 0) { + ok.put(x, Boolean.TRUE); + reads(f.body, c, p, new IdentityHashMap()); + } + } + } + } + } else if (o instanceof ClassDef) { + ClassDef was = c.readCls; + c.readCls = (ClassDef) o; + Infer.children(o, x -> reads(x, c, param, ok)); + c.readCls = was; + return; + } else if (o instanceof Attribute && c.readCls != null && isName(((Attribute) o).value, "self") + && ((Attribute) o).attr.equals(c.shadowed.get(c.readCls))) { + return; + } + if (holds(c, o, param) && !ok.containsKey(o)) { + c.refusal = "a stored family class is read at " + c.mod + ":" + ((Node) o).line + " " + + ConstArgSpecialize.dump(o); + return; + } + Infer.children(o, x -> reads(x, c, param, ok)); + } + + /// The module-level function `name` binds in the current module, or null. + private static FunctionDef topFunction(Ctx c, String name) { + Node.Module m = c.res.mods.get(c.mod); + if (m == null) { + return null; + } + for (Stmt s : m.body) { + if (s instanceof FunctionDef && ((FunctionDef) s).name.equals(name)) { + return bindCount(m, name) == 2 ? (FunctionDef) s : null; + } + } + // Imported: resolve through `from x import name`. + List froms = new ArrayList(); + Resolver.gather(m, froms); + for (Node.ImportFrom f : froms) { + for (Node.Alias a : f.names) { + if (name.equals(a.asname != null ? a.asname : a.name)) { + Node.Module t = c.res.mods.get(c.res.target(c.mod, f)); + if (t != null) { + for (Stmt s : t.body) { + if (s instanceof FunctionDef && ((FunctionDef) s).name.equals(a.name)) { + return (FunctionDef) s; + } + } + } + } + } + } + return null; + } + + /// True when `name` is bound exactly once anywhere in `m`. + private static boolean once(Node m, String name) { + return bindCount(m, name) == 1; + } + + /// Assignments of `name` in `o`, a def or class of it counting two. + private static int bindCount(Object o, String name) { + final int[] n = {0}; + binds(o, name, n); + return n[0]; + } + + private static void binds(Object o, final String name, final int[] n) { + if (o instanceof Node.Assign) { + for (Expr t : ((Node.Assign) o).targets) { + countUses(t, name, n); + } + } else if (o instanceof Node.AugAssign) { + countUses(((Node.AugAssign) o).target, name, n); + } else if (o instanceof Node.AnnAssign) { + countUses(((Node.AnnAssign) o).target, name, n); + } else if (o instanceof Node.For) { + countUses(((Node.For) o).target, name, n); + } else if (o instanceof FunctionDef && ((FunctionDef) o).name.equals(name) + || o instanceof ClassDef && ((ClassDef) o).name.equals(name)) { + n[0] += 2; + } else if (o instanceof Node.Global) { + n[0] += 2; + } + Infer.children(o, x -> binds(x, name, n)); + } + + /// True when a Name `name` is used anywhere other than to call it or + /// test `isinstance` against it (by simple name: a superset). + private static boolean nameEscapes(List all, String name, Ctx c) { + final IdentityHashMap ok = new IdentityHashMap(); + final boolean[] r = {false}; + for (Node.Module m : all) { + escapes(m, name, ok, r, c); + } + return r[0]; + } + + private static void escapes(Object o, final String name, final IdentityHashMap ok, + final boolean[] r, final Ctx c) { + if (o instanceof Call) { + Call call = (Call) o; + ok.put(call.func, Boolean.TRUE); + if ((isName(call.func, "_dm_meta_serialisable") || isName(call.func, "_dm_meta_strict")) + && call.args.size() == 1 && isName(call.args.get(0), name)) { + // DeclarativeMap's metaclass functions (META_MODULE): they + // read the class's dictionary, and a value that is not a + // Descriptor instance reaches nothing but isinstance there. + ok.put(call.args.get(0), Boolean.TRUE); + } + if (c.family.contains(nameOf(call.func))) { + // `Sequence(expected_type=IgnoredError)`: stored in the + // descriptor's attribute, whose reads are then checked and + // may not read the shadowed attribute off it. + for (Keyword k : call.keywords) { + if (k.arg != null && isName(k.value, name)) { + ok.put(k.value, Boolean.TRUE); + c.escAttrs.add(k.arg); + } + } + } + if ((isName(call.func, "isinstance") || isName(call.func, "issubclass")) && call.args.size() == 2) { + ok.put(call.args.get(1), Boolean.TRUE); + if (call.args.get(1) instanceof Node.TupleExpr) { + for (Expr x : ((Node.TupleExpr) call.args.get(1)).elts) { + ok.put(x, Boolean.TRUE); + } + } + } + } else if (o instanceof Node.Assign && isAll((Node.Assign) o)) { + return; + } else if ((isName(o, name) || o instanceof Attribute && ((Attribute) o).attr.equals(name)) + && !ok.containsKey(o)) { + if (!r[0] && System.getenv("CN1_PY_KWATTR_DEBUG") != null) { + System.err.println("KwAttrInit: " + name + " escapes: " + ConstArgSpecialize.dump(o) + " line " + ((Node) o).line); + } + r[0] = true; + } + Infer.children(o, x -> escapes(x, name, ok, r, c)); + } + + /// True when `k`'s `__init__` stores `self.` as a statement of its + /// own body, before any return. + private static boolean initStores(ClassDef k, String attr) { + FunctionDef init = method(k, "__init__"); + if (init == null || init.args.positional.isEmpty()) { + return false; + } + String self = init.args.positional.get(0).name; + for (Stmt s : init.body) { + if (s instanceof Node.Return || s instanceof Node.Raise) { + return false; + } + if (s instanceof Node.Assign && ((Node.Assign) s).targets.size() == 1 + && ((Node.Assign) s).targets.get(0) instanceof Attribute + && attr.equals(((Attribute) ((Node.Assign) s).targets.get(0)).attr) + && isName(((Attribute) ((Node.Assign) s).targets.get(0)).value, self)) { + return true; + } + } + return false; + } + + private static boolean isTop(Map trees, ClassDef k) { + for (Node.Module m : trees.values()) { + if (m.body.contains(k)) { + return true; + } + } + return false; + } + + + private static boolean relevant(Object o, final String top) { + final boolean[] r = {false}; + imports(o, top, r); + return r[0]; + } + + private static void imports(Object o, final String top, final boolean[] r) { + if (r[0]) { + return; + } + if (o instanceof Node.ImportFrom) { + Node.ImportFrom f = (Node.ImportFrom) o; + if (f.module != null && (f.module.equals(top) || f.module.startsWith(top + "."))) { + r[0] = true; + } + } else if (o instanceof Node.Import) { + for (Node.Alias a : ((Node.Import) o).names) { + if (a.name.equals(top) || a.name.startsWith(top + ".")) { + r[0] = true; + } + } + } + Infer.children(o, x -> imports(x, top, r)); + } + + + private static boolean isSuperInit(Call call) { + return call.func instanceof Attribute && "__init__".equals(((Attribute) call.func).attr) + && ((Attribute) call.func).value instanceof Call + && isName(((Call) ((Attribute) call.func).value).func, "super"); + } + + private static void walk(Object o, final Ctx c, final ClassDef cls, final FunctionDef fn, + final Node.For rootLoop) { + if (c.refusal != null || o == rootLoop) { //NOPMD CompareObjectsWithEquals - identity is meant + return; + } + ClassDef inCls = cls; + FunctionDef inFn = fn; + if (o instanceof ClassDef) { + inCls = c.famDefs.containsKey(o) ? (ClassDef) o : null; + { + // Any class body: `sqref = CellRange` stores the class too. + for (Stmt st : ((ClassDef) o).body) { + if (st instanceof Node.Assign && ((Node.Assign) st).targets.size() == 1 + && ((Node.Assign) st).targets.get(0) instanceof Name + && (((Node.Assign) st).value instanceof Name + || ((Node.Assign) st).value instanceof Attribute) + && isFamily(c, ((Node.Assign) st).value)) { + c.allowed.put(((Node.Assign) st).value, Boolean.TRUE); + String k = ((Name) ((Node.Assign) st).targets.get(0)).id; + c.escClasses.put(o, Boolean.TRUE); + if (inCls == null && initStores((ClassDef) o, k)) { + // Every instance stores its own `self.k` first, + // so only the class object reads the class; that + // is checked not to escape below. + c.shadowed.put(o, k); + } else { + c.escAttrs.add(k); + } + } + } + } + inFn = null; + } else if (o instanceof FunctionDef) { + inFn = (FunctionDef) o; + if (inCls != null && inFn.args.kwarg != null && !inFn.body.contains(rootLoop)) { + kwUses(inFn.body, inFn.args.kwarg.name, c); + } + } else if (o instanceof Node.Assign && isAll((Node.Assign) o)) { + return; + } else if (o instanceof Call) { + Call call = (Call) o; + String n = nameOf(call.func); + boolean site = isFamily(c, call.func); + if (n != null && (site || "isinstance".equals(n) || "issubclass".equals(n))) { + c.allowed.put(call.func, Boolean.TRUE); + } + if (("isinstance".equals(n) || "issubclass".equals(n)) && call.args.size() == 2) { + Expr t = call.args.get(1); + c.allowed.put(t, Boolean.TRUE); + if (t instanceof Node.TupleExpr) { + for (Expr x : ((Node.TupleExpr) t).elts) { + c.allowed.put(x, Boolean.TRUE); + } + } + } + boolean init = "__init__".equals(n) && call.func instanceof Attribute + && (isSuperInit(call) ? cls != null + : isFamily(c, ((Attribute) call.func).value)); + if (init && !isSuperInit(call)) { + c.allowed.put(((Attribute) call.func).value, Boolean.TRUE); + } + if (cls != null && (isName(call.func, "cls") || call.func instanceof Call + && isName(((Call) call.func).func, "type") + || call.func instanceof Attribute && "__class__".equals(((Attribute) call.func).attr))) { + c.refusal = "a constructor call no name shows in " + cls.name; + return; + } + if (site || init) { + for (Keyword k : call.keywords) { + if (k.arg != null) { + c.keys.add(k.arg); + if (site && (k.value instanceof Name || k.value instanceof Attribute) + && isFamily(c, k.value)) { + // `Typed(expected_type=Percentage)`: the class is + // stored as the attribute, whose reads are checked. + c.allowed.put(k.value, Boolean.TRUE); + c.escAttrs.add(k.arg); + } + } else if (!(cls != null && fn != null && fn.args.kwarg != null + && isName(k.value, fn.args.kwarg.name))) { + c.refusal = "a **mapping call of " + n + " at line " + call.line; + return; + } else { + c.allowed.put(k.value, Boolean.TRUE); + } + } + } + } else if (o instanceof Name) { + if (!c.allowed.containsKey(o) && isFamily(c, (Name) o)) { + c.refusal = ((Name) o).id + " escapes in " + c.mod + " at line " + ((Name) o).line; + return; + } + } else if (o instanceof Attribute) { + String a = ((Attribute) o).attr; + if (!a.startsWith("__") || "__set__".equals(a) || "__get__".equals(a) || "__delete__".equals(a) + || "__init__".equals(a) || "__doc__".equals(a)) { + // `Descriptor.__set__(self, ...)` reads a member; the class + // object itself goes nowhere. + c.allowed.put(((Attribute) o).value, Boolean.TRUE); + } + if (!c.allowed.containsKey(o) && isFamily(c, (Attribute) o)) { + c.refusal = ((Attribute) o).attr + " escapes in " + c.mod + " at line " + ((Attribute) o).line; + return; + } + } + final ClassDef cc = inCls; + final FunctionDef ff = inFn; + Infer.children(o, x -> walk(x, c, cc, ff, rootLoop)); + } + + private static boolean isAll(Node.Assign a) { + return a.targets.size() == 1 && a.targets.get(0) instanceof Name + && "__all__".equals(((Name) a.targets.get(0)).id); + } + + /// Checks that every use of the family `__init__`'s `**kw` named `kw` is + /// a forward, a literal key or a membership test, and adds those keys. + private static void kwUses(Object o, final String kw, final Ctx c) { + if (c.refusal != null) { + return; + } + if (o instanceof Node.Subscript && isName(((Node.Subscript) o).value, kw)) { + Expr i = ((Node.Subscript) o).index; + if (!(i instanceof Constant) || ((Constant) i).kind != Constant.Kind.STR) { + c.refusal = "a computed key of " + kw; + return; + } + c.keys.add(((Constant) i).text); + c.allowed.put(((Node.Subscript) o).value, Boolean.TRUE); + } else if (o instanceof Call && ((Call) o).func instanceof Attribute + && isName(((Attribute) ((Call) o).func).value, kw)) { + Call call = (Call) o; + String m = ((Attribute) call.func).attr; + if (!("get".equals(m) || "pop".equals(m) || "setdefault".equals(m)) || call.args.isEmpty() + || !(call.args.get(0) instanceof Constant) + || ((Constant) call.args.get(0)).kind != Constant.Kind.STR) { + c.refusal = kw + "." + m + " in a family __init__"; + return; + } + c.keys.add(((Constant) call.args.get(0)).text); + c.allowed.put(((Attribute) call.func).value, Boolean.TRUE); + } else if (o instanceof Node.Compare && ((Node.Compare) o).comparators.size() == 1 + && isName(((Node.Compare) o).comparators.get(0), kw) + && ((Node.Compare) o).left instanceof Constant) { + c.allowed.put(((Node.Compare) o).comparators.get(0), Boolean.TRUE); + } else if (o instanceof Call && (isSuperInit((Call) o) || isFamily(c, ((Call) o).func))) { + // Only a forward into the family keeps the keys inside it. + for (Keyword k : ((Call) o).keywords) { + if (k.arg == null && isName(k.value, kw)) { + c.allowed.put(k.value, Boolean.TRUE); + } + } + } else if (isName(o, kw) && !c.allowed.containsKey(o)) { + c.refusal = kw + " used other than by literal key"; + return; + } + Infer.children(o, x -> kwUses(x, kw, c)); + } +} diff --git a/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/Layouts.java b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/Layouts.java index 50d98b7e8ce..2bfc1acb445 100644 --- a/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/Layouts.java +++ b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/Layouts.java @@ -26,6 +26,7 @@ import com.codename1.python.transpiler.ast.Node.*; import java.util.ArrayList; +import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedHashSet; @@ -49,11 +50,110 @@ /// body, since a class attribute -- a property in particular -- must keep /// deciding what a store to that name does. final class Layouts { + /// The most parameters a function compiled typed may take. Java's own + /// limit is 255 slots; this keeps generated signatures readable. bs4's + /// Tag.__init__ takes 17, and a cap of 8 left every field it sets + /// unanalysed -- the class every HTML converter walks. + static final int MAX_TYPED_PARAMS = 24; + + /// Per program: for each class name, the names a subclass anywhere + /// below it binds by a decorated definition or a call in its body + /// (see [#subclassBindings]). Set by the transpiler before emitting. + private static final ThreadLocal>> SUBCLASS_BINDINGS = + new ThreadLocal>>(); + + /// Records, for every class of `modules`, what its subclasses bind over + /// it, so a field a subclass of another module turns into a property is + /// planned as no field of the base ([#plan]). + static void subclassBindings(java.util.Collection modules) { + final Map> own = new HashMap>(); + final Map> subs = new HashMap>(); + for (Object m : modules) { + collectBindings(m, own, subs); + } + Map> all = new HashMap>(); + for (Map.Entry> sb : subs.entrySet()) { + String b = sb.getKey(); + Set r = new HashSet(); + java.util.Deque todo = new java.util.ArrayDeque(sb.getValue()); + Set seen = new HashSet(); + while (!todo.isEmpty()) { + String c = todo.pop(); + if (!seen.add(c)) { + continue; + } + if (own.containsKey(c)) { + r.addAll(own.get(c)); + } + if (subs.containsKey(c)) { + todo.addAll(subs.get(c)); + } + } + if (!r.isEmpty()) { + all.put(b, r); + } + } + SUBCLASS_BINDINGS.set(all); + } + + private static void collectBindings(Object o, final Map> own, + final Map> subs) { + if (o instanceof ClassDef) { + ClassDef c = (ClassDef) o; + Set n = new HashSet(); + for (Stmt s : c.body) { + if (s instanceof FunctionDef && !((FunctionDef) s).decorators.isEmpty()) { + n.add(((FunctionDef) s).name); + } else if (s instanceof Assign && ((Assign) s).value instanceof Call) { + for (Expr t : ((Assign) s).targets) { + if (t instanceof Name) { + n.add(((Name) t).id); + } + } + } + } + if (!n.isEmpty()) { + Set e = own.get(c.name); + if (e == null) { + own.put(c.name, n); + } else { + e.addAll(n); + } + } + for (Expr b : c.bases) { + String bn = b instanceof Name ? ((Name) b).id + : b instanceof Attribute ? ((Attribute) b).attr : null; + if (bn != null && !bn.equals(c.name)) { + Set l = subs.get(bn); + if (l == null) { + l = new HashSet(); + subs.put(bn, l); + } + l.add(c.name); + } + } + } + Infer.children(o, x -> collectBindings(x, own, subs)); + } + static final class Cls { final ClassDef def; final String javaName; final String typeVar; + /// `javaName` qualified by the module's Java class: how code in any + /// module of the program names this class. + String ref; + /// The typed code of the module declaring the class, once its typed + /// fields are decided: whether a field is held typed, and how. + TypedEmit typed; final Cls parent; + /// False for a class given no Java layout (see [Layouts#analysed]): + /// the inference follows its instances, fields and methods like any + /// other class's, and generated code holds them as plain objects. + boolean compiled = true; + /// The plan this class is part of: a parent of another module's + /// plan is a compiled class another module declares. + Layouts home; final List fields = new ArrayList(); /// Every field, the inherited ones first: the index order the /// generated `fieldIndex` uses. @@ -64,80 +164,1869 @@ static final class Cls { /// generic dispatch: those `Infer` and the typed code still see. final Map typable = new LinkedHashMap(); - Cls(ClassDef def, String javaName, String typeVar, Cls parent) { - this.def = def; - this.javaName = javaName; - this.typeVar = typeVar; - this.parent = parent; - this.bodyNames = def.scope.assigned; + /// Names the extra bases of this class bind, which the class + /// reaches through its MRO after the compiled chain (see + /// [#neutralMixin]), and so may not be fields of it. + final Set mixinNames = new HashSet(); + /// The compiled classes this class names as bases, in order: the + /// compiled parent (if any) and every compiled extra base. The C3 + /// MRO of a subclass is computed over them ([#c3]). + final List bases = new ArrayList(); + /// The compiled classes of this class's MRO that are not in its + /// compiled chain: their fields are copied into this layout, and + /// their methods reached through the MRO ([#mergeExtras]). + final List mixedFrom = new ArrayList(); + /// The names this class's MRO resolves in a merged class rather than + /// in its compiled chain; added to [#bodyNames], and withdrawn from + /// the typed dispatch of every class above it. + final Set mroNames = new HashSet(); + /// Whether the class has a base besides its compiled parent: the + /// generated code then asks the runtime to confirm the extra bases + /// add nothing to an instance before giving the layout. + boolean extraBases; + /// The builtin type the instances extend (`str` for bs4's + /// `NavigableString`), held in `PyInstance.base`; inherited from the + /// compiled parent. Null for none. + String builtin; + + /// Whether `enum.EnumType` makes the class: its body's definitions + /// become members when it is made (runtime class `EnumMeta`), and + /// calling it looks a member up rather than constructing one. + boolean enumMeta; + /// Whether this class is a metaclass ([Layouts#metaclassDef]): its + /// instances are classes, never of a Java class of its own. + boolean metaclass; + /// Whether calling this class runs a metaclass `__call__` + /// ([Layouts#LAYOUT_SAFE_HOOKS]), its own or inherited: typed code + /// constructs it by calling the class, and the result is any object. + boolean metaCall; + /// Whether typed code must construct the class by calling it. + boolean callConstructed() { + return exception || metaCall; + } + /// Whether `builtin` is this class's own first base, which the + /// generated code then has the runtime confirm + /// (`PyType.builtinBased`). + boolean builtinOwn; + /// The builtin exception types among this class's own bases, by + /// their canonical name (`IOError` is `OSError`), in base order. An + /// exception instance is a plain `PyInstance` whose `args`, + /// `__cause__` and the like live in its attribute table, so the + /// layout extends the compiled parent (or none) like any class and + /// the type object keeps every builtin base for `except` and + /// `isinstance`; the generated code has the runtime confirm them + /// (`PyType.exceptionBased`). + final List excBases = new ArrayList(); + /// Whether the class derives, directly or through its compiled + /// chain, from a builtin exception: BaseException's `__new__` then + /// fills `args` from the constructor's arguments, so typed code + /// constructs it by calling the class, never by `new` and `__init__`. + boolean exception; + + /// Whether this class is, or extends, a frozen dataclass: the + /// `__setattr__` the decorator adds decides every store on its + /// instances, so generated code never writes their fields directly. + boolean frozenStores() { + for (Cls c = this; c != null; c = c.parent) { + if (c.def.dataclassFrozen) { + return true; + } + } + return false; + } + + Cls(ClassDef def, String javaName, String typeVar, Cls parent) { + this.def = def; + this.javaName = javaName; + this.typeVar = typeVar; + this.parent = parent; + this.bodyNames = bodyBindings(def); + } + } + + /// The names a class body binds. A bare annotation (`name_rules: List[Rule]`) + /// binds nothing -- it only records the annotation -- so a name that only + /// appears that way is left out, and stays free to be a field: bs4 annotates + /// every instance attribute of `Tag` and `SoupStrainer` in the class body. A body + /// with any statement whose bindings are not read here keeps the scope's set. + static Set bodyBindings(ClassDef def) { + Set bare = new HashSet(); + Set bound = new HashSet(); + for (Stmt s : def.body) { + if (s instanceof AnnAssign && ((AnnAssign) s).value == null) { + if (((AnnAssign) s).target instanceof Name) { + bare.add(((Name) ((AnnAssign) s).target).id); + } + } else if (s instanceof AnnAssign) { + names(((AnnAssign) s).target, bound); + } else if (s instanceof Assign) { + for (Expr t : ((Assign) s).targets) { + names(t, bound); + } + } else if (s instanceof AugAssign) { + names(((AugAssign) s).target, bound); + } else if (s instanceof FunctionDef) { + bound.add(((FunctionDef) s).name); + } else if (s instanceof ClassDef) { + bound.add(((ClassDef) s).name); + } else if (!(s instanceof ExprStmt) && !(s instanceof Pass)) { + return def.scope.assigned; + } + } + bare.removeAll(bound); + if (bare.isEmpty()) { + return def.scope.assigned; + } + Set r = new HashSet(def.scope.assigned); + r.removeAll(bare); + return r; + } + + /// The names one statement of a class body binds, as [#bodyBindings] + /// reads them; null for a statement it does not read, which may bind + /// any name. + static Set bodyBindingsOf(Stmt s) { + Set bound = new HashSet(); + if (s instanceof AnnAssign && ((AnnAssign) s).value != null || s instanceof AugAssign) { + names(s instanceof AnnAssign ? ((AnnAssign) s).target : ((AugAssign) s).target, bound); + } else if (s instanceof Assign) { + for (Expr t : ((Assign) s).targets) { + names(t, bound); + } + } else if (s instanceof FunctionDef) { + bound.add(((FunctionDef) s).name); + } else if (s instanceof ClassDef) { + bound.add(((ClassDef) s).name); + } else if (!(s instanceof ExprStmt) && !(s instanceof Pass) && !bareAnnotation(s)) { + return null; + } + return bound; + } + + private static boolean bareAnnotation(Stmt s) { + return s instanceof AnnAssign && ((AnnAssign) s).value == null; + } + + final Map classes = new LinkedHashMap(); + /// The names the module assigns at top level ([#plan]). + private Set moduleAssigned = java.util.Collections.emptySet(); + /// Whether a global of this module holds a constant literal for the + /// whole run (Infer#constantGlobal); null before whole-program planning. + private java.util.function.Predicate constantGlobal; + /// Whether a global of this module is bound once and never rebound by + /// any module (Infer#fixedGlobal); null before whole-program planning. + private java.util.function.Predicate fixedGlobal; + + /// Whether the module assigns `name` at top level (a builtin it shadows). + boolean moduleBinds(String name) { + return moduleAssigned.contains(name); + } + /// The classes of [#refused] that the inference still follows: a class + /// the emitter cannot lay out is a class all the same, whose instances, + /// fields and methods have types. Never emitted as Java classes. + final Map analysed = new LinkedHashMap(); + + /// Every class the inference follows: the compiled ones, then the + /// analysed ones. + Map all() { + if (all == null) { + all = new LinkedHashMap(classes); + all.putAll(analysed); + } + return all; + } + + private Map all; + /// The classes given no layout, with why: the strict mode's report. + final Map refused = new LinkedHashMap(); + /// Field name -> the classes that declare it (not inherit it). + final Map> fieldOwners = new LinkedHashMap>(); + /// `name/arity` of every compiled method, arity without the receiver. + final Set dispatch = new LinkedHashSet(); + /// The classes that put each entry into [#dispatch]. + private final Map> dispatchBy = new HashMap>(); + final Map staticNames = new LinkedHashMap(); + /// The class each compiled method belongs to. + final Map methodClass = new LinkedHashMap(); + /// The methods given a static entry only for build-time-bound calls. + final Set directEntries = new HashSet(); + /// Every instance method a class body defines -> that class: the class + /// its first parameter is, as `self`. Only a hint for the typed copy of + /// that parameter, which is guarded by `instanceof`, so an unusual call + /// (`K.m(other)`) is slower, never wrong. + final Map receiverClass = new LinkedHashMap(); + + /// Field name -> every class of the whole program declaring it, typed + /// (`Cls.typed`) or not. The program is closed: a class compiled in + /// one module is a class code in every other module may read the + /// fields of directly (`ShadowTypes`). Filled once every module's + /// typed fields are known, before any module is emitted. + static Map> program(List all) { + Map> r = new LinkedHashMap>(); + for (Layouts l : all) { + for (Cls k : l.classes.values()) { + for (String f : k.fields) { + List o = r.get(f); + if (o == null) { + o = new ArrayList(); + r.put(f, o); + } + o.add(k); + } + } + } + return r; + } + + /// The top-level classes of the module that some other class of it + /// names as a base after its first and that a compiled class may have + /// as such ([#neutralMixin]). pdfminer's `LTChar(LTComponent, LTText)`: + /// the MRO is LTChar, the compiled chain, LTText, object, so every + /// field and compiled method resolves in the chain before the mixin is + /// asked, and the mixin only adds what the chain lacks. + private static Set mixins(List body) { + Set used = new HashSet(); + for (Stmt s : body) { + if (s instanceof ClassDef) { + List b = ((ClassDef) s).bases; + for (int i = 1; i < b.size(); i++) { + if (b.get(i) instanceof Name) { + used.add(((Name) b.get(i)).id); + } + } + } + } + Set superNames = new HashSet(); + superAttrs(body, superNames); + Set r = new HashSet(); + for (String n : used) { + ClassDef m = classNamed(body, n); + if (m != null && neutralMixin(m, superNames) && definedOnce(body, n)) { + r.add(n); + } + } + return r; + } + + /// Whether `m` adds nothing to an instance and nothing typed code acts + /// on: no base but `object`, no decorator or keyword, a body of methods + /// (and docstrings, constants, bare annotations) none of which is + /// `__init__`, `__new__`, an attribute hook or a special method typed + /// code assumes, no store to any attribute, and no method a `super()` + /// call in the module names -- which a compiled chain resolves + /// without the mixin the MRO puts after it. + static boolean neutralMixin(ClassDef m, Set superNames) { + if (!m.decorators.isEmpty() || !m.keywords.isEmpty() || m.bases.size() > 1 + || m.bases.size() == 1 && !(m.bases.get(0) instanceof Name && "object".equals(((Name) m.bases.get(0)).id))) { + return false; + } + for (Stmt s : m.body) { + if (s instanceof FunctionDef) { + String n = ((FunctionDef) s).name; + if (n.startsWith("__") && n.endsWith("__") && !NEUTRAL_SPECIALS.contains(n) || superNames.contains(n)) { + return false; + } + } else if (!(s instanceof ExprStmt) && !(s instanceof Pass) && !bareAnnotation(s) + && !(s instanceof Assign && ((Assign) s).targets.size() == 1 && ((Assign) s).targets.get(0) instanceof Name + && ((Assign) s).value instanceof Constant)) { + return false; + } + } + boolean[] stores = {false}; + attrStore(m.body, stores); + return !stores[0]; + } + + /// Whether `m`, a class of another module mixed in as a later base, can + /// stay uncompiled under a compiled subclass: [#neutralMixin]'s shape + /// (checked again by the runtime, PyType.neutralExtraBases) except that + /// its methods may store attributes of `self` -- their first parameter + /// -- and nothing else. Those names are kept out of every subclass's + /// fields ([#selfStores]), so the generic stores reach the instance's + /// own attributes and typed code reads them generically. + /// `superNames` holds every name a `super()` call in the program reads. + static boolean foreignMixin(ClassDef m, Set superNames) { + if (!m.decorators.isEmpty() || !m.keywords.isEmpty() || m.bases.size() > 1 + || m.bases.size() == 1 && !(m.bases.get(0) instanceof Name && "object".equals(((Name) m.bases.get(0)).id))) { + return false; + } + for (Stmt s : m.body) { + if (s instanceof FunctionDef) { + FunctionDef f = (FunctionDef) s; + String n = f.name; + if (n.startsWith("__") && n.endsWith("__") && !NEUTRAL_SPECIALS.contains(n) || superNames.contains(n)) { + return false; + } + String self = f.args.positional.isEmpty() ? null : f.args.positional.get(0).name; + boolean[] other = {false}; + otherStore(f.body, self, other); + if (other[0]) { + return false; + } + } else if (!(s instanceof ExprStmt) && !(s instanceof Pass) && !bareAnnotation(s) + && !plainClassBinding(s)) { + return false; + } + } + return true; + } + + /// `X = value` or `X: T = value` in a class body, `X` no special name: + /// a class attribute of an uncompiled mixin, whatever the value (bs4's + /// `LOOKS_LIKE_HTML: Pattern[str] = re.compile(...)`). The subclass keeps + /// the name out of its fields, so it always reads the class's value. + private static boolean plainClassBinding(Stmt s) { + Expr t = s instanceof Assign && ((Assign) s).targets.size() == 1 ? ((Assign) s).targets.get(0) + : s instanceof AnnAssign ? ((AnnAssign) s).target : null; + return t instanceof Name && !((Name) t).id.startsWith("__"); + } + + /// The attribute names `m`'s methods store on `self`. + static Set selfStores(ClassDef m) { + Set r = new HashSet(); + for (Stmt s : m.body) { + if (s instanceof FunctionDef && !((FunctionDef) s).args.names().isEmpty()) { + selfStores(((FunctionDef) s).body, ((FunctionDef) s).args.names().get(0), r); + } + } + return r; + } + + /// Sets `r[0]` when a store or delete in `o` has a target other than a + /// name or an attribute of the name `self`, or a nested function or + /// class rebinds `self`'s meaning. + private static void otherStore(Object o, String self, boolean[] r) { + if (r[0]) { + return; + } + List targets = new ArrayList(); + if (o instanceof Assign) { + targets.addAll(((Assign) o).targets); + } else if (o instanceof AugAssign) { + targets.add(((AugAssign) o).target); + } else if (o instanceof AnnAssign) { + targets.add(((AnnAssign) o).target); + } else if (o instanceof Delete || o instanceof FunctionDef || o instanceof ClassDef || o instanceof Lambda) { + r[0] = true; + return; + } + for (Expr t : targets) { + r[0] |= !(t instanceof Name || self != null && t instanceof Attribute + && ((Attribute) t).value instanceof Name && ((Name) ((Attribute) t).value).id.equals(self)); + r[0] |= t instanceof Name && ((Name) t).id.equals(self); + } + Infer.children(o, x -> otherStore(x, self, r)); + } + + private static final Set NEUTRAL_SPECIALS = new HashSet(); + + static { + // Kept equal to the runtime's PyType.NEUTRAL_SPECIALS, which checks + // the same of a mixin at run time before the layout is given. + String[] n = {"__repr__", "__str__", "__format__", "__getstate__", "__setstate__", "__reduce__", + "__reduce_ex__", "__copy__", "__deepcopy__", "__init_subclass__", "__class_getitem__", "__sizeof__", + "__dir__", "__enter__", "__exit__"}; + for (String x : n) { + NEUTRAL_SPECIALS.add(x); + } + } + + private static void attrStore(Object o, boolean[] r) { + if (r[0]) { + return; + } + if (o instanceof Assign) { + for (Expr t : ((Assign) o).targets) { + r[0] |= !(t instanceof Name); + } + } else if (o instanceof AugAssign) { + r[0] |= !(((AugAssign) o).target instanceof Name); + } else if (o instanceof AnnAssign) { + r[0] |= !(((AnnAssign) o).target instanceof Name); + } else if (o instanceof Delete) { + r[0] = true; + } + Infer.children(o, x -> attrStore(x, r)); + } + + static void superAttrs(Object o, Set r) { + if (o instanceof Attribute && ((Attribute) o).value instanceof Call + && ((Call) ((Attribute) o).value).func instanceof Name + && "super".equals(((Name) ((Call) ((Attribute) o).value).func).id)) { + r.add(((Attribute) o).attr); + } + Infer.children(o, x -> superAttrs(x, r)); + } + + /// `typing.Generic[...]`, or bare: a base that only records type + /// parameters. `Protocol` is not one: its metaclass makes every + /// subclass's instance checks its own. The runtime confirms the base + /// adds nothing at class creation (PyType.neutralExtraBases). + static boolean typingBase(Expr b) { + Expr e = b instanceof Subscript ? ((Subscript) b).value : b; + String n = e instanceof Name ? ((Name) e).id : e instanceof Attribute ? ((Attribute) e).attr : null; + return "Generic".equals(n); + } + + /// The class a base expression derives from: `LTContainer[LTItemT]` + /// is `LTContainer`, as `__mro_entries__` of the alias makes it at run + /// time. `Generic[T]` stays as written ([#typingBase]). + static Expr origin(Expr b) { + if (b instanceof Subscript && !typingBase(b) + && (((Subscript) b).value instanceof Name || ((Subscript) b).value instanceof Attribute)) { + return ((Subscript) b).value; + } + return b; + } + + static ClassDef classNamed(List body, String name) { + for (Stmt s : body) { + if (s instanceof ClassDef && ((ClassDef) s).name.equals(name)) { + return (ClassDef) s; + } + } + return null; + } + + private static boolean definedOnce(List body, String name) { + int k = 0; + for (Stmt s : body) { + k += s instanceof ClassDef && ((ClassDef) s).name.equals(name) ? 1 : 0; + } + return k == 1; + } + + /// Whether the module defines a top-level class `name` (one the planner + /// may have rejected): a base of that name is that class, never an + /// import of the same name. + private static boolean moduleClassNamed(List body, String name) { + for (Stmt s : body) { + if (s instanceof ClassDef && ((ClassDef) s).name.equals(name)) { + return true; + } + } + return false; + } + + /// Whether class `c` may extend `base`, a compiled class of another + /// module, whose plan is already made and cannot learn of `c`: no name + /// `c` binds in its body may be a field above it (it would be a class + /// attribute, maybe a property, that the base reads as a field), and no + /// name its methods store on `self` may be a method above it (the + /// base's own plan would have looked that method up per call). A class + /// failing either keeps the generic instances it has today. + private static String extendsForeign(ClassDef c, Cls base, Layouts home, Map byName, + java.util.function.Function foreignBase) { + Set body = bodyBindings(c); + Set stored = new HashSet(); + for (Stmt s : c.body) { + if (s instanceof FunctionDef && !((FunctionDef) s).args.names().isEmpty()) { + selfStores(((FunctionDef) s).body, ((FunctionDef) s).args.names().get(0), stored); + } + } + // Names the base chain itself stores on `self`: its plan already + // reads those per instance, whatever a class body above binds them + // to. bs4's `PageElement` binds `known_xml = None` and `hidden = + // False` as defaults that `Tag` stores over, and `BeautifulSoup` + // storing them too kept it -- the parser's every `self.tagStack`, + // `self.currentTag` -- off a layout. + Set baseStored = new HashSet(); + for (Cls a = base; a != null; a = a.parent) { + for (Stmt s : a.def.body) { + if (s instanceof FunctionDef && !((FunctionDef) s).args.names().isEmpty()) { + selfStores(((FunctionDef) s).body, ((FunctionDef) s).args.names().get(0), baseStored); + } + } + } + for (Cls a = base; a != null; a = a.parent) { + for (String f : a.allFields) { + if (body.contains(f) && !plainDefault(c, f, home) + && !(bindsNothing(c, f) && extraBasesPlain(c, f, byName, foreignBase))) { + return "its body binds " + f + ", a field of " + a.def.name; + } + } + for (String m : stored) { + if (setterOf(a, m)) { + // A property with a setter: the store is a call to it. + continue; + } + if (a.methods.containsKey(m) || a.typable.containsKey(m) + || a.bodyNames.contains(m) && !baseStored.contains(m) && !shadowableDefault(a, m)) { + return "it stores self." + m + ", which " + a.def.name + " binds in its class"; + } + } + } + return null; + } + + /// Whether `c`'s body binds `f` exactly once, to a default that is no + /// descriptor: a constant, a builtin class (`expected_type = bool`) or + /// `type(x)`. openpyxl's `Bool(Convertible)` binds `expected_type` and + /// `allow_none` over what the base `Descriptor` stores as fields. Such a + /// binding is as harmless here as in one module (the `constants` of + /// [#plan]): a store binds the instance's own slot, and an unset slot + /// falls back to the generic read, which looks the name up on the + /// instance's actual class and finds this default. The base never folds + /// the read to its own class value, since the field is stored + /// (Infer#classStatic, Emitter#classConstantGet). + /// Whether no statement of `c`'s own body binds `f` (it is in the body's + /// names because an extra base's body binds it). + private static boolean bindsNothing(ClassDef c, String f) { + for (Stmt s : c.body) { + if (bodyBindingsOf(s).contains(f)) { + return false; + } + } + return true; + } + + /// Whether every class above `c`'s extra bases (`NestedBoolText(Bool, + /// NestedText)`) that binds `f` binds it to a [#plainDefault]. An extra + /// base that cannot be resolved answers false. + private static boolean extraBasesPlain(ClassDef c, String f, Map byName, + java.util.function.Function foreignBase) { + for (int i = 1; i < c.bases.size(); i++) { + Expr b = origin(c.bases.get(i)); + Cls x = b instanceof Name ? byName.get(((Name) b).id) : null; + if (x == null && foreignBase != null) { + x = foreignBase.apply(b); + } + if (x == null) { + return false; + } + for (Cls a = x; a != null; a = a.parent) { + if (!bindsNothing(a.def, f) && !plainDefault(a.def, f, a.home)) { + return false; + } + } + } + return true; + } + + /// Stands for an undecorated def in [#plainDefault]. + private static final Expr PLAIN_DEF = new Name("def"); + + private static boolean plainDefault(ClassDef c, String f, Layouts home) { + Set moduleAssigned = home.moduleAssigned; + Expr found = null; + for (Stmt s : c.body) { + Set b = new HashSet(); + Expr v = null; + if (s instanceof Assign) { + for (Expr t : ((Assign) s).targets) { + names(t, b); + } + if (((Assign) s).targets.size() == 1 && ((Assign) s).targets.get(0) instanceof Name) { + v = ((Assign) s).value; + } + } else if (s instanceof AnnAssign) { + if (!bareAnnotation(s)) { + names(((AnnAssign) s).target, b); + v = ((AnnAssign) s).target instanceof Name ? ((AnnAssign) s).value : null; + } + } else if (s instanceof FunctionDef) { + b.add(((FunctionDef) s).name); + if (((FunctionDef) s).decorators.isEmpty()) { + // A plain def is no data descriptor: a store fills the + // slot, and an unset one reads the method generically. + // Its calls dispatch generically too (see the plan's + // `inheritedField`), so the instance's value wins. + v = ((FunctionDef) s).name.isEmpty() ? null : PLAIN_DEF; + } + } else if (s instanceof ClassDef) { + b.add(((ClassDef) s).name); + } else if (s instanceof AugAssign) { + names(((AugAssign) s).target, b); + } else if (!(s instanceof ExprStmt) && !(s instanceof Pass)) { + return false; + } + if (b.contains(f)) { + if (found != null || v == null) { + return false; + } + found = v; + } + } + if (found == PLAIN_DEF) { //NOPMD CompareObjectsWithEquals - identity is meant + return true; + } + if (found instanceof UnaryOp && ("-".equals(((UnaryOp) found).op) || "+".equals(((UnaryOp) found).op))) { + found = ((UnaryOp) found).operand; + } + if (found instanceof Constant) { + return true; + } + if (found instanceof Name) { + String id = ((Name) found).id; + if (home.constantGlobal != null && moduleAssigned.contains(id) && !bodyBindings(c).contains(id) + && home.constantGlobal.test(id)) { + // A global holding one literal for the whole run is that + // literal: openpyxl's `namespace = REL_NS`. + return true; + } + return DEFAULT_TYPES.contains(id) && !moduleAssigned.contains(id); + } + return found instanceof Call && ((Call) found).func instanceof Name + && "type".equals(((Name) ((Call) found).func).id) && ((Call) found).args.size() == 1 + && ((Call) found).keywords.isEmpty() && !moduleAssigned.contains("type"); + } + + /// Whether `a`'s body binds `m` as a property with a `@m.setter`. + private static boolean setterOf(Cls a, String m) { + for (Stmt s : a.def.body) { + if (s instanceof FunctionDef && m.equals(((FunctionDef) s).name)) { + for (Expr d : ((FunctionDef) s).decorators) { + if (d instanceof Attribute && "setter".equals(((Attribute) d).attr) + && ((Attribute) d).value instanceof Name && m.equals(((Name) ((Attribute) d).value).id)) { + return true; + } + } + } + } + return false; + } + + /// The builtin classes a class body may bind as a plain default + /// (`expected_type = float`): a class object is no descriptor. + private static final Set DEFAULT_TYPES = new HashSet(java.util.Arrays.asList("int", "float", + "str", "bool", "bytes", "tuple", "list", "dict", "set", "frozenset", "object", "type", "complex")); + + /// Whether a store to `self.m` cannot change what the base's plan made + /// of the binding `a`'s body gives `m`. True for a default that is no + /// descriptor -- a constant (`idx_base = 0`) or a builtin class + /// (`expected_type = float`) -- whose every read the base folds only + /// under the whole-program "nobody stores it" fact (Infer#classStatic, + /// Emitter#classConstantGet), which the store itself turns off; the + /// instance then holds the value and the generic read finds it first. + /// And true for an instance of a data descriptor of `a`'s module + /// (`number_format = NumberFormatDescriptor()`, a class with + /// `__set__`): a store goes through `__set__` and the instance never + /// holds the name, so the base's reads are unchanged. + private static boolean shadowableDefault(Cls a, String m) { + Expr v = onceValue(a, m); + if (v instanceof Constant) { + return true; + } + if (v instanceof Name) { + return DEFAULT_TYPES.contains(((Name) v).id) && !a.home.moduleBinds(((Name) v).id); + } + if (v instanceof Call && ((Call) v).func instanceof Name) { + String f = ((Name) ((Call) v).func).id; + if ("type".equals(f) && ((Call) v).args.size() == 1) { + return !a.home.moduleBinds("type"); + } + for (Cls d : a.home.classes.values()) { + if (d.def.name.equals(f) && d.compiled && d.home == a.home) { //NOPMD CompareObjectsWithEquals - identity is meant + Cls set = resolver(d, "__set__"); + return set != null && set.methods.containsKey("__set__"); + } + } + } + return false; + } + + private static final Set FORBIDDEN = new HashSet(); + /// Methods Python makes static or class methods without a decorator. + static final Set IMPLICIT_CLASS_LEVEL = new HashSet(java.util.Arrays.asList("__new__", + "__init_subclass__", "__class_getitem__")); + + static { + // A class that customises attribute access itself is left alone. + // `__slots__` is not on the list: it fixes the attribute set, which + // is what a layout is, and the generic instance does not enforce it + // either, so the two paths agree. + FORBIDDEN.add("__setattr__"); + FORBIDDEN.add("__getattribute__"); + FORBIDDEN.add("__delattr__"); + FORBIDDEN.add("__dict__"); + FORBIDDEN.add("__class__"); + // `__new__` is not on the list: typed code constructs such a class + // through the class itself (TypedEmit#construct), which runs it. + } + + /// `moduleAssigned` is every name the module binds, imports included. + /// `attrStores` is the module scope's (`Scope.attrStores`): a field the + /// module itself assigns on a class is left to the generic path, since + /// the class attribute -- a property, say -- must then decide its reads. + /// The builtin types a compiled class may extend, by name, with the + /// names each binds (CPython's, less the class metadata). + static final Map> BUILTIN_NAMES = new LinkedHashMap>(); + + static { + BUILTIN_NAMES.put("str", names("__add__ __contains__ __eq__ __format__ __ge__ __getitem__ __getnewargs__ __gt__ __hash__ " + + "__iter__ __le__ __len__ __lt__ __mod__ __mul__ __ne__ __new__ __repr__ __rmod__ __rmul__ " + + "__sizeof__ __str__ capitalize casefold center count encode endswith expandtabs find " + + "format format_map index isalnum isalpha isascii isdecimal isdigit isidentifier islower " + + "isnumeric isprintable isspace istitle isupper join ljust lower lstrip maketrans " + + "partition removeprefix removesuffix replace rfind rindex rjust rpartition rsplit rstrip " + + "split splitlines startswith strip swapcase title translate upper zfill ")); + BUILTIN_NAMES.put("list", names("__add__ __class_getitem__ __contains__ __delitem__ __eq__ __ge__ __getitem__ __gt__ " + + "__hash__ __iadd__ __imul__ __init__ __iter__ __le__ __len__ __lt__ __mul__ __ne__ " + + "__new__ __repr__ __reversed__ __rmul__ __setitem__ __sizeof__ append clear copy count " + + "extend index insert pop remove reverse sort ")); + BUILTIN_NAMES.put("dict", names("__class_getitem__ __contains__ __delitem__ __eq__ __ge__ __getitem__ __gt__ __hash__ " + + "__init__ __ior__ __iter__ __le__ __len__ __lt__ __ne__ __new__ __or__ __repr__ " + + "__reversed__ __ror__ __setitem__ __sizeof__ clear copy fromkeys get items keys pop " + + "popitem setdefault update values ")); + BUILTIN_NAMES.put("set", names("__and__ __class_getitem__ __contains__ __eq__ __ge__ __gt__ __hash__ __iand__ __init__ " + + "__ior__ __isub__ __iter__ __ixor__ __le__ __len__ __lt__ __ne__ __new__ __or__ __rand__ " + + "__reduce__ __repr__ __ror__ __rsub__ __rxor__ __sizeof__ __sub__ __xor__ add clear copy " + + "difference difference_update discard intersection intersection_update isdisjoint " + + "issubset issuperset pop remove symmetric_difference symmetric_difference_update union " + + "update ")); + BUILTIN_NAMES.put("tuple", names("__add__ __class_getitem__ __contains__ __eq__ __ge__ __getitem__ __getnewargs__ __gt__ " + + "__hash__ __iter__ __le__ __len__ __lt__ __mul__ __ne__ __new__ __repr__ __rmul__ count " + + "index ")); + BUILTIN_NAMES.put("bytes", names("__add__ __buffer__ __bytes__ __contains__ __eq__ __ge__ __getitem__ __getnewargs__ " + + "__gt__ __hash__ __iter__ __le__ __len__ __lt__ __mod__ __mul__ __ne__ __new__ __repr__ " + + "__rmod__ __rmul__ __str__ capitalize center count decode endswith expandtabs find " + + "fromhex hex index isalnum isalpha isascii isdigit islower isspace istitle isupper join " + + "ljust lower lstrip maketrans partition removeprefix removesuffix replace rfind rindex " + + "rjust rpartition rsplit rstrip split splitlines startswith strip swapcase title " + + "translate upper zfill ")); + BUILTIN_NAMES.put("int", names("__abs__ __add__ __and__ __bool__ __ceil__ __divmod__ __eq__ __float__ __floor__ " + + "__floordiv__ __format__ __ge__ __getnewargs__ __gt__ __hash__ __index__ __int__ " + + "__invert__ __le__ __lshift__ __lt__ __mod__ __mul__ __ne__ __neg__ __new__ __or__ " + + "__pos__ __pow__ __radd__ __rand__ __rdivmod__ __repr__ __rfloordiv__ __rlshift__ " + + "__rmod__ __rmul__ __ror__ __round__ __rpow__ __rrshift__ __rshift__ __rsub__ " + + "__rtruediv__ __rxor__ __sizeof__ __sub__ __truediv__ __trunc__ __xor__ as_integer_ratio " + + "bit_count bit_length conjugate denominator from_bytes imag is_integer numerator real " + + "to_bytes ")); + BUILTIN_NAMES.put("float", names("__abs__ __add__ __bool__ __ceil__ __divmod__ __eq__ __float__ __floor__ __floordiv__ " + + "__format__ __ge__ __getformat__ __getnewargs__ __gt__ __hash__ __int__ __le__ __lt__ " + + "__mod__ __mul__ __ne__ __neg__ __new__ __pos__ __pow__ __radd__ __rdivmod__ __repr__ " + + "__rfloordiv__ __rmod__ __rmul__ __round__ __rpow__ __rsub__ __rtruediv__ __sub__ " + + "__truediv__ __trunc__ as_integer_ratio conjugate from_number fromhex hex imag is_integer " + + "real ")); + BUILTIN_NAMES.put("frozenset", names("__and__ __class_getitem__ __contains__ __eq__ __ge__ __gt__ __hash__ __iter__ __le__ " + + "__len__ __lt__ __ne__ __new__ __or__ __rand__ __reduce__ __repr__ __ror__ __rsub__ " + + "__rxor__ __sizeof__ __sub__ __xor__ copy difference intersection isdisjoint issubset " + + "issuperset symmetric_difference union ")); + } + + private static Set names(String s) { + return new HashSet(java.util.Arrays.asList(s.trim().split(" +"))); + } + + /// The builtin `b` names as a first base -- `str`, or `list[str]` -- + /// when the module never rebinds the name; null otherwise. + static String builtinBase(Expr b, Set moduleAssigned) { + Expr e = b instanceof Subscript ? ((Subscript) b).value : b; + if (!(e instanceof Name) || moduleAssigned.contains(((Name) e).id) + || !BUILTIN_NAMES.containsKey(((Name) e).id)) { + return null; + } + return ((Name) e).id; + } + + /// The builtin exception types a compiled class may derive from, by + /// the name a base spells, to the canonical name the runtime gives the + /// type (`IOError` and `EnvironmentError` are `OSError`). + static final Map EXCEPTION_TYPES = new LinkedHashMap(); + + static { + for (String n : ("BaseException SystemExit KeyboardInterrupt GeneratorExit Exception StopIteration " + + "ArithmeticError ZeroDivisionError OverflowError AssertionError AttributeError LookupError " + + "IndexError KeyError NameError UnboundLocalError RuntimeError NotImplementedError RecursionError " + + "TypeError ValueError UnicodeError ImportError ModuleNotFoundError OSError FileNotFoundError " + + "MemoryError UnicodeEncodeError UnicodeDecodeError UnicodeTranslateError FloatingPointError " + + "StopAsyncIteration EOFError BufferError ReferenceError SystemError SyntaxError IndentationError " + + "TabError FileExistsError PermissionError IsADirectoryError NotADirectoryError TimeoutError " + + "InterruptedError BlockingIOError ChildProcessError ProcessLookupError ConnectionError " + + "BrokenPipeError ConnectionAbortedError ConnectionRefusedError ConnectionResetError Warning " + + "UserWarning DeprecationWarning PendingDeprecationWarning SyntaxWarning RuntimeWarning " + + "FutureWarning ImportWarning UnicodeWarning BytesWarning ResourceWarning EncodingWarning").split(" ")) { + EXCEPTION_TYPES.put(n, n); + } + EXCEPTION_TYPES.put("IOError", "OSError"); + EXCEPTION_TYPES.put("EnvironmentError", "OSError"); + } + + /// What every builtin exception binds or stores in an instance's + /// attribute table, the attributes of the families that set more + /// (OSError's `errno`, SyntaxError's `lineno`, UnicodeError's `start`) + /// included for all of them: such a name is never a field, so the + /// runtime's own stores and reads of it meet the user's. + static final Set EXCEPTION_NAMES = names("__init__ __new__ __str__ __repr__ __reduce__ __setstate__ " + + "args with_traceback add_note __notes__ __cause__ __context__ __suppress_context__ __traceback__ " + + "errno strerror filename filename2 winerror characters_written encoding object start end reason " + + "code value msg lineno offset text end_lineno end_offset print_file_and_line name path obj " + + "exceptions message"); + + /// The canonical builtin exception `b` names, when the module never + /// rebinds the name; null otherwise. + static String exceptionBase(Expr b, Set moduleAssigned) { + if (!(b instanceof Name) || moduleAssigned.contains(((Name) b).id)) { + return null; + } + return EXCEPTION_TYPES.get(((Name) b).id); + } + + /// Whether `c`'s one keyword is `metaclass=M`, `M` a class of the + /// module deriving from `type` alone that does not bind `__call__`: it + /// shapes the class object (bs4's lazily computed entity tables), and + /// constructing an instance still runs `type.__call__`, which makes it + /// with the layout. + /// Why the keywords of `kc` (named ones other than `metaclass` already + /// dropped) refuse a layout: a metaclass the build cannot rewrite, or a + /// `**mapping` that may carry one. + private static String keywordWhy(ClassDef kc) { + for (Keyword kw : kc.keywords) { + if (kw.arg == null) { + return "its class keywords include **" + text(kw.value) + ", which may carry a metaclass"; + } + } + if (kc.keywords.size() == 1) { + return "its metaclass " + text(kc.keywords.get(0).value) + " is not one defined once in the module," + + " deriving from type and binding no hook besides __call__, __getattr__, __new__ and __init__"; + } + return "it names more than one metaclass"; + } + + private static boolean plainMetaclass(List body, ClassDef c, Set moduleAssigned) { + if (c.keywords.size() == 1 && "metaclass".equals(c.keywords.get(0).arg) + && (abcMeta(body, c.keywords.get(0).value) || enumTypeMeta(body, c.keywords.get(0).value))) { + return true; + } + if (c.keywords.size() != 1 || !"metaclass".equals(c.keywords.get(0).arg) + || !(c.keywords.get(0).value instanceof Name)) { + return false; + } + return metaclassChain(body, ((Name) c.keywords.get(0).value).id, moduleAssigned, LAYOUT_SAFE_HOOKS, 0); + } + + /// The hooks a metaclass may bind and still leave its classes a + /// layout. `__getattr__` runs only for a class attribute that is not + /// found, so nothing the compiler resolves statically reaches it, and + /// an instance never consults its metaclass. `__call__` decides what + /// calling the class answers: such a class is constructed by calling + /// it ([Cls#metaCall]), never by `new` and `__init__`, and the result + /// is typed as any object. `__new__` and `__init__` shape the class + /// when it is made: what they add to it is reached as any class + /// attribute is, and the runtime refuses one that replaces the class or + /// rebinds or adds a name the layout compiled (`PyType.finish`). + private static final Set LAYOUT_SAFE_HOOKS = new HashSet(java.util.Arrays.asList("__call__", + "__getattr__", "__new__", "__init__")); + + /// Whether `m` is a metaclass of the module, defined once, deriving + /// from `type` alone or from such a metaclass (each level checked), no + /// level with class keywords, decorators, or a hook of + /// [#METACLASS_HOOKS] outside `allowed`. + private static boolean metaclassChain(List body, String m, Set moduleAssigned, Set allowed, + int depth) { + ClassDef md = classNamed(body, m); + if (depth > 16 || md == null || !definedOnce(body, m) || md.bases.size() != 1 || !md.keywords.isEmpty() + || !md.decorators.isEmpty() || !(md.bases.get(0) instanceof Name)) { + return false; + } + Set hooks = new HashSet(bodyBindings(md)); + hooks.retainAll(METACLASS_HOOKS); + hooks.removeAll(allowed); + if (!hooks.isEmpty()) { + return false; + } + for (Stmt st : md.body) { + if (!(st instanceof FunctionDef)) { + continue; + } + FunctionDef f = (FunctionDef) st; + if ("__new__".equals(f.name) && (!keepsClass(f) || !leavesNamespace(f, classBound(body))) + || "__init__".equals(f.name) && !leavesNamespace(f, classBound(body)) + || "__prepare__".equals(f.name) && !plainPrepare(f)) { + return false; + } + } + String b = ((Name) md.bases.get(0)).id; + if ("type".equals(b)) { + return !moduleAssigned.contains("type"); + } + return metaclassChain(body, b, moduleAssigned, allowed, depth + 1); + } + + /// Whether a metaclass `__new__` answers the class the class statement + /// built: every `return` hands back `X.__new__(mcs, name, bases, ...)` + /// with its own `bases` parameter, never rebound, or a local assigned + /// only from such a call. Another class (other bases, a class of its + /// own making) is a class the layout does not describe. + private static boolean keepsClass(FunctionDef f) { + if (f.args.positional.size() < 3 || !f.decorators.isEmpty()) { + return false; + } + String bases = f.args.positional.get(2).name; + Map n = new HashMap(); + for (Stmt s : f.body) { + DataclassInit.count(s, n); + } + if (n.containsKey(bases)) { + return false; + } + Map fwd = new HashMap(); + for (Stmt s : f.body) { + madeLocals(s, bases, fwd); + } + Set made = new HashSet(); + for (Map.Entry e : fwd.entrySet()) { + if (e.getValue().equals(n.get(e.getKey()))) { + made.add(e.getKey()); + } + } + boolean[] ok = {true}; + for (Stmt s : f.body) { + returnsClass(s, bases, made, ok); + } + return ok[0]; + } + + /// Whether a `__prepare__` answers a fresh empty dict on every path + /// (`return {}` or `return dict()`): any other mapping can rewrite the + /// names the class body binds, which the layout compiled as written. + private static boolean plainPrepare(FunctionDef f) { + boolean[] ok = {true}; + for (Stmt s : f.body) { + emptyDictReturns(s, ok); + } + return ok[0]; + } + + private static void emptyDictReturns(Object o, boolean[] ok) { + if (o instanceof FunctionDef || o instanceof ClassDef || o instanceof Lambda) { + return; + } + if (o instanceof Return) { + Expr v = ((Return) o).value; + ok[0] &= v instanceof DictExpr && ((DictExpr) v).keys.isEmpty() + || v instanceof Call && ((Call) v).func instanceof Name && "dict".equals(((Name) ((Call) v).func).id) + && ((Call) v).args.isEmpty() && ((Call) v).keywords.isEmpty(); + return; + } + Infer.children(o, x -> emptyDictReturns(x, ok)); + } + + /// Reading methods of the namespace dict that never change it. + private static final Set NAMESPACE_READS = new HashSet(java.util.Arrays.asList("get", "items", + "keys", "values", "copy", "__contains__", "__getitem__")); + + /// Whether a metaclass `__new__` or `__init__` leaves the class body's + /// names as the body bound them: it never calls `setattr` or `delattr`, + /// never deletes an attribute or key, stores an attribute or a namespace + /// key only by a literal name no class body of the module binds + /// (`cls._inst = None`, `ns["made_by"] = ...`: an addition, never a + /// rewrite), never rebinds its namespace parameter, and uses that + /// parameter otherwise only to read it + /// (subscript load, `in`, a method of [#NAMESPACE_READS]) or to hand it + /// unchanged to a `__new__` / `__init__` call. Anything else may rewrite + /// or wrap a name the layout compiled, so strict refuses the layout at + /// build time; `PyType.finish` stays as the run-time backstop. + private static boolean leavesNamespace(FunctionDef f, Set bound) { + if (!f.decorators.isEmpty()) { + return false; + } + String ns = f.args.positional.size() >= 4 ? f.args.positional.get(3).name : null; + if (ns != null) { + Map n = new HashMap(); + for (Stmt s : f.body) { + DataclassInit.count(s, n); + } + if (n.containsKey(ns)) { + return false; + } + } + java.util.IdentityHashMap okUses = new java.util.IdentityHashMap(); + boolean[] ok = {true}; + for (Stmt s : f.body) { + namespaceUses(s, ns, bound, okUses, ok); + } + return ok[0]; + } + + private static boolean isNs(Expr e, String ns) { + return ns != null && e instanceof Name && ns.equals(((Name) e).id); + } + + private static void storeTarget(Expr t, String ns, Set bound, boolean[] ok) { + // `cls._inst = None` or `ns["made_by"] = ...`: a name no class body + // of the module binds adds to the class and rewrites nothing the + // layout compiled + boolean fresh = bound != null && (t instanceof Attribute && ((Attribute) t).value instanceof Name + && !bound.contains(((Attribute) t).attr) + || t instanceof Subscript && isNs(((Subscript) t).value, ns) + && ((Subscript) t).index instanceof Constant + && ((Constant) ((Subscript) t).index).kind == Constant.Kind.STR + && !bound.contains(((Constant) ((Subscript) t).index).text)); + if (fresh) { + return; + } else if (t instanceof Attribute || t instanceof Subscript) { + ok[0] = false; + } else if (t instanceof TupleExpr) { + for (Expr e : ((TupleExpr) t).elts) { + storeTarget(e, ns, null, ok); + } + } else if (t instanceof ListExpr) { + for (Expr e : ((ListExpr) t).elts) { + storeTarget(e, ns, null, ok); + } + } else if (t instanceof Starred) { + storeTarget(((Starred) t).value, ns, null, ok); + } + } + + private static void namespaceUses(Object o, String ns, Set bound, + java.util.IdentityHashMap okUses, boolean[] ok) { + if (!ok[0] || o instanceof FunctionDef || o instanceof ClassDef || o instanceof Lambda) { + if (o instanceof FunctionDef || o instanceof ClassDef || o instanceof Lambda) { + // a nested scope that names the namespace may keep it and write it later + Set names = new HashSet(); + Infer.children(o, x -> collectNames(x, names)); + ok[0] &= ns == null || !names.contains(ns); + } + return; + } + if (o instanceof Assign) { + for (Expr t : ((Assign) o).targets) { + storeTarget(t, ns, bound, ok); + } + } else if (o instanceof AugAssign) { + storeTarget(((AugAssign) o).target, ns, null, ok); + } else if (o instanceof AnnAssign) { + storeTarget(((AnnAssign) o).target, ns, bound, ok); + } else if (o instanceof Delete) { + for (Expr t : ((Delete) o).targets) { + storeTarget(t, ns, null, ok); + } + } else if (o instanceof For) { + storeTarget(((For) o).target, ns, null, ok); + } else if (o instanceof Call) { + Call c = (Call) o; + if (c.func instanceof Name && ("setattr".equals(((Name) c.func).id) + || "delattr".equals(((Name) c.func).id))) { + ok[0] = false; + return; + } + if (c.func instanceof Attribute && isNs(((Attribute) c.func).value, ns) + && NAMESPACE_READS.contains(((Attribute) c.func).attr)) { + okUses.put(((Attribute) c.func).value, Boolean.TRUE); + } + if (c.func instanceof Attribute && ("__new__".equals(((Attribute) c.func).attr) + || "__init__".equals(((Attribute) c.func).attr))) { + for (Expr a : c.args) { + if (isNs(a, ns)) { + okUses.put(a, Boolean.TRUE); + } + } + } + } else if (o instanceof Subscript && isNs(((Subscript) o).value, ns)) { + // a load, or a store of a fresh literal key storeTarget allowed + okUses.put(((Subscript) o).value, Boolean.TRUE); + } else if (o instanceof Compare) { + Compare c = (Compare) o; + for (int i = 0; i < c.ops.size(); i++) { + String op = c.ops.get(i); + if (("in".equals(op) || "not in".equals(op)) && isNs(c.comparators.get(i), ns)) { + okUses.put(c.comparators.get(i), Boolean.TRUE); + } + } + } else if (isNs(o instanceof Expr ? (Expr) o : null, ns) && !okUses.containsKey(o)) { + ok[0] = false; + return; + } + Infer.children(o, x -> namespaceUses(x, ns, bound, okUses, ok)); + } + + /// Every name some class body of the module binds: a metaclass write + /// of any other name cannot rewrite what a layout compiled. + private static Set classBound(List body) { + Set r = new HashSet(); + for (Stmt s : body) { + if (s instanceof ClassDef) { + r.addAll(bodyBindings((ClassDef) s)); + } + } + return r; + } + + private static void collectNames(Object o, Set names) { + if (o instanceof Name) { + names.add(((Name) o).id); + } + Infer.children(o, x -> collectNames(x, names)); + } + + private static boolean forwardingNew(Expr v, String bases) { + return v instanceof Call && ((Call) v).func instanceof Attribute + && "__new__".equals(((Attribute) ((Call) v).func).attr) && ((Call) v).args.size() >= 3 + && ((Call) v).args.get(2) instanceof Name && bases.equals(((Name) ((Call) v).args.get(2)).id); + } + + /// Counts, per local, the assignments `v = X.__new__(mcs, name, bases, ...)`. + private static void madeLocals(Object o, String bases, Map fwd) { + if (o instanceof FunctionDef || o instanceof ClassDef || o instanceof Lambda) { + return; + } + if (o instanceof Assign && ((Assign) o).targets.size() == 1 && ((Assign) o).targets.get(0) instanceof Name + && forwardingNew(((Assign) o).value, bases)) { + String t = ((Name) ((Assign) o).targets.get(0)).id; + Integer c = fwd.get(t); + fwd.put(t, c == null ? 1 : c + 1); + } + Infer.children(o, x -> madeLocals(x, bases, fwd)); + } + + private static void returnsClass(Object o, String bases, Set made, boolean[] ok) { + if (o instanceof FunctionDef || o instanceof ClassDef || o instanceof Lambda) { + return; + } + if (o instanceof Return) { + Expr v = ((Return) o).value; + ok[0] &= forwardingNew(v, bases) || v instanceof Name && made.contains(((Name) v).id); + return; + } + Infer.children(o, x -> returnsClass(x, bases, made, ok)); + } + + /// Whether some level of the metaclass chain of `m` ([#metaclassChain]) + /// binds `__call__`. + private static boolean metaclassCalls(List body, String m, int depth) { + ClassDef md = classNamed(body, m); + if (md == null || depth > 16) { + return false; + } + if (bodyBindings(md).contains("__call__")) { + return true; + } + return md.bases.size() == 1 && md.bases.get(0) instanceof Name + && metaclassCalls(body, ((Name) md.bases.get(0)).id, depth + 1); + } + + /// Whether `c` is itself a metaclass: a class statement with no + /// keywords or decorators whose one base is `type` (never rebound) or a + /// metaclass of the module. Its instances are classes -- `PyType` + /// objects, whose attributes live in the class's own dictionary -- so it + /// is laid out as that: no Java class of its own, its methods typed and + /// entered as dynamic dispatch enters them (by `type.__call__`, a class + /// statement, an attribute of a class it made). + static boolean metaclassDef(List body, ClassDef c, Set moduleAssigned, Map byName) { + if (!c.keywords.isEmpty() || !c.decorators.isEmpty() || c.bases.size() != 1 + || !(c.bases.get(0) instanceof Name)) { + return false; + } + String b = ((Name) c.bases.get(0)).id; + if ("type".equals(b)) { + return !moduleAssigned.contains("type"); + } + Cls k = byName.get(b); + return k != null && k.metaclass; + } + + /// Whether `m` is `abc.ABCMeta`: the name imported once from `abc` (or + /// from `_cn1op`, where abc.py itself takes it) and never rebound, or + /// `abc.ABCMeta` through a module imported once as `abc` or an alias. + /// That metaclass is the runtime's own (runtime class `Abc`): it computes + /// `__abstractmethods__` when the class is made and checks them on + /// construction, and type.__call__ still makes the instance, so its + /// classes keep a layout. + static boolean abcMeta(List body, Expr m) { + return runtimeMeta(body, m, "abc", "ABCMeta", null); + } + + /// Whether `m` is `enum.EnumType` (or its alias `EnumMeta`), the + /// runtime's own metaclass (runtime class `EnumMeta`), bound as + /// [#abcMeta] binds `ABCMeta`. + static boolean enumTypeMeta(List body, Expr m) { + return runtimeMeta(body, m, "enum", "EnumType", null) || runtimeMeta(body, m, "enum", "EnumMeta", "EnumType"); + } + + /// [#abcMeta] for the metaclass `attr` of module `module`; `real` is the + /// name `_cn1op` binds it to when that differs from `attr`. + private static boolean runtimeMeta(List body, Expr m, String module, String attr, String real) { + String opName = real != null ? real : attr; + if (m instanceof Attribute && attr.equals(((Attribute) m).attr) && ((Attribute) m).value instanceof Name) { + String alias = ((Name) ((Attribute) m).value).id; + int found = 0; + int binds = 0; + for (Stmt s : body) { + if (s instanceof Import) { + for (Alias a : ((Import) s).names) { + String as = a.asname != null ? a.asname : a.name; + if (as.equals(alias)) { + binds++; + found += module.equals(a.name) ? 1 : 0; + } + } + } else if (s instanceof ImportFrom) { + for (Alias a : ((ImportFrom) s).names) { + binds += (a.asname != null ? a.asname : a.name).equals(alias) ? 1 : 0; + } + } else if (s instanceof Assign || s instanceof AnnAssign || s instanceof ClassDef + || s instanceof FunctionDef) { + binds += bindsName(s, alias) ? 1 : 0; + } + } + return found == 1 && binds == 1; + } + if (!(m instanceof Name)) { + return false; + } + String n = ((Name) m).id; + int found = 0; + int binds = 0; + for (Stmt s : body) { + if (s instanceof ImportFrom) { + ImportFrom f = (ImportFrom) s; + for (Alias a : f.names) { + String as = a.asname != null ? a.asname : a.name; + if (as.equals(n)) { + binds++; + found += f.level == 0 && (module.equals(f.module) && attr.equals(a.name) + || "_cn1op".equals(f.module) && opName.equals(a.name)) ? 1 : 0; + } + } + } else if (s instanceof Assign || s instanceof AnnAssign || s instanceof ClassDef + || s instanceof FunctionDef || s instanceof Import) { + binds += bindsName(s, n) ? 1 : 0; + } + } + return found == 1 && binds == 1; + } + + /// The dunders `EnumType` copies onto a class mixing a builtin into an + /// enum; `PyType.ENUM_COPIED` in the runtime must name the same ones. + private static final Set ENUM_COPIED = new HashSet(java.util.Arrays.asList("__repr__", + "__str__", "__format__", "__hash__")); + + /// What a metaclass may not define for its classes to keep a layout: + /// construction, and the comparisons typed code makes by identity. + private static final Set METACLASS_HOOKS = new HashSet(java.util.Arrays.asList("__call__", + "__eq__", "__ne__", "__hash__", "__instancecheck__", "__subclasscheck__", "__new__", "__init__", + "__getattribute__", "__getattr__", "__name__", "__qualname__", "__module__")); + + /// The builtins `typing`'s aliases stand for as a base: `class + /// ResultSet(List[T])` extends `list`. + private static final Map TYPING_ALIASES = new LinkedHashMap(); + + static { + TYPING_ALIASES.put("List", "list"); + TYPING_ALIASES.put("Dict", "dict"); + TYPING_ALIASES.put("Set", "set"); + TYPING_ALIASES.put("FrozenSet", "frozenset"); + TYPING_ALIASES.put("Tuple", "tuple"); + } + + /// The builtin `b` stands for when it is `Alias[...]` of a `typing` + /// alias the module imports under its own name, once, and never rebinds. + static String typingAliasBase(List body, Expr b) { + if (!(b instanceof Subscript) || !(((Subscript) b).value instanceof Name)) { + return null; + } + String n = ((Name) ((Subscript) b).value).id; + String t = TYPING_ALIASES.get(n); + if (t == null) { + return null; + } + int imports = 0; + int binds = 0; + for (Stmt s : body) { + if (s instanceof ImportFrom) { + for (Alias a : ((ImportFrom) s).names) { + String as = a.asname != null ? a.asname : a.name; + if (as.equals(n)) { + binds++; + imports += "typing".equals(((ImportFrom) s).module) && ((ImportFrom) s).level == 0 + && a.name.equals(n) ? 1 : 0; + } + } + } else if (s instanceof Assign || s instanceof AnnAssign || s instanceof ClassDef + || s instanceof FunctionDef || s instanceof Import) { + binds += bindsName(s, n) ? 1 : 0; + } + } + return imports == 1 && binds == 1 ? t : null; + } + + private static boolean bindsName(Stmt s, String n) { + if (s instanceof ClassDef) { + return ((ClassDef) s).name.equals(n); + } + if (s instanceof FunctionDef) { + return ((FunctionDef) s).name.equals(n); + } + if (s instanceof Import) { + for (Alias a : ((Import) s).names) { + if ((a.asname != null ? a.asname : a.name.split("\\.")[0]).equals(n)) { + return true; + } + } + return false; + } + List ts = s instanceof Assign ? ((Assign) s).targets : java.util.Collections.singletonList(((AnnAssign) s).target); + for (Expr t : ts) { + if (t instanceof Name && ((Name) t).id.equals(n)) { + return true; + } + } + return false; + } + + /// A name the chain from `k` up binds that the builtin `builtin` binds + /// too, or null. + /// A name the class binds itself is not one: its own binding comes + /// before both. Nor, below an enum, is a name `EnumType` copies onto + /// each mixed-in class from the nearest enum (or the mixin, for + /// `__hash__`) when the class is made, as CPython's does. + private static String builtinClash(Cls k, String builtin, Set own) { + Set bn = BUILTIN_NAMES.get(builtin); + for (Cls a = k; a != null; a = a.parent) { + for (String n : a.bodyNames) { + if (bn.contains(n) && !own.contains(n) && !(k.enumMeta && ENUM_COPIED.contains(n))) { + return n; + } + } + } + return null; + } + + /// Whether every decorator of `c` provably answers the class it is + /// given, so the name binds the class the layout describes: a module + /// function `f(p)`, or the `__call__(self, p)` of an instance of a + /// module class (`@Deco("c")`), never rebinding `p`, whose every path + /// that a class reaches returns `p` -- all of its returns, or those under + /// an `if isinstance(p, type):` that ends in one. What the decorator + /// does to the class besides (`p.__init__ = f`) is a store on a class + /// like any other, which the program's facts already account for. + boolean returnsItsClass(List body, ClassDef c) { + if (fixedGlobal == null) { + return false; + } + for (Expr d : c.decorators) { + FunctionDef f = null; + int param = 0; + if (d instanceof Name && fixedGlobal.test(((Name) d).id)) { + f = moduleDef(body, ((Name) d).id); + } else if (d instanceof Call && ((Call) d).func instanceof Name + && fixedGlobal.test(((Name) ((Call) d).func).id)) { + for (Stmt s : body) { + if (s instanceof ClassDef && ((ClassDef) s).name.equals(((Name) ((Call) d).func).id) + && ((ClassDef) s).decorators.isEmpty() && ((ClassDef) s).bases.isEmpty()) { + f = moduleDef(((ClassDef) s).body, "__call__"); + param = 1; + } + } + } + if (f == null || f.args.positional.size() != param + 1 || f.args.vararg != null + || !f.args.kwonly.isEmpty() || f.args.kwarg != null || !f.decorators.isEmpty() || f.isAsync) { + return false; + } + String p = f.args.positional.get(param).name; + if (stores(f.body, p) || !returnsParam(f.body, p)) { + return false; + } } + return true; } - final Map classes = new LinkedHashMap(); - /// Field name -> the classes that declare it (not inherit it). - final Map> fieldOwners = new LinkedHashMap>(); - /// `name/arity` of every compiled method, arity without the receiver. - final Set dispatch = new LinkedHashSet(); - final Map staticNames = new LinkedHashMap(); - /// The class each compiled method belongs to. - final Map methodClass = new LinkedHashMap(); + private static FunctionDef moduleDef(List body, String name) { + FunctionDef found = null; + for (Stmt s : body) { + if (s instanceof FunctionDef && ((FunctionDef) s).name.equals(name)) { + if (found != null) { + return null; + } + found = (FunctionDef) s; + } + } + return found; + } - private static final Set FORBIDDEN = new HashSet(); + /// Whether `block`, entered with a class in `p`, ends every path in + /// `return p`. + private static boolean returnsParam(List block, String p) { + for (Stmt s : block) { + if (s instanceof Return) { + Expr v = ((Return) s).value; + return v instanceof Name && ((Name) v).id.equals(p); + } + if (s instanceof If) { + If i = (If) s; + if (isTypeTest(i.test, p)) { + // A class never reaches the else branch nor what follows. + return returnsParam(i.body, p); + } + if (!noReturn(i.body) || !noReturn(i.orelse)) { + return false; + } + } else if (!noReturn(java.util.Collections.singletonList(s))) { + return false; + } + } + return false; + } - static { - // A class that customises attribute access itself is left alone. - // `__slots__` is not on the list: it fixes the attribute set, which - // is what a layout is, and the generic instance does not enforce it - // either, so the two paths agree. - FORBIDDEN.add("__setattr__"); - FORBIDDEN.add("__getattribute__"); - FORBIDDEN.add("__delattr__"); - FORBIDDEN.add("__dict__"); - FORBIDDEN.add("__class__"); - FORBIDDEN.add("__new__"); + private static boolean isTypeTest(Expr t, String p) { + if (!(t instanceof Call)) { + return false; + } + Call c = (Call) t; + return c.func instanceof Name && "isinstance".equals(((Name) c.func).id) && c.args.size() == 2 + && c.keywords.isEmpty() && c.args.get(0) instanceof Name && ((Name) c.args.get(0)).id.equals(p) + && c.args.get(1) instanceof Name && "type".equals(((Name) c.args.get(1)).id); } - /// `attrStores` is the module scope's (`Scope.attrStores`): a field the - /// module itself assigns on a class is left to the generic path, since - /// the class attribute -- a property, say -- must then decide its reads. - static Layouts plan(List body, String prefix, Set attrStores) { + /// Whether no `return`, `yield` or `raise`-free escape of the function + /// itself is in `o` (nested functions and classes are their own). + private static boolean noReturn(Object o) { + if (o instanceof Return || o instanceof Yield || o instanceof Try) { + return false; + } + if (o instanceof FunctionDef || o instanceof ClassDef || o instanceof Lambda) { + return true; + } + boolean[] ok = {true}; + Infer.children(o, x -> ok[0] &= noReturn(x)); + return ok[0]; + } + + /// Whether `p` is stored anywhere in the function, nested scopes included. + private static boolean stores(Object o, String p) { + if (o instanceof Name) { + return false; + } + if (o instanceof Assign) { + for (Expr t : ((Assign) o).targets) { + if (t instanceof Name && ((Name) t).id.equals(p)) { + return true; + } + } + } + if ((o instanceof AugAssign && ((AugAssign) o).target instanceof Name && ((Name) ((AugAssign) o).target).id.equals(p)) + || (o instanceof For && ((For) o).target instanceof Name && ((Name) ((For) o).target).id.equals(p)) + || o instanceof Global || o instanceof NamedExpr) { + return true; + } + boolean[] hit = {false}; + Infer.children(o, x -> hit[0] |= stores(x, p)); + return hit[0]; + } + + static String text(Expr e) { + if (e instanceof Name) { + return ((Name) e).id; + } + if (e instanceof Attribute) { + return text(((Attribute) e).value) + "." + ((Attribute) e).attr; + } + return e.getClass().getSimpleName(); + } + + static Layouts plan(List body, String prefix, Set attrStores, Set moduleAssigned) { + return plan(body, prefix, attrStores, moduleAssigned, null); + } + + static Layouts plan(List body, String prefix, Set attrStores, Set moduleAssigned, + java.util.function.Function foreignBase) { + return plan(body, prefix, attrStores, moduleAssigned, foreignBase, java.util.Collections.emptySet(), + null, null, null); + } + + /// `foreignBase` names the compiled class of another module a base + /// expression is, or answers null; it is asked only for a base that is + /// none of this module's classes. Such a class extends that class's + /// Java class -- `BeautifulSoup(Tag)` in `bs4` over `bs4.element`'s + /// `Tag` -- and is planned only when nothing it binds or stores changes + /// what the base's fields and methods were planned as + /// ([#extendsForeign]), since that plan is already made. + /// + /// `excluded` names this module's classes another module mixes in + /// ([#foreignMixin]): they stay uncompiled, as a mixin of this module + /// does. `foreignMixin` names such a class of another module that a base + /// expression is, or answers null: a class mixing it in is planned with + /// what it binds and stores kept out of its fields. + static Layouts plan(List body, String prefix, Set attrStores, Set moduleAssigned, + java.util.function.Function foreignBase, Set excluded, + java.util.function.Function foreignMixin, java.util.function.Predicate constantGlobal, + java.util.function.Predicate fixedGlobal) { Layouts l = new Layouts(); + l.moduleAssigned = moduleAssigned; + l.constantGlobal = constantGlobal; + l.fixedGlobal = fixedGlobal; Map byName = new LinkedHashMap(); + Set mixins = mixins(body); + Set superNames = new HashSet(); + superAttrs(body, superNames); int n = 0; + boolean bindsObject = moduleAssigned.contains("object"); for (Stmt s : body) { if (!(s instanceof ClassDef)) { continue; } ClassDef c = (ClassDef) s; Cls parent = null; - boolean ok = c.keywords.isEmpty() && c.decorators.isEmpty() && c.bases.size() <= 1; - if (ok && c.bases.size() == 1) { - Expr b = c.bases.get(0); + // A class another class names as an extra base keeps its own + // layout: that class copies its fields ([#mergeExtras]), and + // `isinstance` never narrows to it (Infer#layoutHolds), since + // the instances of that other class do not extend its Java class. + // `boundary=` is EnumType's own keyword (`class Flag(Enum, + // boundary=STRICT)`), consumed when the class is made; the class + // must turn out to be an enum (checked below). + boolean boundaryKw = false; + ClassDef kc = c; + for (Keyword kw : c.keywords) { + boundaryKw |= "boundary".equals(kw.arg); + } + // Any other named keyword is handed to the metaclass and to + // `__init_subclass__` when the class is made, which run as they + // do for a class without keywords (PyType.finish); it shapes no + // instance. A `**mapping` may hold `metaclass`, and stays. + boolean namedKw = false; + for (Keyword kw : c.keywords) { + namedKw |= kw.arg != null && !"metaclass".equals(kw.arg); + } + if (boundaryKw || namedKw) { + kc = new ClassDef(c.name, c.bases, new ArrayList(), c.body, c.decorators); + for (Keyword kw : c.keywords) { + if (kw.arg == null || "metaclass".equals(kw.arg)) { + kc.keywords.add(kw); + } + } + } + if (metaclassDef(body, c, moduleAssigned, byName)) { + Cls mk = byName.get(((Name) c.bases.get(0)).id); + Cls k = new Cls(c, prefix + "M" + c.line + "_" + Emitter.mangle(c.name), + "V" + c.line + "_" + Emitter.mangle(c.name), mk); + k.compiled = false; + k.metaclass = true; + k.home = l; + l.classes.put(c, k); + byName.put(c.name, k); + continue; + } + boolean enumKw = kc.keywords.size() == 1 && "metaclass".equals(kc.keywords.get(0).arg) + && enumTypeMeta(body, kc.keywords.get(0).value); + boolean ok = (kc.keywords.isEmpty() || plainMetaclass(body, kc, moduleAssigned)) && (c.decorators.isEmpty() || c.dataclass || l.returnsItsClass(body, c)); + String why = ok ? null : c.decorators.isEmpty() ? keywordWhy(kc) : "it has class decorators"; + Set extraNames = new HashSet(); + List extraCls = new ArrayList(); + boolean extra = false; + String builtin = ok && !c.bases.isEmpty() ? builtinBase(c.bases.get(0), moduleAssigned) : null; + if (builtin == null && ok && !c.bases.isEmpty()) { + builtin = typingAliasBase(body, c.bases.get(0)); + } + String foreignWhy = null; + List after = new ArrayList(); + for (int i = 1; builtin != null && i < c.bases.size(); i++) { + if (typingBase(c.bases.get(i))) { + // `Generic[T]` adds nothing an instance has. + extra = true; + } else { + after.add(origin(c.bases.get(i))); + } + } + if (builtin != null && after.size() > 1) { + ok = false; + why = "more than one base after the builtin " + builtin; + } else if (builtin != null && after.size() == 1) { + // `class NavigableString(str, PageElement)`: the compiled + // class is the Java parent, the builtin value the instance's + // base; the MRO puts the builtin first, so none of the + // chain's names may be one of the builtin's. + Expr b = after.get(0); parent = b instanceof Name ? byName.get(((Name) b).id) : null; - ok = parent != null; + if (parent == null && foreignBase != null && !(b instanceof Name && moduleClassNamed(body, ((Name) b).id))) { + Cls fp = foreignBase.apply(b); + foreignWhy = fp == null ? null : extendsForeign(c, fp, l, byName, foreignBase); + parent = fp != null && foreignWhy == null ? fp : null; + } + String clash = parent == null ? null : builtinClash(parent, builtin, bodyBindings(c)); + if (parent == null) { + ok = false; + why = foreignWhy != null ? "it cannot extend " + text(b) + ": " + foreignWhy + : "base " + text(b) + " has no layout"; + } else if (parent.builtin != null) { + ok = false; + why = "base " + text(b) + " extends the builtin " + parent.builtin + " too"; + } else if (clash != null) { + ok = false; + why = "base " + text(b) + " binds " + clash + ", which the builtin " + builtin + " binds before it"; + } + } + List excBases = new ArrayList(); + String firstExc = builtin == null && ok && !c.bases.isEmpty() ? exceptionBase(c.bases.get(0), moduleAssigned) : null; + if (firstExc != null) { + excBases.add(firstExc); + } + for (int i = 1; ok && builtin == null && i < c.bases.size(); i++) { + Expr b = origin(c.bases.get(i)); + String eb = exceptionBase(b, moduleAssigned); + if (eb != null) { + // `class InvalidSchema(RequestException, ValueError)`: + // the type keeps the builtin, which the MRO puts after + // the compiled chain, for `except` and `isinstance`. + excBases.add(eb); + continue; + } + if (firstExc != null || !excBases.isEmpty()) { + ok = false; + why = "extra base " + text(b) + " beside a builtin exception"; + break; + } + extra = true; + Cls xb = b instanceof Name ? byName.get(((Name) b).id) : null; + if (xb == null && foreignBase != null && !(b instanceof Name && moduleClassNamed(body, ((Name) b).id))) { + xb = foreignBase.apply(b); + } + if (xb != null && xb.compiled) { + // A compiled extra base: merged by the MRO below. + extraCls.add(xb); + continue; + } + ClassDef fm = b instanceof Name && moduleClassNamed(body, ((Name) b).id) || foreignMixin == null ? null + : foreignMixin.apply(b); + if (b instanceof Name && mixins.contains(((Name) b).id)) { + extraNames.addAll(bodyBindings(classNamed(body, ((Name) b).id))); + } else if (fm != null) { + // bs4's `BeautifulSoupHTMLParser(HTMLParser, + // DetectsXMLParsedAsHTML)`: the mixin's methods run as + // generic code over this instance, its stores of `self` + // landing in the instance's own attributes. + extraNames.addAll(bodyBindings(fm)); + extraNames.addAll(selfStores(fm)); + } else { + ok = typingBase(b); + why = ok ? why : "extra base " + text(b); + } + } + if (builtin == null && ok && !c.bases.isEmpty() && typingBase(c.bases.get(0))) { + // `class Box(Generic[T])`: no compiled base, as for `object`. + extra = true; + } else if (firstExc != null && ok) { + // `class UnsupportedOperation(OSError, ValueError)`: no + // compiled parent, every base a builtin exception. + parent = null; + } else if (builtin == null && ok && !c.bases.isEmpty()) { + Expr b = origin(c.bases.get(0)); + // `class X(object)` is a class with no base: the builtin adds + // nothing a compiled layout must defer to. Only when the + // module never rebinds the name, which it then could. + if (b instanceof Name && "object".equals(((Name) b).id) && !bindsObject) { + ok = true; + } else { + parent = b instanceof Name ? byName.get(((Name) b).id) : null; + if (parent == null && foreignBase != null && !(b instanceof Name && moduleClassNamed(body, ((Name) b).id))) { + Cls fp = foreignBase.apply(b); + foreignWhy = fp == null ? null : extendsForeign(c, fp, l, byName, foreignBase); + parent = fp != null && foreignWhy == null ? fp : null; + } + ok = parent != null; + why = ok ? why : foreignWhy != null ? "it cannot extend " + text(b) + ": " + foreignWhy + : "base " + text(b) + " has no layout"; + } + } + if (ok && extra && !excBases.isEmpty()) { + ok = false; + why = "a builtin exception base beside another extra base"; } for (String f : FORBIDDEN) { - ok &= !c.scope.assigned.contains(f); + if (ok && c.scope.assigned.contains(f)) { + ok = false; + why = "its body binds " + f; + } + } + if (ok && parent != null && !parent.compiled) { + ok = false; + why = "base " + parent.def.name + " has no layout"; + } + List merged = new ArrayList(); + Set inheritedNames = new HashSet(); + Cls javaParent = null; + if (ok && !extraCls.isEmpty()) { + why = mergeExtras(bodyBindings(c), parent, extraCls, superNames, extraNames, merged, inheritedNames); + ok = why == null; + // `class _BaseSlidePlaceholder(_InheritsDimensions, Shape)`: + // the first base is a mixin and a later one carries the + // __init__ and the fields. The Java parent need not be the + // first base: any base whose chain the C3 MRO keeps whole + // can be it, the others merged by the same rules (their + // names reached through the MRO, their fields copied). The + // MRO itself, and so every lookup, is that of the source + // order, which k.bases keeps. + for (int xi = 0; !ok && parent != null && parent.builtin == null && !parent.exception + && parent.excBases.isEmpty() && xi < extraCls.size(); xi++) { + Cls alt = extraCls.get(xi); + if (alt.builtin != null || alt.exception || !alt.excBases.isEmpty() || !alt.compiled) { + continue; + } + List rest = new ArrayList(); + rest.add(parent); + for (Cls e : extraCls) { + if (e != alt) { //NOPMD CompareObjectsWithEquals - identity is meant + rest.add(e); + } + } + Set tryNames = new HashSet(extraNames); + List tryMerged = new ArrayList(); + Set tryInherited = new HashSet(); + if (mergeExtrasOrdered(bodyBindings(c), alt, rest, srcOrder(parent, extraCls), superNames, tryNames, + tryMerged, tryInherited) == null) { + ok = true; + why = null; + javaParent = alt; + extraNames.addAll(tryNames); + merged.addAll(tryMerged); + inheritedNames.addAll(tryInherited); + } + } + } + if (ok && boundaryKw && !enumKw && (parent == null || !parent.enumMeta)) { + ok = false; + why = "its class keyword boundary= is EnumType's, but the class is not an enum"; } if (!ok) { - byName.remove(c.name); + l.refused.put(c, why); + Cls k = new Cls(c, prefix + "A" + l.refused.size() + "_" + Emitter.mangle(c.name), + "U" + l.refused.size() + "_" + Emitter.mangle(c.name), analysedParent(c, body, byName, foreignBase)); + k.compiled = false; + k.home = l; + l.classes.put(c, k); + byName.put(c.name, k); continue; } n++; + Cls srcParent = parent; + if (javaParent != null) { + parent = javaParent; + } Cls k = new Cls(c, prefix + "L" + n + "_" + Emitter.mangle(c.name), "T" + n + "_" + Emitter.mangle(c.name), parent); + k.mixinNames.addAll(extraNames); + if (srcParent != null) { + k.bases.add(srcParent); + } + k.bases.addAll(extraCls); + k.mixedFrom.addAll(merged); + k.bodyNames.addAll(inheritedNames); + k.mroNames.addAll(inheritedNames); + k.extraBases = extra; + k.builtin = builtin != null ? builtin : parent != null ? parent.builtin : null; + k.builtinOwn = builtin != null; + k.enumMeta = enumKw || parent != null && parent.enumMeta; + k.excBases.addAll(excBases); + k.exception = !excBases.isEmpty() || parent != null && parent.exception; + k.metaCall = parent != null && parent.metaCall || kc.keywords.size() == 1 + && kc.keywords.get(0).value instanceof Name + && metaclassCalls(body, ((Name) kc.keywords.get(0).value).id, 0); + for (Cls x : extraCls) { + k.metaCall |= x.metaCall; + } + if (!excBases.isEmpty()) { + // After the class's own body (and its compiled chain) in the + // MRO: what BaseException binds is found there, generically. + k.bodyNames.addAll(EXCEPTION_NAMES); + } + if (builtin != null) { + // Next in the MRO after the class's own body: every check of + // what the chain binds sees the builtin's names. + k.bodyNames.addAll(BUILTIN_NAMES.get(builtin)); + } + k.home = l; l.classes.put(c, k); byName.put(c.name, k); } - Set bodyNames = new HashSet(); + // A name a class body binds cannot be a field of that class, of any + // class above it, or of any compiled class below it (whose instances + // pass the `instanceof` of every class above). An unrelated class + // binding the same name changes nothing: only the exact compiled + // class gets the layout, so no instance of it reaches that body. + // Module-wide, a property `name` on `LoggerAdapter` cost `Logger` + // every field set after `name`, which then all lived in the shape. + Map> related = new LinkedHashMap>(); + for (Cls k : l.classes.values()) { + Set r = new HashSet(); + for (Cls c : l.classes.values()) { + if ((c.compiled == k.compiled) && (ancestorOf(k, c) || ancestorOf(c, k))) { + r.addAll(c.bodyNames); + r.addAll(c.mixinNames); + } + } + // A base of another module binds names in its body too. + for (Cls a = k.parent; a != null; a = a.parent) { + if (a.home != l) { //NOPMD CompareObjectsWithEquals - identity is meant + r.addAll(a.bodyNames); + } + } + related.put(k, r); + } + // `tag = None` in a class body is a default, not a descriptor: a + // constant has no `__set__` or `__get__`, so a store to the name on an + // instance binds the instance's own attribute, which a field holds, + // and an unset field falls back to the generic read, which finds the + // class's value. Only a name that every class binds that way and + // nothing else rebinds is freed. + Set constants = new HashSet(); + Set otherwise = new HashSet(); for (Cls k : l.classes.values()) { - bodyNames.addAll(k.bodyNames); + if (!k.compiled) { + continue; + } + for (Stmt s : k.def.body) { + if (s instanceof Assign && ((Assign) s).targets.size() == 1 && ((Assign) s).targets.get(0) instanceof Name + && ((Assign) s).value instanceof Constant) { + constants.add(((Name) ((Assign) s).targets.get(0)).id); + } else if (s instanceof AnnAssign && ((AnnAssign) s).target instanceof Name + && ((AnnAssign) s).value instanceof Constant) { + // `known_xml: Optional[bool] = None`: the annotation + // binds nothing, the constant is the same default. + constants.add(((Name) ((AnnAssign) s).target).id); + } else { + Set b = new HashSet(); + if (s instanceof FunctionDef) { + b.add(((FunctionDef) s).name); + } else if (s instanceof ClassDef) { + b.add(((ClassDef) s).name); + } else if (s instanceof Assign) { + for (Expr t : ((Assign) s).targets) { + names(t, b); + } + } else if (s instanceof AugAssign) { + names(((AugAssign) s).target, b); + } else if (s instanceof AnnAssign) { + if (!bareAnnotation(s)) { + names(((AnnAssign) s).target, b); + } + } else if (!(s instanceof ExprStmt) && !(s instanceof Pass)) { + b.addAll(k.bodyNames); + } + otherwise.addAll(b); + } + } + } + constants.removeAll(otherwise); + for (Set r : related.values()) { + r.removeAll(constants); + } + // A subclass in another module that binds a property (or any + // decorated definition, or a descriptor call) over a field demotes + // that field in its whole chain above: the base was planned first + // and its compiled `self.raw` would read the slot past the property. + // Only the names so bound leave the layout; every other field keeps + // its slot. Keyed by simple class name, so a collision only costs a + // fast path. + Map> demoted = SUBCLASS_BINDINGS.get(); + if (demoted != null) { + for (Map.Entry> e : related.entrySet()) { + Set d = demoted.get(e.getKey().def.name); + if (d != null) { + e.getValue().addAll(d); + } + } } boolean noFields = false; for (String st : attrStores) { int dot = st.indexOf('.'); - if (byName.containsKey(st.substring(0, dot))) { + Cls owner = byName.get(st.substring(0, dot)); + if (owner != null) { String a = st.substring(dot + 1); - bodyNames.add(a); + for (Map.Entry> e : related.entrySet()) { + if (ancestorOf(e.getKey(), owner) || ancestorOf(owner, e.getKey())) { + e.getValue().add(a); + } + } // An attribute hook added from outside sees every access. noFields |= "*".equals(a) || FORBIDDEN.contains(a); } @@ -159,7 +2048,9 @@ static Layouts plan(List body, String prefix, Set attrStores) { } else if (s instanceof AugAssign) { names(((AugAssign) s).target, rebound); } else if (s instanceof AnnAssign) { - names(((AnnAssign) s).target, rebound); + if (!bareAnnotation(s)) { + names(((AnnAssign) s).target, rebound); + } } else if (s instanceof For) { names(((For) s).target, rebound); } else if (s instanceof ClassDef) { @@ -170,6 +2061,24 @@ static Layouts plan(List body, String prefix, Set attrStores) { } } Set stored = new LinkedHashSet(); + for (Stmt s : k.def.body) { + if (s instanceof FunctionDef && !((FunctionDef) s).args.names().isEmpty()) { + selfStores(((FunctionDef) s).body, ((FunctionDef) s).args.names().get(0), stored); + } + } + // A method the instance may shadow (`self.default = default`) + // is looked up per call, here and in every class above. + for (Cls a = k.parent; a != null; a = a.parent) { + if (!k.compiled && a.compiled) { + // An analysed class's instances are not the compiled + // class's: they reach its methods generically. + break; + } + a.typable.keySet().removeAll(stored); + a.methods.keySet().removeAll(stored); + a.typable.keySet().removeAll(k.mroNames); + a.methods.keySet().removeAll(k.mroNames); + } for (Stmt s : k.def.body) { if (!(s instanceof FunctionDef)) { continue; @@ -179,25 +2088,52 @@ static Layouts plan(List body, String prefix, Set attrStores) { if (names.isEmpty()) { continue; } - selfStores(f.body, names.get(0), stored); - boolean plain = f.decorators.isEmpty() && !f.isAsync && !f.scope.hasYield && f.args.vararg == null - && f.args.kwarg == null && f.args.kwonly.isEmpty() && defined.get(f.name) == 1 + if (IMPLICIT_CLASS_LEVEL.contains(f.name)) { + // Takes the class, not an instance: no typed receiver, + // and no dispatch on an instance. + continue; + } + if (!decoratedAs(f, "staticmethod") && !decoratedAs(f, "classmethod")) { + l.receiverClass.put(f, k); + } + // Plain but for keyword-only parameters: still one fixed list + // of parameters a call site can bind at build time. + // A field of a base of another module (extendsForeign let + // this def over it): an instance may hold its own value, so + // the method is looked up per call. + boolean inheritedField = k.parent != null && k.parent.allFields.contains(f.name); + boolean plainKw = !stored.contains(f.name) && !inheritedField && f.decorators.isEmpty() && !f.isAsync + && f.args.vararg == null && f.args.kwarg == null && defined.get(f.name) == 1 && !rebound.contains(f.name) && !hasFree(f); - if (plain && names.size() <= 8) { + boolean plain = plainKw && f.args.kwonly.isEmpty(); + if (plainKw && names.size() <= MAX_TYPED_PARAMS) { + // Keyword-only parameters follow the positional ones in + // the typed body's list; a call binds them at build time + // (Infer#staticArgs) or goes through the door. k.typable.put(f.name, f); } if (plain && names.size() <= 4) { k.methods.put(f.name, f); l.dispatch.add(f.name + "/" + (names.size() - 1)); + l.dispatchBy.computeIfAbsent(f.name + "/" + (names.size() - 1), x -> new HashSet()).add(k); l.staticNames.put(f, "M_" + k.javaName.substring(prefix.length()) + "_" + Emitter.mangle(f.name)); l.methodClass.put(f, k); } + if (plainKw && names.size() <= 14 && !l.staticNames.containsKey(f)) { + // A static entry with every parameter its own Java one, + // for call sites that bind their arguments at build time + // (Emitter.boundInit). Not dispatched by arity: a + // positional call must not fill a keyword-only parameter. + l.staticNames.put(f, "D_" + k.javaName.substring(prefix.length()) + "_" + Emitter.mangle(f.name)); + l.methodClass.put(f, k); + l.directEntries.add(f); + } } if (k.parent != null) { k.allFields.addAll(k.parent.allFields); } for (String f : stored) { - if (noFields || f.startsWith("__") && f.endsWith("__") || bodyNames.contains(f) || k.allFields.contains(f)) { + if (noFields || f.startsWith("__") && f.endsWith("__") || related.get(k).contains(f) || k.allFields.contains(f)) { continue; } k.fields.add(f); @@ -209,10 +2145,92 @@ static Layouts plan(List body, String prefix, Set attrStores) { } o.add(k); } + // Copied slots: the fields of every compiled class of the MRO + // outside the compiled chain, which its methods (run over this + // instance generically) store and read by name. + for (Cls x : k.mixedFrom) { + for (String f : x.allFields) { + if (noFields || related.get(k).contains(f) || k.allFields.contains(f)) { + continue; + } + k.fields.add(f); + k.allFields.add(f); + l.fieldOwners.computeIfAbsent(f, z -> new ArrayList()).add(k); + } + } } + l.partition(); return l; } + /// The class an analysed class `c` derives from, for the inference: its + /// first base that is a class of this plan or a compiled class of + /// another module, or null. + private static Cls analysedParent(ClassDef c, List body, Map byName, + java.util.function.Function foreignBase) { + Expr b = null; + for (int i = 0; b == null && i < c.bases.size(); i++) { + b = typingBase(c.bases.get(i)) ? null : origin(c.bases.get(i)); + } + if (b == null) { + return null; + } + Cls p = b instanceof Name ? byName.get(((Name) b).id) : null; + if (p == null && foreignBase != null && !(b instanceof Name && moduleClassNamed(body, ((Name) b).id))) { + p = foreignBase.apply(b); + } + return p; + } + + /// Moves every class not compiled from [#classes] to [#analysed], and + /// drops what the emitter would generate for it: its methods' entries, + /// its fields' owners, and its methods' arities. + private void partition() { + for (java.util.Iterator> it = classes.entrySet().iterator(); it.hasNext();) { + Map.Entry e = it.next(); + if (!e.getValue().compiled) { + analysed.put(e.getKey(), e.getValue()); + it.remove(); + } + } + if (analysed.isEmpty()) { + return; + } + Set gone = new HashSet(analysed.values()); + for (Cls k : gone) { + for (Stmt s : k.def.body) { + if (s instanceof FunctionDef) { + staticNames.remove(s); + methodClass.remove(s); + directEntries.remove(s); + receiverClass.remove(s); + } + } + } + for (java.util.Iterator> it = fieldOwners.values().iterator(); it.hasNext();) { + List o = it.next(); + o.removeAll(gone); + if (o.isEmpty()) { + it.remove(); + } + } + for (Map.Entry> e : dispatchBy.entrySet()) { + if (gone.containsAll(e.getValue())) { + dispatch.remove(e.getKey()); + } + } + } + + /// Whether `a` is `k` or one of the compiled classes above it. + private static boolean ancestorOf(Cls a, Cls k) { + for (Cls c = k; c != null; c = c.parent) { + if (c == a) { //NOPMD CompareObjectsWithEquals - identity is meant + return true; + } + } + return false; + } + /// Whether the method uses `super()` or `__class__`, the one way a method /// at the top of a module captures anything: its body becomes a static /// Java method, which can capture nothing. @@ -222,9 +2240,30 @@ private static boolean hasFree(FunctionDef f) { /// The attribute names `self. = ...` stores in `body`, outside /// nested functions and classes. + /// The name `object.__setattr__(self, "name", v)` stores, a plain store + /// past the class's own `__setattr__` (a frozen dataclass's + /// constructor); null for any other statement. + private static String objectSetattr(Stmt s, String self) { + if (!(s instanceof ExprStmt) || !(((ExprStmt) s).value instanceof Call)) { + return null; + } + Call c = (Call) ((ExprStmt) s).value; + if (!(c.func instanceof Attribute) || !"__setattr__".equals(((Attribute) c.func).attr) + || !(((Attribute) c.func).value instanceof Name) || !"object".equals(((Name) ((Attribute) c.func).value).id) + || c.args.size() != 3 || !c.keywords.isEmpty() || !(c.args.get(0) instanceof Name) + || !((Name) c.args.get(0)).id.equals(self) || !(c.args.get(1) instanceof Constant) + || ((Constant) c.args.get(1)).kind != Constant.Kind.STR) { + return null; + } + return ((Constant) c.args.get(1)).text; + } + private static void selfStores(List body, String self, Set out) { for (Stmt s : body) { - if (s instanceof Assign) { + String named = objectSetattr(s, self); + if (named != null) { + out.add(named); + } else if (s instanceof Assign) { for (Expr t : ((Assign) s).targets) { target(t, self, out); } @@ -306,4 +2345,339 @@ static Cls resolver(Cls k, String name) { } return null; } + + /// The constant an instance of exactly `k` finds for `name` through its + /// class: the nearest class body up the chain that binds the name must + /// bind it once, as `name = `, and nothing else. Null when it + /// binds it any other way, or no compiled class binds it at all (the + /// name may then come from a builtin base, a property, a method). + /// The value `k`'s own body binds `name` to, when it binds it exactly + /// once, as a plain `name = value` and nothing else, and no other + /// statement of the body could bind it unseen. Null otherwise. + static Expr onceValue(Cls k, String name) { + if (!k.bodyNames.contains(name)) { + Map t = TRAILING.get(k.def); + return t == null ? null : t.get(name); + } + if (trailing(k.def).containsKey(name)) { + // Bound in the body and again right after it. + return null; + } + Expr found = null; + int binds = 0; + for (Stmt s : k.def.body) { + Set b = new HashSet(); + if (s instanceof Assign) { + for (Expr t : ((Assign) s).targets) { + names(t, b); + } + } else if (s instanceof FunctionDef) { + b.add(((FunctionDef) s).name); + } else if (s instanceof ClassDef) { + b.add(((ClassDef) s).name); + } else if (s instanceof AugAssign) { + names(((AugAssign) s).target, b); + } else if (s instanceof AnnAssign) { + names(((AnnAssign) s).target, b); + } else if (!(s instanceof ExprStmt) && !(s instanceof Pass)) { + return null; + } + if (!b.contains(name)) { + continue; + } + binds++; + Assign a = s instanceof Assign ? (Assign) s : null; + found = a != null && a.targets.size() == 1 && a.targets.get(0) instanceof Name ? a.value : null; + } + return binds == 1 ? found : null; + } + + /// Per class, the module-level `C.X = value` statements that directly + /// follow its class statement (only such statements in between), for a + /// name the class body does not bind and the run binds once: the class + /// attributes defined right after the class, as the enumeration members + /// EnumLowering writes are. Keyed by identity, filled by [#scanTrailing]. + private static final Map> TRAILING = java.util.Collections.synchronizedMap( + new java.util.IdentityHashMap>()); + /// The statements [#TRAILING] holds: no other store of their name. + private static final Set TRAILING_STORES = java.util.Collections.synchronizedSet( + java.util.Collections.newSetFromMap(new java.util.IdentityHashMap())); + + /// Records the once-bound trailing class attributes of module `m`. + static void scanTrailing(com.codename1.python.transpiler.ast.Node.Module m) { //NOPMD UnnecessaryFullyQualifiedName - java.lang.Module is ambiguous + List body = m.body; + for (int i = 0; i < body.size(); i++) { + if (!(body.get(i) instanceof ClassDef)) { + continue; + } + ClassDef c = (ClassDef) body.get(i); + Map found = new LinkedHashMap(); + Map at = new HashMap(); + Set twice = new HashSet(); + for (int j = i + 1; j < body.size(); j++) { + Stmt s = body.get(j); + if (!(s instanceof Assign) || ((Assign) s).targets.size() != 1 + || !(((Assign) s).targets.get(0) instanceof Attribute)) { + break; + } + Attribute t = (Attribute) ((Assign) s).targets.get(0); + if (!(t.value instanceof Name) || !((Name) t.value).id.equals(c.name)) { + break; + } + if (found.containsKey(t.attr) || t.attr.startsWith("__")) { + twice.add(t.attr); + } + found.put(t.attr, ((Assign) s).value); + at.put(t.attr, s); + } + for (String n : twice) { + found.remove(n); + at.remove(n); + } + if (!found.isEmpty()) { + TRAILING.put(c, found); + TRAILING_STORES.addAll(at.values()); + } + } + } + + /// Whether `s` is one of the trailing class attribute stores + /// ([#scanTrailing]). + static boolean trailingStore(Object s) { + return TRAILING_STORES.contains(s); + } + + /// The trailing class attributes of `c` ([#scanTrailing]), never null. + static Map trailing(ClassDef c) { + Map t = TRAILING.get(c); + return t == null ? java.util.Collections.emptyMap() : t; + } + + static Constant classConstant(Cls k, String name) { + Cls c = k; + while (c != null && !c.bodyNames.contains(name)) { + c = c.parent; + } + if (c == null) { + return null; + } + Constant found = null; + int binds = 0; + for (Stmt s : c.def.body) { + Set b = new HashSet(); + if (s instanceof Assign) { + for (Expr t : ((Assign) s).targets) { + names(t, b); + } + } else if (s instanceof FunctionDef) { + b.add(((FunctionDef) s).name); + } else if (s instanceof ClassDef) { + b.add(((ClassDef) s).name); + } else if (s instanceof AugAssign) { + names(((AugAssign) s).target, b); + } else if (s instanceof AnnAssign) { + names(((AnnAssign) s).target, b); + } else if (!(s instanceof ExprStmt) && !(s instanceof Pass)) { + // A loop, an import, a with: what it binds is not read here. + return null; + } + if (!b.contains(name)) { + continue; + } + binds++; + Assign a = s instanceof Assign ? (Assign) s : null; + if (a != null && a.targets.size() == 1 && a.targets.get(0) instanceof Name && a.value instanceof Constant) { + found = (Constant) a.value; + } + } + return binds == 1 ? found : null; + } + + /// Judges a class whose compiled parent is `parent` (or none) and whose + /// other bases are the compiled classes `extras`: answers why it cannot + /// take a layout, or null, having put the names the merged classes bind + /// into `names` (kept out of the fields) and the classes of the C3 MRO + /// outside the compiled chain into `merged`. Every name the chain binds + /// must still resolve in the chain -- no merged class binds a name a + /// chain class after it in the MRO binds -- so typed code, which + /// resolves along the Java chain, agrees with the MRO; a merged class's + /// own names are reached generically through the MRO, and its methods + /// read its fields by name, which the subclass holds as copied slots. + static String mergeExtras(Set own, Cls parent, List extras, Set superNames, Set names, + List merged, Set inherited) { + List bs = new ArrayList(); + if (parent != null) { + bs.add(parent); + } + bs.addAll(extras); + return mergeExtrasOrdered(own, parent, extras, bs, superNames, names, merged, inherited); + } + + /// The bases of a class in source order: `first`, then `extras`. + static List srcOrder(Cls first, List extras) { + List bs = new ArrayList(); + bs.add(first); + bs.addAll(extras); + return bs; + } + + /// [#mergeExtras] with the Java parent `parent` taken from anywhere in + /// the source-ordered bases `bs`, whose C3 MRO is the one judged. + static String mergeExtrasOrdered(Set own, Cls parent, List extras, List bs, Set superNames, + Set names, List merged, Set inherited) { + List mro = c3(bs); + if (mro == null) { + return "its bases have no consistent MRO"; + } + Set chain = new HashSet(); + for (Cls a = parent; a != null; a = a.parent) { + chain.add(a); + } + for (int i = 0; i < mro.size(); i++) { + Cls x = mro.get(i); + if (chain.contains(x)) { + continue; + } + String xn = x.def.name; + // requests' `JSONDecodeError(InvalidJSONError, json.JSONDecodeError)`: + // an extra base made directly over builtin exceptions merges + // into a chain that derives from a builtin exception too. An + // exception instance keeps args and the like in its attribute + // table whatever its builtin, so the extra builtins add nothing + // to the layout; the type's MRO keeps them for `except` and + // `isinstance`, and the runtime judges them the same way + // (PyType.neutralExtraBases). + boolean excMixin = parent != null && parent.exception && x.compiled && x.builtin == null && x.parent == null + && !x.excBases.isEmpty(); + if (!excMixin && (!x.compiled || x.builtin != null || x.exception || !x.excBases.isEmpty())) { + return "extra base " + xn + " has a builtin base or no layout"; + } + for (String nm : x.bodyNames) { + if ("__setattr__".equals(nm) || "__getattribute__".equals(nm) || "__delattr__".equals(nm) + || "__getattr__".equals(nm) || "__slots__".equals(nm) && !emptySlots(x.def)) { + return "extra base " + xn + " binds " + nm; + } + // Shadowed: a class before x in the MRO binds the name (the + // class itself, a chain class or an earlier merged class). + boolean shadowed = own.contains(nm); + for (int j = 0; j < i && !shadowed; j++) { + shadowed = mro.get(j).bodyNames.contains(nm); + } + // A name a super() call reads may be bound here too: a + // super() call is resolved statically only where every + // class below its own has one base (Infer.superTarget), and + // this class has two, so every one that can reach x's + // binding runs through the MRO of type(self). Likewise an + // unshadowed __init__ is x's: the class then binds no def of + // its own for it (inherited below), so construction takes + // the MRO's. Only __new__, which makes the Java instance, + // must come from the chain. + if (!shadowed && "__new__".equals(nm) && !abstractIn(x.def, nm)) { + return "extra base " + xn + " binds " + nm + ", which no class before it in the MRO binds"; + } + if (!shadowed && !"__slots__".equals(nm)) { + // The MRO finds x's binding: the class binds the name + // as far as typed code is concerned, with no def of + // its own, so every use of it on an instance goes + // through the MRO -- also where a chain class after x + // binds it, whose typed dispatch the class withdraws. + inherited.add(nm); + } + } + names.addAll(x.bodyNames); + merged.add(x); + } + return null; + } + + /// The C3 linearization of a class with bases `bs`, the class itself + /// left out, or null when the bases admit none. + static List c3(List bs) { + List> seqs = new ArrayList>(); + for (Cls b : bs) { + List m = new ArrayList(); + m.add(b); + List up = c3(b.bases); + if (up == null) { + return null; + } + m.addAll(up); + seqs.add(m); + } + seqs.add(new ArrayList(bs)); + List r = new ArrayList(); + while (true) { + Cls next = null; + for (List sq : seqs) { + if (sq.isEmpty()) { + continue; + } + Cls h = sq.get(0); + boolean inTail = false; + for (List o : seqs) { + if (o.indexOf(h) > 0) { + inTail = true; + break; + } + } + if (!inTail) { + next = h; + break; + } + } + if (next == null) { + for (List sq : seqs) { + if (!sq.isEmpty()) { + return null; + } + } + return r; + } + r.add(next); + for (List sq : seqs) { + if (!sq.isEmpty() && sq.get(0) == next) { //NOPMD CompareObjectsWithEquals - identity is meant + sq.remove(0); + } + } + } + } + + /// Whether `def` binds `__slots__` only to an empty tuple or list. + private static boolean emptySlots(ClassDef def) { + for (Stmt s : def.body) { + if (s instanceof Assign && ((Assign) s).targets.size() == 1 && ((Assign) s).targets.get(0) instanceof Name + && "__slots__".equals(((Name) ((Assign) s).targets.get(0)).id)) { + Expr v = ((Assign) s).value; + if (!(v instanceof TupleExpr && ((TupleExpr) v).elts.isEmpty() || v instanceof ListExpr && ((ListExpr) v).elts.isEmpty())) { + return false; + } + } + } + return true; + } + + /// Whether `def` defines `name` as an `@abstractmethod` (no instance + /// reaches such a method: a concrete class overrides it earlier). + private static boolean abstractIn(ClassDef def, String name) { + for (Stmt s : def.body) { + if (s instanceof FunctionDef && name.equals(((FunctionDef) s).name)) { + boolean abs = false; + for (Expr d : ((FunctionDef) s).decorators) { + String dn = d instanceof Name ? ((Name) d).id : d instanceof Attribute ? ((Attribute) d).attr : null; + abs |= "abstractmethod".equals(dn); + } + return abs; + } + } + return false; + } + + private static boolean decoratedAs(FunctionDef f, String name) { + for (Expr d : f.decorators) { + if (d instanceof Name && name.equals(((Name) d).id)) { + return true; + } + } + return false; + } } diff --git a/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/LiteralAttrStore.java b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/LiteralAttrStore.java new file mode 100644 index 00000000000..0a52fdd6a24 --- /dev/null +++ b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/LiteralAttrStore.java @@ -0,0 +1,447 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.python.transpiler.codegen; + +import com.codename1.python.transpiler.ast.Node; +import com.codename1.python.transpiler.ast.Node.Assign; +import com.codename1.python.transpiler.ast.Node.Attribute; +import com.codename1.python.transpiler.ast.Node.Call; +import com.codename1.python.transpiler.ast.Node.ClassDef; +import com.codename1.python.transpiler.ast.Node.Constant; +import com.codename1.python.transpiler.ast.Node.Expr; +import com.codename1.python.transpiler.ast.Node.ExprStmt; +import com.codename1.python.transpiler.ast.Node.FunctionDef; +import com.codename1.python.transpiler.ast.Node.Name; +import com.codename1.python.transpiler.ast.Node.Stmt; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/// `setattr(obj, axis.tagname, value)` where every class of the program +/// binds `tagname` in its body to a string literal, and nothing anywhere +/// stores, deletes or otherwise binds it: the name stored is a constant of +/// `axis`'s class. Each class binding the attribute gets a method +/// `_cn1_set_tagname(self, target, value)` storing `target.`, +/// and the call becomes `axis._cn1_set_tagname(obj, value)`: a method call +/// picks the class's own store, as reading the attribute picked its own +/// name, with no name looked up at run time. openpyxl's +/// `PlotArea.to_tree` stores each chart axis under its axis's tag name. +/// +/// Only an attribute read whose every binding is such a literal qualifies: +/// a class binding it any other way, an instance store of it (`x.tagname = +/// ...`, `del x.tagname`, `setattr(x, "tagname", ...)`) or a literal that +/// is not an identifier leaves every call as it is. +public final class LiteralAttrStore { + private static final String PREFIX = "_cn1_set_"; + /// The classes whose binding of the attribute is a property that only + /// raises, with that property; one rewrite at a time. + private static final ThreadLocal> RAISING = new ThreadLocal>(); + + private LiteralAttrStore() { + } + + public static void rewrite(Map trees) { + rewrite(trees, java.util.Collections.emptyList()); + } + + /// @param library the bundled standard library and site modules the + /// program will import, which are added after this pass runs: + /// they are only scanned, so a store of the attribute there + /// (or a class binding it otherwise) disqualifies it as one in + /// the program would + public static void rewrite(Map trees, java.util.Collection library) { + // The attribute names a setattr reads its name from. + final Set wanted = new HashSet(); + for (Node.Module m : trees.values()) { + walk(m, new Infer.Visit() { + @Override + public void on(Object o) { + String a = target(o); + if (a != null) { + wanted.add(a); + } + walk(o, this); + } + }); + } + if (wanted.isEmpty()) { + return; + } + // Each wanted attribute's class-body literals; a bad binding + // anywhere disqualifies it. + final Set bad = new HashSet(); + final Map raising = new HashMap(); + RAISING.set(raising); + final Map> literals = new HashMap>(); + for (Node.Module m : library) { + walk(m, new Infer.Visit() { + @Override + public void on(Object o) { + if (o instanceof ClassDef) { + // No store method is added to a library class, so + // any binding of the attribute there is a bad one. + Map> none = new HashMap>(); + classBody((ClassDef) o, wanted, bad, none); + FunctionDef r = raising.remove((ClassDef) o); + if (r != null) { + bad.add(r.name); + } + for (Map l : none.values()) { + bad.addAll(l.keySet()); + } + } else { + stores(o, wanted, bad); + } + walk(o, this); + } + }); + } + for (Node.Module m : trees.values()) { + walk(m, new Infer.Visit() { + @Override + public void on(Object o) { + if (o instanceof ClassDef) { + classBody((ClassDef) o, wanted, bad, literals); + } else { + stores(o, wanted, bad); + } + walk(o, this); + } + }); + } + wanted.removeAll(bad); + if (wanted.isEmpty()) { + return; + } + // A class named as a later base (openpyxl's `_3DBase` beside + // `_BarChartBase`) takes no store: a method a mixin binds and the + // first base's chain does not costs every chart class its layout. + // Only where each class naming it as a base binds the attribute + // itself, so every subclass instance has its own store; an + // instance of the mixin itself, an abstract base, has none. + Map> byBase = new HashMap>(); + final Set later = new HashSet(); + for (ClassDef c : allClasses(trees)) { + for (int i = 0; i < c.bases.size(); i++) { + Expr b = c.bases.get(i); + String n = b instanceof Name ? ((Name) b).id : b instanceof Attribute ? ((Attribute) b).attr : null; + if (n == null) { + continue; + } + if (i > 0) { + later.add(n); + } + List l = byBase.get(n); + if (l == null) { + l = new ArrayList(); + byBase.put(n, l); + } + l.add(c); + } + } + for (java.util.Iterator>> it = literals.entrySet().iterator(); it.hasNext();) { + Map.Entry> e = it.next(); + if (!later.contains(e.getKey().name)) { + continue; + } + it.remove(); + List subs = byBase.get(e.getKey().name); + for (String a : e.getValue().keySet()) { + for (ClassDef sc : subs == null ? new ArrayList() : subs) { + Map own = literals.get(sc); + if (own == null || !own.containsKey(a)) { + wanted.remove(a); + } + } + } + } + if (wanted.isEmpty()) { + return; + } + for (Map.Entry> e : literals.entrySet()) { + for (Map.Entry l : e.getValue().entrySet()) { + if (wanted.contains(l.getKey())) { + ClassDef c = e.getKey(); + FunctionDef f = ConstArgSpecialize.parseMethod("def " + PREFIX + l.getKey() + + "(self, target, value):\n target." + l.getValue() + " = value\n", + Math.max(c.line, 1), "<" + PREFIX + l.getKey() + ">"); + c.body.add(f); + } + } + } + for (Map.Entry e : raising.entrySet()) { + FunctionDef p = e.getValue(); + if (wanted.contains(p.name)) { + FunctionDef f = ConstArgSpecialize.parseMethod("def " + PREFIX + p.name + + "(self, target, value):\n pass\n", Math.max(p.line, 1), "<" + PREFIX + p.name + ">"); + f.body.clear(); + f.body.addAll(p.body); + e.getKey().body.add(f); + } + } + RAISING.remove(); + for (Node.Module m : trees.values()) { + replace(m.body, wanted); + } + } + + /// Walks the children of `o`, entering nested statement lists. + private static void walk(Object o, Infer.Visit v) { + Infer.children(o, v); + } + + private static List allClasses(Map trees) { + final List out = new ArrayList(); + for (Node.Module m : trees.values()) { + walk(m, new Infer.Visit() { + @Override + public void on(Object o) { + if (o instanceof ClassDef) { + out.add((ClassDef) o); + } + walk(o, this); + } + }); + } + return out; + } + + /// The attribute `setattr(x, y., v)` reads its name from. + private static String target(Object o) { + if (!(o instanceof Call)) { + return null; + } + Call c = (Call) o; + if (!(c.func instanceof Name) || !"setattr".equals(((Name) c.func).id) || c.args.size() != 3 + || !c.keywords.isEmpty() || !(c.args.get(1) instanceof Attribute)) { + return null; + } + return ((Attribute) c.args.get(1)).attr; + } + + private static void classBody(ClassDef c, Set wanted, Set bad, + Map> literals) { + for (Stmt s : c.body) { + for (String a : wanted) { + if (s instanceof Assign && ((Assign) s).targets.size() == 1 + && ((Assign) s).targets.get(0) instanceof Name && a.equals(((Name) ((Assign) s).targets.get(0)).id)) { + Expr v = ((Assign) s).value; + Map mine = literals.get(c); + if (v instanceof Constant && ((Constant) v).kind == Constant.Kind.STR && identifier(((Constant) v).text) + && (mine == null || !mine.containsKey(a))) { + if (mine == null) { + mine = new HashMap(); + literals.put(c, mine); + } + mine.put(a, ((Constant) v).text); + } else { + bad.add(a); + } + } else if (raisingProperty(s, a)) { + // openpyxl's abstract `tagname` property: the store + // raises what reading the name raised. + Map mine = RAISING.get(); + mine.put(c, (FunctionDef) s); + } else if (binds(s, a)) { + bad.add(a); + } + } + } + } + + /// Whether a class-body statement binds `a` other than by a plain + /// literal assignment (a def, an annotated or augmented assignment, an + /// unpacking, an import). + private static boolean binds(Stmt s, final String a) { + if (s instanceof FunctionDef) { + return a.equals(((FunctionDef) s).name); + } + if (s instanceof ClassDef) { + return a.equals(((ClassDef) s).name); + } + if (s instanceof Node.Import || s instanceof Node.ImportFrom) { + return true; + } + if (s instanceof Node.If || s instanceof Node.For || s instanceof Node.While || s instanceof Node.Try + || s instanceof Node.With) { + // A conditional or looped binding: judged by any Name of `a`. + final boolean[] hit = {false}; + Infer.children(s, new Infer.Visit() { + @Override + public void on(Object o) { + if (o instanceof Name && a.equals(((Name) o).id)) { + hit[0] = true; + } else if (!(o instanceof FunctionDef) && !(o instanceof ClassDef)) { + Infer.children(o, this); + } + } + }); + return hit[0]; + } + final boolean[] hit = {false}; + Expr[] targets = s instanceof Assign ? ((Assign) s).targets.toArray(new Expr[0]) + : s instanceof Node.AnnAssign ? new Expr[] {((Node.AnnAssign) s).target} + : s instanceof Node.AugAssign ? new Expr[] {((Node.AugAssign) s).target} + : s instanceof Node.Delete ? ((Node.Delete) s).targets.toArray(new Expr[0]) : new Expr[0]; + for (Expr t : targets) { + if (t instanceof Name) { + hit[0] |= a.equals(((Name) t).id); + } else { + Infer.children(t, new Infer.Visit() { + @Override + public void on(Object o) { + if (o instanceof Name && a.equals(((Name) o).id)) { + hit[0] = true; + } + Infer.children(o, this); + } + }); + } + } + return hit[0]; + } + + /// Marks a wanted attribute stored, deleted or set by a literal name. + private static void stores(Object o, Set wanted, Set bad) { + List targets = new ArrayList(); + if (o instanceof Assign) { + targets.addAll(((Assign) o).targets); + } else if (o instanceof Node.AnnAssign) { + targets.add(((Node.AnnAssign) o).target); + } else if (o instanceof Node.AugAssign) { + targets.add(((Node.AugAssign) o).target); + } else if (o instanceof Node.Delete) { + targets.addAll(((Node.Delete) o).targets); + } else if (o instanceof Node.For) { + targets.add(((Node.For) o).target); + } else if (o instanceof Call && ((Call) o).func instanceof Name && ((Call) o).args.size() >= 2 + && ("setattr".equals(((Name) ((Call) o).func).id) || "delattr".equals(((Name) ((Call) o).func).id)) + && ((Call) o).args.get(1) instanceof Constant && wanted.contains(((Constant) ((Call) o).args.get(1)).text)) { + bad.add(((Constant) ((Call) o).args.get(1)).text); + } + for (Expr t : targets) { + final Set found = new HashSet(); + Infer.Visit v = new Infer.Visit() { + @Override + public void on(Object x) { + if (x instanceof Attribute) { + found.add(((Attribute) x).attr); + } + } + }; + v.on(t); + if (t instanceof Node.TupleExpr || t instanceof Node.ListExpr || t instanceof Node.Starred) { + Infer.children(t, v); + } + for (String f : found) { + if (wanted.contains(f)) { + bad.add(f); + } + } + } + } + + private static void replace(Object o, final Set wanted) { + if (o instanceof List) { + @SuppressWarnings("unchecked") + List l = (List) o; + for (int i = 0; i < l.size(); i++) { + Object x = l.get(i); + if (x instanceof ExprStmt) { + String a = target(((ExprStmt) x).value); + if (a != null && wanted.contains(a)) { + Call old = (Call) ((ExprStmt) x).value; + Call c = new Call(new Attribute(((Attribute) old.args.get(1)).value, PREFIX + a)); + c.args.add(old.args.get(0)); + c.args.add(old.args.get(2)); + c.line = old.line; + c.col = old.col; + c.func.line = old.line; + c.func.col = old.col; + ExprStmt n = new ExprStmt(c); + n.line = ((ExprStmt) x).line; + n.col = ((ExprStmt) x).col; + l.set(i, n); + continue; + } + } + replace(x, wanted); + } + return; + } + if (o instanceof Node) { + final List lists = new ArrayList(); + for (Class k = o.getClass(); k != null && k != Object.class; k = k.getSuperclass()) { + for (java.lang.reflect.Field f : k.getDeclaredFields()) { + if (java.lang.reflect.Modifier.isStatic(f.getModifiers()) || !List.class.isAssignableFrom(f.getType())) { + continue; + } + try { + lists.add(f.get(o)); + } catch (IllegalAccessException e) { + throw new IllegalStateException(e); + } + } + } + for (Object l : lists) { + replace(l, wanted); + } + } + } + + /// `@property def a(self): raise X`, a docstring allowed before it. + private static boolean raisingProperty(Stmt s, String a) { + if (!(s instanceof FunctionDef) || !a.equals(((FunctionDef) s).name)) { + return false; + } + FunctionDef f = (FunctionDef) s; + if (f.decorators.size() != 1 || !(f.decorators.get(0) instanceof Name) + || !"property".equals(((Name) f.decorators.get(0)).id) || f.body.isEmpty()) { + return false; + } + for (int i = 0; i < f.body.size() - 1; i++) { + Stmt b = f.body.get(i); + if (!(b instanceof ExprStmt) || !(((ExprStmt) b).value instanceof Constant)) { + return false; + } + } + return f.body.get(f.body.size() - 1) instanceof Node.Raise; + } + + private static boolean identifier(String s) { + if (s.isEmpty() || !(Character.isLetter(s.charAt(0)) || s.charAt(0) == '_') || s.charAt(0) > 0x7e) { + return false; + } + for (int i = 1; i < s.length(); i++) { + char c = s.charAt(i); + if (c > 0x7e || !(Character.isLetterOrDigit(c) || c == '_')) { + return false; + } + } + return !"None".equals(s) && !"True".equals(s) && !"False".equals(s); + } +} diff --git a/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/Liveness.java b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/Liveness.java new file mode 100644 index 00000000000..f57b9f7f9d1 --- /dev/null +++ b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/Liveness.java @@ -0,0 +1,2060 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.python.transpiler.codegen; + +import com.codename1.python.transpiler.ast.Node.*; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Deque; +import java.util.HashMap; +import java.util.HashSet; +import java.util.IdentityHashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/// Which top-level statements of the program ever matter, before anything +/// else reads it: a module that is imported for one function keeps that +/// function and what it needs, not the module's every definition and every +/// import those definitions would have needed. +/// +/// A top-level statement is *pure* when running it only binds names: +/// a `def` or `class` with no decorator that could register it somewhere, +/// an import of modules that are pure themselves, an assignment of a value +/// built from constants, names and the calls in [#PURE_CALLS]. Anything +/// else is *effectful* and runs whenever its module does. A pure statement +/// is kept only when a name it binds is live -- read by kept code of its +/// module, imported from it by kept code of another, or named by a string +/// where the module may look a name up. Liveness is followed whole-program: +/// the names an import binds lead to the names of the module imported, so +/// one live name of a package keeps the one import that binds it. +/// +/// What can reach a module's names other than by reading them makes the +/// whole module live: the module used as a value (`vars(m)`, `m` passed +/// on), `getattr` on it with a computed name, `globals()`, a star import of +/// it, an import of it by a computed name, and the modules the Java runtime +/// reads (`copyreg`, `io`, `builtins`). Statements are kept or dropped +/// whole, and only at the top level of a module; a kept class keeps its +/// whole body (its methods are left to the inference's reachability). +public final class Liveness { + /// Calls whose result is a value and nothing else. + private static final Set PURE_CALLS = new HashSet(Arrays.asList( + "TypeVar", "ParamSpec", "TypeVarTuple", "NewType", "namedtuple", "NamedTuple", "TypedDict", + "getLogger", "compile", "frozenset", "set", "dict", "list", "tuple", "object", "field", "Field", + "cast", "TypeAliasType", "partial", "ConfigDict", "PropertyInfo", "cached_property", "property", + "staticmethod", "classmethod", "lru_cache", "str", "int", "float", "bool", "bytes", "Struct", + "defaultdict", "OrderedDict", "deque", "ContextVar", "Lock", "RLock", "MappingProxyType", + "frozendict", "Literal", "Union", "Optional", "Annotated", "Sentinel", "sentinel", "range", + "Decimal", "timedelta", "datetime", "date", "time", "Path", "PurePath", "Enum", "IntEnum", + "StrEnum", "Flag", "IntFlag", "auto", "Pattern", "escape", "join", "Event", "Condition", + "Semaphore", "local", "WeakValueDictionary", "WeakKeyDictionary", "WeakSet", "count", "Counter", + "ChainMap", "Template", "Formatter", "TypeAdapter", "Discriminator", "Tag", "Required", + "NotRequired", "ReadOnly", "Unpack", "deprecated", "final", "dataclass", "make_dataclass", + "getenv", "get", "format", "replace", "encode", "decode", "lower", "upper", "split", "strip")); + /// Decorators that wrap or mark what they decorate and register it + /// nowhere. + private static final Set PURE_DECORATORS = new HashSet(Arrays.asList( + "dataclass", "overload", "property", "_cn1_property", "staticmethod", "classmethod", "wraps", "lru_cache", "cache", + "cached_property", "contextmanager", "asynccontextmanager", "runtime_checkable", "final", + "override", "total_ordering", "abstractmethod", "deprecated", "unique", "dataclass_transform", + "setter", "getter", "deleter", "no_type_check", "singledispatch", "functools", "typing", + "typing_extensions", "model_validator", "field_validator", "validator", "root_validator", + "computed_field", "field_serializer", "model_serializer", "type_check_only", "coroutine", + "frozen", "define", "attrs", "attrib", "s", "contextlib", "abc")); + /// The modules the Java runtime imports by name and reads names of. + private static final String[] RUNTIME_MODULES = {"builtins", "copyreg", "io"}; + + private static final class Mod { + final String name; + final boolean pkg; + final List body; + /// Name -> the top-level statements binding it. + final Map> binders = new HashMap>(); + /// Names bound to a module by a top-level import: the import, and + /// the alias it binds. + final Map> importsOf = new HashMap>(); + boolean effects; + boolean importsByName; + final List strings = new ArrayList(); + final List prefixes = new ArrayList(); + /// `"Name": (".module", "Symbol")` and `"Name": ".module"`: the + /// table a module-level `__getattr__` imports a name it does not + /// bind from. + final Map> lazy = new HashMap>(); + /// Holds the module once its strings were all taken as prefixes. + /// Whether its globals are read only by the names of `__all__` + /// (see #indexedByAll); null until asked. + Boolean allIndexed; + boolean allRead; + final Set prefixStrings = new HashSet(); + + Mod(String name, boolean pkg, List body) { + this.name = name; + this.pkg = pkg; + this.body = body; + } + } + + private final Map mods = new LinkedHashMap(); + private final Set live = java.util.Collections.newSetFromMap(new IdentityHashMap()); + private final Set full = java.util.Collections.newSetFromMap(new IdentityHashMap()); + private final Map> names = new IdentityHashMap>(); + private final Set kept = java.util.Collections.newSetFromMap(new IdentityHashMap()); + private final Deque work = new ArrayDeque(); + private final Map homeOf = new IdentityHashMap(); + private boolean distributionsRead; + private static final boolean WHY = System.getProperty("cn1.python.whyLive") != null; + private String cause = "root"; + private static final String WHY_MEMBER = System.getProperty("cn1.python.whyMember"); + /// `-Dcn1.python.whyAttr=name`: where the attribute name was first read. + private static final String WHY_ATTR = System.getProperty("cn1.python.whyAttr"); + /// The module being visited, for #WHY_ATTR. + private String visiting = ""; + /// Every attribute name live code reads (and every identifier of its + /// strings, and what the Java runtime looks up by name): a method of a + /// kept class whose name is in none of them is never called. + private final Set attrs = new HashSet(); + /// Method name -> the methods of kept classes waiting for it. + private final Map> waiting = new HashMap>(); + private final Set members = java.util.Collections.newSetFromMap(new IdentityHashMap()); + private final Set classes = java.util.Collections.newSetFromMap(new IdentityHashMap()); + /// Whether methods are pruned: only when the runtime's names are known. + private boolean pruneMembers; + + private Liveness() { + } + + /// Cuts every module body after a top-level `import` of a module that + /// cannot exist when the program runs: one whose top-level package is + /// not in `known` (compiled into the program or written in Java) and + /// is not named anywhere in the runtime. That import raises + /// ModuleNotFoundError where it stands, so nothing after it ever runs; + /// the import itself stays, and raises as it did. bs4's html5lib + /// builder imports html5lib, which MarkItDown does not ship: bs4 + /// catches the error, and the module's classes were analysed for + /// nothing. A program that adds to `sys.modules` itself could make + /// such an import succeed, so a name is only taken as missing when no + /// string of a module that writes there names it, and nothing is cut + /// when one of + /// those additions is keyed by anything but a name or a constant. + public static void truncateDoomed(List> bodies, Set known, Set runtimeNames) { + Set strings = new HashSet(); + for (List body : bodies) { + boolean[] w = {false}; + boolean[] any = {false}; + for (Stmt s : body) { + sysModulesWrite(s, w); + anyModulesWrite(s, any); + } + if (w[0]) { + return; + } + if (any[0]) { + for (Stmt s : body) { + stringTokens(s, strings); + } + } + } + known = new HashSet(known); + known.addAll(strings); + for (List body : bodies) { + for (int i = 0; i < body.size(); i++) { + Stmt s = body.get(i); + boolean doomed = false; + if (s instanceof Import) { + for (Alias a : ((Import) s).names) { + doomed |= missing(a.name, known, runtimeNames); + } + } else if (s instanceof ImportFrom && ((ImportFrom) s).level == 0 && ((ImportFrom) s).module != null) { + doomed = missing(((ImportFrom) s).module, known, runtimeNames); + } + if (doomed) { + body.subList(i + 1, body.size()).clear(); + break; + } + } + } + } + + private static boolean missing(String module, Set known, Set runtimeNames) { + int dot = module.indexOf('.'); + String top = dot < 0 ? module : module.substring(0, dot); + return !known.contains(top) && !runtimeNames.contains(top) && !"java".equals(top) + && !"__future__".equals(top); + } + + /// Sets `w[0]` when `o` stores into, deletes from or adds to some + /// `x.modules` (taken as `sys.modules`; a plain read does not count). + private static void sysModulesWrite(Object o, boolean[] w) { + if (w[0]) { + return; + } + List targets = o instanceof Assign ? ((Assign) o).targets + : o instanceof AugAssign ? java.util.Collections.singletonList(((AugAssign) o).target) + : o instanceof Delete ? ((Delete) o).targets : java.util.Collections.emptyList(); + for (Expr t : targets) { + if (t instanceof Subscript && modulesAttr(((Subscript) t).value) + && !(((Subscript) t).index instanceof Name || ((Subscript) t).index instanceof Constant)) { + w[0] = true; + return; + } + } + if (o instanceof Call && ((Call) o).func instanceof Attribute + && modulesAttr(((Attribute) ((Call) o).func).value) + && ("update".equals(((Attribute) ((Call) o).func).attr) + || "__setitem__".equals(((Attribute) ((Call) o).func).attr) + || "setdefault".equals(((Attribute) ((Call) o).func).attr) + && !((Call) o).args.isEmpty() && !(((Call) o).args.get(0) instanceof Name + || ((Call) o).args.get(0) instanceof Constant))) { + w[0] = true; + return; + } + Infer.children(o, x -> sysModulesWrite(x, w)); + } + + /// Adds to `out` every top-level package name a string constant under + /// `o` could stand for: the run of identifier characters up to its + /// first dot. + private static void stringTokens(Object o, Set out) { + if (o instanceof Constant && ((Constant) o).kind == Constant.Kind.STR) { + String t = ((Constant) o).text; + int start = -1; + for (int i = 0; i <= t.length(); i++) { + char c = i < t.length() ? t.charAt(i) : ' '; + boolean id = c == '_' || c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9'; + if (id && start < 0) { + start = i; + } else if (!id && start >= 0) { + out.add(t.substring(start, i)); + start = -1; + } + } + return; + } + Infer.children(o, x -> stringTokens(x, out)); + } + + /// Sets `w[0]` when `o` writes `x.modules` in any way at all. + private static void anyModulesWrite(Object o, boolean[] w) { + if (w[0]) { + return; + } + List targets = o instanceof Assign ? ((Assign) o).targets + : o instanceof Delete ? ((Delete) o).targets : java.util.Collections.emptyList(); + for (Expr t : targets) { + if (t instanceof Subscript && modulesAttr(((Subscript) t).value)) { + w[0] = true; + return; + } + } + if (o instanceof Call && ((Call) o).func instanceof Attribute + && modulesAttr(((Attribute) ((Call) o).func).value)) { + w[0] = true; + return; + } + Infer.children(o, x -> anyModulesWrite(x, w)); + } + + private static boolean modulesAttr(Expr e) { + return e instanceof Attribute && "modules".equals(((Attribute) e).attr); + } + + /// Prunes `trees` (module name to body, and whether it is a package) + /// to what module `main` reaches, in place. Answers the modules that + /// never run; their bodies are left alone. + public static Set prune(Map> bodies, Set packages, String main, + Collection keep, Set runtimeNames) { + Liveness l = new Liveness(); + l.pruneMembers = runtimeNames != null; + if (runtimeNames != null) { + l.attrs.addAll(runtimeNames); + } + for (Map.Entry> e : bodies.entrySet()) { + l.mods.put(e.getKey(), new Mod(e.getKey(), packages.contains(e.getKey()), e.getValue())); + } + for (Mod m : l.mods.values()) { + for (Stmt s : m.body) { + l.homeOf.put(s, m); + l.bind(m, s, s); + } + if (m.binders.containsKey("__getattr__")) { + for (Stmt s : m.body) { + lazyTables(s, m); + } + } + } + l.effects(); + l.full(l.mods.get(main)); + for (String r : RUNTIME_MODULES) { + l.full(l.mods.get(r)); + } + for (Mod m : l.mods.values()) { + if (usesJava(m)) { + // Its classes are named by the generated Java interop. + l.full(m); + } + } + for (String k : keep) { + for (int dot = k.lastIndexOf('.'); dot > 0; dot = k.lastIndexOf('.', dot - 1)) { + Mod m = l.mods.get(k.substring(0, dot)); + if (m != null) { + String rest = k.substring(dot + 1); + int d2 = rest.indexOf('.'); + l.name(m, d2 < 0 ? rest : rest.substring(0, d2)); + break; + } + } + } + l.drain(); + boolean more = true; + while (more) { + // Both run every round: each can make the other find more. + more = l.entryPoints(); + more = l.trimImports(false) || more; + l.drain(); + } + l.trimImports(true); + Set dead = new HashSet(); + for (Mod m : l.mods.values()) { + if (!l.live.contains(m)) { + dead.add(m.name); + } else if (!l.full.contains(m)) { + m.body.removeIf(s -> !l.kept.contains(s)); + l.replaceImports(m.body); + } + } + if (WHY_MEMBER != null) { + for (ClassDef c : l.classes) { + if (WHY_MEMBER.contains("," + c.name + ",")) { + System.err.println("class kept " + c.name + ":" + c.line); + } + } + } + if (l.pruneMembers) { + for (ClassDef c : l.classes) { + c.body.removeIf(s -> s instanceof FunctionDef && prunable((FunctionDef) s) && !l.members.contains(s)); + if (c.body.isEmpty()) { + c.body.add(new Pass()); + } + } + } + if (System.getProperty("cn1.python.whyLive") != null) { + System.err.println("liveness: " + l.live.size() + " of " + l.mods.size() + " modules, " + + l.kept.size() + " statements kept"); + } + return dead; + } + + /// Reads the lazy export tables of a module with a `__getattr__` (the + /// dict literals with string keys outside its functions). + private static void lazyTables(Object o, Mod m) { + if (o instanceof FunctionDef || o instanceof ClassDef) { + return; + } + if (o instanceof DictExpr) { + DictExpr d = (DictExpr) o; + for (int i = 0; i < d.keys.size(); i++) { + Expr k = d.keys.get(i); + Expr v = d.values.get(i); + if (!isStr(k)) { + continue; + } + String[] target = null; + if (isStr(v)) { + target = new String[] {((Constant) v).text}; + } else if (v instanceof TupleExpr && !((TupleExpr) v).elts.isEmpty()) { + List es = ((TupleExpr) v).elts; + target = new String[es.size()]; + for (int j = 0; j < es.size(); j++) { + target[j] = isStr(es.get(j)) ? ((Constant) es.get(j)).text : null; + } + } + if (target != null && target[0] != null) { + List l = m.lazy.get(((Constant) k).text); + if (l == null) { + l = new ArrayList(); + m.lazy.put(((Constant) k).text, l); + } + l.add(target); + } + } + } + Infer.children(o, c -> lazyTables(c, m)); + } + + /// Decorators a method may carry and still be found by its name only. + private static final Set BY_NAME = new HashSet(Arrays.asList( + "property", "_cn1_property", "cached_property", "staticmethod", "classmethod", "overload", "override", + "abstractmethod", "setter", "getter", "deleter", "final", "wraps", "lru_cache", "cache", + "contextmanager", "asynccontextmanager", "deprecated")); + + /// Whether a method is reached only through its name: no dunder (the + /// runtime calls those by protocol), and no decorator that may hand it + /// on (a validator, a registration). + static boolean prunable(FunctionDef f) { + if (f.name.startsWith("__") && f.name.endsWith("__")) { + return false; + } + for (Expr d : f.decorators) { + String last = lastName(d instanceof Call ? ((Call) d).func : d); + if (last == null || !BY_NAME.contains(last)) { + return false; + } + } + return true; + } + + /// Method name prefixes live code may match names against: what it + /// passes to `startswith`, and the constant start of a name it formats + /// (`"test"`, `"visit_" + kind`, `f"_assert_{t}"`). + private final Set namePrefixes = new HashSet(); + + private void prefix(String p) { + String id = leadingIdentifier(p); + if (id.length() < p.length() && p.charAt(id.length()) != '%' && p.charAt(id.length()) != '{') { + // A character no identifier holds follows (`f"to-unicode-{n}"`): + // nothing the string starts can be a method name. Only a `%` + // directive or a `{` field can still add identifier characters. + return; + } + if (id.length() < 2 || !namePrefixes.add(id)) { + return; + } + if (WHY_ATTR != null && WHY_ATTR.startsWith(id)) { + System.err.println("prefix " + id + " <- " + cause + " in " + visiting); + } + for (String n : new ArrayList(waiting.keySet())) { + if (n.startsWith(id)) { + wake(waiting.remove(n)); + } + } + } + + private static String heldName(Expr a) { + return a instanceof Name ? ((Name) a).id : ((Attribute) a).attr; + } + + /// Takes as prefixes the strings stored under `held`: `held = "test"`, + /// `self.held = ...`, `held: str = ...`, a tuple of them included. + private void storedStrings(Object o, String held) { + if (o instanceof Assign) { + for (Expr t : ((Assign) o).targets) { + if (held.equals(boundName(t))) { + allStrings(((Assign) o).value); + } + } + } else if (o instanceof AnnAssign && ((AnnAssign) o).value != null + && held.equals(boundName(((AnnAssign) o).target))) { + allStrings(((AnnAssign) o).value); + } + Infer.children(o, c -> storedStrings(c, held)); + } + + private static String boundName(Expr t) { + return t instanceof Name ? ((Name) t).id : t instanceof Attribute ? ((Attribute) t).attr : null; + } + + private void allStrings(Object o) { + if (o instanceof Constant && ((Constant) o).kind == Constant.Kind.STR) { + prefix(((Constant) o).text); + } + Infer.children(o, this::allStrings); + } + + private static String leadingIdentifier(String p) { + int i = 0; + while (i < p.length() && (p.charAt(i) == '_' || Character.isLetterOrDigit(p.charAt(i)))) { + i++; + } + return p.substring(0, i); + } + + private boolean byPrefix(String n) { + for (String p : namePrefixes) { + if (n.startsWith(p)) { + return true; + } + } + return false; + } + + /// A method named bare in its own class body (`x = property(_get)`, + /// `@_get.setter`) is read the way an attribute is. A name read + /// anywhere else is a variable, and keeps no method of that name. + private void bareNames(Object o) { + if (o instanceof Name) { + attr(((Name) o).id); + } else if (!(o instanceof FunctionDef) && !(o instanceof ClassDef) && !(o instanceof Lambda)) { + Infer.children(o, this::bareNames); + } + } + + private void attr(String n) { + if (!attrs.add(n)) { + return; + } + if (WHY_ATTR != null && WHY_ATTR.equals(n)) { + System.err.println("attr " + n + " <- " + cause + " in " + visiting); + } + wake(waiting.remove(n)); + } + + private void wake(List ws) { + if (ws == null) { + return; + } + for (Object[] w : ws) { + Mod m = (Mod) w[0]; + FunctionDef f = (FunctionDef) w[1]; + @SuppressWarnings("unchecked") + Map local = (Map) w[2]; + if (members.add(f)) { + if (WHY_MEMBER != null && WHY_MEMBER.equals(m.name)) { + System.err.println("member " + f.name + " of " + m.name + ":" + f.line); + } + work.add(() -> { + localImports(m, f, local, false); + visit(m, f, local); + }); + } + } + } + + private static boolean usesJava(Mod m) { + for (Stmt s : m.body) { + if (s instanceof ImportFrom && ((ImportFrom) s).module != null + && ("java".equals(((ImportFrom) s).module) || ((ImportFrom) s).module.startsWith("java."))) { + return true; + } + if (s instanceof Import) { + for (Alias a : ((Import) s).names) { + if ("java".equals(a.name) || a.name.startsWith("java.")) { + return true; + } + } + } + } + return false; + } + + /// Takes the names nothing reads out of each kept top-level + /// `from m import ...`: the statement imports every name it lists, so + /// a name left in must be one `m` keeps. One kept only for running its + /// module keeps its first name. Answers whether a name became live, + /// which needs another drain. + private boolean trimImports(boolean apply) { + boolean more = false; + for (Mod m : mods.values()) { + if (!live.contains(m) || full.contains(m)) { + continue; + } + for (Stmt s : m.body) { + if (kept.contains(s)) { + more |= trim(m, s, apply); + } + } + } + return more; + } + + /// Imports kept only for running their module, as `import x as _`. + private final Map replacements = new IdentityHashMap(); + + private void replaceImports(List b) { + for (int i = 0; i < b.size(); i++) { + Stmt s = b.get(i); + Stmt r = replacements.get(s); + if (r != null) { + b.set(i, r); + } else if (s instanceof If) { + replaceImports(((If) s).body); + replaceImports(((If) s).orelse); + } else if (s instanceof Try) { + replaceImports(((Try) s).body); + for (ExceptHandler h : ((Try) s).handlers) { + replaceImports(h.body); + } + replaceImports(((Try) s).orelse); + replaceImports(((Try) s).finalbody); + } + } + } + + /// With `apply` false only makes sure each import keeps a name, and + /// answers whether that made one live; with it true, once liveness + /// settled, takes the dead names out. + private boolean trim(Mod m, Stmt s, boolean apply) { + boolean more = false; + if (s instanceof If) { + for (Stmt x : ((If) s).body) { + more |= trim(m, x, apply); + } + for (Stmt x : ((If) s).orelse) { + more |= trim(m, x, apply); + } + } else if (s instanceof Try) { + for (Stmt x : ((Try) s).body) { + more |= trim(m, x, apply); + } + for (ExceptHandler h : ((Try) s).handlers) { + for (Stmt x : h.body) { + more |= trim(m, x, apply); + } + } + for (Stmt x : ((Try) s).orelse) { + more |= trim(m, x, apply); + } + } else if (s instanceof ImportFrom && !"__future__".equals(((ImportFrom) s).module)) { + ImportFrom f = (ImportFrom) s; + Set ns = names.get(m); + List keepNames = new ArrayList(); + for (Alias a : f.names) { + if ("*".equals(a.name) || ns.contains(a.asname != null ? a.asname : a.name)) { + keepNames.add(a); + } + } + if (keepNames.isEmpty() && !f.names.isEmpty()) { + String base = absolute(m, f.level, f.module); + boolean submodule = base == null; + for (Alias a : f.names) { + submodule |= base != null && mods.containsKey(base + "." + a.name); + } + if (submodule) { + // `from . import x` runs the submodule x: keep x. + Alias a = f.names.get(0); + name(m, a.asname != null ? a.asname : a.name); + return true; + } + if (apply) { + // Kept only to run the module: binding a name of it + // would keep that name's definition too. + Import i = new Import(new ArrayList(java.util.Collections.singletonList( + new Alias(base, "_cn1_imported")))); + i.line = f.line; + replacements.put(f, i); + } + return more; + } + if (apply) { + f.names.retainAll(keepNames); + } + } + return more; + } + + // ---- what each statement binds ----------------------------------- + + /// Records the names top-level statement `top` binds through `s` + /// (itself, or a statement nested in its `if`/`try` blocks). + private void bind(Mod m, Stmt top, Stmt s) { + if (s instanceof FunctionDef) { + binder(m, ((FunctionDef) s).name, top); + } else if (s instanceof ClassDef) { + binder(m, ((ClassDef) s).name, top); + } else if (s instanceof Assign) { + for (Expr t : ((Assign) s).targets) { + targets(m, t, top); + } + } else if (s instanceof AnnAssign) { + targets(m, ((AnnAssign) s).target, top); + } else if (s instanceof AugAssign) { + targets(m, ((AugAssign) s).target, top); + } else if (s instanceof TypeAlias) { + binder(m, ((TypeAlias) s).name, top); + } else if (s instanceof Import) { + for (Alias a : ((Import) s).names) { + String n = a.asname != null ? a.asname : first(a.name); + binder(m, n, top); + importOf(m, n, s, a); + } + } else if (s instanceof ImportFrom) { + for (Alias a : ((ImportFrom) s).names) { + if (!"*".equals(a.name)) { + String n = a.asname != null ? a.asname : a.name; + binder(m, n, top); + importOf(m, n, s, a); + } + } + } else if (s instanceof If) { + if (!typeChecking(((If) s).test)) { + for (Stmt x : ((If) s).body) { + bind(m, top, x); + } + } + for (Stmt x : ((If) s).orelse) { + bind(m, top, x); + } + } else if (s instanceof Try) { + Try t = (Try) s; + for (Stmt x : t.body) { + bind(m, top, x); + } + for (ExceptHandler h : t.handlers) { + if (h.name != null) { + binder(m, h.name, top); + } + for (Stmt x : h.body) { + bind(m, top, x); + } + } + for (Stmt x : t.orelse) { + bind(m, top, x); + } + for (Stmt x : t.finalbody) { + bind(m, top, x); + } + } else if (s instanceof For) { + targets(m, ((For) s).target, top); + for (Stmt x : ((For) s).body) { + bind(m, top, x); + } + } else if (s instanceof With) { + for (WithItem w : ((With) s).items) { + if (w.vars != null) { + targets(m, w.vars, top); + } + } + for (Stmt x : ((With) s).body) { + bind(m, top, x); + } + } else if (s instanceof While) { + for (Stmt x : ((While) s).body) { + bind(m, top, x); + } + } + } + + private void targets(Mod m, Expr t, Stmt top) { + if (t instanceof Name) { + binder(m, ((Name) t).id, top); + } else if (t instanceof TupleExpr || t instanceof ListExpr || t instanceof Starred) { + Infer.children(t, c -> { + if (c instanceof Expr) { + targets(m, (Expr) c, top); + } + }); + } + } + + private static void binder(Mod m, String n, Stmt top) { + List l = m.binders.get(n); + if (l == null) { + l = new ArrayList(); + m.binders.put(n, l); + } + if (!l.contains(top)) { + l.add(top); + } + } + + private static void importOf(Mod m, String n, Stmt s, Alias a) { + List l = m.importsOf.get(n); + if (l == null) { + l = new ArrayList(); + m.importsOf.put(n, l); + } + l.add(new Object[] {s, a}); + } + + private static String first(String dotted) { + int dot = dotted.indexOf('.'); + return dot < 0 ? dotted : dotted.substring(0, dot); + } + + // ---- which statements have effects --------------------------------- + + /// Decides [Mod#effects] for every module: an effectful statement of + /// its own, or an import of a module that has effects. Settles by + /// iteration; effects only ever spread. + private void effects() { + boolean changed = true; + while (changed) { + changed = false; + for (Mod m : mods.values()) { + if (m.effects) { + continue; + } + for (Stmt s : m.body) { + if (effectful(m, s)) { + m.effects = true; + changed = true; + break; + } + } + } + } + } + + private boolean effectful(Mod m, Stmt s) { + if (EntryPointTable.MODULE.equals(m.name) && EntryPointTable.registers(s) != null) { + // Kept by #entryPoints once live code spells the group. + return false; + } + if (s instanceof Pass || s instanceof Global || s instanceof Raise || s instanceof Assert) { + return false; + } + if (s instanceof ExprStmt) { + // A docstring is kept regardless (see #keepAlways). + return !(((ExprStmt) s).value instanceof Constant); + } + if (s instanceof FunctionDef) { + FunctionDef f = (FunctionDef) s; + return !pureDecorators(f.decorators) || !pure(f.args) || f.returns != null && !pure(f.returns); + } + if (s instanceof ClassDef) { + // The body builds the class; bases and keywords name types. + return !pureDecorators(((ClassDef) s).decorators); + } + if (s instanceof Assign) { + for (Expr t : ((Assign) s).targets) { + if (!plainTarget(t)) { + return true; + } + } + return !pure(((Assign) s).value) && !pureInstance(m, ((Assign) s).value); + } + if (s instanceof AnnAssign) { + AnnAssign a = (AnnAssign) s; + return !plainTarget(a.target) || a.value != null && !pure(a.value) && !pureInstance(m, a.value); + } + if (s instanceof TypeAlias) { + return false; + } + if (s instanceof Import) { + for (Alias a : ((Import) s).names) { + for (String p = a.name;; p = p.substring(0, p.lastIndexOf('.'))) { + Mod t = mods.get(p); + if (t != null && t.effects) { + return true; + } + if (p.indexOf('.') < 0) { + break; + } + } + } + return false; + } + if (s instanceof ImportFrom) { + ImportFrom f = (ImportFrom) s; + if ("__future__".equals(f.module)) { + return false; + } + String base = absolute(m, f.level, f.module); + if (base == null) { + return false; + } + for (String p = base;; p = p.substring(0, p.lastIndexOf('.'))) { + Mod t = mods.get(p); + if (t != null && t.effects) { + return true; + } + if (p.indexOf('.') < 0) { + break; + } + } + for (Alias a : f.names) { + Mod t = mods.get(base + "." + a.name); + if (t != null && t.effects) { + return true; + } + } + return false; + } + if (s instanceof If) { + If i = (If) s; + if (typeChecking(i.test)) { + return effectful(m, i.orelse); + } + return !pure(i.test) || effectful(m, i.body) || effectful(m, i.orelse); + } + if (s instanceof Try) { + Try t = (Try) s; + if (effectful(m, t.body) || effectful(m, t.orelse) || effectful(m, t.finalbody)) { + return true; + } + for (ExceptHandler h : t.handlers) { + if (h.type != null && !pure(h.type) || effectful(m, h.body)) { + return true; + } + } + return false; + } + return true; + } + + private boolean effectful(Mod m, List b) { + for (Stmt s : b) { + if (effectful(m, s)) { + return true; + } + } + return false; + } + + /// A class statement and the module it is in. + private static final class Cls { + final Mod mod; + final ClassDef def; + + Cls(Mod mod, ClassDef def) { + this.mod = mod; + this.def = def; + } + } + + /// Bases a class may have and still be built without running code. + private static final Set PLAIN_BASES = new HashSet(Arrays.asList( + "object", "Generic", "ABC", "Protocol")); + + /// Whether `e` is `C()` or `C().m()` with constant-free pure arguments, + /// where `C` is a class of the program that defines no `__init__`, + /// `__new__` or metaclass anywhere in its bases, and `m` is a plain + /// method whose body only returns a pure value. Building such an + /// instance runs nothing of the program: openai's module-level + /// `chat = ChatProxy().__as_proxied__()` is one. + private boolean pureInstance(Mod m, Expr e) { + if (!(e instanceof Call) || !pureArgs((Call) e)) { + return false; + } + Call c = (Call) e; + String meth = null; + Expr ctor = c; + if (c.func instanceof Attribute && ((Attribute) c.func).value instanceof Call) { + meth = ((Attribute) c.func).attr; + ctor = ((Attribute) c.func).value; + if (!pureArgs((Call) ctor)) { + return false; + } + } + Expr f = ((Call) ctor).func; + if (!(f instanceof Name)) { + return false; + } + Cls cls = classOf(m, ((Name) f).id, 0); + if (cls == null) { + return false; + } + List chain = new ArrayList(); + if (!plainClass(cls, chain, 0)) { + return false; + } + if (meth == null) { + return true; + } + for (Cls k : chain) { + for (Stmt x : k.def.body) { + if (x instanceof FunctionDef && meth.equals(((FunctionDef) x).name)) { + return returnsOnly((FunctionDef) x); + } + } + } + return false; + } + + private static boolean returnsOnly(FunctionDef f) { + if (f.isAsync || !f.decorators.isEmpty()) { + return false; + } + List b = f.body; + int i = !b.isEmpty() && b.get(0) instanceof ExprStmt && ((ExprStmt) b.get(0)).value instanceof Constant ? 1 : 0; + return b.size() == i + 1 && b.get(i) instanceof Return && pure(((Return) b.get(i)).value); + } + + /// Collects `cls` and its program bases, depth first, into `chain`; + /// false when building one could run code. + private boolean plainClass(Cls cls, List chain, int depth) { + ClassDef d = cls.def; + if (depth > 16 || !d.decorators.isEmpty() || !d.keywords.isEmpty()) { + return false; + } + for (Stmt x : d.body) { + if (x instanceof FunctionDef) { + String n = ((FunctionDef) x).name; + if ("__init__".equals(n) || "__new__".equals(n) || "__post_init__".equals(n)) { + return false; + } + } + } + chain.add(cls); + for (Expr b : d.bases) { + Expr base = b instanceof Subscript ? ((Subscript) b).value : b; + String last = lastName(base); + if (last != null && PLAIN_BASES.contains(last)) { + continue; + } + if (!(base instanceof Name)) { + return false; + } + Cls k = classOf(cls.mod, ((Name) base).id, 0); + if (k == null || !plainClass(k, chain, depth + 1)) { + return false; + } + } + return true; + } + + /// The module and class statement that `n` names in `m`, following + /// `from x import n` into the program; null for anything else. + private Cls classOf(Mod m, String n, int depth) { + List bs = m.binders.get(n); + if (bs == null || bs.size() != 1 || depth > 8) { + return null; + } + Stmt s = bs.get(0); + if (s instanceof ClassDef && n.equals(((ClassDef) s).name)) { + return new Cls(m, (ClassDef) s); + } + if (s instanceof ImportFrom) { + ImportFrom f = (ImportFrom) s; + String base = absolute(m, f.level, f.module); + Mod t = base == null ? null : mods.get(base); + if (t == null) { + return null; + } + for (Alias a : f.names) { + if (n.equals(a.asname != null ? a.asname : a.name)) { + return classOf(t, a.name, depth + 1); + } + } + } + return null; + } + + private static boolean plainTarget(Expr t) { + if (t instanceof Name) { + return true; + } + if (t instanceof TupleExpr || t instanceof ListExpr) { + final boolean[] ok = {true}; + Infer.children(t, c -> ok[0] &= c instanceof Expr && plainTarget((Expr) c)); + return ok[0]; + } + return false; + } + + private static boolean pureDecorators(List ds) { + for (Expr d : ds) { + Expr f = d instanceof Call ? ((Call) d).func : d; + String last = lastName(f); + if (last == null || !PURE_DECORATORS.contains(last) && !PURE_DECORATORS.contains(rootName(f)) + || d instanceof Call && !pureArgs((Call) d)) { + return false; + } + } + return true; + } + + private static String lastName(Expr e) { + return e instanceof Name ? ((Name) e).id : e instanceof Attribute ? ((Attribute) e).attr : null; + } + + private static String rootName(Expr e) { + while (e instanceof Attribute) { + e = ((Attribute) e).value; + } + return e instanceof Name ? ((Name) e).id : null; + } + + private static boolean pureArgs(Call c) { + for (Expr a : c.args) { + if (!pure(a)) { + return false; + } + } + for (Keyword k : c.keywords) { + if (!pure(k.value)) { + return false; + } + } + return true; + } + + /// Whether evaluating `o` only computes a value. + private static boolean pure(Object o) { + if (o == null) { + return true; + } + if (o instanceof Lambda) { + // Builds a function; its body runs when called. + return true; + } + if (o instanceof Await || o instanceof Yield || o instanceof NamedExpr) { + return false; + } + if (o instanceof Call) { + Call c = (Call) o; + String last = lastName(c.func); + if (last == null || !PURE_CALLS.contains(last) || !pure(c.func)) { + return false; + } + return pureArgs(c); + } + final boolean[] ok = {true}; + Infer.children(o, c -> ok[0] &= pure(c)); + return ok[0]; + } + + /// Whether `test` is typing's `TYPE_CHECKING`, False when the program + /// runs: what it guards binds and imports nothing. + static boolean typeChecking(Expr test) { + return test instanceof Name && "TYPE_CHECKING".equals(((Name) test).id) + || test instanceof Attribute && "TYPE_CHECKING".equals(((Attribute) test).attr); + } + + // ---- liveness ------------------------------------------------------- + + private void drain() { + while (!work.isEmpty()) { + work.poll().run(); + } + } + + private void module(Mod m) { + if (m == null || !live.add(m)) { + return; + } + if (WHY) { + System.err.println("live " + m.name + " <- " + cause); + } + // A package's __init__ runs before any module under it. + int dot = m.name.lastIndexOf('.'); + if (dot > 0) { + module(mods.get(m.name.substring(0, dot))); + } + names.put(m, new HashSet()); + for (Stmt s : m.body) { + if (keepAlways(m, s)) { + keep(m, s); + } + } + for (String n : m.binders.keySet()) { + if (n.startsWith("__") && n.endsWith("__")) { + // __all__, __getattr__, __version__: the import system and + // the runtime read them by name. + name(m, n); + } + } + distributions(m); + } + + private boolean keepAlways(Mod m, Stmt s) { + if (s instanceof ExprStmt && ((ExprStmt) s).value instanceof Constant) { + return true; + } + if (s instanceof ImportFrom && "__future__".equals(((ImportFrom) s).module)) { + return true; + } + return effectful(m, s); + } + + private void full(Mod m) { + if (m == null || !full.add(m)) { + return; + } + module(m); + for (Stmt s : m.body) { + keep(m, s); + } + for (String n : m.binders.keySet()) { + name(m, n); + } + } + + private void name(Mod m, String n) { + if (m == null) { + return; + } + module(m); + if (!names.get(m).add(n)) { + return; + } + List bs = m.binders.get(n); + if (bs != null) { + for (Stmt s : bs) { + keep(m, s); + } + } + List is = m.importsOf.get(n); + if (is != null) { + for (Object[] i : is) { + importAlias(m, (Stmt) i[0], (Alias) i[1]); + } + } + if (bs == null) { + List lz = m.lazy.get(n); + if (lz != null) { + // Imported by the module's __getattr__ when read. + for (String[] t : lz) { + Mod target = mods.get(relativeToken(m, t[0])); + module(target); + if (target != null && t.length > 1 && t[1] != null) { + name(target, t[1]); + } + } + } + } + // An attribute of a package may be its submodule, bound by + // importing it. + Mod sub = mods.get(m.name + "." + n); + if (sub != null && !m.binders.containsKey(n)) { + module(sub); + } + } + + /// What a top-level import binding live alias `a` reads. + private void importAlias(Mod m, Stmt s, Alias a) { + if (s instanceof Import) { + modulePath(a.name); + return; + } + ImportFrom f = (ImportFrom) s; + String base = absolute(m, f.level, f.module); + if (base == null) { + return; + } + Mod b = mods.get(base); + module(b); + Mod sub = mods.get(base + "." + a.name); + if (sub != null) { + module(sub); + } + if (b != null) { + name(b, a.name); + } + } + + private void modulePath(String dotted) { + for (int i = dotted.indexOf('.'); ; i = dotted.indexOf('.', i + 1)) { + module(mods.get(i < 0 ? dotted : dotted.substring(0, i))); + if (i < 0) { + return; + } + } + } + + private void keep(Mod m, Stmt s) { + if (!kept.add(s)) { + return; + } + work.add(() -> reads(m, s)); + } + + /// Follows everything kept top-level statement `s` of `m` reads. + private void reads(Mod m, Stmt s) { + cause = m.name + ":" + s.line; + Map local = new HashMap(); + localImports(m, s, local, s instanceof Import || s instanceof ImportFrom); + if (s instanceof Import || s instanceof ImportFrom) { + // An import runs the module whether or not its names are + // read; which names it imports follows from those that are + // live (see #name). + if (s instanceof Import) { + for (Alias a : ((Import) s).names) { + modulePath(a.name); + } + } else { + ImportFrom f = (ImportFrom) s; + String base = absolute(m, f.level, f.module); + if (base != null) { + modulePath(base); + for (Alias a : f.names) { + if ("*".equals(a.name)) { + star(base); + } else if (mods.containsKey(base + "." + a.name) && mods.get(base + "." + a.name).effects) { + module(mods.get(base + "." + a.name)); + } + } + } + } + return; + } + tableStrings = !(s instanceof FunctionDef) && !(s instanceof ClassDef) + && (!m.lazy.isEmpty() || binds(s, "__all__")); + try { + visit(m, s, local); + } finally { + tableStrings = false; + } + } + + /// Set while the visit is in a module's `__all__`, or in the top-level + /// code of a module that imports names lazily: those strings name the + /// module's globals and submodules (`".evals"`, `"Evals"`), which + /// #name and the lazy tables resolve, never attributes of an object. + private boolean tableStrings; + + /// Whether every `globals()`/`locals()` of `m`'s top level is bound to a + /// name read only as `ns[n]`, with `n` the variable of a loop over + /// `__all__` (openai's loop setting each export's `__module__`), and + /// nothing else of `m` calls either. Such a module reads its globals by + /// the names of `__all__` and no others. + private boolean indexedByAll(Mod m) { + if (m.allIndexed == null) { + Set ns = new HashSet(); + boolean ok = m.binders.containsKey("__all__"); + for (Stmt x : m.body) { + if (x instanceof Assign && ((Assign) x).targets.size() == 1 + && ((Assign) x).targets.get(0) instanceof Name && namespaceCall(((Assign) x).value)) { + ns.add(((Name) ((Assign) x).targets.get(0)).id); + } + } + final boolean[] good = {ok && !ns.isEmpty()}; + for (Stmt x : m.body) { + if (!good[0]) { + break; + } + if (x instanceof Assign && ((Assign) x).targets.size() == 1 + && ((Assign) x).targets.get(0) instanceof Name + && ns.contains(((Name) ((Assign) x).targets.get(0)).id) + && namespaceCall(((Assign) x).value)) { + continue; + } + namespaceUses(x, ns, null, good); + } + m.allIndexed = good[0]; + } + return m.allIndexed; + } + + private static boolean namespaceCall(Expr e) { + return e instanceof Call && ((Call) e).args.isEmpty() && ((Call) e).func instanceof Name + && ("globals".equals(((Name) ((Call) e).func).id) || "locals".equals(((Name) ((Call) e).func).id)); + } + + /// Clears `good[0]` on a read of a name of `ns` other than `ns[v]`, + /// `v` being `loopVar` (a loop over `__all__`), or on any other call of + /// `globals`/`locals`. + private static void namespaceUses(Object o, Set ns, String loopVar, boolean[] good) { + if (!good[0]) { + return; + } + if (o instanceof FunctionDef && "__dir__".equals(((FunctionDef) o).name)) { + // A module's __dir__ answers dir(module), which lists names + // and reads none of them. + return; + } + if (o instanceof Assign && ((Assign) o).targets.size() == 1 + && ((Assign) o).targets.get(0) instanceof Subscript + && namespaceCall(((Subscript) ((Assign) o).targets.get(0)).value)) { + // `globals()[name] = value` (a lazy __getattr__ caching what it + // imported) stores a name and reads none. + namespaceUses(((Subscript) ((Assign) o).targets.get(0)).index, ns, loopVar, good); + namespaceUses(((Assign) o).value, ns, loopVar, good); + return; + } + if (o instanceof For && ((For) o).iter instanceof Name && "__all__".equals(((Name) ((For) o).iter).id) + && ((For) o).target instanceof Name) { + String v = ((Name) ((For) o).target).id; + for (Stmt x : ((For) o).body) { + namespaceUses(x, ns, v, good); + } + for (Stmt x : ((For) o).orelse) { + namespaceUses(x, ns, loopVar, good); + } + return; + } + if (o instanceof Subscript && ((Subscript) o).value instanceof Name + && ns.contains(((Name) ((Subscript) o).value).id)) { + if (loopVar == null || !(((Subscript) o).index instanceof Name) + || !loopVar.equals(((Name) ((Subscript) o).index).id)) { + good[0] = false; + } + return; + } + if (o instanceof Name && (ns.contains(((Name) o).id) || "globals".equals(((Name) o).id) + || "locals".equals(((Name) o).id) || "vars".equals(((Name) o).id))) { + good[0] = false; + return; + } + Infer.children(o, c -> namespaceUses(c, ns, loopVar, good)); + } + + /// Makes live every name the module's `__all__` lists. + private void allNames(Mod m) { + if (m.allRead) { + return; + } + m.allRead = true; + for (Stmt x : m.body) { + if (binds(x, "__all__")) { + Expr v = x instanceof Assign ? ((Assign) x).value + : x instanceof AugAssign ? ((AugAssign) x).value : ((AnnAssign) x).value; + if (!(v instanceof ListExpr) && !(v instanceof TupleExpr)) { + full(m); + return; + } + Infer.children(v, c -> { + if (c instanceof Constant && ((Constant) c).kind == Constant.Kind.STR) { + name(m, ((Constant) c).text); + } else { + full(m); + } + }); + } + } + } + + private static boolean binds(Stmt s, String n) { + List ts = s instanceof Assign ? ((Assign) s).targets + : s instanceof AnnAssign ? java.util.Collections.singletonList(((AnnAssign) s).target) + : s instanceof AugAssign ? java.util.Collections.singletonList(((AugAssign) s).target) + : java.util.Collections.emptyList(); + for (Expr t : ts) { + if (t instanceof Name && n.equals(((Name) t).id)) { + return true; + } + } + return false; + } + + private void star(String base) { + // Binds what __all__ names, or every public name: and which of + // them is read is not followed through the star. + full(mods.get(base)); + if (mods.get(base) != null) { + for (Mod x : mods.values()) { + if (x.name.startsWith(base + ".") && x.name.indexOf('.', base.length() + 1) < 0 + && mods.get(base).binders.get("__all__") != null) { + // __all__ may name a submodule, which the import runs. + module(x); + } + } + } + } + + /// Collects the module aliases imports nested in `s` bind (inside + /// functions and classes), and runs those imports. A nested import is + /// followed whole: it runs only if its function does, and then binds + /// a name the function reads. + private void localImports(Mod m, Object o, Map local, boolean top) { + if (o instanceof If && typeChecking(((If) o).test)) { + for (Stmt x : ((If) o).orelse) { + localImports(m, x, local, false); + } + return; + } + if (!top && o instanceof Import) { + for (Alias a : ((Import) o).names) { + modulePath(a.name); + if (a.asname != null) { + local.put(a.asname, a.name); + } else { + local.put(first(a.name), first(a.name)); + } + } + return; + } + if (!top && o instanceof ImportFrom) { + ImportFrom f = (ImportFrom) o; + String base = absolute(m, f.level, f.module); + if (base == null || "__future__".equals(base)) { + return; + } + modulePath(base); + for (Alias a : f.names) { + if ("*".equals(a.name)) { + star(base); + continue; + } + String n = a.asname != null ? a.asname : a.name; + if (mods.containsKey(base + "." + a.name)) { + module(mods.get(base + "." + a.name)); + local.put(n, base + "." + a.name); + } else { + name(mods.get(base), a.name); + String r = moduleOf(mods.get(base), a.name, 0); + if (r != null) { + local.put(n, r); + } + } + } + return; + } + if (o instanceof ClassDef && pruneMembers) { + // A method that may be pruned runs its imports when it is + // found live (#wake), not with its class. + for (Stmt x : ((ClassDef) o).body) { + if (x instanceof FunctionDef && prunable((FunctionDef) x)) { + for (Expr d : ((FunctionDef) x).decorators) { + localImports(m, d, local, false); + } + } else { + localImports(m, x, local, false); + } + } + for (Expr b : ((ClassDef) o).bases) { + localImports(m, b, local, false); + } + return; + } + Infer.children(o, c -> localImports(m, c, local, false)); + } + + /// The module that name `n` of module `m` is bound to by a top-level + /// import, through re-exports, or null. + private String moduleOf(Mod m, String n, int depth) { + if (m == null || depth > 12) { + return null; + } + List is = m.importsOf.get(n); + if (is == null) { + return null; + } + for (Object[] i : is) { + Stmt s = (Stmt) i[0]; + Alias a = (Alias) i[1]; + if (s instanceof Import) { + return a.asname != null ? a.name : first(a.name); + } + ImportFrom f = (ImportFrom) s; + String base = absolute(m, f.level, f.module); + if (base == null) { + continue; + } + if (mods.containsKey(base + "." + a.name)) { + return base + "." + a.name; + } + String r = moduleOf(mods.get(base), a.name, depth + 1); + if (r != null) { + return r; + } + } + return null; + } + + private String aliasModule(Mod m, String n, Map local) { + if (local.containsKey(n)) { + return local.get(n); + } + return moduleOf(m, n, 0); + } + + private void visit(Mod m, Object o, Map local) { + if (tableStrings && (o instanceof FunctionDef || o instanceof Lambda || o instanceof ClassDef)) { + // The body of a function runs on its own terms. + tableStrings = false; + try { + visitNode(m, o, local); + } finally { + tableStrings = true; + } + return; + } + visitNode(m, o, local); + } + + private void visitNode(Mod m, Object o, Map local) { + visiting = m.name; + if (o instanceof If && typeChecking(((If) o).test)) { + visit(m, ((If) o).test, local); + for (Stmt x : ((If) o).orelse) { + visit(m, x, local); + } + return; + } + if (o instanceof Import || o instanceof ImportFrom) { + // Run in localImports; their names are read where used. + return; + } + if (o instanceof ClassDef && pruneMembers) { + ClassDef c = (ClassDef) o; + classes.add(c); + for (Expr d : c.decorators) { + visit(m, d, local); + } + for (Expr b : c.bases) { + visit(m, b, local); + } + for (Keyword k : c.keywords) { + visit(m, k.value, local); + } + for (Stmt x : c.body) { + if (x instanceof FunctionDef && prunable((FunctionDef) x) && !attrs.contains(((FunctionDef) x).name) + && !byPrefix(((FunctionDef) x).name)) { + List ws = waiting.get(((FunctionDef) x).name); + if (ws == null) { + ws = new ArrayList(); + waiting.put(((FunctionDef) x).name, ws); + } + ws.add(new Object[] {m, x, local}); + } else { + if (x instanceof FunctionDef) { + members.add((FunctionDef) x); + if (prunable((FunctionDef) x)) { + localImports(m, x, local, false); + } + for (Expr d : ((FunctionDef) x).decorators) { + bareNames(d); + } + } else if (!(x instanceof ClassDef)) { + bareNames(x); + } + visit(m, x, local); + } + } + return; + } + if (o instanceof Attribute) { + List chain = new ArrayList(); + Expr e = (Expr) o; + while (e instanceof Attribute) { + chain.add(0, ((Attribute) e).attr); + attr(((Attribute) e).attr); + e = ((Attribute) e).value; + } + if (chain.contains("import_module") || chain.contains("load") && e instanceof Name + && "_cn1imp".equals(((Name) e).id)) { + importsByName(m); + } + if (e instanceof Name) { + String base = ((Name) e).id; + String mod = aliasModule(m, base, local); + if (mod != null && mods.containsKey(mod)) { + if (!local.containsKey(base)) { + name(m, base); + } + attributes(mod, chain); + return; + } + } + } + if (o instanceof Call) { + Call c = (Call) o; + if (c.func instanceof Name && ("getattr".equals(((Name) c.func).id) || "hasattr".equals(((Name) c.func).id)) + && c.args.size() >= 2 && c.args.get(0) instanceof Name && c.args.get(1) instanceof Constant) { + String base = ((Name) c.args.get(0)).id; + String mod = aliasModule(m, base, local); + if (mod != null && mods.containsKey(mod)) { + if (!local.containsKey(base)) { + name(m, base); + } + name(mods.get(mod), ((Constant) c.args.get(1)).text); + attr(((Constant) c.args.get(1)).text); + for (int i = 2; i < c.args.size(); i++) { + visit(m, c.args.get(i), local); + } + return; + } + } + if (c.args.size() == 2 && isStr(c.args.get(0)) && isStr(c.args.get(1))) { + String rel = ((Constant) c.args.get(0)).text; + if (rel.startsWith(".")) { + String base = ((Constant) c.args.get(1)).text; + int level = 0; + while (level < rel.length() && rel.charAt(level) == '.') { + level++; + } + for (int i = 1; i < level && base.lastIndexOf('.') > 0; i++) { + base = base.substring(0, base.lastIndexOf('.')); + } + m.strings.add(level == rel.length() ? base : base + "." + rel.substring(level)); + } + } + } + if (o instanceof Call && constantImport(m, (Call) o, local)) { + return; + } + if (o instanceof Name) { + String id = ((Name) o).id; + if (importer(id)) { + importsByName(m); + } + if (("globals".equals(id) || "locals".equals(id)) && indexedByAll(m)) { + // Only ever `ns[name]` for the names of __all__. + allNames(m); + } else if ("globals".equals(id) || "vars".equals(id) || "locals".equals(id) || "_getframe".equals(id) + || "currentframe".equals(id)) { + full(m); + } + String mod = aliasModule(m, id, local); + if (mod != null && mods.containsKey(mod)) { + // The module as a value: any of its names may be read. + full(mods.get(mod)); + } + if (!local.containsKey(id)) { + name(m, id); + } + return; + } + if (o instanceof Constant && ((Constant) o).kind == Constant.Kind.STR) { + String t = ((Constant) o).text; + m.strings.add(t); + if (m.importsByName) { + readStrings(m); + } + if (hasSpace(t) || tableStrings || t.startsWith(".")) { + // Prose (a docstring, a message), a relative module path or + // a table of the module's own names: it names no attribute. + return; + } + // A forward reference, an annotation as a string, a name + // looked up by getattr on the module: any identifier in the + // string that the module binds. + for (String tok : tokens(t)) { + for (String part : tok.split("\\.")) { + attr(part); + if (m.binders.containsKey(part)) { + name(m, part); + } + } + } + if (m.importsByName) { + readStrings(m); + } + return; + } + if (o instanceof JoinedStr && !((JoinedStr) o).parts.isEmpty() && isStr(((JoinedStr) o).parts.get(0))) { + m.prefixes.add(((Constant) ((JoinedStr) o).parts.get(0)).text); + prefix(((Constant) ((JoinedStr) o).parts.get(0)).text); + } else if (o instanceof BinOp && ("+".equals(((BinOp) o).op) || "%".equals(((BinOp) o).op)) + && isStr(((BinOp) o).left)) { + m.prefixes.add(((Constant) ((BinOp) o).left).text); + prefix(((Constant) ((BinOp) o).left).text); + } else if (o instanceof Call && ((Call) o).func instanceof Attribute + && "format".equals(((Attribute) ((Call) o).func).attr) && isStr(((Attribute) ((Call) o).func).value)) { + // `"do_{}".format(op)`: pdfminer's interpreter finds its + // operators this way. + Constant fmt = (Constant) ((Attribute) ((Call) o).func).value; + m.prefixes.add(fmt.text); + prefix(fmt.text); + } else if (o instanceof Call && ((Call) o).func instanceof Attribute + && "startswith".equals(((Attribute) ((Call) o).func).attr) && !((Call) o).args.isEmpty()) { + Expr a = ((Call) o).args.get(0); + if (isStr(a)) { + prefix(((Constant) a).text); + } else if (a instanceof TupleExpr) { + for (Expr x : ((TupleExpr) a).elts) { + if (isStr(x)) { + prefix(((Constant) x).text); + } + } + } else if ((a instanceof Name || a instanceof Attribute) && m.prefixStrings.add(heldName(a))) { + // A prefix held in a variable (`self.testMethodPrefix`): + // any string the module stores under that name may be it. + // Every string of the module was once taken instead, and a + // `v.startswith(p)` over a parameter made each constant of + // pandas (`"str"`) a prefix that kept `structure_tree`. A + // parameter is filled by the caller, whose own strings are + // read where it calls. + String held = heldName(a); + for (Stmt st : m.body) { + storedStrings(st, held); + } + } + } + Infer.children(o, c -> visit(m, c, local)); + } + + /// Reads `mod.a.b...`: the first name that is not a submodule is the + /// name read. + private void attributes(String mod, List chain) { + String cur = mod; + for (String a : chain) { + if ("__dict__".equals(a)) { + full(mods.get(cur)); + return; + } + Mod c = mods.get(cur); + name(c, a); + String sub = moduleOf(c, a, 0); + if (sub == null && mods.containsKey(cur + "." + a)) { + sub = cur + "." + a; + } + if (sub == null || !mods.containsKey(sub)) { + return; + } + module(mods.get(sub)); + cur = sub; + } + } + + private static boolean hasSpace(String t) { + for (int i = 0; i < t.length(); i++) { + if (Character.isWhitespace(t.charAt(i))) { + return true; + } + } + return false; + } + + /// `import_module("a.b")`, `import_module(".x", __name__)` or + /// `import_module(".x", "pkg")`: imports the one module it names, so + /// the module making the call does not import by computed names. The + /// module comes back as a value, so all of it is live. + private boolean constantImport(Mod m, Call c, Map local) { + if (!"import_module".equals(lastName(c.func)) || c.args.isEmpty() || c.args.size() > 2 + || !c.keywords.isEmpty() || !isStr(c.args.get(0))) { + return false; + } + String target = ((Constant) c.args.get(0)).text; + if (target.startsWith(".")) { + if (c.args.size() != 2) { + return false; + } + Expr anchor = c.args.get(1); + String base; + if (isStr(anchor)) { + base = ((Constant) anchor).text; + } else if (anchor instanceof Name && "__name__".equals(((Name) anchor).id)) { + base = m.name; + } else if (anchor instanceof Name && "__package__".equals(((Name) anchor).id)) { + base = m.pkg ? m.name : m.name.substring(0, Math.max(0, m.name.lastIndexOf('.'))); + } else { + return false; + } + int level = 0; + while (level < target.length() && target.charAt(level) == '.') { + level++; + } + for (int i = 1; i < level && base.lastIndexOf('.') > 0; i++) { + base = base.substring(0, base.lastIndexOf('.')); + } + target = level == target.length() ? base : base + "." + target.substring(level); + } else if (c.args.size() == 2 && !pure(c.args.get(1))) { + return false; + } + Mod t = mods.get(target); + if (t == null) { + return false; + } + full(t); + if (c.func instanceof Attribute) { + // `importlib.import_module`: the module importlib is read. + visit(m, ((Attribute) c.func).value, local); + } else if (!local.containsKey(((Name) c.func).id)) { + name(m, ((Name) c.func).id); + } + return true; + } + + private static boolean importer(String n) { + return "import_module".equals(n) || "__import__".equals(n) || "_cn1imp".equals(n); + } + + private static boolean isStr(Expr e) { + return e instanceof Constant && ((Constant) e).kind == Constant.Kind.STR; + } + + private void importsByName(Mod m) { + if (!m.lazy.isEmpty()) { + // What its __getattr__ imports by name is in its tables, read + // a name at a time (see #name). + return; + } + if (!m.importsByName) { + m.importsByName = true; + readStrings(m); + } + } + + private void distributions(Mod m) { + if ("importlib.metadata".equals(m.name) && !distributionsRead) { + distributionsRead = true; + Mod d = mods.get("_cn1_distributions"); + if (d != null) { + // The table is kept whole, but its strings are not read as + // imports: they name every installed package and every + // console script, and a program reaches a package's code + // through its own imports. What the metadata hands out by + // name is entry points, followed by #entryPoints. + full(d); + EntryPointScan scan = new EntryPointScan(); + for (Stmt x : d.body) { + scan.on(x); + } + } + } + } + + /// The groups whose EntryPointTable registration is kept. + private final Set keptGroups = new HashSet(); + + /// Group -> the `module` or `module:attr` targets of its entry points. + private final Map> entryGroups = new HashMap>(); + + /// Reads the `entry_points.txt` texts out of `_cn1_distributions`. + private final class EntryPointScan implements Infer.Visit { + @Override + public void on(Object o) { + if (o instanceof Constant && ((Constant) o).kind == Constant.Kind.STR) { + String group = null; + for (String line : ((Constant) o).text.split("\n")) { + String t = line.trim(); + if (t.startsWith("[") && t.endsWith("]")) { + group = t.substring(1, t.length() - 1).trim(); + } else if (group != null && t.indexOf('=') > 0) { + String target = t.substring(t.indexOf('=') + 1).trim(); + int sp = target.indexOf(' '); + if (sp > 0) { + target = target.substring(0, sp); + } + List l = entryGroups.get(group); + if (l == null) { + l = new ArrayList(); + entryGroups.put(group, l); + } + l.add(target); + } + } + } else { + Infer.children(o, this); + } + } + } + + /// Follows the entry points of every group whose name live code has + /// spelled (pluggy's `load_setuptools_entrypoints("llm")`); true when + /// it reached something new. + private boolean entryPoints() { + boolean any = false; + Mod table = mods.get(EntryPointTable.MODULE); + if (table != null && live.contains(table)) { + for (Stmt x : table.body) { + String g = EntryPointTable.registers(x); + if (g != null && attrs.contains(g) && keptGroups.add(g)) { + cause = "entry point group " + g; + keep(table, x); + any = true; + } + } + } + for (java.util.Iterator>> it = entryGroups.entrySet().iterator(); + it.hasNext();) { + Map.Entry> e = it.next(); + if (!attrs.contains(e.getKey())) { + continue; + } + it.remove(); + any = true; + for (String target : e.getValue()) { + int colon = target.indexOf(':'); + String mod = colon < 0 ? target : target.substring(0, colon); + Mod t = mods.get(mod); + if (t == null) { + continue; + } + cause = "entry point group " + e.getKey(); + if (colon < 0) { + full(t); + } else { + module(t); + String attr = target.substring(colon + 1); + int dot = attr.indexOf('.'); + name(t, dot < 0 ? attr : attr.substring(0, dot)); + } + } + } + return any; + } + + /// What a module that imports by computed names may import: every + /// module its kept strings name, and every module under the constant + /// start of a formatted one. Such a module is reached by name, so all + /// of its names are. + private void readStrings(Mod m) { + List ss = new ArrayList(m.strings); + m.strings.clear(); + List ps = new ArrayList(m.prefixes); + m.prefixes.clear(); + for (String t : ss) { + for (String tok : tokens(t)) { + String n = relativeToken(m, tok); + if (n != null && mods.containsKey(n)) { + full(mods.get(n)); + } + } + } + for (String t : ps) { + List toks = tokens(t); + if (toks.isEmpty() || !t.endsWith(toks.get(toks.size() - 1))) { + continue; + } + String n = relativeToken(m, toks.get(toks.size() - 1)); + if (n != null && n.indexOf('.') > 0) { + for (Mod x : new ArrayList(mods.values())) { + if (x.name.startsWith(n)) { + full(x); + } + } + } + } + if (!m.importsByName) { + // Kept for when the module turns out to import by name. + m.strings.addAll(ss); + m.prefixes.addAll(ps); + } + } + + private String relativeToken(Mod m, String tok) { + int level = 0; + while (level < tok.length() && tok.charAt(level) == '.') { + level++; + } + if (level == 0) { + return tok; + } + String rest = tok.substring(level); + return absolute(m, level, rest.isEmpty() ? null : rest); + } + + private static List tokens(String s) { + List out = new ArrayList(); + int start = -1; + for (int i = 0; i <= s.length(); i++) { + char c = i < s.length() ? s.charAt(i) : ' '; + boolean id = c == '.' || c == '_' || c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9'; + if (id && start < 0) { + start = i; + } else if (!id && start >= 0) { + out.add(s.substring(start, i)); + start = -1; + } + } + return out; + } + + /// The absolute name of `from import` in `m`, or null + /// when it climbs out of the top-level package. + private static String absolute(Mod m, int level, String module) { + if (level == 0) { + return module; + } + String base = m.name; + int up = m.pkg ? level - 1 : level; + for (int i = 0; i < up; i++) { + int dot = base.lastIndexOf('.'); + if (dot < 0) { + return null; + } + base = base.substring(0, dot); + } + if (module == null) { + return base; + } + return base.isEmpty() ? module : base + "." + module; + } +} diff --git a/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/LoopUnroll.java b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/LoopUnroll.java new file mode 100644 index 00000000000..c131df59526 --- /dev/null +++ b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/LoopUnroll.java @@ -0,0 +1,2509 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.python.transpiler.codegen; + +import com.codename1.python.transpiler.ast.Node; +import com.codename1.python.transpiler.ast.Node.Attribute; +import com.codename1.python.transpiler.ast.Node.Call; +import com.codename1.python.transpiler.ast.Node.ClassDef; +import com.codename1.python.transpiler.ast.Node.Constant; +import com.codename1.python.transpiler.ast.Node.Expr; +import com.codename1.python.transpiler.ast.Node.FunctionDef; +import com.codename1.python.transpiler.ast.Node.Name; +import com.codename1.python.transpiler.ast.Node.Stmt; +import com.codename1.python.transpiler.parser.Lexer; +import com.codename1.python.transpiler.parser.Token; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.IdentityHashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/// Unrolls a loop over attribute names the program spells out. +/// +/// openpyxl walks its fields by name: +/// +/// ```python +/// def __iter__(self): +/// for attr in self.__attrs__: +/// value = getattr(self, attr) +/// ... +/// ``` +/// +/// When the loop variable is the name argument of a +/// `getattr`/`setattr`/`hasattr`/`delattr` and the iterable is a +/// statically known sequence of identifier strings -- a literal tuple or +/// list, a module-level tuple bound once, or `self.X`/`cls.X` where `X` is +/// a class-level tuple (as `DeclarativeMap` writes `__attrs__`, +/// `__elements__` and `__nested__`, or as the source spells `__fields__`) +/// -- the loop is replaced by one copy of its body per name with the name +/// written in as a literal. Every attribute access is then literal, which +/// the strict build accepts and the inference can type. +/// +/// `self.X` is resolved per concrete class: a subclass whose tuple +/// differs gets its own copy of the unrolled method, in the same module; +/// a method reached through `super()` from an override with a different +/// tuple, a copy that would cross modules, or one whose body names +/// `super` or a private (mangled) name is refused. A loop with `else`, +/// `break` or `continue`, a body that rebinds the variable or closes +/// over it, a variable read after the loop, a tuple attribute stored +/// anywhere in the program, and a method whose tree no longer matches its +/// source text are refused as well. No name-dispatch code is generated. +public final class LoopUnroll { + + private static final int MAX_PASSES = 64; + private static final int MAX_DEPTH = 32; + + private LoopUnroll() { + } + + /// A class, the module it is in and the program classes it derives from. + private static final class Cls { + final String path; + final ClassDef def; + final List bases = new ArrayList(); + final List subs = new ArrayList(); + boolean opaque; + /// A base names no single program class: what derives from what is + /// then unknown, not only what the class binds. + boolean unlinked; + + Cls(String path, ClassDef def) { + this.path = path; + this.def = def; + } + } + + /// The program as this pass reads it. + private static final class World { + final Map trees; + final Map> byName = new HashMap>(); + final Map byDef = new IdentityHashMap(); + final Set storedAttrs = new HashSet(); + /// Per attribute, the classes whose instances (or the classes + /// themselves) a store with a known receiver can reach; closed under + /// [#family]. A class outside it keeps its class-level tuple. + final Map> blocked = new HashMap>(); + /// Attributes whose receivers were only inferred from a typed + /// sequence descriptor: an unrolled read of one on the receiver is + /// guarded at run time ([#guardText]). + final Set guarded = new HashSet(); + /// Set while [#names] relies on a [#guarded] attribute of the receiver. + String needGuard; + /// Per `path:name`, whether that function is an options-dict helper. + final Map helpers = new HashMap(); + /// Per attribute, whether [#frozen] proved every list a class body + /// binds to it is never mutated or handed on. + final Map frozen = new HashMap(); + /// The text of each method ConstArgSpecialize made, which no module source holds. + final Map made = new IdentityHashMap(); + /// Calls whose arguments [#frozen] may ignore: ConstArgSpecialize is + /// replacing every one of them. + final Set exempt = java.util.Collections.newSetFromMap(new IdentityHashMap()); + + World(Map trees) { + this.trees = trees; + } + } + + /// Unrolls every qualifying loop among `trees`; `sources` holds the + /// text each tree was parsed from, under the same keys. + public static void rewrite(Map trees, Map sources) { + rewrite(trees, sources, new IdentityHashMap()); + } + + /// As [#rewrite(Map, Map)], reading the text of a method ConstArgSpecialize + /// cloned from `made`. + public static void rewrite(Map trees, Map sources, + Map made) { + World w = build(trees); + w.made.putAll(made); + for (Map.Entry e : trees.entrySet()) { + String path = e.getKey(); + for (Stmt s : new ArrayList(e.getValue().body)) { + if (s instanceof FunctionDef) { + unrollFunction(w, path, null, (FunctionDef) s, e.getValue().body, sources); + } + } + unrollModule(w, path, e.getValue(), sources.get(path)); + } + for (List l : new ArrayList>(w.byName.values())) { + for (Cls c : l) { + for (Stmt s : new ArrayList(c.def.body)) { + if (s instanceof FunctionDef) { + unrollFunction(w, c.path, c, (FunctionDef) s, c.def.body, sources); + } + } + } + } + dropHelpers(w); + } + + /// The identifier strings `e`, an argument of a call in module `path`, + /// always evaluates to (a literal, a module constant, or a class-level + /// sequence such as `Container.cached_properties`), or null. The calls + /// in `exempt` are being specialized away, so handing the sequence to + /// them does not count as letting it escape. + static List staticSeq(Map trees, String path, Expr e, + java.util.Collection exempt) { + World w = build(trees); + w.exempt.addAll(exempt); + w.needGuard = null; + List r = names(w, path, null, null, e, false, 0); + return w.needGuard == null ? r : null; + } + + private static World build(Map trees) { + World w = new World(trees); + for (Map.Entry e : trees.entrySet()) { + collect(w, e.getKey(), e.getValue()); + } + for (List l : w.byName.values()) { + for (Cls c : l) { + for (Expr b : c.def.bases) { + String n = b instanceof Name ? ((Name) b).id : b instanceof Attribute ? ((Attribute) b).attr : null; + if (n == null) { + c.opaque = true; + c.unlinked = true; + continue; + } + Cls base = find(w, n, c.path); + if (base == AMBIGUOUS) { + c.opaque = true; + c.unlinked = true; + } else if (base != null) { + c.bases.add(base); + base.subs.add(c); + } + } + if (!c.def.keywords.isEmpty()) { + c.opaque = true; + } + } + } + for (Map.Entry e : trees.entrySet()) { + boolean meta = DeclarativeMap.META_PATH.equals(e.getKey()); + for (Stmt s : e.getValue().body) { + typeStores(w, e.getKey(), meta, null, null, s); + } + } + return w; + } + + /// Removes an options-dict helper every call of which was lowered: no + /// name, attribute, string or import anywhere spells it any more. + private static void dropHelpers(World w) { + for (Map.Entry h : w.helpers.entrySet()) { + if (!h.getValue().booleanValue()) { + continue; + } + int cut = h.getKey().lastIndexOf(':'); + String path = h.getKey().substring(0, cut); + String name = h.getKey().substring(cut + 1); + int refs = 0; + for (Map.Entry e : w.trees.entrySet()) { + refs += refsOther(e.getValue(), name, false); + } + Node.Module m = w.trees.get(path); + int defs = 0; + for (Stmt s : m.body) { + if (s instanceof FunctionDef && name.equals(((FunctionDef) s).name)) { + defs++; + } + } + // With own == false the definition and every call count, so the + // one definition is all that is left. + if (defs == 1 && refs == 1) { + for (int i = 0; i < m.body.size(); i++) { + if (m.body.get(i) instanceof FunctionDef && name.equals(((FunctionDef) m.body.get(i)).name)) { + m.body.remove(i); + break; + } + } + } + } + } + + private static final Cls AMBIGUOUS = new Cls("", null); + + private static Cls find(World w, String name, String path) { + List l = w.byName.get(name); + if (l == null || l.isEmpty()) { + return null; + } + if (l.size() == 1) { + return l.get(0); + } + Cls hit = null; + for (Cls c : l) { + if (c.path.equals(path)) { + if (hit != null) { + return AMBIGUOUS; + } + hit = c; + } + } + return hit == null ? AMBIGUOUS : hit; + } + + private static void collect(final World w, final String path, Object o) { + if (o instanceof ClassDef) { + ClassDef d = (ClassDef) o; + Cls c = new Cls(path, d); + List l = w.byName.get(d.name); + if (l == null) { + l = new ArrayList(); + w.byName.put(d.name, l); + } + l.add(c); + w.byDef.put(d, c); + } + List targets = new ArrayList(); + if (o instanceof Node.Assign) { + targets.addAll(((Node.Assign) o).targets); + } else if (o instanceof Node.AugAssign) { + targets.add(((Node.AugAssign) o).target); + } else if (o instanceof Node.AnnAssign) { + targets.add(((Node.AnnAssign) o).target); + } else if (o instanceof Node.Delete) { + targets.addAll(((Node.Delete) o).targets); + } else if (o instanceof Node.For) { + targets.add(((Node.For) o).target); + } + if (!DeclarativeMap.META_PATH.equals(path)) { + // The model metaclass only fills in what a class body left + // out, and a class under a metaclass is resolved from its own + // body alone (classAttr). + for (Expr t : targets) { + storedAttrs(w, t); + } + } + Infer.children(o, x -> collect(w, path, x)); + } + + private static void storedAttrs(final World w, Object t) { + if (t instanceof Attribute) { + // Typed by typeStores once every class is known. + return; + } + if (t instanceof Node.TupleExpr || t instanceof Node.ListExpr || t instanceof Node.Starred) { + Infer.children(t, x -> storedAttrs(w, x)); + } + } + + /// Unrolls the qualifying loops at the top level of module `m` + /// (`for name in ("sqrt", "exp"): getattr(cmath, name)(z)`). The loop + /// variable is a module global, so it must be read nowhere else at + /// module level, and it is bound to the last name afterwards, as the + /// loop would have left it. + private static void unrollModule(World w, String path, Node.Module m, String src) { + if (src == null) { + return; + } + String[] lines = src.split("\n", -1); + for (int i = 0; i < m.body.size(); i++) { + if (!(m.body.get(i) instanceof Node.For)) { + continue; + } + Node.For loop = (Node.For) m.body.get(i); + if (loop.isAsync || !(loop.target instanceof Name) || !hasCandidate(loop)) { + continue; + } + String v = ((Name) loop.target).id; + // Other module-level reads and stores of v run before or after + // the loop and see what they would have seen: the unrolled text + // ends by binding v to the last name. Only code that can run + // DURING the loop -- a function or lambda body the loop calls -- + // could observe the per-iteration value, so a deferred use of v + // (or an import binding it) refuses the loop. + if (declaresGlobal(m, v) || deferredUses(m, v, false) != 0) { + continue; + } + int endLine = lines.length; + if (i + 1 < m.body.size()) { + endLine = startLine(m.body.get(i + 1)) - 1; + } + if (loop.line < 1 || endLine < loop.line || endLine > lines.length) { + continue; + } + StringBuilder b = new StringBuilder("def _cn1_m():\n"); + for (int l = loop.line; l <= endLine; l++) { + String s = lines[l - 1]; + if (s.startsWith(" ") || s.startsWith("\t") && !s.trim().isEmpty()) { + if (s.startsWith("\t")) { + b = null; + break; + } + } + b.append(s.isEmpty() ? "" : " " + s).append('\n'); + } + if (b == null) { + continue; + } + ConstArgSpecialize.Text t = new ConstArgSpecialize.Text(b.toString(), loop.line - 1); + FunctionDef f; + try { + f = ConstArgSpecialize.parseMethod(t.src, t.line, path); + } catch (RuntimeException ex) { + continue; + } + if (f.body.size() != 1 || !ConstArgSpecialize.dump(f.body.get(0)).equals(ConstArgSpecialize.dump(loop))) { + continue; + } + List names = qualifies(w, path, null, null, f, (Node.For) f.body.get(0)); + if (names == null) { + continue; + } + String out = unrollAll(w, path, null, null, t); + if (out == null) { + continue; + } + if (!names.isEmpty()) { + out = out + (out.endsWith("\n") ? "" : "\n") + " " + v + " = '" + names.get(names.size() - 1) + "'\n"; + } + FunctionDef g; + try { + g = ConstArgSpecialize.parseMethod(out, t.line, path); + } catch (RuntimeException ex) { + continue; + } + m.body.remove(i); + m.body.addAll(i, g.body); + i += g.body.size() - 1; + } + } + + /// The first line `s` occupies, decorators included. + private static int startLine(Stmt s) { + int l = s.line; + List decs = s instanceof FunctionDef ? ((FunctionDef) s).decorators + : s instanceof ClassDef ? ((ClassDef) s).decorators : null; + if (decs != null) { + for (Expr d : decs) { + l = Math.min(l, d.line - 1); + } + } + return l; + } + + /// The reads and stores of the global `v` inside function and lambda + /// bodies (deferred code) under `o`, plus 1000 for an import binding it. + private static int deferredUses(Object o, final String v, final boolean deferred) { + if (o instanceof FunctionDef) { + FunctionDef f = (FunctionDef) o; + if ((paramNamed(f, v) || binds(f.body, v)) && !declaresGlobal(f, v)) { + return 0; + } + } + if (o instanceof Node.Alias) { + Node.Alias a = (Node.Alias) o; + String b = a.asname != null ? a.asname : a.name; + if (v.equals(b) || "*".equals(a.name)) { + return 1000; + } + } + final boolean inner = deferred || o instanceof FunctionDef || o instanceof Node.Lambda; + final int[] n = {inner && o instanceof Name && v.equals(((Name) o).id) ? 1 : 0}; + Infer.children(o, x -> n[0] += deferredUses(x, v, inner)); + return n[0]; + } + + // ---- attribute stores, by the classes they can reach ---- + + /// Types every attribute store under `o`. `cls` is the class whose body + /// directly holds the method `fn` (null elsewhere). A store whose + /// receiver is the method's own `self`/`cls`, or a program class by + /// name, reaches that class's [#family] only; one whose receiver is the + /// element variable of a loop over a typed sequence descriptor reaches + /// that element type's family and leaves the attribute [World#guarded]; + /// any other store makes the attribute non-constant everywhere. + private static void typeStores(final World w, final String path, final boolean meta, final Cls cls, + final FunctionDef fn, Object o) { + if (o instanceof ClassDef) { + Cls c = w.byDef.get(o); + for (Stmt s : ((ClassDef) o).body) { + if (s instanceof FunctionDef) { + FunctionDef d = (FunctionDef) s; + typeStores(w, path, meta, c, d, d.body); + typeStores(w, path, meta, null, fn, d.decorators); + typeStores(w, path, meta, null, fn, d.args); + } else { + typeStores(w, path, meta, null, fn, s); + } + } + typeStores(w, path, meta, null, fn, ((ClassDef) o).bases); + return; + } + if (o instanceof FunctionDef) { + FunctionDef d = (FunctionDef) o; + typeStores(w, path, meta, null, d, d.body); + typeStores(w, path, meta, null, fn, d.decorators); + typeStores(w, path, meta, null, fn, d.args); + return; + } + if (o instanceof List) { + for (Object x : (List) o) { + typeStores(w, path, meta, cls, fn, x); + } + return; + } + List targets = new ArrayList(); + if (o instanceof Node.Assign) { + targets.addAll(((Node.Assign) o).targets); + } else if (o instanceof Node.AugAssign) { + targets.add(((Node.AugAssign) o).target); + } else if (o instanceof Node.AnnAssign) { + targets.add(((Node.AnnAssign) o).target); + } else if (o instanceof Node.Delete) { + targets.addAll(((Node.Delete) o).targets); + } else if (o instanceof Node.For) { + targets.add(((Node.For) o).target); + } + if (!meta) { + for (Expr t : targets) { + storeTarget(w, path, cls, fn, t); + } + } + if (o instanceof Call && ((Call) o).func instanceof Name) { + Call c = (Call) o; + String f = ((Name) c.func).id; + if (("setattr".equals(f) || "delattr".equals(f)) && c.args.size() >= 2 + && c.args.get(1) instanceof Constant) { + store(w, path, cls, fn, c.args.get(0), ((Constant) c.args.get(1)).text); + } + } + Infer.children(o, x -> typeStores(w, path, meta, cls, fn, x)); + } + + private static void storeTarget(World w, String path, Cls cls, FunctionDef fn, Expr t) { + if (t instanceof Attribute) { + store(w, path, cls, fn, ((Attribute) t).value, ((Attribute) t).attr); + } else if (t instanceof Node.TupleExpr) { + for (Expr x : ((Node.TupleExpr) t).elts) { + storeTarget(w, path, cls, fn, x); + } + } else if (t instanceof Node.ListExpr) { + for (Expr x : ((Node.ListExpr) t).elts) { + storeTarget(w, path, cls, fn, x); + } + } else if (t instanceof Node.Starred) { + storeTarget(w, path, cls, fn, ((Node.Starred) t).value); + } + } + + private static void store(World w, String path, Cls cls, FunctionDef fn, Expr recv, String attr) { + if (w.storedAttrs.contains(attr)) { + return; + } + Set reach = null; + boolean guard = false; + if (recv instanceof Name) { + String n = ((Name) recv).id; + String self = selfName(cls, fn); + if (n.equals(self)) { + reach = family(w, cls); + } else if (fn != null && (paramNamed(fn, n) || binds(fn.body, n))) { + Set elems = sequenceElements(w, cls, fn, self, n); + if (elems != null) { + reach = new HashSet(); + for (Cls x : elems) { + Set f = family(w, x); + if (f == null) { + reach = null; + break; + } + reach.addAll(f); + } + guard = true; + } + } else if (fn == null || !declaresGlobal(fn, n)) { + Cls c = find(w, n, path); + reach = c == null || c == AMBIGUOUS ? null : family(w, c); //NOPMD CompareObjectsWithEquals - sentinel + } + } + if (reach == null) { + w.storedAttrs.add(attr); + w.blocked.remove(attr); + w.guarded.remove(attr); + return; + } + Set b = w.blocked.get(attr); + if (b == null) { + b = new HashSet(); + w.blocked.put(attr, b); + } + b.addAll(reach); + if (guard) { + w.guarded.add(attr); + } + } + + /// The name the method `fn` of `cls` receives its instance or class as, + /// or null. + private static String selfName(Cls cls, FunctionDef fn) { + if (cls == null || fn == null || fn.args.positional.isEmpty()) { + return null; + } + boolean plain = fn.decorators.isEmpty(); + boolean cm = fn.decorators.size() == 1 && fn.decorators.get(0) instanceof Name + && "classmethod".equals(((Name) fn.decorators.get(0)).id); + String n = fn.args.positional.get(0).name; + return (plain || cm) && !binds(fn.body, n) ? n : null; + } + + private static boolean paramNamed(FunctionDef fn, String n) { + final boolean[] hit = {false}; + Infer.children(fn.args, x -> hit[0] |= x instanceof Node.Arg && n.equals(((Node.Arg) x).name)); + return hit[0]; + } + + /// `c`, every class deriving from it and every ancestor of those: the + /// classes an instance of `c` (or `c` itself) can be looked up through. + /// Null when an opaque class could hide part of it. + private static Set family(World w, Cls c) { + if (c == null) { + return null; + } + Set down = new HashSet(); + List work = new ArrayList(); + work.add(c); + while (!work.isEmpty()) { + Cls k = work.remove(work.size() - 1); + if (down.add(k)) { + work.addAll(k.subs); + } + } + Set out = new HashSet(); + for (Cls d : down) { + if (!ancestors(d, out)) { + return null; + } + } + Set names = new HashSet(); + for (Cls x : out) { + names.add(x.def.name); + } + for (List l : w.byName.values()) { + for (Cls x : l) { + if (x.unlinked && !out.contains(x)) { + for (Expr b : x.def.bases) { + if (mentions(b, names)) { + return null; + } + } + } + } + } + return out; + } + + /// True when `e` spells one of `names`, as a name or an attribute: a + /// base computed by a call can only reach a family class through one. + private static boolean mentions(Object e, final Set names) { + if (e instanceof Name && names.contains(((Name) e).id) + || e instanceof Attribute && names.contains(((Attribute) e).attr)) { + return true; + } + final boolean[] hit = {false}; + Infer.children(e, x -> hit[0] |= mentions(x, names)); + return hit[0]; + } + + private static boolean ancestors(Cls c, Set out) { + if (!out.add(c)) { + return true; + } + if (c.unlinked) { + return false; + } + for (Cls b : c.bases) { + if (!ancestors(b, out)) { + return false; + } + } + return true; + } + + /// The element classes of `n` when the method's only binding of it is + /// `for n in self.F:` and every class `self` can be binds `F` to a + /// sequence descriptor naming its element type (openpyxl's `Sequence`, + /// which converts each element it is given), an empty tuple, or another + /// class's `F`. A list such a descriptor keeps can still be mutated, so + /// the claim is only trusted behind a run-time guard ([World#guarded]). + private static Set sequenceElements(World w, Cls cls, FunctionDef fn, String self, String n) { + if (self == null || paramNamed(fn, n) || count(fn, n) < 1) { + return null; + } + final Node.For[] only = {null}; + final int[] binds = {0}; + countBinds(fn.body, n, only, binds); + if (binds[0] != 1 || only[0] == null || !(only[0].iter instanceof Attribute) + || !(((Attribute) only[0].iter).value instanceof Name) + || !self.equals(((Name) ((Attribute) only[0].iter).value).id)) { + return null; + } + String f = ((Attribute) only[0].iter).attr; + Set fam = family(w, cls); + if (fam == null) { + return null; + } + Set out = new HashSet(); + for (Cls k : fam) { + if (!sequenceBinding(w, k, f, out, 0)) { + return null; + } + } + return out.isEmpty() ? null : out; + } + + private static void countBinds(Object o, String n, Node.For[] only, int[] binds) { + if (bindsHere(o, n)) { + binds[0]++; + if (o instanceof Node.For && ((Node.For) o).target instanceof Name) { + only[0] = (Node.For) o; + } else { + binds[0] += 2; + } + } + if (o instanceof Node.Global && ((Node.Global) o).names.contains(n)) { + binds[0] += 2; + } + if (o instanceof Node.Comp) { + return; + } + Infer.children(o, x -> countBinds(x, n, only, binds)); + } + + private static boolean sequenceBinding(World w, Cls k, String f, Set out, int depth) { + if (depth > MAX_DEPTH) { + return false; + } + for (Stmt s : k.def.body) { + if (!bindsHere(s, f)) { + continue; + } + if (!(s instanceof Node.Assign) || ((Node.Assign) s).targets.size() != 1 + || !(((Node.Assign) s).targets.get(0) instanceof Name)) { + return false; + } + Expr v = ((Node.Assign) s).value; + if (v instanceof Node.TupleExpr && ((Node.TupleExpr) v).elts.isEmpty()) { + continue; + } + if (v instanceof Attribute && ((Attribute) v).value instanceof Name && f.equals(((Attribute) v).attr)) { + Cls b = find(w, ((Name) ((Attribute) v).value).id, k.path); + if (b == null || b == AMBIGUOUS || !sequenceBinding(w, b, f, out, depth + 1)) { //NOPMD CompareObjectsWithEquals - sentinel + return false; + } + continue; + } + if (!(v instanceof Call) || !(((Call) v).func instanceof Name) + || !"Sequence".equals(((Name) ((Call) v).func).id) + || !importsFrom(w, k.path, "Sequence", "openpyxl.descriptors")) { + return false; + } + Cls e = null; + for (Node.Keyword kw : ((Call) v).keywords) { + if ("expected_type".equals(kw.arg) && kw.value instanceof Name) { + e = find(w, ((Name) kw.value).id, k.path); + } + } + if (e == null || e == AMBIGUOUS) { //NOPMD CompareObjectsWithEquals - sentinel + return false; + } + out.add(e); + } + return true; + } + + /// True when module `path` binds `name` at top level only through + /// `from import name`. + private static boolean importsFrom(World w, String path, String name, String pkg) { + Node.Module m = w.trees.get(path); + if (m == null) { + return false; + } + boolean hit = false; + for (Stmt s : m.body) { + if (s instanceof Node.ImportFrom) { + Node.ImportFrom f = (Node.ImportFrom) s; + for (Node.Alias a : f.names) { + if (name.equals(a.asname != null ? a.asname : a.name)) { + if (f.level != 0 || f.module == null || !(f.module.equals(pkg) || f.module.startsWith(pkg + "."))) { + return false; + } + hit = true; + } + } + } else if (binds(s, name)) { + return false; + } + } + return hit; + } + + /// The line an unrolled loop over the receiver's `attr` starts with: + /// the names were read from the class, and an instance may hold its + /// own tuple, so a different one stops the method loudly rather than + /// running the class's copies. + private static String guardText(String recv, String attr, List names) { + StringBuilder b = new StringBuilder("if ").append(recv).append('.').append(attr).append(" != ("); + for (String n : names) { + b.append('\'').append(n).append("', "); + } + return b.append("): raise TypeError('").append(attr) + .append(" differs from the class tuple the loop was unrolled for')").toString(); + } + + // ---- the method ---- + + private static void unrollFunction(World w, String path, Cls owner, FunctionDef f, List body, + Map sources) { + if (f.isAsync || !hasCandidate(f)) { + return; + } + String recv = null; + if (owner != null && !f.args.positional.isEmpty()) { + boolean plain = f.decorators.isEmpty(); + boolean cm = f.decorators.size() == 1 && f.decorators.get(0) instanceof Name + && "classmethod".equals(((Name) f.decorators.get(0)).id); + if ((plain || cm) && !binds(f.body, f.args.positional.get(0).name)) { + recv = f.args.positional.get(0).name; + } + } + ConstArgSpecialize.Text t = w.made.get(f); + if (t == null) { + t = ConstArgSpecialize.extract(sources.get(path), f); + } + if (t == null || !ConstArgSpecialize.dump(f).equals( + ConstArgSpecialize.dump(ConstArgSpecialize.parseMethod(t.src, t.line, path)))) { + return; + } + String own = unrollAll(w, path, owner, recv, t); + if (own == null) { + return; + } + Map copies = new LinkedHashMap(); + if (owner != null && recv != null) { + Set needs = new HashSet(); + List order = descendants(owner); + if (order == null) { + return; + } + for (Cls k : order) { + String tk = unrollAll(w, path, k, recv, t); + if (tk == null) { + return; + } + boolean overridden = overridesBetween(k, owner, f.name); + boolean inheritsCopy = false; + for (Cls b : k.bases) { + if (needs.contains(b)) { + inheritsCopy = true; + } + } + if (overridden) { + // Reached only through super(): the text must not depend on the class. + if (!tk.equals(own)) { + return; + } + continue; + } + if (!tk.equals(own) || inheritsCopy) { + if (!copyable(tk) || !k.path.equals(path) && !portable(w, path, k.path, tk)) { + return; + } + needs.add(k); + copies.put(k, tk); + } + } + } + int at = indexOf(body, f); + body.set(at, ConstArgSpecialize.parseMethod(own, t.line, path)); + for (Map.Entry e : copies.entrySet()) { + e.getKey().def.body.add(ConstArgSpecialize.parseMethod(e.getValue(), t.line, path)); + } + } + + /// Every program subclass of `c`, each after all of its bases that are + /// themselves subclasses of `c`; null when one cannot be classified. + private static List descendants(Cls c) { + Set all = new HashSet(); + List work = new ArrayList(c.subs); + while (!work.isEmpty()) { + Cls k = work.remove(work.size() - 1); + if (k.opaque) { + return null; + } + if (all.add(k)) { + work.addAll(k.subs); + } + } + List order = new ArrayList(); + Set done = new HashSet(); + done.add(c); + while (order.size() < all.size()) { + boolean moved = false; + for (Cls k : all) { + if (done.contains(k)) { + continue; + } + boolean ready = true; + for (Cls b : k.bases) { + if (all.contains(b) && !done.contains(b)) { + ready = false; + } + } + if (ready) { + order.add(k); + done.add(k); + moved = true; + } + } + if (!moved) { + return null; + } + } + return order; + } + + /// True when `k` or a class between it and `top` defines `name`. + private static boolean overridesBetween(Cls k, Cls top, String name) { + if (k == top) { //NOPMD CompareObjectsWithEquals - identity is meant + return false; + } + if (defines(k.def, name)) { + return true; + } + for (Cls b : k.bases) { + if (derives(b, top) && overridesBetween(b, top, name)) { + return true; + } + } + return false; + } + + private static boolean derives(Cls k, Cls top) { + if (k == top) { //NOPMD CompareObjectsWithEquals - identity is meant + return true; + } + for (Cls b : k.bases) { + if (derives(b, top)) { + return true; + } + } + return false; + } + + private static boolean defines(ClassDef d, String name) { + for (Stmt s : d.body) { + if (s instanceof FunctionDef && name.equals(((FunctionDef) s).name)) { + return true; + } + if (s instanceof Node.Assign) { + for (Expr t : ((Node.Assign) s).targets) { + if (t instanceof Name && name.equals(((Name) t).id)) { + return true; + } + } + } + } + return false; + } + + /// A copy placed in another class must mean the same there. + private static boolean copyable(String src) { + for (Token k : new Lexer(src, "").tokenize()) { + if (k.kind == Token.Kind.NAME && ("super".equals(k.text) || "__class__".equals(k.text) + || k.text.startsWith("__") && !k.text.endsWith("__"))) { + return false; + } + } + return true; + } + + private static int indexOf(List body, Stmt s) { + for (int i = 0; i < body.size(); i++) { + if (body.get(i) == s) { //NOPMD CompareObjectsWithEquals - identity is meant + return i; + } + } + throw new IllegalStateException("function not in its body"); + } + + private static boolean hasCandidate(Object o) { + if (o instanceof Node.For && ((Node.For) o).target instanceof Name + && namesAttribute(((Node.For) o).body, ((Name) ((Node.For) o).target).id)) { + return true; + } + if (compCandidate(o) || o instanceof Call && ((Call) o).func instanceof Name + && ((Call) o).args.size() == 1 && ((Call) o).keywords.isEmpty()) { + // A one-argument call might be an options-dict helper (findOptionsDict). + return true; + } + final boolean[] found = {false}; + Infer.children(o, x -> { + if (!found[0] && hasCandidate(x)) { + found[0] = true; + } + }); + return found[0]; + } + + /// `t` with every qualifying loop unrolled for receiver class `k`, or + /// null when nothing qualifies. + private static String unrollAll(World w, String path, Cls k, String recv, ConstArgSpecialize.Text t) { + String src = t.src; + boolean any = false; + for (int pass = 0; pass < MAX_PASSES; pass++) { + FunctionDef f = ConstArgSpecialize.parseMethod(src, t.line, path); + Object[] hit = new Object[3]; + findLoop(w, path, k, recv, f, f, hit); + if (hit[0] == null) { + findComp(w, path, k, recv, f, f, hit); + if (hit[0] == null) { + findOptionsDict(w, path, k, recv, f, f, hit); + if (hit[0] == null) { + break; + } + @SuppressWarnings("unchecked") + List keys = (List) hit[1]; + String dnext = optionsDictText(src, t.line, (Call) hit[0], keys); + if (dnext == null) { + break; + } + src = dnext; + any = true; + continue; + } + @SuppressWarnings("unchecked") + List cn = (List) hit[1]; + String cnext = compText(src, t.line, (Node.Comp) hit[0], cn, (String) hit[2]); + if (cnext == null) { + break; + } + src = cnext; + any = true; + continue; + } + @SuppressWarnings("unchecked") + List names = (List) hit[1]; + String next = unrollText(src, t.line, (Node.For) hit[0], names, (String) hit[2]); + if (next == null) { + break; + } + src = next; + any = true; + } + return any ? src : null; + } + + /// Whether `o` is a list comprehension over one plain name whose element + /// names an attribute by it: `[getattr(self, a) for a in self.__attrs__]`. + private static boolean compCandidate(Object o) { + if (!(o instanceof Node.Comp)) { + return false; + } + Node.Comp c = (Node.Comp) o; + if (c.kind != Node.Comp.Kind.LIST || c.generators.size() != 1) { + return false; + } + Node.Comprehension g = c.generators.get(0); + return !g.isAsync && g.ifs.isEmpty() && g.target instanceof Name + && namesAttribute(c.elt, ((Name) g.target).id); + } + + /// Finds a list comprehension [#compCandidate] whose iterable is a known + /// sequence of names. It becomes a list display with one element per + /// name: the iterable is evaluated first in both forms and is free of + /// effects ([#names] accepts only literals and constant tuples), the + /// elements are then evaluated in the same order, and the comprehension + /// variable is local to the comprehension, so nothing outside can see + /// that it is gone. A guarded receiver, a closure or comprehension over + /// the variable, or a walrus binding it is refused. + private static void findComp(final World w, final String path, final Cls k, final String recv, + final FunctionDef f, Object o, final Object[] hit) { + if (hit[0] != null) { + return; + } + if (compCandidate(o)) { + Node.Comp c = (Node.Comp) o; + String v = ((Name) c.generators.get(0).target).id; + if (!badUse(c.elt, v)) { + w.needGuard = null; + List names = names(w, path, k, recv, c.generators.get(0).iter, true, 0); + String guard = null; + if (names != null && w.needGuard != null) { + guard = compGuard(w, path, k, recv, c.generators.get(0).iter, w.needGuard); + } + if (names != null && (w.needGuard == null || guard != null)) { + hit[0] = c; + hit[1] = names; + hit[2] = guard; + w.needGuard = null; + return; + } + w.needGuard = null; + } + } + if (o instanceof Node.Lambda || o instanceof ClassDef + || o instanceof FunctionDef && o != f) { //NOPMD CompareObjectsWithEquals - identity is meant + return; + } + Infer.children(o, x -> findComp(w, path, k, recv, f, x, hit)); + } + + /// The run-time guard for the operand `self.` of a `+` chain + /// `e` whose names were inferred from a typed descriptor, or null. + private static String compGuard(World w, String path, Cls k, String recv, Expr e, String attr) { + List ops = new ArrayList(); + Expr x = e; + while (x instanceof Node.BinOp && "+".equals(((Node.BinOp) x).op)) { + ops.add(0, ((Node.BinOp) x).right); + x = ((Node.BinOp) x).left; + } + ops.add(0, x); + String out = null; + for (Expr op : ops) { + if (op instanceof Attribute && ((Attribute) op).value instanceof Name + && recv != null && recv.equals(((Name) ((Attribute) op).value).id) + && attr.equals(((Attribute) op).attr)) { + if (out != null) { + return null; + } + w.needGuard = null; + List part = names(w, path, k, recv, op, true, 0); + if (part == null || !attr.equals(w.needGuard)) { + return null; + } + out = guardText(recv, attr, part); + } + } + w.needGuard = attr; + return out; + } + + /// `src` with the one-line comprehension `comp` written as a list + /// display of its element once per name, or null. + private static String compText(String src, int line0, Node.Comp comp, List names, String guard) { + String v = ((Name) comp.generators.get(0).target).id; + List toks = new Lexer(src, "").tokenize(); + int rel = comp.line - line0 + 1; + int open = -1; + int forAt = -1; + int close = -1; + for (int i = 0; i < toks.size(); i++) { + Token k = toks.get(i); + if (k.line != rel || !k.is("[")) { + continue; + } + int depth = 0; + int fa = -1; + int cl = -1; + for (int j = i; j < toks.size(); j++) { + Token q = toks.get(j); + if (q.is("[") || q.is("(") || q.is("{")) { + depth++; + } else if (q.is("]") || q.is(")") || q.is("}")) { + depth--; + if (depth == 0) { + cl = j; + break; + } + } else if (depth == 1 && q.is("for")) { + if (fa >= 0) { + fa = -2; + } else { + fa = j; + } + } + } + if (fa >= 0 && cl > 0 && toks.get(fa + 1).kind == Token.Kind.NAME && toks.get(fa + 1).text.equals(v) + && toks.get(fa + 2).is("in")) { + if (open >= 0) { + // Two candidates on one line: which one the tree means is unknown. + return null; + } + open = i; + forAt = fa; + close = cl; + } + } + if (open < 0 || toks.get(close).line != rel || forAt == open + 1) { + return null; + } + int[] starts = ConstArgSpecialize.lineStarts(src); + int eltStart = ConstArgSpecialize.off(starts, toks.get(open + 1)); + int eltEnd = ConstArgSpecialize.off(starts, toks.get(forAt)); + StringBuilder disp = new StringBuilder("["); + for (int n = 0; n < names.size(); n++) { + StringBuilder b = new StringBuilder(src.substring(eltStart, eltEnd)); + int base = eltStart; + for (int i = forAt - 1; i > open; i--) { + Token k = toks.get(i); + if (k.kind == Token.Kind.STRING && (k.prefix != null && k.prefix.indexOf('f') >= 0 + && k.text.contains(v) || ConstArgSpecialize.count(k.text, '\n') > 0)) { + return null; + } + if (k.kind != Token.Kind.NAME || !k.text.equals(v) || toks.get(i - 1).is(".")) { + continue; + } + if (toks.get(i + 1).is("=")) { + return null; + } + int o = ConstArgSpecialize.off(starts, k) - base; + b.replace(o, o + v.length(), "\"" + names.get(n) + "\""); + } + if (n > 0) { + disp.append(", "); + } + disp.append(b); + } + disp.append(']'); + int s0 = ConstArgSpecialize.off(starts, toks.get(open)); + int s1 = ConstArgSpecialize.off(starts, toks.get(close)) + 1; + if (guard != null) { + // Only `name = [...]` as a whole statement: nothing of the + // statement runs between the guard and the comprehension. + if (open < 3 || !toks.get(open - 1).is("=") || toks.get(open - 2).kind != Token.Kind.NAME + || toks.get(open - 2).line != rel + || toks.get(open - 3).kind != Token.Kind.NEWLINE && toks.get(open - 3).kind != Token.Kind.INDENT + && toks.get(open - 3).kind != Token.Kind.DEDENT + || close + 1 >= toks.size() || toks.get(close + 1).kind != Token.Kind.NEWLINE) { + return null; + } + int ls = ConstArgSpecialize.off(starts, toks.get(open - 2)); + int lineStart = starts[rel - 1]; + String ind = src.substring(lineStart, ls); + if (!ind.trim().isEmpty()) { + return null; + } + return src.substring(0, ls) + guard + "\n" + ind + src.substring(ls, s0) + disp + src.substring(s1); + } + return src.substring(0, s0) + disp + src.substring(s1); + } + + // ---- options classes read as a dict ---- + + /// markdownify collects its options from nested classes: + /// + /// ```python + /// def _todict(obj): + /// return dict((k, getattr(obj, k)) for k in dir(obj) if not k.startswith('_')) + /// ... + /// self.options = _todict(self.DefaultOptions) + /// ``` + /// + /// When the helper has exactly that shape, nothing references it but + /// one-argument calls in its own module, and the argument is `self.N` or + /// a module class `N` where `N` resolves, for the receiver class this + /// copy is made for, to a nested class whose body (and its nested base + /// chain) binds plain names only, the call becomes the dict display + /// `{"a": X.a, "b": X.b}` with the public names in `dir()` order + /// (sorted). The values are still read at run time from the class, so + /// only the key set is fixed at build time; it is refused when any of + /// the names, or `N` itself, is stored anywhere a store can reach these + /// classes, or when the classes involve a metaclass or decorator. + private static void findOptionsDict(final World w, final String path, final Cls k, final String recv, + final FunctionDef f, Object o, final Object[] hit) { + if (hit[0] != null) { + return; + } + if (o instanceof Call && ((Call) o).func instanceof Name && ((Call) o).args.size() == 1 + && ((Call) o).keywords.isEmpty() && isOptionsHelper(w, path, ((Name) ((Call) o).func).id)) { + List keys = optionKeys(w, k, recv, ((Call) o).args.get(0)); + if (keys != null) { + hit[0] = o; + hit[1] = keys; + return; + } + } + if (o instanceof Node.Lambda || o instanceof ClassDef + || o instanceof FunctionDef && o != f) { //NOPMD CompareObjectsWithEquals - identity is meant + return; + } + Infer.children(o, x -> findOptionsDict(w, path, k, recv, f, x, hit)); + } + + /// Whether `name` is a module-level function of `path` with the exact + /// shape [#findOptionsDict] reads, referenced only by one-argument calls + /// in that module. + private static boolean isOptionsHelper(World w, String path, String name) { + String key = path + ":" + name; + Boolean b = w.helpers.get(key); + if (b == null) { + b = Boolean.valueOf(helperShape(w, path, name)); + w.helpers.put(key, b); + } + return b.booleanValue(); + } + + private static boolean helperShape(World w, String path, String name) { + Node.Module m = w.trees.get(path); + if (m == null || declaresGlobal(m, name)) { + return false; + } + FunctionDef def = null; + for (Stmt s : m.body) { + if (s instanceof FunctionDef && name.equals(((FunctionDef) s).name)) { + if (def != null) { + return false; + } + def = (FunctionDef) s; + } else if (binds(s, name)) { + return false; + } + } + if (def == null || def.isAsync || !def.decorators.isEmpty() || def.args.positional.size() != 1 + || !def.args.defaults.isEmpty() || def.args.vararg != null || !def.args.kwonly.isEmpty() + || def.args.kwarg != null || def.body.size() != 1 || !(def.body.get(0) instanceof Node.Return)) { + return false; + } + Expr r = ((Node.Return) def.body.get(0)).value; + if (!(r instanceof Call) || ((Call) r).args.size() != 1 || !(((Call) r).args.get(0) instanceof Node.Comp)) { + return false; + } + Node.Comp c = (Node.Comp) ((Call) r).args.get(0); + if (c.generators.size() != 1 || !(c.generators.get(0).target instanceof Name)) { + return false; + } + String p = def.args.positional.get(0).name; + String v = ((Name) c.generators.get(0).target).id; + if (p.equals(v) || "dict".equals(p) || "dir".equals(p) || "getattr".equals(p) + || "dict".equals(v) || "dir".equals(v) || "getattr".equals(v)) { + return false; + } + String tmpl = "def " + name + "(" + p + "):\n return dict((" + v + ", getattr(" + p + ", " + v + + ")) for " + v + " in dir(" + p + ") if not " + v + ".startswith('_'))\n"; + FunctionDef want; + try { + want = ConstArgSpecialize.parseMethod(tmpl, def.line, path); + } catch (RuntimeException e) { //NOPMD AvoidCatchingGenericException - an unparsable template is no match + return false; + } + if (want == null || !ConstArgSpecialize.dump(want).equals(ConstArgSpecialize.dump(def))) { + return false; + } + // The builtins it calls must be the builtins. + for (Stmt s : m.body) { + if (binds(s, "dict") || binds(s, "dir") || binds(s, "getattr")) { + return false; + } + } + // Every reference is a direct one-argument call in this module. + for (Map.Entry e : w.trees.entrySet()) { + int refs = refsOther(e.getValue(), name, e.getKey().equals(path)); + if (refs != 0) { + return false; + } + } + return true; + } + + /// References of `name` other than a one-argument call (in its own + /// module) or its own definition. + private static int refsOther(Object o, final String name, final boolean own) { + if (o instanceof Call && ((Call) o).func instanceof Name && name.equals(((Name) ((Call) o).func).id)) { + Call c = (Call) o; + int n = own && c.args.size() == 1 && c.keywords.isEmpty() ? 0 : 1; + for (Expr a : c.args) { + n += refsOther(a, name, own); + } + for (Node.Keyword kw : c.keywords) { + n += refsOther(kw, name, own); + } + return n; + } + if (o instanceof Name && name.equals(((Name) o).id) + || o instanceof Attribute && name.equals(((Attribute) o).attr) + || o instanceof Constant && ((Constant) o).kind == Constant.Kind.STR && name.equals(((Constant) o).text) + || o instanceof Node.Alias && (name.equals(((Node.Alias) o).name) + || name.equals(((Node.Alias) o).asname)) + || o instanceof FunctionDef && name.equals(((FunctionDef) o).name) && !own) { + return 1; + } + final int[] n = {0}; + Infer.children(o, x -> n[0] += refsOther(x, name, own)); + return n[0]; + } + + /// The sorted public names the options class `arg` evaluates to binds, + /// or null. + private static List optionKeys(World w, Cls k, String recv, Expr arg) { + Cls holder; + String n; + if (arg instanceof Attribute && ((Attribute) arg).value instanceof Name && recv != null + && recv.equals(((Name) ((Attribute) arg).value).id) && k != null) { + holder = k; + n = ((Attribute) arg).attr; + } else { + return null; + } + ClassDef[] found = new ClassDef[2]; + if (!nestedClass(holder, n, found, 0)) { + return null; + } + List keys = new ArrayList(); + Set chain = new HashSet(); + if (!classKeys(w, found[1], found[0], keys, chain, 0)) { + return null; + } + Set uniq = new java.util.TreeSet(keys); + if (uniq.size() != keys.size()) { + // A name rebound down the chain: dir() lists it once, as here, + // but keep to the plain case. + return null; + } + // The key set is fixed only if nothing can store into or delete from + // these class objects: each is reachable by name only as a helper + // argument `X.N` or as a nested base, never stored, passed or spelled. + for (Cls c : chain) { + for (Map.Entry e : w.trees.entrySet()) { + if (classEscapes(w, e.getKey(), e.getValue(), c.def.name)) { + return null; + } + } + } + return new ArrayList(uniq); + } + + /// Whether the name `n` occurs in module `o` other than as the class + /// definition itself, a base of a class definition, or the attribute of + /// the sole argument of an options-dict helper call. + private static boolean classEscapes(final World w, final String path, Object o, final String n) { + if (o instanceof Call && ((Call) o).func instanceof Name && ((Call) o).args.size() == 1 + && ((Call) o).keywords.isEmpty() && ((Call) o).args.get(0) instanceof Attribute + && ((Attribute) ((Call) o).args.get(0)).value instanceof Name + && n.equals(((Attribute) ((Call) o).args.get(0)).attr) + && isOptionsHelper(w, path, ((Name) ((Call) o).func).id)) { + return false; + } + if (o instanceof ClassDef) { + ClassDef d = (ClassDef) o; + for (Expr b : d.bases) { + if (!(b instanceof Name) && classEscapes(w, path, b, n)) { + return true; + } + } + for (Expr x : d.decorators) { + if (classEscapes(w, path, x, n)) { + return true; + } + } + for (Node.Keyword kw : d.keywords) { + if (classEscapes(w, path, kw, n)) { + return true; + } + } + for (Stmt s : d.body) { + if (classEscapes(w, path, s, n)) { + return true; + } + } + return false; + } + if (o instanceof Name && n.equals(((Name) o).id) + || o instanceof Attribute && n.equals(((Attribute) o).attr) + || o instanceof Constant && ((Constant) o).kind == Constant.Kind.STR && n.equals(((Constant) o).text) + || o instanceof Node.Alias && (n.equals(((Node.Alias) o).name) || n.equals(((Node.Alias) o).asname)) + || o instanceof FunctionDef && n.equals(((FunctionDef) o).name)) { + return true; + } + final boolean[] found = {false}; + Infer.children(o, x -> { + if (!found[0] && classEscapes(w, path, x, n)) { + found[0] = true; + } + }); + return found[0]; + } + + /// Finds the nested class `n` that class `k` (or a base, through single + /// inheritance) defines: found[0] the nested class, found[1] the class + /// whose body holds it. + private static boolean nestedClass(Cls k, String n, ClassDef[] found, int depth) { + if (depth > MAX_DEPTH || k.opaque || hasMeta(k, 0) || !k.def.decorators.isEmpty()) { + return false; + } + for (Stmt s : k.def.body) { + if (s instanceof ClassDef && n.equals(((ClassDef) s).name)) { + if (found[0] != null) { + return false; + } + found[0] = (ClassDef) s; + found[1] = k.def; + } else if (s instanceof FunctionDef && n.equals(((FunctionDef) s).name) + || !(s instanceof FunctionDef) && !(s instanceof ClassDef) && binds(s, n)) { + return false; + } + } + if (found[0] != null) { + return true; + } + int declared = 0; + for (Expr b : k.def.bases) { + if (!(b instanceof Name && "object".equals(((Name) b).id))) { + declared++; + } + } + if (declared != k.bases.size() || k.bases.size() != 1) { + return false; + } + return nestedClass(k.bases.get(0), n, found, depth + 1); + } + + /// Adds the names nested class `d` (held in `outer`) and its nested base + /// chain bind; false when anything else is in a body. + private static boolean classKeys(World w, ClassDef outer, ClassDef d, List keys, Set chain, + int depth) { + if (depth > MAX_DEPTH || !d.decorators.isEmpty() || !d.keywords.isEmpty() || d.bases.size() > 1) { + return false; + } + Cls dc = w.byDef.get(d); + if (dc == null || dc.unlinked) { + return false; + } + chain.add(dc); + for (Stmt s : d.body) { + if (s instanceof Node.Pass) { + continue; + } + if (s instanceof Node.ExprStmt && ((Node.ExprStmt) s).value instanceof Constant) { + continue; + } + if (s instanceof Node.Assign && ((Node.Assign) s).targets.size() == 1 + && ((Node.Assign) s).targets.get(0) instanceof Name) { + String key = ((Name) ((Node.Assign) s).targets.get(0)).id; + if (!key.startsWith("_")) { + // The helper drops the private names. + keys.add(key); + } + } else { + return false; + } + } + if (d.bases.isEmpty() || d.bases.get(0) instanceof Name && "object".equals(((Name) d.bases.get(0)).id)) { + return true; + } + if (!(d.bases.get(0) instanceof Name)) { + return false; + } + String bn = ((Name) d.bases.get(0)).id; + ClassDef base = null; + for (Stmt s : outer.body) { + if (s instanceof ClassDef && bn.equals(((ClassDef) s).name)) { + if (base != null) { + return false; + } + base = (ClassDef) s; + } else if (!(s instanceof FunctionDef) && binds(s, bn)) { + return false; + } + } + if (base == null || base == d || dc.bases.size() != 1 //NOPMD CompareObjectsWithEquals - identity is meant + || dc.bases.get(0).def != base) { //NOPMD CompareObjectsWithEquals - identity is meant + return false; + } + return classKeys(w, outer, base, keys, chain, depth + 1); + } + + /// `src` with the one-line call `call` written as a dict display. + private static String optionsDictText(String src, int line0, Call call, List keys) { + String fn = ((Name) call.func).id; + List toks = new Lexer(src, "").tokenize(); + int rel = call.line - line0 + 1; + int at = -1; + int close = -1; + for (int i = 0; i + 1 < toks.size(); i++) { + Token k = toks.get(i); + if (k.line != rel || k.kind != Token.Kind.NAME || !k.text.equals(fn) || !toks.get(i + 1).is("(") + || i > 0 && toks.get(i - 1).is(".")) { + continue; + } + if (at >= 0) { + return null; + } + int depth = 0; + for (int j = i + 1; j < toks.size(); j++) { + Token q = toks.get(j); + if (q.is("[") || q.is("(") || q.is("{")) { + depth++; + } else if (q.is("]") || q.is(")") || q.is("}")) { + depth--; + if (depth == 0) { + close = j; + break; + } + } + } + at = i; + } + if (at < 0 || close < 0 || toks.get(close).line != rel) { + return null; + } + int[] starts = ConstArgSpecialize.lineStarts(src); + int s0 = ConstArgSpecialize.off(starts, toks.get(at)); + int a0 = ConstArgSpecialize.off(starts, toks.get(at + 2)); + int s1 = ConstArgSpecialize.off(starts, toks.get(close)); + String arg = src.substring(a0, s1).trim(); + StringBuilder d = new StringBuilder("{"); + for (int i = 0; i < keys.size(); i++) { + if (i > 0) { + d.append(", "); + } + d.append('"').append(keys.get(i)).append("\": ").append(arg).append('.').append(keys.get(i)); + } + d.append('}'); + return src.substring(0, s0) + d + src.substring(s1 + 1); + } + + private static void findLoop(final World w, final String path, final Cls k, final String recv, + final FunctionDef f, Object o, final Object[] hit) { + if (hit[0] != null) { + return; + } + if (o instanceof Node.For) { + Node.For loop = (Node.For) o; + List names = qualifies(w, path, k, recv, f, loop); + if (names != null) { + hit[0] = loop; + hit[1] = names; + hit[2] = w.needGuard == null ? null + : guardText(((Name) ((Attribute) loop.iter).value).id, w.needGuard, names); + return; + } + } + if (o instanceof Node.Lambda || o instanceof ClassDef + || o instanceof FunctionDef && o != f) { //NOPMD CompareObjectsWithEquals - identity is meant + return; + } + Infer.children(o, x -> findLoop(w, path, k, recv, f, x, hit)); + } + + private static List qualifies(World w, String path, Cls k, String recv, FunctionDef f, Node.For loop) { + w.needGuard = null; + if (loop.isAsync || !loop.orelse.isEmpty() || !(loop.target instanceof Name)) { + return null; + } + String v = ((Name) loop.target).id; + if (!namesAttribute(loop.body, v) || ownJump(loop.body, true) || badUse(loop.body, v)) { + return null; + } + if (count(f, v) != count(loop.body, v) + 1) { + return null; + } + if (loop.iter instanceof Name) { + List local = localConst(w, path, k, recv, f, ((Name) loop.iter).id); + if (local != null) { + return local; + } + } + w.needGuard = null; + List out = names(w, path, k, recv, loop.iter, true, 0); + if (out != null && w.needGuard != null && !(loop.iter instanceof Attribute + && ((Attribute) loop.iter).value instanceof Name && ((Attribute) loop.iter).attr.equals(w.needGuard))) { + return null; + } + return out; + } + + /// The names a function local evaluates to when the function binds it + /// exactly once, at the top of its body, to a literal list or tuple of + /// identifiers, and reads it nowhere but as the loop's iterable + /// (`names = ['top', 'left']` then `for name in names:`). Nothing else + /// can reach the local, so the literal is the only value it holds. + private static List localConst(World w, String path, Cls k, String recv, FunctionDef f, String n) { + if (count(f, n) != 2 || declaresGlobal(f, n)) { + return null; + } + for (Stmt s : f.body) { + if (s instanceof Node.Assign && ((Node.Assign) s).targets.size() == 1 + && ((Node.Assign) s).targets.get(0) instanceof Name + && n.equals(((Name) ((Node.Assign) s).targets.get(0)).id)) { + Expr v = fold(((Node.Assign) s).value); + if (v instanceof Node.Attribute && w != null) { + // `props = self.cached_properties`: a class-level + // sequence, resolved per class as the loop's own would be. + w.needGuard = null; + List r = names(w, path, k, recv, v, false, 0); + return w.needGuard == null ? r : null; + } + if (!(v instanceof Node.TupleExpr || v instanceof Node.ListExpr)) { + return null; + } + return names(null, null, null, null, v, true, 0); + } + } + return null; + } + + /// The names `e` evaluates to, every one an identifier, or null. + private static List names(World w, String path, Cls k, String recv, Expr e, boolean inline, int depth) { + if (depth > MAX_DEPTH) { + return null; + } + if (e instanceof Node.TupleExpr || inline && e instanceof Node.ListExpr) { + List elts = e instanceof Node.TupleExpr ? ((Node.TupleExpr) e).elts : ((Node.ListExpr) e).elts; + List out = new ArrayList(); + for (Expr x : elts) { + if (!(x instanceof Constant) || ((Constant) x).kind != Constant.Kind.STR + || !ConstArgSpecialize.ident(((Constant) x).text)) { + return null; + } + out.add(((Constant) x).text); + } + return out; + } + if (e instanceof Node.BinOp && "+".equals(((Node.BinOp) e).op)) { + // `+` makes a new sequence: an operand literal is as private as + // the result is. + List a = names(w, path, k, recv, ((Node.BinOp) e).left, inline, depth + 1); + List b = a == null ? null : names(w, path, k, recv, ((Node.BinOp) e).right, inline, depth + 1); + if (b == null) { + return null; + } + List out = new ArrayList(a); + out.addAll(b); + return out; + } + if (e instanceof Attribute && ((Attribute) e).value instanceof Name) { + String base = ((Name) ((Attribute) e).value).id; + String attr = ((Attribute) e).attr; + if (w.storedAttrs.contains(attr)) { + return null; + } + Set blocked = w.blocked.get(attr); + if (recv != null && recv.equals(base)) { + if (k == null || blocked != null && blocked.contains(k)) { + return null; + } + if (w.guarded.contains(attr)) { + w.needGuard = attr; + } + return classAttr(w, k, attr, depth + 1); + } + Cls c = find(w, base, path); + if (c == null || c == AMBIGUOUS || blocked != null && blocked.contains(c)) { + return null; + } + return classAttr(w, c, attr, depth + 1); + } + if (e instanceof Name) { + return moduleConst(w, path, ((Name) e).id, depth + 1); + } + return null; + } + + private static List moduleConst(World w, String path, String n, int depth) { + Node.Module m = w.trees.get(path); + if (m == null || declaresGlobal(m, n)) { + return null; + } + Expr value = null; + int stores = 0; + for (Stmt s : m.body) { + if (binds(s, n)) { + stores++; + if (s instanceof Node.Assign && ((Node.Assign) s).targets.size() == 1 + && ((Node.Assign) s).targets.get(0) instanceof Name) { + value = ((Node.Assign) s).value; + } else { + return null; + } + } + } + if (stores != 1 || value == null) { + return null; + } + return names(w, path, null, null, value, false, depth); + } + + private static boolean declaresGlobal(Object o, final String n) { + if (o instanceof Node.Global && ((Node.Global) o).names.contains(n)) { + return true; + } + final boolean[] found = {false}; + Infer.children(o, x -> { + if (!found[0] && declaresGlobal(x, n)) { + found[0] = true; + } + }); + return found[0]; + } + + /// `attr` looked up on class `c` as a class-level tuple, or null. + private static List classAttr(World w, Cls c, String attr, int depth) { + if (depth > MAX_DEPTH || c.opaque) { + return null; + } + Expr own = null; + int stores = 0; + for (Stmt s : c.def.body) { + if (s instanceof Node.Assign) { + for (Expr t : ((Node.Assign) s).targets) { + if (mentionsName(t, attr)) { + stores++; + own = ((Node.Assign) s).targets.size() == 1 && t instanceof Name ? ((Node.Assign) s).value + : null; + } + } + } else if (s instanceof Node.AnnAssign && ((Node.AnnAssign) s).target instanceof Name + && attr.equals(((Name) ((Node.AnnAssign) s).target).id)) { + stores++; + own = ((Node.AnnAssign) s).value; + } else if (s instanceof FunctionDef && attr.equals(((FunctionDef) s).name) + || !(s instanceof FunctionDef) && !(s instanceof Node.Assign) && !(s instanceof Node.AnnAssign) + && binds(s, attr)) { + return null; + } + } + if (stores > 1) { + return null; + } + if (stores == 1) { + return own == null ? null : classBodyNames(w, c, own, depth + 1, frozen(w, attr)); + } + List found = null; + if (c.bases.isEmpty() || hasMeta(c, 0)) { + // A metaclass computes what a class body leaves out, per class. + return null; + } + if (c.bases.size() != c.def.bases.size()) { + // A base outside the program might define it. + return null; + } + for (Cls b : c.bases) { + List r = classAttr(w, b, attr, depth + 1); + if (r == null || found != null && !found.equals(r)) { + return null; + } + found = r; + } + return found; + } + + /// An expression of a class body: names bound earlier in it resolve + /// there before the module. + private static List classBodyNames(World w, Cls c, Expr e, int depth, boolean lists) { + if (e instanceof Name && definesAttr(c.def, ((Name) e).id)) { + return classAttr(w, c, ((Name) e).id, depth); + } + if (e instanceof Node.BinOp && "+".equals(((Node.BinOp) e).op)) { + List a = classBodyNames(w, c, ((Node.BinOp) e).left, depth + 1, lists); + List b = a == null ? null : classBodyNames(w, c, ((Node.BinOp) e).right, depth + 1, lists); + if (b == null) { + return null; + } + List out = new ArrayList(a); + out.addAll(b); + return out; + } + return names(w, c.path, null, null, e, lists, depth); + } + + /// `v` with a conditional whose test compares literals to `None` by + /// identity decided (`A if None is None else None`, as + /// ConstArgSpecialize writes a defaulted parameter in); `v` itself + /// otherwise, or null when such a test cannot be decided. + private static Expr fold(Expr v) { + if (!(v instanceof Node.IfExp)) { + return v; + } + Node.IfExp x = (Node.IfExp) v; + if (!(x.test instanceof Node.Compare) || ((Node.Compare) x.test).ops.size() != 1) { + return null; + } + Node.Compare c = (Node.Compare) x.test; + String op = c.ops.get(0); + if (!"is".equals(op) && !"is not".equals(op)) { + return null; + } + Expr l = c.left; + Expr r = c.comparators.get(0); + boolean ln = isNone(l); + boolean rn = isNone(r); + if (!ln && !literalSeq(l) || !rn && !literalSeq(r) || !ln && !rn) { + return null; + } + boolean same = ln && rn; + return fold("is".equals(op) == same ? x.body : x.orelse); + } + + private static boolean isNone(Expr e) { + return e instanceof Constant && ((Constant) e).kind == Constant.Kind.NONE; + } + + private static boolean literalSeq(Expr e) { + return e instanceof Node.TupleExpr || e instanceof Node.ListExpr; + } + + /// Whether every list a class body binds to `attr` is provably never + /// mutated and never handed to code that could: whole program, every + /// read of `.attr` is a loop's iterable, an operand of `+` or of a + /// comparison, the argument of a call in [World#exempt], or (bare or + /// as a branch of a conditional) the value of a function local that is + /// read only as a loop's iterable. The attribute is never stored or + /// deleted outside its class bodies, never spelled as a string (a + /// literal `getattr`), and a class body binding it reads it nowhere + /// else. A list so used holds what its literal says, as a tuple would. + private static boolean frozen(World w, String attr) { + Boolean b = w.frozen.get(attr); + if (b == null) { + boolean[] ok = {!w.storedAttrs.contains(attr)}; + for (Node.Module m : w.trees.values()) { + for (Stmt s : m.body) { + frozenScan(w, attr, s, null, ok); + } + } + b = Boolean.valueOf(ok[0]); + w.frozen.put(attr, b); + } + return b.booleanValue(); + } + + private static boolean isRead(Object o, String attr) { + return o instanceof Attribute && attr.equals(((Attribute) o).attr); + } + + /// Scans `e`, a position where a read of `attr` is harmless: such a + /// read has only its receiver scanned. + private static void frozenSafe(World w, String attr, Expr e, FunctionDef fn, boolean[] ok) { + frozenScan(w, attr, isRead(e, attr) ? ((Attribute) e).value : e, fn, ok); + } + + private static void frozenScan(final World w, final String attr, Object o, FunctionDef fn, final boolean[] ok) { + if (!ok[0] || o == null) { + return; + } + if (o instanceof Constant && ((Constant) o).kind == Constant.Kind.STR && attr.equals(((Constant) o).text) + || isRead(o, attr)) { + ok[0] = false; + return; + } + if (o instanceof Node.For) { + Node.For f = (Node.For) o; + frozenSafe(w, attr, f.iter, fn, ok); + frozenScan(w, attr, f.target, fn, ok); + for (Stmt s : f.body) { + frozenScan(w, attr, s, fn, ok); + } + for (Stmt s : f.orelse) { + frozenScan(w, attr, s, fn, ok); + } + return; + } + if (o instanceof Node.BinOp && "+".equals(((Node.BinOp) o).op)) { + frozenSafe(w, attr, ((Node.BinOp) o).left, fn, ok); + frozenSafe(w, attr, ((Node.BinOp) o).right, fn, ok); + return; + } + if (o instanceof Node.Compare) { + frozenSafe(w, attr, ((Node.Compare) o).left, fn, ok); + for (Expr x : ((Node.Compare) o).comparators) { + frozenSafe(w, attr, x, fn, ok); + } + return; + } + if (o instanceof Call && w.exempt.contains(o)) { + frozenScan(w, attr, ((Call) o).func, fn, ok); + for (Expr x : ((Call) o).args) { + frozenSafe(w, attr, x, fn, ok); + } + for (Node.Keyword k : ((Call) o).keywords) { + frozenScan(w, attr, k, fn, ok); + } + return; + } + if (o instanceof Node.Assign && fn != null && ((Node.Assign) o).targets.size() == 1 + && ((Node.Assign) o).targets.get(0) instanceof Name + && onlyIterated(fn, ((Name) ((Node.Assign) o).targets.get(0)).id)) { + Expr v = ((Node.Assign) o).value; + if (v instanceof Node.IfExp) { + frozenScan(w, attr, ((Node.IfExp) v).test, fn, ok); + frozenSafe(w, attr, ((Node.IfExp) v).body, fn, ok); + frozenSafe(w, attr, ((Node.IfExp) v).orelse, fn, ok); + } else { + frozenSafe(w, attr, v, fn, ok); + } + return; + } + if (o instanceof ClassDef) { + for (Stmt s : ((ClassDef) o).body) { + if (s instanceof FunctionDef) { + continue; + } + Expr own = null; + if (s instanceof Node.Assign && ((Node.Assign) s).targets.size() == 1 + && ((Node.Assign) s).targets.get(0) instanceof Name + && attr.equals(((Name) ((Node.Assign) s).targets.get(0)).id)) { + own = ((Node.Assign) s).value; + } else if (s instanceof Node.AnnAssign && ((Node.AnnAssign) s).target instanceof Name + && attr.equals(((Name) ((Node.AnnAssign) s).target).id)) { + own = ((Node.AnnAssign) s).value; + } + if (own != null ? count(own, attr) > 0 : count(s, attr) > 0) { + ok[0] = false; + return; + } + } + } + final FunctionDef in = o instanceof FunctionDef ? (FunctionDef) o : fn; + Infer.children(o, x -> frozenScan(w, attr, x, in, ok)); + } + + /// Whether local `n` of `fn` is bound once and read, if at all, only + /// as the iterable of a loop. + private static boolean onlyIterated(FunctionDef fn, final String n) { + if (declaresGlobal(fn, n)) { + return false; + } + final int[] iters = {0}; + iterUses(fn, n, iters); + return count(fn, n) == 1 + iters[0] && iters[0] <= 1; + } + + private static void iterUses(Object o, final String n, final int[] iters) { + if (o instanceof Node.For && ((Node.For) o).iter instanceof Name && n.equals(((Name) ((Node.For) o).iter).id)) { + iters[0]++; + } + Infer.children(o, x -> iterUses(x, n, iters)); + } + + private static final Set PORTABLE_BUILTINS = new HashSet(java.util.Arrays.asList( + "hasattr", "delattr", "getattr", "setattr", "isinstance", "len", "None", "True", "False")); + + /// Whether `src`, a method of module `from`, means the same in module + /// `to`: it reads no name but its parameters, its own plain locals and + /// builtins neither module rebinds, and opens no nested scope. + private static boolean portable(World w, String from, String to, String src) { + FunctionDef f = ConstArgSpecialize.parseMethod(src, 1, to); + final Set local = new HashSet(); + for (Node.Arg a : f.args.positional) { + local.add(a.name); + } + if (f.args.vararg != null || f.args.kwarg != null || !f.args.kwonly.isEmpty() || !f.decorators.isEmpty()) { + return false; + } + final Set used = new HashSet(); + final boolean[] ok = {true}; + for (Stmt s : f.body) { + portableScan(s, local, used, ok); + } + if (!ok[0]) { + return false; + } + for (String n : used) { + if (local.contains(n)) { + continue; + } + if (!PORTABLE_BUILTINS.contains(n)) { + return false; + } + for (String p : new String[] {from, to}) { + Node.Module m = w.trees.get(p); + if (m == null) { + return false; + } + for (Stmt s : m.body) { + if (binds(s, n)) { + return false; + } + } + } + } + return true; + } + + private static void portableScan(Object o, final Set local, final Set used, final boolean[] ok) { + if (o instanceof Node.Lambda || o instanceof FunctionDef || o instanceof ClassDef || o instanceof Node.Comp + || o instanceof Node.Global) { + ok[0] = false; + return; + } + if (o instanceof Node.Assign) { + for (Expr t : ((Node.Assign) o).targets) { + if (t instanceof Name) { + local.add(((Name) t).id); + } + } + } else if (o instanceof Node.For && ((Node.For) o).target instanceof Name) { + local.add(((Name) ((Node.For) o).target).id); + } + if (o instanceof Name) { + used.add(((Name) o).id); + } + Infer.children(o, x -> portableScan(x, local, used, ok)); + } + + private static boolean definesAttr(ClassDef d, String n) { + for (Stmt s : d.body) { + if (!(s instanceof FunctionDef) && binds(s, n)) { + return true; + } + } + return false; + } + + private static boolean hasMeta(Cls c, int depth) { + if (depth > MAX_DEPTH || !c.def.keywords.isEmpty()) { + return true; + } + for (Cls b : c.bases) { + if (hasMeta(b, depth + 1)) { + return true; + } + } + return false; + } + + private static boolean mentionsName(Object o, String n) { + return count(o, n) > 0; + } + + /// True when `o` binds `n` in the scope it is in. + private static boolean binds(Object o, final String n) { + if (bindsHere(o, n)) { + return true; + } + if (o instanceof Node.Lambda || o instanceof FunctionDef || o instanceof ClassDef || o instanceof Node.Comp) { + return false; + } + final boolean[] found = {false}; + Infer.children(o, x -> { + if (!found[0] && binds(x, n)) { + found[0] = true; + } + }); + return found[0]; + } + + /// True when the node `o` itself binds `n`. + private static boolean bindsHere(Object o, String n) { + List targets = new ArrayList(); + if (o instanceof Node.Assign) { + targets.addAll(((Node.Assign) o).targets); + } else if (o instanceof Node.AugAssign) { + targets.add(((Node.AugAssign) o).target); + } else if (o instanceof Node.AnnAssign) { + targets.add(((Node.AnnAssign) o).target); + } else if (o instanceof Node.For) { + targets.add(((Node.For) o).target); + } else if (o instanceof Node.WithItem) { + targets.add(((Node.WithItem) o).vars); + } else if (o instanceof Node.NamedExpr) { + targets.add(((Node.NamedExpr) o).target); + } else if (o instanceof Node.Delete) { + targets.addAll(((Node.Delete) o).targets); + } else if (o instanceof Node.ExceptHandler) { + return n.equals(((Node.ExceptHandler) o).name); + } else if (o instanceof FunctionDef) { + return n.equals(((FunctionDef) o).name); + } else if (o instanceof ClassDef) { + return n.equals(((ClassDef) o).name); + } else if (o instanceof Node.Alias) { + Node.Alias a = (Node.Alias) o; + String b = a.asname != null ? a.asname : a.name; + return b != null && (n.equals(b) || b.startsWith(n + ".")); + } + for (Object t : targets) { + if (t != null && storesName(t, n)) { + return true; + } + } + return false; + } + + private static boolean storesName(Object t, final String n) { + if (t instanceof Name) { + return n.equals(((Name) t).id); + } + if (t instanceof Node.TupleExpr || t instanceof Node.ListExpr || t instanceof Node.Starred) { + final boolean[] found = {false}; + Infer.children(t, x -> { + if (!found[0] && storesName(x, n)) { + found[0] = true; + } + }); + return found[0]; + } + return false; + } + + // ---- the loop body ---- + + /// True when `p` is the name argument of a getattr/setattr/hasattr/delattr in `o`. + private static boolean namesAttribute(Object o, final String p) { + if (o instanceof Call) { + Call c = (Call) o; + if (c.func instanceof Name && c.args.size() >= 2 && foldsTo(c.args.get(1), p)) { + String n = ((Name) c.func).id; + if ("getattr".equals(n) || "setattr".equals(n) || "hasattr".equals(n) || "delattr".equals(n)) { + return true; + } + } + } + final boolean[] found = {false}; + Infer.children(o, x -> { + if (!found[0] && namesAttribute(x, p)) { + found[0] = true; + } + }); + return found[0]; + } + + /// Whether `e` is the loop variable `p`, or a pure string transform of + /// it that [#unrollText] folds to a literal once the name is written + /// in: `p.lower()`, `p.upper()`, `p + "s"` or `"s" + p`, with a plain + /// literal operand. + private static boolean foldsTo(Expr e, String p) { + if (e instanceof Name) { + return p.equals(((Name) e).id); + } + if (e instanceof Call) { + Call c = (Call) e; + return c.args.isEmpty() && c.keywords.isEmpty() && c.func instanceof Attribute + && ("lower".equals(((Attribute) c.func).attr) || "upper".equals(((Attribute) c.func).attr)) + && ((Attribute) c.func).value instanceof Name && p.equals(((Name) ((Attribute) c.func).value).id); + } + if (e instanceof Node.BinOp && "+".equals(((Node.BinOp) e).op)) { + Expr l = ((Node.BinOp) e).left; + Expr r = ((Node.BinOp) e).right; + return l instanceof Name && p.equals(((Name) l).id) && identSuffix(r) + || r instanceof Name && p.equals(((Name) r).id) && identSuffix(l); + } + return false; + } + + private static boolean identSuffix(Expr e) { + if (!(e instanceof Constant) || ((Constant) e).kind != Constant.Kind.STR) { + return false; + } + String t = ((Constant) e).text; + for (int i = 0; i < t.length(); i++) { + char ch = t.charAt(i); + if (!(ch == '_' || ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z' || ch >= '0' && ch <= '9')) { + return false; + } + } + return true; + } + + /// Whether `o` holds a `break` (with `breaks`) or a `continue` (without) + /// of the loop whose body it is: a jump inside a nested loop or scope + /// belongs to that one. A `continue` is lowered by [#unrollText]; a + /// `break` refuses the loop. + private static boolean ownJump(Object o, boolean breaks) { + if (breaks ? o instanceof Node.Break : o instanceof Node.Continue) { + return true; + } + if (o instanceof Node.For || o instanceof Node.While || o instanceof FunctionDef || o instanceof ClassDef + || o instanceof Node.Lambda) { + return false; + } + final boolean[] found = {false}; + Infer.children(o, x -> { + if (!found[0] && ownJump(x, breaks)) { + found[0] = true; + } + }); + return found[0]; + } + + /// True when `v` is rebound in `o`, or used inside a nested scope. + private static boolean badUse(Object o, final String v) { + if (eagerComp(o, v)) { + // A list, set or dict comprehension runs to completion where it + // stands, inside the iteration, so reading the loop variable in + // it sees exactly the name written in (a generator would run + // later and is refused below). + final boolean[] bad = {false}; + Infer.children(o, x -> bad[0] |= !bad[0] && badUse(x, v)); + return bad[0]; + } + if (o instanceof Node.Lambda || o instanceof FunctionDef || o instanceof ClassDef || o instanceof Node.Comp + || o instanceof Node.Global || o instanceof Node.Match) { + return count(o, v) > 0 || o instanceof Node.Global && ((Node.Global) o).names.contains(v) + || o instanceof FunctionDef && v.equals(((FunctionDef) o).name) + || o instanceof ClassDef && v.equals(((ClassDef) o).name); + } + if (bindsHere(o, v)) { + return true; + } + final boolean[] found = {false}; + Infer.children(o, x -> { + if (!found[0] && badUse(x, v)) { + found[0] = true; + } + }); + return found[0]; + } + + /// Whether `o` is a non-generator, non-async comprehension none of + /// whose targets binds `v`. + private static boolean eagerComp(Object o, String v) { + if (!(o instanceof Node.Comp) || ((Node.Comp) o).kind == Node.Comp.Kind.GENERATOR) { + return false; + } + for (Node.Comprehension g : ((Node.Comp) o).generators) { + if (g.isAsync || count(g.target, v) > 0) { + return false; + } + } + return true; + } + + private static int count(Object o, final String v) { + final int[] n = {o instanceof Name && v.equals(((Name) o).id) ? 1 : 0}; + Infer.children(o, x -> n[0] += count(x, v)); + return n[0]; + } + + // ---- the text ---- + + /// `src` with `loop` replaced by one copy of its body per name, or null. + private static String unrollText(String src, int line0, Node.For loop, List names, String guard) { + String v = ((Name) loop.target).id; + List toks = new Lexer(src, "").tokenize(); + int rel = loop.line - line0 + 1; + int start = -1; + for (int i = 1; i < toks.size(); i++) { + Token k = toks.get(i); + Token prev = toks.get(i - 1); + if (k.line == rel && k.is("for") && (prev.kind == Token.Kind.NEWLINE || prev.kind == Token.Kind.INDENT + || prev.kind == Token.Kind.DEDENT)) { + start = i; + break; + } + } + if (start < 0) { + return null; + } + // The header ends at the first NEWLINE; the body must be an indented block. + int nl = -1; + for (int i = start; i < toks.size(); i++) { + if (toks.get(i).kind == Token.Kind.NEWLINE) { + nl = i; + break; + } + } + if (nl < 0 || nl + 1 >= toks.size() || toks.get(nl + 1).kind != Token.Kind.INDENT + || !toks.get(nl - 1).is(":")) { + return null; + } + int depth = 0; + int end = -1; + int last = -1; + for (int i = nl + 1; i < toks.size(); i++) { + Token k = toks.get(i); + if (k.kind == Token.Kind.INDENT) { + depth++; + } else if (k.kind == Token.Kind.DEDENT) { + depth--; + if (depth == 0) { + end = i; + break; + } + } else if (k.kind == Token.Kind.EOF) { + end = i; + break; + } else if (k.kind != Token.Kind.NEWLINE) { + if (k.kind == Token.Kind.STRING && ConstArgSpecialize.count(k.text, '\n') > 0) { + return null; + } + if (k.kind == Token.Kind.STRING && k.prefix != null && k.prefix.indexOf('f') >= 0 + && k.text.contains(v)) { + return null; + } + last = Math.max(last, k.line); + } + } + if (end < 0 || last < 0) { + return null; + } + Token first = toks.get(nl + 2); + int forInd = toks.get(start).col - 1; + int bodyInd = first.col - 1; + int bodyFirst = first.line; + int headerLast = toks.get(nl).line; + int[] starts = ConstArgSpecialize.lineStarts(src); + String[] lines = src.split("\n", -1); + if (last > lines.length || bodyFirst <= headerLast) { + return null; + } + // Only blank and comment lines may sit between the header and the + // first statement; they are dropped from the copies. + for (int l = headerLast + 1; l < bodyFirst; l++) { + String s = lines[l - 1].trim(); + if (!s.isEmpty() && s.charAt(0) != '#') { + return null; + } + } + StringBuilder out = new StringBuilder(); + for (int l = 1; l < rel; l++) { + out.append(lines[l - 1]).append('\n'); + } + String pad = spaces(forInd); + // A `continue` skips the rest of one name's copy: each copy then runs + // as the body of a loop over one element, where `continue` means + // exactly that and nothing else changes (a `break` of the unrolled + // loop was refused, [#qualifies]). + boolean once = false; + for (Stmt s : loop.body) { + once |= ownJump(s, false); + } + String copyPad = once ? pad + " " : pad; + if (guard != null) { + out.append(pad).append(guard).append('\n'); + } + for (String name : names) { + if (once) { + out.append(pad).append("for _cn1_once in (0,):\n"); + } + StringBuilder b = new StringBuilder(src); + for (int i = end - 1; i > nl; i--) { + Token k = toks.get(i); + if (k.kind != Token.Kind.NAME || !k.text.equals(v)) { + continue; + } + if (toks.get(i - 1).is(".")) { + continue; + } + if (toks.get(i + 1).is("=")) { + // A keyword argument named like the variable. + return null; + } + int o = ConstArgSpecialize.off(starts, k); + int e = o + v.length(); + String lit = name; + // Fold the pure string transforms [#foldsTo] accepts, so the + // attribute name reaches the strict build as one literal. + if (i + 4 < end && toks.get(i + 1).is(".") && toks.get(i + 3).is("(") + && toks.get(i + 4).is(")") + && (toks.get(i + 2).is("lower") || toks.get(i + 2).is("upper"))) { + lit = asciiCase(name, toks.get(i + 2).is("upper")); + e = ConstArgSpecialize.off(starts, toks.get(i + 4)) + 1; + } else if (i + 3 < end && toks.get(i + 1).is("+") && plainString(src, starts, toks.get(i + 2)) + && concatEdge(toks.get(i - 1)) && concatEdge(toks.get(i + 3))) { + Token r = toks.get(i + 2); + int ro = ConstArgSpecialize.off(starts, r); + int re = src.indexOf(src.charAt(ro), ro + 1) + 1; + lit = name + src.substring(ro + 1, re - 1); + e = re; + } else if (i - 3 > nl && toks.get(i - 1).is("+") && plainString(src, starts, toks.get(i - 2)) + && concatEdge(toks.get(i - 3)) && concatEdge(toks.get(i + 1))) { + Token l = toks.get(i - 2); + int lo = ConstArgSpecialize.off(starts, l); + lit = src.substring(lo + 1, src.indexOf(src.charAt(lo), lo + 1)) + name; + o = lo; + i -= 2; + } + b.replace(o, e, "\"" + lit + "\""); + } + String[] sub = b.toString().split("\n", -1); + for (int l = bodyFirst; l <= last; l++) { + String s = sub[l - 1]; + if (s.trim().isEmpty()) { + out.append('\n'); + continue; + } + int lead = 0; + while (lead < s.length() && s.charAt(lead) == ' ') { + lead++; + } + if (lead < bodyInd || lead < s.length() && s.charAt(lead) == '\t') { + return null; + } + out.append(copyPad).append(s.substring(bodyInd)).append('\n'); + } + } + if (names.isEmpty()) { + out.append(pad).append("pass\n"); + } + for (int l = last + 1; l <= lines.length; l++) { + out.append(lines[l - 1]); + if (l < lines.length) { + out.append('\n'); + } + } + return out.toString(); + } + + /// Whether `t` is a one-line string literal with no prefix and no + /// escape whose text is identifier characters, as [#identSuffix] reads it. + private static boolean plainString(String src, int[] starts, Token t) { + if (t.kind != Token.Kind.STRING || t.prefix != null && !t.prefix.isEmpty()) { + return false; + } + int o = ConstArgSpecialize.off(starts, t); + char q = src.charAt(o); + if (q != '"' && q != '\'') { + return false; + } + int c = src.indexOf(q, o + 1); + if (c < 0 || c + 1 < src.length() && src.charAt(c + 1) == q && c == o + 1) { + return false; + } + for (int j = o + 1; j < c; j++) { + char ch = src.charAt(j); + if (!(ch == '_' || ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z' || ch >= '0' && ch <= '9')) { + return false; + } + } + return true; + } + + /// Whether a token beside `a + "s"` binds no tighter than `+`, so the + /// concatenation is one operand that a literal can replace. + private static boolean concatEdge(Token t) { + return t.kind == Token.Kind.NEWLINE || t.is("(") || t.is(")") || t.is(",") || t.is("[") || t.is("]") + || t.is("=") || t.is(":") || t.is("+"); + } + + /// ASCII case mapping; names are identifiers, so no locale applies. + private static String asciiCase(String s, boolean upper) { + StringBuilder b = new StringBuilder(s.length()); + for (int j = 0; j < s.length(); j++) { + char ch = s.charAt(j); + if (upper && ch >= 'a' && ch <= 'z') { + ch = (char) (ch - 32); + } else if (!upper && ch >= 'A' && ch <= 'Z') { + ch = (char) (ch + 32); + } + b.append(ch); + } + return b.toString(); + } + + private static String spaces(int n) { + StringBuilder b = new StringBuilder(); + for (int i = 0; i < n; i++) { + b.append(' '); + } + return b.toString(); + } +} diff --git a/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/NamedStyleLowering.java b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/NamedStyleLowering.java new file mode 100644 index 00000000000..aaf9b915ff4 --- /dev/null +++ b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/NamedStyleLowering.java @@ -0,0 +1,186 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.python.transpiler.codegen; + +import com.codename1.python.transpiler.ast.Node; +import com.codename1.python.transpiler.ast.Node.Assign; +import com.codename1.python.transpiler.ast.Node.Attribute; +import com.codename1.python.transpiler.ast.Node.Call; +import com.codename1.python.transpiler.ast.Node.ClassDef; +import com.codename1.python.transpiler.ast.Node.Constant; +import com.codename1.python.transpiler.ast.Node.Expr; +import com.codename1.python.transpiler.ast.Node.FunctionDef; +import com.codename1.python.transpiler.ast.Node.Name; +import com.codename1.python.transpiler.ast.Node.Stmt; +import com.codename1.python.transpiler.parser.Parser; + +import java.util.ArrayList; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/// Lowers openpyxl's `NamedStyle.__setattr__` (`styles/named_styles.py`), +/// which forwards every store and then recalculates the style when one of +/// a literal tuple of fields changed on a style bound to a workbook. +/// +/// A class that binds `__setattr__` has no layout. The hook only matters +/// for the listed fields, and each of them is a descriptor whose `__set__` +/// every store of it runs, whatever the receiver's static type: so each such +/// field's descriptor is constructed from a subclass of its own descriptor +/// class (`_cn1_Hooked_Typed(Typed)`), written next to the class, whose +/// `__set__` calls the original and then the hook. The descriptors stay +/// descriptors of the same kind, so [DeclarativeMap] and +/// `Serialisable.from_tree` see what they saw before, and `__setattr__` is +/// dropped. No attribute name is compared at run time. +/// +/// If `__setattr__` or any listed field has another shape, nothing is +/// changed. +public final class NamedStyleLowering { + + private static final String PATH = "openpyxl/styles/named_styles.py"; + + private NamedStyleLowering() { + } + + public static void rewrite(Map trees) { + for (Map.Entry e : trees.entrySet()) { + if (e.getKey().endsWith(PATH)) { + List body = e.getValue().body; + for (int i = 0; i < body.size(); i++) { + if (body.get(i) instanceof ClassDef && "NamedStyle".equals(((ClassDef) body.get(i)).name)) { + lower(body, i, e.getKey()); + return; + } + } + } + } + } + + private static void lower(List module, int at, String file) { + ClassDef c = (ClassDef) module.get(at); + int sa = -1; + for (int i = 0; i < c.body.size(); i++) { + if (c.body.get(i) instanceof FunctionDef && "__setattr__".equals(((FunctionDef) c.body.get(i)).name)) { + if (sa >= 0) { + return; + } + sa = i; + } + } + if (sa < 0) { + return; + } + List names = hooked((FunctionDef) c.body.get(sa)); + if (names == null) { + return; + } + List ctors = new ArrayList(); + Set kinds = new LinkedHashSet(); + for (String n : names) { + Assign k = null; + int seen = 0; + for (Stmt s : c.body) { + if (s instanceof Assign && ((Assign) s).targets.size() == 1 + && ((Assign) s).targets.get(0) instanceof Name + && n.equals(((Name) ((Assign) s).targets.get(0)).id)) { + seen++; + Expr v = ((Assign) s).value; + if (v instanceof Call && ((Call) v).func instanceof Name) { + k = (Assign) s; + } + } else if (s instanceof FunctionDef && n.equals(((FunctionDef) s).name)) { + seen++; + } + } + if (k == null || seen != 1) { + return; + } + ctors.add(k); + kinds.add(((Name) ((Call) k.value).func).id); + } + StringBuilder b = new StringBuilder(); + for (String k : kinds) { + b.append("class _cn1_Hooked_").append(k).append('(').append(k).append("):\n") + .append(" def __set__(self, instance, value):\n") + .append(" super().__set__(instance, value)\n") + .append(" if instance._wb:\n") + .append(" instance._recalculate()\n"); + } + Node.Module parsed = Parser.parse(b.toString(), file); + DataclassInit.atLine(parsed, c.line); + for (Assign k : ctors) { + Call old = (Call) k.value; + Name f = new Name("_cn1_Hooked_" + ((Name) old.func).id); + f.line = old.func.line; + Call nc = new Call(f); + nc.line = old.line; + nc.args.addAll(old.args); + nc.keywords.addAll(old.keywords); + Assign na = new Assign(k.targets, nc); + na.line = k.line; + c.body.set(c.body.indexOf(k), na); + } + c.body.remove(sa); + module.addAll(at, parsed.body); + } + + /// The fields of `def __setattr__(self, attr, value): + /// super().__setattr__(attr, value); if getattr(self, '_wb', None) and + /// attr in (): self._recalculate()`, or null. + private static List hooked(FunctionDef f) { + if (f.body.size() != 2 || f.args.positional.size() != 3 || !f.decorators.isEmpty() + || !(f.body.get(1) instanceof Node.If)) { + return null; + } + Node.If i = (Node.If) f.body.get(1); + if (!i.orelse.isEmpty() || i.body.size() != 1 || !(i.test instanceof Node.BoolOp)) { + return null; + } + Node.BoolOp t = (Node.BoolOp) i.test; + if (t.values.size() != 2 || !(t.values.get(1) instanceof Node.Compare)) { + return null; + } + Node.Compare cmp = (Node.Compare) t.values.get(1); + if (cmp.comparators.size() != 1 || !(cmp.comparators.get(0) instanceof Node.TupleExpr)) { + return null; + } + if (!(i.body.get(0) instanceof Node.ExprStmt)) { + return null; + } + Expr call = ((Node.ExprStmt) i.body.get(0)).value; + if (!(call instanceof Call) || !(((Call) call).func instanceof Attribute) + || !"_recalculate".equals(((Attribute) ((Call) call).func).attr)) { + return null; + } + List out = new ArrayList(); + for (Expr e : ((Node.TupleExpr) cmp.comparators.get(0)).elts) { + if (!(e instanceof Constant) || ((Constant) e).kind != Constant.Kind.STR) { + return null; + } + out.add(((Constant) e).text); + } + return out; + } +} diff --git a/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/NamedTupleLowering.java b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/NamedTupleLowering.java new file mode 100644 index 00000000000..b5e79097047 --- /dev/null +++ b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/NamedTupleLowering.java @@ -0,0 +1,542 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.python.transpiler.codegen; + +import com.codename1.python.transpiler.ast.Node; +import com.codename1.python.transpiler.ast.Node.AnnAssign; +import com.codename1.python.transpiler.ast.Node.Assign; +import com.codename1.python.transpiler.ast.Node.Attribute; +import com.codename1.python.transpiler.ast.Node.Call; +import com.codename1.python.transpiler.ast.Node.ClassDef; +import com.codename1.python.transpiler.ast.Node.Constant; +import com.codename1.python.transpiler.ast.Node.Expr; +import com.codename1.python.transpiler.ast.Node.ExprStmt; +import com.codename1.python.transpiler.ast.Node.FunctionDef; +import com.codename1.python.transpiler.ast.Node.ImportFrom; +import com.codename1.python.transpiler.ast.Node.Name; +import com.codename1.python.transpiler.ast.Node.Pass; +import com.codename1.python.transpiler.ast.Node.Stmt; +import com.codename1.python.transpiler.ast.Node.Subscript; +import com.codename1.python.transpiler.parser.Parser; + +import java.util.ArrayList; +import java.util.List; + +/// Writes named tuple classes out as class statements at build time. +/// +/// A base built by a call, `class Version(namedtuple("Version", [...]))`, +/// and a `class TreeForms(typing.NamedTuple)` body of annotated fields are +/// both classes the runtime makes with `type(...)`, so the planner can give +/// neither a layout and every subclass is generic. When the type name and +/// the fields are literals, this pass writes the class `namedtuple` would +/// make as Python source (`__new__`, `_make`, `_replace`, `_asdict`, +/// `__repr__`, `__getnewargs__`, one read-only property per field, a +/// `tuple` base and empty `__slots__`), as CPython's own generated code +/// does. The call base becomes a class statement named `_cn1nt_` +/// placed just before its subclass; a `NamedTuple` class keeps its name, +/// docstring and annotations and gets `tuple` as its base, which is the +/// base CPython gives it too. Anything else -- defaults, `rename`, a +/// computed name, a body with methods -- is left as it is. +public final class NamedTupleLowering { + + private NamedTupleLowering() { + } + + /// Lowers the named tuple classes of module `m` (from `file`). + public static void rewrite(Node.Module m, String file) { + boolean nt = imported(m, "collections", "namedtuple"); + boolean typed = imported(m, "typing", "NamedTuple"); + boolean td = imported(m, "typing", "TypedDict") || imported(m, "typing_extensions", "TypedDict"); + boolean mod = moduleImported(m, "typing"); + if (!nt && !typed && !td && !mod) { + return; + } + List out = new ArrayList(); + boolean changed = false; + for (Stmt s : m.body) { + if (s instanceof ClassDef && ((ClassDef) s).bases.size() == 1 && (((ClassDef) s).keywords.isEmpty() + || (td || mod) && totalOnly((ClassDef) s))) { + ClassDef c = (ClassDef) s; + Expr b = c.bases.get(0); + List fields = nt ? callFields(b) : null; + if (fields != null) { + String base = "_cn1nt_" + c.name; + Node.Module gen = Parser.parse(source(base, str(((Call) b).args.get(0)), fields, null, null), file); + DataclassInit.atLine(gen, c.line); + out.addAll(gen.body); + Node.Module ref = Parser.parse(base + "\n", file); + DataclassInit.atLine(ref, c.line); + c.bases.set(0, ((ExprStmt) ref.body.get(0)).value); + changed = true; + } else if (c.decorators.isEmpty() && (td && b instanceof Name && "TypedDict".equals(((Name) b).id) + || mod && typingAttr(b, "TypedDict")) + && typedDict(c, b instanceof Name ? "TypedDict" : "typing.TypedDict", futureAnnotations(m), file, out)) { + changed = true; + continue; + } else if ((typed && b instanceof Name && "NamedTuple".equals(((Name) b).id) + || mod && typingAttr(b, "NamedTuple")) && c.decorators.isEmpty()) { + java.util.Map defaults = new java.util.LinkedHashMap(); + List own = annotatedFields(c, defaults); + if (own != null) { + Node.Module gen = Parser.parse(source(c.name, c.name, own, c, defaults), file); + DataclassInit.atLine(gen, c.line); + ClassDef g = (ClassDef) gen.body.get(0); + // The docstring and the annotations first, as written. + List body = new ArrayList(); + for (Stmt k : c.body) { + if (k instanceof AnnAssign && ((AnnAssign) k).value != null) { + // The default moved into __new__; a class attribute would only be + // shadowed by the field's property. + AnnAssign aa = (AnnAssign) k; + AnnAssign bare = new AnnAssign(aa.target, aa.annotation, null); + bare.line = aa.line; + body.add(bare); + } else if (!(k instanceof Pass)) { + body.add(k); + } + } + body.addAll(g.body); + c.body.clear(); + c.body.addAll(body); + c.bases.set(0, g.bases.get(0)); + changed = true; + } + } + } + out.add(s); + } + if (changed) { + m.body.clear(); + m.body.addAll(out); + } + } + + /// Whether `b` is `typing.` through `import typing` ([#moduleImported]). + private static boolean typingAttr(Expr b, String attr) { + return b instanceof Attribute && attr.equals(((Attribute) b).attr) && ((Attribute) b).value instanceof Name + && "typing".equals(((Name) ((Attribute) b).value).id); + } + + /// Whether `import module` binds `module` once, and nothing else in the + /// module's top level binds that name. + private static boolean moduleImported(Node.Module m, String module) { + int found = 0; + int other = 0; + for (Stmt s : m.body) { + if (s instanceof Node.Import) { + for (Node.Alias a : ((Node.Import) s).names) { + String as = a.asname != null ? a.asname : a.name.split("\\.")[0]; + if (as.equals(module)) { + if (a.asname == null && a.name.equals(module)) { + found++; + } else { + other++; + } + } + } + } else if (s instanceof ImportFrom) { + for (Node.Alias a : ((ImportFrom) s).names) { + other += "*".equals(a.name) || module.equals(a.asname != null ? a.asname : a.name) ? 1 : 0; + } + } else if (s instanceof Assign) { + for (Expr t : ((Assign) s).targets) { + other += t instanceof Name && ((Name) t).id.equals(module) ? 1 : 0; + } + } else if (s instanceof FunctionDef && ((FunctionDef) s).name.equals(module) + || s instanceof ClassDef && ((ClassDef) s).name.equals(module)) { + other++; + } + } + return found == 1 && other == 0; + } + + /// Whether the class statement's only keyword is `total=True|False`. + private static boolean totalOnly(ClassDef c) { + return c.keywords.size() == 1 && "total".equals(c.keywords.get(0).arg) + && c.keywords.get(0).value instanceof Constant + && (((Constant) c.keywords.get(0).value).kind == Constant.Kind.TRUE + || ((Constant) c.keywords.get(0).value).kind == Constant.Kind.FALSE); + } + + private static boolean futureAnnotations(Node.Module m) { + for (Stmt s : m.body) { + if (s instanceof ImportFrom && "__future__".equals(((ImportFrom) s).module)) { + for (Node.Alias a : ((ImportFrom) s).names) { + if ("annotations".equals(a.name)) { + return true; + } + } + } + } + return false; + } + + /// Lowers `class X(TypedDict[, total=B]):` whose body is only + /// annotations without values (and `pass`) to the functional form + /// `X = TypedDict("X", {"k": , ...}, total=B)`, which makes + /// the very same object: a `_TypedDictMeta` class whose call answers a + /// plain dict, with `__annotations__`, `__total__` and the key sets. Each + /// annotation is evaluated where the class body would have evaluated it + /// (module scope), or kept as its source text under `from __future__ + /// import annotations`, as CPython keeps it. A docstring, a method, a + /// base other than `TypedDict` or an annotation this pass cannot write + /// back as source leaves the class as it is. + private static boolean typedDict(ClassDef c, String fn, boolean future, String file, List out) { + StringBuilder sb = new StringBuilder(); + sb.append(c.name).append(" = ").append(fn).append("(\"").append(c.name).append("\", {"); + boolean any = false; + for (Stmt s : c.body) { + if (s instanceof Pass) { + continue; + } + if (!(s instanceof AnnAssign) || ((AnnAssign) s).value != null || !(((AnnAssign) s).target instanceof Name)) { + return false; + } + String ann = unparse(((AnnAssign) s).annotation); + if (ann == null) { + return false; + } + String key = pyStr(((Name) ((AnnAssign) s).target).id); + String val = future ? pyStr(ann) : ann; + if (key == null || val == null) { + return false; + } + sb.append(any ? ", " : "").append(key).append(": ").append(val); + any = true; + } + sb.append("}"); + if (!c.keywords.isEmpty()) { + sb.append(", total=").append(((Constant) c.keywords.get(0).value).kind == Constant.Kind.TRUE + ? "True" : "False"); + } + sb.append(")\n"); + Node.Module gen = Parser.parse(sb.toString(), file); + DataclassInit.atLine(gen, c.line); + out.addAll(gen.body); + return true; + } + + private static String pyStr(String v) { + StringBuilder sb = new StringBuilder("'"); + for (int i = 0; i < v.length(); i++) { + char ch = v.charAt(i); + if (ch == '\\' || ch == '\'') { + sb.append('\\'); + } + if (ch < 32 || ch > 126) { + return null; + } + sb.append(ch); + } + return sb.append('\'').toString(); + } + + /// Source text of a type annotation built from names, attributes, + /// subscripts, tuples, lists, constants and `|`; null for anything else. + private static String unparse(Expr e) { + if (e instanceof Name) { + return ((Name) e).id; + } + if (e instanceof Attribute) { + String v = unparse(((Attribute) e).value); + return v == null ? null : v + "." + ((Attribute) e).attr; + } + if (e instanceof Subscript) { + String v = unparse(((Subscript) e).value); + Expr ix = ((Subscript) e).index; + String i = ix instanceof Node.TupleExpr ? elts(((Node.TupleExpr) ix).elts) : unparse(ix); + return v == null || i == null ? null : v + "[" + i + "]"; + } + if (e instanceof Node.TupleExpr) { + String i = elts(((Node.TupleExpr) e).elts); + return i == null ? null : "(" + i + (((Node.TupleExpr) e).elts.size() == 1 ? ",)" : ")"); + } + if (e instanceof Node.ListExpr) { + String i = elts(((Node.ListExpr) e).elts); + return i == null ? null : "[" + i + "]"; + } + if (e instanceof Node.BinOp && "|".equals(((Node.BinOp) e).op)) { + String l = unparse(((Node.BinOp) e).left); + String r = unparse(((Node.BinOp) e).right); + return l == null || r == null ? null : l + " | " + r; + } + if (e instanceof Constant) { + Constant k = (Constant) e; + switch (k.kind) { + case NONE: + return "None"; + case ELLIPSIS: + return "..."; + case STR: + return pyStr(k.text); + default: + return null; + } + } + return null; + } + + private static String elts(List es) { + StringBuilder sb = new StringBuilder(); + for (Expr x : es) { + String u = unparse(x); + if (u == null) { + return null; + } + sb.append(sb.length() == 0 ? "" : ", ").append(u); + } + return sb.toString(); + } + + /// Whether `from module import name` binds `name` and nothing else in + /// the module's top level does. + private static boolean imported(Node.Module m, String module, String name) { + int from = 0; + int other = 0; + for (Stmt s : m.body) { + if (s instanceof ImportFrom) { + for (Node.Alias a : ((ImportFrom) s).names) { + String as = a.asname != null ? a.asname : a.name; + if ("*".equals(a.name)) { + other++; + } else if (as.equals(name)) { + if (module.equals(((ImportFrom) s).module) && ((ImportFrom) s).level == 0 && a.name.equals(name)) { + from++; + } else { + other++; + } + } + } + } else if (s instanceof Assign) { + for (Expr t : ((Assign) s).targets) { + other += t instanceof Name && ((Name) t).id.equals(name) ? 1 : 0; + } + } else if (s instanceof FunctionDef && ((FunctionDef) s).name.equals(name) + || s instanceof ClassDef && ((ClassDef) s).name.equals(name)) { + other++; + } + } + return from == 1 && other == 0; + } + + /// The fields of `namedtuple("Name", )`, or null. + private static List callFields(Expr b) { + if (!(b instanceof Call) || !(((Call) b).func instanceof Name) + || !"namedtuple".equals(((Name) ((Call) b).func).id)) { + return null; + } + Call c = (Call) b; + if (c.args.size() != 2 || !c.keywords.isEmpty() || str(c.args.get(0)) == null + || !ident(str(c.args.get(0)))) { + return null; + } + Expr f = c.args.get(1); + List out = new ArrayList(); + if (str(f) != null) { + for (String p : str(f).replace(',', ' ').trim().split("\\s+")) { + out.add(p); + } + } else if (f instanceof Node.ListExpr || f instanceof Node.TupleExpr) { + for (Expr e : f instanceof Node.ListExpr ? ((Node.ListExpr) f).elts : ((Node.TupleExpr) f).elts) { + if (str(e) == null) { + return null; + } + out.add(str(e)); + } + } else { + return null; + } + return valid(out) ? out : null; + } + + /// The fields of a `NamedTuple` body holding a docstring, `pass`, + /// annotations (trailing ones may carry a literal default, recorded in + /// `defaults` as source) and methods that do not replace a generated + /// member, or null. + private static List annotatedFields(ClassDef c, java.util.Map defaults) { + List out = new ArrayList(); + List methods = new ArrayList(); + for (int i = 0; i < c.body.size(); i++) { + Stmt s = c.body.get(i); + if (s instanceof AnnAssign && ((AnnAssign) s).target instanceof Name) { + String f = ((Name) ((AnnAssign) s).target).id; + Expr v = ((AnnAssign) s).value; + if (v == null) { + if (!defaults.isEmpty()) { + return null; + } + } else { + String lit = literal(v); + if (lit == null) { + return null; + } + defaults.put(f, lit); + } + out.add(f); + } else if (s instanceof FunctionDef) { + String n = ((FunctionDef) s).name; + if (GENERATED.contains(n) || n.startsWith("_") && !(n.startsWith("__") && n.endsWith("__"))) { + return null; + } + methods.add(n); + } else if (!(s instanceof Pass) && !(i == 0 && s instanceof ExprStmt && str(((ExprStmt) s).value) != null)) { + return null; + } + } + for (String m : methods) { + if (out.contains(m)) { + return null; + } + } + return valid(out) ? out : null; + } + + private static final java.util.Set GENERATED = new java.util.HashSet(java.util.Arrays.asList( + "__new__", "__init__", "__repr__", "__getnewargs__", "__slots__", "__setattr__", "__getattr__", + "__getattribute__", "__delattr__", "__init_subclass__", "__class_getitem__")); + + /// The source of an immutable literal default, or null. + private static String literal(Expr e) { + if (!(e instanceof Constant)) { + return null; + } + Constant k = (Constant) e; + switch (k.kind) { + case NONE: + return "None"; + case TRUE: + return "True"; + case FALSE: + return "False"; + case INT: + case FLOAT: + return k.text; + case STR: + for (int i = 0; i < k.text.length(); i++) { + char ch = k.text.charAt(i); + if (ch < 32 || ch > 126 || ch == '\'' || ch == '\\') { + return null; + } + } + return "'" + k.text + "'"; + default: + return null; + } + } + + /// Field names `namedtuple` accepts without `rename`. + private static boolean valid(List fields) { + if (fields.isEmpty()) { + return false; + } + for (int i = 0; i < fields.size(); i++) { + String f = fields.get(i); + if (!ident(f) || f.startsWith("_") || fields.indexOf(f) != i || KEYWORDS.contains(f)) { + return false; + } + } + return true; + } + + private static final java.util.Set KEYWORDS = new java.util.HashSet(java.util.Arrays.asList( + "False", "None", "True", "and", "as", "assert", "async", "await", "break", "class", "continue", "def", + "del", "elif", "else", "except", "finally", "for", "from", "global", "if", "import", "in", "is", "lambda", + "nonlocal", "not", "or", "pass", "raise", "return", "try", "while", "with", "yield", "self", "cls", + "tuple", "property", "dict", "zip", "len", "list", "TypeError", "classmethod")); + + private static String str(Expr e) { + return e instanceof Constant && ((Constant) e).kind == Constant.Kind.STR ? ((Constant) e).text : null; + } + + private static boolean ident(String s) { + if (s == null || s.isEmpty() || !Character.isJavaIdentifierStart(s.charAt(0)) || s.charAt(0) == '$') { + return false; + } + for (int i = 0; i < s.length(); i++) { + char ch = s.charAt(i); + if (ch > 127 || !(Character.isLetterOrDigit(ch) || ch == '_')) { + return false; + } + } + return true; + } + + /// The class `namedtuple(typename, fields)` makes, as source, named + /// `cls`; the docstring is left out when `keep` already has its own. + private static String source(String cls, String typename, List fields, ClassDef keep, + java.util.Map defaults) { + int n = fields.size(); + StringBuilder a = new StringBuilder(); + StringBuilder q = new StringBuilder(); + StringBuilder r = new StringBuilder(); + StringBuilder sig = new StringBuilder(); + StringBuilder fd = new StringBuilder(); + for (int i = 0; i < n; i++) { + String f = fields.get(i); + a.append(i == 0 ? "" : ", ").append(f); + String d = defaults == null ? null : defaults.get(f); + sig.append(i == 0 ? "" : ", ").append(f); + if (d != null) { + sig.append('=').append(d); + fd.append(fd.length() == 0 ? "" : ", ").append('\'').append(f).append("': ").append(d); + } + q.append('\'').append(f).append("', "); + r.append(i == 0 ? "" : ", ").append(f).append("=%r"); + } + StringBuilder s = new StringBuilder(); + s.append("class ").append(cls).append("(tuple):\n"); + boolean doc = keep != null && !keep.body.isEmpty() && keep.body.get(0) instanceof ExprStmt; + if (!doc) { + s.append(" \"").append(typename).append('(').append(a).append(")\"\n"); + } + s.append(" __slots__ = ()\n"); + s.append(" _fields = (").append(q).append(")\n"); + s.append(" _field_defaults = {").append(fd).append("}\n"); + s.append(" __match_args__ = (").append(q).append(")\n"); + s.append(" def __new__(_cls, ").append(sig).append("):\n"); + s.append(" return tuple.__new__(_cls, (").append(a).append(",))\n"); + s.append(" @classmethod\n def _make(cls, iterable):\n result = tuple.__new__(cls, iterable)\n"); + s.append(" if len(result) != ").append(n).append(":\n"); + s.append(" raise TypeError(\"Expected ").append(n).append(" arguments, got %d\" % len(result))\n"); + s.append(" return result\n"); + s.append(" def _replace(self, /, **kwds):\n"); + s.append(" result = self._make([kwds.pop(name) if name in kwds else v for name, v in zip(self._fields, self)])\n"); + s.append(" if kwds:\n raise TypeError(\"Got unexpected field names: %r\" % list(kwds))\n"); + s.append(" return result\n"); + s.append(" def __repr__(self):\n return self.__class__.__name__ + \"(").append(r).append(")\" % self\n"); + s.append(" def _asdict(self):\n return dict(zip(self._fields, self))\n"); + s.append(" def __getnewargs__(self):\n return tuple(self)\n"); + for (int i = 0; i < n; i++) { + s.append(" @property\n def ").append(fields.get(i)).append("(self):\n"); + s.append(" \"Alias for field number ").append(i).append("\"\n"); + s.append(" return self[").append(i).append("]\n"); + } + if (!cls.equals(typename)) { + // The synthesized base answers the name namedtuple() was given, as CPython's does. + s.append(cls).append(".__name__ = '").append(typename).append("'\n"); + s.append(cls).append(".__qualname__ = '").append(typename).append("'\n"); + } + return s.toString(); + } +} diff --git a/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/OxmlDeclarative.java b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/OxmlDeclarative.java new file mode 100644 index 00000000000..2fbe4cfdb25 --- /dev/null +++ b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/OxmlDeclarative.java @@ -0,0 +1,963 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.python.transpiler.codegen; + +import com.codename1.python.transpiler.ast.Node; +import com.codename1.python.transpiler.ast.Node.Alias; +import com.codename1.python.transpiler.ast.Node.AnnAssign; +import com.codename1.python.transpiler.ast.Node.Assign; +import com.codename1.python.transpiler.ast.Node.Attribute; +import com.codename1.python.transpiler.ast.Node.BinOp; +import com.codename1.python.transpiler.ast.Node.Call; +import com.codename1.python.transpiler.ast.Node.ClassDef; +import com.codename1.python.transpiler.ast.Node.Constant; +import com.codename1.python.transpiler.ast.Node.Expr; +import com.codename1.python.transpiler.ast.Node.FunctionDef; +import com.codename1.python.transpiler.ast.Node.ImportFrom; +import com.codename1.python.transpiler.ast.Node.Keyword; +import com.codename1.python.transpiler.ast.Node.Name; +import com.codename1.python.transpiler.ast.Node.Slice; +import com.codename1.python.transpiler.ast.Node.Stmt; +import com.codename1.python.transpiler.ast.Node.Subscript; +import com.codename1.python.transpiler.ast.Node.UnaryOp; +import com.codename1.python.transpiler.parser.Parser; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.IdentityHashMap; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/// Evaluates xmlchemy-style declarative element classes at build time. +/// +/// python-pptx (and python-docx, which shares the design) declare the +/// children and attributes of an XML element class as class attributes +/// holding descriptor objects: +/// +/// ```python +/// class CT_Foo(BaseOxmlElement): +/// ln = ZeroOrOne("a:ln", successors=("a:extLst",)) +/// w = OptionalAttribute("w", ST_Coordinate, default=0) +/// ``` +/// +/// A metaclass walks the class dictionary when the class is made and calls +/// `populate_class_members` on every descriptor, which `setattr`s methods +/// and properties under computed names (`get_or_add_ln`, `_add_ln`, +/// `_insert_ln`, ...). That is reflection the strict build refuses, and the +/// metaclass `__init__` leaves the whole hierarchy without a layout. +/// +/// Every argument of those descriptors is a literal (or a tuple bound in the +/// class body), so this pass runs `populate_class_members` here instead: it +/// replaces each descriptor assignment with the members it would have made, +/// as ordinary statically named methods and properties, removes the +/// metaclass `__init__` and empties the descriptor classes, whose bodies are +/// then unreachable. `_add_to_class` skips a name the class already has, own +/// or inherited, and that rule is kept: a generated name the class body or a +/// base defines is not generated. +/// +/// The private adder takes `**attrs` and assigns each with `setattr`. Here it +/// takes, as keyword parameters, exactly the names any call site in the +/// program passes to a method of that name, each assigned as a plain +/// attribute. The pass is all or nothing: if any descriptor or call site +/// cannot be evaluated, the program is left untouched and the reason is +/// reported (`-Dcn1.python.oxml.report=true`). +public final class OxmlDeclarative { + + private static final Set KINDS = new HashSet(Arrays.asList("OptionalAttribute", + "RequiredAttribute", "OneAndOnlyOne", "OneOrMore", "ZeroOrMore", "ZeroOrOne", "ZeroOrOneChoice", + "Choice")); + private static final Set MACHINERY = new HashSet(Arrays.asList("BaseAttribute", + "_BaseChildElement")); + private static final String PFX = "_ox_"; + + private final Map modules = new LinkedHashMap(); + private final Set packages = new HashSet(); + private final List report = new ArrayList(); + private final Map> adderKeywords = new HashMap>(); + private final Map> names = new IdentityHashMap>(); + private final Map moduleOfClass = new IdentityHashMap(); + private final Map>> plans = new IdentityHashMap>>(); + private final Map> hoisted = new IdentityHashMap>(); + private final Set lowered = java.util.Collections.newSetFromMap(new IdentityHashMap()); + /// Tag -> "module:Class" from literal `register_element_cls` calls; a tag + /// registered to two classes maps to null. + private final Map registry = new HashMap(); + /// A `register_element_cls` call that is not a top-level literal one was + /// seen, so no tag's class is known. + private boolean registryOpen; + private String chem; + private ClassDef meta; + private boolean failed; + + private OxmlDeclarative() { + } + + /// Lowers every declarative element class among `trees` (by path) and + /// answers why it did not, if it did not. + public static List rewrite(Map trees) { + OxmlDeclarative d = new OxmlDeclarative(); + for (Map.Entry e : trees.entrySet()) { + String p = e.getKey(); + if (!p.endsWith(".py")) { + continue; + } + String m = p.substring(0, p.length() - 3); + if (m.endsWith("/__init__")) { + m = m.substring(0, m.length() - 9); + d.packages.add(m.replace('/', '.')); + } + d.modules.put(m.replace('/', '.'), e.getValue()); + } + d.run(); + if (Boolean.getBoolean("cn1.python.oxml.report")) { + for (String r : d.report) { + System.err.println("oxml: " + r); //NOPMD SystemPrintln - opt-in diagnostics + } + } + return new ArrayList(d.report); + } + + private void run() { + if (!findChemistry()) { + return; + } + for (Map.Entry e : modules.entrySet()) { + for (Stmt s : e.getValue().body) { + if (s instanceof ClassDef) { + moduleOfClass.put((ClassDef) s, e.getKey()); + } + } + collectAdders(e.getValue()); + collectRegistry(e.getKey(), e.getValue()); + } + for (Map.Entry e : modules.entrySet()) { + for (Stmt s : e.getValue().body) { + if (s instanceof ClassDef) { + namesOf((ClassDef) s); + } + } + } + for (Map.Entry e : modules.entrySet()) { + if (!e.getKey().equals(chem)) { + unlowered(e.getKey(), e.getValue()); + } + } + if (failed) { + report.add(0, "left every declarative class alone"); + return; + } + apply(); + } + + /// Records `register_element_cls("p:tag", CT_Cls)` at module level. The + /// parser's lookup answers that class for every element so tagged, which + /// is what lets the generated accessors narrow what they return. + private void collectRegistry(String mod, Node.Module m) { + Map where = new HashMap(); + for (Stmt s : m.body) { + if (s instanceof ClassDef) { + where.put(((ClassDef) s).name, mod + ":" + ((ClassDef) s).name); + } + if (s instanceof ImportFrom && ((ImportFrom) s).level == 0) { + for (Alias a : ((ImportFrom) s).names) { + where.put(a.asname != null ? a.asname : a.name, ((ImportFrom) s).module + ":" + a.name); + } + } + } + for (Stmt s : m.body) { + if (!(s instanceof Node.ExprStmt) || !(((Node.ExprStmt) s).value instanceof Call)) { + continue; + } + Call c = (Call) ((Node.ExprStmt) s).value; + if (!(c.func instanceof Name) || !"register_element_cls".equals(((Name) c.func).id)) { + continue; + } + String tag = c.args.size() == 2 && c.keywords.isEmpty() ? str(c.args.get(0)) : null; + String k = tag != null && c.args.get(1) instanceof Name ? where.get(((Name) c.args.get(1)).id) : null; + if (k == null) { + registryOpen = true; + report.add("register_element_cls not literal at line " + c.line); + continue; + } + if (registry.containsKey(tag) && !k.equals(registry.get(tag))) { + k = null; + } + registry.put(tag, k); + } + } + + /// The class the parser makes for `tag`, as "module:Class", or null. + private String registered(String tag) { + return registryOpen ? null : registry.get(tag); + } + + /// Appends, indented, a narrowing of local `v` (known not None) to the + /// registered class of `tag`, returning it. The import is local because + /// the element modules import each other's classes only by tag; by the + /// time an accessor runs every one of them is loaded. The raise is + /// unreachable while the registry above holds. + private String narrow(String mod, String tag, String v, String ind) { + String k = registered(tag); + if (k == null) { + return ind + "return " + v + "\n"; + } + int i = k.indexOf(':'); + return ind + "from " + k.substring(0, i) + " import " + k.substring(i + 1) + " as _ox_k\n" + ind + "if isinstance(" + + v + ", _ox_k):\n" + ind + " return " + v + "\n" + ind + "raise " + + chemName("InvalidXmlError", mod) + "(" + + DeclarativeMap.quote("<" + tag + "> is not a " + k.substring(i + 1)) + ")\n"; + } + + /// Finds the module that defines the descriptor kinds and the metaclass + /// whose `__init__` calls `populate_class_members`. + private boolean findChemistry() { + for (Map.Entry e : modules.entrySet()) { + Set kinds = new HashSet(); + ClassDef m = null; + for (Stmt s : e.getValue().body) { + if (!(s instanceof ClassDef)) { + continue; + } + ClassDef c = (ClassDef) s; + if (KINDS.contains(c.name)) { + kinds.add(c.name); + } + if (c.bases.size() == 1 && c.bases.get(0) instanceof Name && "type".equals(((Name) c.bases.get(0)).id) + && populates(c)) { + m = c; + } + } + if (m != null && kinds.equals(KINDS)) { + chem = e.getKey(); + meta = m; + return true; + } + } + return false; + } + + private static boolean populates(ClassDef c) { + for (Stmt s : c.body) { + if (s instanceof FunctionDef && "__init__".equals(((FunctionDef) s).name)) { + boolean[] hit = new boolean[1]; + calls(s, hit); + return hit[0]; + } + } + return false; + } + + private static void calls(Object o, boolean[] hit) { + if (o instanceof Call && ((Call) o).func instanceof Attribute + && "populate_class_members".equals(((Attribute) ((Call) o).func).attr)) { + hit[0] = true; + } + Infer.children(o, x -> calls(x, hit)); + } + + /// Fails the pass on a descriptor made anywhere but as a class attribute + /// this pass lowers: its `populate_class_members` would still run. + private void unlowered(String mod, Object o) { + if (o instanceof Call && kindOf(mod, ((Call) o).func) != null && !lowered.contains(o)) { + report.add(mod + ":" + ((Call) o).line + " a descriptor this pass does not lower"); + failed = true; + } + Infer.children(o, x -> unlowered(mod, x)); + } + + /// Records the keyword names every `x._add_(...)` call passes. + private void collectAdders(Object o) { + if (o instanceof Call && ((Call) o).func instanceof Attribute + && ((Attribute) ((Call) o).func).attr.startsWith("_add_")) { + Call c = (Call) o; + String a = ((Attribute) c.func).attr; + Set ks = adderKeywords.get(a); + if (ks == null) { + ks = new LinkedHashSet(); + adderKeywords.put(a, ks); + } + for (Keyword k : c.keywords) { + if (k.arg == null) { + // A spread: the names are not known here. + ks.add(null); + } else { + ks.add(k.arg); + } + } + } + Infer.children(o, this::collectAdders); + } + + /// The names class `c` has once made, own and inherited, lowering it + /// (and its bases first) on the way. + private Set namesOf(ClassDef c) { + Set n = names.get(c); + if (n != null) { + return n; + } + n = new HashSet(); + names.put(c, n); + String mod = moduleOfClass.get(c); + for (Expr b : c.bases) { + ClassDef bc = b instanceof Name && mod != null ? resolveClass(mod, ((Name) b).id, 0) : null; + if (bc != null) { + n.addAll(namesOf(bc)); + } + } + for (Stmt s : c.body) { + bound(s, n); + } + if (mod != null && !mod.equals(chem)) { + lower(mod, c, n); + } + return n; + } + + private static void bound(Stmt s, Set n) { + if (s instanceof FunctionDef) { + n.add(((FunctionDef) s).name); + } else if (s instanceof ClassDef) { + n.add(((ClassDef) s).name); + } else if (s instanceof Assign) { + for (Expr t : ((Assign) s).targets) { + if (t instanceof Name) { + n.add(((Name) t).id); + } + } + } else if (s instanceof AnnAssign && ((AnnAssign) s).target instanceof Name && ((AnnAssign) s).value != null) { + // A bare annotation binds nothing: `get_or_add_x: Callable[...]` + // only declares what the metaclass will add. + n.add(((Name) ((AnnAssign) s).target).id); + } + } + + private ClassDef resolveClass(String mod, String name, int depth) { + Node.Module m = modules.get(mod); + if (m == null || depth > 4) { + return null; + } + for (Stmt s : m.body) { + if (s instanceof ClassDef && name.equals(((ClassDef) s).name)) { + return (ClassDef) s; + } + } + for (Stmt s : m.body) { + if (s instanceof ImportFrom) { + ImportFrom f = (ImportFrom) s; + for (Alias a : f.names) { + if (name.equals(a.asname == null ? a.name : a.asname)) { + String from = absolute(mod, f); + return from == null ? null : resolveClass(from, a.name, depth + 1); + } + } + } + } + return null; + } + + private String absolute(String mod, ImportFrom f) { + if (f.level == 0) { + return f.module; + } + String base = packages.contains(mod) ? mod : parent(mod); + for (int i = 1; i < f.level && base != null; i++) { + base = parent(base); + } + if (base == null) { + return null; + } + return f.module == null || f.module.isEmpty() ? base : base + "." + f.module; + } + + private static String parent(String m) { + int i = m.lastIndexOf('.'); + return i < 0 ? null : m.substring(0, i); + } + + /// The descriptor kind a call makes, or null. + private String kindOf(String mod, Expr func) { + if (!(func instanceof Name)) { + return null; + } + String id = ((Name) func).id; + Node.Module m = modules.get(mod); + for (Stmt s : m.body) { + if (s instanceof ImportFrom) { + ImportFrom f = (ImportFrom) s; + for (Alias a : f.names) { + if (id.equals(a.asname == null ? a.name : a.asname) && KINDS.contains(a.name) + && chem.equals(absolute(mod, f))) { + return a.name; + } + } + } + } + return null; + } + + private void lower(String mod, ClassDef c, Set taken) { + Map> plan = new IdentityHashMap>(); + Set unconditional = new HashSet(); + for (int i = 0; i < c.body.size(); i++) { + Stmt s = c.body.get(i); + Expr target; + Expr value; + if (s instanceof Assign && ((Assign) s).targets.size() == 1) { + target = ((Assign) s).targets.get(0); + value = ((Assign) s).value; + } else if (s instanceof AnnAssign) { + target = ((AnnAssign) s).target; + value = ((AnnAssign) s).value; + } else { + continue; + } + if (!(target instanceof Name) || !(value instanceof Call)) { + continue; + } + Call v = (Call) value; + String kind = kindOf(mod, v.func); + if (kind == null) { + continue; + } + lowered.add(v); + if (v.func instanceof Name && "ZeroOrOneChoice".equals(kind)) { + for (Expr a : v.args) { + if (a instanceof Node.TupleExpr || a instanceof Node.ListExpr) { + lowered.addAll(a instanceof Node.TupleExpr ? ((Node.TupleExpr) a).elts : ((Node.ListExpr) a).elts); + } + } + } + String prop = ((Name) target).id; + String where = mod + ":" + s.line + " " + c.name + "." + prop + " " + kind + ": "; + StringBuilder b = new StringBuilder(); + String why = member(mod, c, i, kind, prop, v, taken, unconditional, b); + if (why != null) { + report.add(where + why); + failed = true; + continue; + } + String file = mod.replace('.', '/') + ".py"; + Node.Module parsed = Parser.parse("class _ox:\n" + indent(b.toString()), file); + DataclassInit.atLine(parsed, s.line); + plan.put(s, ((ClassDef) parsed.body.get(0)).body); + } + if (!plan.isEmpty()) { + // A property the metaclass sets replaces a method of that name in + // the body (setattr runs after the body). + for (Stmt s : c.body) { + if (s instanceof FunctionDef && unconditional.contains(((FunctionDef) s).name) + && ((FunctionDef) s).decorators.isEmpty()) { + plan.put(s, new ArrayList()); + } + } + plans.put(c, plan); + } + } + + /// Appends the members descriptor `v` makes to `b`; answers why not. + private String member(String mod, ClassDef c, int at, String kind, String prop, Call v, Set taken, + Set unconditional, StringBuilder b) { + if ("OptionalAttribute".equals(kind) || "RequiredAttribute".equals(kind)) { + if (v.args.size() < 2 || v.args.size() > 3 || str(v.args.get(0)) == null) { + return "attribute arguments"; + } + String type = text(v.args.get(1)); + Expr defExpr = v.args.size() == 3 ? v.args.get(2) : null; + for (Keyword k : v.keywords) { + if ("default".equals(k.arg) && defExpr == null) { + defExpr = k.value; + } else { + return "keyword " + k.arg; + } + } + String type0 = type; + type = type0 == null ? hoist(c, prop, "type", v.args.get(1)) : type0; + String def = defExpr == null ? "None" : text(defExpr); + def = def == null ? hoist(c, prop, "default", defExpr) : def; + if ("RequiredAttribute".equals(kind) && defExpr != null) { + return "default on a required attribute"; + } + attribute(b, prop, str(v.args.get(0)), type, def, "OptionalAttribute".equals(kind)); + unconditional.add(prop); + taken.add(prop); + return null; + } + if ("Choice".equals(kind)) { + return "a choice outside a group"; + } + if ("ZeroOrOneChoice".equals(kind)) { + return choiceGroup(mod, c, at, prop, v, taken, unconditional, b); + } + if (v.args.isEmpty() || str(v.args.get(0)) == null) { + return "tag name"; + } + String tag = str(v.args.get(0)); + List succ = new ArrayList(); + Expr se = v.args.size() > 1 ? v.args.get(1) : null; + if (v.args.size() > 2) { + return "positional arguments"; + } + for (Keyword k : v.keywords) { + if ("successors".equals(k.arg) && se == null) { + se = k.value; + } else { + return "keyword " + k.arg; + } + } + if ("OneAndOnlyOne".equals(kind) && se != null) { + return "successors on OneAndOnlyOne"; + } + if (se != null) { + succ = strings(mod, c, at, se, 0); + if (succ == null) { + return "successors are not a literal sequence"; + } + } + if ("OneAndOnlyOne".equals(kind)) { + b.append("@property\ndef ").append(prop).append("(self):\n child = self.find(").append(qn(tag)) + .append(")\n if child is None:\n raise ").append(chemName("InvalidXmlError", mod)) + .append("(").append(DeclarativeMap.quote("required ``<" + tag + ">`` child element not present")) + .append(")\n").append(narrow(mod, tag, "child", " ")); + unconditional.add(prop); + taken.add(prop); + return null; + } + boolean many = "ZeroOrMore".equals(kind) || "OneOrMore".equals(kind); + if (many) { + b.append("@property\ndef ").append(prop).append("_lst(self):\n return self.findall(") + .append(qn(tag)).append(")\n"); + unconditional.add(prop + "_lst"); + taken.add(prop + "_lst"); + } else { + getter(b, prop, tag, mod); + unconditional.add(prop); + taken.add(prop); + } + String why = childMethods(mod, prop, tag, succ, taken, b); + if (why != null) { + return why; + } + if ("OneOrMore".equals(kind) && taken.add("add_" + prop)) { + b.append("def add_").append(prop).append("(self):\n return self._add_").append(prop).append("()\n"); + } + if ("ZeroOrOne".equals(kind)) { + if (taken.add("get_or_add_" + prop)) { + b.append("def get_or_add_").append(prop).append("(self):\n child = self.").append(prop) + .append("\n if child is None:\n child = self._add_").append(prop) + .append("()\n return child\n"); + } + if (taken.add("_remove_" + prop)) { + b.append("def _remove_").append(prop).append("(self):\n self.remove_all(") + .append(DeclarativeMap.quote(tag)).append(")\n"); + } + } + return null; + } + + private String choiceGroup(String mod, ClassDef c, int at, String prop, Call v, Set taken, + Set unconditional, StringBuilder b) { + if (v.args.isEmpty() || v.args.size() > 2) { + return "group arguments"; + } + Expr choices = v.args.get(0); + Expr se = v.args.size() > 1 ? v.args.get(1) : null; + for (Keyword k : v.keywords) { + if ("successors".equals(k.arg) && se == null) { + se = k.value; + } else if ("choices".equals(k.arg) && choices == null) { + choices = k.value; + } else { + return "keyword " + k.arg; + } + } + List elts = choices instanceof Node.TupleExpr ? ((Node.TupleExpr) choices).elts + : choices instanceof Node.ListExpr ? ((Node.ListExpr) choices).elts : null; + if (elts == null) { + return "choices are not a literal sequence"; + } + List succ = se == null ? new ArrayList() : strings(mod, c, at, se, 0); + if (succ == null) { + return "successors are not a literal sequence"; + } + List tags = new ArrayList(); + for (Expr x : elts) { + if (!(x instanceof Call) || !"Choice".equals(kindOf(mod, ((Call) x).func))) { + return "a choice that is not Choice(...)"; + } + Call cc = (Call) x; + if (cc.args.isEmpty() || str(cc.args.get(0)) == null) { + return "choice tag name"; + } + tags.add(str(cc.args.get(0))); + } + b.append("@property\ndef ").append(prop).append("(self):\n return self.first_child_found_in(") + .append(joined(tags)).append(")\n"); + unconditional.add(prop); + taken.add(prop); + for (String tag : tags) { + String p = tag.indexOf(':') >= 0 ? tag.substring(tag.indexOf(':') + 1) : tag; + getter(b, p, tag, mod); + unconditional.add(p); + taken.add(p); + String why = childMethods(mod, p, tag, succ, taken, b); + if (why != null) { + return why; + } + if (taken.add("get_or_change_to_" + p)) { + b.append("def get_or_change_to_").append(p).append("(self):\n child = self.").append(p) + .append("\n if child is not None:\n return child\n self._remove_").append(prop) + .append("()\n return self._add_").append(p).append("()\n"); + } + } + if (taken.add("_remove_" + prop)) { + b.append("def _remove_").append(prop).append("(self):\n"); + for (String tag : tags) { + b.append(" self.remove_all(").append(DeclarativeMap.quote(tag)).append(")\n"); + } + if (tags.isEmpty()) { + b.append(" pass\n"); + } + } + return null; + } + + private String childMethods(String mod, String p, String tag, List succ, Set taken, + StringBuilder b) { + if (taken.add("_new_" + p)) { + b.append("def _new_").append(p).append("(self):\n _ox_c = ").append(chemName("OxmlElement", mod)) + .append("(").append(DeclarativeMap.quote(tag)).append(")\n").append(narrow(mod, tag, "_ox_c", " ")); + } + if (taken.add("_insert_" + p)) { + b.append("def _insert_").append(p).append("(self, child):\n self.insert_element_before(child"); + for (String s : succ) { + b.append(", ").append(DeclarativeMap.quote(s)); + } + b.append(")\n return child\n"); + } + if (taken.add("_add_" + p)) { + Set ks = adderKeywords.get("_add_" + p); + List kw = ks == null ? new ArrayList() : new ArrayList(ks); + if (kw.contains(null)) { + return "a call spreads keywords into _add_" + p; + } + b.append("def _add_").append(p).append("(self"); + for (String k : kw) { + b.append(", ").append(k).append('=').append(chemName("_ox_unset", mod)); + } + b.append("):\n _ox_child = self._new_").append(p).append("()\n"); + for (String k : kw) { + b.append(" if ").append(k).append(" is not ").append(chemName("_ox_unset", mod)) + .append(":\n _ox_child.").append(k).append(" = ").append(k).append('\n'); + } + b.append(" self._insert_").append(p).append("(_ox_child)\n return _ox_child\n"); + } + return null; + } + + /// Binds `e` once, at module level just before class `c`, as Python + /// evaluates it once when the class body runs; answers the name. + private String hoist(ClassDef c, String prop, String what, Expr e) { + String n = PFX + c.name + "_" + prop + "_" + what; + List t = new ArrayList(); + t.add(new Name(n).at(e.line, e.col)); + List l = hoisted.get(c); + if (l == null) { + l = new ArrayList(); + hoisted.put(c, l); + } + l.add(new Assign(t, e).at(e.line, e.col)); + return n; + } + + private void getter(StringBuilder b, String prop, String tag, String mod) { + if (registered(tag) == null) { + b.append("@property\ndef ").append(prop).append("(self):\n return self.find(").append(qn(tag)) + .append(")\n"); + return; + } + b.append("@property\ndef ").append(prop).append("(self):\n _ox_c = self.find(").append(qn(tag)) + .append(")\n if _ox_c is None:\n return None\n").append(narrow(mod, tag, "_ox_c", " ")); + } + + private static void attribute(StringBuilder b, String prop, String attr, String type, String def, + boolean optional) { + String clark = attr.indexOf(':') >= 0 ? PFX + "qn(" + DeclarativeMap.quote(attr) + ")" + : DeclarativeMap.quote(attr); + b.append("@property\ndef ").append(prop).append("(self):\n _ox_v = self.get(").append(clark) + .append(")\n if _ox_v is None:\n"); + if (optional) { + b.append(" return ").append(def).append('\n'); + } else { + b.append(" raise ").append(PFX).append("InvalidXmlError(") + .append(DeclarativeMap.quote("required '" + attr + "' attribute not present on element %s")) + .append(" % (self.tag,))\n"); + } + b.append(" return ").append(type).append(".from_xml(_ox_v)\n@").append(prop).append(".setter\ndef ") + .append(prop).append("(self, value):\n"); + if (optional) { + b.append(" if value == ").append(def).append(":\n if ").append(clark) + .append(" in self.attrib:\n del self.attrib[").append(clark) + .append("]\n return\n"); + } + b.append(" self.set(").append(clark).append(", ").append(type).append(".to_xml(value))\n"); + } + + private static String qn(String tag) { + return PFX + "qn(" + DeclarativeMap.quote(tag) + ")"; + } + + private String chemName(String n, String mod) { + return mod.equals(chem) ? n : n.startsWith(PFX) ? n : PFX + n; + } + + private static String joined(List tags) { + StringBuilder b = new StringBuilder(); + for (String t : tags) { + if (b.length() > 0) { + b.append(", "); + } + b.append(DeclarativeMap.quote(t)); + } + return b.toString(); + } + + private static String indent(String s) { + StringBuilder b = new StringBuilder(); + for (String line : s.split("\n", -1)) { + if (!line.isEmpty()) { + b.append(" ").append(line); + } + b.append('\n'); + } + return b.toString(); + } + + private static String str(Expr e) { + return e instanceof Constant && ((Constant) e).kind == Constant.Kind.STR ? ((Constant) e).text : null; + } + + /// Python source for a literal, a name or a dotted name; null otherwise. + private static String text(Expr e) { + if (e instanceof Name) { + return ((Name) e).id; + } + if (e instanceof Attribute) { + String v = text(((Attribute) e).value); + return v == null || !(((Attribute) e).value instanceof Name || ((Attribute) e).value instanceof Attribute) + ? null : v + "." + ((Attribute) e).attr; + } + if (e instanceof UnaryOp && "-".equals(((UnaryOp) e).op) && ((UnaryOp) e).operand instanceof Constant) { + Constant k = (Constant) ((UnaryOp) e).operand; + return k.kind == Constant.Kind.INT || k.kind == Constant.Kind.FLOAT ? "-" + k.text : null; + } + if (e instanceof Constant) { + Constant k = (Constant) e; + switch (k.kind) { + case NONE: + return "None"; + case TRUE: + return "True"; + case FALSE: + return "False"; + case INT: + case FLOAT: + return k.text; + case STR: + return DeclarativeMap.quote(k.text); + default: + return null; + } + } + return null; + } + + /// The strings sequence `e` evaluates to in the body of `c` before + /// statement `at`, or null. + private List strings(String mod, ClassDef c, int at, Expr e, int depth) { + if (depth > 8) { + return null; + } + if (e instanceof Node.TupleExpr || e instanceof Node.ListExpr) { + List elts = e instanceof Node.TupleExpr ? ((Node.TupleExpr) e).elts : ((Node.ListExpr) e).elts; + List out = new ArrayList(); + for (Expr x : elts) { + if (str(x) == null) { + return null; + } + out.add(str(x)); + } + return out; + } + if (e instanceof BinOp && "+".equals(((BinOp) e).op)) { + List l = strings(mod, c, at, ((BinOp) e).left, depth + 1); + List r = strings(mod, c, at, ((BinOp) e).right, depth + 1); + if (l == null || r == null) { + return null; + } + l.addAll(r); + return l; + } + if (e instanceof Subscript && ((Subscript) e).index instanceof Slice) { + Slice s = (Slice) ((Subscript) e).index; + List v = strings(mod, c, at, ((Subscript) e).value, depth + 1); + if (v == null || s.step != null) { + return null; + } + Integer lo = s.lower == null ? Integer.valueOf(0) : intOf(s.lower); + Integer hi = s.upper == null ? Integer.valueOf(v.size()) : intOf(s.upper); + if (lo == null || hi == null) { + return null; + } + int a = clamp(lo, v.size()); + int z = clamp(hi, v.size()); + return a >= z ? new ArrayList() : new ArrayList(v.subList(a, z)); + } + if (e instanceof Name) { + String id = ((Name) e).id; + for (int i = at - 1; i >= 0; i--) { + Stmt s = c.body.get(i); + if (s instanceof Assign && ((Assign) s).targets.size() == 1 && ((Assign) s).targets.get(0) instanceof Name + && id.equals(((Name) ((Assign) s).targets.get(0)).id)) { + return strings(mod, c, i, ((Assign) s).value, depth + 1); + } + } + Expr found = null; + int count = 0; + for (Stmt s : modules.get(mod).body) { + Set n = new HashSet(); + bound(s, n); + if (n.contains(id)) { + count++; + found = s instanceof Assign ? ((Assign) s).value : null; + } + } + return count == 1 && found != null ? strings(mod, c, 0, found, depth + 1) : null; + } + return null; + } + + private static int clamp(int i, int n) { + int r = i < 0 ? n + i : i; + return r < 0 ? 0 : r > n ? n : r; + } + + private static Integer intOf(Expr e) { + String t = text(e); + if (t == null) { + return null; + } + try { + return Integer.valueOf(t); + } catch (NumberFormatException ex) { + return null; + } + } + + private void apply() { + Set touched = new HashSet(); + for (Map.Entry>> e : plans.entrySet()) { + ClassDef c = e.getKey(); + List out = new ArrayList(); + for (Stmt s : c.body) { + List r = e.getValue().get(s); + if (r == null) { + out.add(s); + } else { + out.addAll(r); + } + } + c.body.clear(); + c.body.addAll(out); + touched.add(moduleOfClass.get(c)); + } + String file = chem.replace('.', '/') + ".py"; + Node.Module chemMod = modules.get(chem); + for (String mod : touched) { + Node.Module m = modules.get(mod); + int first = -1; + for (int i = 0; i < m.body.size() && first < 0; i++) { + if (m.body.get(i) instanceof ClassDef && plans.containsKey(m.body.get(i))) { + first = i; + } + } + for (int i = 0; i < m.body.size(); i++) { + List h = m.body.get(i) instanceof ClassDef ? hoisted.get(m.body.get(i)) : null; + if (h != null) { + m.body.addAll(i, h); + i += h.size(); + } + } + Node.Module imp = Parser.parse("from " + chem + " import qn as _ox_qn, OxmlElement as _ox_OxmlElement, " + + "InvalidXmlError as _ox_InvalidXmlError, _ox_unset\n", mod.replace('.', '/') + ".py"); + DataclassInit.atLine(imp, m.body.get(first).line); + m.body.addAll(first, imp.body); + } + // The metaclass populates nothing now, and nothing makes a descriptor. + for (int i = 0; i < chemMod.body.size(); i++) { + Stmt s = chemMod.body.get(i); + if (s == meta) { //NOPMD CompareObjectsWithEquals - identity is meant + // The metaclass is `type` itself now; classes naming it as + // their metaclass drop the keyword below. + Node.Module sentinel = Parser.parse("_ox_unset = object()\n" + meta.name + " = type\n", file); + DataclassInit.atLine(sentinel, s.line); + chemMod.body.remove(i); + chemMod.body.addAll(i, sentinel.body); + i += sentinel.body.size() - 1; + } else if (s instanceof ClassDef && (KINDS.contains(((ClassDef) s).name) + || MACHINERY.contains(((ClassDef) s).name))) { + emptied((ClassDef) s, file); + } + } + for (Node.Module m : modules.values()) { + for (Stmt s : m.body) { + if (s instanceof ClassDef) { + dropMetaclass((ClassDef) s); + } + } + } + report.add("lowered " + plans.size() + " classes"); + } + + private void dropMetaclass(ClassDef c) { + for (int i = c.keywords.size() - 1; i >= 0; i--) { + Keyword k = c.keywords.get(i); + if ("metaclass".equals(k.arg) && k.value instanceof Name && meta.name.equals(((Name) k.value).id) + && chem.equals(moduleOfClass.get(c))) { + c.keywords.remove(i); + } + } + } + + private static void emptied(ClassDef c, String file) { + Node.Module p = Parser.parse("pass\n", file); + DataclassInit.atLine(p, c.line); + c.body.clear(); + c.body.addAll(p.body); + } +} diff --git a/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/ProtocolChecks.java b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/ProtocolChecks.java new file mode 100644 index 00000000000..07ee31112b5 --- /dev/null +++ b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/ProtocolChecks.java @@ -0,0 +1,160 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.python.transpiler.codegen; + +import com.codename1.python.transpiler.ast.Node; +import com.codename1.python.transpiler.ast.Node.AnnAssign; +import com.codename1.python.transpiler.ast.Node.Assign; +import com.codename1.python.transpiler.ast.Node.Attribute; +import com.codename1.python.transpiler.ast.Node.ClassDef; +import com.codename1.python.transpiler.ast.Node.Expr; +import com.codename1.python.transpiler.ast.Node.FunctionDef; +import com.codename1.python.transpiler.ast.Node.Name; +import com.codename1.python.transpiler.ast.Node.Stmt; +import com.codename1.python.transpiler.ast.Node.Subscript; +import com.codename1.python.transpiler.parser.Parser; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Set; + +/// Writes the structural check of every `typing.Protocol` class at build +/// time, so `isinstance`/`issubclass` against a `@runtime_checkable` +/// protocol need no member looked up by a computed name. +/// +/// A protocol is a class with `Protocol` (or `Protocol[...]`, from `typing` +/// or `typing_extensions`) among its direct bases, as CPython's +/// `Protocol.__init_subclass__` decides. Its members are the names its body +/// binds -- methods, assignments and bare annotations -- less the names +/// CPython's `_get_protocol_attrs` leaves out. The class gets a static +/// `__cn1_protocol_check__(o)`: a method member must be present and not +/// None, any other member present (CPython's `__instancecheck__`), and each +/// further base -- a protocol too -- must hold as well. A class with a +/// non-method member also gets `__cn1_protocol_data__`, their quoted names, which makes +/// `issubclass` refuse it. The runtime (PyType.protocolCheck) calls the +/// check when the nominal test fails, and refuses a protocol that is not +/// runtime checkable. +public final class ProtocolChecks { + private static final Set EXCLUDED = new HashSet(Arrays.asList( + "__abstractmethods__", "__annotations__", "__dict__", "__doc__", "__init__", "__module__", "__new__", + "__slots__", "__subclasshook__", "__weakref__", "__class_getitem__", "__match_args__", + "__static_attributes__", "__firstlineno__", "_is_protocol", "_is_runtime_protocol", + "__protocol_attrs__", "__non_callable_proto_members__", "__type_params__", "__orig_bases__", + "__parameters__", "__qualname__", "_MutableMapping__marker", "__init_subclass__")); + + private ProtocolChecks() { + } + + /// Whether `c` names `Protocol` among its direct bases. + static boolean isProtocol(ClassDef c) { + for (Expr x : c.bases) { + Expr e = x instanceof Subscript ? ((Subscript) x).value : x; + if (e instanceof Name && "Protocol".equals(((Name) e).id) + || e instanceof Attribute && "Protocol".equals(((Attribute) e).attr)) { + return true; + } + } + return false; + } + + /// Adds the checks to the protocol classes at module level of `tree`. + public static void rewrite(Node.Module tree, String path) { + Map protocols = new HashMap(); + for (Stmt s : tree.body) { + if (s instanceof ClassDef && isProtocol((ClassDef) s)) { + ClassDef c = (ClassDef) s; + protocols.put(c.name, c); + lower(c, protocols, path); + } + } + } + + private static void lower(ClassDef c, Map protocols, String path) { + // member name -> whether it is a method + Map members = new LinkedHashMap(); + for (Stmt s : c.body) { + if (s instanceof FunctionDef) { + FunctionDef f = (FunctionDef) s; + boolean prop = false; + for (Expr d : f.decorators) { + prop |= d instanceof Name && "property".equals(((Name) d).id) + || d instanceof Attribute && ("setter".equals(((Attribute) d).attr) + || "deleter".equals(((Attribute) d).attr) || "property".equals(((Attribute) d).attr)); + } + member(members, f.name, !prop); + } else if (s instanceof AnnAssign && ((AnnAssign) s).target instanceof Name) { + member(members, ((Name) ((AnnAssign) s).target).id, false); + } else if (s instanceof Assign) { + for (Expr t : ((Assign) s).targets) { + if (t instanceof Name) { + member(members, ((Name) t).id, false); + } + } + } + } + StringBuilder b = new StringBuilder(); + StringBuilder data = new StringBuilder(); + for (Map.Entry m : members.entrySet()) { + if (!m.getValue()) { + data.append(data.length() == 0 ? "" : ", ").append('\'').append(m.getKey()).append('\''); + } + } + if (data.length() > 0) { + b.append("__cn1_protocol_data__ = \"").append(data).append("\"\n"); + } + b.append("@staticmethod\ndef __cn1_protocol_check__(o):\n return True"); + for (Map.Entry m : members.entrySet()) { + if (m.getValue()) { + b.append(" and getattr(o, '").append(m.getKey()).append("', None) is not None"); + } else { + b.append(" and hasattr(o, '").append(m.getKey()).append("')"); + } + } + for (Expr x : c.bases) { + Expr e = x instanceof Subscript ? ((Subscript) x).value : x; + String n = e instanceof Name ? ((Name) e).id : e instanceof Attribute ? ((Attribute) e).attr : null; + if ("Protocol".equals(n) || "Generic".equals(n) || "object".equals(n)) { + continue; + } + if (e instanceof Name && protocols.containsKey(n) && protocols.get(n) != c) { //NOPMD CompareObjectsWithEquals - identity is meant + b.append(" and ").append(n).append(".__cn1_protocol_check__(o)"); + } else if (e instanceof Name || e instanceof Attribute && ((Attribute) e).value instanceof Name) { + String ref = e instanceof Name ? n : ((Name) ((Attribute) e).value).id + "." + n; + b.append(" and (issubclass(o, ").append(ref).append(") if isinstance(o, type) else isinstance(o, ") + .append(ref).append("))"); + } + } + b.append('\n'); + Node.Module gen = Parser.parse(b.toString(), path); + DataclassInit.atLine(gen, c.line); + c.body.addAll(gen.body); + } + + private static void member(Map members, String name, boolean method) { + if (!EXCLUDED.contains(name) && !name.startsWith("_abc_") && !members.containsKey(name)) { + members.put(name, method); + } + } +} diff --git a/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/PydanticLowering.java b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/PydanticLowering.java new file mode 100644 index 00000000000..d2cd43bf275 --- /dev/null +++ b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/PydanticLowering.java @@ -0,0 +1,521 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.python.transpiler.codegen; + +import com.codename1.python.transpiler.api.PythonSyntaxError; +import com.codename1.python.transpiler.ast.Node; +import com.codename1.python.transpiler.ast.Node.Alias; +import com.codename1.python.transpiler.ast.Node.AnnAssign; +import com.codename1.python.transpiler.ast.Node.Assign; +import com.codename1.python.transpiler.ast.Node.Call; +import com.codename1.python.transpiler.ast.Node.ClassDef; +import com.codename1.python.transpiler.ast.Node.DictExpr; +import com.codename1.python.transpiler.ast.Node.Expr; +import com.codename1.python.transpiler.ast.Node.FunctionDef; +import com.codename1.python.transpiler.ast.Node.ImportFrom; +import com.codename1.python.transpiler.ast.Node.Keyword; +import com.codename1.python.transpiler.ast.Node.Name; +import com.codename1.python.transpiler.ast.Node.Stmt; +import com.codename1.python.transpiler.ast.Node.Subscript; +import com.codename1.python.transpiler.parser.Parser; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/// The per-class hooks a pydantic model class gets, written into the class +/// at compile time as plain Python naming each field literally. +/// +/// The bundled pydantic validates and dumps through a dict of field values; +/// CPython's reads and writes those values with `getattr`/`setattr` over the +/// field names, which is reflection. Here every `class M(BaseModel)` (or a +/// subclass of one in the same module) gets, as if its author had written +/// them: +/// +/// ```python +/// class Item(BaseModel): +/// name: str +/// size: int = 0 +/// # added: +/// def __cn1_pd_load__(self): return {"name": self.name, "size": self.size} +/// def __cn1_pd_store__(self, values): ... # self.name = values["name"] ... +/// @classmethod +/// def __cn1_pd_from_attrs__(cls, v): ... # from_attributes=True +/// def __cn1_pd_init_private__(self): ... # PrivateAttr defaults +/// def __cn1_pd_copy_private__(self, src, deep): ... +/// def __cn1_pd_computed__(self): ... # @computed_field values +/// ``` +/// +/// A frozen or `validate_assignment` model has its fields replaced by +/// properties whose setter calls `BaseModel._cn1_pd_assign` with the field's +/// FieldInfo by position and its literal name (a class binding `__setattr__` has no layout); the hooks read and +/// write the backing slots directly, so construction never meets the frozen +/// check. `class P(RootModel[T])` becomes `class P(RootModel)` with +/// `root: T`, the hooks RootModel itself declares. +/// +/// What cannot be lowered exactly fails the build, naming the class: a +/// model whose base is a model of another module, class keywords, a +/// `model_config` that is not a literal `ConfigDict(...)`/dict, a name-mangled +/// private attribute. +/// +/// Every field of a non-root model is such a property: on a model that is +/// neither frozen nor validate_assignment the setter stores the slot and +/// adds the literal name to `model_fields_set`. A name that is not a field +/// reaches `BaseModel.__cn1_new_attr__` (the runtime's new-attribute hook), +/// which raises pydantic's ValueError or writes the extras dict. +public final class PydanticLowering { + + private PydanticLowering() { + } + + private static final class Model { + final List fields = new ArrayList(); + final List privates = new ArrayList(); + final List computed = new ArrayList(); + /// The class's own field annotations, in order, for __cn1_pd_ann__. + final List annNodes = new ArrayList(); + /// Fields are properties over `_cn1pd_` slots: every non-root model. + boolean props; + /// frozen or validate_assignment: the setter goes through _cn1_pd_assign. + boolean guarded; + boolean frozen; + } + + /// Lowers the model classes of `tree`, the module at path `path`. + public static void rewrite(Node.Module tree, String path) { + if (path.endsWith("pydantic/__init__.py")) { + return; + } + Set base = new HashSet(); + Set root = new HashSet(); + Set computedDeco = new HashSet(); + Set fieldFn = new HashSet(); + Set privateFn = new HashSet(); + for (Stmt s : tree.body) { + if (s instanceof ImportFrom && "pydantic".equals(((ImportFrom) s).module) && ((ImportFrom) s).level == 0) { + for (Alias a : ((ImportFrom) s).names) { + String bound = a.asname != null ? a.asname : a.name; + if ("BaseModel".equals(a.name)) { + base.add(bound); + } else if ("RootModel".equals(a.name)) { + root.add(bound); + } else if ("computed_field".equals(a.name)) { + computedDeco.add(bound); + } else if ("Field".equals(a.name)) { + fieldFn.add(bound); + } else if ("PrivateAttr".equals(a.name)) { + privateFn.add(bound); + } + } + } + } + if (base.isEmpty() && root.isEmpty()) { + return; + } + Map models = new HashMap(); + for (int i = 0; i < tree.body.size(); i++) { + Stmt s = tree.body.get(i); + if (s instanceof ClassDef + && lower((ClassDef) s, path, base, root, computedDeco, fieldFn, privateFn, models)) { + // The tables the metaclass used to build, made once the + // class exists: `Item.__cn1_pd_setup__()`. + for (Stmt g : Parser.parse(((ClassDef) s).name + ".__cn1_pd_setup__()\n", path).body) { + DataclassInit.atLine(g, s.line); + tree.body.add(++i, g); + } + } + } + refuseNested(tree.body, path, base, root, models, false); + } + + /// A model class not at module level is refused: its hooks would be + /// lowered with nothing to check the base against. + private static void refuseNested(Object o, String path, Set base, Set root, + Map models, boolean nested) { + if (o instanceof ClassDef) { + ClassDef c = (ClassDef) o; + if (nested && !c.bases.isEmpty() && modelBase(c.bases.get(0), base, root, models)) { + throw error(path, c, "pydantic model class " + c.name + + " is not defined at module level; its per-class hooks cannot be generated"); + } + for (Stmt s : c.body) { + refuseNested(s, path, base, root, models, true); + } + return; + } + if (o instanceof FunctionDef) { + for (Stmt s : ((FunctionDef) o).body) { + refuseNested(s, path, base, root, models, true); + } + return; + } + if (o instanceof List) { + for (Object x : (List) o) { + refuseNested(x, path, base, root, models, nested); + } + } + } + + private static boolean modelBase(Expr b, Set base, Set root, Map models) { + if (b instanceof Name) { + String id = ((Name) b).id; + return base.contains(id) || root.contains(id) || models.containsKey(id); + } + return b instanceof Subscript && ((Subscript) b).value instanceof Name + && root.contains(((Name) ((Subscript) b).value).id); + } + + private static boolean lower(ClassDef c, String path, Set base, Set root, Set computedDeco, + Set fieldFn, Set privateFn, Map models) { + if (c.bases.isEmpty()) { + return false; + } + Expr b0 = c.bases.get(0); + Model parent = null; + boolean isRoot = false; + if (b0 instanceof Subscript && ((Subscript) b0).value instanceof Name + && root.contains(((Name) ((Subscript) b0).value).id)) { + // class Pets(RootModel[List[str]]) -> class Pets(RootModel): root: List[str] + Subscript sb = (Subscript) b0; + c.bases.set(0, sb.value); + AnnAssign ann = new AnnAssign(new Name("root"), sb.index, null); + DataclassInit.atLine(ann, c.line); + c.body.add(0, ann); + isRoot = true; + } else if (b0 instanceof Name && root.contains(((Name) b0).id)) { + isRoot = true; + } else if (b0 instanceof Name && models.containsKey(((Name) b0).id)) { + parent = models.get(((Name) b0).id); + } else if (!(b0 instanceof Name && base.contains(((Name) b0).id))) { + for (Expr b : c.bases) { + if (modelBase(b, base, root, models)) { + throw error(path, c, "pydantic model class " + c.name + + " must name its model base first; its hooks cannot be generated"); + } + } + return false; + } + for (int i = 1; i < c.bases.size(); i++) { + if (!(c.bases.get(i) instanceof Name) || modelBase(c.bases.get(i), base, root, models)) { + throw error(path, c, "pydantic model class " + c.name + " has more than one base;" + + " its per-class hooks cannot be generated"); + } + } + if (!c.keywords.isEmpty()) { + throw error(path, c, "pydantic model class " + c.name + " takes class keywords; write them in" + + " model_config = ConfigDict(...) so the build can read them"); + } + Model m = new Model(); + if (parent != null) { + m.fields.addAll(parent.fields); + m.privates.addAll(parent.privates); + m.computed.addAll(parent.computed); + m.props = parent.props; + m.guarded = parent.guarded; + m.frozen = parent.frozen; + } + if (isRoot) { + m.fields.add("root"); + } + List own = new ArrayList(); + List ownPrivates = new ArrayList(); + Set fieldProps = new HashSet(); + boolean ownConfig = false; + for (Stmt s : c.body) { + if (s instanceof AnnAssign && ((AnnAssign) s).target instanceof Name) { + AnnAssign a = (AnnAssign) s; + String n = ((Name) a.target).id; + Expr annBase = a.annotation instanceof Subscript ? ((Subscript) a.annotation).value : a.annotation; + String ann = annBase instanceof Name || annBase instanceof Node.Attribute ? Layouts.text(annBase) : ""; + if ("ClassVar".equals(ann) || "typing.ClassVar".equals(ann) + || isConst(a.annotation, Node.Constant.Kind.STR) + && ((Node.Constant) a.annotation).text.startsWith("ClassVar")) { + continue; + } + if ("model_config".equals(n)) { + ownConfig = true; + config(c, path, a.value, m); + continue; + } + if (n.startsWith("__")) { + throw error(path, s, "pydantic model " + c.name + " field " + n + + " is name-mangled; its hooks cannot name it"); + } + if (n.startsWith("_")) { + if (a.value != null && !m.privates.contains(n)) { + m.privates.add(n); + ownPrivates.add(n); + } + continue; + } + if (!m.fields.contains(n)) { + m.fields.add(n); + } + own.add(n); + if (a.value instanceof Call && ((Call) a.value).func instanceof Name + && fieldFn.contains(((Name) ((Call) a.value).func).id)) { + for (Keyword k : ((Call) a.value).keywords) { + if ("frozen".equals(k.arg) && isConst(k.value, Node.Constant.Kind.TRUE)) { + fieldProps.add(n); + } + } + } + } else if (s instanceof Assign && ((Assign) s).targets.size() == 1 + && ((Assign) s).targets.get(0) instanceof Name) { + Assign a = (Assign) s; + String n = ((Name) a.targets.get(0)).id; + if ("model_config".equals(n)) { + ownConfig = true; + config(c, path, a.value, m); + } else if (a.value instanceof Call && ((Call) a.value).func instanceof Name + && privateFn.contains(((Name) ((Call) a.value).func).id)) { + if (n.startsWith("__")) { + throw error(path, s, "pydantic model " + c.name + " private attribute " + n + + " is name-mangled; its hooks cannot name it"); + } + if (!m.privates.contains(n)) { + m.privates.add(n); + ownPrivates.add(n); + } + } + } else if (s instanceof FunctionDef) { + FunctionDef f = (FunctionDef) s; + for (Expr d : f.decorators) { + Expr fn = d instanceof Call ? ((Call) d).func : d; + if (fn instanceof Name && computedDeco.contains(((Name) fn).id) && !m.computed.contains(f.name)) { + m.computed.add(f.name); + } + } + } + } + if (!ownConfig && parent == null) { + m.frozen = false; + } + if (!fieldProps.isEmpty()) { + m.guarded = true; + } + if (m.guarded && parent != null && !parent.guarded && !parent.fields.isEmpty()) { + throw error(path, c, "pydantic model " + c.name + " turns on frozen/validate_assignment over the" + + " fields of " + Layouts.text(b0) + "; declare it on the base"); + } + // Every field of a non-root model is a property, so a plain store + // adds the name to model_fields_set as pydantic's __setattr__ does. + m.props = !isRoot && !(parent != null && !parent.props && !parent.fields.isEmpty()); + if (isRoot && m.guarded) { + throw error(path, c, "pydantic root model " + c.name + " cannot be frozen or validate_assignment here"); + } + models.put(c.name, m); + if (ownConfig && parent != null) { + // The metaclass merged the bases' config into the class's own; + // the class body does it now: `{**Base.model_config, **(...)}`. + for (Stmt s : c.body) { + Expr v = s instanceof Assign && ((Assign) s).targets.get(0) instanceof Name + && "model_config".equals(((Name) ((Assign) s).targets.get(0)).id) ? ((Assign) s).value : null; + if (v != null) { + throw error(path, c, "pydantic model " + c.name + " sets model_config over a model base;" + + " not supported yet"); + } + } + } + // The annotations, evaluated when the table is asked for: the + // generated dict's values are the class's own annotation nodes. + StringBuilder ann = new StringBuilder("@classmethod\ndef __cn1_pd_ann__(cls):\n return {"); + for (Stmt s : c.body) { + if (s instanceof AnnAssign && ((AnnAssign) s).target instanceof Name + && own.contains(((Name) ((AnnAssign) s).target).id)) { + ann.append('"').append(((Name) ((AnnAssign) s).target).id).append("\": None, "); + m.annNodes.add(((AnnAssign) s).annotation); + } + } + if (isRoot && !own.contains("root")) { + throw error(path, c, "pydantic root model " + c.name + " has no root annotation the build can see"); + } + ann.append("}\n__cn1_pd_privates__ = ("); + for (String p : ownPrivates) { + ann.append('"').append(p).append("\", "); + } + ann.append(")\n"); + emit(c, path, m, own, isRoot, ann.toString()); + return true; + } + + private static void config(ClassDef c, String path, Expr v, Model m) { + List kws = new ArrayList(); + if (v instanceof Call && ((Call) v).func instanceof Name && "ConfigDict".equals(((Name) ((Call) v).func).id) + && ((Call) v).args.isEmpty()) { + kws = ((Call) v).keywords; + } else if (v instanceof DictExpr) { + DictExpr d = (DictExpr) v; + for (int i = 0; i < d.keys.size(); i++) { + Expr k = d.keys.get(i); + if (!isConst(k, Node.Constant.Kind.STR)) { + throw error(path, c, "pydantic model " + c.name + " has a model_config the build cannot read"); + } + kws.add(new Keyword(((Node.Constant) k).text, d.values.get(i))); + } + } else { + throw error(path, c, "pydantic model " + c.name + " has a model_config the build cannot read;" + + " write it as ConfigDict(...) with keywords"); + } + for (Keyword k : kws) { + if (k.arg == null) { + throw error(path, c, "pydantic model " + c.name + " has a model_config the build cannot read"); + } + if ("frozen".equals(k.arg) || "validate_assignment".equals(k.arg)) { + if (isConst(k.value, Node.Constant.Kind.TRUE)) { + m.guarded = true; + } else if (!isConst(k.value, Node.Constant.Kind.FALSE)) { + throw error(path, c, "pydantic model " + c.name + " sets " + k.arg + " to something" + + " other than a literal True or False"); + } + } + } + } + + private static String slot(Model m, String f) { + return m.props ? "self._cn1pd_" + f : "self." + f; + } + + private static void emit(ClassDef c, String path, Model m, List own, boolean isRoot, String tables) { + StringBuilder src = new StringBuilder(tables); + if (!isRoot) { + src.append("def __cn1_pd_load__(self):\n return {"); + for (String f : m.fields) { + src.append('"').append(f).append("\": ").append(slot(m, f)).append(", "); + } + src.append("}\n"); + src.append("def __cn1_pd_store__(self, values):\n pass\n"); + for (String f : m.fields) { + src.append(" if \"").append(f).append("\" in values:\n ").append(slot(m, f)) + .append(" = values[\"").append(f).append("\"]\n"); + } + src.append("@classmethod\ndef __cn1_pd_from_attrs__(cls, v):\n d = {}\n"); + for (String f : m.fields) { + src.append(" if hasattr(v, \"").append(f).append("\"):\n d[\"").append(f) + .append("\"] = v.").append(f).append('\n'); + } + src.append(" return d\n"); + } + if (!m.privates.isEmpty()) { + src.append("def __cn1_pd_init_private__(self):\n"); + src.append("def __cn1_pd_copy_private__(self, src, deep):\n"); + StringBuilder init = new StringBuilder(); + StringBuilder copy = new StringBuilder(); + for (String p : m.privates) { + init.append(" v = self._cn1_pd_private(\"").append(p).append("\")\n if self._cn1_pd_has(v):\n self.") + .append(p).append(" = v\n"); + copy.append(" if hasattr(src, \"").append(p).append("\"):\n self.").append(p) + .append(" = self._cn1_pd_copy(src.").append(p).append(", deep)\n"); + } + int at = src.indexOf("def __cn1_pd_copy_private__"); + src.insert(at, init.toString()); + src.append(copy); + } + if (!m.computed.isEmpty()) { + src.append("def __cn1_pd_computed__(self):\n return {"); + for (String f : m.computed) { + src.append('"').append(f).append("\": self.").append(f).append(", "); + } + src.append("}\n"); + } + if (m.props) { + for (String f : own) { + src.append("@property\ndef ").append(f).append("(self):\n return self._cn1pd_").append(f).append('\n'); + src.append('@').append(f).append(".setter\ndef ").append(f).append("(self, value):\n"); + if (m.guarded) { + // The field's plan entry by its position: model_fields is + // built in m.fields order (__cn1_pd_names__ holds it), so + // nothing is looked up by name. + src.append(" self._cn1pd_").append(f).append(" = self._cn1_pd_assign(") + .append(m.fields.indexOf(f)).append(", \"").append(f).append("\", value)\n"); + } else { + src.append(" self._cn1pd_").append(f).append(" = value\n self.__pydantic_fields_set__.add(\"") + .append(f).append("\")\n"); + } + } + src.append("__cn1_pd_names__ = ("); + for (String f : m.fields) { + src.append('"').append(f).append("\", "); + } + src.append(")\n"); + if (m.guarded && !hasDef(c, "__hash__")) { + src.append("def __hash__(self):\n return self._cn1_pd_hash()\n"); + } + // The defaults the properties displace: the metaclass reads a + // property's field default from `_cn1pd_default_`. + for (int i = 0; i < c.body.size(); i++) { + Stmt s = c.body.get(i); + if (s instanceof AnnAssign && ((AnnAssign) s).target instanceof Name + && own.contains(((Name) ((AnnAssign) s).target).id) && ((AnnAssign) s).value != null) { + AnnAssign a = (AnnAssign) s; + String n = ((Name) a.target).id; + AnnAssign bare = new AnnAssign(a.target, a.annotation, null); + Assign dflt = new Assign(new ArrayList(Collections.singletonList(new Name("_cn1pd_default_" + n))), + a.value); + DataclassInit.atLine(bare, s.line); + DataclassInit.atLine(dflt.targets, s.line); + dflt.line = s.line; + c.body.set(i, bare); + c.body.add(i + 1, dflt); + i++; + } + } + } + if (src.length() == 0) { + return; + } + int line = c.body.isEmpty() ? c.line : c.body.get(c.body.size() - 1).line; + for (Stmt s : Parser.parse(src.toString(), path).body) { + DataclassInit.atLine(s, line); + if (s instanceof FunctionDef && "__cn1_pd_ann__".equals(((FunctionDef) s).name)) { + Node.DictExpr d = (Node.DictExpr) ((Node.Return) ((FunctionDef) s).body.get(0)).value; + for (int i = 0; i < m.annNodes.size(); i++) { + d.values.set(i, m.annNodes.get(i)); + } + } + c.body.add(s); + } + } + + private static boolean isConst(Expr e, Node.Constant.Kind k) { + return e instanceof Node.Constant && ((Node.Constant) e).kind == k; + } + + private static boolean hasDef(ClassDef c, String name) { + for (Stmt s : c.body) { + if (s instanceof FunctionDef && name.equals(((FunctionDef) s).name)) { + return true; + } + } + return false; + } + + private static PythonSyntaxError error(String path, Node at, String why) { + return new PythonSyntaxError(path, at.line, 1, why); + } +} diff --git a/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/PytestLowering.java b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/PytestLowering.java new file mode 100644 index 00000000000..30da0e7c1c8 --- /dev/null +++ b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/PytestLowering.java @@ -0,0 +1,477 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.python.transpiler.codegen; + +import com.codename1.python.transpiler.ast.Node; +import com.codename1.python.transpiler.ast.Node.Alias; +import com.codename1.python.transpiler.ast.Node.Attribute; +import com.codename1.python.transpiler.ast.Node.Call; +import com.codename1.python.transpiler.ast.Node.ClassDef; +import com.codename1.python.transpiler.ast.Node.Constant; +import com.codename1.python.transpiler.ast.Node.Expr; +import com.codename1.python.transpiler.ast.Node.ExprStmt; +import com.codename1.python.transpiler.ast.Node.FunctionDef; +import com.codename1.python.transpiler.ast.Node.Import; +import com.codename1.python.transpiler.ast.Node.ImportFrom; +import com.codename1.python.transpiler.ast.Node.Keyword; +import com.codename1.python.transpiler.parser.Parser; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; + +/// Gives the bundled pytest a test table written at build time. +/// +/// pytest finds tests and fixtures by name -- `dir(module)`, then +/// `getattr(module, name)` for every `test_*`, and a fixture by the name of +/// the parameter asking for it -- which is reflection. Here every module +/// that imports pytest gets one more statement, after its last test or +/// fixture definition, +/// +/// ```python +/// import pytest as _cn1_pytest_mod +/// __cn1_pytest__ = _cn1_pytest_mod._Table([ +/// ("f", "total", total, ("numbers",), +/// lambda _cn1_r: total(numbers=_cn1_r("numbers"))), +/// ("c", "TestGroup", TestGroup, [ +/// ("test_m", TestGroup.test_m, ("k",), +/// lambda _cn1_s, _cn1_r: _cn1_s.test_m(k=_cn1_r("k")), +/// lambda _cn1_s: _cn1_s.test_m)]), +/// ]) +/// ``` +/// +/// listing, in `dir` order, each module-level `test*` function and fixture, +/// each `Test*` class with its `test*` methods and fixtures, the fixture +/// names each one asks for (its parameters without defaults, read from the +/// signature) and a call that passes each of them literally. The runner +/// iterates the table and resolves a name through dictionaries of fixtures, +/// never through attributes. +/// +/// `monkeypatch.setattr(obj, "name", value)`, `delattr(obj, "name")` and +/// `setattr("pkg.mod.attr", value)` get their accessors as one more keyword, +/// `_cn1_acc=(name, get, set, delete, owner)`, each lambda naming the +/// attribute literally; `owner` resolves a dotted target by trying each +/// module prefix of the path, longest first, with the rest as literal +/// attribute loads. No receiver is trusted by its name: a call statement +/// `r.setattr(...)` with a readable name becomes +/// `_cn1_pytest_mod._cn1_mp(r, delete, acc)(...)`, which hands the accessors +/// to `r` only when it is a MonkeyPatch at run time and otherwise calls +/// `r.setattr` unchanged, so any other object with such a method is +/// unaffected. A call the build cannot lower is refused in strict mode, +/// naming its line, when its receiver may be a MonkeyPatch: a parameter +/// named `monkeypatch` (the fixture) or a name bound from `MonkeyPatch()` or +/// `.context()`. A fixture defined inside a function, and +/// `run_module(sys.modules[__name__])` in a module that gets no table, are +/// refused the same way. +public final class PytestLowering { + + private PytestLowering() { + } + + /// Adds the test table and the monkeypatch accessors to `tree`, the module at `path`. + public static void rewrite(Node.Module tree, String path) { + if (path.endsWith("pytest/__init__.py") || "pytest.py".equals(path) || !importsPytest(tree)) { + return; + } + // One alias of pytest the generated code names, bound right after + // the module's own import of it. + tree.body.add(pytestImport(tree) + 1, Parser.parse("import pytest as _cn1_pytest_mod\n", path).body.get(0)); + List known = new ArrayList(); + Infer.children(tree, x -> knownMonkeypatches(x, known)); + monkeypatch(tree.body, path, known); + nestedFixtures(tree.body, false); + Map entries = new TreeMap(); + int last = -1; + for (int i = 0; i < tree.body.size(); i++) { + Node.Stmt s = tree.body.get(i); + if (s instanceof FunctionDef) { + FunctionDef f = (FunctionDef) s; + if (f.name.startsWith("test") || isFixture(f)) { + entries.put(f.name, "(\"f\", \"" + f.name + "\", " + f.name + ", " + deps(f, false) + + ", lambda _cn1_r: " + call(f.name, f, false) + ")"); + last = i; + } else { + entries.remove(f.name); + } + } else if (s instanceof ClassDef) { + ClassDef c = (ClassDef) s; + if (c.name.startsWith("Test")) { + entries.put(c.name, classEntry(c)); + last = i; + } else { + entries.remove(c.name); + } + } + } + if (last < 0) { + Infer.children(tree, PytestLowering::selfRunWithoutTable); + return; + } + StringBuilder src = new StringBuilder("__cn1_pytest__ = _cn1_pytest_mod._Table(["); + for (String e : entries.values()) { + src.append(e).append(", "); + } + src.append("])\n"); + Node.Module gen = Parser.parse(src.toString(), path); + tree.body.addAll(last + 1, gen.body); + } + + private static String classEntry(ClassDef c) { + Map members = new TreeMap(); + for (Node.Stmt s : c.body) { + if (!(s instanceof FunctionDef)) { + continue; + } + FunctionDef f = (FunctionDef) s; + if (f.name.startsWith("__") || !(f.name.startsWith("test") || isFixture(f))) { + members.remove(f.name); + continue; + } + boolean bound = !decorated(f, "staticmethod"); + members.put(f.name, "(\"" + f.name + "\", " + c.name + "." + f.name + ", " + deps(f, bound) + + ", lambda _cn1_s, _cn1_r: " + call("_cn1_s." + f.name, f, bound) + + ", lambda _cn1_s: _cn1_s." + f.name + ")"); + } + StringBuilder b = new StringBuilder("(\"c\", \"" + c.name + "\", " + c.name + ", ["); + for (String m : members.values()) { + b.append(m).append(", "); + } + return b.append("])").toString(); + } + + /// The parameters pytest fills with fixtures: those without a default, + /// past `self`/`cls` for a method. + private static List fixtureParams(FunctionDef f, boolean method) { + Node.Arguments a = f.args; + List r = new ArrayList(); + int required = a.positional.size() - a.defaults.size(); + for (int i = method ? 1 : 0; i < required; i++) { + r.add(a.positional.get(i)); + } + for (int i = 0; i < a.kwonly.size(); i++) { + if (a.kwDefaults.get(i) == null) { + r.add(a.kwonly.get(i)); + } + } + return r; + } + + private static String deps(FunctionDef f, boolean method) { + StringBuilder b = new StringBuilder("("); + for (Node.Arg a : fixtureParams(f, method)) { + b.append('"').append(a.name).append("\", "); + } + return b.append(')').toString(); + } + + private static String call(String callee, FunctionDef f, boolean method) { + StringBuilder b = new StringBuilder(callee).append('('); + for (Node.Arg a : fixtureParams(f, method)) { + int at = f.args.positional.indexOf(a); + if (at >= 0 && at < f.args.positionalOnly) { + b.append("_cn1_r(\"").append(a.name).append("\"), "); + } else { + b.append(a.name).append("=_cn1_r(\"").append(a.name).append("\"), "); + } + } + return b.append(')').toString(); + } + + private static boolean isFixture(FunctionDef f) { + return decorated(f, "fixture"); + } + + private static boolean decorated(FunctionDef f, String name) { + for (Expr d : f.decorators) { + Expr e = d instanceof Call ? ((Call) d).func : d; + if (e instanceof Node.Name && name.equals(((Node.Name) e).id) + || e instanceof Attribute && name.equals(((Attribute) e).attr)) { + return true; + } + } + return false; + } + + private static boolean importsPytest(Node.Module tree) { + return pytestImport(tree) >= 0; + } + + /// The index of the first top-level statement importing pytest, or -1. + private static int pytestImport(Node.Module tree) { + for (int i = 0; i < tree.body.size(); i++) { + Node.Stmt s = tree.body.get(i); + if (s instanceof ImportFrom && "pytest".equals(((ImportFrom) s).module)) { + return i; + } + if (s instanceof Import) { + for (Alias a : ((Import) s).names) { + if ("pytest".equals(a.name)) { + return i; + } + } + } + } + return -1; + } + + /// Collects the names that may hold a MonkeyPatch: parameters named + /// `monkeypatch` and names bound from `MonkeyPatch(...)` or `.context()`. + private static void knownMonkeypatches(Object o, List known) { + if (o instanceof FunctionDef) { + Node.Arguments a = ((FunctionDef) o).args; + for (Node.Arg p : a.positional) { + if ("monkeypatch".equals(p.name)) { + known.add(p.name); + } + } + for (Node.Arg p : a.kwonly) { + if ("monkeypatch".equals(p.name)) { + known.add(p.name); + } + } + } else if (o instanceof Node.Assign && makesMonkeypatch(((Node.Assign) o).value)) { + for (Expr t : ((Node.Assign) o).targets) { + if (t instanceof Node.Name) { + known.add(((Node.Name) t).id); + } + } + } else if (o instanceof Node.WithItem && makesMonkeypatch(((Node.WithItem) o).context) + && ((Node.WithItem) o).vars instanceof Node.Name) { + known.add(((Node.Name) ((Node.WithItem) o).vars).id); + } + Infer.children(o, x -> knownMonkeypatches(x, known)); + } + + private static boolean makesMonkeypatch(Expr e) { + if (!(e instanceof Call)) { + return false; + } + Expr f = ((Call) e).func; + String n = f instanceof Node.Name ? ((Node.Name) f).id : f instanceof Attribute ? ((Attribute) f).attr : null; + return "MonkeyPatch".equals(n) || "context".equals(n); + } + + private static boolean mayBeMonkeypatch(Expr recv, List known) { + return recv instanceof Node.Name && known.contains(((Node.Name) recv).id); + } + + private static Attribute patchCall(Object o) { + if (o instanceof Call && ((Call) o).func instanceof Attribute) { + Attribute fn = (Attribute) ((Call) o).func; + if ("setattr".equals(fn.attr) || "delattr".equals(fn.attr)) { + return fn; + } + } + return null; + } + + @SuppressWarnings("unchecked") + private static void monkeypatch(Object o, String path, List known) { + if (o instanceof List) { + List l = (List) o; + for (int i = 0; i < l.size(); i++) { + Object x = l.get(i); + if (x instanceof ExprStmt && patchCall(((ExprStmt) x).value) != null) { + Call c = (Call) ((ExprStmt) x).value; + Attribute fn = (Attribute) c.func; + boolean set = "setattr".equals(fn.attr); + String acc = accessors(c, set); + if (acc != null) { + l.set(i, viaHelper(c, fn, set, acc, path)); + continue; + } + if (mayBeMonkeypatch(fn.value, known)) { + c.refusal = refusalOf(c, set); + } + } + monkeypatch(x, path, known); + } + return; + } + Attribute fn = patchCall(o); + if (fn != null && mayBeMonkeypatch(fn.value, known)) { + // An expression position: the receiver is a MonkeyPatch by what + // bound it, so the accessors are passed directly. + Call c = (Call) o; + boolean set = "setattr".equals(fn.attr); + String acc = accessors(c, set); + if (acc == null) { + c.refusal = refusalOf(c, set); + } else { + c.keywords.add(new Keyword("_cn1_acc", ((ExprStmt) Parser.parse(acc + "\n", path).body.get(0)).value)); + } + } + if (!(o instanceof Node)) { + return; + } + // Statement lists are walked as lists, so a call statement in any + // block can be replaced in place. + for (Class k = o.getClass(); k != null && k != Object.class; k = k.getSuperclass()) { + for (java.lang.reflect.Field f : k.getDeclaredFields()) { + if (java.lang.reflect.Modifier.isStatic(f.getModifiers()) + || !java.lang.reflect.Modifier.isPublic(f.getModifiers())) { + continue; + } + try { + Object x = f.get(o); + if (x instanceof List || x instanceof Node) { + monkeypatch(x, path, known); + } + } catch (IllegalAccessException e) { + throw new IllegalStateException(e); + } + } + } + } + + private static ExprStmt viaHelper(Call c, Attribute fn, boolean set, String acc, String path) { + ExprStmt s = (ExprStmt) Parser.parse("_cn1_pytest_mod._cn1_mp(_cn1_x, " + (set ? "False" : "True") + ", " + + acc + ")()\n", path).body.get(0); + Call outer = (Call) s.value; + Call inner = (Call) outer.func; + inner.args.set(0, fn.value); + outer.args.addAll(c.args); + outer.keywords.addAll(c.keywords); + s.line = c.line; + s.col = c.col; + outer.line = c.line; + outer.col = c.col; + inner.line = c.line; + inner.col = c.col; + return s; + } + + private static String refusalOf(Call c, boolean set) { + String what = "monkeypatch." + (set ? "setattr" : "delattr") + "(...)"; + for (Keyword k : c.keywords) { + if (k.arg == null || "name".equals(k.arg) || "target".equals(k.arg) || "value".equals(k.arg)) { + return what + " with keyword or **mapping arguments the build cannot read; pass the target" + + " and a literal name positionally"; + } + } + return what + " with an attribute name the build cannot read stores by computed name, which is" + + " reflection; write the name as a literal"; + } + + /// The `_cn1_acc` tuple's source for `c`, or null when the build cannot read the name. + private static String accessors(Call c, boolean set) { + for (Keyword k : c.keywords) { + if (k.arg == null || "name".equals(k.arg) || "target".equals(k.arg) || "value".equals(k.arg) + || "_cn1_acc".equals(k.arg)) { + return null; + } + } + for (Expr a : c.args) { + if (a instanceof Node.Starred) { + return null; + } + } + String dotted = set && c.args.size() == 2 ? str(c.args.get(0)) : null; + String owner = "None"; + String name; + if (dotted != null && dotted.indexOf('.') > 0) { + name = dotted.substring(dotted.lastIndexOf('.') + 1); + owner = owner(dotted.substring(0, dotted.lastIndexOf('.'))); + } else { + name = c.args.size() >= 2 ? str(c.args.get(1)) : null; + } + if (name == null || !ident(name)) { + return null; + } + return "(\"" + name + "\", lambda _cn1_o, _cn1_d: getattr(_cn1_o, \"" + name + "\", _cn1_d), " + + "lambda _cn1_o, _cn1_v: setattr(_cn1_o, \"" + name + "\", _cn1_v), " + + "lambda _cn1_o: delattr(_cn1_o, \"" + name + "\"), " + owner + ")"; + } + + /// Refuses a `@fixture` defined inside a function: the runner's table + /// lists top-level and class fixtures only. + private static void nestedFixtures(Object o, boolean inFunction) { + if (o instanceof FunctionDef) { + FunctionDef f = (FunctionDef) o; + if (inFunction && isFixture(f)) { + f.refusal = "@pytest.fixture '" + f.name + "' defined inside a function is registered only when" + + " that function runs; define fixtures at module or class level"; + } + for (Node.Stmt s : f.body) { + nestedFixtures(s, true); + } + return; + } + Infer.children(o, x -> nestedFixtures(x, inFunction)); + } + + /// Refuses `run_module(sys.modules[__name__])` in a module that defines no tests. + private static void selfRunWithoutTable(Object o) { + if (o instanceof Call && ((Call) o).args.size() >= 1) { + Call c = (Call) o; + String n = c.func instanceof Node.Name ? ((Node.Name) c.func).id + : c.func instanceof Attribute ? ((Attribute) c.func).attr : null; + Expr a = c.args.get(0); + if ("run_module".equals(n) && a instanceof Node.Subscript + && ((Node.Subscript) a).index instanceof Node.Name + && "__name__".equals(((Node.Name) ((Node.Subscript) a).index).id)) { + c.refusal = "pytest.run_module on this module, which defines no top-level test_* function or" + + " Test* class, so the build wrote it no test table"; + } + } + Infer.children(o, PytestLowering::selfRunWithoutTable); + } + + /// `lambda: _cn1_pytest_mod._dotted(path, ((module, load), ...))`, longest module prefix first. + private static String owner(String path) { + String[] parts = path.split("\\."); + StringBuilder b = new StringBuilder("lambda: _cn1_pytest_mod._dotted(\"" + path + "\", ("); + for (int i = parts.length; i > 0; i--) { + StringBuilder mod = new StringBuilder(); + StringBuilder load = new StringBuilder("_cn1_m"); + for (int j = 0; j < parts.length; j++) { + if (j < i) { + mod.append(j == 0 ? "" : ".").append(parts[j]); + } else { + load.append('.').append(parts[j]); + } + } + b.append("(\"").append(mod).append("\", lambda _cn1_m: ").append(load).append("), "); + } + return b.append("))").toString(); + } + + private static String str(Expr e) { + return e instanceof Constant && ((Constant) e).kind == Constant.Kind.STR ? ((Constant) e).text : null; + } + + private static boolean ident(String s) { + if (s.isEmpty() || !Character.isJavaIdentifierStart(s.charAt(0)) || s.charAt(0) == '$') { + return false; + } + for (int i = 1; i < s.length(); i++) { + char ch = s.charAt(i); + if (!(ch == '_' || ch < 128 && Character.isLetterOrDigit(ch))) { + return false; + } + } + return true; + } +} diff --git a/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/SerialisableMethods.java b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/SerialisableMethods.java new file mode 100644 index 00000000000..856fec52c49 --- /dev/null +++ b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/SerialisableMethods.java @@ -0,0 +1,423 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.python.transpiler.codegen; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/// The Python [DeclarativeMap] writes into one openpyxl model class: the +/// metaclass's tuples as literals, and `Serialisable`'s generic methods +/// unrolled over them. +/// +/// Each method is `openpyxl/descriptors/serialisable.py`'s own, statement +/// for statement, with its loop over `__attrs__` or `__elements__` +/// replaced by one block per name. A field is then read as `self.name`, +/// which the inference can type, where the generic method's +/// `getattr(self, attr)` names no field at all. What the descriptor kind +/// settles is decided here: whether a child is a `NestedSequence`, a +/// `Sequence` or nested. +public final class SerialisableMethods { + /// The module holding what the generated methods share, once: how a + /// child element is read through the descriptor that names it. The + /// descriptor is handed in, read by name in the class's own + /// `from_tree` (one branch per descriptor the class and its bases + /// declare), and `__copy__` names each instance key it carries over, so + /// nothing here looks a name up. + public static final String MODULE_PATH = "openpyxl/_dm_serialisable.py"; + private static final String MODULE = "from openpyxl.descriptors.serialisable import KEYWORDS, localname, Sequence, " + + "NestedSequence, MultiSequencePart, safe_string, Element, namespaced, copy, seq_types, Descriptor\n" + + "def child(desc, tag, el, attrib):\n" + + " if hasattr(desc, 'from_tree'):\n obj = desc.from_tree(el)\n else:\n" + + " if hasattr(desc.expected_type, \"from_tree\"):\n obj = desc.expected_type.from_tree(el)\n" + + " else:\n obj = el.text\n if isinstance(desc, NestedSequence):\n" + + " attrib[tag] = obj\n elif isinstance(desc, Sequence):\n attrib.setdefault(tag, [])\n" + + " attrib[tag].append(obj)\n elif isinstance(desc, MultiSequencePart):\n" + + " attrib.setdefault(desc.store, [])\n attrib[desc.store].append(obj)\n else:\n" + + " attrib[tag] = obj\n" + + "def text(v):\n if isinstance(v, str):\n return v\n return None\n"; + /// The source of the module at [#MODULE_PATH]. + public static String moduleSource() { + return MODULE; + } + + /// The names the generated methods use, imported under names no model + /// module binds. + static final String HELPERS = "from openpyxl._dm_serialisable import KEYWORDS as _dm_KEYWORDS, " + + "localname as _dm_localname, Sequence as _dm_Sequence, NestedSequence as _dm_NestedSequence, " + + "safe_string as _dm_safe_string, Element as _dm_Element, namespaced as _dm_namespaced, " + + "seq_types as _dm_seq_types, child as _dm_child, copy as _dm_copy, text as _dm_text, " + + "Descriptor as _dm_Descriptor\n"; + /// Each generic method of `Serialisable` and the method that calls the + /// per-class `_dm_` version in its place. A class whose lineage binds a + /// method of its own gets the generated one under the `_dm_` name, and + /// `super().name(...)` from that lineage reaches it through these. + static final Map DISPATCH = new LinkedHashMap(); + + static { + DISPATCH.put("from_tree", "@classmethod\ndef from_tree(cls, node):\n return cls._dm_from_tree(node)\n"); + DISPATCH.put("to_tree", "def to_tree(self, tagname=None, idx=None, namespace=None):\n" + + " return self._dm_to_tree(tagname, idx, namespace)\n"); + DISPATCH.put("__iter__", "def __iter__(self):\n return self._dm___iter__()\n"); + DISPATCH.put("__eq__", "def __eq__(self, other):\n return self._dm___eq__(other)\n"); + DISPATCH.put("__repr__", "def __repr__(self):\n return self._dm___repr__()\n"); + DISPATCH.put("__hash__", "def __hash__(self):\n return self._dm___hash__()\n"); + DISPATCH.put("__add__", "def __add__(self, other):\n return self._dm___add__(other)\n"); + DISPATCH.put("__copy__", "def __copy__(self):\n return self._dm___copy__()\n"); + } + + /// What replaces `Serialisable`'s generic methods: the dispatchers, + /// and the `_dm_` methods every model class overrides. + static String baseSource() { + StringBuilder b = new StringBuilder(); + for (Map.Entry e : DISPATCH.entrySet()) { + b.append(e.getValue()); + String d = e.getValue().replaceFirst("def " + e.getKey() + "\\(", "def _dm_" + e.getKey() + "("); + b.append(d.substring(0, d.indexOf(" return "))) + .append(" raise NotImplementedError(\"generated per class\")\n"); + } + return b.toString(); + } + + /// `src`, one generated method, under the name `name` takes in a class + /// whose lineage binds `custom` and whose subclasses bind `below`; with + /// the dispatcher when only a subclass binds it. + private static String place(String name, String src, Set custom, Set below) { + if (!custom.contains(name) && !below.contains(name)) { + return src; + } + String renamed = src.replaceFirst("(?m)^def " + name + "\\(", "def _dm_" + name + "("); + return custom.contains(name) ? renamed : renamed + DISPATCH.get(name); + } + private static final Set KEYWORDS = new HashSet(Arrays.asList("False", "None", "True", "and", + "as", "assert", "async", "await", "break", "class", "continue", "def", "del", "elif", "else", "except", + "finally", "for", "from", "global", "if", "import", "in", "is", "lambda", "nonlocal", "not", "or", + "pass", "raise", "return", "try", "while", "with", "yield")); + + private SerialisableMethods() { + } + + /// `obj.name`, or a constant-name `getattr` where `name` is not one. + private static String read(String obj, String name) { + boolean ident = !name.isEmpty() && !KEYWORDS.contains(name) && !name.startsWith("__") + && (Character.isLetter(name.charAt(0)) || name.charAt(0) == '_'); + for (int i = 0; i < name.length() && ident; i++) { + char ch = name.charAt(i); + ident = ch < 0x80 && (Character.isLetterOrDigit(ch) || ch == '_'); + } + return ident ? obj + "." + name : "getattr(" + obj + ", " + DeclarativeMap.quote(name) + ")"; + } + + private static String tuple(List names) { + StringBuilder b = new StringBuilder("("); + for (String n : names) { + b.append(DeclarativeMap.quote(n)).append(", "); + } + return b.append(')').toString(); + } + + /// The class-body source; `custom` names what the class or a program base + /// below `Serialisable` binds, `below` what a program subclass binds. + @SuppressWarnings("checkstyle:ParameterNumber") + static String methods(List attrs, List elements, List nested, List namespaced, + Map kinds, Set written, Set lowered, List aliases, + Set custom, Set below, List init, Map descs, + List copied) { + StringBuilder b = new StringBuilder(); + if (written.contains("__attrs__")) { + b.append("__attrs__ = ").append(tuple(attrs)).append('\n'); + } + if (written.contains("__elements__")) { + b.append("__elements__ = ").append(tuple(elements)).append('\n'); + } + if (written.contains("__nested__")) { + b.append("__nested__ = ").append(tuple(nested)).append('\n'); + } + StringBuilder ns = new StringBuilder("("); + for (String[] p : namespaced) { + ns.append('(').append(DeclarativeMap.quote(p[0])).append(", ").append(DeclarativeMap.quote(p[1])) + .append("), "); + } + ns.append(')'); + b.append("__namespaced__ = ").append(ns).append('\n'); + StringBuilder m = new StringBuilder(); + iter(m, attrs, lowered); + b.append(place("__iter__", m.toString(), custom, below)); + m.setLength(0); + toTree(m, attrs, elements, nested, namespaced, kinds); + b.append(place("to_tree", m.toString(), custom, below)); + m.setLength(0); + fromTree(m, attrs, namespaced, lowered, aliases, init, descs); + b.append(place("from_tree", m.toString(), custom, below)); + m.setLength(0); + { + m.append("def __eq__(self, other):\n if not self.__class__ == other.__class__:\n return False\n" + + " elif not dict(self) == dict(other):\n return False\n"); + for (String e : elements) { + m.append(" if ").append(read("self", e)).append(" != ").append(read("other", e)) + .append(":\n return False\n"); + } + m.append(" return True\n"); + b.append(place("__eq__", m.toString(), custom, below)); + m.setLength(0); + } + { + m.append("def __repr__(self):\n s = u\"<{0}.{1} object>\\nParameters:\".format(self.__module__, " + + "self.__class__.__name__)\n args = []\n"); + List all = new ArrayList(attrs); + all.addAll(elements); + for (String k : all) { + m.append(" v = ").append(read("self", k)).append("\n if isinstance(v, _dm_Descriptor):\n" + + " v = None\n args.append(u\"{0}={1}\".format(").append(DeclarativeMap.quote(k)) + .append(", repr(v)))\n"); + } + m.append(" return u\"\\n\".join([s, u\", \".join(args)])\n"); + b.append(place("__repr__", m.toString(), custom, below)); + m.setLength(0); + } + // A class that defines __eq__ alone has its __hash__ set to None by + // Python; adding one would make it hashable. Such a lineage gets + // the generated one under the `_dm_` name, which nothing calls. + if (custom.contains("__eq__") && !custom.contains("__hash__")) { + custom = new HashSet(custom); + custom.add("__hash__"); + } + { + List all = new ArrayList(attrs); + all.addAll(elements); + m.append("def __hash__(self):\n"); + for (int i = 0; i < all.size(); i++) { + m.append(" f").append(i).append(" = ").append(read("self", all.get(i))).append("\n if isinstance(f") + .append(i).append(", list):\n f").append(i).append(" = tuple(f").append(i).append(")\n"); + } + m.append(" return hash(("); + for (int i = 0; i < all.size(); i++) { + m.append('f').append(i).append(", "); + } + m.append("))\n"); + b.append(place("__hash__", m.toString(), custom, below)); + m.setLength(0); + } + { + m.append("def __add__(self, other):\n if type(self) != type(other):\n" + + " raise TypeError(\"Cannot combine instances of different types\")\n vals = {}\n"); + for (String a : attrs) { + m.append(" vals[").append(DeclarativeMap.quote(a)).append("] = ").append(read("self", a)) + .append(" or ").append(read("other", a)).append('\n'); + } + for (String e : elements) { + String q = DeclarativeMap.quote(e); + m.append(" a = ").append(read("self", e)).append("\n b = ").append(read("other", e)) + .append("\n if a and b:\n vals[").append(q).append("] = a + b\n else:\n vals[") + .append(q).append("] = a or b\n"); + } + m.append(" return self.__class__(**vals)\n"); + b.append(place("__add__", m.toString(), custom, below)); + m.setLength(0); + } + { + // The persisted names, plus the slots a lowered field keeps its + // value in, which the descriptor kept under the field's name. + List skip = new ArrayList(attrs); + skip.addAll(elements); + for (String a : new ArrayList(skip)) { + if (lowered.contains(a)) { + skip.add("_dm_" + a); + } + } + // Each key the instance dictionary may hold, by name; the + // generic method walked the dictionary with getattr/setattr. + m.append("def __copy__(self):\n xml = self.to_tree(tagname=\"dummy\")\n" + + " cp = self.__class__.from_tree(xml)\n d = self.__dict__\n"); + for (String k : copied) { + if (!skip.contains(k)) { + String q = DeclarativeMap.quote(k); + String target = read("cp", k); + String v = "_dm_copy(" + read("self", k) + ")"; + m.append(" if ").append(q).append(" in d:\n ") + .append(target.startsWith("getattr(") ? "setattr(cp, " + q + ", " + v + ")" + : target + " = " + v).append('\n'); + } + } + m.append(" return cp\n"); + b.append(place("__copy__", m.toString(), custom, below)); + } + return b.toString(); + } + + private static void iter(StringBuilder b, List attrs, Set lowered) { + b.append("def __iter__(self):\n"); + if (attrs.isEmpty()) { + b.append(" return\n yield\n"); + return; + } + for (String attr : attrs) { + b.append(" value = ").append(read("self", attr)).append('\n'); + if ("attr_text".equals(attr)) { + continue; + } + String key = DeclarativeMap.quote(attr.startsWith("_") ? attr.substring(1) : attr); + if (!attr.startsWith("_") && attr.indexOf('_') >= 0) { + if (lowered.contains(attr)) { + // A lowered descriptor took no `hyphenated` keyword. + key = DeclarativeMap.quote(attr); + } else { + b.append(" key = ").append(DeclarativeMap.quote(attr)).append("\n if getattr(getattr(self.__class__, ") + .append(DeclarativeMap.quote(attr)).append("), \"hyphenated\", False):\n key = ") + .append(DeclarativeMap.quote(attr.replace('_', '-'))).append('\n'); + key = "key"; + } + } + b.append(" if value is not None:\n yield ").append(key).append(", _dm_safe_string(value)\n"); + } + } + + @SuppressWarnings("checkstyle:ParameterNumber") + private static void toTree(StringBuilder b, List attrs, List elements, List nested, + List namespaced, Map kinds) { + b.append("def to_tree(self, tagname=None, idx=None, namespace=None):\n if tagname is None:\n" + + " tagname = self.tagname\n if tagname.startswith(\"_\"):\n tagname = tagname[1:]\n" + + " tagname = _dm_namespaced(self, tagname, namespace)\n" + + " namespace = getattr(self, \"namespace\", namespace)\n attrs = dict(self)\n"); + for (String[] p : namespaced) { + String k = DeclarativeMap.quote(p[0]); + b.append(" if ").append(k).append(" in attrs:\n attrs[").append(DeclarativeMap.quote(p[1])) + .append("] = attrs[").append(k).append("]\n del attrs[").append(k).append("]\n"); + } + b.append(" el = _dm_Element(tagname, attrs)\n"); + if (attrs.contains("attr_text")) { + b.append(" el.text = _dm_safe_string(self.attr_text)\n"); + } + for (String e : elements) { + String q = DeclarativeMap.quote(e); + String kind = kinds.get(e); + b.append(" desc = getattr(self.__class__, ").append(q).append(", None)\n obj = ").append(read("self", e)) + .append("\n if hasattr(desc, \"namespace\") and hasattr(obj, 'namespace'):\n" + + " obj.namespace = desc.namespace\n if isinstance(obj, _dm_seq_types):\n"); + String nestedSeq = " if obj:\n el.append(desc.to_tree(" + q + ", obj, namespace))\n"; + String seq = " desc.idx_base = self.idx_base\n for node in desc.to_tree(" + q + + ", obj, namespace):\n el.append(node)\n"; + String other = " for v in obj:\n el.append(v.to_tree(" + q + ", namespace))\n"; + if ("nestedseq".equals(kind)) { + b.append(nestedSeq); + } else if ("seq".equals(kind)) { + b.append(seq); + } else if ("other".equals(kind)) { + b.append(other); + } else { + // A name the class dictionary does not declare: decide at + // run time, as the generic method does. + b.append(" if isinstance(desc, _dm_NestedSequence):\n").append(indent(nestedSeq)) + .append(" elif isinstance(desc, _dm_Sequence):\n").append(indent(seq)) + .append(" else:\n").append(indent(other)); + } + b.append(" else:\n"); + if (nested.contains(e)) { + b.append(" node = desc.to_tree(").append(q).append(", obj, namespace)\n" + + " if node is not None:\n el.append(node)\n"); + } else { + b.append(" if obj is not None:\n node = obj.to_tree(").append(q) + .append(")\n if node is not None:\n el.append(node)\n"); + } + } + b.append(" return el\n"); + } + + private static String indent(String s) { + return s.replaceAll("(?m)^(?=.)", " "); + } + + @SuppressWarnings("checkstyle:ParameterNumber") + private static void fromTree(StringBuilder b, List attrs, List namespaced, Set lowered, + List aliases, List init, Map descs) { + b.append("@classmethod\ndef from_tree(cls, node):\n attrib = dict(node.attrib)\n"); + for (String[] p : namespaced) { + String ns = DeclarativeMap.quote(p[1]); + b.append(" if ").append(ns).append(" in attrib:\n attrib[").append(DeclarativeMap.quote(p[0])) + .append("] = attrib[").append(ns).append("]\n del attrib[").append(ns).append("]\n"); + } + b.append(" for key in list(attrib):\n if key.startswith('{'):\n del attrib[key]\n" + + " elif key in _dm_KEYWORDS:\n attrib[\"_\" + key] = attrib[key]\n" + + " del attrib[key]\n elif \"-\" in key:\n n = key.replace(\"-\", \"_\")\n" + + " attrib[n] = attrib[key]\n del attrib[key]\n"); + if (attrs.contains("attr_text")) { + b.append(" if node.text:\n attrib[\"attr_text\"] = node.text\n"); + } + b.append(" for el in node:\n tag = _dm_localname(el)\n if tag in _dm_KEYWORDS:\n" + + " tag = \"_\" + tag\n"); + // A lowered field was a descriptor with no from_tree whose type has + // none either: the generic method stored the child's text. + List plain = new ArrayList(lowered); + java.util.Collections.sort(plain); + for (String f : plain) { + b.append(" ").append("if tag == ").append(DeclarativeMap.quote(f)) + .append(":\n attrib[tag] = el.text\n continue\n"); + } + for (String a : aliases) { + // An Alias has no expected_type: the generic method failed here. + b.append(" if tag == ").append(DeclarativeMap.quote(a)) + .append(":\n raise AttributeError(\"'Alias' object has no attribute 'expected_type'\")\n"); + } + // The descriptor a child tag names, read by name: an Alias (whose + // class read fails, which the generic getattr answered with None) + // and any other tag are skipped, as the generic method skipped them. + String kw = "if"; + for (Map.Entry e : descs.entrySet()) { + if (e.getValue() || lowered.contains(e.getKey()) || aliases.contains(e.getKey())) { + continue; + } + b.append(" ").append(kw).append(" tag == ").append(DeclarativeMap.quote(e.getKey())) + .append(":\n _dm_child(").append(read("cls", e.getKey())).append(", tag, el, attrib)\n"); + kw = "elif"; + } + if (init == null) { + b.append(" return cls(**attrib)\n"); + return; + } + // The call by keywords, one per parameter, wherever it binds what + // cls(**attrib) would; any other dictionary (an unknown name, a + // missing required one) still takes that call, and its TypeError. + List names = new ArrayList(); + for (String[] p : init) { + names.add(p[0]); + if (p[1] == null) { + b.append(" if ").append(DeclarativeMap.quote(p[0])).append(" not in attrib:\n return cls(**attrib)\n"); + } + } + b.append(" for k in attrib:\n if k not in ").append(tuple(names)).append(":\n") + .append(" return cls(**attrib)\n return cls("); + for (String[] p : init) { + String q = DeclarativeMap.quote(p[0]); + // A lowered field's entry is attribute or child text: str or None. + String v = lowered.contains(p[0]) ? "_dm_text(attrib[" + q + "])" : "attrib[" + q + "]"; + b.append(p[0]).append('=').append(p[1] == null ? v : "(" + v + " if " + q + " in attrib else " + p[1] + ")") + .append(", "); + } + b.append(")\n"); + } +} diff --git a/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/SetNameDescriptor.java b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/SetNameDescriptor.java new file mode 100644 index 00000000000..ddae69f4f1e --- /dev/null +++ b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/SetNameDescriptor.java @@ -0,0 +1,444 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.python.transpiler.codegen; + +import com.codename1.python.transpiler.ast.Node; +import com.codename1.python.transpiler.ast.Node.Attribute; +import com.codename1.python.transpiler.ast.Node.Call; +import com.codename1.python.transpiler.ast.Node.ClassDef; +import com.codename1.python.transpiler.ast.Node.Constant; +import com.codename1.python.transpiler.ast.Node.Expr; +import com.codename1.python.transpiler.ast.Node.FunctionDef; +import com.codename1.python.transpiler.ast.Node.Name; +import com.codename1.python.transpiler.ast.Node.Stmt; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/// Folds the attribute name a descriptor learns from `__set_name__`. +/// +/// ```python +/// class Field: +/// def __set_name__(self, owner, name): +/// self.name = "_" + name +/// def __get__(self, obj, objtype=None): +/// return getattr(obj, self.name, "unset") +/// +/// class Rec: +/// title = Field() +/// ``` +/// +/// The name `__set_name__` receives is the class-body target the descriptor +/// is bound to, a literal in the source. When the descriptor class is +/// constructed exactly once in the closed program, as the whole value of a +/// one-name assignment in a class body, its `__set_name__` field is that +/// literal (evaluated at build time from the target name) for its one +/// instance, and `getattr(obj, self.name, ...)` in its methods is written +/// with the literal. `class S(*bases)` over a module-level tuple of names +/// bound once is folded to `class S(A, B)`. +/// +/// It refuses (leaves the code to the strict check) anything it cannot +/// prove: a class name defined twice, used other than by the one call (a +/// base, an argument, a second binding), a field stored anywhere but the +/// one assignment in `__set_name__`, or a value it cannot evaluate. Two +/// bindings would need a clone of the class per binding, with identity, +/// `isinstance` and `type(...).__name__` rewritten with it; that is not +/// done here. +public final class SetNameDescriptor { + + private SetNameDescriptor() { + } + + /// Folds every qualifying descriptor and starred base list in `trees`. + public static void rewrite(Map trees) { + final Map> classes = new HashMap>(); + final Map nameUses = new HashMap(); + final Map attrStores = new HashMap(); + final Map> bindings = new HashMap>(); + for (Node.Module m : trees.values()) { + scan(m, null, classes, nameUses, attrStores, bindings); + foldStarBases(m); + } + for (Map.Entry> e : classes.entrySet()) { + if (e.getValue().size() != 1) { + continue; + } + ClassDef d = e.getValue().get(0); + FunctionDef setName = method(d, "__set_name__"); + if (setName == null || setName.args.positional.size() != 3 || !setName.decorators.isEmpty()) { + continue; + } + List b = bindings.get(d.name); + Integer uses = nameUses.get(d.name); + if (b == null || b.size() != 1 || uses == null || uses.intValue() != 1 + || nameUses.containsKey("__set_name__")) { + continue; + } + String self = setName.args.positional.get(0).name; + String param = setName.args.positional.get(2).name; + String target = (String) b.get(0)[0]; + Map fields = new HashMap(); + for (Stmt s : setName.body) { + if (!(s instanceof Node.Assign)) { + continue; + } + Node.Assign a = (Node.Assign) s; + if (a.targets.size() != 1 || !(a.targets.get(0) instanceof Attribute)) { + continue; + } + Attribute t = (Attribute) a.targets.get(0); + if (!(t.value instanceof Name) || !self.equals(((Name) t.value).id)) { + continue; + } + String v = eval(a.value, param, target); + Integer st = attrStores.get(t.attr); + if (v == null || fields.containsKey(t.attr) || st == null || st.intValue() != 1) { + fields.put(t.attr, null); + continue; + } + fields.put(t.attr, v); + } + if (fields.isEmpty() || rebinds(setName, param)) { + continue; + } + for (Stmt s : d.body) { + if (s instanceof FunctionDef && s != setName) { //NOPMD CompareObjectsWithEquals - identity is meant + fold(s, fields); + } + } + } + } + + private static void scan(Object o, ClassDef owner, final Map> classes, + final Map nameUses, final Map attrStores, + final Map> bindings) { + if (o instanceof ClassDef) { + final ClassDef c = (ClassDef) o; + List l = classes.get(c.name); + if (l == null) { + l = new ArrayList(); + classes.put(c.name, l); + } + l.add(c); + for (Stmt s : c.body) { + if (s instanceof Node.Assign) { + Node.Assign a = (Node.Assign) s; + if (a.targets.size() == 1 && a.targets.get(0) instanceof Name && a.value instanceof Call) { + Call k = (Call) a.value; + if (k.func instanceof Name) { + List bl = bindings.get(((Name) k.func).id); + if (bl == null) { + bl = new ArrayList(); + bindings.put(((Name) k.func).id, bl); + } + bl.add(new Object[] {((Name) a.targets.get(0)).id, k}); + } + } + } + } + Infer.children(o, x -> scan(x, c, classes, nameUses, attrStores, bindings)); + return; + } + if (o instanceof Name) { + count(nameUses, ((Name) o).id); + } else if (o instanceof Attribute) { + // `mod.Field()` makes an instance too; an explicit + // `d.__set_name__(...)` sets the field again. + count(nameUses, ((Attribute) o).attr); + } else if (o instanceof Node.Assign) { + for (Expr t : ((Node.Assign) o).targets) { + stores(t, attrStores); + } + } else if (o instanceof Node.AugAssign) { + stores(((Node.AugAssign) o).target, attrStores); + } else if (o instanceof Node.AnnAssign) { + stores(((Node.AnnAssign) o).target, attrStores); + } else if (o instanceof Node.Delete) { + for (Expr t : ((Node.Delete) o).targets) { + stores(t, attrStores); + } + } else if (o instanceof Node.For) { + stores(((Node.For) o).target, attrStores); + } else if (o instanceof Call) { + Call c = (Call) o; + if (c.func instanceof Name && ("setattr".equals(((Name) c.func).id) || "delattr".equals(((Name) c.func).id)) + && c.args.size() >= 2 && c.args.get(1) instanceof Constant) { + count(attrStores, ((Constant) c.args.get(1)).text); + } + } + final ClassDef w = owner; + Infer.children(o, x -> scan(x, w, classes, nameUses, attrStores, bindings)); + } + + private static void stores(Expr t, Map attrStores) { + if (t instanceof Attribute) { + count(attrStores, ((Attribute) t).attr); + } else if (t instanceof Node.TupleExpr) { + for (Expr x : ((Node.TupleExpr) t).elts) { + stores(x, attrStores); + } + } else if (t instanceof Node.ListExpr) { + for (Expr x : ((Node.ListExpr) t).elts) { + stores(x, attrStores); + } + } else if (t instanceof Node.Starred) { + stores(((Node.Starred) t).value, attrStores); + } + } + + private static void count(Map m, String k) { + Integer n = m.get(k); + m.put(k, n == null ? 1 : n + 1); + } + + private static FunctionDef method(ClassDef d, String name) { + FunctionDef f = null; + for (Stmt s : d.body) { + if (s instanceof FunctionDef && name.equals(((FunctionDef) s).name)) { + if (f != null) { + return null; + } + f = (FunctionDef) s; + } + } + return f; + } + + /// The build-time value of `e` with `param` bound to `value`, or null. + private static String eval(Expr e, String param, String value) { + if (e instanceof Constant && ((Constant) e).kind == Constant.Kind.STR) { + return ((Constant) e).text; + } + if (e instanceof Name && param.equals(((Name) e).id)) { + return value; + } + if (e instanceof Node.BinOp && "+".equals(((Node.BinOp) e).op)) { + String l = eval(((Node.BinOp) e).left, param, value); + String r = eval(((Node.BinOp) e).right, param, value); + return l == null || r == null ? null : l + r; + } + return null; + } + + private static boolean rebinds(FunctionDef f, final String p) { + final boolean[] r = new boolean[1]; + walk(f.body, o -> { + if (o instanceof Node.Assign) { + for (Expr t : ((Node.Assign) o).targets) { + if (t instanceof Name && p.equals(((Name) t).id)) { + r[0] = true; + } + } + } else if (o instanceof Node.AugAssign && ((Node.AugAssign) o).target instanceof Name + && p.equals(((Name) ((Node.AugAssign) o).target).id)) { + r[0] = true; + } + }); + return r[0]; + } + + private interface V { + void see(Object o); + } + + private static void walk(Object o, final V v) { + if (o instanceof List) { + for (Object x : (List) o) { + walk(x, v); + } + return; + } + v.see(o); + Infer.children(o, x -> walk(x, v)); + } + + /// Writes the literal for `self.` where it names an attribute. + private static void fold(Object fn, final Map fields) { + final String self = ((FunctionDef) fn).args.positional.isEmpty() ? null + : ((FunctionDef) fn).args.positional.get(0).name; + if (self == null) { + return; + } + walk(fn, o -> { + if (!(o instanceof Call) || !(((Call) o).func instanceof Name)) { + return; + } + Call c = (Call) o; + String n = ((Name) c.func).id; + if (!("getattr".equals(n) || "setattr".equals(n) || "hasattr".equals(n) || "delattr".equals(n)) + || c.args.size() < 2 || !(c.args.get(1) instanceof Attribute)) { + return; + } + Attribute a = (Attribute) c.args.get(1); + if (a.value instanceof Name && self.equals(((Name) a.value).id) && fields.get(a.attr) != null) { + c.args.set(1, new Constant(Constant.Kind.STR, fields.get(a.attr))); + } + }); + } + + /// `class S(*bases)` at the top level of a module, after `bases = (A, + /// B)` there, where `bases` appears nowhere else in the module and each + /// of `A`, `B` is bound once: the tuple's names are written in. + /// Anything else is left to the strict check. + private static void foldStarBases(Node.Module m) { + final Map uses = new HashMap(); + final Map binds = new HashMap(); + final boolean[] dynamic = {false}; + // Module scope only: a parameter or local of the same name in a + // function or class body is another variable, and only a `global` + // (refused below) rebinds the module's from there. + walkModuleScope(m, o -> { + if (o instanceof Name) { + count(uses, ((Name) o).id); + } else if (o instanceof Node.Arg) { + count(uses, ((Node.Arg) o).name); + count(binds, ((Node.Arg) o).name); + } else if (o instanceof Node.Alias) { + Node.Alias al = (Node.Alias) o; + String n = al.asname != null ? al.asname : al.name; + count(uses, n); + count(binds, n); + } else if (o instanceof FunctionDef) { + count(uses, ((FunctionDef) o).name); + count(binds, ((FunctionDef) o).name); + } else if (o instanceof ClassDef) { + count(binds, ((ClassDef) o).name); + } else if (o instanceof Node.Global || o instanceof Node.Delete) { + dynamic[0] = true; + } + if (o instanceof Node.Assign) { + for (Expr t : ((Node.Assign) o).targets) { + bindName(t, binds); + } + } else if (o instanceof Node.AugAssign) { + bindName(((Node.AugAssign) o).target, binds); + } else if (o instanceof Node.For) { + bindName(((Node.For) o).target, binds); + } + }); + if (dynamic[0]) { + return; + } + Map tuples = new HashMap(); + for (Stmt s : m.body) { + if (s instanceof Node.Assign && ((Node.Assign) s).targets.size() == 1 + && ((Node.Assign) s).targets.get(0) instanceof Name + && ((Node.Assign) s).value instanceof Node.TupleExpr) { + Node.TupleExpr t = (Node.TupleExpr) ((Node.Assign) s).value; + boolean names = true; + for (Expr x : t.elts) { + names &= x instanceof Name && once(binds, ((Name) x).id); + } + if (names) { + tuples.put(((Name) ((Node.Assign) s).targets.get(0)).id, t); + } + continue; + } + if (!(s instanceof ClassDef)) { + continue; + } + List bases = ((ClassDef) s).bases; + List folded = new ArrayList(); + boolean changed = false; + for (Expr e : bases) { + Node.TupleExpr t = null; + if (e instanceof Node.Starred && ((Node.Starred) e).value instanceof Name) { + String n = ((Name) ((Node.Starred) e).value).id; + // The tuple's own binding and this one use. + if (once(binds, n) && Integer.valueOf(2).equals(uses.get(n))) { + t = tuples.get(n); + } + } + if (t == null) { + folded.add(e); + } else { + changed = true; + for (Expr x : t.elts) { + folded.add(new Name(((Name) x).id)); + } + } + } + if (changed) { + bases.clear(); + bases.addAll(folded); + } + } + } + + private static void walkModuleScope(Object o, final V v) { + if (o instanceof List) { + for (Object x : (List) o) { + walkModuleScope(x, v); + } + return; + } + v.see(o); + if (o instanceof FunctionDef || o instanceof ClassDef || o instanceof Node.Lambda + || o instanceof Node.Comp) { + // The name a def or class binds is seen; its body is another + // scope. A `global` inside it is still found. + walk(o, x -> { + if (x instanceof Node.Global) { + v.see(x); + } + }); + if (o instanceof ClassDef) { + for (Expr b : ((ClassDef) o).bases) { + walkModuleScope(b, v); + } + } + return; + } + Infer.children(o, x -> walkModuleScope(x, v)); + } + + private static boolean once(Map binds, String n) { + return Integer.valueOf(1).equals(binds.get(n)); + } + + private static void bindName(Expr t, Map binds) { + if (t instanceof Name) { + count(binds, ((Name) t).id); + } else if (t instanceof Node.TupleExpr) { + for (Expr x : ((Node.TupleExpr) t).elts) { + bindName(x, binds); + } + } else if (t instanceof Node.ListExpr) { + for (Expr x : ((Node.ListExpr) t).elts) { + bindName(x, binds); + } + } else if (t instanceof Node.Starred) { + bindName(((Node.Starred) t).value, binds); + } + } + + /// Records what every class's subclasses bind over it, for the layout + /// plan: a field a subclass of another module turns into a property is + /// then no field of the base (Layouts). + public static void subclassBindings(java.util.Collection modules) { + Layouts.subclassBindings(modules); + } +} diff --git a/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/ShadowTypes.java b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/ShadowTypes.java index 69d310a8c62..0460dff8e45 100644 --- a/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/ShadowTypes.java +++ b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/ShadowTypes.java @@ -38,17 +38,17 @@ /// (see `Emitter.shadows`). Nested functions, classes, lambdas and /// comprehensions are their own scopes and are not walked. final class ShadowTypes { - private final Layouts layouts; + private final Map> owners; private final Map> counts = new HashMap>(); - private ShadowTypes(Layouts layouts) { - this.layouts = layouts; + private ShadowTypes(Map> owners) { + this.owners = owners; } /// Local name -> class, for the names read for a compiled field at /// least twice. - static Map of(List body, Layouts layouts) { - ShadowTypes t = new ShadowTypes(layouts); + static Map of(List body, Map> owners) { + ShadowTypes t = new ShadowTypes(owners); for (Stmt s : body) { t.walk(s); } @@ -82,15 +82,15 @@ private void walk(Object o) { } if (o instanceof Attribute && ((Attribute) o).value instanceof Name) { Attribute a = (Attribute) o; - List owners = layouts.fieldOwners.get(a.attr); - if (owners != null) { + List os = owners.get(a.attr); + if (os != null) { String n = ((Name) a.value).id; Map m = counts.get(n); if (m == null) { m = new LinkedHashMap(); counts.put(n, m); } - for (Layouts.Cls c : owners) { + for (Layouts.Cls c : os) { // A subclass reached through this access counts for the // declaring class too: its instances pass that test. Integer k = m.get(c); diff --git a/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/SqlAlchemyLowering.java b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/SqlAlchemyLowering.java new file mode 100644 index 00000000000..cb5caa37e96 --- /dev/null +++ b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/SqlAlchemyLowering.java @@ -0,0 +1,749 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.python.transpiler.codegen; + +import com.codename1.python.transpiler.api.PythonSyntaxError; +import com.codename1.python.transpiler.ast.Node; +import com.codename1.python.transpiler.ast.Node.Alias; +import com.codename1.python.transpiler.ast.Node.AnnAssign; +import com.codename1.python.transpiler.ast.Node.Assign; +import com.codename1.python.transpiler.ast.Node.Attribute; +import com.codename1.python.transpiler.ast.Node.BinOp; +import com.codename1.python.transpiler.ast.Node.Call; +import com.codename1.python.transpiler.ast.Node.ClassDef; +import com.codename1.python.transpiler.ast.Node.Constant; +import com.codename1.python.transpiler.ast.Node.Expr; +import com.codename1.python.transpiler.ast.Node.FunctionDef; +import com.codename1.python.transpiler.ast.Node.ImportFrom; +import com.codename1.python.transpiler.ast.Node.Keyword; +import com.codename1.python.transpiler.ast.Node.Name; +import com.codename1.python.transpiler.ast.Node.Stmt; +import com.codename1.python.transpiler.ast.Node.Subscript; +import com.codename1.python.transpiler.ast.Node.TupleExpr; +import com.codename1.python.transpiler.parser.Parser; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/// The per-class code a SQLAlchemy declarative model gets, written into the +/// class at compile time as plain Python naming every attribute literally. +/// +/// The bundled `sqlalchemy.orm` used to map a class with a metaclass that +/// read `__annotations__`, installed descriptors with `setattr` and kept the +/// instance state in `obj.__dict__[key]`: reflection, and no layout for any +/// model. Here every module-level `class M(Base)` whose base derives from +/// `DeclarativeBase` (or is `Base = declarative_base()`) is rewritten, as if +/// its author had written: +/// +/// ```python +/// class User(Base): +/// __tablename__ = "users" +/// id = __cn1_sa__._sa_col(0, "id", "int", False, mapped_column(primary_key=True)) +/// addresses = __cn1_sa__._sa_rel(1, "addresses", lambda: Address, True, relationship(...)) +/// __cn1_sa_cols__ = (id,) +/// __cn1_sa_rels__ = (addresses,) +/// __cn1_sa_parent__ = None # the mapped base, for inheritance +/// __cn1_sa_table__ = "users" # None: single-table inheritance +/// __cn1_sa_args__ = None # __mapper_args__ +/// __cn1_sa_nslots__ = 2 +/// def __cn1_sa_kw__(self, kw): ... # keyword hook for a user __init__'s super() call +/// def __init__(self, *, id=__cn1_sa__._UNSET, addresses=__cn1_sa__._UNSET): +/// self._sa_new() +/// if id is not __cn1_sa__._UNSET: +/// self._sa_v[0] = id # a column: its slot, literally +/// if addresses is not __cn1_sa__._UNSET: +/// User.__cn1_sa_rels__[0].__set__(self, addresses) +/// User.__cn1_sa_map__() +/// __cn1_sa__._sa_pair(User.addresses, Address.user) # back_populates +/// ``` +/// +/// Each column and relationship owns a slot number of the instance's state +/// list (`obj._sa_v`), fixed here: inherited attributes keep the base's slots +/// and a joined-inheritance primary key shares the inherited one. The +/// annotation is read here too (`Mapped[Optional[int]]` is type "int", +/// optional), a relationship's target is a lambda naming the class, and +/// `back_populates` and a string `order_by` are resolved against the classes +/// of the module. +/// +/// What cannot be lowered exactly fails the build naming the construct: a +/// model not at module level, more than one base, class keywords, a +/// `__table__`, a non-literal `__tablename__`, a relationship whose target or +/// `back_populates` is not a mapped class or attribute of the module. +public final class SqlAlchemyLowering { + + private SqlAlchemyLowering() { + } + + private static final String RT = "__cn1_sa__"; + + private static final class Rel { + final String owner; + final String key; + final String target; + final String back; + final Stmt at; + + Rel(String owner, String key, String target, String back, Stmt at) { + this.owner = owner; + this.key = key; + this.target = target; + this.back = back; + this.at = at; + } + } + + private static final class Model { + final String name; + final Model parent; + /// Every attribute key (inherited first) to its slot number. + final Map slots = new LinkedHashMap(); + /// Every attribute key to the descriptor expression the keyword hook sets. + final Map setters = new LinkedHashMap(); + final Set rels = new HashSet(); + int mapStmt; + + Model(String name, Model parent) { + this.name = name; + this.parent = parent; + if (parent != null) { + slots.putAll(parent.slots); + setters.putAll(parent.setters); + rels.addAll(parent.rels); + } + } + } + + private static final class Ann { + String type; + boolean optional; + Boolean list; + } + + /// Lowers the declarative models of `tree`, the module at path `path`. + public static void rewrite(Node.Module tree, String path) { + if (path.endsWith("sqlalchemy/orm/__init__.py")) { + return; + } + Set declFn = new HashSet(); + Set baseFn = new HashSet(); + Set colFn = new HashSet(); + Set relFn = new HashSet(); + Set mappedFn = new HashSet(); + for (Stmt s : tree.body) { + if (!(s instanceof ImportFrom) || ((ImportFrom) s).level != 0) { + continue; + } + String mod = ((ImportFrom) s).module; + boolean orm = "sqlalchemy.orm".equals(mod) || "sqlalchemy.ext.declarative".equals(mod); + if (!orm && !"sqlalchemy".equals(mod)) { + continue; + } + for (Alias a : ((ImportFrom) s).names) { + String bound = a.asname != null ? a.asname : a.name; + if ("Column".equals(a.name)) { + colFn.add(bound); + } else if (!orm) { + continue; + } else if ("DeclarativeBase".equals(a.name) || "DeclarativeBaseNoMeta".equals(a.name)) { + baseFn.add(bound); + } else if ("declarative_base".equals(a.name)) { + declFn.add(bound); + } else if ("mapped_column".equals(a.name)) { + colFn.add(bound); + } else if ("relationship".equals(a.name)) { + relFn.add(bound); + } else if ("Mapped".equals(a.name) || "WriteOnlyMapped".equals(a.name) + || "DynamicMapped".equals(a.name)) { + mappedFn.add(bound); + } + } + } + for (Stmt s : tree.body) { + if (s instanceof ClassDef) { + for (Expr b : ((ClassDef) s).bases) { + if (b instanceof Attribute && ("DeclarativeBase".equals(((Attribute) b).attr) + || "DeclarativeBaseNoMeta".equals(((Attribute) b).attr))) { + throw error(path, s, "SQLAlchemy base class " + ((ClassDef) s).name + " names " + + Layouts.text(b) + "; write `from sqlalchemy.orm import DeclarativeBase` and" + + " derive from that name so the build can map its models"); + } + } + } + } + if (baseFn.isEmpty() && declFn.isEmpty()) { + return; + } + Set bases = new HashSet(); + Map models = new LinkedHashMap(); + List rels = new ArrayList(); + boolean any = false; + // Bases and models whose instances run an __init__ the user wrote + // (their own or an ancestor's here): they keep DeclarativeBase's + // keyword constructor, which that __init__ reaches with super(). + Set userInit = new HashSet(); + for (int i = 0; i < tree.body.size(); i++) { + Stmt s = tree.body.get(i); + if (s instanceof Assign && ((Assign) s).value instanceof Call + && isFn(((Call) ((Assign) s).value).func, declFn)) { + Assign a = (Assign) s; + if (a.targets.size() != 1 || !(a.targets.get(0) instanceof Name)) { + throw error(path, s, "declarative_base() must be assigned to one name"); + } + tree.body.set(i, declarativeBase(path, a, ((Name) a.targets.get(0)).id)); + bases.add(((Name) a.targets.get(0)).id); + any = true; + continue; + } + if (!(s instanceof ClassDef)) { + continue; + } + ClassDef c = (ClassDef) s; + if (c.bases.isEmpty()) { + continue; + } + Expr b0 = c.bases.get(0); + String b0n = b0 instanceof Name ? ((Name) b0).id : null; + boolean direct = isFn(b0, baseFn); + boolean onBase = b0n != null && bases.contains(b0n); + Model parent = b0n != null ? models.get(b0n) : null; + if (b0n != null && userInit.contains(b0n) || definesInit(c)) { + userInit.add(c.name); + } + if (!direct && !onBase && parent == null) { + for (Expr b : c.bases) { + if (isFn(b, baseFn) || b instanceof Name + && (bases.contains(((Name) b).id) || models.containsKey(((Name) b).id))) { + throw error(path, c, "SQLAlchemy model class " + c.name + + " must name its declarative base first"); + } + } + continue; + } + any = true; + if (c.bases.size() > 1) { + throw error(path, c, "SQLAlchemy model class " + c.name + " has more than one base;" + + " its mapping cannot be generated (mixins and MappedAsDataclass are not supported)"); + } + if (!c.keywords.isEmpty()) { + throw error(path, c, "SQLAlchemy model class " + c.name + " takes class keywords;" + + " its mapping cannot be generated"); + } + if (direct) { + bases.add(c.name); + if (!binds(c, "metadata")) { + addBody(c, path, "metadata = " + RT + ".MetaData()\n", c.line); + } + continue; + } + String table = null; + for (Stmt x : c.body) { + String n = boundName(x); + if ("__table__".equals(n)) { + throw error(path, x, "SQLAlchemy model class " + c.name + + " assigns __table__; only __tablename__ mappings are supported"); + } + if ("__tablename__".equals(n)) { + Expr v = x instanceof Assign ? ((Assign) x).value : ((AnnAssign) x).value; + if (!(v instanceof Constant) || ((Constant) v).kind != Constant.Kind.STR) { + throw error(path, x, "SQLAlchemy model class " + c.name + + " has a __tablename__ that is not a string literal"); + } + table = ((Constant) v).text; + } + } + if (parent == null && table == null) { + // An intermediate base with no table: abstract, maps nothing. + for (Stmt x : c.body) { + if (attrValue(x, colFn, relFn, mappedFn) != null) { + throw error(path, x, "SQLAlchemy model class " + c.name + + " declares mapped attributes but has no __tablename__"); + } + } + bases.add(c.name); + continue; + } + Model m = new Model(c.name, parent); + lowerClass(c, path, m, table, colFn, relFn, mappedFn, rels, !userInit.contains(c.name)); + models.put(c.name, m); + List after = Parser.parse(c.name + ".__cn1_sa_map__()\n", path).body; + DataclassInit.atLine(after, c.line); + tree.body.addAll(i + 1, after); + i += after.size(); + m.mapStmt = i; + } + if (!any) { + return; + } + refuseNested(tree.body, path, baseFn, bases, models, false); + // back_populates, resolved here: each pair is linked once, after the + // later of its two classes is mapped. + Map> pairs = new java.util.TreeMap>( + java.util.Collections.reverseOrder()); + Set done = new HashSet(); + for (Rel r : rels) { + Model t = models.get(r.target); + if (t == null) { + throw error(path, r.at, "relationship " + r.owner + "." + r.key + " targets " + r.target + + ", which is not a mapped class of this module"); + } + if (r.back == null) { + continue; + } + if (!t.rels.contains(r.back)) { + throw error(path, r.at, "relationship " + r.owner + "." + r.key + " has back_populates=\"" + + r.back + "\", but " + r.target + " has no relationship " + r.back); + } + String k1 = r.owner + "." + r.key; + String k2 = r.target + "." + r.back; + if (done.contains(k1 + "|" + k2) || done.contains(k2 + "|" + k1)) { + continue; + } + done.add(k1 + "|" + k2); + int at = Math.max(models.get(r.owner).mapStmt, t.mapStmt); + List l = pairs.get(at); + if (l == null) { + l = new ArrayList(); + pairs.put(at, l); + } + l.add(RT + "._sa_pair(" + k1 + ", " + k2 + ")\n"); + } + for (Map.Entry> e : pairs.entrySet()) { + StringBuilder b = new StringBuilder(); + for (String x : e.getValue()) { + b.append(x); + } + List st = Parser.parse(b.toString(), path).body; + DataclassInit.atLine(st, tree.body.get(e.getKey()).line); + tree.body.addAll(e.getKey() + 1, st); + } + int at = 0; + while (at < tree.body.size() && (tree.body.get(at) instanceof ImportFrom + && "__future__".equals(((ImportFrom) tree.body.get(at)).module) + || at == 0 && tree.body.get(0) instanceof Node.ExprStmt + && ((Node.ExprStmt) tree.body.get(0)).value instanceof Constant)) { + at++; + } + List imp = Parser.parse("import sqlalchemy.orm as " + RT + "\n", path).body; + DataclassInit.atLine(imp, tree.body.isEmpty() ? 1 : tree.body.get(Math.min(at, tree.body.size() - 1)).line); + tree.body.addAll(at, imp); + } + + private static Stmt declarativeBase(String path, Assign a, String name) { + Call call = (Call) a.value; + Expr md = null; + if (call.args.size() == 1 && call.keywords.isEmpty()) { + md = call.args.get(0); + } else if (call.args.isEmpty() && call.keywords.size() == 1 && "metadata".equals(call.keywords.get(0).arg)) { + md = call.keywords.get(0).value; + } else if (!call.args.isEmpty() || !call.keywords.isEmpty()) { + throw error(path, a, "declarative_base() takes only metadata= here; its other options are not supported"); + } + ClassDef c = (ClassDef) Parser.parse("class " + name + "(" + RT + ".DeclarativeBase):\n metadata = " + + RT + ".MetaData()\n", path).body.get(0); + if (md != null) { + c.body.set(0, new Assign(new ArrayList(java.util.Collections.singletonList(new Name("metadata"))), + md)); + } + DataclassInit.atLine(c, a.line); + return c; + } + + /// The column or relationship value a class-body statement declares, or + /// null when it declares neither. A bare `x: Mapped[int]` answers its + /// annotation. + private static Expr attrValue(Stmt s, Set colFn, Set relFn, Set mappedFn) { + Expr v; + Expr ann = null; + if (s instanceof AnnAssign && ((AnnAssign) s).target instanceof Name) { + v = ((AnnAssign) s).value; + ann = ((AnnAssign) s).annotation; + } else if (s instanceof Assign && ((Assign) s).targets.size() == 1 && ((Assign) s).targets.get(0) instanceof Name) { + v = ((Assign) s).value; + } else { + return null; + } + if (v instanceof Call && (isFn(((Call) v).func, colFn) || isFn(((Call) v).func, relFn))) { + return v; + } + if (ann != null && mappedInner(ann, mappedFn) != null) { + return v != null ? v : ann; + } + return null; + } + + private static void lowerClass(ClassDef c, String path, Model m, String table, Set colFn, + Set relFn, Set mappedFn, List rels, boolean genInit) { + List cols = new ArrayList(); + List ownRels = new ArrayList(); + boolean args = false; + for (int i = 0; i < c.body.size(); i++) { + Stmt s = c.body.get(i); + if (s instanceof FunctionDef && "__init__".equals(((FunctionDef) s).name) && !superInitFirst((FunctionDef) s)) { + // The base __init__ allocates the instance's state slots; + // a constructor that skips it would store into nothing. + throw error(path, s, "SQLAlchemy model " + c.name + " defines __init__ without calling" + + " super().__init__(...) first; its mapped state would never be allocated"); + } + if ("__mapper_args__".equals(boundName(s))) { + args = true; + } + Expr v = attrValue(s, colFn, relFn, mappedFn); + if (v == null) { + continue; + } + String key = boundName(s); + if (key.startsWith("__") && !key.endsWith("__")) { + throw error(path, s, "SQLAlchemy model " + c.name + " attribute " + key + + " is name-mangled; its mapping cannot name it"); + } + Expr annExpr = s instanceof AnnAssign ? ((AnnAssign) s).annotation : null; + Ann ann = annExpr != null ? analyze(c, path, s, mappedInner(annExpr, mappedFn)) : null; + if (annExpr != null && ann == null && !(v instanceof Call)) { + throw error(path, s, "SQLAlchemy model " + c.name + " attribute " + key + + " has an annotation the build cannot read"); + } + Integer slot = m.slots.get(key); + if (slot == null) { + slot = m.slots.size(); + m.slots.put(key, slot); + } + StringBuilder src = new StringBuilder(key).append(" = ").append(RT); + Call user = v instanceof Call ? (Call) v : null; + if (user != null && isFn(user.func, relFn)) { + String target = relTarget(c, path, s, user, ann); + String back = null; + for (int k = 0; k < user.keywords.size(); k++) { + Keyword kw = user.keywords.get(k); + if ("back_populates".equals(kw.arg)) { + if (!(kw.value instanceof Constant) || ((Constant) kw.value).kind != Constant.Kind.STR) { + throw error(path, s, "relationship " + c.name + "." + key + + " has a back_populates that is not a string literal"); + } + back = ((Constant) kw.value).text; + } else if ("order_by".equals(kw.arg) && kw.value instanceof Constant + && ((Constant) kw.value).kind == Constant.Kind.STR) { + user.keywords.set(k, new Keyword("order_by", thunk(path, s, ((Constant) kw.value).text))); + } else if ("primaryjoin".equals(kw.arg) || "secondaryjoin".equals(kw.arg) + || "backref".equals(kw.arg)) { + throw error(path, s, "relationship " + c.name + "." + key + " uses " + kw.arg + + ", which is not supported; declare both sides with back_populates"); + } + } + rels.add(new Rel(c.name, key, target, back, s)); + m.rels.add(key); + src.append("._sa_rel(").append(slot).append(", \"").append(key).append("\", lambda: ").append(target) + .append(", ").append(ann == null || ann.list == null ? "None" : ann.list ? "True" : "False") + .append(", None)\n"); + m.setters.put(key, c.name + ".__cn1_sa_rels__[" + ownRels.size() + "]"); + ownRels.add(key); + } else { + src.append("._sa_col(").append(slot).append(", \"").append(key).append("\", ") + .append(ann == null || ann.type == null ? "None" : DeclarativeMap.quote(ann.type)) + .append(", ").append(ann != null && ann.optional ? "True" : "False").append(", None)\n"); + m.setters.put(key, c.name + ".__cn1_sa_cols__[" + cols.size() + "]"); + cols.add(key); + } + Assign repl = (Assign) Parser.parse(src.toString(), path).body.get(0); + if (user != null) { + Call made = (Call) repl.value; + made.args.set(made.args.size() - 1, user); + } + DataclassInit.atLine(repl.targets, s.line); + DataclassInit.atLine(repl.value, s.line); + repl.line = s.line; + c.body.set(i, repl); + } + StringBuilder b = new StringBuilder("__cn1_sa_cols__ = ("); + for (String k : cols) { + b.append(k).append(", "); + } + b.append(")\n__cn1_sa_rels__ = ("); + for (String k : ownRels) { + b.append(k).append(", "); + } + b.append(")\n__cn1_sa_parent__ = ").append(m.parent != null ? m.parent.name : "None"); + b.append("\n__cn1_sa_table__ = ").append(table != null ? DeclarativeMap.quote(table) : "None"); + b.append("\n__cn1_sa_args__ = ").append(args ? "__mapper_args__" : "None"); + b.append("\n__cn1_sa_nslots__ = ").append(m.slots.size()); + b.append("\n"); + b.append("def __cn1_sa_kw__(self, kw):\n pass\n"); + for (Map.Entry e : m.setters.entrySet()) { + b.append(" if ").append(DeclarativeMap.quote(e.getKey())).append(" in kw:\n ") + .append(e.getValue()).append(".__set__(self, kw.pop(").append(DeclarativeMap.quote(e.getKey())) + .append("))\n"); + } + if (genInit && !m.setters.containsKey("self")) { + // The constructor itself, keyword-only: each key a parameter, a + // column stored into its slot literally, no keyword dict and no + // lookup by string. An unknown keyword or a positional argument is + // a TypeError from the call, as SQLAlchemy's constructor raises. + String unset = RT + "._UNSET"; + b.append("def __init__(self"); + if (!m.setters.isEmpty()) { + b.append(", *"); + for (String k : m.setters.keySet()) { + b.append(", ").append(k).append("=").append(unset); + } + } + b.append("):\n self._sa_new()\n"); + for (Map.Entry e : m.setters.entrySet()) { + String k = e.getKey(); + b.append(" if ").append(k).append(" is not ").append(unset).append(":\n "); + if (m.rels.contains(k)) { + b.append(e.getValue()).append(".__set__(self, ").append(k).append(")\n"); + } else { + b.append("self._sa_v[").append(m.slots.get(k)).append("] = ").append(k).append("\n"); + } + } + } + addBody(c, path, b.toString(), c.body.isEmpty() ? c.line : c.body.get(c.body.size() - 1).line); + } + + /// The class a relationship targets: its first argument (a class name or + /// a string naming one), else its annotation's. + private static String relTarget(ClassDef c, String path, Stmt s, Call user, Ann ann) { + String target = null; + if (!user.args.isEmpty()) { + Expr a = user.args.get(0); + if (a instanceof Name) { + target = ((Name) a).id; + } else if (a instanceof Constant && ((Constant) a).kind == Constant.Kind.STR + && ((Constant) a).text.matches("[A-Za-z_][A-Za-z_0-9]*")) { + target = ((Constant) a).text; + } else { + throw error(path, s, "relationship " + c.name + "." + boundName(s) + + " names its target with an expression the build cannot read; write the class name"); + } + user.args.remove(0); + if (!user.args.isEmpty()) { + throw error(path, s, "relationship " + c.name + "." + boundName(s) + + " takes more than one positional argument"); + } + } else if (ann != null && ann.type != null) { + target = ann.type; + } + if (target == null || !target.matches("[A-Za-z_][A-Za-z_0-9]*")) { + throw error(path, s, "relationship " + c.name + "." + boundName(s) + + " has no target class the build can read; annotate it Mapped[\"Class\"]"); + } + return target; + } + + private static Expr thunk(String path, Stmt s, String text) { + Assign a = (Assign) Parser.parse("_ = " + RT + "._Thunk(lambda: " + text + ")\n", path).body.get(0); + DataclassInit.atLine(a.value, s.line); + return a.value; + } + + /// The `X` of `Mapped[X]` (or WriteOnlyMapped/DynamicMapped), a string + /// annotation parsed; null when `ann` is not one. + private static Expr mappedInner(Expr ann, Set mappedFn) { + if (ann instanceof Constant && ((Constant) ann).kind == Constant.Kind.STR) { + ann = parseExpr(((Constant) ann).text); + if (ann == null) { + return null; + } + } + if (ann instanceof Subscript) { + Expr v = ((Subscript) ann).value; + if (isFn(v, mappedFn) || v instanceof Attribute + && ("Mapped".equals(((Attribute) v).attr) || "WriteOnlyMapped".equals(((Attribute) v).attr) + || "DynamicMapped".equals(((Attribute) v).attr))) { + return ((Subscript) ann).index; + } + } + return null; + } + + private static Expr parseExpr(String text) { + try { + Stmt s = Parser.parse("_ = " + text.trim() + "\n", "").body.get(0); + return s instanceof Assign ? ((Assign) s).value : null; + } catch (PythonSyntaxError e) { + return null; + } + } + + private static Ann analyze(ClassDef c, String path, Stmt at, Expr e) { + if (e == null) { + return null; + } + if (e instanceof Constant && ((Constant) e).kind == Constant.Kind.STR) { + Expr p = parseExpr(((Constant) e).text); + if (p == null) { + throw error(path, at, "SQLAlchemy model " + c.name + " has an annotation the build cannot read: " + + ((Constant) e).text); + } + return analyze(c, path, at, p); + } + if (e instanceof BinOp && "|".equals(((BinOp) e).op)) { + BinOp b = (BinOp) e; + Expr rest = isNone(b.right) ? b.left : isNone(b.left) ? b.right : null; + if (rest == null) { + throw error(path, at, "SQLAlchemy model " + c.name + " has a union annotation the build cannot map"); + } + Ann a = analyze(c, path, at, rest); + a.optional = true; + return a; + } + if (e instanceof Subscript) { + Subscript s = (Subscript) e; + String head = Layouts.text(s.value); + String last = head.substring(head.lastIndexOf('.') + 1); + if ("Optional".equals(last)) { + Ann a = analyze(c, path, at, s.index); + a.optional = true; + return a; + } + if ("Union".equals(last) && s.index instanceof TupleExpr) { + List elts = ((TupleExpr) s.index).elts; + Expr rest = null; + boolean none = false; + for (Expr x : elts) { + if (isNone(x)) { + none = true; + } else if (rest == null) { + rest = x; + } else { + throw error(path, at, "SQLAlchemy model " + c.name + + " has a union annotation the build cannot map"); + } + } + Ann a = analyze(c, path, at, rest); + a.optional = none; + return a; + } + if ("List".equals(last) || "list".equals(last) || "Set".equals(last) || "set".equals(last)) { + Ann a = analyze(c, path, at, s.index); + a.list = Boolean.TRUE; + return a; + } + throw error(path, at, "SQLAlchemy model " + c.name + " has an annotation the build cannot map: " + + Layouts.text(e)); + } + if (e instanceof Name || e instanceof Attribute) { + Ann a = new Ann(); + a.type = Layouts.text(e); + a.list = Boolean.FALSE; + return a; + } + throw error(path, at, "SQLAlchemy model " + c.name + " has an annotation the build cannot map"); + } + + private static boolean superInitFirst(FunctionDef f) { + if (f.body.isEmpty() || !(f.body.get(0) instanceof Node.ExprStmt)) { + return false; + } + Expr e = ((Node.ExprStmt) f.body.get(0)).value; + if (!(e instanceof Call) || !(((Call) e).func instanceof Attribute)) { + return false; + } + Attribute a = (Attribute) ((Call) e).func; + return "__init__".equals(a.attr) && a.value instanceof Call && ((Call) a.value).func instanceof Name + && "super".equals(((Name) ((Call) a.value).func).id); + } + + private static boolean isNone(Expr e) { + return e instanceof Constant && ((Constant) e).kind == Constant.Kind.NONE; + } + + private static boolean isFn(Expr f, Set names) { + return f instanceof Name && names.contains(((Name) f).id); + } + + private static String boundName(Stmt s) { + if (s instanceof AnnAssign && ((AnnAssign) s).target instanceof Name) { + return ((Name) ((AnnAssign) s).target).id; + } + if (s instanceof Assign && ((Assign) s).targets.size() == 1 && ((Assign) s).targets.get(0) instanceof Name) { + return ((Name) ((Assign) s).targets.get(0)).id; + } + return null; + } + + private static boolean definesInit(ClassDef c) { + for (Stmt s : c.body) { + if (s instanceof FunctionDef && "__init__".equals(((FunctionDef) s).name)) { + return true; + } + } + return binds(c, "__init__"); + } + + private static boolean binds(ClassDef c, String name) { + for (Stmt s : c.body) { + if (name.equals(boundName(s))) { + return true; + } + } + return false; + } + + private static void addBody(ClassDef c, String path, String src, int line) { + for (Stmt s : Parser.parse(src, path).body) { + DataclassInit.atLine(s, line); + c.body.add(s); + } + } + + /// A model class or declarative_base() call not at module level is + /// refused: its mapping would be generated with nothing to check it against. + private static void refuseNested(Object o, String path, Set baseFn, Set bases, + Map models, boolean nested) { + if (o instanceof ClassDef) { + ClassDef c = (ClassDef) o; + if (nested && !c.bases.isEmpty()) { + Expr b = c.bases.get(0); + if (isFn(b, baseFn) || b instanceof Name + && (bases.contains(((Name) b).id) || models.containsKey(((Name) b).id))) { + throw error(path, c, "SQLAlchemy model class " + c.name + + " is not defined at module level; its mapping cannot be generated"); + } + } + for (Stmt s : c.body) { + refuseNested(s, path, baseFn, bases, models, true); + } + return; + } + if (o instanceof FunctionDef) { + for (Stmt s : ((FunctionDef) o).body) { + refuseNested(s, path, baseFn, bases, models, true); + } + return; + } + if (o instanceof List) { + for (Object x : (List) o) { + refuseNested(x, path, baseFn, bases, models, nested); + } + } + } + + private static PythonSyntaxError error(String path, Node at, String why) { + return new PythonSyntaxError(path, at.line, 1, why); + } +} diff --git a/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/StyleableLowering.java b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/StyleableLowering.java new file mode 100644 index 00000000000..90eef4b223e --- /dev/null +++ b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/StyleableLowering.java @@ -0,0 +1,200 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.python.transpiler.codegen; + +import com.codename1.python.transpiler.ast.Node; +import com.codename1.python.transpiler.ast.Node.Assign; +import com.codename1.python.transpiler.ast.Node.Call; +import com.codename1.python.transpiler.ast.Node.ClassDef; +import com.codename1.python.transpiler.ast.Node.Constant; +import com.codename1.python.transpiler.ast.Node.Expr; +import com.codename1.python.transpiler.ast.Node.Name; +import com.codename1.python.transpiler.ast.Node.Stmt; +import com.codename1.python.transpiler.parser.Parser; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/// Evaluates openpyxl's style descriptors at build time. +/// +/// `openpyxl/styles/styleable.py` declares the style fields of every cell +/// as class attributes of `StyleableObject` holding descriptor objects: +/// +/// ```python +/// class StyleableObject: +/// font = StyleDescriptor('_fonts', "fontId") +/// quotePrefix = StyleArrayDescriptor('quotePrefix') +/// ``` +/// +/// whose `__get__` and `__set__` reach the workbook collection and the +/// style array slot through `getattr`/`setattr` with the names stored in +/// the descriptor: reflection the strict build refuses, on the hottest +/// path of a spreadsheet read. Every argument is a literal, so this pass +/// writes each field as a property whose getter and setter are the +/// descriptor's methods with those names spelled out +/// (`self.parent.parent._fonts`, `self._style.fontId`), and empties the +/// four descriptor classes, which nothing else uses. The upstream source is +/// not edited. If the module does not have exactly the shape expected, it +/// is left as it is. +public final class StyleableLowering { + + private static final String PATH = "openpyxl/styles/styleable.py"; + private static final String[] DESCRIPTORS = {"StyleDescriptor", "NumberFormatDescriptor", + "NamedStyleDescriptor", "StyleArrayDescriptor"}; + private static final String INIT = " if not self._style:\n self._style = StyleArray()\n"; + + private StyleableLowering() { + } + + /// Lowers the style descriptors of `StyleableObject` among `trees`. + public static void rewrite(Map trees) { + for (Map.Entry e : trees.entrySet()) { + if (e.getKey().endsWith(PATH)) { + lower(e.getValue(), e.getKey()); + } + } + } + + private static void lower(Node.Module m, String file) { + Map classes = new HashMap(); + for (Stmt s : m.body) { + if (s instanceof ClassDef) { + classes.put(((ClassDef) s).name, (ClassDef) s); + } + } + ClassDef owner = classes.get("StyleableObject"); + if (owner == null) { + return; + } + for (String d : DESCRIPTORS) { + if (!classes.containsKey(d)) { + return; + } + } + List body = new ArrayList(); + for (Stmt s : owner.body) { + String src = s instanceof Assign ? property((Assign) s) : null; + if (src == null && s instanceof Assign && ((Assign) s).value instanceof Call + && ((Call) ((Assign) s).value).func instanceof Name + && isDescriptor(((Name) ((Call) ((Assign) s).value).func).id)) { + // A descriptor this pass cannot spell out: leave it all. + return; + } + if (src == null) { + body.add(s); + continue; + } + Node.Module parsed = Parser.parse("class _st:\n" + src.replaceAll("(?m)^(?=.)", " "), file); + DataclassInit.atLine(parsed, s.line); + body.addAll(((ClassDef) parsed.body.get(0)).body); + } + owner.body.clear(); + owner.body.addAll(body); + for (String d : DESCRIPTORS) { + ClassDef c = classes.get(d); + Node.Module p = Parser.parse("pass\n", file); + DataclassInit.atLine(p, c.line); + c.body.clear(); + c.body.addAll(p.body); + } + } + + private static boolean isDescriptor(String n) { + for (String d : DESCRIPTORS) { + if (d.equals(n)) { + return true; + } + } + return false; + } + + /// The property source replacing `s`, or null when it is not a + /// descriptor field with literal arguments. + private static String property(Assign s) { + if (s.targets.size() != 1 || !(s.targets.get(0) instanceof Name) || !(s.value instanceof Call)) { + return null; + } + Call c = (Call) s.value; + if (!(c.func instanceof Name) || !c.keywords.isEmpty()) { + return null; + } + List args = new ArrayList(); + for (Expr a : c.args) { + if (!(a instanceof Constant) || ((Constant) a).kind != Constant.Kind.STR || !ident(((Constant) a).text)) { + return null; + } + args.add(((Constant) a).text); + } + String n = ((Name) s.targets.get(0)).id; + String kind = ((Name) c.func).id; + String head = "@property\ndef " + n + "(self):\n"; + String set = "@" + n + ".setter\ndef " + n + "(self, value):\n"; + if ("StyleDescriptor".equals(kind) && args.size() == 2) { + String coll = " coll = self.parent.parent." + args.get(0) + "\n"; + return head + coll + INIT + " idx = self._style." + args.get(1) + "\n return StyleProxy(coll[idx])\n" + + set + coll + INIT + " self._style." + args.get(1) + " = coll.add(value)\n"; + } + if ("StyleArrayDescriptor".equals(kind) && args.size() == 1) { + return head + " if self._style is None:\n return False\n return bool(self._style." + + args.get(0) + ")\n" + set + " if self._style is None:\n self._style = StyleArray()\n" + + " self._style." + args.get(0) + " = value\n"; + } + if ("NumberFormatDescriptor".equals(kind) && args.isEmpty()) { + return head + INIT + " idx = self._style.numFmtId\n if idx < BUILTIN_FORMATS_MAX_SIZE:\n" + + " return BUILTIN_FORMATS.get(idx, \"General\")\n" + + " coll = self.parent.parent._number_formats\n return coll[idx - BUILTIN_FORMATS_MAX_SIZE]\n" + + set + " coll = self.parent.parent._number_formats\n if value in BUILTIN_FORMATS_REVERSE:\n" + + " idx = BUILTIN_FORMATS_REVERSE[value]\n else:\n" + + " idx = coll.add(value) + BUILTIN_FORMATS_MAX_SIZE\n" + INIT + + " self._style.numFmtId = idx\n"; + } + if ("NamedStyleDescriptor".equals(kind) && args.isEmpty()) { + return head + INIT + " idx = self._style.xfId\n coll = self.parent.parent._named_styles\n" + + " return coll.names[idx]\n" + + set + INIT + " coll = self.parent.parent._named_styles\n if isinstance(value, NamedStyle):\n" + + " style = value\n if style not in coll:\n" + + " self.parent.parent.add_named_style(style)\n elif value not in coll.names:\n" + + " if value in styles:\n style = styles[value]\n if style not in coll:\n" + + " self.parent.parent.add_named_style(style)\n else:\n" + + " raise ValueError(\"{0} is not a known style\".format(value))\n else:\n" + + " style = coll[value]\n self._style = copy(style.as_tuple())\n"; + } + return null; + } + + private static boolean ident(String s) { + if (s.isEmpty() || !(Character.isLetter(s.charAt(0)) || s.charAt(0) == '_')) { + return false; + } + for (int i = 0; i < s.length(); i++) { + char ch = s.charAt(i); + if (ch >= 0x80 || !(Character.isLetterOrDigit(ch) || ch == '_')) { + return false; + } + } + return true; + } +} diff --git a/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/ThreadLocalLowering.java b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/ThreadLocalLowering.java new file mode 100644 index 00000000000..f9d5236d707 --- /dev/null +++ b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/ThreadLocalLowering.java @@ -0,0 +1,302 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.python.transpiler.codegen; + +import com.codename1.python.transpiler.ast.Node; +import com.codename1.python.transpiler.ast.Node.Alias; +import com.codename1.python.transpiler.ast.Node.Assign; +import com.codename1.python.transpiler.ast.Node.Attribute; +import com.codename1.python.transpiler.ast.Node.Call; +import com.codename1.python.transpiler.ast.Node.Constant; +import com.codename1.python.transpiler.ast.Node.Delete; +import com.codename1.python.transpiler.ast.Node.Expr; +import com.codename1.python.transpiler.ast.Node.Global; +import com.codename1.python.transpiler.ast.Node.Import; +import com.codename1.python.transpiler.ast.Node.ImportFrom; +import com.codename1.python.transpiler.ast.Node.Name; +import com.codename1.python.transpiler.ast.Node.Stmt; +import com.codename1.python.transpiler.parser.Parser; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeSet; + +/// `threading.local` stores every attribute by name in a per-thread dict, +/// through `__getattr__`/`__setattr__`, which a closed world cannot compile. +/// Here a module-level `x = threading.local()` (or `local()` imported from +/// `threading`), bound once, whose every use in the program is `x.` +/// (read, store or `del`) or `hasattr`/`getattr`/`setattr`/`delattr` of `x` +/// with a literal name, becomes an instance of a generated holder class: +/// one property per name the program uses, each reading or writing that +/// field of a generated slot object kept per thread ident. Names are +/// literal, so nothing is looked up by name at run time. +/// +/// Anything else -- `x` passed, returned or rebound, `global x`, any other +/// module importing a name `x` (or `*`) or reading an attribute named `x`, +/// a subclass of `local` -- leaves the statement as it is, and the bundled +/// `threading.local` is refused in strict mode as before. +public final class ThreadLocalLowering { + private ThreadLocalLowering() { + } + + /// Lowers the thread-local objects of every module of `trees`. + public static void rewrite(Map trees) { + for (Map.Entry e : trees.entrySet()) { + String p = e.getKey(); + if (p.matches("(.*/)?threading\\.py")) { + continue; + } + rewrite(e.getValue(), p, trees); + } + } + + private static void rewrite(Node.Module tree, String path, Map trees) { + Set mods = new HashSet(); + Set locals = new HashSet(); + for (Stmt s : tree.body) { + if (s instanceof Import) { + for (Alias a : ((Import) s).names) { + if ("threading".equals(a.name)) { + mods.add(a.asname != null ? a.asname : a.name); + } + } + } else if (s instanceof ImportFrom && ((ImportFrom) s).level == 0 + && "threading".equals(((ImportFrom) s).module)) { + for (Alias a : ((ImportFrom) s).names) { + if ("local".equals(a.name)) { + locals.add(a.asname != null ? a.asname : a.name); + } + } + } + } + if (mods.isEmpty() && locals.isEmpty()) { + return; + } + Map bindings = new HashMap(); + for (Stmt s : tree.body) { + DataclassInit.count(s, bindings); + } + for (String m : mods) { + if (bindings.getOrDefault(m, 0) != 1) { + return; + } + } + for (String l : locals) { + if (bindings.getOrDefault(l, 0) != 1) { + return; + } + } + for (int i = 0; i < tree.body.size(); i++) { + Stmt s = tree.body.get(i); + if (!(s instanceof Assign) || ((Assign) s).targets.size() != 1 + || !(((Assign) s).targets.get(0) instanceof Name) || !isLocalCall(((Assign) s).value, mods, locals)) { + continue; + } + String x = ((Name) ((Assign) s).targets.get(0)).id; + if (bindings.getOrDefault(x, 0) != 1 || escapes(x, tree, trees)) { + continue; + } + Set names = new TreeSet(); + boolean[] bad = {false}; + boolean[] deletes = {false}; + collect(tree.body, null, x, s, names, bad, deletes); + if (bad[0]) { + continue; + } + String holder = "_cn1_tl_" + x; + String slots = "_cn1_tls_" + x; + StringBuilder src = new StringBuilder(); + src.append("from threading import get_ident as _cn1_tl_ident\n\n\n"); + src.append("class ").append(slots).append(":\n def __init__(self):\n"); + if (names.isEmpty()) { + src.append(" pass\n"); + } + for (String n : names) { + src.append(" self.").append(n).append(" = None\n"); + src.append(" self.").append(n).append("_cn1_set = False\n"); + } + src.append("\n\nclass ").append(holder).append(":\n def __init__(self):\n") + .append(" self._cn1_d = {}\n\n") + .append(" def _cn1_ns(self):\n me = _cn1_tl_ident()\n") + .append(" ns = self._cn1_d.get(me)\n if ns is None:\n") + .append(" ns = ").append(slots).append("()\n self._cn1_d[me] = ns\n") + .append(" return ns\n"); + for (String n : names) { + src.append("\n @property\n def ").append(n).append("(self):\n") + .append(" ns = self._cn1_ns()\n if not ns.").append(n).append("_cn1_set:\n") + .append(" raise AttributeError(\"'_thread._local' object has no attribute '") + .append(n).append("'\")\n return ns.").append(n).append("\n"); + src.append("\n @").append(n).append(".setter\n def ").append(n).append("(self, v):\n") + .append(" ns = self._cn1_ns()\n ns.").append(n).append(" = v\n") + .append(" ns.").append(n).append("_cn1_set = True\n"); + if (deletes[0]) { + src.append("\n @").append(n).append(".deleter\n def ").append(n).append("(self):\n") + .append(" ns = self._cn1_ns()\n if not ns.").append(n) + .append("_cn1_set:\n raise AttributeError(\"").append(n).append("\")\n") + .append(" ns.").append(n).append(" = None\n") + .append(" ns.").append(n).append("_cn1_set = False\n"); + } + } + List gen = Parser.parse(src.toString(), path).body; + for (Stmt g : gen) { + DataclassInit.atLine(g, s.line); + } + Call c = new Call(new Name(holder)); + c.line = s.line; + c.func.line = s.line; + Assign a = new Assign(((Assign) s).targets, c); + a.line = s.line; + tree.body.set(i, a); + tree.body.addAll(i, gen); + i += gen.size(); + } + } + + private static boolean isLocalCall(Expr e, Set mods, Set locals) { + if (!(e instanceof Call) || !((Call) e).args.isEmpty() || !((Call) e).keywords.isEmpty()) { + return false; + } + Expr f = ((Call) e).func; + if (f instanceof Name) { + return locals.contains(((Name) f).id); + } + return f instanceof Attribute && "local".equals(((Attribute) f).attr) && ((Attribute) f).value instanceof Name + && mods.contains(((Name) ((Attribute) f).value).id); + } + + /// Whether another module could reach `x`: it imports a name `x` or + /// `*`, or reads an attribute named `x` of anything. + private static boolean escapes(String x, Node.Module self, Map trees) { + boolean[] hit = {false}; + for (Node.Module t : trees.values()) { + if (t != self) { //NOPMD CompareObjectsWithEquals - identity is meant + reaches(t, x, hit); + if (hit[0]) { + return true; + } + } + } + return false; + } + + private static void reaches(Object o, String x, boolean[] hit) { + if (hit[0]) { + return; + } + if (o instanceof ImportFrom) { + for (Alias a : ((ImportFrom) o).names) { + if (x.equals(a.name) || "*".equals(a.name)) { + hit[0] = true; + } + } + } else if (o instanceof Attribute && x.equals(((Attribute) o).attr)) { + hit[0] = true; + } + Infer.children(o, c -> reaches(c, x, hit)); + } + + private static final Set REFLECT = new HashSet(java.util.Arrays.asList("hasattr", "getattr", + "setattr", "delattr")); + + /// Collects the literal names used on `x`, setting `bad` for any other + /// use of it. + private static void collect(Object o, Object parent, String x, Stmt def, Set names, boolean[] bad, + boolean[] deletes) { + if (bad[0]) { + return; + } + if (o instanceof Global && ((Global) o).names.contains(x)) { + bad[0] = true; + return; + } + if (o instanceof Delete) { + for (Expr t : ((Delete) o).targets) { + if (t instanceof Attribute && ((Attribute) t).value instanceof Name + && x.equals(((Name) ((Attribute) t).value).id)) { + deletes[0] = true; + } + } + } + if (o instanceof Attribute && ((Attribute) o).value instanceof Name + && x.equals(((Name) ((Attribute) o).value).id)) { + String a = ((Attribute) o).attr; + if (a.startsWith("__")) { + bad[0] = true; + } + names.add(a); + return; + } + if (o instanceof Call && ((Call) o).func instanceof Name && REFLECT.contains(((Name) ((Call) o).func).id)) { + Call c = (Call) o; + if (!c.args.isEmpty() && c.args.get(0) instanceof Name && x.equals(((Name) c.args.get(0)).id)) { + if (c.args.size() < 2 || !(c.args.get(1) instanceof Constant) + || ((Constant) c.args.get(1)).kind != Constant.Kind.STR || !c.keywords.isEmpty() + || !((Constant) c.args.get(1)).text.matches("[A-Za-z_][A-Za-z0-9_]*") + || ((Constant) c.args.get(1)).text.startsWith("__")) { + bad[0] = true; + return; + } + if ("delattr".equals(((Name) c.func).id)) { + deletes[0] = true; + } + names.add(((Constant) c.args.get(1)).text); + for (int i = 1; i < c.args.size(); i++) { + collect(c.args.get(i), c, x, def, names, bad, deletes); + } + return; + } + } + if (o instanceof Name && x.equals(((Name) o).id)) { + if (parent != def) { //NOPMD CompareObjectsWithEquals - identity is meant + bad[0] = true; + } + return; + } + if (o instanceof Node.FunctionDef) { + // A parameter named `x` shadows it; uses of the parameter would + // then be miscounted, so the whole object is left alone. + if (paramNamed((Node.FunctionDef) o, x)) { + bad[0] = true; + return; + } + } + Infer.children(o, c -> collect(c, o, x, def, names, bad, deletes)); + } + + private static boolean paramNamed(Node.FunctionDef f, String x) { + boolean[] hit = {false}; + Infer.children(f.args, c -> { + if (c instanceof Node && x.equals(argName(c))) { + hit[0] = true; + } + }); + return hit[0]; + } + + private static String argName(Object o) { + return o instanceof Node.Arg ? ((Node.Arg) o).name : null; + } +} diff --git a/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/Ty.java b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/Ty.java index 2871cec390b..d7a28d93d41 100644 --- a/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/Ty.java +++ b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/Ty.java @@ -30,7 +30,7 @@ /// /// The lattice is deliberately small. Every kind maps to one Java /// representation, so a join that would need two (an int or a float, a bool -/// or None) goes to `DYN`, which is the plain `Object` the generic code uses: +/// or None) goes to `OBJECT`, which is the plain `Object` the generic code uses: /// /// | kind | Java | None | /// |---|---|---| @@ -38,16 +38,22 @@ /// | `FLOAT` | `double` | -- | /// | `INT` | `Object` (a `Long`, or a big int) | -- | /// | `STR` | `String` | null when `opt` | +/// | `BYTES` | `Object` (a `PyBytes`) | -- | /// | `INST` | the class's layout class | null when `opt` | /// | `LIST` | `PyList` | null when `opt` | -/// | `NONE`, `DYN`, `BOT` | `Object` | `Py.NONE` | +/// | `TUPLE` | `Object` (the generic tuple) | -- | +/// | `DICT` | `Object` (a `PyDict`) | -- | +/// | `CLS` | `Object` (one of the classes whose ids are `sites`, any class when there are none) | `Py.NONE` when `opt` | +/// | `OBJ` | `Object` (a runtime object of the named builtin type) | `Py.NONE` when `opt` | +/// | `METH` | `Object` (a bound method of one of the compiled methods whose ids are `sites`) | `Py.NONE` when `opt` | +/// | `NONE`, `OBJECT`, `BOT` | `Object` | `Py.NONE` | /// /// An int stays an object because a Python int has no bound: overflowing a /// `long` local would have nowhere to go without deoptimizing mid-statement. /// On ParparVM a `Long` below 2^60 is a tagged immediate, so keeping it /// boxed allocates nothing. final class Ty { - enum K { BOT, NONE, BOOL, INT, FLOAT, STR, INST, LIST, DYN } + enum K { BOT, NONE, BOOL, INT, FLOAT, STR, BYTES, INST, LIST, TUPLE, DICT, OBJ, CLS, METH, FUNC, UNION, OBJECT } static final Ty BOT = new Ty(K.BOT, null, false, null); static final Ty NONE = new Ty(K.NONE, null, false, null); @@ -55,23 +61,102 @@ enum K { BOT, NONE, BOOL, INT, FLOAT, STR, INST, LIST, DYN } static final Ty INT = new Ty(K.INT, null, false, null); static final Ty FLOAT = new Ty(K.FLOAT, null, false, null); static final Ty STR = new Ty(K.STR, null, false, null); - static final Ty DYN = new Ty(K.DYN, null, false, null); + static final Ty BYTES = new Ty(K.BYTES, null, false, null); + static final Ty OBJECT = new Ty(K.OBJECT, null, false, null); + + /// A value from a source the pass cannot see: a computed attribute, an + /// element of a container it does not follow, the result of a call of + /// something it does not know. It is no evidence of what a slot holds, + /// so a join ignores it ([#join]); a slot every source of which is + /// unseen is held as [#OBJECT] is. Typed code converts such a value to the + /// slot's type, checked, where it enters. + static final Ty UNSEEN = new Ty(K.OBJECT, null, false, null, "unseen"); + + /// [#UNSEEN] joined with None: a type the other sources say holds the + /// None as well. + static final Ty UNSEEN_NONE = new Ty(K.OBJECT, null, true, null, "unseen"); /// The list sites a `LIST` value may have come from (see `Infer`). Past - /// this many it is any list at all. - static final int MAX_SITES = 8; + /// this many it is any list at all. That is not a small loss: an "any + /// list" that escapes escapes every list of the program + /// (`Infer.escape`), and with a cap of 8 one pandas call and one in + /// charset_normalizer did -- so every list in bs4 and markdownify, a + /// tag's `contents` among them, held untyped elements. A set of sites + /// stays exact well past what a real program merges. + static final int MAX_SITES = 4096; final K k; final Layouts.Cls cls; final boolean opt; /// Sorted allocation sites of a `LIST`; empty means "any list". final int[] sites; + /// The builtin type an `OBJ` value is an instance of (`set`, + /// `ValueError`, `re.Pattern`). + final String name; + /// UNION: the types a value may be, two or more, none of them a union, + /// OBJECT or BOT, at most one of each kind except INST and OBJ (one per + /// class tree / per name), in a fixed order. A union is a known set: + /// whatever the program does with the value, it does to one of these. + final Ty[] alts; private Ty(K k, Layouts.Cls cls, boolean opt, int[] sites) { + this(k, cls, opt, sites, null); + } + + private Ty(K k, Layouts.Cls cls, boolean opt, int[] sites, String name) { + this(k, cls, opt, sites, name, null); + } + + private Ty(K k, Layouts.Cls cls, boolean opt, int[] sites, String name, Ty[] alts) { this.k = k; this.cls = cls; this.opt = opt; this.sites = sites; + this.name = name; + this.alts = alts; + } + + /// The types this one may be: its union members, or itself. + Ty[] members() { + return k == K.UNION ? alts.clone() : new Ty[] {this}; + } + + /// Whether this is a value the analysis cannot name one type for: OBJECT, + /// or a union of several. + /// Whether this is [#UNSEEN]. + boolean unseen() { + return k == K.OBJECT && "unseen".equals(name); + } + + boolean wide() { + return k == K.OBJECT || k == K.UNION; + } + + /// The class object itself, one of the compiled classes whose ids + /// (`Infer.Program#clsId`) are `ids`; held as the generic object. + static Ty cls(int[] ids) { + return new Ty(K.CLS, null, false, ids); + } + + /// A bound method of one of the compiled methods whose ids + /// (`Infer.Program#methId`) are `ids`, held as the generic object. + /// Only locals and results hold one: it reaches no parameter, field + /// or container (`Infer#noMeth`), so no guard has to test for it. + static Ty meth(int[] ids) { + return new Ty(K.METH, null, false, ids); + } + + /// One of the functions whose ids (`Infer.Program#funcId`) are `ids`, as + /// a value: a nested function, a lambda, a module function named + /// without being called. The inference follows it to where it is + /// called; generated code holds it as an object (`Infer#loc`). + static Ty func(int[] ids) { + return new Ty(K.FUNC, null, false, ids); + } + + /// An instance of the builtin type `name`, held as the generic object. + static Ty obj(String name) { + return new Ty(K.OBJ, null, false, null, name); } static Ty inst(Layouts.Cls c, boolean opt) { @@ -82,6 +167,21 @@ static Ty list(int[] sites, boolean opt) { return new Ty(K.LIST, null, opt, sites); } + /// A tuple from these allocation sites. It is held as the generic + /// object; what the kind adds is the type of each position (see + /// `Infer.slot`), so unpacking it or indexing it with a constant gives + /// typed values instead of dynamic ones. + static Ty tuple(int[] sites) { + return new Ty(K.TUPLE, null, false, sites); + } + + /// A dict from these allocation sites. It is held as the generic object; + /// what the kind adds is the type of its keys and values (see + /// `Infer.dictVal`), so a read of it gives a typed value. + static Ty dict(int[] sites) { + return new Ty(K.DICT, null, false, sites); + } + Ty orNone() { switch (k) { case BOT: @@ -91,14 +191,22 @@ Ty orNone() { case INST: case LIST: return opt ? this : new Ty(k, cls, true, sites); + case OBJ: + case CLS: + case METH: + case FUNC: + return opt ? this : new Ty(k, null, true, sites, name); + case OBJECT: + return this; default: - return DYN; + // An int, a float, a tuple ... or None: a union with None. + return unionOf(this, NONE); } } /// The same type without None, for a value already tested non-None. Ty nonNone() { - return opt ? new Ty(k, cls, false, sites) : this; + return opt ? new Ty(k, cls, false, sites, name) : this; } /// Whether the representation can hold None (as Java null). @@ -107,7 +215,7 @@ boolean nullable() { } boolean isObject() { - return k == K.BOT || k == K.NONE || k == K.DYN || k == K.INT; + return k == K.BOT || k == K.NONE || k == K.OBJECT || k == K.UNION || k == K.INT || k == K.BYTES || k == K.TUPLE || k == K.DICT || k == K.OBJ || k == K.CLS || k == K.METH || k == K.FUNC; } static Ty join(Ty a, Ty b) { @@ -120,8 +228,24 @@ static Ty join(Ty a, Ty b) { if (a.equals(b)) { return a; } - if (a.k == K.DYN || b.k == K.DYN) { - return DYN; + // An unseen value is no evidence (UNSEEN), but None is no type to + // hold the rest in: a slot only None reached has nothing to guard, + // so a value besides it stays unseen rather than claiming None. + // It remembers the None, though: the type the other sources say + // holds it as well. + if (a.unseen() || b.unseen()) { + Ty u = a.unseen() ? a : b; + Ty o = a.unseen() ? b : a; + if (o.k == K.NONE || o.unseen()) { + return u.opt || o.k == K.NONE || o.opt ? UNSEEN_NONE : UNSEEN; + } + return u.opt ? o.orNone() : o; + } + if (a.k == K.OBJECT || b.k == K.OBJECT) { + return OBJECT; + } + if (a.k == K.UNION || b.k == K.UNION) { + return unionOf(a, b); } if (a.k == K.NONE) { return b.orNone(); @@ -134,26 +258,106 @@ static Ty join(Ty a, Ty b) { return INT; } if (a.k != b.k) { - return DYN; + return unionOf(a, b); } boolean opt = a.opt || b.opt; switch (a.k) { case INST: { Layouts.Cls c = common(a.cls, b.cls); - return c == null ? DYN : inst(c, opt); + return c == null ? unionOf(a, b) : inst(c, opt); } case LIST: return list(union(a.sites, b.sites), opt); + case TUPLE: + return tuple(union(a.sites, b.sites)); + case DICT: + return dict(union(a.sites, b.sites)); + case CLS: { + // No ids: any class at all. + Ty r = cls(union(a.sites, b.sites)); + return opt ? r.orNone() : r; + } + case METH: { + Ty r = meth(union(a.sites, b.sites)); + return r.sites.length == 0 ? OBJECT : opt ? r.orNone() : r; + } + case FUNC: { + Ty r = func(union(a.sites, b.sites)); + return opt ? r.orNone() : r; + } case STR: return opt ? STR.orNone() : STR; + case OBJ: + return a.name.equals(b.name) ? (opt ? a.orNone() : a.nonNone()) : unionOf(a, b); default: return a; } } + /// The union of `a` and `b` (either may be one): each member of `b` + /// joins the member of `a` it shares a kind with -- a class tree, for + /// an instance -- or is added beside them. None is a member of its + /// own when no member can hold it as `opt`. + private static Ty unionOf(Ty a, Ty b) { + java.util.List acc = new java.util.ArrayList(Arrays.asList(a.members())); + for (Ty m : b.members()) { + add(acc, m); + } + // A member that can be None absorbs a None member. + int none = -1; + for (int i = 0; i < acc.size(); i++) { + if (acc.get(i).k == K.NONE) { + none = i; + } + } + if (none >= 0) { + for (int i = 0; i < acc.size(); i++) { + Ty m = acc.get(i); + if (i != none && (m.k == K.STR || m.k == K.INST || m.k == K.LIST || m.k == K.OBJ + || m.k == K.CLS || m.k == K.METH || m.k == K.FUNC)) { + acc.set(i, m.orNone()); + acc.remove(none); + break; + } + } + } + if (acc.size() == 1) { + return acc.get(0); + } + Ty[] r = acc.toArray(new Ty[0]); + Arrays.sort(r, (x, y) -> x.toString().compareTo(y.toString())); + return new Ty(K.UNION, null, false, null, null, r); + } + + private static void add(java.util.List acc, Ty m) { + for (int i = 0; i < acc.size(); i++) { + Ty o = acc.get(i); + boolean same = o.k == m.k || o.k == K.INT && m.k == K.BOOL || o.k == K.BOOL && m.k == K.INT; + if (same && o.k == K.INST && common(o.cls, m.cls) == null) { + same = false; + } + if (same && o.k == K.OBJ && !o.name.equals(m.name)) { + same = false; + } + if (same) { + Ty j = join(o, m); + if (j.k == K.UNION || j.k == K.OBJECT) { + continue; + } + acc.set(i, j); + return; + } + } + acc.add(m); + } + + /// The nearest class both derive from. An analysed class's compiled + /// ancestors are not shared with it: generated code takes an instance + /// of a compiled class to be one of its Java class, which an analysed + /// class's instance is not. private static Layouts.Cls common(Layouts.Cls a, Layouts.Cls b) { - for (Layouts.Cls x = a; x != null; x = x.parent) { - for (Layouts.Cls y = b; y != null; y = y.parent) { + for (Layouts.Cls x = a; x != null && x.compiled == a.compiled; x = x.parent) { + for (Layouts.Cls y = b; y != null && y.compiled == b.compiled; y = y.parent) { if (x == y) { //NOPMD CompareObjectsWithEquals - identity is meant return x; } @@ -196,7 +400,8 @@ public boolean equals(Object o) { return false; } Ty t = (Ty) o; - return k == t.k && cls == t.cls && opt == t.opt && Arrays.equals(sites, t.sites); //NOPMD CompareObjectsWithEquals - identity is meant + return k == t.k && cls == t.cls && opt == t.opt && Arrays.equals(sites, t.sites) && Arrays.equals(alts, t.alts) //NOPMD CompareObjectsWithEquals - classes are interned + && (name == null ? t.name == null : name.equals(t.name)); //NOPMD CompareObjectsWithEquals - identity is meant } @Override @@ -206,7 +411,16 @@ public int hashCode() { @Override public String toString() { - String s = k == K.INST ? cls.def.name : k == K.LIST ? "list" + Arrays.toString(sites) : k.name(); + if (k == K.UNION) { + StringBuilder u = new StringBuilder(); + for (Ty m : alts) { + u.append(u.length() == 0 ? "" : " | ").append(m); + } + return u.toString(); + } + String s = k == K.INST ? cls.def.name : k == K.LIST ? "list" + Arrays.toString(sites) + : k == K.TUPLE ? "tuple" + Arrays.toString(sites) + : k == K.DICT ? "dict" + Arrays.toString(sites) : k == K.OBJ ? "<" + name + ">" : k == K.CLS ? "class" + Arrays.toString(sites) : k == K.METH ? "method" + Arrays.toString(sites) : k == K.FUNC ? "function" + Arrays.toString(sites) : unseen() ? "unseen" : k.name(); return opt ? s + "?" : s; } } diff --git a/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/TypedEmit.java b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/TypedEmit.java index f7c14443dbd..3f6efb1e3ae 100644 --- a/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/TypedEmit.java +++ b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/TypedEmit.java @@ -23,6 +23,7 @@ */ package com.codename1.python.transpiler.codegen; +import com.codename1.python.transpiler.ast.Node; import com.codename1.python.transpiler.ast.Node.*; import com.codename1.python.transpiler.ast.Scope; @@ -36,6 +37,7 @@ import java.util.List; import java.util.Map; import java.util.Set; +import java.util.TreeMap; import java.util.TreeSet; /// The typed half of a closed program: a second, statically typed Java @@ -80,6 +82,37 @@ static final class E { /// waiting in `Typed.take`, which `c` takes. Only the consumers that /// know to take it exactly once see one (see `pushed`); or null. String pk; + /// Whether `lc` is known to fit a Java `int` (a length, an index + /// `find` answered), so adding a constant of 31 bits to it cannot + /// overflow a `long`. + boolean small; + /// A guessed value (Infer#guessed) held as a pair: `gr`, a plain + /// Java name of type `gt`, holds it while `go`, the plain name of + /// the object that replaces it, is null. `c` reads the pair as an + /// object and `t` is OBJECT, so code that does not know pairs reads it + /// right; code that does takes the typed form when `go` is null. + String gr; + String go; + Ty gt; + /// A one-char read `s[i]` of a str with its pair count at hand: the + /// str, the long index and the count, all plain or free of effects + /// (see [#compareOp]); or null. + String[] charAt; + /// A value with a typed form valid only while a test holds: `gg`, + /// a Java test free of side effects; `gview`, the typed form, which + /// holds the value while `gg` is true; `ga`, the value as an object, + /// right whatever `gg` says. `gstable` is false when `gg` reads a + /// field, which a call evaluated between the test and the read could + /// change. A pair is one (`gg` tests its object for null); so is the + /// result of an expression over such values (see [#split]). + String gg; + E gview; + String ga; + boolean gstable; + /// The value's truth as a Java boolean expression evaluating the + /// same operands once, when one is cheaper than testing `c` (a + /// comparison answers its truth without boxing a bool); or null. + String tst; E(String c, Ty t) { this(c, t, null); @@ -91,7 +124,10 @@ static final class E { E(String c, Ty t, String lc, String ll, String bg) { this.c = c; - this.t = t; + // A value the pass had no evidence for (Ty#UNSEEN) is, once + // written, an object of any type: joined with a typed one it is + // untyped, never converted to the other's type. + this.t = t != null && t.unseen() ? Ty.OBJECT : t; this.lc = lc; this.ll = ll; this.bg = bg; @@ -146,10 +182,96 @@ static E dual(String l, String b) { private Set nonNull = new HashSet(); /// Int locals whose value a Java long holds right now, and that long. private Map shadow = new HashMap(); + /// The exceptions of the handlers being lowered, innermost last: what a + /// bare `raise` raises again. + private final List handlers = new ArrayList(); + /// For each loop being lowered, innermost first, the label a break + /// leaves by: the block around a loop with an `else`, or "" for a plain + /// break. + private final java.util.ArrayDeque loopLabels = new java.util.ArrayDeque(); /// The int ranges of the function being emitted, and the locals they /// put in a Java `long` (see `IntRanges`). private IntRanges ranges; private Set longLocals = new HashSet(); + /// Untyped locals that accumulate with `+=` / `-=`: held as a long and + /// an object (null while the long is the value), so adding an int to + /// one that holds an int allocates nothing. The object takes anything + /// else, and every read boxes the pair back into one value. + private Set accLocals = new HashSet(); + /// Str locals bound by nothing but `name = value` statements: each has + /// an `int` beside it (`sp` + its Java name) holding its surrogate pair + /// count once a subscript asked, reset by every store, so `s[i]` in a + /// loop does not count them again on every read (Typed#sat). + private Set flatStr = new HashSet(); + + /// The names every binding of which, in `body` outside nested functions + /// and classes, is an assignment statement with that one name as its + /// only target. None when the body has a `match`, which binds by + /// pattern. + static Set simplyAssigned(List body) { + Set simple = new HashSet(); + Set other = new HashSet(); + boolean[] match = new boolean[1]; + for (Stmt s : body) { + bindingsIn(s, simple, other, match); + } + if (match[0]) { + return new HashSet(); + } + simple.removeAll(other); + return simple; + } + + private static void bindingsIn(Object o, Set simple, Set other, boolean[] match) { + if (o instanceof FunctionDef || o instanceof ClassDef) { + // Its name is bound here; its body is a scope of its own. + other.add(o instanceof FunctionDef ? ((FunctionDef) o).name : ((ClassDef) o).name); + return; + } + if (o instanceof Lambda) { + return; + } + if (o instanceof Match) { + match[0] = true; + } + List out = new ArrayList(); + if (o instanceof Assign) { + List ts = ((Assign) o).targets; + if (ts.size() == 1 && ts.get(0) instanceof Name) { + simple.add(((Name) ts.get(0)).id); + } else { + for (Expr t : ts) { + names(t, out); + } + } + } else if (o instanceof AugAssign) { + names(((AugAssign) o).target, out); + } else if (o instanceof AnnAssign) { + names(((AnnAssign) o).target, out); + } else if (o instanceof For) { + names(((For) o).target, out); + } else if (o instanceof Comprehension) { + names(((Comprehension) o).target, out); + } else if (o instanceof NamedExpr) { + out.add(((NamedExpr) o).target.id); + } else if (o instanceof WithItem && ((WithItem) o).vars != null) { + names(((WithItem) o).vars, out); + } else if (o instanceof ExceptHandler && ((ExceptHandler) o).name != null) { + out.add(((ExceptHandler) o).name); + } else if (o instanceof Delete) { + for (Expr t : ((Delete) o).targets) { + names(t, out); + } + } else if (o instanceof Import || o instanceof ImportFrom) { + for (Alias a : o instanceof Import ? ((Import) o).names : ((ImportFrom) o).names) { + String n = a.asname != null ? a.asname : a.name; + int dot = n.indexOf('.'); + out.add(dot < 0 ? n : n.substring(0, dot)); + } + } + other.addAll(out); + Infer.children(o, x -> bindingsIn(x, simple, other, match)); + } /// The module functions that also have a version taking their int /// parameters as Java longs (`TL_`), and the interval each such /// parameter is known to hold there; what that version returns, when @@ -212,7 +334,7 @@ private void findPure() { for (Map.Entry e : in.globalFns.entrySet()) { pure.add(e.getValue()); } - for (Infer.Fn f : in.fns.values()) { + for (Infer.Fn f : in.emitFns().values()) { if (f.cls != null && !f.def.name.equals("__init__")) { pure.add(f); } else if (f.cls != null) { @@ -272,7 +394,7 @@ private boolean pureMethod(String m) { return false; } boolean any = false; - for (Infer.Fn f : in.fns.values()) { + for (Infer.Fn f : in.emitFns().values()) { if (f.cls != null && f.def.name.equals(m)) { if (!pure.contains(f)) { return false; @@ -284,7 +406,7 @@ private boolean pureMethod(String m) { } private boolean pureNode(Object o) { - if (!(o instanceof com.codename1.python.transpiler.ast.Node)) { + if (!(o instanceof Node)) { // An operator or a name in a node's list of strings. return true; } @@ -364,14 +486,14 @@ private boolean pureCall(Call c, Scope scope) { if (f != null && (b == null || b == Scope.Binding.GLOBAL)) { return pure.contains(f); } - Layouts.Cls k = in.globalClasses.get(n); + Layouts.Cls k = in.emitClass(n); if (k != null && (b == null || b == Scope.Binding.GLOBAL)) { Layouts.Cls o = Layouts.resolver(k, "__init__"); if (o == null) { return true; } FunctionDef init = o.typable.get("__init__"); - return init != null && pureInits.contains(in.fns.get(init)); + return init != null && pureInits.contains(in.emitFns().get(init)); } return (b == null || b == Scope.Binding.BUILTIN) && PURE_BUILTINS.contains(n) && !em.moduleScopeHasStarImport(); @@ -388,22 +510,48 @@ private boolean callsArePure(Object o) { void plan() { findPure(); - if (!in.open.isEmpty()) { - return; - } for (Layouts.Cls k : layouts.classes.values()) { Map m = new LinkedHashMap(); for (String f : k.fields) { Ty t = in.fieldType(k, f); + if (t.k == Ty.K.DICT && in.guarded(k, f)) { + // A guarded dict (Infer#guessedDict) stays an object + // slot, which any store fits: only what is read from + // it is taken to be a dict, and checked as one. + continue; + } if (representable(t) && in.definitelySet(k, f)) { m.put(f, t); + } else if (representable(t) && in.openable(k, f, t)) { + m.put(f, t); + openFields.computeIfAbsent(k, x -> new HashSet()).add(f); } } typedFields.put(k, m); } - for (Infer.Fn f : in.fns.values()) { + // A typed field no generic code may reach directly: the generic + // code goes through getField/setField, which box. Done before any + // body is written: a typed function holding a nested def writes + // that def's generic code as part of its own. + for (Map.Entry> e : typedFields.entrySet()) { + for (String f : e.getValue().keySet()) { + List o = layouts.fieldOwners.get(f); + o.remove(e.getKey()); + if (o.isEmpty()) { + layouts.fieldOwners.remove(f); + } + } + } + } + + /// Writes the typed bodies. Every module's typed fields are decided + /// ([#plan]) before any module's bodies, which read the fields of + /// other modules' classes as those modules hold them (see + /// [#typedField]). + void planBodies() { + for (Infer.Fn f : in.emitFns().values()) { byScope.put(f.def.scope, f); - if (f.cls != null && !f.def.name.equals("__init__")) { + if (f.cls != null && !f.def.name.equals("__init__") && !in.removed(f.def)) { String key = f.def.name + "/" + (f.params.length - 1); List g = groups.get(key); if (g == null) { @@ -413,10 +561,17 @@ void plan() { g.add(f); } } - Set ok = new LinkedHashSet(in.fns.values()); + Set ok = new LinkedHashSet(in.emitFns().values()); + for (Infer.Fn f : in.emitFns().values()) { + // Nothing reaches it: there is no body to type, and no types + // its calls and stores were held to. + if (in.removed(f.def)) { + ok.remove(f); + } + } Map> deps = new HashMap>(); Map> gdeps = new HashMap>(); - for (Infer.Fn f : in.fns.values()) { + for (Infer.Fn f : ok) { typed.put(f, typedName(f)); } boolean changed = true; @@ -459,17 +614,6 @@ void plan() { } } usedGroups.retainAll(liveGroups(ok)); - // A typed field no generic code may reach directly: the generic - // code goes through getField/setField, which box. - for (Map.Entry> e : typedFields.entrySet()) { - for (String f : e.getValue().keySet()) { - List o = layouts.fieldOwners.get(f); - o.remove(e.getKey()); - if (o.isEmpty()) { - layouts.fieldOwners.remove(f); - } - } - } } private Set liveGroups(Set ok) { @@ -521,7 +665,7 @@ private void planLongParams(Set ok) { } for (Map.Entry e : all) { Infer.Fn g = in.globalFns.get(((Name) e.getKey().func).id); - IntRanges.Iv[] a = g == null || !ok.contains(g) || g.cls != null ? null + IntRanges.Iv[] a = g == null || !ok.contains(g) || g.cls != null || g.def.scope.hasYield ? null : IntRanges.longArgs(g, e.getValue()); if (a == null) { continue; @@ -644,20 +788,80 @@ private static String longName(Infer.Fn f) { return "TL_" + Emitter.mangle(f.def.name); } + /// Typed names given so far: a property's getter and setter, or a + /// function defined twice, share a Python name and not a Java one. + private final Set typedNames = new HashSet(); + private String typedName(Infer.Fn f) { - if (f.cls != null) { - return "TM_" + f.cls.javaName + "_" + Emitter.mangle(f.def.name); + String base = f.cls != null ? "TM_" + f.cls.javaName + "_" + Emitter.mangle(f.def.name) + : "TF_" + Emitter.mangle(f.def.name); + String n = base; + for (int i = 2; !typedNames.add(n); i++) { + n = base + "$" + i; + } + return n; + } + + /// Field `f` of `k` read on `recv`, an expression of `k`'s Java class, + /// as an object, or null when the field is not held typed. + String foreignGet(Layouts.Cls k, String f, String recv) { + Ty t = typedField(k, f); + if (t == null) { + return null; + } + String m = Emitter.mangle(f); + if (t.k == Ty.K.INT) { + return dual(recv + ".t_" + m, recv + ".b_" + m).c; + } + if (guardedField(k, f)) { + return pairE(recv + ".t_" + m, recv + ".b_" + m, t, present(k, f, recv + ".b_" + m, recv)).c; + } + return box(new E(recv + ".t_" + m, t)); + } + + /// Typed fields no constructor is known to set (see Infer#openable): + /// held as a guarded pair whose object half starts as Typed.UNSET. + private final Map> openFields = new HashMap>(); + + /// Whether typed field `f` of `owner` may be absent (see [#openFields]). + boolean openField(Layouts.Cls owner, String f) { + // A subclass shares the slot an ancestor declares, absent or not; + // each class is asked of the module that decided its fields. + for (Layouts.Cls x = owner; x != null; x = x.parent) { + TypedEmit home = x.typed != null ? x.typed : this; + Set s = home.openFields.get(x); + if (s != null && s.contains(f)) { + return true; + } } - return "TF_" + Emitter.mangle(f.def.name); + return false; + } + + /// The object half `o` of field `f` of `k` on `recv` as a value: an + /// absent field (Typed.UNSET) is read generically. + private String present(Layouts.Cls k, String f, String o, String recv) { + return openField(k, f) ? "Typed.present(" + o + ", " + recv + ", " + Emitter.javaString(f) + ")" : null; } Ty typedField(Layouts.Cls owner, String f) { + if (owner != null && owner.typed != null && owner.typed != this) { //NOPMD CompareObjectsWithEquals - identity is meant + // A field a compiled class of another module declares (one this + // module's class inherits) is held as that module decided. + return owner.typed.typedField(owner, f); + } Map m = typedFields.get(owner); return m == null ? null : m.get(f); } // ---- Java types ------------------------------------------------------ + /// How typed code names compiled class `k`: qualified by its module's + /// Java class, which names it from any module of the program (an + /// instance of another module's class is typed as any other). + static String clsJ(Layouts.Cls k) { + return k.ref != null ? k.ref : k.javaName; + } + static String jt(Ty t) { switch (t.k) { case BOOL: @@ -667,7 +871,7 @@ static String jt(Ty t) { case STR: return "String"; case INST: - return t.cls.javaName; + return clsJ(t.cls); case LIST: return "PyList"; default: @@ -700,9 +904,14 @@ private static String zero(Ty t) { // ---- conversions ----------------------------------------------------- String box(E e) { + if (e.gview != null) { + return e.go != null ? e.c : "(" + e.gg + " ? " + box(e.gview) + " : " + e.ga + ")"; + } switch (e.t.k) { case BOOL: - return "Py.bool(" + e.c + ")"; + // A constant needs no call: `return True` in bs4's match + // rules boxed through Py.bool on every return. + return "true".equals(e.c) ? "Py.TRUE" : "false".equals(e.c) ? "Py.FALSE" : "Py.bool(" + e.c + ")"; case FLOAT: return "Py.of(" + e.c + ")"; case STR: @@ -714,6 +923,18 @@ String box(E e) { } } + /// Guarded `e` as an object where its test is false: a pair's object + /// itself. + private static String orElse(E e) { + return e.go != null ? e.go : e.ga; + } + + /// Loop source `e`, a list, as a PyList: a guarded pair is typed as an + /// object and holds its list type beside it (see [#pairE]). + private String listOf(E e) { + return e.gview != null ? conv(e, e.gt) : e.t.k == Ty.K.LIST ? e.c : unbox(box(e), e.t); + } + /// `c`, an object the inference proved to be of type `to`, as `to`. String unbox(String c, Ty to) { switch (to.k) { @@ -727,7 +948,7 @@ String unbox(String c, Ty to) { return "Typed.asList(" + c + ")"; case INST: unboxers.add(to.cls); - return "u_" + to.cls.javaName + "(" + c + ")"; + return unboxerName(to.cls) + "(" + c + ")"; default: return c; } @@ -738,6 +959,13 @@ String conv(E e, Ty to) { if ("Object".equals(tj)) { return box(e); } + if (e.gview != null) { + try { + return "(" + e.gg + " ? " + conv(e.gview, to) + " : " + unbox(orElse(e), to) + ")"; + } catch (Unsupported u) { + return unbox(e.c, to); + } + } if (e.t.k == Ty.K.NONE) { if (to.nullable()) { return "Py.NONE".equals(e.c) ? "null" : "Typed.<" + tj + ">none(" + e.c + ")"; @@ -757,6 +985,9 @@ String conv(E e, Ty to) { } String toD(E e) { + if (e.gview != null) { + return "(" + e.gg + " ? " + toD(e.gview) + " : Typed.asFloat(" + orElse(e) + "))"; + } switch (e.t.k) { case FLOAT: return e.c; @@ -769,18 +1000,39 @@ String toD(E e) { } } + /// Whether an instance typed `k` may answer its truth itself: `k`, a + /// class above it or one below it anywhere in the program binds + /// `__bool__` or `__len__`, or has a base besides its compiled parent. + /// The whole program, not this module's classes: contextlib's + /// `while self._exit_callbacks` holds a `deque` of `collections`, whose + /// `__len__` a test of this module alone took for "never empty". private boolean customTruth(Layouts.Cls k) { - for (Layouts.Cls c : layouts.classes.values()) { - if (Infer.isSelfOrAncestor(k, c) || Infer.isSelfOrAncestor(c, k)) { - if (c.bodyNames.contains("__bool__") || c.bodyNames.contains("__len__")) { - return true; - } + return hierarchyBinds(k, "__bool__", "__len__"); + } + + /// Whether `k`, a class above it or one below it in the whole program + /// binds `a` or `b`, or has a base besides its compiled parent. + private boolean hierarchyBinds(Layouts.Cls k, String a, String b) { + for (Layouts.Cls c = k; c != null; c = c.parent) { + if (c.extraBases || c.bodyNames.contains(a) || c.bodyNames.contains(b)) { + return true; + } + } + for (Layouts.Cls c : in.subclasses(k)) { + if (c.extraBases || c.bodyNames.contains(a) || c.bodyNames.contains(b)) { + return true; } } return false; } String test(E e) { + if (e.tst != null) { + return e.tst; + } + if (e.gview != null) { + return "(" + e.gg + " ? " + test(e.gview) + " : Py.isTrue(" + orElse(e) + "))"; + } switch (e.t.k) { case BOOL: return e.c; @@ -801,8 +1053,145 @@ String test(E e) { // ---- functions ------------------------------------------------------- + /// The cells of the function being lowered that a closure shares and + /// something stores into. + private Set trueCells = new TreeSet(); + + /// Whether [#var] answers the cell of a [#trueCells] name: not while + /// the signature and the parameters copied into cells are written. + private boolean cellsLive; + + /// Int locals of the function being lowered that a read may find + /// unbound: their object half starts as Typed.UNBOUND. + private Set unboundInts = new HashSet(); + + /// Whether `n`, read from the scope being lowered, is one of [#trueCells]. + private boolean trueCell(String n) { + if (!trueCells.contains(n) || compVar(n) != null) { + return false; + } + Scope.Binding b = sc.resolve(n); + return b == Scope.Binding.CELL && sc == cur.def.scope //NOPMD CompareObjectsWithEquals - identity is meant + || b == Scope.Binding.FREE && sc.owner(n) == cur.def.scope; //NOPMD CompareObjectsWithEquals - identity is meant + } + + private String cellRef(String n) { + return em.cellName(cur.def.scope, n) + "[0]"; + } + private String var(String n) { - return "v_" + Emitter.mangle(n); + String c = compVar(n); + if (c == null && cellsLive && trueCell(n)) { + // A store a lowering writes directly (a loop target) goes to + // the cell; a Java long, double or boolean boxes to the value + // Python holds. + return cellRef(n); + } + return c != null ? c : "v_" + Emitter.mangle(n); + } + + /// Where `n` resolves from the scope being lowered. A cell only + /// comprehensions capture is a plain local: they are lowered in line, + /// reading it where they stand. Inside one, its own targets and the + /// locals of the function (or of a comprehension around it) are locals. + private Scope.Binding binding(String n) { + Scope.Binding b = sc.resolve(n); + if (b == Scope.Binding.CELL && (in.compOnlyCell(sc, n) || compVar(n) != null)) { + return Scope.Binding.LOCAL; + } + if (b == Scope.Binding.FREE && sc.kind == Scope.Kind.COMPREHENSION) { + Scope o = sc.owner(n); + // A name Emitter.uncell took off the function's cells (only + // helper comprehensions read it) is a plain local of it too. + if (o == cur.def.scope && (in.compOnlyCell(o, n) || !o.cells.contains(n)) || o != null && o.kind == Scope.Kind.COMPREHENSION //NOPMD CompareObjectsWithEquals - identity is meant + && compVars.containsKey(o)) { + return Scope.Binding.LOCAL; + } + } + return b; + } + + /// The Java local of each target of the comprehensions being lowered. + private final Map> compVars = new IdentityHashMap>(); + + /// The Java local holding comprehension target `n` as seen from the + /// scope being lowered, or null when `n` is not one. + private String compVar(String n) { + for (Scope s = sc; s != null && s.kind == Scope.Kind.COMPREHENSION; s = s.parent) { + Map m = compVars.get(s); + if (m != null && s.isLocal(n)) { + return m.get(n); + } + } + return null; + } + + /// The type comprehension target `n` is held as, seen from the scope + /// being lowered (see [#compTy]); OBJECT when it is not one. + private Ty compVarType(String n) { + for (Scope s = sc; s != null && s.kind == Scope.Kind.COMPREHENSION; s = s.parent) { + Map m = compVars.get(s); + if (m != null && s.isLocal(n)) { + return compTy(s, n); + } + } + return Ty.OBJECT; + } + + /// The Java type a temporary for target `n` of comprehension scope `s` + /// holds: what the analysis says its iterable yields (Infer#compLocal), + /// where that has a Java type of its own; an int keeps its big half + /// beside the long, which a temporary has no room for, so it is boxed. + private Ty compTy(Scope s, String n) { + Ty t = in.compLocal(s, n); + if (t == null || t.k == Ty.K.INT || t.k == Ty.K.BOT || !representable(t) || "Object".equals(jt(t))) { + return Ty.OBJECT; + } + return t; + } + + /// Binds the target of generator `g` to `raw`, the element its + /// iterable gave. Where the analysis narrowed the target by the + /// generator's `isinstance` filter (Infer#narrowedBy), an element of + /// another class is skipped before it reaches the typed variable: the + /// filter would skip it anyway, and a cast would fail on it first. + /// The object half of each comprehension target held as a guess (see + /// Infer#guessedCompVar), by the Java variable of its typed half. + private final Map compOver = new HashMap(); + + private void compStore(Comprehension g, String raw, StringBuilder p, int d) { + if (g.target instanceof Name) { + String v = compVar(((Name) g.target).id); + String o = v == null ? null : compOver.get(v); + if (o != null) { + String x = exprTemp("Object"); + indent(p, d); + p.append(x).append(" = ").append(raw).append(";\n"); + indent(p, d); + fitInto(x, compVarType(((Name) g.target).id), v, o, p, d); + // The typed half holds nothing of an element that missed: + // never the element before it. + indent(p, d); + p.append("if (").append(o).append(" != null) ").append(v).append(" = null;\n"); + return; + } + } + Layouts.Cls k = in.narrowedBy(g); + if (k != null && g.target instanceof Name + && compVarType(((Name) g.target).id).k == Ty.K.INST) { + String o = exprTemp("Object"); + indent(p, d); + p.append(o).append(" = ").append(raw).append(";\n"); + indent(p, d); + p.append("if (!(").append(o).append(" instanceof ").append(clsJ(k)).append(")) {\n"); + indent(p, d + 1); + p.append("continue;\n"); + indent(p, d); + p.append("}\n"); + store(g.target, new E("((" + clsJ(k) + ") " + o + ")", Ty.inst(k, false)), p, d); + return; + } + store(g.target, new E(raw, Ty.OBJECT), p, d); } /// The object half of int local `n` (see `dual`). @@ -828,7 +1217,21 @@ private String[] parts(E e) { return new String[] {"0L", box(e)}; } + /// The lowering's own locals (`GenLowering.hidden`) a generator body + /// used: values kept across a suspension, fields of the generator. + private final Set hiddenLocals = new TreeSet(); + private Ty localType(String n) { + if (compVar(n) != null) { + return compVarType(n); + } + if (inGen && n.startsWith("$y")) { + hiddenLocals.add(n); + return Ty.OBJECT; + } + if (trueCells.contains(n)) { + return Ty.OBJECT; + } Ty t = cur.locals.get(n); return t == null ? Ty.BOT : t; } @@ -871,6 +1274,7 @@ private static Map seeds(Infer.Fn f, IntRanges.Iv[] iv) { private String function(Infer.Fn f, boolean asLong) { cur = f; sc = f.def.scope; + fallback = null; calls = new LinkedHashSet(); callsGroups = new LinkedHashSet(); tmp = 0; @@ -889,39 +1293,136 @@ private String function(Infer.Fn f, boolean asLong) { throw new Unsupported("long parameter " + f.names.get(i) + " outgrows a long"); } } - if (!f.def.scope.cells.isEmpty() || f.def.scope.hasYield || f.def.isAsync || !f.def.decorators.isEmpty() - || f.def.args.vararg != null || f.def.args.kwarg != null || !f.def.args.kwonly.isEmpty()) { - throw new Unsupported("signature"); + boolean generator = f.def.scope.hasYield; + cellsLive = false; + trueCells = new TreeSet(f.def.scope.cells); + trueCells.removeAll(Infer.compOnlyCells(f.def)); + fallbackStores = null; + loopStored = null; + for (String n : f.def.scope.cells) { + // A cell a lazy generator captures (Emitter.uncell kept it) and + // the function rebinds: the generator must read the value at the + // time it runs, so it shares the cell too. + if (!trueCells.contains(n) && !Infer.paramCells(f.def).contains(n) && !settled(n)) { + trueCells.add(n); + } + } + for (String n : trueCells) { + // Shared with a closure: an Object in a cell, never a Java local. + f.locals.remove(n); + longLocals.remove(n); + } + if (generator && asLong || f.def.isAsync) { + throw new Unsupported("signature: " + (f.def.isAsync ? "async" : "long generator")); } for (String n : f.locals.keySet()) { - if (sc.resolve(n) != Scope.Binding.LOCAL) { + if (binding(n) != Scope.Binding.LOCAL) { throw new Unsupported("non-local " + n); } } + widenRebound(f); da = new DefAssign(); da.function(f.def.body, sc.params); + unboundInts = new HashSet(); + for (Name x : da.unsafe) { + Ty lt = f.locals.get(x.id); + if (lt == null || sc.params.contains(x.id) || generator || asLong) { + continue; + } + if (lt.k == Ty.K.INT) { + // A read that may come first: held as a pair, whose object + // half can say "unbound", even where a long would do. + unboundInts.add(x.id); + } else if (!"null".equals(zero(lt))) { + // A bool or a float has no value meaning "unbound": held as + // an object, whose null does. + f.locals.put(x.id, Ty.OBJECT); + } + } + longLocals.removeAll(unboundInts); + soleStores = soleStores(f.def.body); + fallbackStores = null; + loopStored = null; + // A parameter is bound on entry as well: its one assignment in the + // body is a second store, and folding it gave every read the value + // only one path assigns. + soleStores.keySet().removeAll(sc.params); + accLocals = accumulators(f); + flatStr = generator || asLong ? new HashSet() : simplyAssigned(f.def.body); + flatStr.removeAll(sc.params); + for (java.util.Iterator it = flatStr.iterator(); it.hasNext();) { + String n = it.next(); + Ty lt = f.locals.get(n); + if (lt == null || lt.k != Ty.K.STR || trueCell(n) || longLocals.contains(n) || accLocals.contains(n)) { + it.remove(); + } + } + for (Name x : da.unsafe) { + if (accLocals.contains(x.id) && !sc.params.contains(x.id) && !generator && !asLong) { + // An accumulator is a pair as well. + unboundInts.add(x.id); + } + } + folded = new IdentityHashMap(); recycled = ListRecycling.find(f.def.body, f.names, sc); scalars = findScalars(f); StringBuilder b = new StringBuilder(); b.append(" static ").append(retJ(f)).append(' ').append(lp != null ? longName(f) : typed.get(f)).append('('); Set declared = new HashSet(f.names); StringBuilder norm = new StringBuilder(); + // A parameter the body rebinds to other types (an int made a tuple) + // arrives under its own name and is copied into the local. + StringBuilder rebound = new StringBuilder(); + paramAlias.clear(); for (int i = 0; i < f.names.size(); i++) { String n = f.names.get(i); if (lp != null && lp[i] != null) { b.append(i == 0 ? "" : ", ").append("long ").append(var(n)); continue; } - b.append(i == 0 ? "" : ", ").append(param(f.params[i], var(n), big(n))); + Ty lt = f.locals.get(n); + String pv = var(n); + String pb = big(n); + boolean pi = f.params[i].k == Ty.K.INT; + if (lt != null && !longLocals.contains(n) + && (pi != (lt.k == Ty.K.INT) || !pi && !jt(lt).equals(jt(f.params[i])))) { + if (lt.k == Ty.K.INT || longParams.get(f) != null) { + throw new Unsupported("parameter " + n + " of " + f.def.name + " rebound: " + f.params[i] + " -> " + lt); + } + pv = "p_" + var(n); + pb = "p_" + big(n); + E arg = f.params[i].k == Ty.K.INT ? dual(pv, pb) : new E(pv, f.params[i]); + if ("Object".equals(jt(lt))) { + rebound.append(" Object ").append(var(n)).append(" = ").append(box(arg)).append(";\n"); + } else { + // The argument need not convert (`xy = list(xy)` takes a + // tuple): read as it came until the first statement, which + // must rebind it, stores the local. + Stmt first = f.def.body.isEmpty() ? null : f.def.body.get(0); + if (!(first instanceof Assign) || ((Assign) first).targets.size() != 1 + || !(((Assign) first).targets.get(0) instanceof Name) + || !n.equals(((Name) ((Assign) first).targets.get(0)).id)) { + throw new Unsupported("parameter " + n + " of " + f.def.name + " rebound: " + f.params[i] + " -> " + lt); + } + paramAlias.put(n, arg); + rebound.append(" ").append(jt(lt)).append(' ').append(var(n)).append(" = ") + .append("double".equals(jt(lt)) ? "0.0" : "boolean".equals(jt(lt)) ? "false" : "null") + .append(";\n"); + } + } + b.append(i == 0 ? "" : ", ").append(param(f.params[i], pv, pb)); if (f.params[i].k == Ty.K.INT) { // A caller holding only the object passes it whole. - norm.append(" if (").append(big(n)).append(" instanceof Long) {\n ").append(var(n)) - .append(" = ((Long) ").append(big(n)).append(").longValue();\n ").append(big(n)) + norm.append(" if (").append(pb).append(" instanceof Long) {\n ").append(pv) + .append(" = ((Long) ").append(pb).append(").longValue();\n ").append(pb) .append(" = null;\n }\n"); } } - b.append(") {\n").append(norm); - IntRanges.Iv[] dl = asLong ? null : longParams.get(f); + b.append(") {\n").append(norm).append(rebound); + if (generator && (rebound.length() > 0 || !paramAlias.isEmpty())) { + throw new Unsupported("generator parameter rebound"); + } + IntRanges.Iv[] dl = asLong || generator ? null : longParams.get(f); if (dl != null) { // Arguments the long version takes go there. StringBuilder test = new StringBuilder(); @@ -946,6 +1447,9 @@ private String function(Infer.Fn f, boolean asLong) { b.append(" if (").append(test).append(") {\n return ").append(longName(f)).append('(') .append(pass).append(");\n }\n"); } + // A generator's locals live across suspensions: from here on the + // declarations become fields of the generator object. + int declAt = b.length(); for (Map.Entry e : f.locals.entrySet()) { if (longLocals.contains(e.getKey())) { if (declared.contains(e.getKey())) { @@ -954,17 +1458,68 @@ private String function(Infer.Fn f, boolean asLong) { declared.add(e.getKey()); b.append(" long ").append(var(e.getKey())).append(" = 0L;\n"); } else if (declared.add(e.getKey())) { - if (e.getValue().k == Ty.K.INT) { + if (e.getValue().k == Ty.K.INT || accLocals.contains(e.getKey())) { b.append(" long ").append(var(e.getKey())).append(" = 0L;\n Object ") - .append(big(e.getKey())).append(" = null;\n"); + .append(big(e.getKey())).append(unboundInts.contains(e.getKey()) ? " = Typed.UNBOUND;\n" + : " = null;\n"); } else { b.append(" ").append(jt(e.getValue())).append(' ').append(var(e.getKey())).append(" = ") .append(zero(e.getValue())).append(";\n"); } } } + for (String n : new TreeSet(flatStr)) { + b.append(" int sp").append(var(n)).append(" = -1;\n"); + } + for (String n : new TreeSet(f.locals.keySet())) { + if (guessLocal(n)) { + b.append(" Object ").append(over(n)).append(" = null;\n"); + } + } scalarDecls(b); + for (String n : Infer.paramCells(f.def)) { + // The cell a closure reads, beside the typed parameter. + int pi = f.names.indexOf(n); + Ty lt = f.locals.get(n); + String v; + if (lp != null && lp[pi] != null || longLocals.contains(n)) { + v = "Long.valueOf(" + var(n) + ")"; + } else if (lt != null && lt.k == Ty.K.INT) { + v = box(dual(var(n), big(n))); + } else { + v = box(new E(var(n), lt == null ? Ty.OBJECT : lt)); + } + b.append(" final Object[] ").append(em.cellName(f.def.scope, n)).append(" = new Object[] {").append(v) + .append("};\n"); + } + cellsLive = false; + for (String n : trueCells) { + // A cell a closure shares and something stores into: every read + // and store goes through it, so each sees the other's. + int pi = f.names.indexOf(n); + String v = "null"; + if (pi >= 0) { + IntRanges.Iv[] lpp = lp; + if (lpp != null && lpp[pi] != null) { + v = "Long.valueOf(" + var(n) + ")"; + } else if (f.params[pi].k == Ty.K.INT) { + v = box(dual(var(n), big(n))); + } else { + v = box(new E(var(n), f.params[pi])); + } + } + b.append(" final Object[] ").append(em.cellName(f.def.scope, n)).append(" = new Object[] {").append(v) + .append("};\n"); + } + cellsLive = true; + temps = new StringBuilder(); + if (generator) { + return generator(f, b, declAt); + } + int at = b.length(); boolean abrupt = block(f.def.body, b, 2); + temps.append(fallbackDecls()); + b.insert(at, temps); if (!abrupt) { if (f.ret.k == Ty.K.INT) { // Never reached (the function would not return an int if @@ -982,6 +1537,185 @@ private String function(Infer.Fn f, boolean asLong) { return b.toString(); } + /// Whether the body being emitted is a generator's step (see `generator`). + private boolean inGen; + + /// Ends `b`, the typed version of generator `f` up to its declarations + /// (from `declAt`), with the generator object it returns: the locals as + /// its fields, each parameter copied into its own, and the body lowered + /// into its states by [GenLowering], every statement that cannot suspend + /// emitted by this class. + private String generator(Infer.Fn f, StringBuilder b, int declAt) { + String decls = b.substring(declAt); + b.setLength(declAt); + StringBuilder copies = new StringBuilder(); + StringBuilder own = new StringBuilder(); + for (int i = 0; i < f.names.size(); i++) { + String n = f.names.get(i); + if (f.params[i].k == Ty.K.INT) { + copy(copies, own, "long", var(n)); + copy(copies, own, "Object", big(n)); + } else { + copy(copies, own, jt(f.params[i]), var(n)); + } + } + boolean saved = inGen; + inGen = true; + hiddenLocals.clear(); + String step; + GenLowering g = new GenLowering(genTarget(), em.file(), sc); + g.plain = true; + try { + step = g.step(f.def.body); + } finally { + inGen = saved; + } + b.append(copies); + b.append(" return new PyGenerator(").append(Emitter.javaString(f.def.name)).append(", false) {\n"); + b.append(own).append(decls).append(g.fields()); + for (String n : hiddenLocals) { + b.append(" Object ").append(var(n)).append(" = null;\n"); + } + if (g.usesReturnField()) { + b.append(" Object ret$;\n"); + } + b.append("\n @Override\n protected Object step() {\n"); + b.append(temps).append(fallbackDecls()); + b.append(step); + b.append(" }\n };\n }\n"); + return b.toString(); + } + + /// A parameter the body rebinds to another type (`parser=None`, then + /// `if parser is None: parser = XMLParser()`), other than by its first + /// statement: its local holds either, so it is an object here. + private void widenRebound(Infer.Fn f) { + if (longParams.get(f) != null) { + return; + } + Stmt first = f.def.body.isEmpty() ? null : f.def.body.get(0); + for (int i = 0; i < f.names.size(); i++) { + String n = f.names.get(i); + Ty lt = f.locals.get(n); + if (lt == null || lt.k == Ty.K.INT || f.params[i].k == Ty.K.INT + || "Object".equals(jt(lt)) || jt(lt).equals(jt(f.params[i]))) { + continue; + } + boolean byFirst = first instanceof Assign && ((Assign) first).targets.size() == 1 + && ((Assign) first).targets.get(0) instanceof Name + && n.equals(((Name) ((Assign) first).targets.get(0)).id); + if (!byFirst) { + f.locals.put(n, Ty.OBJECT); + } + } + } + + /// The final copy of parameter `v` the generator object takes, and the + /// field of the object that holds it. + private static void copy(StringBuilder copies, StringBuilder own, String jt, String v) { + copies.append(" final ").append(jt).append(" g$").append(v).append(" = ").append(v).append(";\n"); + own.append(" ").append(jt).append(' ').append(v).append(" = g$").append(v).append(";\n"); + } + + /// This emitter as the target of a typed generator's lowering. Every + /// statement starts with no flow facts: the states it sits between are + /// joined by jumps this class does not see, so what held before one + /// need not hold at the next. + private GenTarget genTarget() { + return new GenTarget() { + @Override + public void stmt(Stmt s, StringBuilder out, int ind) { + forgetFlow(); + StringBuilder r = new StringBuilder(); + if (TypedEmit.this.stmt(s, r, ind + 1)) { + // The lowering goes on writing after it, as javac must allow. + indent(out, ind); + out.append("if (true) {\n").append(r); + indent(out, ind); + out.append("}\n"); + } else { + out.append(r); + } + forgetFlow(); + } + + @Override + public void store(Expr t, String value, StringBuilder out, int ind) { + forgetFlow(); + TypedEmit.this.store(t, new E(value, Ty.OBJECT), out, ind); + forgetFlow(); + } + + @Override + public void storeName(String n, String value, StringBuilder out, int ind) { + store(new Name(n), value, out, ind); + } + + @Override + public String nameLvalue(String n) { + Ty t = cur.locals.get(n); + if (t == null || !"Object".equals(jt(t)) || longLocals.contains(n) || accLocals.contains(n)) { + throw new Unsupported("handler name " + n); + } + return var(n); + } + + @Override + public String expr(Expr e) { + return outOfStmt(() -> box(TypedEmit.this.expr(e))); + } + + @Override + public String cond(Expr e) { + return outOfStmt(() -> testExpr(e)); + } + + @Override + public String fresh(String prefix) { + return prefix + "$" + (++tmp); + } + + @Override + public RuntimeException unsupported(Node n, String what) { + return new Unsupported(what); + } + + @Override + public List handlers() { + return handlers; + } + }; + } + + /// `f` evaluated where no statement is being lowered: nothing may be + /// hoisted ahead of it, and no flow fact holds. + private String outOfStmt(java.util.function.Supplier f) { + StringBuilder savedPre = pre; + Stmt savedStmt = curStmt; + pre = null; + curStmt = null; + forgetFlow(); + try { + return f.get(); + } finally { + pre = savedPre; + curStmt = savedStmt; + forgetFlow(); + } + } + + /// The declarations of the temporaries the function's generic + /// expressions took. + private String fallbackDecls() { + String d = fallback == null ? "" : em.fallbackDecls(fallback); + return d.isEmpty() ? "" : " " + d + "\n"; + } + + private void forgetFlow() { + nonNull = new HashSet(); + shadow = new HashMap(); + } + // ---- statements ------------------------------------------------------ private static void indent(StringBuilder b, int ind) { @@ -1005,18 +1739,86 @@ private String fresh() { return "t" + (++tmp); } + /// Declarations of the temporaries expressions assign in line + /// (`exprTemp`), put at the top of the function being lowered. + private StringBuilder temps; //NOPMD AvoidStringBufferField - the generator's output + + /// A local of Java type `jt` declared at the top of the function, for an + /// expression to assign a value it reads again (`(t = x) ... t`). + private String exprTemp(String jt) { + String t = fresh(); + temps.append(" ").append(jt).append(' ').append(t).append(" = ") + .append("long".equals(jt) ? "0L" : "double".equals(jt) ? "0.0" : "boolean".equals(jt) ? "false" : "null") + .append(";\n"); + return t; + } + /// Statements that hoisted int arithmetic (`hoistInt`) runs before, or /// null where nothing may run first (a loop header). private StringBuilder pre; //NOPMD AvoidStringBufferField - the generator's output private int preInd; private boolean stmt(Stmt s, StringBuilder b, int ind) { + if (s instanceof FunctionDef) { + FunctionDef d = (FunctionDef) s; + List made = new ArrayList(d.decorators); + made.addAll(d.args.defaults); + for (Expr x : d.args.kwDefaults) { + if (x != null) { + made.add(x); + } + } + // The generic function object, decorated, its free names read + // from the cells made on entry; its decorators and defaults read + // the typed locals' values. + Map names = defNames(made); + if (fallback == null) { + fallback = em.fallbackFrame(sc); + } + String fn = names == null ? null : em.genericDef(fallback, sc, d, names); + if (fn == null) { + throw new Unsupported("nested def"); + } + store(new Name(d.name), new E(fn, Ty.OBJECT), b, ind); + return false; + } + if (s instanceof ClassDef) { + ClassDef cd = (ClassDef) s; + List made = new ArrayList(cd.decorators); + for (Expr x : cd.bases) { + made.add(x); + } + for (Keyword k : cd.keywords) { + made.add(k.value); + } + Map names = defNames(made); + if (fallback == null) { + fallback = em.fallbackFrame(sc); + } + String[] made2 = names == null ? null : em.genericClass(fallback, sc, cd, names); + if (made2 == null) { + throw new Unsupported("ClassDef"); + } + // The class statement as the generic version runs it; its body + // reads the function's cells. + for (String line : made2[0].split("\n")) { + if (!line.isEmpty()) { + indent(b, ind); + b.append(line).append('\n'); + } + } + forgetPaths(); + store(new Name(cd.name), new E(made2[1], Ty.OBJECT), b, ind); + return false; + } StringBuilder savedPre = pre; int savedInd = preInd; boolean hoist = (s instanceof ExprStmt || s instanceof Assign || s instanceof AugAssign || s instanceof Return || s instanceof If) && !hasWalrus(s); pre = hoist ? new StringBuilder() : null; preInd = ind; + Stmt savedStmt = curStmt; + curStmt = s; boolean savedPure = stmtPure; stmtPure = hoist && callsArePure(s instanceof If ? ((If) s).test : s); StringBuilder sb = new StringBuilder(); @@ -1031,31 +1833,361 @@ private boolean stmt(Stmt s, StringBuilder b, int ind) { } finally { pre = savedPre; preInd = savedInd; + curStmt = savedStmt; stmtPure = savedPure; } } - private static boolean hasWalrus(Object o) { - if (o instanceof NamedExpr) { - return true; - } - boolean[] f = new boolean[1]; - Infer.children(o, x -> f[0] |= hasWalrus(x)); - return f[0]; + /// `try` as the generic code lowers it (`Emitter.tryStmt`): the same + /// handler matching, `Typed.untake`, `sys.exception()` bookkeeping and + /// order, so a function with a try keeps its typed version. Only the + /// flow facts change: what the body assigns may or may not have + /// happened when a handler runs, so none of it is known there or after. + /// The abrupt answer follows javac's reachability exactly, as `block` + /// requires: a try with handlers completes normally when its body or any + /// handler does, and a finally is abrupt when its own block is. + /// The exception variable and the label of the try whose body is being + /// lowered as jumps (see `raiseOnly`); null elsewhere. + private String[] localRaise; + + /// Builtin exception classes whose construction from plain values runs + /// no user code and cannot raise. + private static final Set PLAIN_EXCEPTIONS = new HashSet(Arrays.asList("ValueError", "KeyError", + "IndexError", "TypeError", "RuntimeError", "LookupError", "ArithmeticError", "ZeroDivisionError", + "AttributeError", "StopIteration", "Exception", "NotImplementedError", "AssertionError", "OverflowError")); + + /// Whether `body` can raise only by a `raise C(args)` statement of its + /// own, with C a builtin exception: ifs, passes and raises over tests + /// and arguments of int and bool locals and constants, and at least one + /// raise. Such a try needs no Java try (see `tryStmt`). + private boolean raiseOnly(List body) { + boolean[] raises = {false}; + return raiseOnly(body, raises) && raises[0]; } - private boolean stmt0(Stmt s, StringBuilder b, int ind) { - if (s instanceof Pass) { - return false; - } - if (s instanceof ExprStmt) { - Expr v = ((ExprStmt) s).value; - if (v instanceof Constant) { - return false; + private boolean raiseOnly(List body, boolean[] raises) { + for (Stmt s : body) { + if (s instanceof Pass) { + continue; } - E e = expr(v); - indent(b, ind); - if (v instanceof Call && e.c.matches("[A-Za-z_][A-Za-z0-9_.<>]*\\(.*\\)")) { + if (s instanceof If) { + If f = (If) s; + if (!noRaise(f.test) || !raiseOnly(f.body, raises) || !raiseOnly(f.orelse, raises)) { + return false; + } + continue; + } + if (s instanceof Raise && ((Raise) s).cause == null && ((Raise) s).exc instanceof Call) { + Call c = (Call) ((Raise) s).exc; + if (!(c.func instanceof Name) || !PLAIN_EXCEPTIONS.contains(((Name) c.func).id) + || binding(((Name) c.func).id) != Scope.Binding.BUILTIN || !c.keywords.isEmpty()) { + return false; + } + for (Expr a : c.args) { + if (!noRaise(a)) { + return false; + } + } + raises[0] = true; + } else { + return false; + } + } + return true; + } + + /// Whether `e` cannot raise: constants, int and bool locals, and + /// comparisons, `not`, `and`/`or` and the overflow-safe int operators + /// of those (`%` and `//` only by a non-zero constant). + private boolean noRaise(Expr e) { + if (e instanceof Constant) { + Constant.Kind k = ((Constant) e).kind; + return k == Constant.Kind.INT || k == Constant.Kind.TRUE || k == Constant.Kind.FALSE || k == Constant.Kind.NONE; + } + if (e instanceof Name) { + String n = ((Name) e).id; + if (binding(n) != Scope.Binding.LOCAL || inlineArgs != null) { + return false; + } + Ty t = localType(n); + return (t.k == Ty.K.INT || t.k == Ty.K.BOOL) && !t.opt; + } + if (e instanceof UnaryOp) { + UnaryOp u = (UnaryOp) e; + return ("not".equals(u.op) || "-".equals(u.op)) && noRaise(u.operand); + } + if (e instanceof BoolOp) { + for (Expr v : ((BoolOp) e).values) { + if (!noRaise(v)) { + return false; + } + } + return true; + } + if (e instanceof Compare) { + Compare c = (Compare) e; + for (String op : c.ops) { + if (!("==".equals(op) || "!=".equals(op) || "<".equals(op) || "<=".equals(op) || ">".equals(op) + || ">=".equals(op))) { + return false; + } + } + if (!noRaise(c.left)) { + return false; + } + for (Expr x : c.comparators) { + if (!noRaise(x)) { + return false; + } + } + return true; + } + if (e instanceof BinOp) { + BinOp o = (BinOp) e; + if ("%".equals(o.op) || "//".equals(o.op)) { + Long k = intConstant(o.right); + return k != null && k.longValue() != 0 && noRaise(o.left); + } + return ("+".equals(o.op) || "-".equals(o.op) || "*".equals(o.op) || "&".equals(o.op) || "|".equals(o.op) + || "^".equals(o.op)) && noRaise(o.left) && noRaise(o.right); + } + return false; + } + + private boolean tryStmt(Try t, StringBuilder b, int ind) { + if (t.star) { + throw new Unsupported("except*"); + } + Set touched = new HashSet(assigned(t.body)); + for (ExceptHandler h : t.handlers) { + touched.addAll(assigned(h.body)); + if (h.name != null) { + touched.add(h.name); + } + } + touched.addAll(assigned(t.orelse)); + touched.addAll(assigned(t.finalbody)); + nonNull.removeAll(touched); + shadow.keySet().removeAll(touched); + forgetPaths(); + Set entry = new HashSet(nonNull); + boolean fin = !t.finalbody.isEmpty(); + if (fin) { + indent(b, ind); + b.append("try {\n"); + ind++; + } + boolean abrupt; + if (t.handlers.isEmpty()) { + abrupt = block(t.body, b, ind); + } else { + String ok = t.orelse.isEmpty() ? null : fresh(); + if (ok != null) { + indent(b, ind); + b.append("boolean ").append(ok).append(" = false;\n"); + } + boolean jump = t.orelse.isEmpty() && raiseOnly(t.body); + String pe = fresh(); + boolean bodyAbrupt; + if (jump) { + // The body raises only by its own `raise` statements: each + // is a jump to the handlers, and no Java try (a setjmp on + // ParparVM) is entered at all. + String lbl = fresh(); + indent(b, ind); + b.append("PyException ").append(pe).append(" = null;\n"); + indent(b, ind); + b.append(lbl).append(": {\n"); + String[] outer = localRaise; + localRaise = new String[] {pe, lbl}; + try { + block(t.body, b, ind + 1); + } finally { + localRaise = outer; + } + indent(b, ind); + b.append("}\n"); + indent(b, ind); + b.append("if (").append(pe).append(" != null) {\n"); + bodyAbrupt = false; + } else { + String tk = fresh(); + indent(b, ind); + b.append("final int ").append(tk).append(" = Typed.taken();\n"); + indent(b, ind); + b.append("try {\n"); + bodyAbrupt = block(t.body, b, ind + 1); + if (ok != null && !bodyAbrupt) { + indent(b, ind + 1); + b.append(ok).append(" = true;\n"); + } + String th = fresh(); + indent(b, ind); + b.append("} catch (Throwable ").append(th).append(") {\n"); + indent(b, ind + 1); + b.append("Typed.untake(").append(tk).append(");\n"); + indent(b, ind + 1); + b.append("final PyException ").append(pe).append(" = Py.convert(").append(th).append(");\n"); + } + handlers.add(pe); + boolean catchAll = false; + boolean allAbrupt = true; + try { + for (int i = 0; i < t.handlers.size(); i++) { + ExceptHandler h = t.handlers.get(i); + nonNull = new HashSet(entry); + indent(b, ind + 1); + if (h.type == null) { + if (i != t.handlers.size() - 1) { + throw new Unsupported("default except not last"); + } + b.append(i == 0 ? "{\n" : "} else {\n"); + catchAll = true; + } else { + b.append(i == 0 ? "if (" : "} else if (").append(pe).append(".matches(").append(excRef(h.type)) + .append(")) {\n"); + } + if (h.name != null) { + Ty lt = localType(h.name); + // An instance local: the handler matched, so the + // value is one of the classes the local joins. + boolean inst = lt.k == Ty.K.INST; + if (binding(h.name) != Scope.Binding.LOCAL) { + throw new Unsupported("except as " + h.name); + } + if (inst && !guessLocal(h.name) && !longLocals.contains(h.name)) { + indent(b, ind + 2); + b.append(var(h.name)).append(" = (").append(jt(lt)).append(") ").append(pe) + .append(".value;\n"); + } else { + // Any other local takes the exception as any store + // of an object: converted, or into a guess's + // object half. + Name hn = new Name(h.name); + hn.line = h.line; + hn.col = h.col; + store(hn, new E(pe + ".value", Ty.OBJECT), b, ind + 2); + } + } + String hv = fresh(); + indent(b, ind + 2); + b.append("final Object ").append(hv).append(" = Py.enterHandler(").append(pe).append(");\n"); + indent(b, ind + 2); + b.append("try {\n"); + boolean ha = block(h.body, b, ind + 3); + indent(b, ind + 2); + b.append("} finally {\n"); + indent(b, ind + 3); + b.append("Py.exitHandler(").append(hv).append(");\n"); + indent(b, ind + 2); + b.append("}\n"); + if (h.name != null && !ha) { + // The name is unbound when the handler ends. + indent(b, ind + 2); + if (localType(h.name).k == Ty.K.INT) { + if (!unboundInts.contains(h.name)) { + throw new Unsupported("except as int " + h.name); + } + b.append(big(h.name)).append(" = Typed.UNBOUND;\n"); + } else { + b.append(var(h.name)).append(" = null;\n"); + if (guessLocal(h.name)) { + indent(b, ind + 2); + b.append(over(h.name)).append(" = null;\n"); + } + } + } + allAbrupt &= ha; + } + } finally { + handlers.remove(handlers.size() - 1); + } + if (!catchAll) { + indent(b, ind + 1); + b.append("} else {\n"); + indent(b, ind + 2); + b.append("throw ").append(pe).append(";\n"); + } + indent(b, ind + 1); + b.append("}\n"); + indent(b, ind); + b.append("}\n"); + nonNull = new HashSet(entry); + abrupt = bodyAbrupt && allAbrupt; + if (ok != null && !bodyAbrupt) { + indent(b, ind); + b.append("if (").append(ok).append(") {\n"); + block(t.orelse, b, ind + 1); + indent(b, ind); + b.append("}\n"); + nonNull = new HashSet(entry); + } + } + if (fin) { + ind--; + indent(b, ind); + b.append("} finally {\n"); + boolean fa = block(t.finalbody, b, ind + 1); + indent(b, ind); + b.append("}\n"); + nonNull = new HashSet(entry); + abrupt |= fa; + } + shadow.keySet().removeAll(touched); + forgetPaths(); + return abrupt; + } + + /// An exception class or instance for `raise` and `except`: a builtin + /// or a module-level class by reference, a tuple of them, or any value + /// the typed code can lower, boxed. + private String excRef(Expr e) { + if (e instanceof Name) { + String n = ((Name) e).id; + Scope.Binding k = binding(n); + if (k == Scope.Binding.BUILTIN && !em.moduleScopeHasStarImport()) { + return em.builtinRef(n); + } + if (k == Scope.Binding.GLOBAL) { + return "g(" + em.slot(n) + ")"; + } + } + if (e instanceof TupleExpr) { + StringBuilder sb = new StringBuilder("Py.tuple("); + List el = ((TupleExpr) e).elts; + for (int i = 0; i < el.size(); i++) { + if (el.get(i) instanceof Starred) { + throw new Unsupported("starred"); + } + sb.append(i == 0 ? "" : ", ").append(excRef(el.get(i))); + } + sb.append(')'); + return Emitter.foldable(el) ? em.hoist("PyTuple", sb.toString()) : sb.toString(); + } + return box(expr(e)); + } + + private static boolean hasWalrus(Object o) { + if (o instanceof NamedExpr) { + return true; + } + boolean[] f = new boolean[1]; + Infer.children(o, x -> f[0] |= hasWalrus(x)); + return f[0]; + } + + private boolean stmt0(Stmt s, StringBuilder b, int ind) { + if (s instanceof Pass) { + return false; + } + if (s instanceof ExprStmt) { + Expr v = ((ExprStmt) s).value; + if (v instanceof Constant) { + return false; + } + E e = expr(v); + indent(b, ind); + if (v instanceof Call && e.c.matches("[A-Za-z_][A-Za-z0-9_.<>]*\\(.*\\)")) { b.append(e.c).append(";\n"); } else { b.append("Typed.drop(").append(box(e)).append(");\n"); @@ -1077,13 +2209,11 @@ && sliceOf(((Assign) s).value)) { String vp = sliceParts((Slice) src.index); E o = expr(dst.value); String op = sliceParts((Slice) dst.index); - if (v.t.k == Ty.K.LIST && o.t.k == Ty.K.LIST) { - indent(b, ind); - b.append("Py.setsliceFrom(").append(v.c).append(", ").append(vp).append(", ").append(o.c) - .append(", ").append(op).append(");\n"); - return false; - } - throw new Unsupported("slice copy between " + v.t + " and " + o.t); + // Py.setsliceFrom takes any sequences, as the generic code does. + indent(b, ind); + b.append("Py.setsliceFrom(").append(box(v)).append(", ").append(vp).append(", ").append(box(o)) + .append(", ").append(op).append(");\n"); + return false; } if (s instanceof Assign && ((Assign) s).targets.size() == 1 && ((Assign) s).targets.get(0) instanceof Name && recycled.contains(((Name) ((Assign) s).targets.get(0)).id) @@ -1108,6 +2238,9 @@ && localType(((Name) ((Assign) s).targets.get(0)).id).k == Ty.K.LIST store(n, new E(c, localType(n.id).nonNone()), b, ind); return false; } + if (s instanceof Assign && dictCount((Assign) s, b, ind)) { + return false; + } if (s instanceof Assign) { Assign a = (Assign) s; if (a.targets.size() == 1 && a.targets.get(0) instanceof TupleExpr && a.value instanceof TupleExpr) { @@ -1144,6 +2277,17 @@ && localType(((Name) ((Assign) s).targets.get(0)).id).k == Ty.K.LIST augAssign((AugAssign) s, b, ind); return false; } + if (s instanceof Return && inGen) { + // A generator's step ends with pc at -1, answering the value. + indent(b, ind); + b.append("pc = -1;\n"); + inGen = false; + try { + return stmt0(s, b, ind); + } finally { + inGen = true; + } + } if (s instanceof Return) { Expr v = ((Return) s).value; indent(b, ind); @@ -1209,10 +2353,13 @@ && localType(((Name) ((Assign) s).targets.get(0)).id).k == Ty.K.LIST } if (s instanceof While) { While w = (While) s; - if (!w.orelse.isEmpty()) { - throw new Unsupported("while-else"); - } boolean forever = w.test instanceof Constant && ((Constant) w.test).kind == Constant.Kind.TRUE; + // A loop that never ends but by a break never runs its else. + String label = w.orelse.isEmpty() || forever ? "" : fresh(); + if (!label.isEmpty()) { + indent(b, ind); + b.append(label).append(": {\n"); + } nonNull.removeAll(assigned(w.body)); shadow.keySet().removeAll(assigned(w.body)); forgetPaths(); @@ -1252,22 +2399,50 @@ && localType(((Name) ((Assign) s).targets.get(0)).id).k == Ty.K.LIST b.append("while (").append(test).append(") {\n"); } nonNull.addAll(whenTrue(w.test)); - block(w.body, b, ind + 1); + loopLabels.push(label); + try { + block(w.body, b, ind + 1); + } finally { + loopLabels.pop(); + } nonNull = inv; if (!Infer.hasBreak(w.body)) { nonNull.addAll(whenFalse(w.test)); } indent(b, ind); b.append("}\n"); + if (!label.isEmpty()) { + return loopElse(w.orelse, w.body, inv, b, ind); + } return forever && !Infer.hasBreak(w.body); } if (s instanceof For) { - forLoop((For) s, b, ind); + For f = (For) s; + String label = f.orelse.isEmpty() ? "" : fresh(); + if (!label.isEmpty()) { + indent(b, ind); + b.append(label).append(": {\n"); + } + Set inv = new HashSet(nonNull); + inv.removeAll(assigned(f.body)); + if (f.target instanceof Name) { + inv.remove(((Name) f.target).id); + } + loopLabels.push(label); + try { + forLoop(f, b, ind); + } finally { + loopLabels.pop(); + } + if (!label.isEmpty()) { + return loopElse(f.orelse, f.body, inv, b, ind); + } return false; } if (s instanceof Break) { indent(b, ind); - b.append("break;\n"); + String l = loopLabels.isEmpty() ? "" : loopLabels.peek(); + b.append(l.isEmpty() ? "break;\n" : "break " + l + ";\n"); return true; } if (s instanceof Continue) { @@ -1275,38 +2450,313 @@ && localType(((Name) ((Assign) s).targets.get(0)).id).k == Ty.K.LIST b.append("continue;\n"); return true; } + if (s instanceof Raise) { + Raise r = (Raise) s; + indent(b, ind); + if (r.exc == null) { + if (handlers.isEmpty()) { + throw new Unsupported("bare raise outside a handler"); + } + b.append("throw ").append(handlers.get(handlers.size() - 1)).append(";\n"); + } else if (r.cause != null) { + b.append("throw Py.raise(").append(excRef(r.exc)).append(", ").append(excRef(r.cause)).append(");\n"); + } else if (localRaise != null) { + // A jump to the handlers of the try around it (see `raiseOnly`). + // The class is looked up at run time and may have been + // rebound to one whose construction raises: that error is the + // one the handlers see. The Java try is entered only on this + // path, never on the one that does not raise. + String th = fresh(); + b.append("try {\n"); + indent(b, ind + 1); + b.append(localRaise[0]).append(" = Py.raise(").append(excRef(r.exc)).append(");\n"); + indent(b, ind); + b.append("} catch (Throwable ").append(th).append(") {\n"); + indent(b, ind + 1); + b.append(localRaise[0]).append(" = Py.convert(").append(th).append(");\n"); + indent(b, ind); + b.append("}\n"); + indent(b, ind); + b.append("break ").append(localRaise[1]).append(";\n"); + } else { + b.append("throw Py.raise(").append(excRef(r.exc)).append(");\n"); + } + return true; + } + if (s instanceof Try) { + return tryStmt((Try) s, b, ind); + } + if (s instanceof Assert) { + Assert a = (Assert) s; + indent(b, ind); + b.append("if (!(").append(testExpr(a.test)).append(")) {\n"); + indent(b, ind + 1); + if (a.msg == null) { + b.append("throw Py.raise(Py.ASSERTION_ERROR);\n"); + } else { + b.append("throw Py.raise(Py.call(Py.ASSERTION_ERROR, ").append(box(expr(a.msg))).append("));\n"); + } + indent(b, ind); + b.append("}\n"); + return false; + } + if (s instanceof AnnAssign) { + // In a function the annotation is never evaluated. + AnnAssign a = (AnnAssign) s; + if (a.value != null) { + store(a.target, expr(a.value), b, ind); + } + return false; + } + if (s instanceof Global) { + return false; + } + if (s instanceof Import) { + for (Alias a : ((Import) s).names) { + String load = "Py.importModule(" + Emitter.javaString(a.name) + ")"; + int dot = a.name.indexOf('.'); + if (a.asname != null || dot < 0) { + store(new Name(a.asname != null ? a.asname : a.name), new E(load, Ty.OBJECT), b, ind); + } else { + indent(b, ind); + b.append(load).append(";\n"); + String top = a.name.substring(0, dot); + store(new Name(top), new E("Py.importModule(" + Emitter.javaString(top) + ")", Ty.OBJECT), b, ind); + } + } + return false; + } + if (s instanceof ImportFrom) { + ImportFrom f = (ImportFrom) s; + String mod = em.resolveRelative(f); + if ("__future__".equals(mod)) { + return false; + } + String m = fresh(); + indent(b, ind); + b.append("final PyModule ").append(m).append(" = Py.importModule(").append(Emitter.javaString(mod)).append(");\n"); + for (Alias a : f.names) { + if ("*".equals(a.name)) { + throw new Unsupported("import *"); + } + store(new Name(a.asname != null ? a.asname : a.name), + new E("Py.importFrom(" + m + ", " + Emitter.javaString(a.name) + ")", Ty.OBJECT), b, ind); + } + return false; + } + if (s instanceof Delete) { + for (Expr t : ((Delete) s).targets) { + delete(t, b, ind); + } + return false; + } + if (s instanceof With) { + return withStmt((With) s, b, ind); + } throw new Unsupported(s.getClass().getSimpleName()); } - /// `return e` from a function returning an int (see `retJ`); the - /// statement is already indented. - private void returnInt(E e, StringBuilder b, int ind) { - if (e.pk != null) { - // The marker and what it stands for, passed on as they are. - b.append("return ").append(e.pk).append(";\n"); + /// `del t`: an attribute or an item, through the generic object protocol; + /// a local that holds an object, cleared. + private void delete(Expr t, StringBuilder b, int ind) { + if (t instanceof Name && trueCell(((Name) t).id)) { + String n = ((Name) t).id; + indent(b, ind); + b.append("Typed.drop(Typed.local(").append(cellRef(n)).append(", ").append(Emitter.javaString(n)) + .append("));\n"); + indent(b, ind); + b.append(cellRef(n)).append(" = null;\n"); return; } - if (e.lc != null && literal(e.lc) && !e.lc.contains("-9223372036854775808")) { - b.append("return ").append(e.lc).append(";\n"); + if (t instanceof TupleExpr || t instanceof ListExpr) { + for (Expr e : t instanceof TupleExpr ? ((TupleExpr) t).elts : ((ListExpr) t).elts) { + delete(e, b, ind); + } return; } - if (e.lc != null) { - String t = fresh(); - b.append("long ").append(t).append(" = ").append(e.lc).append(";\n"); + if (t instanceof Attribute) { + Attribute a = (Attribute) t; indent(b, ind); - b.append("return ").append(t).append(" != Long.MIN_VALUE ? ").append(t) - .append(" : Typed.retBig(Long.valueOf(").append(t).append("));\n"); + b.append("Py.obj(").append(box(expr(a.value))).append(").delAttr(").append(Emitter.javaString(a.attr)) + .append(");\n"); + forgetPaths(); return; } - if (e.ll != null) { - b.append("return ").append(e.bg).append(" == null && ").append(e.ll).append(" != Long.MIN_VALUE ? ") - .append(e.ll).append(" : Typed.retBig(").append(e.c).append(");\n"); + if (t instanceof Subscript) { + Subscript x = (Subscript) t; + String o = box(expr(x.value)); + indent(b, ind); + b.append("Py.obj(").append(o).append(").delItem(").append(box(expr(x.index))).append(");\n"); + forgetPaths(); return; } - b.append("return Typed.retObj(").append(box(e)).append(");\n"); + if (t instanceof Name && binding(((Name) t).id) == Scope.Binding.LOCAL) { + String n = ((Name) t).id; + Ty lt = localType(n); + if (lt == null || !"Object".equals(jt(lt)) || longLocals.contains(n) || accLocals.contains(n) + || scalars.containsKey(n)) { + throw new Unsupported("del of " + n); + } + if (lt.k == Ty.K.INT) { + if (!unboundInts.contains(n) || shadow.containsKey(n)) { + throw new Unsupported("del of " + n); + } + // Read first (deleting an unbound local raises), then the + // object half says unbound again. + String v = box(expr((Name) t)); + indent(b, ind); + b.append("Typed.drop(").append(v).append(");\n"); + indent(b, ind); + b.append(big(n)).append(" = Typed.UNBOUND;\n"); + forgetPathsOf(n); + return; + } + // Read first: deleting an unbound local raises. + String v = box(expr((Name) t)); + indent(b, ind); + b.append("Typed.drop(").append(v).append(");\n"); + indent(b, ind); + b.append(var(n)).append(" = null;\n"); + if (guessLocal(n)) { + indent(b, ind); + b.append(over(n)).append(" = null;\n"); + } + nonNull.remove(n); + forgetPathsOf(n); + return; + } + throw new Unsupported("del of " + t.getClass().getSimpleName()); } - /// A `range` bound as a Java long. + /// `with`: as the generic version runs it (Emitter.withItems), the body + /// typed. Exit may swallow what the body raised, so nothing the body + /// learned holds after it. + private boolean withStmt(With w, StringBuilder b, int ind) { + if (w.isAsync) { + throw new Unsupported("async with"); + } + Set touched = new HashSet(assigned(w.body)); + for (WithItem it : w.items) { + if (it.vars != null) { + Infer.children(it.vars, x -> { + if (x instanceof Name) { + touched.add(((Name) x).id); + } + }); + if (it.vars instanceof Name) { + touched.add(((Name) it.vars).id); + } + } + } + nonNull.removeAll(touched); + shadow.keySet().removeAll(touched); + forgetPaths(); + Set entry = new HashSet(nonNull); + String[] outer = localRaise; + // A raise in the body is thrown, for the exit to see. + localRaise = null; + try { + withItems(w, 0, b, ind); + } finally { + localRaise = outer; + } + nonNull = entry; + shadow.keySet().removeAll(touched); + forgetPaths(); + return false; + } + + private void withItems(With w, int i, StringBuilder b, int ind) { + if (i == w.items.size()) { + block(w.body, b, ind); + return; + } + WithItem item = w.items.get(i); + String mgr = fresh(); + String exit = fresh(); + String ok = fresh(); + String th = fresh(); + String pe = fresh(); + String tk = fresh(); + String ctx = box(expr(item.context)); + indent(b, ind); + b.append("final Object ").append(mgr).append(" = ").append(ctx).append(";\n"); + indent(b, ind); + b.append("final Object ").append(exit).append(" = ").append(em.attrSite("__exit__")).append(".get(").append(mgr) + .append(");\n"); + String entered = em.attrSite("__enter__") + ".call0(" + mgr + ")"; + if (item.vars != null) { + String ev = fresh(); + indent(b, ind); + b.append("final Object ").append(ev).append(" = ").append(entered).append(";\n"); + store(item.vars, new E(ev, Ty.OBJECT), b, ind); + } else { + indent(b, ind); + b.append(entered).append(";\n"); + } + indent(b, ind); + b.append("boolean ").append(ok).append(" = true;\n"); + indent(b, ind); + b.append("final int ").append(tk).append(" = Typed.taken();\n"); + indent(b, ind); + b.append("try {\n"); + withItems(w, i + 1, b, ind + 1); + indent(b, ind); + b.append("} catch (Throwable ").append(th).append(") {\n"); + indent(b, ind + 1); + b.append("Typed.untake(").append(tk).append(");\n"); + indent(b, ind + 1); + b.append(ok).append(" = false;\n"); + indent(b, ind + 1); + b.append("final PyException ").append(pe).append(" = Py.convert(").append(th).append(");\n"); + indent(b, ind + 1); + b.append("if (!Py.isTrue(Py.call(").append(exit).append(", Py.typeOf(").append(pe).append(".value), ") + .append(pe).append(".value, Py.NONE))) {\n"); + indent(b, ind + 2); + b.append("throw ").append(pe).append(";\n"); + indent(b, ind + 1); + b.append("}\n"); + indent(b, ind); + b.append("} finally {\n"); + indent(b, ind + 1); + b.append("if (").append(ok).append(") {\n"); + indent(b, ind + 2); + b.append("Py.call(").append(exit).append(", Py.NONE, Py.NONE, Py.NONE);\n"); + indent(b, ind + 1); + b.append("}\n"); + indent(b, ind); + b.append("}\n"); + } + + /// `return e` from a function returning an int (see `retJ`); the + /// statement is already indented. + private void returnInt(E e, StringBuilder b, int ind) { + if (e.pk != null) { + // The marker and what it stands for, passed on as they are. + b.append("return ").append(e.pk).append(";\n"); + return; + } + if (e.lc != null && literal(e.lc) && !e.lc.contains("-9223372036854775808")) { + b.append("return ").append(e.lc).append(";\n"); + return; + } + if (e.lc != null) { + String t = fresh(); + b.append("long ").append(t).append(" = ").append(e.lc).append(";\n"); + indent(b, ind); + b.append("return ").append(t).append(" != Long.MIN_VALUE ? ").append(t) + .append(" : Typed.retBig(Long.valueOf(").append(t).append("));\n"); + return; + } + if (e.ll != null) { + b.append("return ").append(e.bg).append(" == null && ").append(e.ll).append(" != Long.MIN_VALUE ? ") + .append(e.ll).append(" : Typed.retBig(").append(e.c).append(");\n"); + return; + } + b.append("return Typed.retObj(").append(box(e)).append(");\n"); + } + + /// A `range` bound as a Java long. private String bound(E e) { if (e.lc != null) { return e.lc; @@ -1359,7 +2809,8 @@ private void strLoop(For f, E it, Set inBody, StringBuilder b, int ind) } else { b.append(var(tn)).append(" = ").append(conv(c, vt)).append(";\n"); } - if (vt.k == Ty.K.STR || vt.k == Ty.K.DYN) { + clearOver(tn, b, ind + 2); + if (vt.k == Ty.K.STR || vt.wide()) { nonNull.add(tn); } } @@ -1374,6 +2825,88 @@ private void strLoop(For f, E it, Set inBody, StringBuilder b, int ind) b.append("}\n"); } + /// `for w in s.split()` / `for w in s.split(sep)` with a str target: the + /// pieces found one at a time in `s`, held in a Java local, so the list + /// and its array are never made. The string is immutable, so finding + /// each piece as the loop reaches it sees what the list would hold. + private boolean splitLoop(For f, StringBuilder b, int ind) { + if (!(f.iter instanceof Call) || !(((Call) f.iter).func instanceof Attribute)) { + return false; + } + Call c = (Call) f.iter; + Attribute m = (Attribute) c.func; + String tn = ((Name) f.target).id; + Ty vt = localType(tn); + if (!"split".equals(m.attr) || !c.keywords.isEmpty() || c.args.size() > 1 + // A separator that is a name or a constant is read with no + // statement of its own, so the receiver is still read first. + || c.args.size() == 1 && !(c.args.get(0) instanceof Name || c.args.get(0) instanceof Constant) + || longLocals.contains(tn) + || vt.k != Ty.K.STR && !vt.wide()) { + return false; + } + E r = expr(m.value); + if (r.t.k != Ty.K.STR || r.t.opt) { + return false; + } + E sepE = c.args.isEmpty() ? null : expr(c.args.get(0)); + if (sepE != null && (sepE.t.k != Ty.K.STR || sepE.t.opt)) { + return false; + } + String s = fresh(); + String p = fresh(); + String q = fresh(); + indent(b, ind); + b.append("{\n"); + indent(b, ind + 1); + b.append("String ").append(s).append(" = ").append(r.c).append(";\n"); + if (sepE == null) { + indent(b, ind + 1); + b.append("int ").append(p).append(" = 0;\n"); + indent(b, ind + 1); + b.append("while ((").append(p).append(" = Typed.wordStart(").append(s).append(", ").append(p).append(")) < ") + .append(s).append(".length()) {\n"); + indent(b, ind + 2); + b.append("int ").append(q).append(" = Typed.wordEnd(").append(s).append(", ").append(p).append(");\n"); + indent(b, ind + 2); + b.append(var(tn)).append(" = ").append(s).append(".substring(").append(p).append(", ").append(q) + .append(");\n"); + clearOver(tn, b, ind + 2); + indent(b, ind + 2); + b.append(p).append(" = ").append(q).append(";\n"); + } else { + String sep = fresh(); + indent(b, ind + 1); + b.append("String ").append(sep).append(" = Typed.splitSep(").append(sepE.c).append(");\n"); + indent(b, ind + 1); + b.append("int ").append(p).append(" = 0;\n"); + indent(b, ind + 1); + b.append("while (").append(p).append(" >= 0) {\n"); + indent(b, ind + 2); + b.append("int ").append(q).append(" = ").append(s).append(".indexOf(").append(sep).append(", ").append(p) + .append(");\n"); + indent(b, ind + 2); + b.append(var(tn)).append(" = ").append(q).append(" < 0 ? ").append(s).append(".substring(").append(p) + .append(") : ").append(s).append(".substring(").append(p).append(", ").append(q).append(");\n"); + clearOver(tn, b, ind + 2); + indent(b, ind + 2); + b.append(p).append(" = ").append(q).append(" < 0 ? -1 : ").append(q).append(" + ").append(sep) + .append(".length();\n"); + } + Set inBody = assigned(f.body); + if (!inBody.contains(tn)) { + nonNull.add(tn); + } + block(f.body, b, ind + 2); + // The target keeps whatever it held when the loop runs no times. + nonNull.remove(tn); + indent(b, ind + 1); + b.append("}\n"); + indent(b, ind); + b.append("}\n"); + return true; + } + /// Whether every read of `n` in `o` is the argument of the builtin `ord`. private boolean onlyOrd(Object o, String n) { if (ordOf(o, n)) { @@ -1398,9 +2931,28 @@ private boolean ordOf(Object o, String n) { && sc.resolve("ord") == Scope.Binding.BUILTIN && !em.moduleScopeHasStarImport(); } + /// The `else` of a loop just emitted inside the block `label` opened: + /// it runs when the loop ends without a break, which leaves the block. + /// Whether the block cannot complete normally, as javac judges it. + private boolean loopElse(List orelse, List body, Set inv, StringBuilder b, int ind) { + boolean abrupt = block(orelse, b, ind + 1); + indent(b, ind); + b.append("}\n"); + // After a break the else did not run: only what held at the top of + // every iteration is known. + nonNull.retainAll(inv); + shadow.keySet().removeAll(assigned(orelse)); + forgetPaths(); + return abrupt && !Infer.hasBreak(body); + } + private void forLoop(For f, StringBuilder b, int ind) { - if (!f.orelse.isEmpty()) { - throw new Unsupported("for-else"); + if (indexedLoop(f, b, ind)) { + return; + } + if (!(f.target instanceof Name) || binding(((Name) f.target).id) != Scope.Binding.LOCAL) { + anyTargetLoop(f, b, ind); + return; } Set inBody = assigned(f.body); nonNull.removeAll(inBody); @@ -1409,7 +2961,7 @@ private void forLoop(For f, StringBuilder b, int ind) { if (f.target instanceof Name) { nonNull.remove(((Name) f.target).id); } - if (!(f.target instanceof Name) || sc.resolve(((Name) f.target).id) != Scope.Binding.LOCAL) { + if (!(f.target instanceof Name) || binding(((Name) f.target).id) != Scope.Binding.LOCAL) { throw new Unsupported("for target"); } String v = var(((Name) f.target).id); @@ -1427,7 +2979,12 @@ private void forLoop(For f, StringBuilder b, int ind) { if (a.size() == 3) { Long c = intConstant(a.get(2)); if (c == null || c.longValue() == 0) { - throw new Unsupported("range step"); + if (longLocals.contains(((Name) f.target).id)) { + throw new Unsupported("range step"); + } + // A step known only at run time: the range object. + anyTargetLoop(f, b, ind); + return; } step = c.longValue(); } @@ -1469,13 +3026,78 @@ private void forLoop(For f, StringBuilder b, int ind) { b.append("}\n"); return; } + if (splitLoop(f, b, ind)) { + return; + } + if (displayItems(f.iter) != null) { + if (longLocals.contains(((Name) f.target).id)) { + throw new Unsupported("for over a display into a long"); + } + if (vt.k == Ty.K.INT) { + anyTargetLoop(f, b, ind); + return; + } + indent(b, ind); + b.append("{\n"); + String x = displayLoopHead(f.iter, b, ind); + indent(b, ind + 2); + if (guessLocal(((Name) f.target).id)) { + storeGuess(v, over(((Name) f.target).id), vt, new E(x, Ty.OBJECT), b, ind + 2); + } else { + b.append(v).append(" = ").append(conv(new E(x, Ty.OBJECT), vt)).append(";\n"); + } + block(f.body, b, ind + 2); + indent(b, ind + 1); + b.append("}\n"); + indent(b, ind); + b.append("}\n"); + return; + } E it = expr(f.iter); if (it.t.k == Ty.K.STR && !it.t.opt) { strLoop(f, it, inBody, b, ind); return; } if (it.t.k != Ty.K.LIST) { - throw new Unsupported("for over " + it.t); + // Any other iterable: the generic iterator, with the body still + // typed. An int target is held as a long and an object, which a + // value of unknown type cannot fill without a test, so it stays + // with the generic version. + if (longLocals.contains(((Name) f.target).id)) { + throw new Unsupported("for over " + it.t + " into a long"); + } + if (vt.k == Ty.K.INT) { + // The general loop stores through storePair, which tests. + anyTargetLoop(f, b, ind); + return; + } + String itr = fresh(); + String x = fresh(); + boolean guess = guessLocal(((Name) f.target).id); + String store = guess ? null : conv(new E(x, Ty.OBJECT), vt); + indent(b, ind); + b.append("{\n"); + indent(b, ind + 1); + b.append("final PyObject ").append(itr).append(" = Py.iter(").append(box(it)).append(");\n"); + indent(b, ind + 1); + b.append("try {\n"); + indent(b, ind + 1); + b.append(loopHead(x, loopNext(itr), null)); + indent(b, ind + 2); + if (guess) { + // A guessed target: the item into the slot when it fits. + storeGuess(v, over(((Name) f.target).id), vt, new E(x, Ty.OBJECT), b, ind + 2); + } else { + b.append(v).append(" = ").append(store).append(";\n"); + } + block(f.body, b, ind + 2); + indent(b, ind + 1); + b.append("}\n"); + indent(b, ind + 1); + b.append(loopHandler(itr)); + indent(b, ind); + b.append("}\n"); + return; } Ty el = in.elem(it.t); String l = fresh(); @@ -1483,17 +3105,20 @@ private void forLoop(For f, StringBuilder b, int ind) { indent(b, ind); b.append("{\n"); indent(b, ind + 1); - b.append("PyList ").append(l).append(" = Typed.iterable(").append(it.c).append(");\n"); + b.append("PyList ").append(l).append(" = Typed.iterable(").append(listOf(it)).append(");\n"); indent(b, ind + 1); b.append("for (int ").append(k).append(" = 0; ").append(k).append(" < ").append(l).append(".size(); ") .append(k).append("++) {\n"); indent(b, ind + 2); - E item = el.k == Ty.K.FLOAT ? new E("Typed.atF(" + l + ", " + k + ")", Ty.FLOAT) + E item = el.k != Ty.K.INT && in.guessedSite(it.t) ? guessedElem(l + ".get(" + k + ")", el, b, ind + 2) + : el.k == Ty.K.FLOAT ? new E("Typed.atF(" + l + ", " + k + ")", Ty.FLOAT) : new E(unbox(l + ".get(" + k + ")", el), el); if (vt.k == Ty.K.INT && !longLocals.contains(((Name) f.target).id)) { storePair(v, big(((Name) f.target).id), item, b, ind + 2); } else if (vt.k == Ty.K.INT) { b.append(v).append(" = Typed.toLong(").append(box(item)).append(");\n"); + } else if (guessLocal(((Name) f.target).id)) { + storeGuess(v, over(((Name) f.target).id), vt, item, b, ind + 2); } else { b.append(v).append(" = ").append(conv(item, vt)).append(";\n"); } @@ -1504,6 +3129,252 @@ private void forLoop(For f, StringBuilder b, int ind) { b.append("}\n"); } + /// `for i, x in enumerate(l)` and `for a, b in zip(l, m)` over typed + /// lists, into plain locals: walked by index as the lists' own + /// iterators walk them (each length read again at every step), with no + /// iterator and no tuple per item. False, writing nothing, for any + /// other loop. + private boolean indexedLoop(For f, StringBuilder b, int ind) { + if (!(f.iter instanceof Call) || !(f.target instanceof TupleExpr)) { + return false; + } + Call c = (Call) f.iter; + if (!(c.func instanceof Name) || binding(((Name) c.func).id) != Scope.Binding.BUILTIN + || em.moduleScopeHasStarImport() || !c.keywords.isEmpty() || Infer.hasStarred(c.args)) { + return false; + } + String n = ((Name) c.func).id; + boolean en = "enumerate".equals(n); + if (!en && !"zip".equals(n) || c.args.isEmpty() || en && c.args.size() > 2) { + return false; + } + List targets = ((TupleExpr) f.target).elts; + int lists = en ? 1 : c.args.size(); + if (targets.size() != (en ? 2 : lists)) { + return false; + } + for (Expr t : targets) { + if (!(t instanceof Name) || binding(((Name) t).id) != Scope.Binding.LOCAL) { + return false; + } + } + for (int i = 0; i < lists; i++) { + Ty lt = in.type(c.args.get(i), cur, sc); + if (lt.k != Ty.K.LIST || lt.opt || in.guessed(c.args.get(i))) { + return false; + } + } + if (en && c.args.size() == 2) { + Ty st = in.type(c.args.get(1), cur, sc); + if (st.k != Ty.K.INT || st.opt) { + return false; + } + } + Set inBody = assigned(f.body); + nonNull.removeAll(inBody); + shadow.keySet().removeAll(inBody); + forgetPaths(); + for (Expr t : targets) { + nonNull.remove(((Name) t).id); + } + indent(b, ind); + b.append("{\n"); + // The arguments in order, once, as the call evaluates them. + String[] ls = new String[lists]; + Ty[] els = new Ty[lists]; + for (int i = 0; i < lists; i++) { + E le = expr(c.args.get(i)); + ls[i] = fresh(); + els[i] = in.elem(le.t); + indent(b, ind + 1); + // A field read may answer through its object fallback: as a + // list, checked. + b.append("PyList ").append(ls[i]).append(" = Typed.iterable(").append(listOf(le)) + .append(");\n"); + } + String start = null; + if (en) { + start = fresh(); + indent(b, ind + 1); + b.append("long ").append(start).append(" = ") + .append(c.args.size() == 2 ? bound(expr(c.args.get(1))) : "0L").append(";\n"); + } + String k = fresh(); + StringBuilder cond = new StringBuilder(); + for (String l : ls) { + cond.append(cond.length() == 0 ? "" : " && ").append(k).append(" < ").append(l).append(".size()"); + } + indent(b, ind + 1); + b.append("for (int ").append(k).append(" = 0; ").append(cond).append("; ").append(k).append("++) {\n"); + int ti = 0; + if (en) { + String tn = ((Name) targets.get(0)).id; + String v = var(tn); + Ty vt = localType(tn); + String ix = "(" + start + " + " + k + ")"; + if (vt.k == Ty.K.INT) { + indent(b, ind + 2); + b.append(v).append(" = ").append(ix).append(";\n"); + if (!longLocals.contains(tn)) { + indent(b, ind + 2); + b.append(big(tn)).append(" = null;\n"); + } + } else { + store(targets.get(0), new E("Long.valueOf(" + ix + ")", Ty.INT), b, ind + 2); + } + ti = 1; + } + for (int i = 0; i < lists; i++) { + Ty el = els[i]; + String l = ls[i]; + Ty at = in.type(c.args.get(i), cur, sc); + E item = el.k != Ty.K.INT && in.guessedSite(at) ? guessedElem(l + ".get(" + k + ")", el, b, ind + 2) + : el.k == Ty.K.FLOAT ? new E("Typed.atF(" + l + ", " + k + ")", Ty.FLOAT) + : new E(unbox(l + ".get(" + k + ")", el), el); + store(targets.get(ti + i), item, b, ind + 2); + } + block(f.body, b, ind + 2); + indent(b, ind + 1); + b.append("}\n"); + indent(b, ind); + b.append("}\n"); + return true; + } + + /// The items of a tuple or list display with no starred item, or null. + private static List displayItems(Expr iter) { + List elts = iter instanceof TupleExpr ? ((TupleExpr) iter).elts + : iter instanceof ListExpr ? ((ListExpr) iter).elts : null; + if (elts == null || elts.isEmpty()) { + return null; + } + for (Expr x : elts) { + if (x instanceof Starred) { + return null; + } + } + return elts; + } + + /// Opens a loop over a display ([#displayItems]) -- bs4's `for attrdict + /// in attrs, kwargs:` -- as an array of the items, evaluated once and in + /// order as the tuple would be, walked by index: no tuple, iterator or + /// loop handler. Answers the name holding the item. + private String displayLoopHead(Expr iter, StringBuilder b, int ind) { + StringBuilder items = new StringBuilder(); + for (Expr x : displayItems(iter)) { + if (items.length() > 0) { + items.append(", "); + } + items.append(box(expr(x))); + } + String arr = fresh(); + String k = fresh(); + String x = fresh(); + indent(b, ind + 1); + b.append("final Object[] ").append(arr).append(" = {").append(items).append("};\n"); + indent(b, ind + 1); + b.append("for (int ").append(k).append(" = 0; ").append(k).append(" < ").append(arr).append(".length; ") + .append(k).append("++) {\n"); + indent(b, ind + 2); + b.append("final Object ").append(x).append(" = ").append(arr).append('[').append(k).append("];\n"); + return x; + } + + /// A loop whose target is not one local: a tuple to unpack, a global, an + /// attribute or an element. Each item is stored as an assignment would. + private void anyTargetLoop(For f, StringBuilder b, int ind) { + Set inBody = new HashSet(assigned(f.body)); + inBody.addAll(assigned(java.util.Collections.singletonList(new Assign( + java.util.Collections.singletonList(f.target), f.target)))); + nonNull.removeAll(inBody); + shadow.keySet().removeAll(inBody); + forgetPaths(); + if (displayItems(f.iter) != null) { + indent(b, ind); + b.append("{\n"); + String x = displayLoopHead(f.iter, b, ind); + store(f.target, new E(x, Ty.OBJECT), b, ind + 2); + block(f.body, b, ind + 2); + indent(b, ind + 1); + b.append("}\n"); + indent(b, ind); + b.append("}\n"); + return; + } + E it = loopSource(f.iter, f.target); + String handled = null; + indent(b, ind); + b.append("{\n"); + if (it.t.k == Ty.K.LIST && !it.t.opt) { + Ty el = in.elem(it.t); + String l = fresh(); + String k = fresh(); + indent(b, ind + 1); + b.append("PyList ").append(l).append(" = Typed.iterable(").append(listOf(it)).append(");\n"); + indent(b, ind + 1); + b.append("for (int ").append(k).append(" = 0; ").append(k).append(" < ").append(l).append(".size(); ") + .append(k).append("++) {\n"); + E item = el.k != Ty.K.INT && in.guessedSite(it.t) ? guessedElem(l + ".get(" + k + ")", el, b, ind + 2) + : el.k == Ty.K.FLOAT ? new E("Typed.atF(" + l + ", " + k + ")", Ty.FLOAT) + : new E(unbox(l + ".get(" + k + ")", el), el); + store(f.target, spillTo(item, b, ind + 2), b, ind + 2); + } else if (Emitter.itemPairs(f.iter, f.target) != null) { + // An ItemWalk is never a generator, and the iterator it may wrap + // runs its own handler: no loop handler, its next() called + // directly. + String itr = fresh(); + String x = fresh(); + indent(b, ind + 1); + b.append("final PyObject ").append(itr).append(" = ").append(it.c).append(";\n"); + indent(b, ind + 1); + b.append(loopHead(x, itr + ".next()", null)); + store(f.target, new E(x, Ty.OBJECT), b, ind + 2); + } else { + String itr = fresh(); + String x = fresh(); + indent(b, ind + 1); + b.append("final PyObject ").append(itr).append(" = Py.iter(").append(box(it)).append(");\n"); + indent(b, ind + 1); + b.append("try {\n"); + indent(b, ind + 1); + b.append(loopHead(x, loopNext(itr), null)); + store(f.target, new E(x, Ty.OBJECT), b, ind + 2); + handled = itr; + } + block(f.body, b, ind + 2); + indent(b, ind + 1); + b.append("}\n"); + if (handled != null) { + indent(b, ind + 1); + b.append(loopHandler(handled)); + } + indent(b, ind); + b.append("}\n"); + } + + /// The next value of loop iterator `itr`, without a handler per value when + /// it is a plain generator: the loop holds the one handler instead + /// ([#loopHandler]; see PyGenerator.loopNext). + static String loopNext(String itr) { + return "PyGenerator.loopNext(" + itr + ")"; + } + + /// `for (Object x = next; x != null; [step, ]x = next) {` -- the first + /// fetch is the init, not the test, so the back edge lands on the test + /// INSIDE the try. A loop whose test is the try's first instruction jumps + /// back to the try's own start, and the translator re-enters the try on + /// every iteration. + static String loopHead(String x, String next, String step) { + return "for (Object " + x + " = " + next + "; " + x + " != null; " + + (step != null ? step + ", " : "") + x + " = " + next + ") {\n"; + } + + /// Closes the try a [#loopNext] loop is wrapped in. + static String loopHandler(String itr) { + return "} catch (Throwable " + itr + "$e) {\n throw PyGenerator.loopEscape(" + itr + ", " + itr + "$e);\n}\n"; + } + private static Long intConstant(Expr e) { if (e instanceof Constant && ((Constant) e).kind == Constant.Kind.INT) { // Any spelling: hex, octal and binary constants are as common @@ -1529,23 +3400,381 @@ private static boolean literal(String c) { return c.matches("\\(?-?[0-9]+L\\)?"); } + /// The statement being lowered, which a comprehension is hoisted ahead of. + private Stmt curStmt; + + /// A list, set or dict comprehension, as a loop run ahead of the + /// statement (`pre`) into a fresh container. Only where nothing the + /// statement evaluates before it could observe the difference + /// (`inertBefore`), and where its targets name no local of the function. + private E comp(Comp c) { + if (pre == null || condDepth != 0 || curStmt == null || c.scope == null || !inertBefore(curStmt, c)) { + throw new Unsupported("comprehension"); + } + Map vars = new HashMap(); + for (Comprehension g : c.generators) { + if (g.isAsync || !compTargets(g.target, vars)) { + throw new Unsupported("comprehension target"); + } + } + boolean[] ok = {true}; + Infer.children(c, x -> ok[0] &= compBody(x)); + if (!ok[0]) { + throw new Unsupported("comprehension body"); + } + StringBuilder p = pre; + int ind = preInd; + Scope outer = sc; + String kind = c.kind == Comp.Kind.SET ? "PySet" : c.kind == Comp.Kind.DICT ? "PyDict" : "PyList"; + String r = exprTemp(kind); + for (Map.Entry v : vars.entrySet()) { + Ty vt = compTy(c.scope, v.getKey()); + v.setValue(exprTemp(vt.wide() ? "Object" : jt(vt))); + if (vt.k == Ty.K.INST && in.guessedCompVar(c.scope, v.getKey())) { + compOver.put(v.getValue(), exprTemp("Object")); + } else { + // Temporaries are numbered per function: an entry of an + // earlier one's comprehension names another variable here. + compOver.remove(v.getValue()); + } + } + forgetPaths(); + compVars.put(c.scope, vars); + try { + String[] first = compHead(c.generators.get(0)); + pre = null; + sc = c.scope; + indent(p, ind); + p.append(r).append(" = new ").append(kind).append("();\n"); + int d = ind; + for (int i = 0; i < c.generators.size(); i++) { + Comprehension g = c.generators.get(i); + String[] h = i == 0 ? first : compHead(g); + indent(p, d); + p.append("{\n"); + indent(p, d + 1); + p.append(h[0]); + indent(p, d + 1); + p.append(h[1]); + d += 2; + compStore(g, h[2], p, d); + for (Expr f : g.ifs) { + indent(p, d); + p.append("if (!(").append(testExpr(f)).append(")) {\n"); + indent(p, d + 1); + p.append("continue;\n"); + indent(p, d); + p.append("}\n"); + } + } + indent(p, d); + if (c.kind == Comp.Kind.DICT) { + String k = box(expr(c.elt)); + p.append(r).append(".setItem(").append(k).append(", ").append(box(expr(c.value))).append(");\n"); + } else { + p.append(r).append(c.kind == Comp.Kind.SET ? ".addItem(" : ".append(").append(box(expr(c.elt))) + .append(");\n"); + } + for (int i = c.generators.size() - 1; i >= 0; i--) { + d -= 2; + indent(p, d + 1); + p.append("}\n"); + indent(p, d); + p.append("}\n"); + } + } finally { + sc = outer; + pre = p; + compVars.remove(c.scope); + nonNull.removeAll(vars.keySet()); + shadow.keySet().removeAll(vars.keySet()); + } + forgetPaths(); + return new E(r, c.kind == Comp.Kind.LIST ? in.type(c, cur, sc) : Ty.OBJECT); + } + + /// `any(e for x in xs if c)` and `all(...)`: the loop run ahead of the + /// statement, as [#comp] runs one, leaving at the first item that + /// decides -- bs4's SoupStrainer made and stepped a generator object for + /// `any(x.exclude_everything for x in self.string_rules)` on every + /// call. When the name no longer holds the builtin, the generic call + /// runs instead. Null where the loop cannot be lowered. + private E anyAll(Call call, String fn) { + Comp c = (Comp) call.args.get(0); + if (pre == null || condDepth != 0 || curStmt == null || c.scope == null || !inertBefore(curStmt, c)) { + return null; + } + Map vars = new HashMap(); + for (Comprehension g : c.generators) { + if (g.isAsync || !compTargets(g.target, vars)) { + return null; + } + } + boolean[] ok = {true}; + Infer.children(c, x -> ok[0] &= compBody(x)); + if (!ok[0]) { + return null; + } + String gen = genericFallback(call); + if (gen == null) { + return null; + } + boolean any = "any".equals(fn); + StringBuilder p = pre; + int ind = preInd; + Scope outer = sc; + String r = exprTemp("boolean"); + String label = fresh(); + Map saved = new HashMap(vars); + for (Map.Entry v : vars.entrySet()) { + Ty vt = compTy(c.scope, v.getKey()); + v.setValue(exprTemp(vt.wide() ? "Object" : jt(vt))); + if (vt.k == Ty.K.INST && in.guessedCompVar(c.scope, v.getKey())) { + compOver.put(v.getValue(), exprTemp("Object")); + } else { + // Temporaries are numbered per function: an entry of an + // earlier one's comprehension names another variable here. + compOver.remove(v.getValue()); + } + } + forgetPaths(); + compVars.put(c.scope, vars); + try { + indent(p, ind); + p.append("if (").append(em.builtinRef(fn)).append(" == Builtins.").append(any ? "ANY" : "ALL").append(") {\n"); + indent(p, ind + 1); + p.append(r).append(" = ").append(!any).append(";\n"); + indent(p, ind + 1); + p.append(label).append(": {\n"); + String[] first = compHead(c.generators.get(0)); + pre = null; + sc = c.scope; + int d = ind + 2; + for (int i = 0; i < c.generators.size(); i++) { + Comprehension g = c.generators.get(i); + String[] h = i == 0 ? first : compHead(g); + indent(p, d); + p.append("{\n"); + indent(p, d + 1); + p.append(h[0]); + indent(p, d + 1); + p.append(h[1]); + d += 2; + compStore(g, h[2], p, d); + for (Expr f : g.ifs) { + indent(p, d); + p.append("if (!(").append(testExpr(f)).append(")) {\n"); + indent(p, d + 1); + p.append("continue;\n"); + indent(p, d); + p.append("}\n"); + } + } + indent(p, d); + p.append("if (").append(any ? "" : "!").append('(').append(testExpr(c.elt)).append(")) {\n"); + indent(p, d + 1); + p.append(r).append(" = ").append(any).append(";\n"); + indent(p, d + 1); + p.append("break ").append(label).append(";\n"); + indent(p, d); + p.append("}\n"); + for (int i = c.generators.size() - 1; i >= 0; i--) { + d -= 2; + indent(p, d + 1); + p.append("}\n"); + indent(p, d); + p.append("}\n"); + } + indent(p, ind + 1); + p.append("}\n"); + indent(p, ind); + p.append("} else {\n"); + indent(p, ind + 1); + p.append(r).append(" = Py.isTrue(").append(gen).append(");\n"); + indent(p, ind); + p.append("}\n"); + } finally { + sc = outer; + pre = p; + compVars.remove(c.scope); + nonNull.removeAll(saved.keySet()); + shadow.keySet().removeAll(saved.keySet()); + } + forgetPaths(); + return new E(r, Ty.BOOL); + } + + /// What a loop over `iter` into `target` iterates: `x.items()` into two + /// names walks the pairs (see Emitter.itemPairs). + private E loopSource(Expr iter, Expr target) { + Expr recv = Emitter.itemPairs(iter, target); + return recv != null ? new E("ItemWalk.of(" + box(expr(recv)) + ")", Ty.OBJECT) : expr(iter); + } + + /// The loop over one `for` clause of a comprehension: the statement + /// evaluating what it iterates, the loop header, and the item (boxed). + /// A `range` counts in a long and a list is indexed, as `for` does. + private String[] compHead(Comprehension g) { + if (in.rangeCall(g.iter, sc) && ((Call) g.iter).args.size() <= 2) { + List a = ((Call) g.iter).args; + String start = a.size() == 1 ? "0L" : bound(expr(a.get(0))); + String stop = bound(expr(a.get(a.size() - 1))); + String s0 = fresh(); + String e = fresh(); + String i = fresh(); + return new String[] {"long " + s0 + " = " + start + ", " + e + " = " + stop + ";\n", + "for (long " + i + " = " + s0 + "; " + i + " < " + e + "; " + i + "++) {\n", + "Long.valueOf(" + i + ")"}; + } + E it = loopSource(g.iter, g.target); + if (it.t.k == Ty.K.LIST && !it.t.opt) { + String l = fresh(); + String k = fresh(); + return new String[] {"PyList " + l + " = Typed.iterable(" + listOf(it) + ");\n", + "for (int " + k + " = 0; " + k + " < " + l + ".size(); " + k + "++) {\n", + l + ".get(" + k + ")"}; + } + String itr = fresh(); + String x = fresh(); + return new String[] {"final PyObject " + itr + " = Py.iter(" + box(it) + ");\n", + "for (Object " + x + "; (" + x + " = " + itr + ".next()) != null;) {\n", x}; + } + + /// Records the names a comprehension target binds; false when it binds + /// anything but names, or a name the function has as a local. + private boolean compTargets(Expr t, Map vars) { + if (t instanceof Name) { + String n = ((Name) t).id; + if (compVar(n) != null) { + return false; + } + vars.put(n, null); + return true; + } + if (t instanceof TupleExpr || t instanceof ListExpr) { + for (Expr e : t instanceof TupleExpr ? ((TupleExpr) t).elts : ((ListExpr) t).elts) { + if (!compTargets(e, vars)) { + return false; + } + } + return true; + } + return false; + } + + /// Whether a comprehension's body can be lowered in line: nothing in it + /// opens a scope that would capture its targets, or binds outside it. + private static boolean compBody(Object o) { + if (o instanceof NamedExpr || o instanceof Lambda || o instanceof Yield || o instanceof Await + || o instanceof Comp && ((Comp) o).kind == Comp.Kind.GENERATOR) { + return false; + } + boolean[] ok = {true}; + Infer.children(o, x -> ok[0] &= compBody(x)); + return ok[0]; + } + + /// Whether everything `s` evaluates before `target` is inert: running + /// the comprehension first cannot change what it reads. Only straight + /// line evaluation is walked; a comprehension under a branch of `and`, + /// `or` or `if` is never reached, so never hoisted. + private boolean inertBefore(Object s, Object target) { + return inertWalk(s, target) == 1; + } + + /// 1 found the target with only inert nodes before it, 0 walked `o` + /// without finding it and it was inert, -1 gave up. + private int inertWalk(Object o, Object target) { + if (o == target) { //NOPMD CompareObjectsWithEquals - identity is meant + return 1; + } + List kids = new ArrayList(); + if (o instanceof ExprStmt) { + kids.add(((ExprStmt) o).value); + } else if (o instanceof Return) { + if (((Return) o).value != null) { + kids.add(((Return) o).value); + } + } else if (o instanceof Assign) { + kids.add(((Assign) o).value); + } else if (o instanceof AugAssign) { + if (!(((AugAssign) o).target instanceof Name)) { + return -1; + } + kids.add(((AugAssign) o).value); + } else if (o instanceof If) { + kids.add(((If) o).test); + } else if (o instanceof Call) { + Call c = (Call) o; + if (c.func instanceof Attribute) { + kids.add(((Attribute) c.func).value); + } else { + kids.add(c.func); + } + kids.addAll(c.args); + for (Keyword k : c.keywords) { + kids.add(k.value); + } + } else if (o instanceof TupleExpr) { + kids.addAll(((TupleExpr) o).elts); + } else if (o instanceof ListExpr) { + kids.addAll(((ListExpr) o).elts); + } else if (o instanceof BinOp) { + kids.add(((BinOp) o).left); + kids.add(((BinOp) o).right); + } else if (o instanceof Name) { + Scope.Binding b = binding(((Name) o).id); + return b == Scope.Binding.LOCAL || b == Scope.Binding.CELL || b == Scope.Binding.BUILTIN ? 0 : -1; + } else if (o instanceof Constant) { + return 0; + } else { + return -1; + } + for (Object k : kids) { + int r = inertWalk(k, target); + if (r != 0) { + return r; + } + } + // A call or an operator finished before the target ran user code. + return o instanceof Call || o instanceof BinOp ? -1 : 0; + } + private void store(Expr t, E v, StringBuilder b, int ind) { + if (t instanceof Name && trueCell(((Name) t).id)) { + indent(b, ind); + b.append(cellRef(((Name) t).id)).append(" = ").append(box(v)).append(";\n"); + return; + } if (t instanceof Name) { String n = ((Name) t).id; - switch (sc.resolve(n)) { + switch (binding(n)) { case LOCAL: + if (compVar(n) == null) { + paramAlias.remove(n); + } indent(b, ind); - if (longLocals.contains(n)) { + // A comprehension target is a variable of its own: what + // the function's local of that name is proved to hold + // says nothing of it. + boolean own = compVar(n) == null; + if (own && longLocals.contains(n)) { // The analysis proved every value it holds fits. b.append(var(n)).append(" = ").append(fitting(v)) .append(";\n"); return; } - if (localType(n).k == Ty.K.INT) { + if (localType(n).k == Ty.K.INT || own && accLocals.contains(n)) { storePair(var(n), big(n), v, b, ind); + } else if (guessLocal(n)) { + storeGuess(var(n), over(n), localType(n), v, b, ind); } else { b.append(var(n)).append(" = ").append(conv(v, localType(n))).append(";\n"); } + if (own && flatStr.contains(n)) { + indent(b, ind); + b.append("sp").append(var(n)).append(" = -1;\n"); + } forgetPathsOf(n); shadow.remove(n); if (v.t.k == localType(n).k && !v.t.opt && v.t.k != Ty.K.NONE) { @@ -1565,6 +3794,21 @@ private void store(Expr t, E v, StringBuilder b, int ind) { if (t instanceof Attribute) { Attribute a = (Attribute) t; E r = expr(a.value); + if (!fieldStore(r, a.attr)) { + // Not a field this build keeps in a Java field: the generic + // store, rather than giving up the whole typed function. + if (!plain(v.c) && !plain(r.c)) { + // Python evaluates the value before the receiver. + String tv = fresh(); + indent(b, ind); + b.append(jt(v.t)).append(' ').append(tv).append(" = ").append(v.c).append(";\n"); + v = new E(tv, v.t); + } + indent(b, ind); + b.append(em.guardedSet(a.attr, "(Object) " + box(r), box(v))).append('\n'); + forgetAttr(a.attr); + return; + } if (fieldTy(r, a.attr).k == Ty.K.INT && typedField(owner(r, a.attr), a.attr) != null) { if (!plain(r.c) && !(v.ll != null || v.lc != null && plain(v.lc) || plain(v.c))) { // Python evaluates the value before the receiver. @@ -1583,6 +3827,12 @@ private void store(Expr t, E v, StringBuilder b, int ind) { forgetAttr(a.attr); return; } + if (guardedField(owner(r, a.attr), a.attr)) { + indent(b, ind); + storeGuardedField(r, a.attr, v, b, ind); + forgetAttr(a.attr); + return; + } if (!plain(v.c) && !plain(r.c)) { // Python evaluates the value before the receiver. String tv = fresh(); @@ -1602,13 +3852,14 @@ private void store(Expr t, E v, StringBuilder b, int ind) { if (t instanceof Subscript) { Subscript s = (Subscript) t; if (s.index instanceof Slice) { - E l = expr(s.value); - if (l.t.k != Ty.K.LIST) { - throw new Unsupported("slice store on " + l.t); + if (!plain(v.c)) { + // Python evaluates the value before the target. + v = spillTo(v, b, ind); } + E l = expr(s.value); String p = sliceParts((Slice) s.index); indent(b, ind); - b.append("Py.setslice(").append(l.c).append(", ").append(p).append(", ").append(box(v)).append(");\n"); + b.append("Py.setslice(").append(box(l)).append(", ").append(p).append(", ").append(box(v)).append(");\n"); return; } E l = expr(s.value); @@ -1669,15 +3920,59 @@ private void store(Expr t, E v, StringBuilder b, int ind) { b.append(el.k == Ty.K.FLOAT ? "h_setF(" : "h_set(").append(l.c).append(", ").append(box(i)) .append(", ").append(el.k == Ty.K.FLOAT ? conv(v, el) : box(v)).append(");\n"); indent(b, ind); - b.append("}\n"); + b.append("}\n"); + return; + } + if (el.k == Ty.K.FLOAT) { + b.append("h_setF(").append(l.c).append(", ").append(box(i)).append(", ").append(conv(v, el)) + .append(");\n"); + } else { + b.append("h_set(").append(l.c).append(", ").append(box(i)).append(", ").append(box(v)) + .append(");\n"); + } + return; + } + if (t instanceof TupleExpr || t instanceof ListExpr) { + // Unpacking anything but a literal of the same length: the + // generic helpers, each element then stored as the target + // wants it (Infer types them as dynamic, or as the list's + // elements). + List elts = t instanceof TupleExpr ? ((TupleExpr) t).elts : ((ListExpr) t).elts; + int star = -1; + for (int i = 0; i < elts.size(); i++) { + if (elts.get(i) instanceof Starred) { + if (star >= 0) { + throw new Unsupported("two starred targets"); + } + star = i; + } + } + String arr = fresh(); + if (star < 0) { + // A fixed-size tuple is read in place: the runtime answers + // an empty array for one and no array is made. + String held = fresh(); + indent(b, ind); + b.append("final Object ").append(held).append(" = ").append(box(v)).append(";\n"); + indent(b, ind); + b.append("final Object[] ").append(arr).append(" = ") + .append(Emitter.onlyNames(t) ? "Py.unpackNamesT(" : "Py.unpackT(").append(held).append(", ") + .append(elts.size()).append(");\n"); + for (int i = 0; i < elts.size(); i++) { + store(elts.get(i), new E("(" + arr + ".length != 0 ? " + arr + "[" + i + "] : ((PyTuple) " + held + + ").get(" + i + "))", Ty.OBJECT), b, ind); + } return; } - if (el.k == Ty.K.FLOAT) { - b.append("h_setF(").append(l.c).append(", ").append(box(i)).append(", ").append(conv(v, el)) - .append(");\n"); - } else { - b.append("h_set(").append(l.c).append(", ").append(box(i)).append(", ").append(box(v)) - .append(");\n"); + indent(b, ind); + b.append("final Object[] ").append(arr).append(" = "); + { + b.append("Py.unpackStar(").append(box(v)).append(", ").append(star).append(", ") + .append(elts.size() - star - 1).append(");\n"); + } + for (int i = 0; i < elts.size(); i++) { + Expr e = elts.get(i); + store(e instanceof Starred ? ((Starred) e).value : e, new E(arr + "[" + i + "]", Ty.OBJECT), b, ind); } return; } @@ -1732,19 +4027,112 @@ private E top(Expr e) { } } + /// The untyped locals of `f` worth holding as a long and an object: a + /// `+=` or `-=` targets them, and nothing deletes them. + private Set accumulators(Infer.Fn f) { + Set targets = new HashSet(); + Infer.Visit[] v = new Infer.Visit[1]; + v[0] = x -> { + if (x instanceof AugAssign && ((AugAssign) x).target instanceof Name + && ("+".equals(((AugAssign) x).op) || "-".equals(((AugAssign) x).op))) { + targets.add(((Name) ((AugAssign) x).target).id); + } + if (!(x instanceof FunctionDef || x instanceof Lambda || x instanceof ClassDef || x instanceof Comp)) { + Infer.children(x, v[0]); + } + }; + for (Stmt st : f.def.body) { + v[0].on(st); + } + Set out = new HashSet(); + for (String n : targets) { + Ty t = f.locals.get(n); + if (t != null && t.wide() && !sc.params.contains(n) && !longLocals.contains(n) + && !sc.deleted.contains(n) && sc.resolve(n) == Scope.Binding.LOCAL) { + out.add(n); + } + } + return out; + } + + /// `n += v` (or `-=`) on an accumulator: the long sum while both are + /// ints and it fits, Python's in-place operator on the boxed value + /// otherwise. + private void accumulate(String n, String op, E v, StringBuilder b, int ind) { + String lv = var(n); + String ob = big(n); + String slow = "Py." + ("+".equals(op) ? "iadd" : "isub") + "(" + ob + " == null ? (Object) Long.valueOf(" + lv + + ") : " + ob + ", "; + String r = fresh(); + String s = fresh(); + indent(b, ind); + String over = "+".equals(op) ? "((" + lv + " ^ " + s + ") & (" + r + " ^ " + s + ")) < 0" + : "((" + lv + " ^ " + r + ") & (" + lv + " ^ " + s + ")) < 0"; + if (v.t.k == Ty.K.INT && !v.t.opt && v.lc != null && v.pk == null) { + b.append("long ").append(r).append(" = ").append(v.lc).append(";\n"); + indent(b, ind); + b.append("long ").append(s).append(" = ").append(lv).append(' ').append(op).append(' ').append(r).append(";\n"); + indent(b, ind); + b.append("if (").append(ob).append(" == null && !(").append(over).append(")) {\n"); + indent(b, ind + 1); + b.append(lv).append(" = ").append(s).append(";\n"); + indent(b, ind); + b.append("} else {\n"); + indent(b, ind + 1); + storePair(lv, ob, new E(slow + "Long.valueOf(" + r + "))", Ty.OBJECT), b, ind + 1); + indent(b, ind); + b.append("}\n"); + return; + } + String x = fresh(); + b.append("Object ").append(x).append(" = ").append(box(v)).append(";\n"); + indent(b, ind); + b.append("if (").append(ob).append(" == null && ").append(x).append(" instanceof Long) {\n"); + indent(b, ind + 1); + b.append("long ").append(r).append(" = ((Long) ").append(x).append(").longValue();\n"); + indent(b, ind + 1); + b.append("long ").append(s).append(" = ").append(lv).append(' ').append(op).append(' ').append(r).append(";\n"); + indent(b, ind + 1); + b.append("if (!(").append(over).append(")) {\n"); + indent(b, ind + 2); + b.append(lv).append(" = ").append(s).append(";\n"); + indent(b, ind + 2); + b.append(x).append(" = null;\n"); + indent(b, ind + 1); + b.append("}\n"); + indent(b, ind); + b.append("}\n"); + indent(b, ind); + b.append("if (").append(x).append(" != null) {\n"); + indent(b, ind + 1); + storePair(lv, ob, new E(slow + x + ")", Ty.OBJECT), b, ind + 1); + indent(b, ind); + b.append("}\n"); + } + private void augAssign(AugAssign a, StringBuilder b, int ind) { Expr t = a.target; + if (t instanceof Name && accLocals.contains(((Name) t).id) && ("+".equals(a.op) || "-".equals(a.op))) { + if (unboundInts.contains(((Name) t).id)) { + // `x += v` reads x before it evaluates v. + indent(b, ind); + b.append("Typed.boundInt(").append(big(((Name) t).id)).append(", ") + .append(Emitter.javaString(((Name) t).id)).append(");\n"); + } + accumulate(((Name) t).id, a.op, expr(a.value), b, ind); + return; + } if (t instanceof Name && longLocals.contains(((Name) t).id)) { store(t, top(new BinOp(t, a.op, a.value)), b, ind); return; } if (t instanceof Name && (localType(((Name) t).id).k == Ty.K.INT || localType(((Name) t).id).k == Ty.K.FLOAT) - && sc.resolve(((Name) t).id) == Scope.Binding.LOCAL) { + && binding(((Name) t).id) == Scope.Binding.LOCAL) { store(t, top(new BinOp(t, a.op, a.value)), b, ind); return; } if (t instanceof Attribute && ((Attribute) t).value instanceof Name - && sc.resolve(((Name) ((Attribute) t).value).id) == Scope.Binding.LOCAL) { + && binding(((Name) ((Attribute) t).value).id) == Scope.Binding.LOCAL) { // The receiver is a local: reading it again is reading it once. E r0 = expr(((Attribute) t).value); if (r0.t.k == Ty.K.INST && fieldTy(r0, ((Attribute) t).attr).k == Ty.K.INT @@ -1755,6 +4143,12 @@ && typedField(owner(r0, ((Attribute) t).attr), ((Attribute) t).attr) != null) { } if (t instanceof Name) { E cur0 = expr(t); + if (cur0.t.k == Ty.K.LIST && !cur0.t.opt && "+".equals(a.op)) { + // list += extends in place, so an alias sees the new items; + // Py.iadd answers the same PyList it was given. + store(t, new E("((PyList) Py.iadd(" + cur0.c + ", " + box(expr(a.value)) + "))", cur0.t), b, ind); + return; + } E r = binop(a.op, cur0, expr(a.value), a.value); store(t, r, b, ind); return; @@ -1769,12 +4163,25 @@ && typedField(owner(r0, ((Attribute) t).attr), ((Attribute) t).attr) != null) { b.append(jt(r.t)).append(' ').append(rv).append(" = ").append(r.c).append(";\n"); } E recv = new E(rv, r.t); + if (!fieldStore(recv, at.attr)) { + // The generic read, operation and store, the receiver once. + E old = new E(attrGet(recv, at.attr), Ty.OBJECT); + E v = binop(a.op, old, expr(a.value), a.value); + indent(b, ind); + b.append(em.guardedSet(at.attr, "(Object) " + box(recv), box(v))).append('\n'); + forgetAttr(at.attr); + return; + } if (fieldTy(recv, at.attr).k == Ty.K.INT && typedField(owner(recv, at.attr), at.attr) != null) { E v = binop(a.op, intField(recv, at.attr), expr(a.value), a.value); indent(b, ind); storeIntField(recv, at.attr, v, b, ind); return; } + if (guardedField(owner(recv, at.attr), at.attr)) { + augGuarded(recv, at.attr, a, b, ind); + return; + } String ref = fieldRef(recv, at.attr); E old = new E(ref, fieldTy(recv, at.attr)); E v = binop(a.op, old, expr(a.value), a.value); @@ -1787,8 +4194,54 @@ && typedField(owner(r0, ((Attribute) t).attr), ((Attribute) t).attr) != null) { Subscript s = (Subscript) t; E l = expr(s.value); E i = expr(s.index); + if (l.t.k == Ty.K.DICT) { + // Python's order: the dict, the key, the read, the operand, + // the store; the dict and the key are each evaluated once. + String dv = fresh(); + String kv = fresh(); + indent(b, ind); + b.append("Object ").append(dv).append(" = ").append(l.c).append(";\n"); + indent(b, ind); + b.append("Object ").append(kv).append(" = ").append(box(i)).append(";\n"); + E old = dictRead("Typed.dgetv(" + dv + ", " + kv + ")", l.t); + String ov = fresh(); + indent(b, ind); + b.append(jt(old.t)).append(' ').append(ov).append(" = ").append(old.c).append(";\n"); + E v; + if (old.t.opt || old.t.k != Ty.K.INT && old.t.k != Ty.K.FLOAT && old.t.k != Ty.K.STR + && old.t.k != Ty.K.BOOL) { + if (Emitter.BIN.get(a.op) == null) { + throw new Unsupported("subscript aug " + a.op); + } + // A mutable item may update in place (a list extends). + v = new E("Py.i" + Emitter.BIN.get(a.op) + "(" + box(new E(ov, old.t)) + ", " + + box(expr(a.value)) + ")", Ty.OBJECT); + } else { + v = binop(a.op, new E(ov, old.t), expr(a.value), a.value); + } + indent(b, ind); + b.append("Py.setitem(").append(dv).append(", ").append(kv).append(", ").append(box(v)).append(");\n"); + return; + } if (l.t.k != Ty.K.LIST || !(i.t.k == Ty.K.INT || i.t.k == Ty.K.BOOL)) { - throw new Unsupported("subscript aug on " + l.t); + // Any other container: the generic protocol, in Python's order. + if (Emitter.BIN.get(a.op) == null) { + throw new Unsupported("subscript aug " + a.op); + } + String dv = fresh(); + String kv = fresh(); + String ov = fresh(); + indent(b, ind); + b.append("Object ").append(dv).append(" = ").append(box(l)).append(";\n"); + indent(b, ind); + b.append("Object ").append(kv).append(" = ").append(box(i)).append(";\n"); + indent(b, ind); + b.append("Object ").append(ov).append(" = Py.getitem(").append(dv).append(", ").append(kv).append(");\n"); + // The in-place protocol: a list item extends where it is. + E v = new E("Py.i" + Emitter.BIN.get(a.op) + "(" + ov + ", " + box(expr(a.value)) + ")", Ty.OBJECT); + indent(b, ind); + b.append("Py.setitem(").append(dv).append(", ").append(kv).append(", ").append(v.c).append(");\n"); + return; } Ty el0 = in.elem(l.t); if (el0.k == Ty.K.FLOAT && i.lc != null && plain(l.c) && !hasCall(a.value)) { @@ -1826,6 +4279,10 @@ && typedField(owner(r0, ((Attribute) t).attr), ((Attribute) t).attr) != null) { indent(b, ind); b.append("Object ").append(iv).append(" = ").append(box(i)).append(";\n"); Ty el = in.elem(l.t); + boolean ge = el.k != Ty.K.INT && in.guessedSite(l.t); + if (ge) { + el = Ty.OBJECT; + } E old = el.k == Ty.K.FLOAT ? new E("h_getF(" + lv + ", " + iv + ")", el) : new E(unbox("h_get(" + lv + ", " + iv + ")", el), el); E v = binop(a.op, old, expr(a.value), a.value); @@ -1886,7 +4343,8 @@ private Set whenFalse(Expr test) { /// `x.attr` of a local `x`, the key narrowing keeps for that field. private String path(Attribute a) { - if (a.value instanceof Name && sc.resolve(((Name) a.value).id) == Scope.Binding.LOCAL) { + if (a.value instanceof Name && binding(((Name) a.value).id) == Scope.Binding.LOCAL + && compVar(((Name) a.value).id) == null) { return ((Name) a.value).id + "." + a.attr; } return null; @@ -1911,6 +4369,156 @@ private static boolean sliceOf(Expr e) { } /// The three parts of a slice, boxed, `Py.NONE` for a missing one. + /// `s[a:b]` with no step and int bounds, the bounds passed as Java + /// longs (each beside the object that replaces it when it is a big int + /// or a bool, see `dual`); or null when a bound is anything else. + private String strSliceLong(E l, Slice sl) { + if (sl.step != null) { + return null; + } + String[] lo = sl.lower == null ? new String[] {"0L", "null"} : longPair(expr(sl.lower)); + String[] hi = sl.upper == null ? new String[] {"Long.MAX_VALUE", "null"} : longPair(expr(sl.upper)); + if (lo.length == 0 || hi.length == 0) { + return null; + } + return "Typed.sliceL(" + l.c + ", " + lo[0] + ", " + lo[1] + ", " + hi[0] + ", " + hi[1] + ")"; + } + + private static final String[] NO_PAIR = new String[0]; + + /// A list read through a call (a module global's `Typed.asList(g(5))`) + /// held in a local before the statement, where the statement cannot + /// rebind it, so the fast index and length paths can name it twice. + private E heldList(E l) { + if (plain(l.c) || pre == null || !stmtPure || condDepth != 0) { + return l; + } + String t = fresh(); + indent(pre, preInd); + pre.append("final PyList ").append(t).append(" = ").append(l.c).append(";\n"); + return new E(t, l.t); + } + + /// `x % k` for an int `x` held as a long and a constant `k` of 31 bits + /// above zero: Python's remainder, never an overflow, and an int. + private E modConstant(BinOp b) { + Long k = intConstant(b.right); + Ty lt = in.type(b.left, cur, sc); + if (lt == null || lt.opt || lt.k != Ty.K.INT) { + return null; + } + if (k == null || k <= 0 || k > Integer.MAX_VALUE) { + // `x % y` of two ints held as longs: the remainder is smaller + // than `y`, so it is a long too; a zero `y` raises. + Ty rt = in.type(b.right, cur, sc); + if (k != null || rt == null || rt.opt || rt.k != Ty.K.INT) { + return null; + } + E l = expr(b.left); + E r = expr(b.right); + if (l.lc == null || l.pk != null || r.lc == null || r.pk != null || l.t.k != Ty.K.INT || r.t.k != Ty.K.INT + || l.t.opt || r.t.opt) { + return binop("%", l, r, b.right); + } + String lc = "Typed.lmod(" + l.lc + ", " + r.lc + ")"; + E m = new E("Long.valueOf(" + lc + ")", Ty.INT, lc); + m.small = r.small; + return m; + } + E l = expr(b.left); + if (l.lc == null || l.pk != null || l.t.k != Ty.K.INT || l.t.opt) { + return binop("%", l, constE(k), b.right); + } + String lc = "Typed.imod(" + l.lc + ", " + k + "L)"; + E r = new E("Long.valueOf(" + lc + ")", Ty.INT, lc); + r.small = true; + return r; + } + + /// `"| %s | %d |" % (s, n)` with every value typed: a str for `%s`, an + /// int held as a long for `%d`, `%i` or `%s`. One Java concatenation, + /// with no tuple, no boxed int and no conversion dispatch; the values + /// are evaluated left to right, as CPython builds the tuple. Null when + /// any value is of another type, so `Py.pct` or `Py.mod` takes it. + private E percentConcat(BinOp b) { + if (!"%".equals(b.op) || !(b.left instanceof Constant)) { + return null; + } + List vals; + if (b.right instanceof TupleExpr) { + vals = ((TupleExpr) b.right).elts; + } else { + Ty rt = in.type(b.right, cur, sc); + if (rt == null || rt.opt || rt.k != Ty.K.STR && rt.k != Ty.K.INT) { + return null; + } + vals = java.util.Collections.singletonList(b.right); + } + for (Expr v : vals) { + Ty vt = v instanceof Starred ? null : in.type(v, cur, sc); + if (vt == null || vt.opt || vt.k != Ty.K.STR && vt.k != Ty.K.INT) { + return null; + } + } + List lits = em.percentParts((Constant) b.left, vals.size()); + if (lits == null) { + return null; + } + String convs = lits.get(lits.size() - 1); + List parts = new ArrayList<>(); + for (int i = 0; i < vals.size(); i++) { + Object kv = inlineArgs == null ? fold(vals.get(i)) : null; + if (kv instanceof String && convs.charAt(i) == 's' || kv instanceof Long) { + // A folded value joins the literal text around it. + lits.set(i, lits.get(i) + kv + lits.get(i + 1)); + lits.remove(i + 1); + convs = convs.substring(0, i) + convs.substring(i + 1); + vals = new ArrayList(vals); + vals.remove(i); + i--; + continue; + } + E v = expr(vals.get(i)); + char k = convs.charAt(i); + if (v.t.k == Ty.K.STR && !v.t.opt && k == 's') { + parts.add(v.c); + } else if (v.t.k == Ty.K.INT && !v.t.opt && v.lc != null && v.pk == null) { + parts.add("Long.toString(" + v.lc + ")"); + } else { + parts.add("Py.pconv('" + k + "', " + box(v) + ")"); + } + } + StringBuilder sb = new StringBuilder("("); + boolean first = true; + for (int i = 0; i <= vals.size(); i++) { + String lit = lits.get(i); + if (!lit.isEmpty() || first && i == vals.size()) { + sb.append(first ? "" : " + ").append(Emitter.javaString(lit)); + first = false; + } + if (i < vals.size()) { + sb.append(first ? "\"\" + " : " + ").append(parts.get(i)); + first = false; + } + } + return new E(sb.append(')').toString(), Ty.STR); + } + + /// An int as a Java long and the object standing in for it (null when + /// the long is the value), both free of effects; or an empty array. + private static String[] longPair(E e) { + if (e.t.k != Ty.K.INT || e.t.opt || e.pk != null) { + return NO_PAIR; + } + if (e.ll != null && e.bg != null) { + return new String[] {e.ll, e.bg}; + } + if (e.lc != null && (plain(e.lc) || literal(e.lc) || e.small)) { + return new String[] {e.lc, "null"}; + } + return NO_PAIR; + } + private String sliceParts(Slice s) { Expr[] parts = {s.lower, s.upper, s.step}; StringBuilder sb = new StringBuilder(); @@ -1921,7 +4529,7 @@ private String sliceParts(Slice s) { } private boolean narrowable(String n) { - return sc.resolve(n) == Scope.Binding.LOCAL && localType(n).nullable(); + return binding(n) == Scope.Binding.LOCAL && localType(n).nullable(); } /// The local `x` of `x is None` / `x is not None`, or null. @@ -1936,10 +4544,357 @@ private String noneTest(Compare c) { if (c.left instanceof Name && narrowable(((Name) c.left).id)) { return ((Name) c.left).id; } - return c.left instanceof Attribute ? path((Attribute) c.left) : null; + return c.left instanceof Attribute ? path((Attribute) c.left) : null; + } + + /// Every local `body` may store into. + /// Per function: each local stored exactly once, by a plain `n = value`, + /// mapped to that value. A local whose one value folds to a constant + /// holds that constant wherever it is bound, in a loop or not. + private Map soleStores; + /// [#fold]'s answers, NO_FOLD for an expression that does not fold. + private Map folded; + private static final Object NO_FOLD = new Object(); + private final Set folding = new HashSet(); + + /// The typed locals `es` read, as the generic code reads them, or null + /// when one cannot be handed over (not bound on every path, or no + /// object value; a closure or `:=` among them). + private Map defNames(List es) { + Map names = new HashMap(); + boolean[] ok = {true}; + Infer.Visit[] v = new Infer.Visit[1]; + v[0] = x -> { + if (x instanceof NamedExpr || x instanceof Lambda || x instanceof Comp || x instanceof Yield + || x instanceof Await) { + ok[0] = false; + return; + } + if (x instanceof Name) { + Name n = (Name) x; + if (!trueCell(n.id) && binding(n.id) == Scope.Binding.LOCAL && !names.containsKey(n.id)) { + if (scalars.containsKey(n.id) || !sc.params.contains(n.id) && !da.safe.contains(n) + && !paramAlias.containsKey(n.id)) { + ok[0] = false; + return; + } + try { + names.put(n.id, "((Object) " + box(expr1(n)) + ")"); + } catch (Unsupported u) { + ok[0] = false; + } + } + } + Infer.children(x, v[0]); + }; + for (Expr e : es) { + v[0].on(e); + } + return ok[0] ? names : null; + } + + /// How many times each name is bound anywhere in `body`, nested scopes + /// included. + static Map storeCounts(List body) { + Map count = new HashMap(); + Map value = new HashMap(); + for (Stmt st : body) { + countStores(st, count, value); + } + return count; + } + + private static Map soleStores(List body) { + Map count = new HashMap(); + Map value = new HashMap(); + for (Stmt st : body) { + countStores(st, count, value); + } + Map r = new HashMap(); + for (Map.Entry en : value.entrySet()) { + if (count.get(en.getKey()) == 1) { + r.put(en.getKey(), en.getValue()); + } + } + return r; + } + + /// Every way a name is bound counts, in nested scopes too: a comprehension + /// variable or an inner function's local of the same name only makes the + /// local look stored twice, which costs a fold and never correctness. + private static void countStores(Object o, Map count, Map value) { + List ns = new ArrayList(); + if (o instanceof Assign) { + Assign a = (Assign) o; + for (Expr t : a.targets) { + names(t, ns); + } + if (a.targets.size() == 1 && a.targets.get(0) instanceof Name) { + value.put(((Name) a.targets.get(0)).id, a.value); + } + } else if (o instanceof AugAssign) { + names(((AugAssign) o).target, ns); + } else if (o instanceof AnnAssign) { + names(((AnnAssign) o).target, ns); + ns.add(ns.isEmpty() ? "" : ns.get(0)); + } else if (o instanceof For) { + names(((For) o).target, ns); + } else if (o instanceof NamedExpr) { + ns.add(((NamedExpr) o).target.id); + } else if (o instanceof Comprehension) { + names(((Comprehension) o).target, ns); + } else if (o instanceof WithItem && ((WithItem) o).vars != null) { + names(((WithItem) o).vars, ns); + } else if (o instanceof ExceptHandler && ((ExceptHandler) o).name != null) { + ns.add(((ExceptHandler) o).name); + } else if (o instanceof Delete) { + for (Expr t : ((Delete) o).targets) { + names(t, ns); + } + } else if (o instanceof Import || o instanceof ImportFrom) { + for (Alias al : o instanceof Import ? ((Import) o).names : ((ImportFrom) o).names) { + ns.add(al.asname != null ? al.asname : al.name); + } + } else if (o instanceof Global) { + for (String n : ((Global) o).names) { + ns.add(n); + ns.add(n); + } + } else if (o instanceof FunctionDef) { + ns.add(((FunctionDef) o).name); + } else if (o instanceof ClassDef) { + ns.add(((ClassDef) o).name); + } + for (String n : ns) { + Integer c = count.get(n); + count.put(n, c == null ? 1 : c + 1); + } + Infer.children(o, x -> countStores(x, count, value)); + } + + /// `e` as a constant computed here, when it is a pure function of + /// literals and of locals whose one store folds: a str, a Long or a + /// Boolean; or null. Strings fold only while ASCII, where Java's + /// `trim`-free scans, `indexOf` and case maps answer what CPython does. + private Object fold(Expr e) { + Object m = folded.get(e); + if (m != null) { + return m == NO_FOLD ? null : m; //NOPMD CompareObjectsWithEquals - sentinel + } + Object r = fold0(e); + folded.put(e, r == null ? NO_FOLD : r); + return r; + } + + private Object fold0(Expr e) { + if (e instanceof Constant) { + Constant c = (Constant) e; + if (c.kind == Constant.Kind.STR) { + return ascii(c.text) ? c.text : null; + } + if (c.kind == Constant.Kind.INT && c.text.length() <= 9 && c.text.matches("[0-9]+")) { + return Long.valueOf(c.text); + } + if (c.kind == Constant.Kind.TRUE || c.kind == Constant.Kind.FALSE) { + return c.kind == Constant.Kind.TRUE; + } + return null; + } + if (e instanceof Name) { + Name n = (Name) e; + Expr v = soleStores.get(n.id); + if (v == null || !da.safe.contains(n) || binding(n.id) != Scope.Binding.LOCAL || !folding.add(n.id)) { + return null; + } + try { + return fold(v); + } finally { + folding.remove(n.id); + } + } + if (e instanceof UnaryOp && "-".equals(((UnaryOp) e).op)) { + Object v = fold(((UnaryOp) e).operand); + return v instanceof Long ? Long.valueOf(-(Long) v) : null; + } + if (e instanceof BinOp) { + BinOp b = (BinOp) e; + Object l = fold(b.left); + Object r = l == null ? null : fold(b.right); + if (l instanceof Long && r instanceof Long && small((Long) l) && small((Long) r)) { + long x = (Long) l; + long y = (Long) r; + switch (b.op) { + case "+": + return x + y; + case "-": + return x - y; + case "*": + return x * y; + default: + return null; + } + } + if (l instanceof String && r instanceof String && "+".equals(b.op) + && ((String) l).length() + ((String) r).length() <= 4096) { + return (String) l + r; + } + return null; + } + if (e instanceof Subscript && ((Subscript) e).index instanceof Slice) { + Slice sl = (Slice) ((Subscript) e).index; + Object v = fold(((Subscript) e).value); + if (!(v instanceof String) || sl.step != null) { + return null; + } + String str = (String) v; + Object lo = sl.lower == null ? Long.valueOf(0) : fold(sl.lower); + Object hi = sl.upper == null ? Long.valueOf(str.length()) : fold(sl.upper); + if (!(lo instanceof Long) || !(hi instanceof Long)) { + return null; + } + int n = str.length(); + long a = (Long) lo < 0 ? Math.max(0, (Long) lo + n) : Math.min((Long) lo, n); + long z = (Long) hi < 0 ? Math.max(0, (Long) hi + n) : Math.min((Long) hi, n); + return a >= z ? "" : str.substring((int) a, (int) z); + } + if (!(e instanceof Call) || !((Call) e).keywords.isEmpty()) { + return null; + } + Call c = (Call) e; + for (Expr a : c.args) { + if (a instanceof Starred) { + return null; + } + } + if (c.func instanceof Name && "len".equals(((Name) c.func).id) && c.args.size() == 1 + && binding("len") == Scope.Binding.BUILTIN) { + Object v = fold(c.args.get(0)); + return v instanceof String ? Long.valueOf(((String) v).length()) : null; + } + if (!(c.func instanceof Attribute)) { + return null; + } + Object recv = fold(((Attribute) c.func).value); + if (!(recv instanceof String)) { + return null; + } + String str = (String) recv; + List args = new ArrayList(); + for (Expr a : c.args) { + Object v = fold(a); + if (!(v instanceof String)) { + return null; + } + args.add(v); + } + String m = ((Attribute) c.func).attr; + int na = args.size(); + if (na == 0) { + switch (m) { + case "strip": + return stripAscii(str, true, true); + case "lstrip": + return stripAscii(str, true, false); + case "rstrip": + return stripAscii(str, false, true); + case "lower": + return asciiCase(str, false); + case "upper": + return asciiCase(str, true); + default: + return null; + } + } + String a0 = (String) args.get(0); + if (na == 1) { + switch (m) { + case "find": + return Long.valueOf(str.indexOf(a0)); + case "rfind": + return Long.valueOf(str.lastIndexOf(a0)); + case "startswith": + return str.startsWith(a0); + case "endswith": + return str.endsWith(a0); + case "count": + return a0.isEmpty() ? null : Long.valueOf(countOf(str, a0)); + default: + return null; + } + } + if (na == 2 && "replace".equals(m) && !a0.isEmpty()) { + String r = str.replace(a0, (String) args.get(1)); + return r.length() <= 4096 ? r : null; + } + return null; + } + + private static boolean small(long v) { + return v > -(1L << 30) && v < (1L << 30); + } + + private static boolean ascii(String s) { + for (int i = 0; i < s.length(); i++) { + if (s.charAt(i) >= 128) { + return false; + } + } + return true; + } + + /// CPython's whitespace among ASCII: space, tab to carriage return, and + /// the four separators 0x1c to 0x1f. + private static boolean pySpace(char ch) { + return ch == ' ' || ch >= '\t' && ch <= '\r' || ch >= 0x1c && ch <= 0x1f; + } + + private static String stripAscii(String s, boolean left, boolean right) { + int a = 0; + int z = s.length(); + while (left && a < z && pySpace(s.charAt(a))) { + a++; + } + while (right && z > a && pySpace(s.charAt(z - 1))) { + z--; + } + return s.substring(a, z); + } + + private static String asciiCase(String s, boolean up) { + char[] cs = s.toCharArray(); + for (int i = 0; i < cs.length; i++) { + char ch = cs[i]; + if (up && ch >= 'a' && ch <= 'z') { + cs[i] = (char) (ch - 32); + } else if (!up && ch >= 'A' && ch <= 'Z') { + cs[i] = (char) (ch + 32); + } + } + return new String(cs); + } + + private static int countOf(String s, String sub) { + int n = 0; + for (int i = s.indexOf(sub); i >= 0; i = s.indexOf(sub, i + sub.length())) { + n++; + } + return n; + } + + /// A folded constant as an expression of its type. + private static E constE(Object k) { + if (k instanceof String) { + return new E(Emitter.javaString((String) k), Ty.STR); + } + if (k instanceof Boolean) { + return new E(((Boolean) k) ? "true" : "false", Ty.BOOL); + } + long v = (Long) k; + E r = new E("Long.valueOf(" + v + "L)", Ty.INT, v + "L"); + r.small = v >= Integer.MIN_VALUE && v <= Integer.MAX_VALUE; + return r; } - /// Every local `body` may store into. static Set assigned(List body) { List out = new ArrayList(); for (Stmt s : body) { @@ -2011,6 +4966,15 @@ private String nz(E r, String attr) { return "Typed.nz(" + r.c + ", " + Emitter.javaString(attr) + ")"; } + /// Whether a store of `attr` on `r` can go straight to its Java field. + private boolean fieldStore(E r, String attr) { + if (r.t.k != Ty.K.INST || r.t.cls.frozenStores()) { + return false; + } + Layouts.Cls o = Infer.fieldOwner(r.t.cls, attr); + return o != null && (typedField(o, attr) != null || in.definitelySet(o, attr)); + } + /// The Java lvalue of field `attr` of `r`. private String fieldRef(E r, String attr) { Layouts.Cls o = owner(r, attr); @@ -2024,6 +4988,11 @@ private String fieldRef(E r, String attr) { return recv + ".f_" + Emitter.mangle(attr); } + /// A Java identifier for a class `ref` (`py_mod.L1_K`), to name a helper. + private static String boxerId(String ref) { + return ref.replace('.', '_'); + } + /// Reads of typed int fields through a helper, where the receiver is /// an expression that may not be evaluated twice nor moved. private final Set fieldBoxers = new TreeSet(); @@ -2037,14 +5006,57 @@ private E intField(E r, String attr) { if (!plain(recv) && pre != null && stmtPure && condDepth == 0) { String t = fresh(); indent(pre, preInd); - pre.append(o.javaName).append(' ').append(t).append(" = ").append(recv).append(";\n"); + pre.append(o.ref).append(' ').append(t).append(" = ").append(recv).append(";\n"); recv = t; } if (plain(recv)) { return dual(recv + ".t_" + m, recv + ".b_" + m); } - fieldBoxers.add(o.javaName + " " + m); - return new E("fb_" + o.javaName + "_" + m + "(" + recv + ")", Ty.INT); + fieldBoxers.add(o.ref + " " + m); + return new E("fb_" + boxerId(o.ref) + "_" + m + "(" + recv + ")", Ty.INT); + } + + /// `recv.attr op= value` on guarded field `attr` of `recv` (a plain + /// name): the typed operation while the field holds its typed value, + /// the generic one when it holds the object that replaced it. + private void augGuarded(E recv, String attr, AugAssign a, StringBuilder b, int ind) { + Layouts.Cls o = owner(recv, attr); + Ty st = typedField(o, attr); + String m = Emitter.mangle(attr); + String rc = nz(recv, attr); + // Python reads the target before it evaluates the value. + String ot = fresh(); + String oo = fresh(); + indent(b, ind); + b.append(jt(st)).append(' ').append(ot).append(" = ").append(rc).append(".t_").append(m).append(";\n"); + indent(b, ind); + b.append("Object ").append(oo).append(" = ").append(rc).append(".b_").append(m).append(";\n"); + E val = spillTo(expr(a.value), b, ind); + StringBuilder tb = new StringBuilder(); + String typedCode = null; + try { + E tv = binop(a.op, new E(ot, st), val, a.value); + indent(tb, ind + 1); + storeGuess(rc + ".t_" + m, rc + ".b_" + m, st, tv, tb, ind + 1); + typedCode = tb.toString(); + } catch (Unsupported u) { + typedCode = null; + } + StringBuilder gb = new StringBuilder(); + E gv = binop(a.op, pairE(ot, oo, st), val, a.value); + indent(gb, ind + 1); + storeGuess(rc + ".t_" + m, rc + ".b_" + m, st, gv, gb, ind + 1); + if (typedCode == null) { + b.append(gb); + return; + } + indent(b, ind); + b.append("if (").append(oo).append(" == null) {\n").append(typedCode); + indent(b, ind); + b.append("} else {\n").append(gb); + indent(b, ind); + b.append("}\n"); + forgetAttr(attr); } /// Stores `v` into typed int field `attr` of `r`; Python evaluates the @@ -2055,7 +5067,7 @@ private void storeIntField(E r, String attr, E v, StringBuilder b, int ind) { String recv = nz(r, attr); if (!plain(recv)) { String t = fresh(); - b.append(o.javaName).append(' ').append(t).append(" = ").append(recv).append(";\n"); + b.append(o.ref).append(' ').append(t).append(" = ").append(recv).append(";\n"); indent(b, ind); recv = t; } @@ -2093,11 +5105,564 @@ String testExpr(Expr e) { return test(expr(e)); } + /// The frame the generic expressions of the function being emitted + /// take their temporaries from (see `genericFallback`), or null before the first. + private Object fallback; + + /// `e`, typed where this class can lower it; where it cannot, the + /// generic code for `e` alone (`genericFallback`), its value an Object. E expr(Expr e) { + List outer = kids; + List mine = new ArrayList(); + StringBuilder p = pre; + int at = p == null ? 0 : p.length(); + int cd = condDepth; + E r; + kids = mine; + try { + r = expr0(e, mine); + } finally { + kids = outer; + } + if (!mine.isEmpty() && pre == p) { //NOPMD CompareObjectsWithEquals - identity is meant + r = split(e, r, mine, p, at, cd); + } + if (outer != null) { + int end = p == null ? 0 : p.length(); + outer.add(new Kid(e, r, p, at, end, p == null ? "" : p.substring(at, end), cd)); + } + return r; + } + + private E expr0(Expr e, List mine) { + StringBuilder p = pre; + int at = p == null ? 0 : p.length(); + Set nn = new HashSet(nonNull); + Map sh = new HashMap(shadow); + try { + return expr1(e); + } catch (Unsupported u) { + // Nothing the failed attempt wrote or learned holds. + if (p != null) { + p.setLength(at); + } + nonNull = nn; + shadow = sh; + mine.clear(); + String g = genericFallback(e); + if (g == null) { + throw u; + } + return new E(g, Ty.OBJECT); + } + } + + /// An operand `expr` lowered for the expression being lowered: the + /// value, and the statements it put before the statement (`pre` from + /// `s` to `end`, that text), at conditional depth `cd`. + private static final class Kid { + final Expr x; + final E v; + final StringBuilder p; //NOPMD AvoidStringBufferField - names the builder, which the generator owns + final int s; + final int end; + final String text; + final int cd; + + Kid(Expr x, E v, StringBuilder p, int s, int end, String text, int cd) { + this.x = x; + this.v = v; + this.p = p; + this.s = s; + this.end = end; + this.text = text; + this.cd = cd; + } + } + + /// The operands `expr` lowered for the expression being lowered, or + /// null outside one (and while [#split] lowers it again). + private List kids; + + /// Whether an expression may run as two versions chosen by a test made + /// before it: not one that evaluates operands conditionally, binds, or + /// suspends, nor a scope of its own. + private static boolean splittable(Expr e) { + return !(e instanceof Name || e instanceof Constant || e instanceof BoolOp || e instanceof IfExp + || e instanceof Lambda || e instanceof Comp || e instanceof NamedExpr || e instanceof Yield + || e instanceof Await || e instanceof Compare && ((Compare) e).ops.size() > 1); + } + + /// Whether evaluating `x` reads and never runs code that could store: + /// a name, a constant, or an attribute or item of one. + private static boolean readOnly(Expr x) { + if (x instanceof Name || x instanceof Constant) { + return true; + } + if (x instanceof Attribute) { + return readOnly(((Attribute) x).value); + } + return false; + } + + /// `e`, whose operands `ks` include guessed values (see `E.gg`), as two + /// versions: one over the typed forms, taken while every operand's test + /// holds, and one over the objects. The typed version is what makes a + /// guess pay: code over a guessed field or local otherwise reads it as + /// an object and runs generic. The operands are evaluated once, by + /// whichever version runs, and the tests read only plain names (or, + /// where every call of the statement is pure, fields), so nothing runs + /// between a test and the read it vouches for that could change it. + /// `trial` is `e` lowered as usual; answered when no split applies. + private E split(Expr e, E trial, List ks, StringBuilder p, int at, int cd) { + if (!splittable(e) || leafSubst.containsKey(e) || inlineArgs != null && !inlined.isEmpty()) { + return trial; + } + boolean any = false; + boolean stable = true; + boolean ok = true; + boolean ran = false; + Set seen = java.util.Collections.newSetFromMap(new IdentityHashMap()); + for (Kid k : ks) { + if (k.cd != cd || k.v.pk != null || !seen.add(k.x) || k.x == e) { //NOPMD CompareObjectsWithEquals - identity is meant + return trial; + } + if (k.v.gview != null) { + any = true; + stable &= k.v.gstable; + // A field the test read may have changed when an operand + // evaluated before this one could run code. + ok &= k.v.gstable || !ran; + } + ran |= !readOnly(k.x); + } + if (!any || !ok && !stmtPure) { + return trial; + } + // Whatever `e` itself put before the statement (an operand copied + // into temporaries, say) stays, and nothing lowered again may skip + // it: such an `e` is left as it is. Where it copied operands, it + // lowered itself again over the copies, and that split already. + int own = p == null ? 0 : p.length() - at; + if (p != null) { + int last = at; + for (Kid k : ks) { + if (k.p != p) { //NOPMD CompareObjectsWithEquals - identity is meant + if (k.end != k.s) { + return trial; + } + continue; + } + if (k.s < last || k.end > p.length() || !p.substring(k.s, k.end).equals(k.text)) { + return trial; + } + own -= k.end - k.s; + last = k.end; + } + } + if (own != 0) { + return trial; + } + Map savedLs = leafSubst; + StringBuilder savedPre = pre; + List savedKids = kids; + Set nn = new HashSet(nonNull); + Map sh = new HashMap(shadow); + List tests = new ArrayList(); + E typed; + E gen; + try { + pre = null; + kids = null; + leafSubst = new IdentityHashMap(savedLs); + for (Kid k : ks) { + leafSubst.put(k.x, k.v.gview != null ? k.v.gview : k.v); + if (k.v.gview != null && !tests.contains(k.v.gg)) { + tests.add(k.v.gg); + } + } + try { + typed = expr1(e); + } catch (Unsupported u) { + return trial; + } finally { + nonNull = new HashSet(nn); + shadow = new HashMap(sh); + } + for (Kid k : ks) { + if (k.v.gview != null) { + leafSubst.put(k.x, new E(k.v.ga, Ty.OBJECT)); + } + } + try { + gen = expr1(e); + } catch (Unsupported u) { + gen = null; + } finally { + nonNull = nn; + shadow = sh; + } + } finally { + pre = savedPre; + kids = savedKids; + leafSubst = savedLs; + } + if (typed.pk != null || gen != null && gen.pk != null) { + return trial; + } + if (gen == null) { + gen = trial; + } + E view = typed; + boolean st = stable; + StringBuilder test = new StringBuilder(); + for (String t : tests) { + test.append(test.length() == 0 ? "" : " && ").append(t); + } + if (typed.gview != null) { + view = typed.gview; + st &= typed.gstable; + test.append(" && ").append(typed.gg); + } else if (typed.t.k != Ty.K.INT && "Object".equals(jt(typed.t)) + && (gen == null || typed.c.equals(gen.c))) { + // An object either way, and no cheaper to reach typed. Where the + // two differ the typed one still pays: `o.name` over a guessed + // `o` reads the field, where the object version asks the + // attribute site. + return trial; + } + String g = test.toString(); + if (gen.gview == null && view.t.k == gen.t.k && jt(view.t).equals(jt(gen.t)) && !"Object".equals(jt(gen.t)) + && (view.t.k != Ty.K.INST || view.t.cls == gen.t.cls) && view.t.opt == gen.t.opt) { //NOPMD CompareObjectsWithEquals - identity is meant + // Both versions answer the same Java type: one typed value. + return new E("(" + g + " ? " + view.c + " : " + gen.c + ")", view.t); + } + if (gen.gview == null && view.t.k == Ty.K.INT && gen.t.k == Ty.K.INT) { + // Both halves with a long form keep one: bs4's `len(self.name_rules) + // == 1` over a split field boxed both lengths to compare them. + return new E("(" + g + " ? " + view.c + " : " + gen.c + ")", Ty.INT, + view.lc != null && gen.lc != null ? "(" + g + " ? " + view.lc + " : " + gen.lc + ")" : null); + } + String ga = box(gen); + E r = new E("(" + g + " ? " + box(view) + " : " + ga + ")", Ty.OBJECT); + r.gg = g; + r.gview = view; + r.ga = ga; + r.gstable = st; + return r; + } + + /// `e` as generic code (Emitter.genericExpr) reading this function's + /// locals boxed, or null where that cannot be: inside an inlined body or + /// a comprehension, for an expression with a scope or binding of its + /// own, or one reading a local that may be unbound here or that has no + /// object (a scalar). + /// Per function: how often each local is bound, and those bound in a loop. + private Map fallbackStores; + private Set loopStored; + + /// Whether local `n` holds one value for good once bound: a parameter + /// the body never rebinds, or a local bound once, outside every loop. + private boolean settled(String n) { + if (fallbackStores == null) { + fallbackStores = storeCounts(cur.def.body); + loopStored = new HashSet(); + Infer.Visit[] v = new Infer.Visit[1]; + v[0] = x -> { + if (x instanceof For) { + For f = (For) x; + List ts = new ArrayList(); + names(f.target, ts); + loopStored.addAll(ts); + loopStored.addAll(assigned(f.body)); + loopStored.addAll(assigned(f.orelse)); + } else if (x instanceof While) { + loopStored.addAll(assigned(((While) x).body)); + loopStored.addAll(assigned(((While) x).orelse)); + } + Infer.children(x, v[0]); + }; + for (Stmt st : cur.def.body) { + v[0].on(st); + } + } + Integer c = fallbackStores.get(n); + if (sc.params.contains(n)) { + return c == null; + } + return c != null && c == 1 && !loopStored.contains(n); + } + + /// Builtins that consume a generator argument before they return and + /// keep nothing of it. + private static final Set CONSUMERS = new HashSet( + Arrays.asList("any", "all", "sum", "min", "max")); + + private String genericFallback(Expr e) { + if (cur == null || sc != cur.def.scope || inlineArgs != null || !inlined.isEmpty() || plainExpr == e //NOPMD CompareObjectsWithEquals - identity is meant + || e instanceof Name) { + // A bare name gains nothing, and a value made here may be moved + // ahead of the branch it is read in: the expression around it + // falls back instead. + return null; + } + boolean[] ok = {true}; + List reads = new ArrayList(); + Infer.Visit[] v = new Infer.Visit[1]; + // Generator expressions their call drains on the spot, found from + // the call before its arguments are visited. + Set drained = new HashSet(); + // Generator expressions a builtin runs to its end, or to where it + // stops, before the call returns: nothing rebinds the function's + // locals meanwhile, so they may read the values captured now. + boolean[] lazy = {false}; + // A generator the call may keep, read after this statement: exact only + // over locals nothing rebinds once it is made (checked below). + boolean[] kept = {false}; + // The reads a kept closure makes when it runs, not when it is made: + // only these need a local nothing rebinds. + Set late = java.util.Collections.newSetFromMap(new IdentityHashMap()); + // Inside a comprehension the generic code makes in a frame of its + // own: anything nested is generic too. + int[] inNow = {0}; + v[0] = x -> { + if (x instanceof Call) { + Call c = (Call) x; + Comp d = em.eagerArgument(c); + if (d == null && !c.args.isEmpty() && c.args.get(0) instanceof Comp && c.func instanceof Name + && CONSUMERS.contains(((Name) c.func).id) + && binding(((Name) c.func).id) == Scope.Binding.BUILTIN + && ((Comp) c.args.get(0)).kind == Comp.Kind.GENERATOR) { + d = (Comp) c.args.get(0); + lazy[0] = true; + } + if (d != null) { + drained.add(d); + } + } + boolean keep = x instanceof Comp && !drained.contains(x) && Emitter.capturable((Comp) x); + if (keep) { + kept[0] = true; + lazy[0] = true; + } + // A list, set or dict comprehension, or a generator its call + // drains, runs to its end where it stands: generic code in a + // frame of its own, over the values the locals hold now. + boolean now = x instanceof Comp && !keep + && (((Comp) x).kind != Comp.Kind.GENERATOR || drained.contains(x)) + && !em.helperNow((Comp) x, drained); + if (now) { + lazy[0] = true; + } + if (x instanceof Lambda && ((Lambda) x).scope.nonlocals.isEmpty()) { + // A closure: kept, so over settled locals only. + kept[0] = true; + lazy[0] = true; + Lambda l = (Lambda) x; + int from = reads.size(); + v[0].on(l.body); + for (int i = reads.size() - 1; i >= from; i--) { + if (l.scope.isLocal(reads.get(i).id)) { + reads.remove(i); + } else { + late.add(reads.get(i)); + } + } + // Defaults are evaluated here, in the function's scope. + for (Expr d : l.args.defaults) { + v[0].on(d); + } + for (Expr d : l.args.kwDefaults) { + if (d != null) { + v[0].on(d); + } + } + } else if (x instanceof Comp && (keep || now || inNow[0] > 0 || em.helperNow((Comp) x, drained))) { + // Written as a method taking what it reads by value; the + // names it binds itself are its own, not the function's. + Scope cs = ((Comp) x).scope; + int from = reads.size(); + boolean nested = inNow[0] > 0 && !keep && !now && !drained.contains(x); + if (nested) { + // May outlive the call: read late, over settled locals. + kept[0] = true; + } + if (now) { + inNow[0]++; + } + try { + Infer.children(x, v[0]); + } finally { + if (now) { + inNow[0]--; + } + } + Set first = java.util.Collections.newSetFromMap(new IdentityHashMap()); + if (keep || nested) { + // The first iterable is evaluated where the generator is made. + Infer.Visit[] fv = new Infer.Visit[1]; + fv[0] = y -> { + if (y instanceof Name) { + first.add((Name) y); + } + Infer.children(y, fv[0]); + }; + fv[0].on(((Comp) x).generators.get(0).iter); + } + for (int i = reads.size() - 1; i >= from; i--) { + if (cs.isLocal(reads.get(i).id)) { + reads.remove(i); + } else if ((keep || nested) && !first.contains(reads.get(i))) { + late.add(reads.get(i)); + } + } + } else if (x instanceof Lambda || x instanceof Comp || x instanceof NamedExpr || x instanceof Yield + || x instanceof Await) { + ok[0] = false; + } else if (ok[0]) { + if (x instanceof Name) { + reads.add((Name) x); + } + if (x instanceof Call && ((Call) x).func instanceof Name && "super".equals(((Name) ((Call) x).func).id) + && ((Call) x).args.isEmpty() && !sc.params.isEmpty()) { + // Zero-argument super() reads the first parameter, and the + // class, which only a layout's field makes reachable here. + reads.add(new Name(sc.params.iterator().next())); + if (sc.enclosingClass == null || em.superClass(sc.enclosingClass) == null) { + ok[0] = false; + } + } + Infer.children(x, v[0]); + } + }; + v[0].on(e); + if (!ok[0]) { + return null; + } + Map names = new HashMap(); + Set unbound = new HashSet(); + for (Name n : reads) { + if (trueCells.contains(n.id) && compVar(n.id) == null) { + // A shared cell: the generic code reads the cell itself. + continue; + } + if (binding(n.id) != Scope.Binding.LOCAL) { + continue; + } + if (scalars.containsKey(n.id) || sc.cells.contains(n.id) && !Infer.compOnlyCells(cur.def).contains(n.id)) { + return null; + } + if (kept[0] && late.contains(n) && !settled(n.id)) { + return null; + } + if (!sc.params.contains(n.id) && !da.safe.contains(n) && compVar(n.id) == null + && !paramAlias.containsKey(n.id)) { + // Not bound on every path: checked where the generic code + // reads it, which may be a branch that never runs -- never + // ahead of the expression. A lambda's capture is read early. + Ty ut = localType(n.id); + if (longLocals.contains(n.id) || accLocals.contains(n.id) || ut.k == Ty.K.INT + || !"null".equals(zero(ut)) || kept[0] && late.contains(n)) { + return null; + } + if (lazy[0]) { + // Handed over as it is, null while unbound, and checked + // inside, where the generic code reads it. + unbound.add(n.id); + names.put(n.id, guessLocal(n.id) ? "((Object) (" + over(n.id) + " != null ? " + over(n.id) + " : (Object) " + + var(n.id) + "))" : "((Object) " + var(n.id) + ")"); + continue; + } + names.put(n.id, guessLocal(n.id) ? "((Object) " + expr1(n).c + ")" + : "((Object) Typed.local(" + var(n.id) + ", " + Emitter.javaString(n.id) + "))"); + continue; + } + try { + // Of static type Object: the generic code tests it with + // instanceof against classes a typed local cannot be. + String r = box(expr1(n)); + if (kept[0] && r.contains("Typed.local(")) { + return null; + } + names.put(n.id, "((Object) " + r + ")"); + } catch (Unsupported u) { + return null; + } + } + if (fallback == null) { + fallback = em.fallbackFrame(sc); + } + if (!lazy[0] || names.isEmpty()) { + return em.genericExpr(fallback, sc, e, names); + } + if (names.size() > 8) { + return null; + } + // The generator is an object the Java expression makes: what it reads + // goes in as parameters, which a local reassigned later cannot be. + Map params = new HashMap(); + StringBuilder sig = new StringBuilder(); + StringBuilder args = new StringBuilder(); + for (Map.Entry en : names.entrySet()) { + String p = fresh(); + params.put(en.getKey(), unbound.contains(en.getKey()) + ? "((Object) Typed.local(" + p + ", " + Emitter.javaString(en.getKey()) + "))" : p); + sig.append(sig.length() == 0 ? "" : ", ").append("Object ").append(p); + args.append(args.length() == 0 ? "" : ", ").append(en.getValue()); + } + // A frame of its own, its temporaries declared inside the lambda, + // which cannot assign the function's. + Object own = em.fallbackFrame(sc); + String g = em.genericExpr(own, sc, e, params); + if (g == null) { + return null; + } + return "((PyFunction.Body" + names.size() + ") (" + sig + ") -> {\n" + em.fallbackDecls(own) + "\nreturn " + g + + ";\n}).run(" + args + ")"; + } + + /// `(n := v)`: a Java assignment, itself an expression, so nothing is + /// hoisted and the value is stored exactly where Python stores it. + private E namedExpr(NamedExpr w) { + String n = w.target.id; + if (trueCell(n)) { + E v = expr(w.value); + return new E("(" + cellRef(n) + " = " + box(v) + ")", Ty.OBJECT); + } + if (binding(n) != Scope.Binding.LOCAL || compVar(n) != null || inlineArgs != null + || longLocals.contains(n) || accLocals.contains(n) || scalars.containsKey(n) || guessLocal(n)) { + // A guessed local's object half would have to change with it. + throw new Unsupported("NamedExpr"); + } + Ty lt = localType(n); + if (lt.k == Ty.K.INT || lt.k == Ty.K.BOT) { + throw new Unsupported("NamedExpr"); + } + E v = expr(w.value); + paramAlias.remove(n); + forgetPathsOf(n); + shadow.remove(n); + nonNull.remove(n); + return new E("(" + var(n) + " = " + conv(v, lt) + ")", lt); + } + + private E expr1(Expr e) { E sub = leafSubst.get(e); if (sub != null) { return sub; } + if (!(e instanceof Constant) && inlineArgs == null && soleStores != null) { + Object k = fold(e); + if (k != null) { + return constE(k); + } + } + if (e instanceof BinOp && "%".equals(((BinOp) e).op) && inlineArgs == null) { + E m = modConstant((BinOp) e); + if (m != null) { + return m; + } + } if (e != plainExpr && (e instanceof BinOp || e instanceof UnaryOp || e instanceof IfExp //NOPMD CompareObjectsWithEquals || e instanceof Call && ranges.inlinable((Call) e) != null)) { E w = wrapped(e); @@ -2128,6 +5693,8 @@ E expr(Expr e) { } case STR: return new E(em.constant(c), Ty.STR); + case BYTES: + return new E(em.constant(c), Ty.BYTES); default: throw new Unsupported("constant"); } @@ -2135,6 +5702,9 @@ E expr(Expr e) { if (e instanceof Name) { return name((Name) e); } + if (e instanceof NamedExpr) { + return namedExpr((NamedExpr) e); + } if (e instanceof Attribute) { Attribute a = (Attribute) e; if (Infer.MATH_CONSTS.contains(a.attr) && in.isMath(a.value, sc)) { @@ -2143,32 +5713,100 @@ E expr(Expr e) { if (a.value instanceof Name && scalars.containsKey(((Name) a.value).id)) { return scalarRead(((Name) a.value).id, a.attr); } + Layouts.Cls sk = in.classStaticOf(a.value, a.attr, sc); + if (sk != null) { + // A once-bound class attribute: its typed static field. + return staticE(em.classStaticRef(sk, a.attr), in.classStatic(sk, a.attr)); + } E r = expr(a.value); if (r.t.k != Ty.K.INST) { - return new E(em.attrSite(a.attr) + ".get(" + box(r) + ")", Ty.DYN); + return new E(attrGet(r, a.attr), Ty.OBJECT); + } + E viaStatic = r.t.opt || !plain(r.c) ? null : instanceStatic(r, a.attr); + if (viaStatic != null) { + return viaStatic; + } + Layouts.Cls fo = Infer.fieldOwner(r.t.cls, a.attr); + if (fo != null && typedField(fo, a.attr) == null && !in.definitelySet(fo, a.attr) && !r.t.opt && plain(r.c)) { + // A field that may be unset: its value when it holds one, the + // generic read -- class attribute, AttributeError -- when not. + String f = r.c + ".f_" + Emitter.mangle(a.attr); + return new E("(" + f + " != null ? " + f + " : " + em.attrSite(a.attr) + ".get(" + r.c + "))", Ty.OBJECT); + } + Infer.Fn pg = fo == null && plain(r.c) ? in.propertyGetter(r.t, a.attr) : null; + if (pg != null && typed.get(pg) != null) { + // A property's getter called as a method is, unless the + // class was patched at run time; generic reads otherwise + // went through the site and the getter's PyFunction (bs4's + // `SoupStrainer.includes_everything` in every match). + calls.add(pg); + E got = result(pg, typed.get(pg) + "(" + r.c + ")"); + return new E("(" + r.c + ".cls.patched ? " + em.attrSite(a.attr) + ".get(" + r.c + ") : " + box(got) + ")", + Ty.OBJECT); + } + if (fo == null || typedField(fo, a.attr) == null && !in.definitelySet(fo, a.attr)) { + // Not a field the class declares, or one that may be unset: the + // generic read, with its AttributeError, __getattr__ and class + // attributes, rather than giving up the whole typed function. + return new E(attrGet(r, a.attr), Ty.OBJECT); } Ty ft = fieldTy(r, a.attr); if (ft.k == Ty.K.INT && typedField(owner(r, a.attr), a.attr) != null) { return intField(r, a.attr); } String p = path(a); + if (guardedField(owner(r, a.attr), a.attr)) { + Ty st = typedField(owner(r, a.attr), a.attr); + return guessField(r, a.attr, p != null && nonNull.contains(p) ? st.nonNone() : st); + } return new E(fieldRef(r, a.attr), p != null && nonNull.contains(p) ? ft.nonNone() : ft); } if (e instanceof BinOp) { - if (pre != null && arith(e)) { + BinOp b = (BinOp) e; + E pc = percentConcat(b); + if (pc != null) { + return pc; + } + String pf = em.percentHead(b); + if (pf != null) { + StringBuilder sb = new StringBuilder(pf); + for (Expr v : ((TupleExpr) b.right).elts) { + sb.append(", ").append(box(expr(v))); + } + return new E(sb.append(')').toString(), Ty.STR); + } + if ("%".equals(b.op) && b.left instanceof Constant && !(b.right instanceof TupleExpr)) { + Ty rt = in.type(b.right, cur, sc); + if (rt != null && !rt.opt && (rt.k == Ty.K.STR || rt.k == Ty.K.INT || rt.k == Ty.K.FLOAT)) { + String one = em.percentHead((Constant) b.left, 1); + if (one != null) { + return new E(one + ", " + box(expr(b.right)) + ")", Ty.STR); + } + } + } + if (pre != null && condDepth == 0 && arith(e)) { + // Not under a branch: the block runs before the statement. E h = hoistInt(e); if (h != null) { return h; } } - BinOp b = (BinOp) e; if ("+".equals(b.op) && b.left instanceof BinOp && "+".equals(((BinOp) b.left).op)) { E c = strChain(b); if (c != null) { return c; } } - return binop(b.op, expr(b.left), expr(b.right), b.right); + E fz = fusedDyn(e); + if (fz != null) { + return fz; + } + E bl = expr(b.left); + E br = expr(b.right); + if (Infer.realPow(b, bl.t, br.t)) { + return new E("Typed.pow(" + toD(bl) + ", " + toD(br) + ")", Ty.FLOAT); + } + return binop(b.op, bl, br, b.right); } if (e instanceof UnaryOp) { UnaryOp u = (UnaryOp) e; @@ -2191,30 +5829,42 @@ E expr(Expr e) { } } } - throw new Unsupported("unary " + u.op + " " + o.t); + String f = "-".equals(u.op) ? "neg" : "~".equals(u.op) ? "invert" : "pos"; + return new E("Py." + f + "(" + box(o) + ")", Ty.OBJECT); } if (e instanceof BoolOp) { BoolOp o = (BoolOp) e; - StringBuilder sb = new StringBuilder("("); - String j = o.isAnd ? " && " : " || "; + List vs = new ArrayList(); + boolean bools = true; for (int i = 0; i < o.values.size(); i++) { condDepth += i == 0 ? 0 : 1; - E v; try { - v = expr(o.values.get(i)); + vs.add(expr(o.values.get(i))); } finally { condDepth -= i == 0 ? 0 : 1; } - if (v.t.k != Ty.K.BOOL) { - throw new Unsupported("and/or of " + v.t); + bools &= vs.get(i).t.k == Ty.K.BOOL; + } + StringBuilder sb = new StringBuilder("("); + if (bools) { + String j = o.isAnd ? " && " : " || "; + for (int i = 0; i < vs.size(); i++) { + sb.append(i == 0 ? "" : j).append(vs.get(i).c); } - sb.append(i == 0 ? "" : j).append(v.c); + return new E(sb.append(')').toString(), Ty.BOOL); } - return new E(sb.append(')').toString(), Ty.BOOL); + // The operand that decides, as Python answers it: each but the + // last is kept in a temporary while its truth is tested. + String t = exprTemp("Object"); + for (int i = 0; i < vs.size() - 1; i++) { + sb.append(o.isAnd ? "!" : "").append("Py.isTrue(").append(t).append(" = ").append(box(vs.get(i))) + .append(") ? ").append(t).append(" : "); + } + return new E(sb.append(box(vs.get(vs.size() - 1))).append(')').toString(), Ty.OBJECT); } if (e instanceof Compare) { Compare cm = (Compare) e; - if (pre != null && cm.ops.size() == 1 && ORDERS.contains(cm.ops.get(0)) + if (pre != null && condDepth == 0 && cm.ops.size() == 1 && ORDERS.contains(cm.ops.get(0)) && (arith(cm.left) || arith(cm.comparators.get(0)) || numeric(cm))) { E h = hoistInt(e); if (h != null) { @@ -2250,8 +5900,18 @@ E expr(Expr e) { Subscript s = (Subscript) e; if (s.index instanceof Slice) { E l = expr(s.value); + if (l.t.k == Ty.K.STR && !l.t.opt) { + String fast = strSliceLong(l, (Slice) s.index); + if (fast != null) { + return new E(fast, Ty.STR); + } + return new E("Typed.slice(" + l.c + ", " + sliceParts((Slice) s.index) + ")", Ty.STR); + } if (l.t.k != Ty.K.LIST) { - throw new Unsupported("slice of " + l.t); + // A bytes or any other value: the generic slice, which has a + // direct path for bytes with int bounds. + return new E("Py.getslice(" + box(l) + ", " + sliceParts((Slice) s.index) + ")", + l.t.k == Ty.K.BYTES ? Ty.BYTES : Ty.OBJECT); } return new E("Typed.asList(Py.getslice(" + l.c + ", " + sliceParts((Slice) s.index) + "))", l.t.nonNone()); @@ -2262,13 +5922,50 @@ E expr(Expr e) { } E l = expr(s.value); E i = expr(s.index); + if (l.t.k == Ty.K.DICT) { + return dictRead("Typed.dgetv(" + l.c + ", " + box(i) + ")", l.t); + } + if (l.t.k == Ty.K.BYTES && (i.t.k == Ty.K.INT || i.t.k == Ty.K.BOOL)) { + if (i.lc == null) { + // As for a str below: the generic read raises what + // CPython raises for an index no long holds. + return new E("Py.getitem(" + box(l) + ", " + box(i) + ")", Ty.INT); + } + String c = "Typed.bat(" + l.c + ", " + i.lc + ")"; + return small(new E("Long.valueOf(" + c + ")", Ty.INT, c)); + } + if (l.t.k == Ty.K.STR && !l.t.opt && (i.t.k == Ty.K.INT || i.t.k == Ty.K.BOOL)) { + // An index that is not a long in hand goes the generic way: one + // too big for a long is an IndexError there, as in CPython. + String slow = "Typed.asStr(Py.getitem(" + l.c + ", " + box(i) + "))"; + String sp = ""; + if (s.value instanceof Name && flatStr.contains(((Name) s.value).id) && sc == cur.def.scope //NOPMD CompareObjectsWithEquals - identity is meant + && compVar(((Name) s.value).id) == null && l.c.equals(var(((Name) s.value).id))) { + String c = "sp" + l.c; + sp = ", (" + c + " < 0 ? (" + c + " = Typed.surr(" + l.c + ")) : " + c + ")"; + } + E se = new E(i.lc != null ? "Typed.sat(" + l.c + ", " + i.lc + sp + ")" + : i.ll != null ? "(" + i.bg + " == null ? Typed.sat(" + l.c + ", " + i.ll + sp + ") : " + slow + ")" + : slow, Ty.STR); + if (!sp.isEmpty() && i.lc != null && (plain(i.lc) || literal(i.lc))) { + se.charAt = new String[] {l.c, i.lc, sp.substring(2)}; + } + return se; + } if (l.t.k != Ty.K.LIST || !(i.t.k == Ty.K.INT || i.t.k == Ty.K.BOOL)) { - return new E("Py.getitem(" + box(l) + ", " + box(i) + ")", Ty.DYN); + if (Emitter.isStrLiteral(i.c)) { + return new E(em.keyRead(box(l), i.c), Ty.OBJECT); + } + return new E("Py.getitem(" + box(l) + ", " + box(i) + ")", Ty.OBJECT); } + l = heldList(l); Ty el = in.elem(l.t); if (el.k == Ty.K.BOT) { throw new Unsupported("element of nothing"); } + if (el.k != Ty.K.INT && in.guessedSite(l.t)) { + return guessedElem("h_get(" + l.c + ", " + box(i) + ")", el, null, 0); + } String slow = el.k == Ty.K.FLOAT ? "h_getF(" + l.c + ", " + box(i) + ")" : "h_get(" + l.c + ", " + box(i) + ")"; String fast = slow; String[] ix = index(i); @@ -2330,6 +6027,9 @@ E expr(Expr e) { : "(" + in + " ? (" + l.c + ".ints != null ? (Object) Long.valueOf(" + l.c + ".ints[(int) " + i.lc + "]) : " + l.c + ".floats == null ? " + l.c + ".items[(int) " + i.lc + "] : " + slow + ") : " + slow + ")"; + } else if (i.lc != null && i.pk == null && el.k != Ty.K.FLOAT) { + // A list named by a call: one helper, the index unboxed. + fast = "Typed.at(" + l.c + ", " + i.lc + ")"; } return el.k == Ty.K.FLOAT ? new E(fast, el) : new E(unbox(fast, el), el); } @@ -2342,7 +6042,8 @@ E expr(Expr e) { } sb.append(i == 0 ? "" : ", ").append(box(expr(el.get(i)))); } - return new E(sb.append(')').toString(), Ty.DYN); + sb.append(')'); + return new E(Emitter.foldable(el) ? em.hoist("PyTuple", sb.toString()) : sb.toString(), Ty.OBJECT); } if (e instanceof ListExpr) { ListExpr l = (ListExpr) e; @@ -2350,6 +6051,9 @@ E expr(Expr e) { if (site == null) { throw new Unsupported("list site"); } + if (l.elts.isEmpty()) { + return new E("Py.list()", Ty.list(new int[] {site.intValue()}, false)); + } StringBuilder sb = new StringBuilder("Typed.list(new Object[] {"); for (int i = 0; i < l.elts.size(); i++) { if (l.elts.get(i) instanceof Starred) { @@ -2360,32 +6064,208 @@ E expr(Expr e) { return new E(sb.append("})").toString(), Ty.list(new int[] {site.intValue()}, false)); } if (e instanceof Call) { - return call((Call) e); + return builtinResult((Call) e, call((Call) e)); + } + if (e instanceof Comp && (((Comp) e).kind != Comp.Kind.GENERATOR || eagerGens.contains(e))) { + return comp((Comp) e); } if (e instanceof DictExpr) { DictExpr d = (DictExpr) e; - StringBuilder sb = new StringBuilder("Py.dict("); + String shape = d.keys.contains(null) ? null : em.dictShape(d.keys); + if (shape != null) { + StringBuilder sb = new StringBuilder("PyDict.literal(").append(shape).append(", new Object[] {"); + for (int i = 0; i < d.values.size(); i++) { + sb.append(i == 0 ? "" : ", ").append(box(expr(d.values.get(i)))); + } + return new E(sb.append("})").toString(), Ty.OBJECT); + } + // Made at its final size, one put per pair: no array of the pairs is built. + StringBuilder sb = new StringBuilder("new PyDict(").append(d.keys.size()).append(')'); for (int i = 0; i < d.keys.size(); i++) { if (d.keys.get(i) == null) { throw new Unsupported("dict spread"); } - sb.append(i == 0 ? "" : ", ").append(box(expr(d.keys.get(i)))).append(", ") - .append(box(expr(d.values.get(i)))); + sb.append(".put(").append(box(expr(d.keys.get(i)))).append(", ") + .append(box(expr(d.values.get(i)))).append(')'); } - return new E(sb.append(')').toString(), Ty.DYN); + return new E(sb.toString(), Ty.OBJECT); + } + if (e instanceof Lambda && closedLambda((Lambda) e) && ((Lambda) e).args.defaults.isEmpty() + && ((Lambda) e).args.kwDefaults.stream().allMatch(x -> x == null)) { + // Nothing of this function in it: the function object the generic + // code makes, which reads no local of the frame it is made in. + return new E(em.lambdaValue((Lambda) e), Ty.OBJECT); + } + if (e instanceof JoinedStr) { + return new E(joined((JoinedStr) e), Ty.OBJECT); } throw new Unsupported(e.getClass().getSimpleName()); } + /// An f-string, as the generic code builds it: every value is formatted + /// by the runtime, so a typed operand is boxed and nothing else differs. + private String joined(JoinedStr j) { + List parts = new ArrayList(); + for (Expr p : j.parts) { + if (p instanceof Constant) { + parts.add(em.constant((Constant) p)); + continue; + } + FormattedValue f = (FormattedValue) p; + String v = box(expr(f.value)); + if (f.conversion == 'r') { + v = "Py.str(Py.toRepr(" + v + "))"; + } else if (f.conversion == 's') { + v = "Py.str(Py.strOf(" + v + "))"; + } else if (f.conversion == 'a') { + v = "Py.call(Builtins.ASCII, " + v + ")"; + } + String spec; + if (f.spec == null || f.spec.parts.isEmpty()) { + spec = "\"\""; + } else if (f.spec.parts.size() == 1 && f.spec.parts.get(0) instanceof Constant) { + spec = Emitter.javaString(((Constant) f.spec.parts.get(0)).text); + } else { + spec = "Py.strOf(" + joined(f.spec) + ")"; + } + parts.add("Py.format(" + v + ", " + spec + ")"); + } + if (parts.isEmpty()) { + return "Py.str(\"\")"; + } + if (parts.size() == 1) { + return parts.get(0); + } + String built = Emitter.stringBuilderChain(parts); + if (built != null) { + return built; + } + StringBuilder sb = new StringBuilder("Py.concat("); + for (int i = 0; i < parts.size(); i++) { + sb.append(i == 0 ? "" : ", ").append(parts.get(i)); + } + return sb.append(')').toString(); + } + + /// Whether lambda `l` reads nothing but its parameters, globals and + /// builtins, and opens no scope of its own. + private static boolean closedLambda(Lambda l) { + if (l.scope.hasYield || !l.scope.cells.isEmpty()) { + return false; + } + boolean[] ok = {true}; + Infer.Visit[] v = new Infer.Visit[1]; + v[0] = x -> { + if (x instanceof Lambda || x instanceof Comp || x instanceof NamedExpr || x instanceof Yield + || x instanceof Await) { + ok[0] = false; + } else if (x instanceof Name) { + Scope.Binding b = l.scope.resolve(((Name) x).id); + ok[0] &= b == Scope.Binding.LOCAL || b == Scope.Binding.GLOBAL || b == Scope.Binding.BUILTIN; + } else if (ok[0]) { + Infer.children(x, v[0]); + } + }; + v[0].on(l.body); + return ok[0]; + } + + /// The parameters of a lambda being expanded in place (`inlineLambda`), + /// each to its argument already in a local; read by `name` while `sc` is + /// that lambda's scope. + private Map inlineArgs; + private Scope inlineScope; + + /// `(lambda x, y: body)(a, b)` as `body`, in this function: the arguments + /// into locals before the statement, in order, then the body over them. + /// Null when that is not the same: the statement may not move its + /// evaluation, or the lambda reads this function's locals. + private E inlineLambda(Lambda l, Call c) { + Arguments la = l.args; + if (pre == null || !stmtPure || condDepth != 0 || inlineArgs != null || !c.keywords.isEmpty() + || la.vararg != null || la.kwarg != null || !la.kwonly.isEmpty() || !la.defaults.isEmpty() + || la.positional.size() != c.args.size() || !closedLambda(l)) { + return null; + } + Map map = new HashMap(); + for (int i = 0; i < c.args.size(); i++) { + if (c.args.get(i) instanceof Starred) { + return null; + } + } + for (int i = 0; i < c.args.size(); i++) { + map.put(la.positional.get(i).name, spillTo(expr(c.args.get(i)), pre, preInd)); + } + Scope saved = sc; + sc = l.scope; + inlineArgs = map; + inlineScope = l.scope; + try { + return expr(l.body); + } finally { + sc = saved; + inlineArgs = null; + inlineScope = null; + } + } + + /// Parameters read as they arrived until the body's first statement + /// rebinds them (`function`). + private final Map paramAlias = new HashMap(); + private E name(Name nm) { String n = nm.id; - switch (sc.resolve(n)) { + if (inlineArgs != null && sc == inlineScope && inlineArgs.containsKey(n)) { //NOPMD CompareObjectsWithEquals - identity is meant + return inlineArgs.get(n); + } + if (trueCell(n)) { + return new E("Typed.local(" + cellRef(n) + ", " + Emitter.javaString(n) + ")", Ty.OBJECT); + } + switch (binding(n)) { case LOCAL: { + String cv = compVar(n); + if (cv != null) { + // A comprehension's own target, in a temporary of its own + // even where the function has a local of the same name; + // a guessed one is the pair, whose typed half holds + // nothing of an element that missed. + String co = compOver.get(cv); + return co != null ? pairE(cv, co, compVarType(n)) : new E(cv, compVarType(n)); + } + E alias = paramAlias.get(n); + if (alias != null) { + return alias; + } if (!sc.params.contains(n) && !da.safe.contains(nm)) { - throw new Unsupported("maybe unbound " + n); + Ty ut = localType(n); + if (ut != null && unboundInts.contains(n) && !longLocals.contains(n) + && !scalars.containsKey(n) && !shadow.containsKey(n) + && inlineArgs == null) { + // Checked here, as CPython checks it. The read is an + // expression, so it stays inside any branch it is in. + String chk = "Typed.boundInt(" + big(n) + ", " + Emitter.javaString(n) + ")"; + if (accLocals.contains(n)) { + return new E("(" + chk + " == null ? (Object) Long.valueOf(" + var(n) + ") : " + big(n) + + ")", Ty.OBJECT); + } + return dual(var(n), chk); + } + if (ut == null || longLocals.contains(n) || accLocals.contains(n) || scalars.containsKey(n) + || ut.k == Ty.K.INT || !"null".equals(zero(ut)) || inlineArgs != null) { + throw new Unsupported("maybe unbound " + n); + } + // Null until bound: checked here, as CPython checks it. + if (guessLocal(n)) { + return new E("(" + over(n) + " != null ? " + over(n) + " : Typed.local(" + box(new E(var(n), ut)) + + ", " + Emitter.javaString(n) + "))", Ty.OBJECT); + } + return new E("Typed.local(" + var(n) + ", " + Emitter.javaString(n) + ")", ut); } Ty t = localType(n); - if (sc.deleted.contains(n)) { + if (sc.deleted.contains(n) && (longLocals.contains(n) || !"Object".equals(jt(t)))) { + // An object local is null once deleted, and DefAssign has + // already proven this read follows a binding (an except + // target inside its handler); a long cannot be unbound. throw new Unsupported("deleted " + n); } if (longLocals.contains(n)) { @@ -2398,18 +6278,53 @@ private E name(Name nm) { if (t.k == Ty.K.INT) { return dual(var(n), big(n)); } + if (accLocals.contains(n)) { + // An int while the object is null: the view [#split] + // lowers comparisons and subscripts over, so html.parser's + // `while k < n and rawdata[k] not in _TAG_END` compares + // longs and reads a char instead of boxing `k` for + // Py.lt and Py.getitem. + E r = new E("(" + big(n) + " == null ? (Object) Long.valueOf(" + var(n) + ") : " + big(n) + ")", Ty.OBJECT); + r.gg = big(n) + " == null"; + r.gview = new E("Long.valueOf(" + var(n) + ")", Ty.INT, var(n)); + r.ga = r.c; + r.gstable = true; + return r; + } + if (guessLocal(n)) { + return pairE(var(n), over(n), nonNull.contains(n) ? t.nonNone() : t); + } + Ty nt = in.narrowedAt.get(nm); + if (nt != null && !"boolean".equals(jt(t)) && !"double".equals(jt(t)) + && (nt.k == Ty.K.INST && nt.cls.compiled || nt.k == Ty.K.STR || nt.k == Ty.K.LIST)) { + // Inside `if isinstance(x, K):` x is a K. + return new E("((" + jt(nt) + ") " + var(n) + ")", nt); + } return new E(var(n), nonNull.contains(n) ? t.nonNone() : t); } case GLOBAL: { if (in.globalFns.containsKey(n) || in.globalClasses.containsKey(n)) { - throw new Unsupported("function as a value"); + // The function or class object itself: Infer has seen + // it escape, so nothing assumes its every caller. + return new E("g(" + em.slot(n) + ")", Ty.OBJECT); } Ty t = in.globals.get(n); if (t == null || t.k == Ty.K.BOT) { - throw new Unsupported("global " + n); + // No type known (bound only through globals(), a star + // import or a later definition): the slot as it is, + // NameError while unbound. + return new E("g(" + em.slot(n) + ")", Ty.OBJECT); + } + if (t.k != Ty.K.INT && in.guessedGlobal(n)) { + return guessedElem("g(" + em.slot(n) + ")", t, null, 0); } return new E(unbox("g(" + em.slot(n) + ")", t), t); } + case BUILTIN: + if (em.moduleScopeHasStarImport()) { + throw new Unsupported("name " + n); + } + return new E(em.builtinRef(n), Ty.OBJECT); default: throw new Unsupported("name " + n); } @@ -2567,7 +6482,7 @@ private boolean collectLeaves(Expr e, List out) { } return collectLeaves(((BinOp) e).left, out) && collectLeaves(((BinOp) e).right, out); } - boolean quiet = e instanceof Constant || e instanceof Name && sc.resolve(((Name) e).id) == Scope.Binding.LOCAL; + boolean quiet = e instanceof Constant || e instanceof Name && binding(((Name) e).id) == Scope.Binding.LOCAL; if (!quiet && !((stmtPure || topLeaves) && condDepth == 0)) { return false; } @@ -2593,6 +6508,9 @@ private char kindOf(Expr e) { if (e instanceof UnaryOp) { return kindOf(((UnaryOp) e).operand); } + if (!(e instanceof BinOp)) { + return 0; + } BinOp b = (BinOp) e; char l = kindOf(b.left); char r = kindOf(b.right); @@ -2679,7 +6597,9 @@ private E generic0(Expr e) { StringBuilder saved = pre; pre = null; try { - return e instanceof Compare ? compare((Compare) e) : expr(e); + // Through expr, so a leaf with a typed view splits (see #split); + // with no pre it cannot come back here. + return expr(e); } finally { pre = saved; } @@ -2687,14 +6607,54 @@ private E generic0(Expr e) { /// `v` in plain Java locals, so it may be read twice: declared in `pre`. private E spill(E v) { - if (v.ll != null || plain(v.c) && v.lc == null || v.lc != null && (plain(v.lc) || literal(v.lc))) { + if (v.gr != null && v.gr.indexOf('.') < 0 || v.ll != null || plain(v.c) && v.lc == null || v.lc != null && (plain(v.lc) || literal(v.lc))) { return v; } - return spillTo(v, pre, preInd); - } - - /// `v` copied into fresh Java locals declared in `into`. - private E spillTo(E v, StringBuilder into, int ind) { + if (v.gview != null && v.gstable && v.gview.lc != null && plain(v.gview.lc) && v.ga.equals(v.c)) { + // An accumulator's read (see the name read): both forms read + // plain locals, so it may be read twice as it is, and a copy + // would lose the int view the comparison splits on. + return v; + } + return spillTo(v, pre, preInd); + } + + /// `v` copied into fresh Java locals declared in `into`. + private E spillTo(E v, StringBuilder into, int ind) { + if (v.gview != null && v.go == null && v.gview.t.k != Ty.K.INT && !"Object".equals(jt(v.gview.t))) { + // Two versions' value: a pair again, the test made once. + Ty t = v.gview.t; + String r = fresh(); + String o = fresh(); + indent(into, ind); + into.append(jt(t)).append(' ').append(r).append(" = ").append(zero(t)).append(";\n"); + indent(into, ind); + into.append("Object ").append(o).append(" = null;\n"); + indent(into, ind); + into.append("if (").append(v.gg).append(") {\n"); + indent(into, ind + 1); + into.append(r).append(" = ").append(v.gview.c).append(";\n"); + indent(into, ind); + into.append("} else {\n"); + indent(into, ind + 1); + into.append(o).append(" = ").append(v.ga).append(";\n"); + indent(into, ind); + into.append("}\n"); + return pairE(r, o, t); + } + if (v.gr != null) { + if (v.gr.indexOf('.') < 0) { + return v; + } + // A field's pair: a copy, which nothing evaluated later changes. + String r = fresh(); + String o = fresh(); + indent(into, ind); + into.append(jt(v.gt)).append(' ').append(r).append(" = ").append(v.gr).append(";\n"); + indent(into, ind); + into.append("Object ").append(o).append(" = ").append(v.go).append(";\n"); + return pairE(r, o, v.gt); + } String t = fresh(); indent(into, ind); if (v.lc != null) { @@ -3145,6 +7105,36 @@ private E strChain(BinOp b) { return new E("new StringBuilder(" + cap + ")" + sb + ".toString()", Ty.STR); } + /// Arithmetic of two or more operators whose every leaf is of a type + /// not known here (`a * x + c * y + e` over a tuple's items): the + /// generic emitter's fused helper, which computes the whole tree in + /// doubles when the leaves are floats and boxes only the result, + /// instead of one boxed value per operator. Null when a leaf is typed; + /// the typed operators are better then. + private E fusedDyn(Expr e) { + if (Emitter.numOps(e) < 2) { + return null; + } + List leaves = new ArrayList(); + Emitter.numLeaves(e, leaves); + if (leaves.isEmpty()) { + return null; + } + Map code = new IdentityHashMap(); + for (Expr l : leaves) { + if (l instanceof Constant) { + continue; + } + E v = expr(l); + if (!v.t.wide()) { + return null; + } + code.put(l, box(v)); + } + String f = em.fused(e, null, x -> code.containsKey(x) ? code.get(x) : box(expr(x))); + return f == null ? null : new E(f, Ty.OBJECT); + } + E binop(String op, E l, E r, Expr right) { Ty t = Infer.binop(op, l.t, r.t, right); if (l.t.k == Ty.K.LIST && "*".equals(op) && (r.t.k == Ty.K.INT || r.t.k == Ty.K.BOOL)) { @@ -3173,14 +7163,35 @@ E binop(String op, E l, E r, Expr right) { throw new Unsupported("float " + op); } } - case INT: + case INT: { + Long k = intConstant(right); + if (("+".equals(op) || "-".equals(op)) && l.small && l.lc != null && l.pk == null && !l.t.opt && k != null + && Math.abs(k.longValue()) < 0x80000000L) { + // A length or an index plus a constant of 31 bits: no + // overflow is possible, so plain Java arithmetic. + String lc = "(" + l.lc + " " + op + " " + k + "L)"; + return new E("Long.valueOf(" + lc + ")", Ty.INT, lc); + } return new E(intOp(pyOp(op), box(l), box(r), right), Ty.INT); + } case STR: + if ("%".equals(op)) { + return new E("Typed.format(" + l.c + ", " + box(r) + ")", Ty.STR); + } + if ("*".equals(op)) { + return new E("Typed.asStr(Py.mul(" + box(l) + ", " + box(r) + "))", Ty.STR); + } return new E("Typed.concat(" + l.c + ", " + r.c + ")", Ty.STR); case BOT: throw new Unsupported("operation on nothing"); default: - return new E("Py." + pyOp(op) + "(" + box(l) + ", " + box(r) + ")", Ty.DYN); + if ("+".equals(op) || "-".equals(op)) { + // An operand of unknown type is still an int most of the time + // (`s += x` over a generator's values). The int helper tests for + // two Longs inline and hands anything else to the same Py call. + return new E(intOp(pyOp(op), box(l), box(r), right), Ty.OBJECT); + } + return new E("Py." + pyOp(op) + "(" + box(l) + ", " + box(r) + ")", Ty.OBJECT); } } @@ -3203,11 +7214,56 @@ private String isNoneTest(E x) { private E compare(Compare c) { if (c.ops.size() != 1) { - throw new Unsupported("chained comparison"); + // `a < b < c` is `a < b and b < c` with b evaluated once (into a + // temporary unless it is a name or a constant) and c only when + // the first link held; every link must be a bool. + StringBuilder sb = new StringBuilder("("); + E left = expr(c.left); + for (int i = 0; i < c.ops.size(); i++) { + Expr rn = c.comparators.get(i); + // A later link runs only when the ones before it held: + // nothing of it may be hoisted ahead of the test. + condDepth += i == 0 ? 0 : 1; + E right; + try { + right = expr(rn); + } finally { + condDepth -= i == 0 ? 0 : 1; + } + E use = right; + E next = right; + if (i < c.ops.size() - 1 && !(rn instanceof Name || rn instanceof Constant)) { + if (right.lc != null || right.ll != null) { + throw new Unsupported("chained comparison"); + } + String t = exprTemp(jt(right.t)); + use = new E("(" + t + " = " + right.c + ")", right.t); + next = new E(t, right.t); + } + E e = compareOp(c.ops.get(i), left, use, rn); + if (e.t.k != Ty.K.BOOL) { + throw new Unsupported("chained comparison"); + } + sb.append(i == 0 ? "" : " && ").append(e.c); + left = next; + } + return new E(sb.append(")").toString(), Ty.BOOL); + } + List lit = Emitter.inTuple(c); + if (lit != null) { + // `x in ("ltr", "rtl")`: compared item by item, no tuple built. + StringBuilder r = new StringBuilder("not in".equals(c.ops.get(0)) ? "(!" : "(").append("Py.inOf(") + .append(box(expr(c.left))); + for (Expr t : lit) { + r.append(", ").append(box(expr(t))); + } + return new E(r.append("))").toString(), Ty.BOOL); } - String op = c.ops.get(0); - E l = expr(c.left); - E r = expr(c.comparators.get(0)); + return compareOp(c.ops.get(0), expr(c.left), expr(c.comparators.get(0)), c.comparators.get(0)); + } + + /// `l op r`, both evaluated; `rn` is r's tree, for its int range. + private E compareOp(String op, E l, E r, Expr rn) { if ("is".equals(op) || "is not".equals(op) || isNone(l) || isNone(r)) { boolean neg = "is not".equals(op) || "!=".equals(op); if (!("is".equals(op) || "is not".equals(op) || "==".equals(op) || "!=".equals(op))) { @@ -3219,9 +7275,12 @@ private E compare(Compare c) { } else if (isNone(l)) { s = isNoneTest(r); } else if (l.t.k == Ty.K.INST && r.t.k == Ty.K.INST || l.t.k == Ty.K.LIST && r.t.k == Ty.K.LIST) { - s = "(" + l.c + " == " + r.c + ")"; + // As objects: Java refuses `==` between two classes neither + // of which extends the other, and two such values are + // simply not the same object. + s = "((Object) " + l.c + " == (Object) " + r.c + ")"; } else if (op.startsWith("is")) { - s = "(" + box(l) + " == " + box(r) + ")"; + s = "((Object) " + box(l) + " == (Object) " + box(r) + ")"; } else { throw new Unsupported("== on " + l.t + ", " + r.t); } @@ -3230,15 +7289,39 @@ private E compare(Compare c) { boolean li = l.t.k == Ty.K.INT || l.t.k == Ty.K.BOOL; boolean ri = r.t.k == Ty.K.INT || r.t.k == Ty.K.BOOL; if ("in".equals(op) || "not in".equals(op)) { + String s; if (r.t.k == Ty.K.LIST) { - String s = "Typed.nzl(" + r.c + ").contains(" + box(l) + ")"; - return new E("in".equals(op) ? s : "!" + s, Ty.BOOL); + s = "Typed.nzl(" + r.c + ").contains(" + box(l) + ")"; + } else if (r.t.k == Ty.K.STR && !r.t.opt && l.charAt != null) { + // `rawdata[k] in _TAG_END` (html.parser): the char itself. + s = "Typed.inAt(" + r.c + ", " + l.charAt[0] + ", " + l.charAt[1] + ", " + l.charAt[2] + ")"; + } else if (r.t.k == Ty.K.STR && !r.t.opt && l.t.k == Ty.K.STR && !l.t.opt) { + s = "(" + r.c + ".indexOf(" + l.c + ") >= 0)"; + } else { + s = "Typed.in(" + box(l) + ", " + box(r) + ")"; } - throw new Unsupported("in " + r.t); + return new E("in".equals(op) ? s : "!" + s, Ty.BOOL); } if (l.t.k == Ty.K.BOOL && r.t.k == Ty.K.BOOL && ("==".equals(op) || "!=".equals(op))) { return new E("(" + l.c + " " + op + " " + r.c + ")", Ty.BOOL); } + if (l.t.k == Ty.K.INT && r.t.k == Ty.K.INT && l.lc != null && r.lc != null && l.pk == null && r.pk == null + && !l.t.opt && !r.t.opt) { + // Both at hand as Java longs (a length, a counter, a constant). + return new E("(" + l.lc + " " + op + " " + r.lc + ")", Ty.BOOL); + } + if (l.t.k == Ty.K.INT && r.t.k == Ty.K.INT && !l.t.opt && !r.t.opt && l.pk == null && r.pk == null + && (l.lc != null || l.ll != null && l.bg != null) && (r.lc != null || r.ll != null && r.bg != null) + && (l.ll != null || r.ll != null) && ORDERS_AND_EQ.contains(op)) { + // At least one side a long with a big-int overflow beside it: the + // longs compare in place unless an overflow is held. + String lv = l.lc != null ? l.lc : l.ll; + String rv = r.lc != null ? r.lc : r.ll; + String held = l.ll != null && r.ll != null ? l.bg + " == null && " + r.bg + " == null" + : (l.ll != null ? l.bg : r.bg) + " == null"; + String slow = "!=".equals(op) ? "!" + intOp("eq", box(l), box(r), rn) : intOp(pyCmp(op), box(l), box(r), rn); + return new E("(" + held + " ? " + lv + " " + op + " " + rv + " : " + slow + ")", Ty.BOOL); + } if (li && ri) { String f; switch (op) { @@ -3258,17 +7341,23 @@ private E compare(Compare c) { f = "eq"; break; case "!=": - return new E("!" + intOp("eq", box(l), box(r), c.comparators.get(0)), Ty.BOOL); + return new E("!" + intOp("eq", box(l), box(r), rn), Ty.BOOL); default: throw new Unsupported("compare " + op); } - return new E(intOp(f, box(l), box(r), c.comparators.get(0)), Ty.BOOL); + return new E(intOp(f, box(l), box(r), rn), Ty.BOOL); } if ((l.t.k == Ty.K.FLOAT || li) && (r.t.k == Ty.K.FLOAT || ri)) { return new E("(" + toD(l) + " " + op + " " + toD(r) + ")", Ty.BOOL); } if (l.t.k == Ty.K.STR && r.t.k == Ty.K.STR && !l.t.opt && !r.t.opt && ("==".equals(op) || "!=".equals(op))) { + String ch = l.charAt != null ? oneChar(r.c) : null; + if (ch != null) { + // `rawdata[k] == "/"`: the char compared in place. + String s = "Typed.charIs(" + l.charAt[0] + ", " + l.charAt[1] + ", " + l.charAt[2] + ", " + ch + ")"; + return new E("==".equals(op) ? s : "!" + s, Ty.BOOL); + } String s = l.c + ".equals(" + r.c + ")"; return new E("==".equals(op) ? s : "!" + s, Ty.BOOL); } @@ -3276,6 +7365,19 @@ private E compare(Compare c) { && !customCompare(l.t.cls) && !customCompare(r.t.cls)) { return new E("(" + l.c + " " + op + " " + r.c + ")", Ty.BOOL); } + if (("==".equals(op) || "!=".equals(op)) && plain(l.c) && plain(r.c) + && (l.t.k == Ty.K.STR && !l.t.opt && r.t.wide() + || r.t.k == Ty.K.STR && !r.t.opt && l.t.wide())) { + // A str against a value of no known type: compared in place when + // the value is a str, the generic comparison (a user __eq__ may + // answer anything) when not. Both sides are locals or constants, + // so neither branch reorders an effect. + String x = l.t.wide() ? l.c : r.c; + String k = l.t.wide() ? r.c : l.c; + String gen = "Py." + ("==".equals(op) ? "eq" : "ne") + "(" + l.c + ", " + r.c + ")"; + return new E("(" + x + " instanceof String ? Py.bool(" + ("==".equals(op) ? "" : "!") + k + ".equals(" + + x + ")) : " + gen + ")", Ty.OBJECT); + } String f; switch (op) { case "==": @@ -3299,19 +7401,50 @@ private E compare(Compare c) { default: throw new Unsupported("compare " + op); } - // Infer types this DYN too: a user comparison may answer anything. - return new E("Py." + f + "(" + box(l) + ", " + box(r) + ")", Ty.DYN); + // Infer types this OBJECT too: a user comparison may answer anything. + // Its truth is asked of the runtime directly: Py.eqBool and its + // siblings answer isTrue of the same call without boxing a bool. + String bl = box(l); + String br = box(r); + E res = new E("Py." + f + "(" + bl + ", " + br + ")", Ty.OBJECT); + res.tst = "Py." + f + "Bool(" + bl + ", " + br + ")"; + return res; } - private boolean customCompare(Layouts.Cls k) { - for (Layouts.Cls c : layouts.classes.values()) { - if (Infer.isSelfOrAncestor(k, c) || Infer.isSelfOrAncestor(c, k)) { - if (c.bodyNames.contains("__eq__") || c.bodyNames.contains("__ne__")) { - return true; - } + /// The Java char literal for a str literal `c` of one plain ASCII + /// printable char (no quote or backslash to escape), or null. + private static String oneChar(String c) { + if (c.length() == 3 && c.charAt(0) == '"' && c.charAt(2) == '"') { + char x = c.charAt(1); + if (x >= 32 && x < 127 && x != '\'' && x != '\\' && x != '"') { + return "'" + x + "'"; } } - return false; + return null; + } + + private static final Set ORDERS_AND_EQ = new HashSet(Arrays.asList("<", "<=", ">", ">=", "==", "!=")); + + private static String pyCmp(String op) { + switch (op) { + case "<": + return "lt"; + case "<=": + return "le"; + case ">": + return "gt"; + case ">=": + return "ge"; + default: + return "eq"; + } + } + + /// Whether an instance typed `k` may compare itself: a class above or + /// below it anywhere in the program binds `__eq__` or `__ne__`, or has a + /// base besides its compiled parent (see [#customTruth]). + private boolean customCompare(Layouts.Cls k) { + return hierarchyBinds(k, "__eq__", "__ne__"); } // ---- calls ----------------------------------------------------------- @@ -3320,8 +7453,29 @@ private List args(Call c) { if (!c.keywords.isEmpty()) { throw new Unsupported("keyword arguments"); } + return exprs(c.args); + } + + /// The arguments of `c`, a call of `f` from its parameter `from` on, + /// keywords bound to parameters as Infer bound them. + private List args(Call c, FunctionDef f, int from) { + List b = f == null ? null : Infer.staticArgs(c, f, from); + if (b == null) { + throw new Unsupported("keyword arguments"); + } + List r = exprs(b); + boundLists.put(r, Boolean.TRUE); + return r; + } + + /// The argument lists [#args(Call, FunctionDef, int)] bound to a + /// callee's parameters by name: only such a list reaches its keyword-only + /// ones (#argList). + private final Map, Boolean> boundLists = new IdentityHashMap, Boolean>(); + + private List exprs(List l) { List r = new ArrayList(); - for (Expr a : c.args) { + for (Expr a : l) { if (a instanceof Starred) { throw new Unsupported("starred argument"); } @@ -3338,17 +7492,33 @@ private String argList(Infer.Fn f, int from, List args) { throw new Unsupported("too many arguments"); } StringBuilder sb = new StringBuilder(); - List defs = f.def.args.defaults; + Arguments fa = f.def.args; + List defs = fa.defaults; + int np = fa.positional.size(); + if (!fa.kwonly.isEmpty() && args.size() > np - from && !boundLists.containsKey(args)) { + // A positional argument past the positional parameters: Python + // raises, it never fills a keyword-only one. + throw new Unsupported("positional argument for a keyword-only parameter"); + } for (int i = 0; i < n; i++) { E a; if (i < args.size()) { a = args.get(i); } else { - int d = defs.size() - (f.params.length - (from + i)); - if (d < 0 || !(defs.get(d) instanceof Constant)) { + // Keyword-only parameters follow the positional ones, each + // with its own default (Arguments#names). + int at = from + i; + Expr dv; + if (at >= np) { + dv = fa.vararg == null && at - np < fa.kwDefaults.size() ? fa.kwDefaults.get(at - np) : null; + } else { + int d = at - (np - defs.size()); + dv = d < 0 ? null : defs.get(d); + } + if (!(dv instanceof Constant)) { throw new Unsupported("missing argument"); } - a = expr(defs.get(d)); + a = expr(dv); } sb.append(i == 0 ? "" : ", ").append(arg(a, f.params[from + i])); } @@ -3464,10 +7634,97 @@ private E result(Infer.Fn f, String call) { } return new E("Typed.unret(" + call + ")", Ty.INT); } - return new E(call, f.ret.k == Ty.K.BOT ? Ty.DYN : f.ret); + if (f.guessRet != null) { + // An object back (Infer.Fn#guessRet): the typed value when it + // fits, as a pair. + return guessedElem(call, f.guessRet, null, 0); + } + return new E(call, f.ret.k == Ty.K.BOT ? Ty.OBJECT : f.ret); } + /// Builtins that consume a generator argument whole, at once: handing + /// them a list of the same items is not observable. + private static final Set EAGER = new HashSet(Arrays.asList( + "sum", "list", "tuple", "set", "frozenset", "sorted", "min", "max")); + + /// Generator expressions lowered as list comprehensions (`EAGER`). + private final Set eagerGens = java.util.Collections.newSetFromMap(new IdentityHashMap()); + + /// Builtins Infer types by their arguments (Infer#builtinValue). + private static final Set LOWERED_BUILTINS = new HashSet( + Arrays.asList("sorted", "min", "max", "sum", "round")); + + private static final Set FRAME_BUILTINS = new HashSet( + Arrays.asList("super", "globals", "locals", "vars", "dir")); + + /// Set while lowering a call [#call] wraps for its caller's module. + private boolean inModuleCall; + private E call(Call c) { + if (in.isCast(c, sc)) { + Layouts.Cls o = in.castClass(c, sc); + E v = expr(c.args.get(1)); + if (o != null) { + // A T, checked (Infer#castClass): TypeError, never a wrong object. + // Nullable whatever v was inferred to be: a cast answers None + // unchanged, and Py.castChecked hands it back as null. + Ty t = Ty.inst(o, true); + return new E("((" + jt(t) + ") Py.castChecked(" + box(v) + ", " + box(expr(c.args.get(0))) + "))", t); + } + // typing.cast(T, v) is v (Infer#isCast). + return v; + } + if (!inModuleCall && (c.func instanceof Name && "type".equals(((Name) c.func).id) && c.args.size() == 3 + && c.keywords.isEmpty() && binding("type") == Scope.Binding.BUILTIN + || Emitter.isClassFactory(c))) { + // __module__ comes from the caller's globals, as in the generic + // code (Emitter's call): Py.typeModule / Py.callerModule. + boolean type = c.func instanceof Name && "type".equals(((Name) c.func).id) && c.args.size() == 3; + inModuleCall = true; + E made; + try { + made = call(c); + } finally { + inModuleCall = false; + } + forgetPaths(); + return new E((type ? "Py.typeModule(" : "Py.callerModule(") + box(made) + ", M)", Ty.OBJECT); + } + if (c.func instanceof Name && FRAME_BUILTINS.contains(((Name) c.func).id) && c.args.isEmpty() + && binding(((Name) c.func).id) == Scope.Binding.BUILTIN) { + // Zero-argument super() needs the class and the first parameter, + // globals() the module: the generic code (genericFallback) has + // both. locals() and vars() name its frame, and stay generic. + throw new Unsupported(((Name) c.func).id); + } + if (Emitter.castCall(c)) { + // `cast(T, v)` (see Emitter.castCall). Both branches are + // conditional, so nothing of either is hoisted ahead of the test. + condDepth++; + try { + String f = box(expr(c.func)); + String v = box(expr(c.args.get(1))); + String r = "(" + f + " == StdModules.CAST ? " + v + " : Py.call(" + box(expr(c.func)) + ", " + + box(expr(c.args.get(0))) + ", " + box(expr(c.args.get(1))) + "))"; + forgetPaths(); + return new E(r, Ty.OBJECT); + } finally { + condDepth--; + } + } + if (c.args.size() == 1 && c.keywords.isEmpty() && c.args.get(0) instanceof Comp + && ((Comp) c.args.get(0)).kind == Comp.Kind.GENERATOR + && (c.func instanceof Name && EAGER.contains(((Name) c.func).id) + && binding(((Name) c.func).id) == Scope.Binding.BUILTIN && !em.moduleScopeHasStarImport() + || c.func instanceof Attribute && "join".equals(((Attribute) c.func).attr) + && ((Attribute) c.func).value instanceof Constant + && ((Constant) ((Attribute) c.func).value).kind == Constant.Kind.STR)) { + eagerGens.add((Comp) c.args.get(0)); + } + Comp extended = Infer.extendedGenerator(c); + if (extended != null && in.extendsEagerly(extended)) { + eagerGens.add(extended); + } E r = call0(c); if (pre != null && stmtPure && condDepth == 0 && (r.t.k == Ty.K.FLOAT || r.t.k == Ty.K.BOOL)) { // A pure call's result into a local, in evaluation order (see @@ -3482,7 +7739,148 @@ private E call(Call c) { return r; } + /// The hidden calls of a miss probe, as `Emitter.missIntrinsic` lowers + /// them. + private E missIntrinsic(Call c) { + String fn = ((Name) c.func).id; + if ("$probe".equals(fn)) { + return new E(probeRead(c.args.get(0), true), Ty.OBJECT); + } + if ("$unmiss".equals(fn) && plainProbe(c.args.get(0))) { + // A miss reaches here only when the handler's name was rebound: + // the re-read raises the real KeyError for it. + String m = box(expr(c.args.get(0))); + return dictRead("(" + m + " == Py.MISS ? " + probeRead(c.args.get(1), false) + " : " + m + ")", + expr(((Subscript) c.args.get(1)).value).t); + } + if ("$ismiss".equals(fn) && plainProbe(c.args.get(0))) { + return new E("(" + box(expr(c.args.get(0))) + " == Py.MISS && " + excRef(c.args.get(1)) + " == Py.KEY_ERROR)", + Ty.BOOL); + } + if ("$unmiss".equals(fn)) { + String m = box(expr(c.args.get(0))); + String v = "(" + m + " == Py.MISS ? " + probeRead(c.args.get(1), false) + " : Py.unmissed(" + m + "))"; + Expr x = c.args.get(1); + if (x instanceof Subscript && ((Subscript) x).value instanceof Name) { + E d = expr(((Subscript) x).value); + if (d.t.k == Ty.K.DICT) { + return dictRead(v, d.t); + } + } + return new E(v, Ty.OBJECT); + } + if ("$ismiss".equals(fn)) { + return new E("Py.isMiss(" + box(expr(c.args.get(0))) + ", " + excRef(c.args.get(1)) + ", " + + ("AttributeError".equals(((Name) c.args.get(1)).id) ? "Py.ATTRIBUTE_ERROR" : "Py.KEY_ERROR") + ")", + Ty.BOOL); + } + return null; + } + + /// `d[k] = d.get(k, c) + e` on a dict local, with a name for a key and + /// int constants for c and e: one probe of `d`, as the generic code + /// does it. False, emitting nothing, when the statement is not that. + private boolean dictCount(Assign a, StringBuilder b, int ind) { + if (a.targets.size() != 1 || !(a.targets.get(0) instanceof Subscript) || !(a.value instanceof BinOp)) { + return false; + } + Subscript t = (Subscript) a.targets.get(0); + BinOp op = (BinOp) a.value; + if (!"+".equals(op.op) || !(t.value instanceof Name) || !(t.index instanceof Name) || !(op.left instanceof Call) + || intConstant(op.right) == null) { + return false; + } + Call c = (Call) op.left; + if (!(c.func instanceof Attribute) || !"get".equals(((Attribute) c.func).attr) + || !(((Attribute) c.func).value instanceof Name) || c.args.size() != 2 || !c.keywords.isEmpty() + || !(c.args.get(0) instanceof Name) || intConstant(c.args.get(1)) == null) { + return false; + } + String d = ((Name) t.value).id; + String k = ((Name) t.index).id; + if (!d.equals(((Name) ((Attribute) c.func).value).id) || !k.equals(((Name) c.args.get(0)).id)) { + return false; + } + E de = expr(t.value); + if (de.t.k != Ty.K.DICT || de.t.opt) { + return false; + } + indent(b, ind); + b.append("Py.dictCount(").append(de.c).append(", ").append(box(expr(t.index))).append(", ") + .append(box(expr(c.args.get(1)))).append(", ").append(box(expr(op.right))).append(");\n"); + return true; + } + + /// `c`, a read of a dict of type `d`, as the type its values have. + private E dictRead(String c, Ty d) { + Ty vt = in.dictVal(d); + if (vt.k == Ty.K.BOT) { + throw new Unsupported("value of an empty dict"); + } + if (vt.k != Ty.K.INT && in.guessedSite(d)) { + return guessedElem(c, vt, null, 0); + } + return vt.wide() || vt.isObject() ? new E(c, vt.wide() ? Ty.OBJECT : vt) : new E(unbox(c, vt), vt); + } + + private String probeRead(Expr e, boolean probe) { + if (e instanceof Attribute) { + Attribute a = (Attribute) e; + if (a.value instanceof Name && scalars.containsKey(((Name) a.value).id)) { + return scalarProbeRead(((Name) a.value).id, a.attr, probe); + } + return em.attrSite(a.attr) + (probe ? ".getOrMiss(" : ".get(") + box(expr(a.value)) + ")"; + } + Subscript s = (Subscript) e; + if (probe && dictProbe(s)) { + E k = expr(s.index); + return "Typed.dprobe(" + expr(s.value).c + ", " + (k.lc != null ? k.lc : box(k)) + ")"; + } + return (probe ? "Py.getitemOrMiss(" : "Py.getitem(") + box(expr(s.value)) + ", " + box(expr(s.index)) + ")"; + } + + /// `d[k]` on a dict local that is never None: a plain `PyDict`, whose + /// probe answers the value or the bare miss sentinel. + private boolean dictProbe(Subscript s) { + if (!(s.value instanceof Name) || binding(((Name) s.value).id) != Scope.Binding.LOCAL) { + return false; + } + Ty t = localType(((Name) s.value).id); + return t.k == Ty.K.DICT && !t.opt; + } + + /// Whether hidden local `m` (a miss probe's) only ever holds a + /// [#dictProbe]: the value itself, or `Py.MISS`. + private boolean plainProbe(Expr m) { + if (!(m instanceof Name) || soleStores == null) { + return false; + } + Expr v = soleStores.get(((Name) m).id); + return v instanceof Call && ((Call) v).func instanceof Name && "$probe".equals(((Name) ((Call) v).func).id) + && ((Call) v).args.get(0) instanceof Subscript && dictProbe((Subscript) ((Call) v).args.get(0)); + } + private E call0(Call c) { + if (Emitter.nextOrStop(c)) { + return new E("Builtins.nextOrStop(" + box(expr(c.args.get(0))) + ", " + box(expr(c.args.get(1))) + ")", + Ty.OBJECT); + } + if (c.func instanceof Lambda) { + E r = inlineLambda((Lambda) c.func, c); + if (r != null) { + return r; + } + } + if (c.func instanceof Name && ((Name) c.func).id.startsWith("$")) { + E miss = missIntrinsic(c); + if (miss != null) { + return miss; + } + } + if (Emitter.getattrDefault(c) && binding("getattr") == Scope.Binding.BUILTIN && !em.moduleScopeHasStarImport()) { + Attribute probe = new Attribute(c.args.get(0), ((Constant) c.args.get(1)).text); + return new E("Py.orDefault(" + probeRead(probe, true) + ", " + box(expr(c.args.get(2))) + ")", Ty.OBJECT); + } if (c.args.size() == 1 && c.args.get(0) instanceof Name && codePoints.containsKey(((Name) c.args.get(0)).id) && ordOf(c, ((Name) c.args.get(0)).id)) { String l = "((long) " + codePoints.get(((Name) c.args.get(0)).id) + ")"; @@ -3492,15 +7890,27 @@ && ordOf(c, ((Name) c.args.get(0)).id)) { && scalars.containsKey(((Name) ((Attribute) c.func).value).id)) { String n = ((Name) ((Attribute) c.func).value).id; Layouts.Cls o = Layouts.resolver(scalars.get(n).k, ((Attribute) c.func).attr); - return scalarRead(n, getterField(in.fns.get(o.typable.get(((Attribute) c.func).attr)))); + return scalarRead(n, getterField(in.emitFns().get(o.typable.get(((Attribute) c.func).attr)))); } if (c.func instanceof Name) { String n = ((Name) c.func).id; - Scope.Binding b = sc.resolve(n); + Scope.Binding b = binding(n); if (b == Scope.Binding.GLOBAL) { Infer.Fn f = in.globalFns.get(n); + if (f != null && (in.doors.contains(c) || substObject(c)) && !doorFits(f, c, 0)) { + // An argument is not known to be what a parameter's + // annotation names (Infer.callFn): the function object + // is called, and its guard picks the version to run. + Ty rt = in.type(c, cur, sc); + String g = genericCall("g(" + em.slot(n) + ")", c).c; + if (rt.k != Ty.K.INT && in.guessed(c)) { + return guessedElem(g, rt, null, 0); + } + return rt.wide() || rt.k == Ty.K.BOT || rt.isObject() ? new E(g, rt.k == Ty.K.BOT ? Ty.OBJECT : rt) + : new E(unbox(g, rt), rt); + } if (f != null) { - List a = args(c); + List a = args(c, f.def, 0); calls.add(f); IntRanges.Iv[] lp = longParams.get(f); String call = lp != null && IntRanges.within(IntRanges.longArgs(f, sites.get(c)), lp) @@ -3517,9 +7927,19 @@ && ordOf(c, ((Name) c.args.get(0)).id)) { E r = result(f, call); return site == null || site.k == r.t.k ? r : relabel(r, site); } - Layouts.Cls k = in.globalClasses.get(n); + Layouts.Cls k = in.emitClass(n); + if (k != null && (in.doors.contains(c) || substObject(c)) && in.newMethod(k) == null && !k.callConstructed() + && !initFits(k, c)) { + // An argument the typed __init__ cannot be sure of + // (Infer.callFn): the class is called as generic code + // calls it, and __init__'s guard picks the version. + return new E(unbox(genericCall("g(" + em.slot(n) + ")", c).c, Ty.inst(k, false)), Ty.inst(k, false)); + } if (k != null) { - return construct(k, args(c)); + Layouts.Cls io = Layouts.resolver(k, "__init__"); + FunctionDef ii = io == null ? null : io.typable.get("__init__"); + return construct(k, c.keywords.isEmpty() && (ii == null || ii.args.kwonly.isEmpty()) ? args(c) + : args(c, ii, 1)); } } if (b == Scope.Binding.BUILTIN && !em.moduleScopeHasStarImport() && "list".equals(n) @@ -3538,18 +7958,58 @@ && ordOf(c, ((Name) c.args.get(0)).id)) { if (x.t.k == Ty.K.LIST) { return new E("Typed.copy(" + x.c + ")", lt); } - throw new Unsupported("list of " + x.t); + return new E("Typed.listOf(" + box(x) + ")", lt); } if (b == Scope.Binding.BUILTIN && !em.moduleScopeHasStarImport()) { + if (("any".equals(n) || "all".equals(n)) && c.keywords.isEmpty() && c.args.size() == 1 + && c.args.get(0) instanceof Comp && ((Comp) c.args.get(0)).kind == Comp.Kind.GENERATOR) { + E r = anyAll(c, n); + if (r != null) { + return r; + } + } if (TYPED_BUILTINS.contains(n) && c.keywords.isEmpty()) { E r = builtin(n, args(c)); if (r != null) { return r; } } - return genericCall(em.builtinRef(n), c); + if ("isinstance".equals(n) && c.args.size() == 2 && c.keywords.isEmpty() + && !(c.args.get(0) instanceof Starred) && !(c.args.get(1) instanceof Starred)) { + // A Java boolean: no argument array, no bool to box and test. + if (c.args.get(1) instanceof TupleExpr) { + List ts = ((TupleExpr) c.args.get(1)).elts; + if (ts.size() >= 2 && ts.size() <= 8 && !Infer.hasStarred(ts)) { + // `isinstance(x, (A, B))`: no tuple built (Py.isinstanceAny). + StringBuilder r = new StringBuilder("Py.isTrue(Py.isinstanceAny(").append(em.builtinRef(n)) + .append(", ").append(box(expr(c.args.get(0)))); + for (Expr t : ts) { + r.append(", ").append(box(expr(t))); + } + return new E(r.append("))").toString(), Ty.BOOL); + } + } + return new E("Py.isinstanceB(" + em.builtinRef(n) + ", " + box(expr(c.args.get(0))) + ", " + + box(expr(c.args.get(1))) + ")", Ty.BOOL); + } + if ("next".equals(n) && (c.args.size() == 1 || c.args.size() == 2) && c.keywords.isEmpty() + && !(c.args.get(0) instanceof Starred) && !(c.args.get(c.args.size() - 1) instanceof Starred)) { + return new E("Py.nextB(" + em.builtinRef(n) + ", " + box(expr(c.args.get(0))) + + (c.args.size() == 2 ? ", " + box(expr(c.args.get(1))) : "") + ")", Ty.OBJECT); + } + E g = genericCall(em.builtinRef(n), c); + Ty fixed = Infer.fixedReturn(n); + if (fixed == null && LOWERED_BUILTINS.contains(n)) { + // What Infer#builtinValue answers for it, over values the + // runtime orders and adds as primitives. + Ty rt = in.type(c, cur, sc); + fixed = rt.wide() || rt.k == Ty.K.BOT || rt.opt ? null : rt; + } + return fixed == null ? g : new E(unbox(g.c, fixed), fixed); } - throw new Unsupported("call of " + n); + // Any other callable a name holds: a class without a layout, + // an imported function, a parameter. + return genericCall(box(name((Name) c.func)), c); } if (in.isMathCall(c, sc)) { String fn = ((Attribute) c.func).attr; @@ -3567,19 +8027,53 @@ && ordOf(c, ((Name) c.args.get(0)).id)) { String in0 = inlineMath(fn, ds); return new E(in0 != null ? "(" + in0 + " : " + sb + ")" : sb.toString(), Ty.FLOAT); } + if (c.func instanceof Attribute) { + Ty nr = in.nativeCalls.get(c); + if (nr != null) { + // A library function of declared result (Infer#NATIVE_RET), + // called as any function and its answer unboxed. + return new E(unbox(genericCall(box(expr(c.func)), c).c, nr), nr); + } + } + if (c.func instanceof Attribute && in.superCall(c) != null) { + // `super().m(args)` as Infer resolved it: the parent's method, + // called directly with self first. + Infer.Fn f = in.superCall(c); + Name self = new Name(cur.names.get(0)); + self.line = c.line; + self.col = c.col; + List all = new ArrayList(); + all.add(expr(self)); + all.addAll(args(c)); + calls.add(f); + return result(f, typed.get(f) + "(" + argList(f, 0, all) + ")"); + } if (c.func instanceof Attribute) { Attribute a = (Attribute) c.func; - if (a.value instanceof Name && in.globalClasses.containsKey(((Name) a.value).id) - && sc.resolve(((Name) a.value).id) == Scope.Binding.GLOBAL) { - Layouts.Cls k = in.globalClasses.get(((Name) a.value).id); + Layouts.Cls ck = in.emitCalledClass(a.value, sc); + boolean local = a.value instanceof Name && in.globalClasses.containsKey(((Name) a.value).id) + && binding(((Name) a.value).id) == Scope.Binding.GLOBAL; + Layouts.Cls cr = ck == null ? null : Layouts.resolver(ck, a.attr); + FunctionDef cm = cr == null ? null : cr.typable.get(a.attr); + if (ck != null && !in.doors.contains(c) && (local || !in.open.contains(ck) && cm != null && in.emitFns().containsKey(cm))) { + // As Infer resolved it: a class of this module, or an + // imported one whose method is this module's. Another + // module's method is called generically, through its door. + Layouts.Cls k = ck; Layouts.Cls o = Layouts.resolver(k, a.attr); FunctionDef m = o == null ? null : o.typable.get(a.attr); if (m == null) { throw new Unsupported("class attribute call"); } - Infer.Fn f = in.fns.get(m); + Infer.Fn f = in.emitFns().get(m); + if (f == null) { + // A method of a class merged into another's layout + // with no typed body of its own here: called through + // the MRO, generically. + throw new Unsupported("class attribute call " + a.attr); + } calls.add(f); - return result(f, typed.get(f) + "(" + argList(f, 0, args(c)) + ")"); + return result(f, typed.get(f) + "(" + argList(f, 0, args(c, m, 0)) + ")"); } E r = expr(a.value); if (r.t.k == Ty.K.LIST && !r.t.opt && "extend".equals(a.attr) && c.keywords.isEmpty() @@ -3592,35 +8086,129 @@ && ordOf(c, ((Name) c.args.get(0)).id)) { return new E("Typed.extendRepeat(" + r.c + ", " + box(left ? first : second) + ", " + box(left ? second : first) + ")", Ty.NONE); } - List args = args(c); + if (r.t.k == Ty.K.LIST && !r.t.opt && "extend".equals(a.attr) && c.keywords.isEmpty() + && c.args.size() == 1 && c.args.get(0) instanceof ListExpr + && (((ListExpr) c.args.get(0)).elts.size() == 2 || ((ListExpr) c.args.get(0)).elts.size() == 3) + && !Infer.hasStarred(((ListExpr) c.args.get(0)).elts)) { + // `l.extend([a, b, c])` (markdownify's process_tag): appended + // in place, no list of them made. + List es = ((ListExpr) c.args.get(0)).elts; + StringBuilder s = new StringBuilder("Typed.extend").append(es.size()).append('(').append(r.c); + for (Expr x : es) { + s.append(", ").append(box(expr(x))); + } + return new E(s.append(')').toString(), Ty.NONE); + } + List args; + if (!c.keywords.isEmpty() && r.t.k == Ty.K.INST) { + // One method it can be: keywords bound to its parameters, + // as Infer bound them. + List b = Infer.sharedArgs(c, in.candidates(r.t.cls, a.attr)); + if (b == null) { + throw new Unsupported("keyword arguments"); + } + args = exprs(b); + } else { + args = args(c); + } if (r.t.k == Ty.K.LIST && !r.t.opt) { return listMethod(r, a.attr, args); } + if (r.t.k == Ty.K.STR && !r.t.opt && Infer.splitCall(a.attr, types(args), c)) { + Integer site = in.siteOf.get(c); + if (site != null) { + return new E("Typed.split(" + r.c + ", " + (args.isEmpty() ? "Py.NONE" : args.get(0).c) + ")", + Ty.list(new int[] {site.intValue()}, false)); + } + } + if (Infer.codecCall(r.t, a.attr, types(args), c)) { + String enc = args.isEmpty() ? "null" : args.get(0).c; + String err = args.size() < 2 ? "null" : args.get(1).c; + return "encode".equals(a.attr) ? new E("Typed.encode(" + r.c + ", " + enc + ", " + err + ")", Ty.BYTES) + : new E("Typed.decode(" + r.c + ", " + enc + ", " + err + ")", Ty.STR); + } + if (r.t.k == Ty.K.STR && !r.t.opt && c.keywords.isEmpty() && !Infer.hasStarred(c.args)) { + E s = strMethod(r, a.attr, args); + if (s != null) { + return s; + } + s = strBoundedDyn(r, a.attr, args); + if (s != null) { + return s; + } + } + if (r.t.k == Ty.K.DICT && !r.t.opt && "get".equals(a.attr) && c.keywords.isEmpty() + && !Infer.hasStarred(c.args) && (args.size() == 1 || args.size() == 2)) { + E def = args.size() == 2 ? args.get(1) : null; + Ty vt = Ty.join(in.dictVal(r.t), def == null ? Ty.NONE : def.t); + String g = "Typed.dgetd(" + r.c + ", " + box(args.get(0)) + ", " + (def == null ? "Py.NONE" : box(def)) + ")"; + if (vt.k == Ty.K.BOT || vt.wide() || vt.opt) { + return new E(g, Ty.OBJECT); + } + if (in.guessedSite(r.t)) { + // Before the object case: an element of a guessed + // dict is a guess whatever it is held as, and a value + // typed an instance is unboxed unchecked downstream. + return guessedElem(g, vt, null, 0); + } + if (vt.isObject()) { + return new E(g, vt); + } + return new E(unbox(g, vt), vt); + } if (r.t.k != Ty.K.INST) { String k = "get".equals(a.attr) && args.size() == 1 && c.keywords.isEmpty() ? intKey(args.get(0)) : null; if (k != null) { // A plain dict looks an int key up without boxing it. - return new E("Typed.dget(" + em.attrSite(a.attr) + ", " + box(r) + ", " + k + ")", Ty.DYN); + return new E("Typed.dget(" + em.attrSite(a.attr) + ", " + box(r) + ", " + k + ")", Ty.OBJECT); + } + return slotResult(c, siteCall(r, a.attr, args)); + } + if ((in.doors.contains(c) || substObject(c)) && !methodDoorFits(r.t.cls, a.attr, c)) { + // An argument nothing knows (Infer.callFn): the method is + // called as generic code calls it, and its guard picks the + // version to run. + Ty rt = in.type(c, cur, sc); + E id = inlineDoor(r, a, c, args, rt); + if (id != null) { + return id; + } + if (!c.keywords.isEmpty() && !boundPositionally(r.t.cls, a.attr)) { + throw new Unsupported("keyword door call " + a.attr); + } + String g = siteCall(r, a.attr, args).c; + if (rt.k != Ty.K.INT && in.guessed(c)) { + return guessedElem(g, rt, null, 0); } - return siteCall(r, a.attr, args); + return rt.wide() || rt.k == Ty.K.BOT || rt.isObject() ? new E(g, rt.k == Ty.K.BOT ? Ty.OBJECT : rt) + : new E(unbox(g, rt), rt); } List cand = in.candidates(r.t.cls, a.attr); - if (cand == null) { - throw new Unsupported("method " + a.attr); + E xc = cand != null && cand.size() == 1 ? foreignCall(r, a.attr, cand.get(0), args) : null; + if (xc != null) { + return xc; + } + if (cand == null || !localRoot(r.t.cls)) { + // A class whose compiled base is another module's has no + // typed virtual methods of this module's: called as the + // generic code calls it, the rest of the expression typed. + if (!c.keywords.isEmpty() || Infer.hasStarred(c.args)) { + throw new Unsupported("method " + a.attr); + } + return slotResult(c, siteCall(r, a.attr, args)); } String recv = nz(r, a.attr); Layouts.Cls res = Layouts.resolver(r.t.cls, a.attr); if (cand.size() == 1 && res != null && res.typable.get(a.attr) == cand.get(0)) { //NOPMD CompareObjectsWithEquals - identity is meant - Infer.Fn f = in.fns.get(cand.get(0)); - String gf = getterField(f); - if (gf != null && args.isEmpty()) { - // `return self.f`: the field, read in place of the call. - E rr = r.t.opt ? new E(recv, r.t.nonNone()) : r; - return fieldRead(rr, gf); - } + // Not the getter's field in place of the call: a class built at + // run time may override the getter (PyType.borrowLayout), which + // the bridge asks about first. + Infer.Fn f = in.emitFns().get(cand.get(0)); calls.add(f); + bridged.add(f); + patchedSite(f.def.name); String al = argList(f, 1, args); - return result(f, typed.get(f) + "(" + recv + (al.isEmpty() ? "" : ", " + al) + ")"); + return result(f, "pt_" + typed.get(f) + "(" + recv + (al.isEmpty() ? "" : ", " + al) + ")"); } String key = a.attr + "/" + args.size(); List g = groups.get(key); @@ -3628,16 +8216,17 @@ && ordOf(c, ((Name) c.args.get(0)).id)) { throw new Unsupported("no group " + key); } for (FunctionDef m : cand) { - if (!g.contains(in.fns.get(m))) { + if (!g.contains(in.emitFns().get(m))) { throw new Unsupported("arity mismatch " + key); } } callsGroups.add(key); + patchedSite(a.attr); Infer.Fn f = g.get(0); String al = argList(f, 1, args); return result(f, recv + ".tv_" + Emitter.mangle(a.attr) + "_" + args.size() + "(" + al + ")"); } - throw new Unsupported("call"); + return genericCall(box(expr(c.func)), c); } /// The guard and the `Math` call of `math.fn(ds)` when its domain can be @@ -3676,20 +8265,61 @@ private static String intKey(E x) { /// `r.attr(args)` as the generic code calls a method: through an inline /// cache, with an untyped result. + /// A call dispatched by name (`g`) as the typed value Infer proved it + /// returns: a method name only program methods answer returns what + /// they return (Infer#closedName), whatever the receiver. + /// A call of a Java builtin the pass types ([BuiltinSigs]): its generic + /// result, converted (checked) to that type. + private E builtinResult(Call c, E g) { + if (!g.t.wide() || !in.builtinCalls.contains(c)) { + return g; + } + Ty rt = in.type(c, cur, sc); + if (rt.wide() || rt.k == Ty.K.BOT) { + return g; + } + return rt.isObject() ? new E(box(g), rt) : new E(unbox(box(g), rt), rt); + } + + private E slotResult(Call c, E g) { + if (!in.slotCall(c)) { + return g; + } + Ty rt = in.type(c, cur, sc); + if (rt.wide() || rt.k == Ty.K.BOT) { + return g; + } + return rt.isObject() ? new E(g.c, rt) : new E(unbox(g.c, rt), rt); + } + private E siteCall(E r, String attr, List args) { + // An instance of a known class too: a door call (an argument of no + // known type) on a typed `self` reached the method through the + // inline cache, where the generic body's guarded dispatch calls it + // directly (bs4's `SoupStrainer.match` calling `self.matches_tag`). + if (r.t.wide() || r.t.k == Ty.K.INST) { + StringBuilder da = new StringBuilder(); + for (E x : args) { + da.append(", ").append(box(x)); + } + String d = em.dispatchCall(attr, args.size(), box(r), da.toString()); + if (d != null) { + return new E(d, Ty.OBJECT); + } + } String site = em.attrSite(attr); StringBuilder a = new StringBuilder(box(r)); for (E x : args) { a.append(", ").append(box(x)); } - if (args.size() <= 6) { - return new E(site + ".call" + args.size() + "(" + a + ")", Ty.DYN); + if (args.size() <= 13) { + return new E(site + ".call" + args.size() + "(" + a + ")", Ty.OBJECT); } StringBuilder arr = new StringBuilder(); for (E x : args) { arr.append(arr.length() == 0 ? "" : ", ").append(box(x)); } - return new E(site + ".callN(" + box(r) + ", new Object[] {null, " + arr + "})", Ty.DYN); + return new E(site + ".callN(" + box(r) + ", new Object[] {null, " + arr + "})", Ty.OBJECT); } /// The field `f` returns when its body is only `return self.` @@ -3704,18 +8334,295 @@ private String getterField(Infer.Fn f) { || !((Name) ((Attribute) v).value).id.equals(f.names.get(0))) { return null; } - String attr = ((Attribute) v).attr; - Layouts.Cls o = Infer.fieldOwner(f.cls, attr); - return o != null && in.definitelySet(o, attr) ? attr : null; + String attr = ((Attribute) v).attr; + Layouts.Cls o = Infer.fieldOwner(f.cls, attr); + return o != null && in.definitelySet(o, attr) ? attr : null; + } + + /// `r.attr` read generically: behind the program's field guard when + /// `r` is held as a plain Object (`Emitter.guardedGet`), else the site. + private String attrGet(E r, String attr) { + if (r.t.wide()) { + String s = shadowGet(r.c, attr); + return s != null ? s : em.guardedGet(attr, box(r)); + } + return em.attrSite(attr) + ".get(" + box(r) + ")"; + } + + /// Whether call `c` of `f` passes, positionally, exactly what the typed + /// version takes: each argument where a parameter of type OBJECT (an + /// Object the version accepts as it is) stands, or of the parameter's + /// own type. Such a call needs no door (Infer#callFn sends a call with + /// a OBJECT argument through the function object so its guard can pick a + /// version), and markdownify's `should_remove_whitespace_inside(node)` + /// paid a generic call and a guard for a version taking Object. + private boolean doorFits(Infer.Fn f, Call c, int from) { + if (typed.get(f) == null && in.emitFns().containsKey(f.def) || !c.keywords.isEmpty() || c.args.size() + from != f.params.length + || Infer.hasStarred(c.args)) { + return false; + } + for (int i = 0; i < c.args.size(); i++) { + Ty p = f.params[from + i]; + // A guess (a guarded field, a guessed element) is of its type + // only when its check passes: the typed version is entered + // through the guard, never a checked conversion that raises + // where the guess was wrong. yaml's `_analyze_scalar(node.value)` + // converted a str to a list. + if (!p.wide() && (!p.equals(in.type(c.args.get(i), cur, sc)) || objectSubst(c.args.get(i)) + || in.guessed(c.args.get(i)))) { + return false; + } + } + return true; + } + + /// Whether the version of an expression being written holds `x` as an + /// object: the generic half of a split over a guess (see [#split]), + /// taken when the guess failed, so the value is of no type it vouches for. + private boolean objectSubst(Expr x) { + E s = leafSubst.get(x); + return s != null && s.t.wide(); + } + + /// Whether any argument of `c` is such an object ([#objectSubst]): a + /// typed callee is then entered through its guard, never a checked + /// conversion that raises where the guess was wrong. + private boolean substObject(Call c) { + for (Expr x : c.args) { + if (objectSubst(x instanceof Starred ? ((Starred) x).value : x)) { + return true; + } + } + for (Keyword kw : c.keywords) { + if (objectSubst(kw.value)) { + return true; + } + } + return false; + } + + /// Whether the typed `__init__` of `k` takes `c`'s arguments as written. + private boolean initFits(Layouts.Cls k, Call c) { + Layouts.Cls io = Layouts.resolver(k, "__init__"); + FunctionDef d = io == null ? null : io.typable.get("__init__"); + Infer.Fn f = d == null ? null : in.anyFn(d); + return f != null && !in.doors.contains(c) && doorFits(f, c, 1); + } + + /// [#doorFits] for every method a call of `attr` on a `cls` may run. + /// A door call (see Infer.callFn) of the one method `r.attr` can run, + /// with the guard in line: each argument of no known type is checked + /// against its parameter, the typed method called when every one fits + /// and the generic call made when not. Through the method's own guard + /// every call of a recursion over values the build cannot type was a + /// dictionary dispatch (markdownify's process_tag over its children). + /// Null when it cannot be written so. + private E inlineDoor(E r, Attribute a, Call c, List args, Ty rt) { + if (pre == null || !stmtPure || condDepth != 0 || r.t.k != Ty.K.INST || !plain(r.c) + || Infer.hasStarred(c.args)) { + return null; + } + List cand = in.candidates(r.t.cls, a.attr); + Layouts.Cls res = Layouts.resolver(r.t.cls, a.attr); + if (cand == null || cand.size() != 1 || res == null || res.typable.get(a.attr) != cand.get(0) //NOPMD CompareObjectsWithEquals - identity is meant + || !localRoot(r.t.cls) || !boundPositionally(r.t.cls, a.attr)) { + return null; + } + Infer.Fn f = in.emitFns().get(cand.get(0)); + if (f == null || typed.get(f) == null || f.ret.k == Ty.K.INT || args.size() + 1 != f.params.length) { + return null; + } + StringBuilder cond = new StringBuilder(); + List typedArgs = new ArrayList(args.size()); + for (int i = 0; i < args.size(); i++) { + E x = args.get(i); + Ty pt = f.params[1 + i]; + boolean need = !pt.wide() && pt.k != Ty.K.BOT && (x.t.wide() || x.gview != null || objectSubst(c.args.size() > i ? c.args.get(i) : null)); + if (!need) { + if (!plain(x.c) && !literal(x.c) && !x.c.startsWith("Py.") || x.t.k == Ty.K.INT && x.ll != null) { + return null; + } + typedArgs.add(x); + continue; + } + if (pt.k == Ty.K.INT || pt.k == Ty.K.FLOAT) { + return null; + } + String o = fresh(); + indent(pre, preInd); + pre.append("Object ").append(o).append(" = ").append(box(x)).append(";\n"); + cond.append(cond.length() == 0 ? "" : " && ").append(fits(o, pt)); + typedArgs.add(new E(o, Ty.OBJECT)); + args = new ArrayList(args); + args.set(i, new E(o, Ty.OBJECT)); + typedArgs.set(i, new E(unbox(o, pt), pt)); + } + if (cond.length() == 0) { + return null; + } + calls.add(f); + bridged.add(f); + patchedSite(f.def.name); + E t = result(f, "pt_" + typed.get(f) + "(" + r.c + (typedArgs.isEmpty() ? "" : ", " + argList(f, 1, typedArgs)) + ")"); + String g = siteCall(r, a.attr, args).c; + String both = "(" + cond + " ? " + box(t) + " : " + g + ")"; + return rt.wide() || rt.k == Ty.K.BOT || rt.isObject() ? new E(both, rt.k == Ty.K.BOT ? Ty.OBJECT : rt) + : new E(unbox(both, rt), rt); + } + + /// Whether every method `cls.attr` may be takes only positional + /// parameters: a call with keywords, bound to them at build time, can + /// then be made generically with the bound list. + private boolean boundPositionally(Layouts.Cls cls, String attr) { + List cand = in.candidates(cls, attr); + if (cand == null) { + return false; + } + for (FunctionDef m : cand) { + if (!m.args.kwonly.isEmpty() || m.args.vararg != null || m.args.kwarg != null) { + return false; + } + } + return true; + } + + private boolean methodDoorFits(Layouts.Cls cls, String attr, Call c) { + List cand = in.candidates(cls, attr); + if (cand == null || cand.isEmpty() || !localRoot(cls) && cand.size() != 1) { + return false; + } + for (FunctionDef m : cand) { + Infer.Fn f = in.anyFn(m); + if (f == null || !doorFits(f, c, 1)) { + return false; + } + } + return true; + } + + /// Calls of other modules' typed methods, by marker (see [#foreignCall]). + private final Map foreign = new HashMap(); + private final Map foreignFn = new HashMap(); + private final Map foreignHome = new HashMap(); + /// Markers are written and resolved by the same emitter (#members), so + /// they need to be unique only within it. + private int foreignIds; + + /// `r.attr(args)` where the method is `m`, defined by a base class of + /// another module and the only one an instance can run + /// (Infer#candidates): that module's typed copy, called directly when + /// the class was not patched at run time. Whether that module kept a + /// typed copy is known only once every module is planned, so the call + /// is a marker until [#members] writes it, else the generic call it + /// stands for -- its result held as the typed copy returns it, which + /// the generic body returns too for the same arguments. + private E foreignCall(E r, String attr, FunctionDef m, List args) { + Layouts.Cls res = Layouts.resolver(r.t.cls, attr); + Infer.Fn f = in.anyFn(m); + if (res == null || res.home == in.layouts || res.typed == null || f == null || f.guessRet != null //NOPMD CompareObjectsWithEquals - identity is meant + || res.typable.get(attr) != m || r.t.opt) { //NOPMD CompareObjectsWithEquals - identity is meant + return null; + } + String recv = r.c; + if (!plain(recv)) { + if (pre == null || !stmtPure || condDepth != 0) { + return null; + } + String tv = fresh(); + indent(pre, preInd); + pre.append(jt(r.t)).append(' ').append(tv).append(" = ").append(recv).append(";\n"); + recv = tv; + } + E rv = new E(recv, r.t); + String al = argList(f, 1, args); + String g = siteCall(rv, attr, args).c; + Ty rt = f.ret.k == Ty.K.BOT ? Ty.OBJECT : f.ret; + String fb = rt.k == Ty.K.INT ? "Typed.retObj(" + g + ")" : "Object".equals(jt(rt)) ? g : unbox(g, rt); + String id = "XC" + (foreignIds++) + "_"; + String cls = res.ref.substring(0, res.ref.lastIndexOf('.')); + foreign.put(id, new String[] {recv, cls, al, fb}); + foreignFn.put(id, f); + foreignHome.put(id, res.typed); + return result(f, "/*" + id + "*/" + fb + "/*" + id + "*/"); + } + + /// `b` with every marker of [#foreignCall] written: the direct call + /// where the defining module kept its typed copy, else the generic one. + private String resolveForeign(String b) { + if (foreign.isEmpty() || b.indexOf("/*XC") < 0) { + return b; + } + StringBuilder o = new StringBuilder(b.length() + 64); + int i = 0; + while (true) { + int s = b.indexOf("/*XC", i); + if (s < 0) { + break; + } + int e = b.indexOf("*/", s); + String id = b.substring(s + 2, e); + String close = "/*" + id + "*/"; + int end = b.indexOf(close, e + 2); + String[] x = foreign.get(id); + String name = foreignHome.get(id).typed.get(foreignFn.get(id)); + o.append(b, i, s); + // An argument may hold another such call, written the same way. + String fb = resolveForeign(x[3]); + if (name == null) { + o.append(fb); + } else { + String al = resolveForeign(x[2]); + o.append('(').append(x[0]).append(".cls.patched ? ").append(fb).append(" : ").append(x[1]).append('.') + .append(name).append('(').append(x[0]).append(al.isEmpty() ? "" : ", " + al).append("))"); + } + i = end + close.length(); + } + return o.append(b, i, b.length()).toString(); } - /// Field `attr` of `r`. - private E fieldRead(E r, String attr) { - Ty ft = fieldTy(r, attr); - if (ft.k == Ty.K.INT && typedField(owner(r, attr), attr) != null) { - return intField(r, attr); + /// Per typed function: its locals and the class their field reads name + /// most (`ShadowTypes`, as the generic body keeps a typed copy of). + private final Map> shadows = new HashMap>(); + + /// `v.attr` for the plain local `v` of no known type whose field reads + /// point at one class: that class's field behind an `instanceof`, the + /// generic read otherwise. A field read past every guard the program + /// can afford (`bs4`'s `Tag.name`, a name a dozen classes declare) + /// otherwise always went through the site -- markdownify's `node`. + private String shadowGet(String v, String attr) { + if (cur == null || cur.def.body == null || !v.startsWith("v_")) { + return null; + } + Map sh = shadows.get(cur); + if (sh == null) { + sh = new HashMap(); + for (Map.Entry e : ShadowTypes.of(cur.def.body, em.fieldOwners()).entrySet()) { + sh.put(var(e.getKey()), e.getValue()); + } + shadows.put(cur, sh); + } + Layouts.Cls k = sh.get(v); + List os = k != null ? em.fieldOwners().get(attr) : null; + Layouts.Cls own = null; + for (Layouts.Cls a = k; a != null && os != null && own == null; a = a.parent) { + if (os.contains(a)) { + own = a; + } + } + if (own == null) { + // The local's class has no such field (bs4's `Tag.children` is + // a property): the program's guards would test classes it is + // not (pdfplumber's `PDFStructTree`), each a miss. + return k != null ? em.attrSite(attr) + ".get(" + v + ")" : null; + } + String cast = "((" + k.ref + ") " + v + ")"; + String site = em.attrSite(attr) + ".get(" + v + ")"; + String typedF = own.typed != null ? own.typed.foreignGet(own, attr, cast) : null; + if (typedF != null) { + return "(" + v + " instanceof " + k.ref + " ? " + typedF + " : " + site + ")"; } - return new E(fieldRef(r, attr), ft); + String f = cast + ".f_" + Emitter.mangle(attr); + return "(" + v + " instanceof " + k.ref + " && " + f + " != null ? " + f + " : " + site + ")"; } /// A call's result known, at this call site, to be `t` (`Infer.siteRet`) @@ -3723,7 +8630,7 @@ private E fieldRead(E r, String attr) { private E relabel(E r, Ty t) { switch (t.k) { case INT: - return new E(r.t.k == Ty.K.DYN ? r.c : box(r), Ty.INT); + return new E(r.t.wide() ? r.c : box(r), Ty.INT); case FLOAT: return new E("Typed.asFloat(" + box(r) + ")", Ty.FLOAT); default: @@ -3811,9 +8718,19 @@ private String mod64(Expr e) { } if (e instanceof IfExp && inlined.isEmpty()) { IfExp x = (IfExp) e; - String a = mod64(x.body); - String b = mod64(x.orelse); - return a == null || b == null ? null : "(" + testExpr(x.test) + " ? " + a + " : " + b + ")"; + String t = testExpr(x.test); + // Each branch runs only when chosen: nothing of either may be + // hoisted ahead of the test. + condDepth++; + String a; + String b; + try { + a = mod64(x.body); + b = mod64(x.orelse); + } finally { + condDepth--; + } + return a == null || b == null ? null : "(" + t + " ? " + a + " : " + b + ")"; } return generic(e); } @@ -3876,7 +8793,7 @@ private String nameLong(Name nm) { java.math.BigInteger c = in.intConsts.get(n); return c == null ? null : lit(c); } - switch (sc.resolve(n)) { + switch (binding(n)) { case LOCAL: if (longLocals.contains(n)) { if (!sc.params.contains(n) && !da.safe.contains(nm)) { @@ -4020,6 +8937,12 @@ private static final class Scalar { String[] attrs; final Set reads = new HashSet(); final Set getters = new HashSet(); + /// Attributes a miss probe or a `getattr` with a default asks for. + final Set probes = new HashSet(); + /// The probed ones no field, class or base defines: each answers a + /// miss while the class still lacks it, and rebuilds the object + /// from every field when it does not. + final Set missing = new HashSet(); } private Map scalars = new HashMap(); @@ -4058,10 +8981,22 @@ private Map findScalars(Infer.Fn f) { /// Whether every use of `x` reads a field its constructor set. private boolean scalarUses(Scalar x) { Set fields = new HashSet(Arrays.asList(x.attrs)); + for (String p : x.probes) { + if (fields.contains(p)) { + x.reads.add(p); + } else if (p.startsWith("__") || Layouts.resolver(x.k, p) != null) { + return false; + } else { + x.missing.add(p); + } + } + if (!x.missing.isEmpty()) { + x.reads.addAll(fields); + } for (String g : x.getters) { Layouts.Cls o = Layouts.resolver(x.k, g); FunctionDef d = o == null ? null : o.typable.get(g); - Infer.Fn gf = d == null ? null : in.fns.get(d); + Infer.Fn gf = d == null ? null : in.emitFns().get(d); String attr = gf == null ? null : getterField(gf); if (attr == null) { return false; @@ -4122,6 +9057,8 @@ private void scanScalars(Object o, Map cand, Set bad) { storeTargets(((Comprehension) o).target, cand, bad); } else if (o instanceof WithItem && ((WithItem) o).vars != null) { storeTargets(((WithItem) o).vars, cand, bad); + } else if (o instanceof Call && scalarProbe((Call) o, cand, bad)) { + return; } else if (o instanceof Call && ((Call) o).func instanceof Attribute) { Attribute f = (Attribute) ((Call) o).func; if (f.value instanceof Name && cand.containsKey(((Name) f.value).id)) { @@ -4157,6 +9094,62 @@ private void scanScalars(Object o, Map cand, Set bad) { Infer.children(o, x -> scanScalars(x, cand, bad)); } + /// A miss probe (`$probe(n.a)`, `$unmiss(m, n.a)`) or `getattr(n, "a", d)` + /// on candidate `n`: records `a` as probed and scans the rest. False, + /// scanning nothing, when the call is none of those. + private boolean scalarProbe(Call c, Map cand, Set bad) { + Expr recv; + String attr; + List rest = new ArrayList(); + String fn = c.func instanceof Name ? ((Name) c.func).id : ""; + if ("$probe".equals(fn) || "$unmiss".equals(fn)) { + Expr x = c.args.get(c.args.size() - 1); + if (!(x instanceof Attribute)) { + return false; + } + recv = ((Attribute) x).value; + attr = ((Attribute) x).attr; + rest.addAll(c.args.subList(0, c.args.size() - 1)); + } else if (Emitter.getattrDefault(c) && binding("getattr") == Scope.Binding.BUILTIN + && !em.moduleScopeHasStarImport()) { + recv = c.args.get(0); + attr = ((Constant) c.args.get(1)).text; + rest.add(c.args.get(2)); + } else { + return false; + } + if (!(recv instanceof Name) || !cand.containsKey(((Name) recv).id)) { + return false; + } + if (da.safe.contains((Name) recv)) { + cand.get(((Name) recv).id).probes.add(attr); + } else { + bad.add(((Name) recv).id); + } + for (Expr x : rest) { + scanScalars(x, cand, bad); + } + return true; + } + + /// `n.attr` probed (`probe`) or read on scalar local `n`. + private String scalarProbeRead(String n, String attr, boolean probe) { + Scalar x = scalars.get(n); + if (!x.missing.contains(attr)) { + return box(scalarRead(n, attr)); + } + List fs = new ArrayList(); + for (String a : x.attrs) { + fs.add(scalarRead(n, a)); + } + String site = em.attrSite(attr); + String obj = construct(x.k, fs).c; + if (!probe) { + return site + ".get(" + obj + ")"; + } + return "(" + site + ".classLacks(" + x.k.typeVar + ") ? Py.MISS : " + site + ".getOrMiss(" + obj + "))"; + } + /// Marks every candidate whose field a store target writes. private static void storeTargets(Expr t, Map cand, Set bad) { if (t instanceof Attribute && ((Attribute) t).value instanceof Name) { @@ -4179,10 +9172,10 @@ private static void storeTargets(Expr t, Map cand, Set b /// `x` on the first one, and requires the same class every time. private boolean scalarCtor(Scalar x, Call c) { if (!(c.func instanceof Name) || !c.keywords.isEmpty() - || sc.resolve(((Name) c.func).id) != Scope.Binding.GLOBAL) { + || binding(((Name) c.func).id) != Scope.Binding.GLOBAL) { return false; } - Layouts.Cls k = in.globalClasses.get(((Name) c.func).id); + Layouts.Cls k = in.emitClass(((Name) c.func).id); if (k == null || x.k != null && x.k != k) { //NOPMD CompareObjectsWithEquals - identity is meant return false; } @@ -4193,7 +9186,7 @@ private boolean scalarCtor(Scalar x, Call c) { } Layouts.Cls o = Layouts.resolver(k, "__init__"); FunctionDef init = o == null ? null : o.typable.get("__init__"); - Infer.Fn f = init == null ? null : in.fns.get(init); + Infer.Fn f = init == null ? null : in.emitFns().get(init); if (f == null || f.names.size() != c.args.size() + 1 || !init.decorators.isEmpty()) { return false; } @@ -4299,8 +9292,53 @@ private void scalarDecls(StringBuilder b) { } } + /// The unboxer of class `k` this module writes (see [#unbox]): named + /// after the class alone for one of its own, after the qualified name + /// for another module's. + private String unboxerName(Layouts.Cls k) { + return k.home == in.layouts ? "u_" + k.javaName : "u_" + boxerId(clsJ(k)); //NOPMD CompareObjectsWithEquals - identity is meant + } + + private boolean localRoot(Layouts.Cls k) { + for (Layouts.Cls x = k; x != null; x = x.parent) { + if (x.home != in.layouts) { //NOPMD CompareObjectsWithEquals - identity is meant + return false; + } + } + return true; + } + private E construct(Layouts.Cls k, List args) { + if (k.callConstructed()) { + // BaseException's `__new__` fills `args` from the arguments + // before any `__init__` runs: the class is called, as generic + // code calls it (Infer types the result as any object). + StringBuilder boxed = new StringBuilder(); + for (E a : args) { + boxed.append(", ").append(box(a)); + } + return new E("Py.call(" + k.typeVar + boxed + ")", Ty.OBJECT); + } + if (in.newMethod(k) != null) { + // Its own `__new__` makes the object: the class is called, as + // the generic code calls it. Inference types the result from + // what `__new__` returns. + StringBuilder boxed = new StringBuilder(); + for (E a : args) { + boxed.append(", ").append(box(a)); + } + return new E("Py.call(" + k.typeVar + boxed + ")", Ty.OBJECT); + } Layouts.Cls o = Layouts.resolver(k, "__init__"); + if (o == null && k.builtin != null) { + // The builtin's __new__ makes the value of the arguments. + StringBuilder boxed = new StringBuilder(); + for (E a : args) { + boxed.append(", ").append(box(a)); + } + return new E("Typed.withBase(new " + k.javaName + "(" + k.typeVar + "), " + builtinType(k.builtin) + + ", false" + boxed + ")", Ty.inst(k, false)); + } if (o == null) { if (!args.isEmpty()) { throw new Unsupported("arguments to object()"); @@ -4308,10 +9346,11 @@ private E construct(Layouts.Cls k, List args) { return new E("new " + k.javaName + "(" + k.typeVar + ")", Ty.inst(k, false)); } FunctionDef init = o.typable.get("__init__"); - if (init == null) { + if (init == null || o.home != k.home) { //NOPMD CompareObjectsWithEquals - identity is meant + // An __init__ compiled in another module has no typed body here. throw new Unsupported("__init__"); } - Infer.Fn f = in.fns.get(init); + Infer.Fn f = in.emitFns().get(init); calls.add(f); String al = argList(f, 1, args); if (plainCtor(k) != null) { @@ -4323,15 +9362,38 @@ private E construct(Layouts.Cls k, List args) { private E builtin(String n, List a) { switch (n) { + case "min": + case "max": + if (a.size() == 2) { + return new E("Typed." + n + "2(" + em.builtinRef(n) + ", " + box(a.get(0)) + ", " + box(a.get(1)) + ")", + Ty.OBJECT); + } + break; + case "set": + if (a.isEmpty()) { + return new E("Typed.set(" + em.builtinRef("set") + ")", Ty.OBJECT); + } + if (a.size() == 1 && (a.get(0).t.wide() || a.get(0).t.k == Ty.K.LIST + || a.get(0).t.k == Ty.K.DICT || a.get(0).t.k == Ty.K.TUPLE + || a.get(0).t.k == Ty.K.STR && !a.get(0).t.opt)) { + // Every one of those kinds is already an Object. + return new E("Typed.set(" + em.builtinRef("set") + ", " + a.get(0).c + ")", Ty.OBJECT); + } + break; case "len": if (a.size() == 1 && a.get(0).t.k == Ty.K.LIST) { - return new E("h_len(" + a.get(0).c + ")", Ty.INT); + a = new ArrayList(a); + a.set(0, heldList(a.get(0))); + // The list read through a call stays in the long: every use + // of a length reads it once. + String l = "Typed.llen(" + a.get(0).c + ")"; + return small(new E("Long.valueOf(" + l + ")", Ty.INT, l)); } if (a.size() == 1 && a.get(0).t.k == Ty.K.STR && !a.get(0).t.opt) { String l = "Typed.slen(" + a.get(0).c + ")"; - return new E("Long.valueOf(" + l + ")", Ty.INT, l); + return small(new E("Long.valueOf(" + l + ")", Ty.INT, l)); } - if (a.size() == 1 && a.get(0).t.k == Ty.K.DYN) { + if (a.size() == 1 && a.get(0).t.wide()) { // The builtin's work without a call, unless the name // was rebound at run time. String l = "Typed.len(" + em.builtinRef("len") + ", " + a.get(0).c + ")"; @@ -4387,9 +9449,22 @@ private E builtin(String n, List a) { return null; } + /// The class object of compiled class `k`, from this module. + String classRef(Layouts.Cls k) { + if (k.home == in.layouts) { //NOPMD CompareObjectsWithEquals - identity is meant + return k.typeVar; + } + return k.ref.substring(0, k.ref.length() - k.javaName.length() - 1) + "." + k.typeVar; + } + + /// The runtime's type object of the builtin `n` a compiled class extends. + static String builtinType(String n) { + return "Py." + n.toUpperCase(java.util.Locale.ROOT) + "_TYPE"; + } + /// The builtins `builtin` lowers; any other is called as Python calls it. private static final Set TYPED_BUILTINS = new HashSet(Arrays.asList("len", "float", "str", "ord", - "abs")); + "abs", "set", "min", "max")); /// A call of `f` with the arguments of `c` boxed, keywords included: /// what the generic code does, with an untyped result. Reached for @@ -4404,7 +9479,7 @@ private E genericCall(String f, Call c) { a.append(a.length() == 0 ? "" : ", ").append(box(expr(x))); } if (c.keywords.isEmpty()) { - return new E("Py.call(" + f + (a.length() == 0 ? "" : ", " + a) + ")", Ty.DYN); + return new E("Py.call(" + f + (a.length() == 0 ? "" : ", " + a) + ")", Ty.OBJECT); } StringBuilder names = new StringBuilder(); for (Keyword kw : c.keywords) { @@ -4414,7 +9489,12 @@ private E genericCall(String f, Call c) { a.append(a.length() == 0 ? "" : ", ").append(box(expr(kw.value))); names.append(names.length() == 0 ? "" : ", ").append(Emitter.javaString(kw.arg)); } - return new E("Py.callKw(" + f + ", new Object[] {" + a + "}, new String[] {" + names + "})", Ty.DYN); + // Hoisted: the callee caches its keyword binding by the array's identity. + String w = em.hoist("String[]", "new String[] {" + names + "}"); + if (c.args.size() + c.keywords.size() <= 14) { + return new E("Py.callKwF(" + f + ", " + w + ", " + a + ")", Ty.OBJECT); + } + return new E("Py.callKw(" + f + ", new Object[] {" + a + "}, " + w + ")", Ty.OBJECT); } /// The count of `[v] * n` or `n * [v]` when it is an int, or null. @@ -4432,6 +9512,107 @@ private Expr repeatCount(Expr e) { return t.k == Ty.K.INT && !t.opt ? n : null; } + /// A str method called on a str: the runtime helper directly, for the + /// shapes [Infer#strMethod] types, so the result type agrees. + /// `s.find(sub, i)` (and `rfind`, `startswith`, `endswith`) on a str + /// with a start nothing knows the type of -- html.parser's + /// `rawdata.find('<', i)`, where `i` is what `updatepos` returned: the + /// typed search when the start is an int, else the generic call, which + /// raises or runs `__index__` as the builtin does. + private E strBoundedDyn(E r, String m, List a) { + boolean find = "find".equals(m) || "rfind".equals(m); + if (!find && !"startswith".equals(m) && !"endswith".equals(m) || a.size() != 2 + || a.get(0).t.k != Ty.K.STR || a.get(0).t.opt || !a.get(1).t.wide() + || !plain(r.c) || !plain(a.get(1).c) || !plain(a.get(0).c) && !a.get(0).c.startsWith("\"")) { + return null; + } + String i = a.get(1).c; + String fast = (find ? "Typed.find(" : "Typed.affix(") + r.c + ", " + a.get(0).c + ", ((Long) " + i + + ").longValue(), " + (find ? "rfind".equals(m) : "startswith".equals(m)) + ")"; + String slow = siteCall(r, m, a).c; + return find ? new E("(" + i + " instanceof Long ? Long.valueOf(" + fast + ") : " + slow + ")", Ty.OBJECT) + : new E("(" + i + " instanceof Long ? " + fast + " : Py.isTrue(" + slow + "))", Ty.BOOL); + } + + private E strMethod(E r, String m, List a) { + List ts = new ArrayList<>(); + for (E x : a) { + ts.add(x.t); + } + Ty t = Infer.strMethod(m, ts); + if (t == null) { + return null; + } + String v = r.c; + String c; + if (a.isEmpty() && Infer.isAllKind(m) >= 0) { + return new E("Typed.isAll(" + v + ", " + Infer.isAllKind(m) + ")", Ty.BOOL); + } + if (a.size() >= 2 && !"replace".equals(m)) { + String bounds = ", " + box(a.get(1)) + ", " + (a.size() == 3 ? box(a.get(2)) : "Py.NONE") + ", "; + String fn = t.k == Ty.K.BOOL ? "Typed.affix(" : "Typed.find("; + String tail = (t.k == Ty.K.BOOL ? "startswith".equals(m) : "rfind".equals(m)) + ")"; + c = fn + v + ", " + a.get(0).c + bounds + tail; + String start = a.size() == 2 ? a.get(1).lc : null; + if (start != null) { + // The start as the long it is: nothing boxed. + c = fn + v + ", " + a.get(0).c + ", " + start + ", " + tail; + } else if (a.size() == 2 && a.get(1).ll != null) { + // Either way the receiver and the text are evaluated once, + // after a test that reads a local of this frame only. + c = "(" + a.get(1).bg + " == null ? " + fn + v + ", " + a.get(0).c + ", " + a.get(1).ll + ", " + tail + + " : " + c + ")"; + } + return t.k == Ty.K.BOOL ? new E(c, Ty.BOOL) : small(new E("Long.valueOf(" + c + ")", t, c)); + } + switch (m) { + case "strip": + case "lstrip": + case "rstrip": + c = "Typed.strip(" + v + (a.isEmpty() ? "" : ", " + a.get(0).c) + ", " + !"rstrip".equals(m) + + ", " + !"lstrip".equals(m) + ")"; + break; + case "lower": + case "upper": + c = "Typed.mapCase(" + v + ", " + ("upper".equals(m) ? 1 : 0) + ")"; + break; + case "replace": + c = "Typed.replace(" + v + ", " + a.get(0).c + ", " + a.get(1).c + ")"; + break; + case "find": + case "rfind": + c = "Typed.find(" + v + ", " + a.get(0).c + ", " + "rfind".equals(m) + ")"; + break; + case "count": + c = "Typed.count(" + v + ", " + a.get(0).c + ")"; + break; + case "startswith": + c = v + ".startsWith(" + a.get(0).c + ")"; + break; + case "endswith": + c = v + ".endsWith(" + a.get(0).c + ")"; + break; + default: + c = "Typed.join(" + v + ", " + box(a.get(0)) + ")"; + break; + } + return t.k == Ty.K.INT ? small(new E("Long.valueOf(" + c + ")", t, c)) : new E(c, t); + } + + /// `e`, marked as an int that fits a Java `int` (see `E.small`). + private static E small(E e) { + e.small = true; + return e; + } + + private static List types(List a) { + List ts = new ArrayList<>(); + for (E x : a) { + ts.add(x.t); + } + return ts; + } + private E listMethod(E l, String m, List a) { switch (m) { case "append": @@ -4448,7 +9629,10 @@ private E listMethod(E l, String m, List a) { if (a.size() <= 1) { Ty el = in.elem(l.t); String c = l.c + ".pop(" + (a.isEmpty() ? "-1L" : "Py.asLong(" + box(a.get(0)) + ")") + ")"; - return new E(unbox(c, el), el.k == Ty.K.BOT ? Ty.DYN : el); + if (el.k != Ty.K.INT && in.guessedSite(l.t)) { + return new E(c, Ty.OBJECT); + } + return new E(unbox(c, el), el.k == Ty.K.BOT ? Ty.OBJECT : el); } break; default: @@ -4493,8 +9677,8 @@ String entry(Infer.Fn f, List locals) { arg = "Typed.asList(" + v + ")"; break; case INST: - check = t.opt ? "(" + v + " instanceof " + t.cls.javaName + " || " + v + " == Py.NONE)" - : v + " instanceof " + t.cls.javaName; + check = t.opt ? "(" + v + " instanceof " + clsJ(t.cls) + " || " + v + " == Py.NONE)" + : v + " instanceof " + clsJ(t.cls); arg = unbox(v, t); break; case INT: @@ -4506,6 +9690,26 @@ String entry(Infer.Fn f, List locals) { check = v + " == Py.NONE"; arg = v; break; + case DICT: + check = "Typed.isDict(" + v + ")"; + arg = v; + break; + case CLS: { + // One of these classes, each with its layout: what + // `__new__` builds of it is then an instance typed code + // reads as fields. + StringBuilder ks = new StringBuilder(); + for (Layouts.Cls k : in.classesOf(t)) { + ks.append(", ").append(classRef(k)); + } + check = t.sites.length == 0 ? "(" + v + " instanceof PyType)" : "Typed.laidOut(" + v + ks + ")"; + arg = v; + break; + } + case BYTES: + check = v + " instanceof PyBytes"; + arg = v; + break; default: arg = v; break; @@ -4540,6 +9744,19 @@ String plainCtor(Layouts.Cls k) { } private String plainCtor0(Layouts.Cls k) { + Layouts.Cls root = k; + while (root.parent != null) { + root = root.parent; + } + if (root.home != k.home) { //NOPMD CompareObjectsWithEquals - identity is meant + // A chain rooted in another module gets no plain constructor + // (the class declaration in Emitter skips it), so no call names one. + return null; + } + if (k.builtin != null || k.callConstructed()) { + // Its value comes from the builtin's __new__ (see construct). + return null; + } for (String h : new String[] {"__new__", "__setattr__", "__getattribute__", "__getattr__", "__del__"}) { if (Layouts.resolver(k, h) != null) { return null; @@ -4547,7 +9764,7 @@ private String plainCtor0(Layouts.Cls k) { } Layouts.Cls o = Layouts.resolver(k, "__init__"); FunctionDef init = o == null ? null : o.typable.get("__init__"); - Infer.Fn f = init == null ? null : in.fns.get(init); + Infer.Fn f = init == null ? null : in.emitFns().get(init); if (f == null || !typed.containsKey(f) || f.names.size() < 2 || !init.decorators.isEmpty() || init.args.vararg != null || init.args.kwarg != null || !init.args.kwonly.isEmpty()) { return null; @@ -4610,10 +9827,52 @@ private String plainCtor0(Layouts.Cls k) { return " " + k.javaName + "(PyType t" + sig + ") {\n super(t);\n" + norm + body + " }\n"; } + /// `self.attr` where `attr` resolves to a once-bound class attribute + /// with a typed static (Infer#classStatic) and no compiled class at or + /// below the receiver's binds it again: the static, while the instance + /// is of one of those compiled classes exactly and nothing wrote to that + /// class since it was built; the generic read, unboxed, otherwise (a + /// class built at run time may bind the name in its own body). Null when + /// it does not apply. + private E instanceStatic(E r, String attr) { + Layouts.Cls owner = Layouts.resolver(r.t.cls, attr); + Ty t = owner == null ? null : in.classStatic(owner, attr); + if (t == null) { + return null; + } + StringBuilder g = new StringBuilder(); + for (Layouts.Cls c : in.selfAndBelow(r.t.cls)) { + if (!c.compiled) { + // Refused a layout: its instances are never typed as these. + continue; + } + if (Layouts.resolver(c, attr) != owner) { //NOPMD CompareObjectsWithEquals - identity is meant + return null; + } + String tv = em.typeVarRef(c); + g.append(g.length() == 0 ? "" : " || ").append(r.c).append(".cls == ").append(tv).append(" && !") + .append(tv).append(".classWritten"); + } + if (g.length() == 0) { + return null; + } + if (t.k == Ty.K.INT) { + return new E("((" + g + ") ? " + staticE(em.classStaticRef(owner, attr), t).c + " : " + attrGet(r, attr) + ")", t); + } + return new E("((" + g + ") ? " + em.classStaticRef(owner, attr) + " : " + unbox(attrGet(r, attr), t) + ")", t); + } + + /// The read of a typed class static named `ref` (Emitter#classStatics): + /// an int is its two-part pair. + private static E staticE(String ref, Ty t) { + return t.k == Ty.K.INT ? dual(ref + "_l", ref + "_b") : new E(ref, t); + } + String fieldDecl(Layouts.Cls k, String f) { Ty t = typedField(k, f); - if (t != null && t.k == Ty.K.INT) { - return "long t_" + Emitter.mangle(f) + ";\n Object b_" + Emitter.mangle(f) + ";"; + if (t != null && (t.k == Ty.K.INT || guardedField(k, f))) { + return (t.k == Ty.K.INT ? "long" : jt(t)) + " t_" + Emitter.mangle(f) + + ";\n Object b_" + Emitter.mangle(f) + (openField(k, f) ? " = Typed.UNSET;" : ";"); } return t == null ? null : jt(t) + " t_" + Emitter.mangle(f) + ";"; } @@ -4623,11 +9882,22 @@ String fieldGetCase(Layouts.Cls k, String f) { if (t.k == Ty.K.INT) { return dual("t_" + Emitter.mangle(f), "b_" + Emitter.mangle(f)).c; } + if (guardedField(k, f)) { + String m = Emitter.mangle(f); + // An absent field answers null, as a plain field never set does. + return pairE("t_" + m, "b_" + m, t, openField(k, f) ? "(b_" + m + " == Typed.UNSET ? null : b_" + m + ")" + : null).c; + } return box(new E("t_" + Emitter.mangle(f), t)); } String fieldSetCase(Layouts.Cls k, String f, String v) { Ty t = typedField(k, f); + if (guardedField(k, f) && t.k != Ty.K.INT) { + StringBuilder b = new StringBuilder(); + fitInto(v, t, "t_" + Emitter.mangle(f), "b_" + Emitter.mangle(f), b, 5); + return b.toString().trim(); + } if (t.k == Ty.K.INT) { String m = Emitter.mangle(f); return "if (" + v + " instanceof Long) {\n t_" + m + " = ((Long) " + v @@ -4637,6 +9907,304 @@ String fieldSetCase(Layouts.Cls k, String f, String v) { return "t_" + Emitter.mangle(f) + " = " + unbox(v, t) + ";"; } + // ---- guessed values (Infer#guessed) --------------------------------- + + /// Whether field `f` of `k` is held typed and guarded: a typed slot and + /// beside it the object that replaces it (see Infer.Program#unknownStores). + boolean guardedField(Layouts.Cls k, String f) { + Ty t = typedField(k, f); + if (t == null) { + return false; + } + return in.guarded(k, f) || openField(k, f); + } + + /// A guessed value of type `t` held in plain Java names `r` and `o`. + private E pairE(String r, String o, Ty t) { + return pairE(r, o, t, null); + } + + /// [#pairE] whose object half, when not null, is read as `present` + /// (see [#present]); the test for the typed slot reads `o` itself. + private E pairE(String r, String o, Ty t, String present) { + if (t.k == Ty.K.INT) { + return dual(r, o); + } + String ov = present != null ? present : o; + // The object half typed as an object: a conditional of two + // reference types in an argument is typed by its target, and a + // typed half of PyList picked the PyList overload of what reads it. + E e = new E("(" + o + " != null ? (Object) " + ov + " : " + box(new E(r, t)) + ")", Ty.OBJECT); + e.gr = r; + e.go = ov; + e.gt = t; + e.gg = o + " == null"; + e.gview = new E(r, t); + e.ga = e.c; + e.gstable = r.indexOf('.') < 0; + return e; + } + + /// The typed form of pair `e`, valid where its object is null. + private static E typedOf(E e) { + return new E(e.gr, e.gt); + } + + /// A Java test that object `v` (a plain name) is a value of type `t`, + /// as a slot of that type holds it. + private String fits(String v, Ty t) { + String none = t.nullable() ? " || " + v + " == Py.NONE" : ""; + switch (t.k) { + case BOOL: + return "(" + v + " == Py.TRUE || " + v + " == Py.FALSE)"; + case FLOAT: + return v + " instanceof Double"; + case STR: + return "(" + v + " instanceof String" + none + ")"; + case LIST: + return "(" + v + " instanceof PyList" + none + ")"; + case INST: + return "(" + v + " instanceof " + clsJ(t.cls) + none + ")"; + default: + throw new Unsupported("no slot for " + t); + } + } + + /// Stores object `v` (a plain name) into the pair `slot`/`over` of + /// type `t`: into the slot when it fits, the object when not. + private void fitInto(String v, Ty t, String slot, String over, StringBuilder b, int ind) { + if (t.k == Ty.K.INT) { + storePair(slot, over, new E(v, Ty.OBJECT), b, ind); + return; + } + b.append("if (").append(fits(v, t)).append(") {\n"); + indent(b, ind + 1); + b.append(slot).append(" = ").append(unbox(v, t)).append(";\n"); + indent(b, ind + 1); + b.append(over).append(" = null;\n"); + indent(b, ind); + b.append("} else {\n"); + indent(b, ind + 1); + b.append(over).append(" = ").append(v).append(";\n"); + indent(b, ind); + b.append("}\n"); + } + + /// `e` converted to `to` without a check, or null where that is not + /// exact: `e` may not be of that type, or may be None where it is not. + private String exactConv(E e, Ty to) { + if ("Object".equals(jt(e.t)) && e.t.k != Ty.K.NONE || e.t.opt && !to.nullable()) { + return null; + } + try { + return conv(e, to); + } catch (Unsupported u) { + return null; + } + } + + /// Stores `v` into the pair `slot`/`over` of type `t`. + private void storeGuess(String slot, String over, Ty t, E v, StringBuilder b, int ind) { + if (t.k == Ty.K.INT) { + storePair(slot, over, v, b, ind); + return; + } + if (v.gr != null) { + String c = exactConv(typedOf(v), t); + if (c != null) { + b.append(slot).append(" = ").append(c).append(";\n"); + indent(b, ind); + b.append(over).append(" = ").append(v.go).append(";\n"); + return; + } + } + String c = exactConv(v, t); + if (c != null) { + b.append(slot).append(" = ").append(c).append(";\n"); + indent(b, ind); + b.append(over).append(" = null;\n"); + return; + } + String vc = v.gview != null && v.go == null ? exactConv(v.gview, t) : null; + if (vc != null) { + // The typed version's value fits as it is; the other is checked. + String o = fresh(); + b.append("if (").append(v.gg).append(") {\n"); + indent(b, ind + 1); + b.append(slot).append(" = ").append(vc).append(";\n"); + indent(b, ind + 1); + b.append(over).append(" = null;\n"); + indent(b, ind); + b.append("} else {\n"); + indent(b, ind + 1); + b.append("Object ").append(o).append(" = ").append(v.ga).append(";\n"); + indent(b, ind + 1); + fitInto(o, t, slot, over, b, ind + 1); + indent(b, ind); + b.append("}\n"); + return; + } + String o = fresh(); + b.append("Object ").append(o).append(" = ").append(box(v)).append(";\n"); + indent(b, ind); + fitInto(o, t, slot, over, b, ind); + } + + /// An element `obj` of a container whose elements are guesses of type + /// `el` (Infer#guessedSite): a pair declared in `into`, or before the + /// statement, or the object itself where neither can be. + private E guessedElem(String obj, Ty el, StringBuilder into, int ind) { + if (el.k == Ty.K.INT || !Infer.guessable(el) || "Object".equals(jt(el))) { + return new E(obj, el.k == Ty.K.INT ? el : Ty.OBJECT); + } + StringBuilder b = into; + int bi = ind; + if (b == null) { + if (pre == null || !stmtPure || condDepth != 0) { + return new E(obj, Ty.OBJECT); + } + b = pre; + bi = preInd; + } + String o = fresh(); + String r = fresh(); + String ro = fresh(); + indent(b, bi); + b.append("Object ").append(o).append(" = ").append(obj).append(";\n"); + indent(b, bi); + b.append(jt(el)).append(' ').append(r).append(" = ").append(zero(el)).append(";\n"); + indent(b, bi); + b.append("Object ").append(ro).append(";\n"); + indent(b, bi); + fitInto(o, el, r, ro, b, bi); + return pairE(r, ro, el); + } + + /// Whether local `n` is a guessed one held as a pair: its typed Java + /// local and the object beside it ([#over]). + private boolean guessLocal(String n) { + if (cur == null || !in.guessedLocal(cur, n) || longLocals.contains(n) || accLocals.contains(n) + || trueCells.contains(n) || compVar(n) != null || scalars.containsKey(n)) { + return false; + } + Ty t = cur.locals.get(n); + return t != null && t.k != Ty.K.INT && Infer.guessable(t) && !"Object".equals(jt(t)); + } + + /// The object half of guessed local `n`. + private static String over(String n) { + return "x_" + Emitter.mangle(n); + } + + /// After a write of the typed half of local `n` alone: its object half + /// no longer replaces it. + private void clearOver(String n, StringBuilder b, int ind) { + if (guessLocal(n)) { + indent(b, ind); + b.append(over(n)).append(" = null;\n"); + } + } + + /// Typed fields read as objects through a helper, where the receiver + /// is an expression that may not be evaluated twice. + /// One helper per guarded field, keyed "class TAB field": sites that + /// type the field with and without None share it, boxing for None. + private final Map guardBoxers = new TreeMap(); + + /// Guarded field `attr` of `r` (see [#guardedField]). + private E guessField(E r, String attr, Ty t) { + Layouts.Cls o = owner(r, attr); + String m = Emitter.mangle(attr); + String recv = nz(r, attr); + if (!plain(recv) && pre != null && stmtPure && condDepth == 0) { + String tv = fresh(); + indent(pre, preInd); + pre.append(o.ref).append(' ').append(tv).append(" = ").append(recv).append(";\n"); + recv = tv; + } + if (plain(recv)) { + return pairE(recv + ".t_" + m, recv + ".b_" + m, t, present(o, attr, recv + ".b_" + m, recv)); + } + String ob = present(o, attr, "o.b_" + m, "o"); + // The typed half is never None (None lives in the object half), but + // sites with and without None share the helper. orNone() keeps a + // reference kind and is OBJECT for the rest -- and box() of OBJECT writes + // a primitive bool as it is, which Java boxed to java.lang.Boolean: + // a value every truth test reads as true (dateutil's `dayfirst`). + Ty bt = t.orNone().k == t.k ? t.orNone() : t.nonNone(); + guardBoxers.merge(o.ref + "\t" + m, (ob != null ? ob : "o.b_" + m) + "\t" + box(new E("o.t_" + m, bt)), + (x, y) -> x); + return new E("fg_" + boxerId(o.ref) + "_" + m + "(" + recv + ")", Ty.OBJECT); + } + + /// Stores `v` into guarded field `attr` of `r`; Python evaluates the + /// value first. + private void storeGuardedField(E r, String attr, E v, StringBuilder b, int ind) { + Layouts.Cls o = owner(r, attr); + String m = Emitter.mangle(attr); + E val = v; + if (!plain(r.c) && val.gr == null && !(plain(val.c) || val.lc != null && plain(val.lc))) { + String tv = fresh(); + b.append(jt(val.t)).append(' ').append(tv).append(" = ").append(val.c).append(";\n"); + indent(b, ind); + val = new E(tv, val.t); + } + String recv = nz(r, attr); + if (!plain(recv)) { + String tv = fresh(); + b.append(o.ref).append(' ').append(tv).append(" = ").append(recv).append(";\n"); + indent(b, ind); + recv = tv; + } + storeGuess(recv + ".t_" + m, recv + ".b_" + m, typedField(o, attr), val, b, ind); + } + + /// Method name -> the site its `pt_` bridge and `tv_` slots fall back + /// to, taken while the bodies are lowered: the site tables are written + /// before the members that use them. + private final Map patchedSites = new HashMap(); + + private void patchedSite(String name) { + if (!patchedSites.containsKey(name)) { + patchedSites.put(name, em.attrSite(name)); + } + } + + /// Typed methods called directly, each through its `pt_` bridge. + private final Set bridged = new LinkedHashSet(); + + /// The statements a typed method entered on `self` runs first: when the + /// instance's class overrides compiled methods (a class built at run + /// time that borrowed this layout, PyType.borrowLayout), the call goes + /// the generic way, which finds the override, and its result is taken + /// back as the typed result. `a1..`/`b1..` are the parameters. + private String patchedFallback(Infer.Fn f, String self) { + int ar = f.params.length - 1; + StringBuilder a = new StringBuilder(); + for (int i = 1; i <= ar; i++) { + Ty t = f.params[i]; + a.append(", ").append(t.k == Ty.K.INT ? "(b" + i + " != null ? b" + i + " : (Object) Long.valueOf(a" + i + "))" + : box(new E("a" + i, t))); + } + String site = patchedSites.get(f.def.name); + if (site == null) { + // Only a method some typed call reaches has a bridge or a slot + // that is called; its site was taken when that call was lowered. + return "if (" + self + ".cls.patched) {\n throw Py.runtimeError(\"unreachable\");\n}"; + } + String call = ar <= 13 ? site + ".call" + ar + "(" + self + a + ")" + : site + ".callN(" + self + ", new Object[] {null" + a + "})"; + String r; + if (f.ret.k == Ty.K.INT) { + r = "Typed.retObj(" + call + ")"; + } else if (objectRet(f.ret)) { + r = call; + } else { + r = unbox(call, f.ret); + } + return "if (" + self + ".cls.patched) {\n return " + r + ";\n}"; + } + /// Members of layout class `k` (`tv_` overrides) and of the base `LB` /// (`k` null: the `tv_` declarations). String layoutMembers(Layouts.Cls k) { @@ -4662,12 +10230,15 @@ String layoutMembers(Layouts.Cls k) { if (m == null || !k.bodyNames.contains(name)) { continue; } - Infer.Fn f = in.fns.get(m); + Infer.Fn f = in.emitFns().get(m); if (!g.contains(f)) { continue; } - o.append(" @Override\n").append(head).append(" return ").append(typed.get(f)) - .append("(this").append(pass).append(");\n }\n"); + o.append(" @Override\n").append(head); + for (String line : patchedFallback(f, "this").split("\n")) { + o.append(" ").append(line).append('\n'); + } + o.append(" return ").append(typed.get(f)).append("(this").append(pass).append(");\n }\n"); } return o.toString(); } @@ -4677,23 +10248,38 @@ String layoutMembers(Layouts.Cls k) { String members() { StringBuilder o = new StringBuilder(); for (String b : bodies.values()) { - o.append(b); + o.append(resolveForeign(b)); } for (String b : longBodies.values()) { - o.append(b); + o.append(resolveForeign(b)); } for (Layouts.Cls k : constructors) { Layouts.Cls ow = Layouts.resolver(k, "__init__"); - Infer.Fn f = in.fns.get(ow.typable.get("__init__")); + Infer.Fn f = in.emitFns().get(ow.typable.get("__init__")); + if (typed.get(f) == null) { + // Its __init__ fell back to the generic version after the + // call that asked for this was lowered, taking every + // function that calls it along. + continue; + } StringBuilder sig = new StringBuilder(); StringBuilder pass = new StringBuilder(); for (int i = 1; i < f.params.length; i++) { sig.append(i == 1 ? "" : ", ").append(param(f.params[i], "a" + i, "b" + i)); pass.append(", a").append(i).append(f.params[i].k == Ty.K.INT ? ", b" + i : ""); } + String made = "new " + k.javaName + "(" + k.typeVar + ")"; + if (k.builtin != null) { + StringBuilder boxed = new StringBuilder(); + for (int i = 1; i < f.params.length; i++) { + boxed.append(", ").append(f.params[i].k == Ty.K.INT ? "(b" + i + " != null ? b" + i + + " : Long.valueOf(a" + i + "))" : box(new E("a" + i, f.params[i]))); + } + made = "Typed.withBase(" + made + ", " + builtinType(k.builtin) + ", true" + boxed + ")"; + } o.append(" static ").append(k.javaName).append(" n_").append(k.javaName).append('(').append(sig) - .append(") {\n ").append(k.javaName).append(" o = new ").append(k.javaName).append('(') - .append(k.typeVar).append(");\n ").append(typed.get(f)).append("(o").append(pass) + .append(") {\n ").append(k.javaName).append(" o = ").append(made) + .append(";\n ").append(typed.get(f)).append("(o").append(pass) .append(");\n return o;\n }\n"); } if (!bodies.isEmpty()) { @@ -4705,14 +10291,37 @@ String members() { } for (String fb : fieldBoxers) { String[] p = fb.split(" "); - o.append(" static Object fb_").append(p[0]).append('_').append(p[1]).append('(').append(p[0]) + o.append(" static Object fb_").append(boxerId(p[0])).append('_').append(p[1]).append('(').append(p[0]) .append(" o) {\n return o.b_").append(p[1]).append(" != null ? o.b_").append(p[1]) .append(" : Long.valueOf(o.t_").append(p[1]).append(");\n }\n"); } + for (Map.Entry ge : guardBoxers.entrySet()) { + String[] p = (ge.getKey() + "\t" + ge.getValue()).split("\t", 4); + o.append(" static Object fg_").append(boxerId(p[0])).append('_').append(p[1]).append('(').append(p[0]) + .append(" o) {\n return o.b_").append(p[1]).append(" != null ? ").append(p[2]) + .append(" : ").append(p[3]).append(";\n }\n"); + } + for (Infer.Fn f : bridged) { + if (typed.get(f) == null) { + continue; + } + StringBuilder sig = new StringBuilder(f.cls.javaName + " a0"); + StringBuilder pass = new StringBuilder("a0"); + for (int i = 1; i < f.params.length; i++) { + sig.append(", ").append(param(f.params[i], "a" + i, "b" + i)); + pass.append(", a").append(i).append(f.params[i].k == Ty.K.INT ? ", b" + i : ""); + } + o.append(" static ").append(retJ(f)).append(" pt_").append(typed.get(f)).append('(').append(sig) + .append(") {\n"); + for (String line : patchedFallback(f, "a0").split("\n")) { + o.append(" ").append(line).append('\n'); + } + o.append(" return ").append(typed.get(f)).append('(').append(pass).append(");\n }\n"); + } for (Layouts.Cls k : unboxers) { - o.append(" static ").append(k.javaName).append(" u_").append(k.javaName) - .append("(Object o) {\n if (o instanceof ").append(k.javaName).append(") {\n return (") - .append(k.javaName).append(") o;\n }\n if (o == Py.NONE) {\n return null;\n") + o.append(" static ").append(clsJ(k)).append(' ').append(unboxerName(k)) + .append("(Object o) {\n if (o instanceof ").append(clsJ(k)).append(") {\n return (") + .append(clsJ(k)).append(") o;\n }\n if (o == Py.NONE) {\n return null;\n") .append(" }\n throw Typed.mismatch(o);\n }\n"); } return o.toString(); diff --git a/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/WholeProgram.java b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/WholeProgram.java new file mode 100644 index 00000000000..9bc89ac046f --- /dev/null +++ b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/codegen/WholeProgram.java @@ -0,0 +1,998 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.python.transpiler.codegen; + +import com.codename1.python.transpiler.ast.Node.*; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/// What the rest of the program does to a module, for `Infer`. +/// +/// The transpiler sees every module of the application, so a module is +/// never typed on the assumption that nothing outside it matters, and +/// never left untyped because something might: the stores that reach it +/// from elsewhere are found here, by name, and handed to its analysis. +/// +/// Three things are all that typed code relies on beyond its own module. +/// A typed field holds only what the stores `Infer` saw put there; a +/// method called directly is the one the class body bound; a global bound +/// once still has that value. Each fact below takes one of those away for +/// one name, and nothing else changes: +/// +/// - an attribute name another module stores through anything but a +/// method's own receiver (`x.n = v`, `setattr(x, "n", v)`) is no typed +/// field and no directly called method here, and a global of that name +/// is not stable; +/// - an attribute name any module deletes (`del x.n`) is no field typed +/// code reads without asking whether it is set; +/// - an attribute name this module stores through anything but a +/// method's own receiver is no directly called method; +/// - a module that hands its own namespace out (`globals()`, `vars()`, +/// `locals()` passed, stored or written through) has no stable globals. +/// Only reading it -- `globals()[name]`, `.get`, `in`, iterating it -- +/// keeps them: such a read can reach any of its names, but rebinds none. +/// +/// Nothing else needs a fact. A class with a base from another module, a +/// decorator, a metaclass or `__new__` has no compiled layout (see +/// `Layouts`), and a subclass defined anywhere gets ordinary instances +/// (`PyType.layout`), so typed code never receives one: its entry checks +/// the Java class of every argument. Importing `copy`, `dataclasses` or +/// `inspect` changes nothing either -- what they do to an instance goes +/// through the same stores as any other code. A store whose name is +/// computed (`setattr(o, name, v)`, `o.__dict__[k] = v`, +/// `object.__setattr__`, a write through `vars(o)`) is followed like any +/// other: the inference joins what it stores into every field it could +/// name -- those of the receiver's class and the classes related to it, +/// or, for a receiver of no known class, those of every class whose +/// instances are held that way (`Infer.computedStore`). The build notes +/// each such store that cost a field its type. The generic store of a +/// field still checks the value against the field's type, so a store the +/// inference could not see raises where it happens and is never read back +/// as a value of the wrong type. +/// +/// The same pass decides what the program reaches (`Infer.Program.reached`): +/// a function nothing calls, names or can find by a computed name is left +/// out of the build, with a body that says so. `Directives` is how a build +/// overrides that by name, in either direction. +public final class WholeProgram { + /// `unittest.mock`'s patchers, which store an attribute named by a + /// string: `patch`, `patch.object`, `patch.multiple`. + private static final Set PATCHERS = new HashSet(Arrays.asList("patch", "object", "multiple")); + private static final Set NAMESPACE = new HashSet(Arrays.asList("globals", "vars", "locals")); + + /// The facts of one module. + public static final class Module { + /// Attribute names stored from outside the module, or by a literal + /// `setattr` inside it. + final Set foreign = new HashSet(); + /// Attribute names the module stores through anything but the + /// receiver of the method the store is in. + final Set loose = new HashSet(); + /// Whether the module hands out its own namespace as a dict, through + /// which any global may be bound again. + boolean namespace; + /// Whether the module reads its own namespace, which can reach any of + /// its names but binds none of them (see [#readOnlyNamespace]). + boolean namespaceRead; + /// Attribute names any module of the program deletes (`del x.n`, + /// `delattr(x, "n")`): a field of that name may be unset on an + /// instance that had it. + Set deleted = new HashSet(); + /// Names other modules mention: an attribute they read, a name + /// they import. What they can call or construct by name. + final Set mentioned = new HashSet(); + /// The names this module mentions. + final Set mentions = new HashSet(); + /// Whether another module takes all of this one's names + /// (`from m import *`). + boolean starImported; + /// Whether the module reads an attribute whose name it computes + /// (`getattr(o, name)`): any method of its classes may be the one. + boolean computedRead; + /// Whether the module gets at the class of a value (`type(x)`, + /// `x.__class__`, a `classmethod`'s first parameter), which it may + /// then call. + boolean classValues; + /// Whether the module takes the attributes of an instance as a + /// dict (`o.__dict__`, `vars(o)`), through which it may remove any + /// of them: no field of its classes is then known to be set. + boolean dictViews; + /// Every attribute name the whole program stores or deletes by + /// name, on any receiver (shared by every module's view). + Set storedAttrs = new HashSet(); + /// Every class statement of a module with a computed attribute + /// store (`setattr(o, name, v)` with `name` not a literal): such a + /// site may rebind any of those classes' attributes unseen (shared + /// by every module's view, see [#computedStoreReaches]). + Set computedStoreClasses = java.util.Collections.newSetFromMap(new java.util.IdentityHashMap()); + /// The last name of every class base the whole program writes + /// (`Base`, `mod.Base`), plus "*" once a base is any other + /// expression or a class may be made by a call (`type`). + Set baseNames = new HashSet(); + + /// Whether some class of the program may derive from a class named + /// `name`: a statement names it as a base, or a base is computed. + boolean mayBeBase(String name, Set reached) { + if (baseNames.contains(name) || baseNames.contains("*")) { + return true; + } + for (FunctionDef f : dynamicBases) { + if (reached.contains(f)) { + return true; + } + } + return false; + } + + /// The functions that make a class from bases the source does not + /// spell out (shared by every module's view). + Set dynamicBases = java.util.Collections.newSetFromMap(new java.util.IdentityHashMap()); + + /// Every name the whole program uses outside the body of the class + /// it names (shared by every module's view); null when that does not + /// bound which classes have instances (see [#namedOutside]). + Set named; + /// Whether the module reaches classes without naming them, through + /// `C.__subclasses__()` it does more with than test against. + boolean subclassReads; + /// Whether any module of the program imports Java classes, whose + /// objects answer methods of any name (shared by every module's view + /// once the program is read). + boolean javaInterop; + /// The attribute names a Java object of the program answers + /// ([JavaInteropGenerator#generate]), shared by every module; null + /// when not known, and then every name may be one. + Set javaNames; + + /// Whether a Java object of the program may answer attribute `n`. + boolean javaAnswers(String n) { + return javaInterop && (javaNames == null || javaNames.contains(n)); + } + /// The `__subclasses__` reads whose classes only reach + /// `issubclass`/`isinstance` (see [#checkedOnly]). + Set checkedSubclassReads = new HashSet(); + /// The names this module imports, which may hold a module. + final Set imported = new HashSet(); + /// The root names of the receivers this module reads a computed + /// attribute of: on a module, that may be any of its classes. + final Set computedRoots = new HashSet(); + /// How deep in class bodies the scan is; a class nested in a class + /// is reached through the outer one, `getattr(Outer, n)` included, + /// so it counts as named. + int classDepth; + + /// Whether class `name` may have instances or be handed out as a + /// value: something names it outside its own body. An instance is + /// made by calling the class, which needs the class; `type(x)` and + /// `__class__` only give back the class of an instance that exists. + /// A class named nowhere but in its own body is dead, whatever reads + /// class values. Unknown (true) when the program is not seen whole, + /// or reads a name it computes or a class's subclasses. + boolean namedOutside(String name) { + return named == null || named.contains(name); + } + + /// Every attribute name the whole program names as a literal to + /// setattr, `__setattr__` or a mock patcher (shared by every + /// module's view). + Set setattrAttrs = new HashSet(); + + /// Whether a method `name` may be replaced in a way the type pass + /// does not see as a store: through setattr or a patcher by a + /// literal name, or deleted. A plain `x.name = v` is not counted + /// here: the pass sees it, and decides which classes it can reach + /// ([Infer.Program#patchedFound]). Counting it by name took the + /// typed `__init__` from every class of a program as soon as one + /// decorator anywhere did `cls.__init__ = ...`. + boolean methodPatched(String name) { + return setattrAttrs.contains(name) || deleted.contains(name); + } + + /// Whether any module stores or deletes attribute `name` by name. + boolean attrStored(String name) { + return storedAttrs.contains(name); + } + + /// Whether a computed attribute store of the program may reach the + /// class `c` declares: `c` is declared in a module holding one. + boolean computedStoreReaches(ClassDef c) { + return computedStoreClasses.contains(c); + } + final List stars = new ArrayList(); + /// The `globals`/`vars`/`locals` names of this module's calls that + /// only read the namespace, or (`vars(o)`) are no namespace at all. + Set nsReads = new HashSet(); + + /// Whether the top-level function or class `name` can be reached + /// from outside the module by its name. + boolean reachable(String name) { + return starImported || namespace || namespaceRead || mentioned.contains(name); + } + + /// Whether a method `name` of a class of this module may be called + /// by code that does not name the class: through an attribute of + /// that name read anywhere else, or one this module computes. + boolean calledByName(String name) { + return computedRead || mentioned.contains(name); + } + + /// Whether attribute `name` of an instance may hold a value this + /// module's stores do not account for. + boolean foreign(String name) { + return foreign.contains(name); + } + + /// Whether a class attribute `name` may be rebound after the class + /// body ran. + boolean patched(String name) { + return foreign.contains(name) || loose.contains(name) || deleted.contains(name); + } + } + + private final Map modules = new HashMap(); + + WholeProgram() { + types.closed = true; + } + + /// The facts of `module`; of a module the program does not have, none. + /// Records the attribute names Java objects of the program answer. + public void javaAnswers(Set names) { + for (Module m : modules.values()) { + m.javaNames = names; + } + } + + public Module module(String module) { + Module m = modules.get(module); + return m == null ? new Module() : m; + } + + /// The types of the whole program: every module's pass over one heap. + Infer.Program types = new Infer.Program(); + + /// Infers the types of every module entered (`Emitter.prepare`). + /// What the Java side of the program may look up by name (see + /// `ClassPathReader.names`), and the functions the build keeps on + /// request. Without the first, no function is left out. + public void roots(Set runtimeNames, java.util.Collection keep) { + types.runtimeNames = runtimeNames; + types.keep.addAll(keep); + } + + /// One line for each place where reached code does to an object of + /// no known class what the typed fields of every class it may be have + /// to allow for: `module:line: function stores ...`. + public List notes() { + List out = new ArrayList(); + for (Infer.Problem q : types.problems.values()) { + if (q.store) { + out.add(q.module + ":" + q.line + ": " + (q.function == null ? "the module" : q.function) + " " + + q.what); + } + } + java.util.Collections.sort(out); + return out; + } + + private String main; + + /// Runs only what module `main` reaches: a module nothing imports from + /// there is left out of the build (see `Infer.Program.live`). Without + /// a call, or with the runtime's names unknown, every module is kept. + public void main(String main) { + this.main = main; + } + + /// Whether module `name` runs, and so is emitted. + public boolean isLive(String name) { + Infer m = types.modules.get(name); + return m == null || types.isLive(m); + } + + public void infer() { + if (main != null && types.modules.containsKey(main) && types.runtimeNames != null) { + types.allLive = false; + types.markLive(main); + // What the runtime imports by name (Py.importModule). + for (String n : new String[] {"builtins", "copyreg", "io"}) { + types.markLive(n); + } + for (String n : types.modules.keySet().toArray(new String[0])) { + if (types.runtimeNames.contains(n)) { + types.markLive(n); + } + } + for (String k : types.keep) { + for (int dot = k.lastIndexOf('.'); dot > 0; dot = k.lastIndexOf('.', dot - 1)) { + if (types.modules.containsKey(k.substring(0, dot))) { + types.markLive(k.substring(0, dot)); + break; + } + } + if (types.modules.containsKey(k)) { + types.markLive(k); + } + } + } + types.run(); + // A method a store may replace on some instance or class is looked + // up per call. Which classes a store reaches is known only once the + // pass is done, so the pass runs again with those methods taken + // out until it finds no new one. Taking a method out only loosens + // the program, so the set only grows and this ends. + while (types.morePatched()) { + types = types.fresh(); + types.run(); + } + { + List errors = new ArrayList(); + for (Infer m : types.modules.values()) { + errors.addAll(m.strictErrors()); + } + if (!errors.isEmpty()) { + StringBuilder b = new StringBuilder("cn1.python.strict: ").append(errors.size()) + .append(" construct(s) a closed world cannot compile"); + for (String e : errors) { + b.append("\n ").append(e); + } + throw new IllegalStateException(b.toString()); + } + } + } + + /// Reads every module of the program (dotted name to body). + public static WholeProgram of(Map> bodies) { + WholeProgram p = new WholeProgram(); + Map> stores = new HashMap>(); + Map count = new HashMap(); + Set deleted = new HashSet(); + Set storedAttrs = new HashSet(); + Set setattrAttrs = new HashSet(); + Set named = new HashSet(); + Set baseNames = new HashSet(); + Set dynamicBases = java.util.Collections.newSetFromMap(new java.util.IdentityHashMap()); + Set computedStoreClasses = java.util.Collections.newSetFromMap(new java.util.IdentityHashMap()); + for (List b : bodies.values()) { + attrStores(b, storedAttrs); + boolean[] computed = new boolean[1]; + List classes = new ArrayList(); + computedStores(b, computed, classes); + if (computed[0]) { + computedStoreClasses.addAll(classes); + } + baseNames(b, null, baseNames, dynamicBases); + } + for (Map.Entry> e : bodies.entrySet()) { + Module m = new Module(); + m.deleted = deleted; + m.storedAttrs = storedAttrs; + m.computedStoreClasses = computedStoreClasses; + m.baseNames = baseNames; + m.dynamicBases = dynamicBases; + m.setattrAttrs = setattrAttrs; + m.named = named; + Set all = new HashSet(); + m.nsReads = readOnlyNamespace(e.getValue()); + for (Stmt s : e.getValue()) { + checkedOnly(s, m.checkedSubclassReads); + } + scan(e.getValue(), null, null, m, all); + p.modules.put(e.getKey(), m); + stores.put(e.getKey(), all); + for (String n : all) { + Integer c = count.get(n); + count.put(n, Integer.valueOf(c == null ? 1 : c.intValue() + 1)); + } + } + boolean unnamed = false; + boolean java = false; + for (Module m : p.modules.values()) { + java |= m.javaInterop; + } + for (Module m : p.modules.values()) { + m.javaInterop = java; + } + for (Module m : p.modules.values()) { + unnamed |= m.subclassReads || m.computedRoots.contains(""); + for (String r : m.computedRoots) { + unnamed |= m.imported.contains(r); + } + } + for (Module m : p.modules.values()) { + // A name a module computes may be any class's, and + // `__subclasses__` hands out classes by no name at all. + m.named = unnamed ? null : named; + } + Map mcount = new HashMap(); + boolean allStarred = false; + Set starred = new HashSet(); + for (Module m : p.modules.values()) { + for (String n : m.mentions) { + Integer c = mcount.get(n); + mcount.put(n, Integer.valueOf(c == null ? 1 : c.intValue() + 1)); + } + for (String st : m.stars) { + allStarred |= st.isEmpty(); + starred.add(st); + } + } + for (Map.Entry e : p.modules.entrySet()) { + Module m = e.getValue(); + for (Map.Entry c : mcount.entrySet()) { + if (c.getValue().intValue() > 1 || !m.mentions.contains(c.getKey())) { + m.mentioned.add(c.getKey()); + } + } + // A relative star import names its module by a suffix: every + // module ending in it is taken to be the one. + m.starImported = allStarred; + for (String st : starred) { + m.starImported |= e.getKey().equals(st) || e.getKey().endsWith("." + st); + } + } + // A name is foreign to a module when a module other than it stores + // it: stored by two modules, or by one that is not this one. + for (Map.Entry e : p.modules.entrySet()) { + Set own = stores.get(e.getKey()); + for (Map.Entry c : count.entrySet()) { + if (c.getValue().intValue() > 1 || !own.contains(c.getKey())) { + e.getValue().foreign.add(c.getKey()); + } + } + } + return p; + } + + /// `self` is the receiver of the method `o` is in, or null. + /// The attribute names stored or deleted anywhere under `o`: every + /// target position, and the literal names of `setattr`, `delattr`, + /// `__setattr__` and `__delattr__` calls. Computed names are Infer's. + static void attrStores(Object o, Set out) { + if (o instanceof FunctionDef && ((FunctionDef) o).dataclassInit) { + // The constructor DataclassInit wrote stores each field once, by + // its literal name: not a store any other code makes. + return; + } + if (o instanceof Assign && !Layouts.trailingStore(o)) { + for (Expr t : ((Assign) o).targets) { + attrTarget(t, out); + } + } else if (o instanceof AugAssign) { + attrTarget(((AugAssign) o).target, out); + } else if (o instanceof AnnAssign) { + attrTarget(((AnnAssign) o).target, out); + } else if (o instanceof Delete) { + for (Expr t : ((Delete) o).targets) { + attrTarget(t, out); + } + } else if (o instanceof For) { + attrTarget(((For) o).target, out); + } else if (o instanceof WithItem) { + attrTarget(((WithItem) o).vars, out); + } else if (o instanceof Comprehension) { + attrTarget(((Comprehension) o).target, out); + } else if (o instanceof Call) { + Call c = (Call) o; + String f = c.func instanceof Name ? ((Name) c.func).id + : c.func instanceof Attribute ? ((Attribute) c.func).attr : null; + if ("setattr".equals(f) || "delattr".equals(f) || "__setattr__".equals(f) || "__delattr__".equals(f)) { + for (Expr a : c.args) { + if (a instanceof Constant && ((Constant) a).kind == Constant.Kind.STR) { + out.add(((Constant) a).text); + } + } + } + } + Infer.children(o, x -> attrStores(x, out)); + } + + /// Finds every class statement under `o`, and sets `computed[0]` at a + /// store or delete whose attribute name is not a literal: + /// `setattr(o, n, v)`, `type.__setattr__(o, n, v)`, `o.__setattr__(n, v)`. + private static void computedStores(Object o, boolean[] computed, List classes) { + if (o instanceof ClassDef) { + classes.add((ClassDef) o); + } else if (o instanceof Call) { + Call c = (Call) o; + String f = c.func instanceof Name ? ((Name) c.func).id + : c.func instanceof Attribute ? ((Attribute) c.func).attr : null; + if ("setattr".equals(f) || "delattr".equals(f) || "__setattr__".equals(f) || "__delattr__".equals(f)) { + boolean del = f.indexOf("del") >= 0; + int at = c.args.size() == (del ? 1 : 2) && c.func instanceof Attribute ? 0 : 1; + Expr n = at < c.args.size() ? c.args.get(at) : null; + computed[0] |= !(n instanceof Constant && ((Constant) n).kind == Constant.Kind.STR); + } + } + Infer.children(o, x -> computedStores(x, computed, classes)); + } + + /// Collects [Module#baseNames]: every base a class statement names, and + /// for a call that may make a class from bases it is handed, those + /// bases. A bases argument the source does not spell out is the name + /// "*" at module level and the enclosing function in `dyn` otherwise, + /// which [Module#mayBeBase] counts once that function runs. + private static void baseNames(Object o, FunctionDef in, Set out, Set dyn) { + if (o instanceof FunctionDef) { + for (Stmt s : ((FunctionDef) o).body) { + baseNames(s, (FunctionDef) o, out, dyn); + } + return; + } + if (o instanceof ClassDef) { + for (Expr b : ((ClassDef) o).bases) { + baseExpr(b, in, out, dyn); + } + } else if (o instanceof Call) { + Call c = (Call) o; + Expr bases = classMakerBases(c); + if (bases != null) { + boolean forwarded = in != null && "__new__".equals(in.name) && bases instanceof Name + && in.args.positional.size() > 2 && in.args.positional.get(2).name.equals(((Name) bases).id); + // A metaclass's `__new__` handing on the bases it was given + // by a class statement, which names them already. + if (!forwarded) { + baseExpr(bases, in, out, dyn); + } + } + for (Keyword k : c.keywords) { + if ("bases".equals(k.arg)) { + baseExpr(k.value, in, out, dyn); + } + } + if (c.args.size() >= 3) { + // `Meta("X", (Base,), {})`: a metaclass called directly. + for (Expr a : c.args) { + if (a instanceof TupleExpr) { + for (Expr e : ((TupleExpr) a).elts) { + if (e instanceof Name) { + out.add(((Name) e).id); + } else if (e instanceof Attribute) { + out.add(((Attribute) e).attr); + } + } + } + } + } + } + Infer.children(o, x -> baseNames(x, in, out, dyn)); + } + + private static void baseExpr(Expr b, FunctionDef in, Set out, Set dyn) { + if (b instanceof Name) { + out.add(((Name) b).id); + } else if (b instanceof Attribute) { + out.add(((Attribute) b).attr); + } else if (b instanceof TupleExpr) { + for (Expr e : ((TupleExpr) b).elts) { + baseExpr(e, in, out, dyn); + } + } else if (b instanceof IfExp) { + baseExpr(((IfExp) b).body, in, out, dyn); + baseExpr(((IfExp) b).orelse, in, out, dyn); + } else if (b instanceof Subscript) { + // `Generic[T]`, `List[str]`: the subscripted class. + baseExpr(((Subscript) b).value, in, out, dyn); + } else if (b instanceof Call) { + // `namedtuple(...)`, `with_metaclass(Meta, Base)`: a class made + // from what the call is handed, if from anything. + for (Expr a : ((Call) b).args) { + if (!(a instanceof Constant)) { + baseExpr(a, in, out, dyn); + } + } + for (Keyword k : ((Call) b).keywords) { + if (!(k.value instanceof Constant)) { + baseExpr(k.value, in, out, dyn); + } + } + } else if (b instanceof Constant || b instanceof ListExpr) { + // A string or a field list (`namedtuple("P", ["x", "y"])`). + return; + } else if (in == null) { + out.add("*"); + } else { + dyn.add(in); + } + } + + /// The bases argument of `type(name, bases, ns)`, `types.new_class(name, + /// bases)` or `X.__new__(mcs, name, bases, ns)`, or null. + private static Expr classMakerBases(Call c) { + String f = c.func instanceof Name ? ((Name) c.func).id + : c.func instanceof Attribute ? ((Attribute) c.func).attr : null; + if ("type".equals(f) && c.args.size() == 3 || "new_class".equals(f) && c.args.size() >= 2) { + return c.args.get(1); + } + if ("__new__".equals(f) && c.args.size() >= 4) { + return c.args.get(2); + } + return null; + } + + private static void attrTarget(Expr t, Set out) { + if (t instanceof Attribute) { + out.add(((Attribute) t).attr); + } else if (t instanceof TupleExpr) { + for (Expr x : ((TupleExpr) t).elts) { + attrTarget(x, out); + } + } else if (t instanceof ListExpr) { + for (Expr x : ((ListExpr) t).elts) { + attrTarget(x, out); + } + } else if (t instanceof Starred) { + attrTarget(((Starred) t).value, out); + } + } + + /// The names `globals`, `vars` and `locals` in `body` whose call only + /// reads the module's namespace: `globals()[k]` (not stored or deleted + /// through), `globals().get(k)` and the other reading methods, + /// `k in globals()`, iterating it, or copying it (`dict(globals())`). A + /// `vars(o)` with an argument is the instance's dict, not the module's + /// (`dictViews` covers it). Matched by identity. bs4's `element` looks a + /// deprecated name up with `globals()[...]` in its `__getattr__`; taking + /// that as a namespace handed out made every one of its classes unstable, + /// so no other module could name `Tag` -- not even in an annotation. + static Set readOnlyNamespace(List body) { + Set stores = java.util.Collections.newSetFromMap(new java.util.IdentityHashMap()); + storeTargets(body, stores); + Set out = java.util.Collections.newSetFromMap(new java.util.IdentityHashMap()); + nsReadsIn(body, stores, out); + return out; + } + + private static final Set NS_READ_METHODS = new HashSet(Arrays.asList( + "get", "keys", "values", "items", "copy", "__contains__", "__getitem__")); + private static final Set NS_COPIES = new HashSet(Arrays.asList( + "len", "list", "sorted", "dict", "set", "tuple", "iter")); + + private static void storeTargets(Object o, Set stores) { + if (o instanceof Assign && !Layouts.trailingStore(o)) { + for (Expr t : ((Assign) o).targets) { + targetsOf(t, stores); + } + } else if (o instanceof AugAssign) { + targetsOf(((AugAssign) o).target, stores); + } else if (o instanceof AnnAssign) { + targetsOf(((AnnAssign) o).target, stores); + } else if (o instanceof Delete) { + for (Expr t : ((Delete) o).targets) { + targetsOf(t, stores); + } + } else if (o instanceof For) { + targetsOf(((For) o).target, stores); + } else if (o instanceof WithItem && ((WithItem) o).vars != null) { + targetsOf(((WithItem) o).vars, stores); + } + Infer.children(o, x -> storeTargets(x, stores)); + } + + private static void targetsOf(Expr t, Set stores) { + stores.add(t); + if (t instanceof TupleExpr) { + for (Expr x : ((TupleExpr) t).elts) { + targetsOf(x, stores); + } + } else if (t instanceof ListExpr) { + for (Expr x : ((ListExpr) t).elts) { + targetsOf(x, stores); + } + } else if (t instanceof Starred) { + targetsOf(((Starred) t).value, stores); + } + } + + /// The name of `e` when it is a call of `globals()`, `vars()` or + /// `locals()` with no arguments; else null. + private static Name nsCall(Expr e) { + if (e instanceof Call && ((Call) e).func instanceof Name && ((Call) e).args.isEmpty() + && ((Call) e).keywords.isEmpty() && NAMESPACE.contains(((Name) ((Call) e).func).id)) { + return (Name) ((Call) e).func; + } + return null; + } + + private static void nsReadsIn(Object o, Set stores, Set out) { + Name n = null; + if (o instanceof Subscript && !stores.contains(o)) { + n = nsCall(((Subscript) o).value); + } else if (o instanceof Call) { + Call c = (Call) o; + if (c.func instanceof Attribute && NS_READ_METHODS.contains(((Attribute) c.func).attr)) { + n = nsCall(((Attribute) c.func).value); + } else if (c.func instanceof Name && NS_COPIES.contains(((Name) c.func).id) && c.args.size() == 1 + && c.keywords.isEmpty()) { + n = nsCall(c.args.get(0)); + } else if (c.func instanceof Name && "vars".equals(((Name) c.func).id) && !c.args.isEmpty()) { + out.add(c.func); + } + } else if (o instanceof Compare) { + Compare c = (Compare) o; + for (int i = 0; i < c.ops.size(); i++) { + String op = c.ops.get(i); + if (("in".equals(op) || "not in".equals(op)) && nsCall(c.comparators.get(i)) != null) { + out.add(nsCall(c.comparators.get(i))); + } + } + } else if (o instanceof For) { + n = nsCall(((For) o).iter); + } + if (n != null) { + out.add(n); + } + Infer.children(o, x -> nsReadsIn(x, stores, out)); + } + + /// Adds to `safe` the `__subclasses__` reads in the iterable of a loop + /// whose variable is used only as an argument to `issubclass` or + /// `isinstance`: the classes they hand out are tested, never called, + /// kept or passed on (`abc`'s subclass check). + private static void checkedOnly(Object o, Set safe) { + if (o instanceof For && ((For) o).target instanceof Name) { + For f = (For) o; + String t = ((Name) f.target).id; + int[] uses = new int[2]; + Infer.children(f, x -> { + if (x != f.iter && x != f.target) { + loopUses(x, t, uses); + } + }); + if (uses[0] == uses[1]) { + subclassReads(f.iter, safe); + } + } + Infer.children(o, x -> checkedOnly(x, safe)); + } + + /// Counts in `uses[0]` every use of name `t` under `o`, and in + /// `uses[1]` those that are a direct argument of `issubclass` or + /// `isinstance`. + private static void loopUses(Object o, String t, int[] uses) { + if (o instanceof Name && t.equals(((Name) o).id)) { + uses[0]++; + } + if (o instanceof Call && ((Call) o).func instanceof Name + && ("issubclass".equals(((Name) ((Call) o).func).id) + || "isinstance".equals(((Name) ((Call) o).func).id))) { + for (Expr a : ((Call) o).args) { + if (a instanceof Name && t.equals(((Name) a).id)) { + uses[1]++; + } + } + } + Infer.children(o, x -> loopUses(x, t, uses)); + } + + /// Adds every `__subclasses__` read under `o` to `safe`. + private static void subclassReads(Object o, Set safe) { + if (o instanceof Attribute && "__subclasses__".equals(((Attribute) o).attr)) { + safe.add(o); + } + Infer.children(o, x -> subclassReads(x, safe)); + } + + /// `fs` is the namespace builtins (`NAMESPACE`) a function `o` is in + /// binds as names of its own, null at the top level. The scopes are + /// not built yet, so this counts the stores itself; a name a nested + /// function binds shadows it there too, as Python resolves it. + private static void scan(Object o, String self, Set fs, Module m, Set all) { + if (o instanceof FunctionDef) { + List names = ((FunctionDef) o).args.names(); + String first = names.isEmpty() ? null : names.get(0); + Set shadow = new HashSet(fs == null ? java.util.Collections.emptySet() : fs); + for (String n : NAMESPACE) { + if (Infer.bindsLocally((FunctionDef) o, n)) { + shadow.add(n); + } + } + Infer.children(o, x -> scan(x, first, shadow, m, all)); + return; + } + if (o instanceof ClassDef && m.named != null) { + // Its own body naming the class (`super(K, self)`) makes no + // instance of it. + Set outer = m.named; + m.named = new HashSet(); + m.classDepth++; + Infer.children(o, x -> scan(x, null, fs, m, all)); + m.classDepth--; + if (m.classDepth == 0) { + m.named.remove(((ClassDef) o).name); + } + outer.addAll(m.named); + m.named = outer; + return; + } + if (o instanceof Lambda || o instanceof ClassDef) { + Infer.children(o, x -> scan(x, null, fs, m, all)); + return; + } + // Only the builtin hands the namespace out: bs4's `BeautifulSoup` + // keeps a frame's globals in a local named `globals`, which had made + // every global of `bs4` unstable -- its imports unbound, and so its + // `BeautifulSoup(Tag)` without a layout. + if (o instanceof Name && NAMESPACE.contains(((Name) o).id) + && (fs == null || !fs.contains(((Name) o).id))) { + if (m.nsReads.contains(o)) { + m.namespaceRead = true; + } else { + m.namespace = true; + } + } + if (o instanceof Attribute) { + m.mentions.add(((Attribute) o).attr); + m.subclassReads |= "__subclasses__".equals(((Attribute) o).attr) && !m.checkedSubclassReads.contains(o); + if (m.named != null) { + m.named.add(((Attribute) o).attr); + } + m.classValues |= "__class__".equals(((Attribute) o).attr); + m.dictViews |= "__dict__".equals(((Attribute) o).attr); + } else if (o instanceof Name) { + if (m.named != null) { + m.named.add(((Name) o).id); + } + m.classValues |= "classmethod".equals(((Name) o).id); + m.dictViews |= "vars".equals(((Name) o).id); + } else if (o instanceof ImportFrom) { + ImportFrom f = (ImportFrom) o; + for (Alias a : f.names) { + if ("*".equals(a.name)) { + m.stars.add(f.module == null ? "" : f.module); + } else { + m.mentions.add(a.name); + m.imported.add(a.asname != null ? a.asname : a.name); + if (m.named != null) { + m.named.add(a.name); + } + } + } + } + if (o instanceof ImportFrom && ((ImportFrom) o).module != null + && ("java".equals(((ImportFrom) o).module) || ((ImportFrom) o).module.startsWith("java."))) { + m.javaInterop = true; + } + if (o instanceof Import) { + for (Alias a : ((Import) o).names) { + m.javaInterop |= "java".equals(a.name) || a.name.startsWith("java."); + m.imported.add(a.asname != null ? a.asname : a.name.split("\\.")[0]); + } + } + if (o instanceof Call) { + Call c = (Call) o; + String f = c.func instanceof Name ? ((Name) c.func).id + : c.func instanceof Attribute ? ((Attribute) c.func).attr : null; + m.classValues |= "type".equals(f) && c.func instanceof Name && c.args.size() == 1; + if (("getattr".equals(f) || "hasattr".equals(f) || "attrgetter".equals(f) || "methodcaller".equals(f) + || "__getattribute__".equals(f)) && !c.args.isEmpty()) { + boolean literal = false; + for (Expr a : c.args) { + if (a instanceof Constant && ((Constant) a).kind == Constant.Kind.STR) { + m.mentions.add(((Constant) a).text); + // A name read by a literal in this module may be + // one of its own methods. + m.mentioned.add(((Constant) a).text); + literal = true; + } + } + m.computedRead |= !literal && !"hasattr".equals(f); + if (!literal) { + Expr r = "__getattribute__".equals(f) && c.func instanceof Attribute + ? ((Attribute) c.func).value : c.args.get(0); + while (r instanceof Attribute) { + r = ((Attribute) r).value; + } + // `type(x)` and `super()` are classes of an instance + // that exists; any other receiver that is no plain name + // may be a module. + boolean classOf = r instanceof Call && ((Call) r).func instanceof Name + && ("type".equals(((Name) ((Call) r).func).id) + || "super".equals(((Name) ((Call) r).func).id)); + if (!classOf) { + m.computedRoots.add(r instanceof Name ? ((Name) r).id : ""); + } + } + } + if ("setattr".equals(f) || "delattr".equals(f) || "__setattr__".equals(f) || "__delattr__".equals(f) + || PATCHERS.contains(f)) { + // The name is the argument before the value: the second of + // setattr(o, n, v) and of object.__setattr__(o, n, v), the + // first of o.__setattr__(n, v), and either of mock's + // patch("mod.n") and patch.object(o, "n"). Every literal + // among the arguments is taken; one too many costs a typed + // field. + for (Expr a : c.args) { + if (a instanceof Constant && ((Constant) a).kind == Constant.Kind.STR) { + // `patch("pkg.mod.name")` names its target by a path. + String n = ((Constant) a).text; + n = n.substring(n.lastIndexOf('.') + 1); + if (f.startsWith("del") || f.startsWith("__del")) { + m.deleted.add(n); + } else { + all.add(n); + m.foreign.add(n); + m.setattrAttrs.add(n); + } + } + } + } + } + if (o instanceof Delete) { + for (Expr t : ((Delete) o).targets) { + if (t instanceof Attribute) { + m.deleted.add(((Attribute) t).attr); + } + } + } else if (o instanceof Assign) { + for (Expr t : ((Assign) o).targets) { + target(t, self, m, all); + } + } else if (o instanceof AugAssign) { + target(((AugAssign) o).target, self, m, all); + } else if (o instanceof AnnAssign) { + target(((AnnAssign) o).target, self, m, all); + } else if (o instanceof For) { + target(((For) o).target, self, m, all); + } else if (o instanceof WithItem && ((WithItem) o).vars != null) { + target(((WithItem) o).vars, self, m, all); + } else if (o instanceof Comp) { + for (Comprehension g : ((Comp) o).generators) { + target(g.target, self, m, all); + } + } + Infer.children(o, x -> scan(x, self, fs, m, all)); + } + + private static void target(Expr t, String self, Module m, Set all) { + if (t instanceof Attribute) { + Attribute a = (Attribute) t; + // A method storing on its own receiver stores on an instance + // of its own class or of a subclass, and no compiled class has + // a parent outside its module: that store is the class's own + // business. (Called unbound on a stranger it is a computed + // store like any other, checked where it happens.) + if (self == null || !(a.value instanceof Name) || !((Name) a.value).id.equals(self)) { + m.loose.add(a.attr); + all.add(a.attr); + } + } else if (t instanceof TupleExpr) { + for (Expr e : ((TupleExpr) t).elts) { + target(e, self, m, all); + } + } else if (t instanceof ListExpr) { + for (Expr e : ((ListExpr) t).elts) { + target(e, self, m, all); + } + } else if (t instanceof Starred) { + target(((Starred) t).value, self, m, all); + } + } +} diff --git a/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/parser/Parser.java b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/parser/Parser.java index 298fb5b6fcd..224b04b1c9e 100644 --- a/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/parser/Parser.java +++ b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/parser/Parser.java @@ -49,6 +49,14 @@ public final class Parser { private final List toks; private final String file; private int p; + /// Where each lambda's body starts in `toks`, and whether it was parsed + /// without a conditional (testNoCond); read by inlineLambda. + private final java.util.IdentityHashMap lambdaBodies = new java.util.IdentityHashMap(); + /// While inlineLambda re-reads a body: each parameter's argument, and how + /// often the body named it. A name outside the map sets substFree. + private java.util.Map subst; + private java.util.Map substUses; + private boolean substFree; public Parser(List toks, String file) { this.toks = toks; @@ -561,7 +569,224 @@ private Stmt tryStmt() { if (handlers.isEmpty() && fin.isEmpty()) { throw err(peek(), "expected 'except' or 'finally' block"); } - return new Try(body, handlers, orelse, fin, star).at(t.line, t.col); + Try parsed = new Try(body, handlers, orelse, fin, star).at(t.line, t.col); + Stmt probed = missProbe(parsed); + return probed != null ? probed : parsed; + } + + /// Hidden locals of the miss probes, numbered per module. + private int missProbes; + + /// `try: hits += d[key]` / `try: hits += obj.attr` with one bare + /// `except KeyError:` / `except AttributeError:` -- a dict miss or a + /// duck-typing probe, the commonest exception-as-control-flow there is -- + /// as a branch: + /// + /// ``` + /// $m = $probe(d[key]) + /// if $ismiss($m, KeyError): + /// else: try: hits += $unmiss($m, d[key]) except KeyError: + /// ``` + /// + /// The probe answers a sentinel instead of raising (`Py.getitemOrMiss`, + /// `AttrSite.getOrMiss`), so a miss allocates no exception and unwinds + /// nothing. The original try stays around the rest of the statement, so + /// the same error raised by anything else in it is still caught, and + /// `$ismiss` compares the handler's type with the builtin at run time: a + /// module that rebinds the name gets the original try, whose `$unmiss` + /// raises the real error. Only taken when the probe is the statement's + /// one lookup of its kind and the rest is operators on names and + /// constants (hoisting the probe then reorders nothing observable), and + /// when the handler calls nothing and raises nothing -- it runs without + /// the exception set, so it must not be able to observe it. + private Stmt missProbe(Try t) { + if (t.star || t.handlers.size() != 1 || !t.orelse.isEmpty() || t.body.size() != 1) { + return null; + } + ExceptHandler h = t.handlers.get(0); + if (h.name != null || !(h.type instanceof Name)) { + return null; + } + String err = ((Name) h.type).id; + boolean attr = "AttributeError".equals(err); + if (!attr && !"KeyError".equals(err)) { + return null; + } + for (Stmt hs : h.body) { + if (!quietStmt(hs)) { + return null; + } + } + Stmt st = t.body.get(0); + Expr value; + if (st instanceof AugAssign && ((AugAssign) st).target instanceof Name) { + value = ((AugAssign) st).value; + } else if (st instanceof Assign && allNames(((Assign) st).targets)) { + value = ((Assign) st).value; + } else if (st instanceof ExprStmt) { + value = ((ExprStmt) st).value; + } else { + return null; + } + if (!plainBody(value)) { + return null; + } + List found = new ArrayList(); + lookups(value, attr, found); + if (found.size() != 1) { + return null; + } + Expr probe = found.get(0); + if (attr ? !sideEffectFree(((Attribute) probe).value) + : !sideEffectFree(((Subscript) probe).value) || !sideEffectFree(((Subscript) probe).index)) { + return null; + } + String m = "$m" + (++missProbes); + Call unmiss = new Call(new Name("$unmiss").at(probe.line, probe.col)).at(probe.line, probe.col); + unmiss.args.add(new Name(m).at(probe.line, probe.col)); + unmiss.args.add(probe); + Expr replaced = replace(value, probe, unmiss); + Stmt rewritten; + if (st instanceof AugAssign) { + AugAssign a = (AugAssign) st; + rewritten = new AugAssign(a.target, a.op, replaced).at(st.line, st.col); + } else if (st instanceof Assign) { + rewritten = new Assign(((Assign) st).targets, replaced).at(st.line, st.col); + } else { + rewritten = new ExprStmt(replaced).at(st.line, st.col); + } + List guarded = new ArrayList(); + guarded.add(rewritten); + List orig = new ArrayList(); + orig.add(new Try(guarded, t.handlers, new ArrayList(), new ArrayList(), false).at(t.line, t.col)); + Call probeCall = new Call(new Name("$probe").at(probe.line, probe.col)).at(probe.line, probe.col); + probeCall.args.add(probe); + List targets = new ArrayList(); + targets.add(new Name(m).at(t.line, t.col)); + Call isMiss = new Call(new Name("$ismiss").at(t.line, t.col)).at(t.line, t.col); + isMiss.args.add(new Name(m).at(t.line, t.col)); + isMiss.args.add(h.type); + List out = new ArrayList(); + out.add(new Assign(targets, probeCall).at(t.line, t.col)); + out.add(new If(isMiss, h.body, orig).at(t.line, t.col)); + // A try with no handlers is a plain block, or keeps its finally. + return new Try(out, new ArrayList(), new ArrayList(), t.finalbody, false) + .at(t.line, t.col); + } + + private static boolean allNames(List targets) { + for (Expr e : targets) { + if (!(e instanceof Name)) { + return false; + } + } + return true; + } + + /// A handler statement that cannot observe the exception: assignments + /// and expressions of operators, no call, no raise. + private boolean quietStmt(Stmt s) { + if (s instanceof Pass) { + return true; + } + if (s instanceof AugAssign) { + AugAssign a = (AugAssign) s; + return plainBody(a.target) && plainBody(a.value); + } + if (s instanceof Assign) { + Assign a = (Assign) s; + for (Expr e : a.targets) { + if (!plainBody(e)) { + return false; + } + } + return plainBody(a.value); + } + return s instanceof ExprStmt && plainBody(((ExprStmt) s).value); + } + + /// The attribute reads (or subscripts) in a [#plainBody] expression. + private static void lookups(Expr e, boolean attr, List out) { + if (e instanceof Attribute) { + if (attr) { + out.add(e); + } + lookups(((Attribute) e).value, attr, out); + } else if (e instanceof Subscript) { + if (!attr) { + out.add(e); + } + lookups(((Subscript) e).value, attr, out); + lookups(((Subscript) e).index, attr, out); + } else if (e instanceof BinOp) { + lookups(((BinOp) e).left, attr, out); + lookups(((BinOp) e).right, attr, out); + } else if (e instanceof UnaryOp) { + lookups(((UnaryOp) e).operand, attr, out); + } else if (e instanceof Compare) { + lookups(((Compare) e).left, attr, out); + for (Expr x : ((Compare) e).comparators) { + lookups(x, attr, out); + } + } else if (e instanceof BoolOp) { + for (Expr x : ((BoolOp) e).values) { + lookups(x, attr, out); + } + } else if (e instanceof IfExp) { + lookups(((IfExp) e).test, attr, out); + lookups(((IfExp) e).body, attr, out); + lookups(((IfExp) e).orelse, attr, out); + } else if (e instanceof TupleExpr) { + for (Expr x : ((TupleExpr) e).elts) { + lookups(x, attr, out); + } + } + } + + /// `e` with the node `from` (by identity) replaced by `to`. + private static Expr replace(Expr e, Expr from, Expr to) { + if (e == from) { //NOPMD CompareObjectsWithEquals - identity is meant + return to; + } + Expr r = e; + if (e instanceof Attribute) { + Attribute a = (Attribute) e; + r = new Attribute(replace(a.value, from, to), a.attr); + } else if (e instanceof Subscript) { + Subscript a = (Subscript) e; + r = new Subscript(replace(a.value, from, to), replace(a.index, from, to)); + } else if (e instanceof BinOp) { + BinOp b = (BinOp) e; + r = new BinOp(replace(b.left, from, to), b.op, replace(b.right, from, to)); + } else if (e instanceof UnaryOp) { + UnaryOp u = (UnaryOp) e; + r = new UnaryOp(u.op, replace(u.operand, from, to)); + } else if (e instanceof Compare) { + Compare c = (Compare) e; + Compare n = new Compare(replace(c.left, from, to)); + n.ops.addAll(c.ops); + for (Expr x : c.comparators) { + n.comparators.add(replace(x, from, to)); + } + r = n; + } else if (e instanceof BoolOp) { + BoolOp b = (BoolOp) e; + List v = new ArrayList(); + for (Expr x : b.values) { + v.add(replace(x, from, to)); + } + r = new BoolOp(b.isAnd, v); + } else if (e instanceof IfExp) { + IfExp i = (IfExp) e; + r = new IfExp(replace(i.test, from, to), replace(i.body, from, to), replace(i.orelse, from, to)); + } else if (e instanceof TupleExpr) { + List v = new ArrayList(); + for (Expr x : ((TupleExpr) e).elts) { + v.add(replace(x, from, to)); + } + r = new TupleExpr(v); + } + return r == e ? e : r.at(e.line, e.col); //NOPMD CompareObjectsWithEquals - identity is meant } private Stmt withStmt(boolean isAsync) { @@ -970,8 +1195,11 @@ private Expr lambda(boolean noCond) { Token t = expect("lambda"); Arguments args = parameters(":", false); expect(":"); + int bodyAt = p; Expr body = noCond ? testNoCond() : test(); - return new Lambda(args, body).at(t.line, t.col); + Lambda l = new Lambda(args, body).at(t.line, t.col); + lambdaBodies.put(l, new int[] {bodyAt, noCond ? 1 : 0, p}); + return l; } private Expr orTest() { @@ -1054,12 +1282,38 @@ private Expr comparison() { Compare c = new Compare(e).at(t.line, t.col); while (op != null) { c.ops.add(op); - c.comparators.add(bitOr()); + c.comparators.add("in".equals(op) || "not in".equals(op) ? foldIn(bitOr()) : bitOr()); op = compOp(); } return c; } + /// What CPython's optimizer does to the right side of `in` when it is a + /// display of constants: a list becomes a tuple constant (membership is + /// the same) and a set a frozenset constant, so no container is built + /// per test. The emitters hoist both. + private static Expr foldIn(Expr e) { + if (e instanceof ListExpr && plainConstants(((ListExpr) e).elts)) { + return new TupleExpr(((ListExpr) e).elts).at(e.line, e.col); + } + if (e instanceof SetExpr && plainConstants(((SetExpr) e).elts)) { + ((SetExpr) e).frozenConstant = true; + } + return e; + } + + private static boolean plainConstants(List elts) { + if (elts.isEmpty()) { + return false; + } + for (Expr x : elts) { + if (!(x instanceof Constant)) { + return false; + } + } + return true; + } + private Expr bitOr() { Expr e = bitXor(); while (at("|")) { @@ -1139,6 +1393,114 @@ private Expr awaitPrimary() { return primary(); } + /// `(lambda x, y: x * y)(a, b)` is `a * b`: the function object is never seen, + /// so the call is replaced by the body, re-read from its tokens with each + /// parameter standing for its argument. Every later pass then sees ordinary + /// code -- the typed lowering, which a lambda anywhere in a function turned off, + /// included. Only where nothing can tell: plain positional parameters, side + /// effect free arguments, each parameter named exactly once (so an argument is + /// evaluated once), a body that names nothing but its parameters (so no + /// binding can resolve differently in the caller, a class body above all) and + /// opens no scope. Null otherwise, and the call stays a call. + private Expr inlineLambda(Lambda l, Call c) { + int[] at = lambdaBodies.get(l); + Arguments a = l.args; + if (at == null || subst != null || !c.keywords.isEmpty() || a.vararg != null || a.kwarg != null + || !a.kwonly.isEmpty() || !a.defaults.isEmpty() || a.positional.size() != c.args.size()) { + return null; + } + java.util.Map map = new java.util.HashMap(); + java.util.Map uses = new java.util.HashMap(); + for (int i = 0; i < c.args.size(); i++) { + if (!sideEffectFree(c.args.get(i))) { + return null; + } + map.put(a.positional.get(i).name, c.args.get(i)); + uses.put(a.positional.get(i).name, new int[1]); + } + int resume = p; + subst = map; + substUses = uses; + substFree = false; + Expr body; + try { + p = at[0]; + body = at[1] == 1 ? testNoCond() : test(); + if (p != at[2]) { + return null; + } + } finally { + p = resume; + subst = null; + substUses = null; + } + if (substFree || !plainBody(body)) { + return null; + } + for (int[] u : uses.values()) { + if (u[0] != 1) { + return null; + } + } + return body; + } + + private static boolean sideEffectFree(Expr e) { + if (e instanceof Name || e instanceof Constant) { + return true; + } + if (e instanceof BinOp) { + return sideEffectFree(((BinOp) e).left) && sideEffectFree(((BinOp) e).right); + } + return e instanceof UnaryOp && sideEffectFree(((UnaryOp) e).operand); + } + + /// Only operators, comparisons, conditionals and the arguments themselves; + /// anything that opens a scope, binds, or yields is refused. + private boolean plainBody(Expr e) { + if (e instanceof Name || e instanceof Constant) { + return true; + } + if (e instanceof BinOp) { + return plainBody(((BinOp) e).left) && plainBody(((BinOp) e).right); + } + if (e instanceof UnaryOp) { + return plainBody(((UnaryOp) e).operand); + } + if (e instanceof Compare) { + boolean ok = plainBody(((Compare) e).left); + for (Expr x : ((Compare) e).comparators) { + ok &= plainBody(x); + } + return ok; + } + if (e instanceof BoolOp) { + boolean ok = true; + for (Expr x : ((BoolOp) e).values) { + ok &= plainBody(x); + } + return ok; + } + if (e instanceof IfExp) { + IfExp i = (IfExp) e; + return plainBody(i.test) && plainBody(i.body) && plainBody(i.orelse); + } + if (e instanceof Attribute) { + return plainBody(((Attribute) e).value); + } + if (e instanceof Subscript) { + return plainBody(((Subscript) e).value) && plainBody(((Subscript) e).index); + } + if (e instanceof TupleExpr) { + boolean ok = true; + for (Expr x : ((TupleExpr) e).elts) { + ok &= plainBody(x); + } + return ok; + } + return false; + } + private Expr primary() { Expr e = atom(); while (true) { @@ -1149,7 +1511,8 @@ private Expr primary() { Call c = new Call(e).at(t.line, t.col); callArgs(c); expect(")"); - e = c; + Expr inl = e instanceof Lambda ? inlineLambda((Lambda) e, c) : null; + e = inl != null ? inl : c; } else if (accept("[")) { e = new Subscript(e, slices()).at(t.line, t.col); expect("]"); @@ -1277,6 +1640,16 @@ private Expr atom() { p++; return new Constant(Constant.Kind.FALSE, null).at(t.line, t.col); default: + if (subst != null) { + String n = name(); + Expr a = subst.get(n); + if (a == null) { + substFree = true; + return new Name(n).at(t.line, t.col); + } + substUses.get(n)[0]++; + return a; + } return new Name(name()).at(t.line, t.col); } } diff --git a/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/parser/UnicodeNames.java b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/parser/UnicodeNames.java index 9cd4d02dfa6..d53a96a81f2 100644 --- a/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/parser/UnicodeNames.java +++ b/maven/python-transpiler/src/main/java/com/codename1/python/transpiler/parser/UnicodeNames.java @@ -23,6 +23,11 @@ */ package com.codename1.python.transpiler.parser; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Locale; import java.util.Map; @@ -35,7 +40,10 @@ /// the first time a source uses the escape. The names the Unicode standard /// derives by algorithm are computed instead, because the JDK spells them /// differently from Python ("CJK UNIFIED IDEOGRAPHS 4E00" rather than -/// "CJK UNIFIED IDEOGRAPH-4E00"). Python's name aliases are not covered. +/// "CJK UNIFIED IDEOGRAPH-4E00"). Python also accepts the formal name +/// aliases ("BYTE ORDER MARK", "LINE FEED", "NBSP"), which the JDK does not +/// know; they come from the Unicode Character Database's `NameAliases.txt`, +/// kept verbatim beside this class. final class UnicodeNames { private static final String[] JAMO_L = {"G", "GG", "N", "D", "DD", "R", "M", "B", "BB", "S", "SS", "", "J", "JJ", "C", "K", "T", "P", "H"}; @@ -45,6 +53,7 @@ final class UnicodeNames { "LT", "LP", "LH", "M", "B", "BS", "S", "SS", "NG", "J", "C", "K", "T", "P", "H"}; private static Map table; + private static Map aliases; private UnicodeNames() { } @@ -57,9 +66,36 @@ static int lookup(String name) { return cp; } Integer v = table().get(key); + if (v == null) { + v = aliases().get(key); + } return v == null ? -1 : v.intValue(); } + private static synchronized Map aliases() { + if (aliases == null) { + Map m = new HashMap(); + try (InputStream in = UnicodeNames.class.getResourceAsStream("NameAliases.txt")) { + if (in == null) { + throw new IllegalStateException("NameAliases.txt is missing from the transpiler"); + } + try (BufferedReader r = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8))) { + for (String l = r.readLine(); l != null; l = r.readLine()) { + String[] f = l.split(";"); + if (l.startsWith("#") || f.length < 2) { + continue; + } + m.put(f[1].trim(), Integer.valueOf(Integer.parseInt(f[0].trim(), 16))); + } + } + } catch (IOException e) { + throw new IllegalStateException("cannot read NameAliases.txt", e); + } + aliases = m; + } + return aliases; + } + private static int derived(String key) { String[] hexPrefixes = {"CJK UNIFIED IDEOGRAPH-", "CJK COMPATIBILITY IDEOGRAPH-", "TANGUT IDEOGRAPH-", "KHITAN SMALL SCRIPT CHARACTER-", "NUSHU CHARACTER-"}; diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/site/PIL/Image.py b/maven/python-transpiler/src/main/resources/com/codename1/python/site/PIL/Image.py index 62e01b970c0..0230a39a5c5 100644 --- a/maven/python-transpiler/src/main/resources/com/codename1/python/site/PIL/Image.py +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/site/PIL/Image.py @@ -135,6 +135,27 @@ def _wrap(mode, size, handle): class Image: format = None + # The file an opened image was read from, as Pillow keeps it: a file + # object passed in, or a BytesIO of a named file's bytes. + fp = None + + # The bytes of an opened JPEG not decoded yet (see _im). + _lazy = None + _imv = None + + @property + def _im(self): + h = self._imv + if h is None and self._lazy is not None: + data = self._lazy + self._lazy = None + h = self._imv = _cn1image.jpeg_decode(data) + return h + + @_im.setter + def _im(self, v): + self._imv = v + self._lazy = None def __init__(self): self.mode = "" @@ -494,8 +515,22 @@ def open(fp, mode="r", formats=None): if isinstance(fp, (str, os.PathLike)): with builtins.open(os.fspath(fp), "rb") as f: data = f.read() + import io + source = io.BytesIO(data) else: + # Pillow reads a file object from its start, wherever it was left + try: + fp.seek(0) + except (AttributeError, OSError): + pass data = fp.read() + source = fp + im = _open_data(fp, data) + im.fp = source + return im + + +def _open_data(fp, data): if data[:8] == _PNG_SIG and not _cn1image.exact(): # A device decodes through the platform, then takes the file's mode mode = {0: "L", 2: "RGB", 3: "RGBA", 4: "LA", 6: "RGBA"}.get(data[25], "RGBA") @@ -507,9 +542,16 @@ def open(fp, mode="r", formats=None): im.format = "PNG" return im if data[:3] == b"\xff\xd8\xff": - handle = _cn1image.jpeg_decode(data) - mode = "L" if len(_cn1image.getpixel(handle, 0, 0)) == 1 else "RGB" - im = _wrap(mode, _cn1image.size(handle), handle) + head = _jpeg_header(data) + if head is None: + handle = _cn1image.jpeg_decode(data) + mode = "L" if len(_cn1image.getpixel(handle, 0, 0)) == 1 else "RGB" + im = _wrap(mode, _cn1image.size(handle), handle) + else: + # As Pillow does, open reads the header; the pixels are decoded + # when first used (python-pptx opens every picture for its size). + im = _wrap(head[0], head[1], None) + im._lazy = data im.format = "JPEG" return im kind = None @@ -531,6 +573,40 @@ def open(fp, mode="r", formats=None): return im +# Start-of-frame markers: baseline, extended, progressive, lossless, and +# their differential and arithmetic-coded forms. +_SOF = frozenset((0xC0, 0xC1, 0xC2, 0xC3, 0xC5, 0xC6, 0xC7, 0xC9, 0xCA, 0xCB, 0xCD, 0xCE, 0xCF)) + + +def _jpeg_header(data): + """(mode, (width, height)) from a JPEG's frame header, or None.""" + i = 2 + n = len(data) + while i + 4 <= n: + if data[i] != 0xFF: + return None + marker = data[i + 1] + if marker == 0xFF: + i += 1 + continue + if marker == 0xD8 or 0xD0 <= marker <= 0xD7 or marker == 0x01: + i += 2 + continue + length = (data[i + 2] << 8) | data[i + 3] + if marker in _SOF: + if i + 10 > n: + return None + h = (data[i + 5] << 8) | data[i + 6] + w = (data[i + 7] << 8) | data[i + 8] + if w == 0 or h == 0: + return None + return ("L" if data[i + 9] == 1 else "RGB"), (w, h) + if marker == 0xDA or length < 2: + return None + i += 2 + length + return None + + def _native_decode(data): if not _cn1image.native_available(): raise OSError("decoding an image on a device needs a running Codename One display") diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/site/attr/__init__.py b/maven/python-transpiler/src/main/resources/com/codename1/python/site/attr/__init__.py index 6db8e8a2bb6..f2ac51da37c 100644 --- a/maven/python-transpiler/src/main/resources/com/codename1/python/site/attr/__init__.py +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/site/attr/__init__.py @@ -3,9 +3,12 @@ # exception, as the rest of the Codename One Python runtime. """Classes without boilerplate: the attrs API. -Written from the documented behaviour of attrs. The generated methods are -closures over the attribute list, since no source text is compiled at run -time. +Written from the documented behaviour of attrs. Nothing is generated at +run time: the build writes every method of an attrs class into the class +itself (codegen.AttrsLowering), each naming its fields literally, and the +class decorator is replaced by _cn1_finish, which only builds the Attribute +list the methods index. A class the build cannot see whole -- one made by +make_class, or a decorator applied to type(...) -- is refused at build time. """ from dataclasses import _is_classvar @@ -107,6 +110,9 @@ def __init__(self, name, default, validator, repr, cmp, hash, init, inherited, m self.inherited = inherited self.on_setattr = on_setattr self.alias = alias + # The hook an assignment runs (the field's own, else the class's), + # set by _cn1_finish and read by the generated properties. + self._cn1_hook = None @property def cmp(self): @@ -116,8 +122,28 @@ def evolve(self, **changes): new = Attribute(self.name, self.default, self.validator, self.repr, None, self.hash, self.init, self.inherited, self.metadata, self.type, self.converter, self.kw_only, self.eq, self.eq_key, self.order, self.order_key, self.on_setattr, self.alias) - for k, v in changes.items(): - setattr(new, k, v) + # Each attribute named literally: no store by a computed name. + for k in changes: + if k not in _ATTRIBUTE_FIELDS: + raise TypeError("Attribute has no field " + repr(k)) + g = changes.get + new.name = g("name", new.name) + new.default = g("default", new.default) + new.validator = g("validator", new.validator) + new.repr = g("repr", new.repr) + new.hash = g("hash", new.hash) + new.init = g("init", new.init) + new.inherited = g("inherited", new.inherited) + new.metadata = g("metadata", new.metadata) + new.type = g("type", new.type) + new.converter = g("converter", new.converter) + new.kw_only = g("kw_only", new.kw_only) + new.eq = g("eq", new.eq) + new.eq_key = g("eq_key", new.eq_key) + new.order = g("order", new.order) + new.order_key = g("order_key", new.order_key) + new.on_setattr = g("on_setattr", new.on_setattr) + new.alias = g("alias", new.alias) return new def __repr__(self): @@ -141,6 +167,11 @@ def __hash__(self): return hash((self.name, self.inherited, self.alias)) +_ATTRIBUTE_FIELDS = frozenset(("name", "default", "validator", "repr", "hash", "init", "inherited", "metadata", + "type", "converter", "kw_only", "eq", "eq_key", "order", "order_key", + "on_setattr", "alias")) + + class _CountingAttr: """What attr.ib()/field() return until the class decorator collects it.""" @@ -297,9 +328,9 @@ def _run_validator(instance, attrib, value): def validate(inst): if validators.get_disabled(): return - for a in fields(inst.__class__): + for a, v in zip(fields(inst.__class__), inst.__cn1_attrs_values__()): if a.validator is not None: - a.validator(inst, a, getattr(inst, a.name)) + a.validator(inst, a, v) def _is_attrs_instance(obj): @@ -310,8 +341,7 @@ def asdict(inst, recurse=True, filter=None, dict_factory=dict, retain_collection value_serializer=None): result = dict_factory() items = [] - for a in fields(inst.__class__): - v = getattr(inst, a.name) + for a, v in zip(fields(inst.__class__), inst.__cn1_attrs_values__()): if filter is not None and not filter(a, v): continue if value_serializer is not None: @@ -347,8 +377,7 @@ def _asdict_value(v, filter, dict_factory, retain, serializer): def astuple(inst, recurse=True, filter=None, tuple_factory=tuple, retain_collection_types=False): rv = [] - for a in fields(inst.__class__): - v = getattr(inst, a.name) + for a, v in zip(fields(inst.__class__), inst.__cn1_attrs_values__()): if filter is not None and not filter(a, v): continue if recurse is True: @@ -381,25 +410,29 @@ def evolve(*args, **changes): raise TypeError("evolve() takes 1 positional argument, but %d were given" % len(args)) inst = args[0] cls = inst.__class__ - for a in fields(cls): + for a, v in zip(fields(cls), inst.__cn1_attrs_values__()): if not a.init: continue name = a.alias if name not in changes: - changes[name] = getattr(inst, a.name) + changes[name] = v return cls(**changes) def assoc(inst, **changes): - new = inst.__class__.__new__(inst.__class__) + # Deprecated in attrs. Here it is evolve() keyed by attribute name: the + # copy goes through the generated __init__ (converters and validators + # run), since nothing stores a field by a computed name. names = set(a.name for a in fields(inst.__class__)) for k in changes: if k not in names: raise exceptions.AttrsAttributeNotFoundError( - "{k} is not an attrs attribute on {cl}.".format(k=k, cl=new.__class__)) + "{k} is not an attrs attribute on {cl}.".format(k=k, cl=inst.__class__)) + by_alias = {} for a in fields(inst.__class__): - object.__setattr__(new, a.name, changes.get(a.name, getattr(inst, a.name))) - return new + if a.name in changes: + by_alias[a.alias] = changes[a.name] + return evolve(inst, **by_alias) def cmp_using(eq=None, lt=None, le=None, gt=None, ge=None, require_same_type=True, class_name="Comparable"): @@ -525,148 +558,54 @@ def _initial(attrib, inst): return d -def _make_init(cls, attrs, frozen_class, pre_init, post_init): - init_attrs = [a for a in attrs if a.init] - std = [a for a in init_attrs if not a.kw_only] - kwo = [a for a in init_attrs if a.kw_only] - qualname = cls.__qualname__ + ".__init__" - nstd = len(std) - nreq = len([a for a in std if a.default is NOTHING]) - names = [a.alias for a in std + kwo] +# What the generated methods of a lowered class call (codegen.AttrsLowering). - def __init__(self, *args, **kwargs): - if len(args) > nstd: - if nreq == nstd: - takes = "%d positional argument%s" % (nstd + 1, "" if nstd == 0 else "s") - else: - takes = "from %d to %d positional arguments" % (nreq + 1, nstd + 1) - raise TypeError("%s() takes %s but %d were given" % (qualname, takes, len(args) + 1)) - values = {} - for i in range(len(args)): - values[std[i].alias] = args[i] - for k, v in kwargs.items(): - if k not in names: - raise TypeError(qualname + "() got an unexpected keyword argument " + repr(k)) - if k in values: - raise TypeError(qualname + "() got multiple values for argument " + repr(k)) - values[k] = v - missing = [a.alias for a in std if a.alias not in values and a.default is NOTHING] - if missing: - raise TypeError("%s() missing %d required positional argument%s: %s" - % (qualname, len(missing), "" if len(missing) == 1 else "s", - _and_join(["'" + m + "'" for m in missing]))) - missing = [a.alias for a in kwo if a.alias not in values and a.default is NOTHING] - if missing: - raise TypeError("%s() missing %d required keyword-only argument%s: %s" - % (qualname, len(missing), "" if len(missing) == 1 else "s", - _and_join(["'" + m + "'" for m in missing]))) - if pre_init: - self.__attrs_pre_init__() - assigned = [] - for a in attrs: - if a.init and a.alias in values: - v = values[a.alias] - elif a.default is not NOTHING: - v = _initial(a, self) - else: - continue - if a.converter is not None: - v = _convert_one(a.converter, v, self, a) - object.__setattr__(self, a.name, v) - assigned.append(a) - if not validators.get_disabled(): - for a in assigned: - if a.validator is not None: - a.validator(self, a, getattr(self, a.name)) - if post_init: - self.__attrs_post_init__() - __init__.__qualname__ = qualname - return __init__ +def _cn1_default(a, inst): + return _initial(a, inst) -_active = set() +def _cn1_convert(a, inst, value): + return _convert_value(inst, a, value) -def _make_repr(attrs): - shown = [a for a in attrs if a.repr is not False] +def _cn1_validating(): + return not validators.get_disabled() - def __repr__(self): - key = id(self) - if key in _active: - return "..." - _active.add(key) - try: - qn = self.__class__.__qualname__ - qn = qn.rsplit(">.", 1)[-1] - parts = [] - for a in shown: - v = getattr(self, a.name) - parts.append(a.name + "=" + (repr(v) if a.repr is True else a.repr(v))) - return qn + "(" + ", ".join(parts) + ")" - finally: - _active.discard(key) - return __repr__ - - -def _tuple_getter(attrs, flag): - chosen = [] - for a in attrs: - if flag == "eq": - if a.eq: - chosen.append((a.name, a.eq_key)) - elif a.order: - chosen.append((a.name, a.order_key)) - - def as_tuple(self): - out = [] - for name, key in chosen: - v = getattr(self, name) - out.append(v if key is None else key(v)) - return tuple(out) - return as_tuple - - -def _make_eq(as_tuple): - def __eq__(self, other): - if other.__class__ is not self.__class__: - return NotImplemented - return as_tuple(self) == as_tuple(other) - def __ne__(self, other): - result = __eq__(self, other) - if result is NotImplemented: - return NotImplemented - return not result - return __eq__, __ne__ +def _cn1_on_set(a, inst, value): + h = a._cn1_hook + if h is None: + return value + return h(inst, a, value) -def _make_order(as_tuple, op): - def compare(self, other): - if other.__class__ is not self.__class__: - return NotImplemented - a = as_tuple(self) - b = as_tuple(other) - if op == "__lt__": - return a < b - if op == "__le__": - return a <= b - if op == "__gt__": - return a > b - return a >= b - compare.__name__ = op - return compare - - -def _make_hash(attrs, cls): - hashed = [] - for a in attrs: - if (a.eq if a.hash is None else a.hash): - hashed.append(a.name) - seed = cls.__qualname__ +_active = set() - def __hash__(self): - return hash((seed,) + tuple(getattr(self, n) for n in hashed)) - return __hash__ + +def _cn1_repr(inst, attrs, values): + key = id(inst) + if key in _active: + return "..." + _active.add(key) + try: + qn = inst.__class__.__qualname__ + qn = qn.rsplit(">.", 1)[-1] + parts = [] + for a, v in zip(attrs, values): + if a.repr is False: + continue + parts.append(a.name + "=" + (repr(v) if a.repr is True else a.repr(v))) + return qn + "(" + ", ".join(parts) + ")" + finally: + _active.discard(key) + + +def _cn1_frozen_setattr(self, name, value): + raise FrozenInstanceError() + + +def _cn1_frozen_delattr(self, name): + raise FrozenInstanceError() def _hook_for(a, class_hook): @@ -676,68 +615,20 @@ def _hook_for(a, class_hook): return hook -def _make_setattr(attrs, frozen_class, class_hook, parent_setattr): - by_name = dict((a.name, a) for a in attrs) - hooks = {} - if not frozen_class: - for a in attrs: - h = _hook_for(a, class_hook) - if h is not None: - hooks[a.name] = h - - def __setattr__(self, name, value): - if frozen_class: - raise FrozenInstanceError() - h = hooks.get(name) - if h is not None: - value = h(self, by_name[name], value) - object.__setattr__(self, name, value) - - def __delattr__(self, name): - if frozen_class: - raise FrozenInstanceError() - object.__delattr__(self, name) - return __setattr__, __delattr__, len(hooks) > 0 - - -def _has_own(cls, name): - return name in cls.__dict__ - - -def _wrap(cls, these, repr_, eq, order, hash_, init, frozen_, kw_only, auto_attribs, auto_detect, on_setattr, - define_mode, match_args, field_transformer, unsafe_hash): - if unsafe_hash is not None: - hash_ = unsafe_hash - if auto_detect: - if _has_own(cls, "__repr__"): - repr_ = False - if _has_own(cls, "__init__"): - init = False - has_eq = _has_own(cls, "__eq__") or _has_own(cls, "__ne__") - if has_eq and eq is None: - eq = False - has_order = (_has_own(cls, "__lt__") or _has_own(cls, "__le__") or _has_own(cls, "__gt__") or - _has_own(cls, "__ge__")) - if has_order and order is None: - order = False - if hash_ is None and _has_own(cls, "__hash__"): - hash_ = False - if eq is None: - eq = True - if order is None: - order = eq if not define_mode else False - if order and not eq: - raise ValueError("`order` can only be True if `eq` is True too.") - if isinstance(on_setattr, (list, tuple)): - on_setattr = setters.pipe(*on_setattr) - if frozen_ and on_setattr is not None: - raise ValueError("Frozen classes can't use on_setattr.") - own, _ = _collect_own(cls, these, auto_attribs, kw_only) +def _cn1_finish(cls): + """The decorator of a lowered attrs class: builds __attrs_attrs__.""" + lowered = cls.__dict__.get("__cn1_attrs_lowered__") + if lowered is None: + raise TypeError("attrs class " + cls.__qualname__ + " was not lowered at build time") + names, rows, kw_only, frozen_, on_setattr, define_mode, match_args = lowered + annotations = cls.__dict__.get("__annotations__", {}) + own = [_attribute_from(n, ca, annotations.get(n), kw_only) for n, ca in rows] taken = set(a.name for a in own) - base = _collect_base(cls, taken, kw_only) - attrs = base + own - if field_transformer is not None: - attrs = list(field_transformer(cls, attrs)) + attrs = _collect_base(cls, taken, kw_only) + own + seen = tuple(a.name for a in attrs) + if seen != names: + raise TypeError("attrs class " + cls.__qualname__ + " has attributes " + repr(seen) + " but was built for " + + repr(names) + ": its attrs bases must be in the same module") had_default = False for a in attrs: if a.init is not False and a.kw_only is False: @@ -746,134 +637,64 @@ def _wrap(cls, these, repr_, eq, order, hash_, init, frozen_, kw_only, auto_attr "factory. Attribute in question: " + repr(a)) if a.default is not NOTHING: had_default = True - # Class-level cleanup: the placeholders must not remain as class attributes. - base_names = set(a.name for a in base) - for a in own: - if a.name not in base_names or True: - v = cls.__dict__.get(a.name, NOTHING) - if v is not NOTHING and (isinstance(v, _CountingAttr) or these is None): - delattr(cls, a.name) - cls.__attrs_attrs__ = _AttrsTuple(attrs) + if isinstance(on_setattr, (list, tuple)): + on_setattr = setters.pipe(*on_setattr) + if frozen_ and on_setattr is not None: + raise ValueError("Frozen classes can't use on_setattr.") if define_mode and on_setattr is None and not frozen_: on_setattr = setters.pipe(setters.convert, setters.validate) - if init: - cls.__init__ = _make_init(cls, attrs, frozen_, hasattr(cls, "__attrs_pre_init__"), - hasattr(cls, "__attrs_post_init__")) - if repr_: - cls.__repr__ = _make_repr(attrs) - if eq: - as_tuple = _tuple_getter(attrs, "eq") - cls.__eq__, cls.__ne__ = _make_eq(as_tuple) - if order: - ot = _tuple_getter(attrs, "order") - for op in ("__lt__", "__le__", "__gt__", "__ge__"): - setattr(cls, op, _make_order(ot, op)) + if not frozen_: + for a in attrs: + a._cn1_hook = _hook_for(a, on_setattr) + cls.__attrs_attrs__ = _AttrsTuple(attrs) if frozen_: - cls.__setattr__, cls.__delattr__, _ = _make_setattr(attrs, True, None, None) - elif on_setattr is not None or any(a.on_setattr is not None for a in attrs): - any_hooks = False - s, d, any_hooks = _make_setattr(attrs, False, on_setattr, None) - if any_hooks and (define_mode is False or any(a.validator is not None or a.converter is not None or - a.on_setattr is not None for a in attrs)): - cls.__setattr__ = s - if hash_ is True: - cls.__hash__ = _make_hash(attrs, cls) - elif hash_ is None: - if eq and frozen_: - cls.__hash__ = _make_hash(attrs, cls) - elif eq: - cls.__hash__ = None - elif hash_ is False: - pass + cls.__setattr__ = _cn1_frozen_setattr + cls.__delattr__ = _cn1_frozen_delattr if match_args and "__match_args__" not in cls.__dict__: cls.__match_args__ = tuple(a.alias for a in attrs if a.init and not a.kw_only) return cls +def _not_lowered(*args, **kwargs): + raise TypeError("attrs: this class was not lowered at build time; decorate a class statement with a " + "decorator the build can read") + + def attrs(maybe_cls=None, these=None, repr_ns=None, repr=None, cmp=None, hash=None, init=None, slots=False, frozen=False, weakref_slot=True, str=False, auto_attribs=False, kw_only=False, cache_hash=False, auto_exc=False, eq=None, order=None, auto_detect=False, collect_by_mro=False, getstate_setstate=None, on_setattr=None, field_transformer=None, match_args=True, unsafe_hash=None): - eq, order = _eq_order_class(cmp, eq, order) - - def wrap(cls): - return _wrap(cls, these, True if repr is None else repr, eq, order, hash, True if init is None else init, - frozen, kw_only, auto_attribs, auto_detect, on_setattr, False, match_args, field_transformer, - unsafe_hash) + # Every class statement it decorates is lowered at build time, and any + # other use is refused there: reaching this means neither happened. if maybe_cls is None: - return wrap - return wrap(maybe_cls) - - -def _eq_order_class(cmp, eq, order): - if cmp is not None and (eq is not None or order is not None): - raise ValueError("Don't mix `cmp` with `eq' and `order`.") - if cmp is not None: - return cmp, cmp - return eq, order + return _not_lowered + return _not_lowered(maybe_cls) s = attrs attributes = attrs -def dataclass(maybe_cls=None, *, these=None, repr=True, unsafe_hash=None, hash=None, init=True, slots=False, - frozen=False, weakref_slot=True, str=False, auto_attribs=True, kw_only=False, cache_hash=False, - auto_exc=True, eq=True, order=False, auto_detect=True, getstate_setstate=None, on_setattr=None, - field_transformer=None, match_args=True): - return attrs(maybe_cls, these=these, repr=repr, hash=hash, init=init, slots=slots, frozen=frozen, - auto_attribs=auto_attribs, kw_only=kw_only, eq=eq, order=order, auto_detect=auto_detect, - on_setattr=on_setattr, field_transformer=field_transformer, match_args=match_args, - unsafe_hash=unsafe_hash) - - -def define(maybe_cls=None, *, these=None, repr=None, unsafe_hash=None, hash=None, init=None, slots=True, - frozen=False, weakref_slot=True, str=False, auto_attribs=None, kw_only=False, cache_hash=False, - auto_exc=True, eq=None, order=False, auto_detect=True, getstate_setstate=None, on_setattr=None, - field_transformer=None, match_args=True): - def wrap(cls): - return _wrap(cls, these, True if repr is None else repr, eq, order, hash, True if init is None else init, - frozen, kw_only, auto_attribs, auto_detect, on_setattr, True, match_args, field_transformer, - unsafe_hash) - if maybe_cls is None: - return wrap - return wrap(maybe_cls) +def dataclass(maybe_cls=None, **kwargs): + return attrs(maybe_cls) + + +def define(maybe_cls=None, **kwargs): + return attrs(maybe_cls) mutable = define def frozen(maybe_cls=None, **kwargs): - kwargs["frozen"] = True - return define(maybe_cls, **kwargs) + return attrs(maybe_cls) def make_class(name, attrs, bases=(object,), class_body=None, **attributes_arguments): - if isinstance(attrs, dict): - cls_dict = {} - for k, v in attrs.items(): - cls_dict[k] = v - cd = dict((k, _recount(v)) for k, v in cls_dict.items()) - elif isinstance(attrs, (list, tuple)): - cd = {} - for k in attrs: - cd[k] = attrib() - else: - raise TypeError("attrs argument must be a dict or a list.") - if class_body is not None: - cd.update(class_body) - cls = type(name, tuple(bases), cd) - return attrs_decorator(cls, attributes_arguments) - - -def _recount(v): - if isinstance(v, _CountingAttr): - v.counter = _next_count() - return v - - -def attrs_decorator(cls, kwargs): - return globals()["attrs"](cls, **kwargs) + # A class made at run time has no layout and no generated methods; the + # build refuses every call of this. + raise TypeError("attrs.make_class builds a class at run time, which a closed-world build cannot compile; " + "declare the class with @define") from attr import converters, filters, setters, validators # noqa: E402 (they import names defined above) diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/site/cobble/__init__.py b/maven/python-transpiler/src/main/resources/com/codename1/python/site/cobble/__init__.py new file mode 100644 index 00000000000..3b5034356f5 --- /dev/null +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/site/cobble/__init__.py @@ -0,0 +1,60 @@ +# Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. +# Licensed under the GNU General Public License version 2 with the Classpath +# exception, as the rest of the Codename One Python runtime. +"""cobble: data classes and visitors, lowered at build time. + +The real package generates __init__, __repr__, __eq__, __ne__, __hash__ and +the visitor's _accept methods as source text and exec()s it. Here the +transpiler writes them into each @data / @visitable class body with static +names (codegen.CobbleLowering) and drops the decorator, so data() and +visitable() are only reached by a class it could not lower, which strict +mode refuses anyway. copy() and visitor() dispatch through the generated +_cobble_copy and _accept0 / _accept1 methods. +""" + +import itertools + +__all__ = ["data", "field", "visitable", "visitor", "copy"] + +_sort_key_count = itertools.count() +_undefined = object() + + +class _Field(object): + def __init__(self, sort_key, default): + self.sort_key = sort_key + self.default = default + + +def field(default=_undefined): + if default not in [_undefined, None]: + raise TypeError("default value must be None") + return _Field(next(_sort_key_count), default=default) + + +def data(cls): + return cls + + +def visitable(cls): + return cls + + +class _Visitor(object): + # One class for every visitor() call, so a class built on it has one + # known base. A visitor made with args=1 is always called with its one + # extra argument, so the argument count picks the accept method. + def visit(self, value, *rest): + if rest: + return value._accept1(self, *rest) + return value._accept0(self) + + +def visitor(cls, args=None): + if args is not None and args not in (0, 1): + raise ValueError("cobble.visitor supports args=0 or args=1") + return _Visitor + + +def copy(obj, **kwargs): + return obj._cobble_copy(**kwargs) diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/site/cryptography/__init__.py b/maven/python-transpiler/src/main/resources/com/codename1/python/site/cryptography/__init__.py new file mode 100644 index 00000000000..c7424a87ad1 --- /dev/null +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/site/cryptography/__init__.py @@ -0,0 +1,11 @@ +# Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. +# Licensed under the GNU General Public License version 2 with the Classpath +# exception, as the rest of the Codename One Python runtime. +"""cryptography: the symmetric cipher subset, over Codename One's own AES. + +Only `hazmat.primitives.ciphers` with AES in CBC and ECB modes is provided +(what pdfminer needs to read encrypted PDFs). The block cipher itself is +`com.codename1.security.Cipher`, which each port backs with its platform +implementation.""" + +__version__ = "44.0.0" diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/site/cryptography/hazmat/__init__.py b/maven/python-transpiler/src/main/resources/com/codename1/python/site/cryptography/hazmat/__init__.py new file mode 100644 index 00000000000..7a5aa707338 --- /dev/null +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/site/cryptography/hazmat/__init__.py @@ -0,0 +1,4 @@ +# Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. +# Licensed under the GNU General Public License version 2 with the Classpath +# exception, as the rest of the Codename One Python runtime. +"""cryptography.hazmat.""" diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/site/cryptography/hazmat/backends/__init__.py b/maven/python-transpiler/src/main/resources/com/codename1/python/site/cryptography/hazmat/backends/__init__.py new file mode 100644 index 00000000000..252e528c3f3 --- /dev/null +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/site/cryptography/hazmat/backends/__init__.py @@ -0,0 +1,8 @@ +# Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. +# Licensed under the GNU General Public License version 2 with the Classpath +# exception, as the rest of the Codename One Python runtime. +"""cryptography.hazmat.backends: there is one backend, the platform's.""" + + +def default_backend(): + return None diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/site/cryptography/hazmat/primitives/__init__.py b/maven/python-transpiler/src/main/resources/com/codename1/python/site/cryptography/hazmat/primitives/__init__.py new file mode 100644 index 00000000000..9e7fba2b55d --- /dev/null +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/site/cryptography/hazmat/primitives/__init__.py @@ -0,0 +1,4 @@ +# Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. +# Licensed under the GNU General Public License version 2 with the Classpath +# exception, as the rest of the Codename One Python runtime. +"""cryptography.hazmat.primitives.""" diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/site/cryptography/hazmat/primitives/ciphers/__init__.py b/maven/python-transpiler/src/main/resources/com/codename1/python/site/cryptography/hazmat/primitives/ciphers/__init__.py new file mode 100644 index 00000000000..cc966673de4 --- /dev/null +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/site/cryptography/hazmat/primitives/ciphers/__init__.py @@ -0,0 +1,77 @@ +# Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. +# Licensed under the GNU General Public License version 2 with the Classpath +# exception, as the rest of the Codename One Python runtime. +"""cryptography.hazmat.primitives.ciphers: Cipher, algorithms.AES, modes.CBC/ECB. + +A context collects its input and runs the platform cipher once in +finalize(); update() returns whole blocks only after finalize, which is +legal for the API (update may buffer) and what every caller that ends with +finalize() expects. Padding is the caller's, as in the real package: +the transformations used are the NoPadding ones. +""" + +import _cn1aes + +from . import algorithms, modes + +__all__ = ["Cipher", "algorithms", "modes"] + + +class _Context: + def __init__(self, cipher, encrypt): + self._cipher = cipher + self._encrypt = encrypt + self._buf = bytearray() + self._done = False + + def update(self, data): + if self._done: + raise ValueError("Context was already finalized.") + self._buf += data + return b"" + + def update_into(self, data, buf): + raise NotImplementedError("update_into is not supported") + + def finalize(self): + if self._done: + raise ValueError("Context was already finalized.") + self._done = True + data = bytes(self._buf) + if len(data) % 16: + raise ValueError("The length of the provided data is not a multiple of the block length.") + if not data: + return b"" + mode = self._cipher.mode + key = self._cipher.algorithm.key + if isinstance(mode, modes.ECB): + # ECB is CBC with a zero IV, one block at a time. + out = bytearray() + zero = b"\0" * 16 + for i in range(0, len(data), 16): + block = data[i:i + 16] + if self._encrypt: + out += _cn1aes.cbc_encrypt(key, zero, block) + else: + out += _cn1aes.cbc_decrypt(key, zero, block) + return bytes(out) + iv = mode.initialization_vector + if self._encrypt: + return _cn1aes.cbc_encrypt(key, iv, data) + return _cn1aes.cbc_decrypt(key, iv, data) + + +class Cipher: + def __init__(self, algorithm, mode, backend=None): + if not isinstance(algorithm, algorithms.AES): + raise NotImplementedError("only AES is supported") + if not isinstance(mode, (modes.CBC, modes.ECB)): + raise NotImplementedError("only CBC and ECB modes are supported") + self.algorithm = algorithm + self.mode = mode + + def encryptor(self): + return _Context(self, True) + + def decryptor(self): + return _Context(self, False) diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/site/cryptography/hazmat/primitives/ciphers/algorithms.py b/maven/python-transpiler/src/main/resources/com/codename1/python/site/cryptography/hazmat/primitives/ciphers/algorithms.py new file mode 100644 index 00000000000..d6769284cf5 --- /dev/null +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/site/cryptography/hazmat/primitives/ciphers/algorithms.py @@ -0,0 +1,19 @@ +# Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. +# Licensed under the GNU General Public License version 2 with the Classpath +# exception, as the rest of the Codename One Python runtime. +"""cryptography.hazmat.primitives.ciphers.algorithms: AES.""" + + +class AES: + name = "AES" + block_size = 128 + + def __init__(self, key): + key = bytes(key) + if len(key) not in (16, 24, 32): + raise ValueError("Invalid key size (%d) for AES." % (len(key) * 8)) + self.key = key + + @property + def key_size(self): + return len(self.key) * 8 diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/site/cryptography/hazmat/primitives/ciphers/modes.py b/maven/python-transpiler/src/main/resources/com/codename1/python/site/cryptography/hazmat/primitives/ciphers/modes.py new file mode 100644 index 00000000000..10ce61d4874 --- /dev/null +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/site/cryptography/hazmat/primitives/ciphers/modes.py @@ -0,0 +1,18 @@ +# Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. +# Licensed under the GNU General Public License version 2 with the Classpath +# exception, as the rest of the Codename One Python runtime. +"""cryptography.hazmat.primitives.ciphers.modes: CBC and ECB.""" + + +class CBC: + name = "CBC" + + def __init__(self, initialization_vector): + initialization_vector = bytes(initialization_vector) + if len(initialization_vector) != 16: + raise ValueError("Invalid IV size (%d) for CBC." % len(initialization_vector)) + self.initialization_vector = initialization_vector + + +class ECB: + name = "ECB" diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/site/dateutil/relativedelta.py b/maven/python-transpiler/src/main/resources/com/codename1/python/site/dateutil/relativedelta.py index 30fe2a17710..5ac5d4fdcea 100644 --- a/maven/python-transpiler/src/main/resources/com/codename1/python/site/dateutil/relativedelta.py +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/site/dateutil/relativedelta.py @@ -330,12 +330,14 @@ def __hash__(self): def __repr__(self): parts = [] - for attr in ("years", "months", "days", "leapdays", "hours", "minutes", "seconds", "microseconds"): - value = getattr(self, attr) + for attr, value in (("years", self.years), ("months", self.months), ("days", self.days), + ("leapdays", self.leapdays), ("hours", self.hours), ("minutes", self.minutes), + ("seconds", self.seconds), ("microseconds", self.microseconds)): if value: parts.append("%s=%+g" % (attr, value)) - for attr in ("year", "month", "day", "weekday", "hour", "minute", "second", "microsecond"): - value = getattr(self, attr) + for attr, value in (("year", self.year), ("month", self.month), ("day", self.day), + ("weekday", self.weekday), ("hour", self.hour), ("minute", self.minute), + ("second", self.second), ("microsecond", self.microsecond)): if value is not None: parts.append("%s=%s" % (attr, repr(value))) return "%s(%s)" % (self.__class__.__name__, ", ".join(parts)) diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/site/fastapi/applications.py b/maven/python-transpiler/src/main/resources/com/codename1/python/site/fastapi/applications.py index 58c761d3c53..9c624e4c9bc 100644 --- a/maven/python-transpiler/src/main/resources/com/codename1/python/site/fastapi/applications.py +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/site/fastapi/applications.py @@ -430,9 +430,8 @@ def _schema(self, tp, schemas, p): if p is not None and p.field is not None: if p.field.title: s["title"] = p.field.title - for k in ("gt", "ge", "lt", "le", "min_length", "max_length", "pattern", "multiple_of"): - v = getattr(p.field, k, None) - if v is not None: + for k, v in p.field.constraints().items(): + if True: s[{"gt": "exclusiveMinimum", "ge": "minimum", "lt": "exclusiveMaximum", "le": "maximum", "min_length": "minLength", "max_length": "maxLength", "pattern": "pattern", "multiple_of": "multipleOf"}[k]] = v diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/site/fastapi/params.py b/maven/python-transpiler/src/main/resources/com/codename1/python/site/fastapi/params.py index be3193e0567..83cb741f059 100644 --- a/maven/python-transpiler/src/main/resources/com/codename1/python/site/fastapi/params.py +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/site/fastapi/params.py @@ -41,8 +41,10 @@ def __init__(self, default=Undefined, *, alias=None, title=None, description=Non def constraints(self): out = {} - for k in ("gt", "ge", "lt", "le", "min_length", "max_length", "pattern", "multiple_of"): - v = getattr(self, k) + # Each constraint by its literal name, in the order they were listed. + for k, v in (("gt", self.gt), ("ge", self.ge), ("lt", self.lt), ("le", self.le), + ("min_length", self.min_length), ("max_length", self.max_length), + ("pattern", self.pattern), ("multiple_of", self.multiple_of)): if v is not None: out[k] = v return out diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/site/flask/__init__.py b/maven/python-transpiler/src/main/resources/com/codename1/python/site/flask/__init__.py index 99a5ba6f596..b1ff3ba4825 100644 --- a/maven/python-transpiler/src/main/resources/com/codename1/python/site/flask/__init__.py +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/site/flask/__init__.py @@ -478,14 +478,9 @@ def _get(self): return c.session return c.app - def __getattr__(self, name): - return getattr(self._get(), name) - - def __setattr__(self, name, value): - setattr(self._get(), name, value) - - def __delattr__(self, name): - delattr(self._get(), name) + # No __getattr__/__setattr__: the build gives each program a subclass + # with one forwarding property per attribute name it uses on the proxy + # (codegen FlaskProxyLowering), so no name is looked up at run time. def __contains__(self, name): return name in self._get() @@ -1636,9 +1631,10 @@ def save_session(self, app, sess, resp): def flash(message, category="message"): - flashes = session.get("_flashes", []) + sess = session._get() + flashes = sess.get("_flashes", []) flashes.append([category, message]) - session["_flashes"] = flashes + sess["_flashes"] = flashes def get_flashed_messages(with_categories=False, category_filter=()): diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/site/httpx/__init__.py b/maven/python-transpiler/src/main/resources/com/codename1/python/site/httpx/__init__.py index cdaa072b002..7aba54f1d89 100644 --- a/maven/python-transpiler/src/main/resources/com/codename1/python/site/httpx/__init__.py +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/site/httpx/__init__.py @@ -6,9 +6,14 @@ `httpx.get` and the other verbs, `Client` and `AsyncClient` (base URL, default headers, params and timeout), `Response`, `Request`, `URL`, `Headers` and httpx's exception hierarchy. As in httpx, redirects are not -followed unless `follow_redirects=True`. Streaming, HTTP/2, transports and -file uploads are not provided. The asynchronous client runs each request -to completion when it is awaited. +followed unless `follow_redirects=True`. Transports follow httpx's +interface (`BaseTransport.handle_request`, `HTTPTransport`, `MockTransport`), +so a library that installs its own transport or wraps the default one works +unchanged. A response is read whole before it is returned: `stream=True`, +`Client.stream()` and the `iter_*` methods hand out the body that already +arrived, so a streamed reply (server-sent events) is delivered all at once +when the request completes. HTTP/2 and file uploads are not provided. The +asynchronous client runs each request to completion when it is awaited. """ import datetime as _datetime @@ -118,6 +123,42 @@ class StreamError(RuntimeError): pass +class StreamConsumed(StreamError): + pass + + +class StreamClosed(StreamError): + pass + + +class ResponseNotRead(StreamError): + pass + + +class RequestNotRead(StreamError): + pass + + +class LocalProtocolError(ProtocolError): + pass + + +class RemoteProtocolError(ProtocolError): + pass + + +class ProxyError(TransportError): + pass + + +class WriteError(NetworkError): + pass + + +class CloseError(NetworkError): + pass + + class codes: CONTINUE = 100 OK = 200 @@ -164,13 +205,88 @@ def items(self): def raw(self): return [(k.lower().encode("ascii"), v.encode("ascii")) for k, v in self._items] + def values(self): + return [self[k] for k in self.keys()] + + def copy(self): + return Headers(self.multi_items(), self.encoding) + + def setdefault(self, key, default=None): + if key not in self: + self[key] = default + return self[key] + + def pop(self, key, *default): + if key in self: + v = self[key] + del self[key] + return v + if default: + return default[0] + raise KeyError(key) + + def popitem(self): + keys = self.keys() + if not keys: + raise KeyError("popitem(): headers are empty") + k = keys[-1] + return (k, self.pop(k)) + + def clear(self): + for k in list(self.keys()): + del self[k] + + def __iter__(self): + return iter(self.keys()) + + def __len__(self): + return len(self.keys()) + + def __eq__(self, other): + if isinstance(other, Headers): + return sorted(self.multi_items()) == sorted(other.multi_items()) + try: + return sorted(self.multi_items()) == sorted(Headers(other).multi_items()) + except Exception: + return NotImplemented + def __repr__(self): return f"Headers({dict(self.items())!r})" +def _qp_str(v): + if v is True: + return "true" + if v is False: + return "false" + if v is None: + return "" + return str(v) + + +def _qp_pairs(params): + if params is None: + return [] + if isinstance(params, QueryParams): + return params.multi_items() + if isinstance(params, str): + return _parse_qsl(params.lstrip("?"), keep_blank_values=True) + items = params.items() if hasattr(params, "items") else params + out = [] + for k, v in items: + if isinstance(v, (list, tuple)): + out.extend((str(k), _qp_str(x)) for x in v) + else: + out.append((str(k), _qp_str(v))) + return out + + class QueryParams: - def __init__(self, pairs=()): - self._pairs = list(pairs) + def __init__(self, pairs=(), **kwargs): + if kwargs: + pairs = kwargs + self._pairs = _qp_pairs(pairs) if not isinstance(pairs, (list, tuple)) else \ + [(str(k), _qp_str(v)) for k, v in pairs] def get(self, key, default=None): for k, v in self._pairs: @@ -199,6 +315,34 @@ def items(self): def multi_items(self): return list(self._pairs) + def values(self): + return list(dict(self._pairs).values()) + + def set(self, key, value=None): + return QueryParams([(k, v) for k, v in self._pairs if k != key] + [(key, _qp_str(value))]) + + def add(self, key, value=None): + return QueryParams(self._pairs + [(key, _qp_str(value))]) + + def remove(self, key): + return QueryParams([(k, v) for k, v in self._pairs if k != key]) + + def merge(self, params=None): + other = params if isinstance(params, QueryParams) else QueryParams(_qp_pairs(params)) + keys = set(other.keys()) + return QueryParams([(k, v) for k, v in self._pairs if k not in keys] + other.multi_items()) + + def update(self, params=None): + raise RuntimeError("QueryParams are immutable since 0.18.0. Use q = q.merge(...) to create an updated copy.") + + def __eq__(self, other): + if not isinstance(other, QueryParams): + return False + return sorted(self._pairs) == sorted(other._pairs) + + def __hash__(self): + return hash(str(self)) + def __len__(self): return len(self.keys()) @@ -254,6 +398,54 @@ def fragment(self): def netloc(self): return self._parts.netloc.encode("ascii") + @property + def raw_path(self): + q = self._parts.query + return ((self._parts.path or "/") + ("?" + q if q else "")).encode("ascii") + + @property + def raw_host(self): + return self.host.encode("ascii") + + @property + def raw_scheme(self): + return self.scheme.encode("ascii") + + @property + def username(self): + from urllib.parse import unquote + return unquote(self._parts.username or "") + + @property + def password(self): + from urllib.parse import unquote + return unquote(self._parts.password or "") + + @property + def userinfo(self): + n = self._parts.netloc + return n.rpartition("@")[0].encode("ascii") if "@" in n else b"" + + @property + def raw(self): + return (self.raw_scheme, self.raw_host, self.port, self.raw_path) + + def _with_params(self, params): + q = str(params) + return self.copy_with(query=q) + + def copy_set_param(self, key, value=None): + return self._with_params(self.params.set(key, value)) + + def copy_add_param(self, key, value=None): + return self._with_params(self.params.add(key, value)) + + def copy_remove_param(self, key): + return self._with_params(self.params.remove(key)) + + def copy_merge_params(self, params): + return self._with_params(self.params.merge(params)) + @property def is_absolute_url(self): return bool(self._parts.scheme and self._parts.netloc) @@ -268,8 +460,25 @@ def join(self, url): def copy_with(self, **kwargs): p = self._parts from urllib.parse import urlunsplit - return URL(urlunsplit((kwargs.get("scheme", p.scheme), kwargs.get("netloc", p.netloc), - kwargs.get("path", p.path), kwargs.get("query", p.query), + netloc = kwargs.get("netloc", p.netloc) + if isinstance(netloc, bytes): + netloc = netloc.decode("ascii") + if "host" in kwargs or "port" in kwargs: + host = kwargs.get("host", p.hostname or "") + port = kwargs.get("port", p.port) + userinfo = netloc.rpartition("@")[0] + "@" if "@" in netloc else "" + netloc = userinfo + host + (":" + str(port) if port is not None else "") + query = kwargs.get("query", p.query) + if isinstance(query, bytes): + query = query.decode("ascii") + if "params" in kwargs: + query = str(QueryParams(kwargs["params"])) + raw_path = kwargs.get("raw_path") + path = kwargs.get("path", p.path) + if raw_path is not None: + rp = raw_path.decode("ascii") if isinstance(raw_path, bytes) else raw_path + path, _, query = rp.partition("?") + return URL(urlunsplit((kwargs.get("scheme", p.scheme), netloc, path, query, kwargs.get("fragment", p.fragment)))) def __str__(self): @@ -312,6 +521,40 @@ def __init__(self, method, url, *, params=None, headers=None, content=None, data def read(self): return self.content + @property + def cookies(self): + c = Cookies() + for v in self.headers.get_list("set-cookie"): + pair = v.split(";", 1)[0] + if "=" in pair: + k, _, val = pair.partition("=") + c.set(k.strip(), val.strip()) + return c + + @property + def links(self): + out = {} + h = self.headers.get("link") + if not h: + return out + for part in h.split(","): + seg = [x.strip() for x in part.split(";")] + if not seg[0].startswith("<"): + continue + link = {"url": seg[0].strip("<>")} + for kv in seg[1:]: + k, _, v = kv.partition("=") + link[k.strip()] = v.strip().strip('"') + out[link.get("rel") or link["url"]] = link + return out + + async def aread(self): + return self.content + + @property + def stream(self): + return ByteStream(self.content) + def __repr__(self): return f"" @@ -328,12 +571,12 @@ def __init__(self, status_code, *, headers=None, content=None, text=None, json=N self.headers.setdefault("Content-Type", "application/json") self.content = content if content is not None else b"" self._request = request - self.http_version = "HTTP/1.1" self.elapsed = _datetime.timedelta(0) self.history = [] self.next_request = None self.extensions = {} self.default_encoding = "utf-8" + self.num_bytes_downloaded = len(self.content) @property def request(self): @@ -392,6 +635,43 @@ def iter_lines(self): for line in self.text.splitlines(): yield line + def iter_raw(self, chunk_size=None): + return self.iter_bytes(chunk_size) + + async def aiter_bytes(self, chunk_size=None): + for chunk in self.iter_bytes(chunk_size): + yield chunk + + async def aiter_raw(self, chunk_size=None): + for chunk in self.iter_bytes(chunk_size): + yield chunk + + async def aiter_text(self, chunk_size=None): + for chunk in self.iter_text(chunk_size): + yield chunk + + async def aiter_lines(self): + for line in self.iter_lines(): + yield line + + @property + def http_version(self): + return "HTTP/1.1" + + @property + def is_closed(self): + return getattr(self, "_closed", False) + + @property + def stream(self): + # The body is read whole when the response arrives, so the raw + # stream is the content, iterable both ways as httpx's is. + return ByteStream(self.content) + + @property + def is_stream_consumed(self): + return True + @property def is_informational(self): return 100 <= self.status_code < 200 @@ -441,15 +721,18 @@ def raise_for_status(self): raise HTTPStatusError(message.format(self, error_type=error_type), request=request, response=self) def close(self): - pass + self._closed = True async def aclose(self): - pass + self._closed = True def __repr__(self): return f"" +_UNSET_TIMEOUT = object() + + def _timeout_seconds(timeout): if timeout is None: return None @@ -461,11 +744,30 @@ def _timeout_seconds(timeout): class Timeout: - def __init__(self, timeout=5.0, *, connect=None, read=None, write=None, pool=None): - self.connect = connect if connect is not None else timeout - self.read = read if read is not None else timeout - self.write = write if write is not None else timeout - self.pool = pool if pool is not None else timeout + def __init__(self, timeout=_UNSET_TIMEOUT, *, connect=_UNSET_TIMEOUT, read=_UNSET_TIMEOUT, + write=_UNSET_TIMEOUT, pool=_UNSET_TIMEOUT): + if isinstance(timeout, Timeout): + self.connect, self.read, self.write, self.pool = timeout.connect, timeout.read, timeout.write, timeout.pool + return + if isinstance(timeout, tuple): + timeout = (tuple(timeout) + (None, None, None, None))[:4] + self.connect, self.read, self.write, self.pool = timeout + return + if timeout is _UNSET_TIMEOUT: + if _UNSET_TIMEOUT in (connect, read, write, pool): + raise ValueError("httpx.Timeout must either include a default, or set all four parameters " + "explicitly.") + timeout = None + self.connect = timeout if connect is _UNSET_TIMEOUT else connect + self.read = timeout if read is _UNSET_TIMEOUT else read + self.write = timeout if write is _UNSET_TIMEOUT else write + self.pool = timeout if pool is _UNSET_TIMEOUT else pool + + def as_dict(self): + return {"connect": self.connect, "read": self.read, "write": self.write, "pool": self.pool} + + def __eq__(self, other): + return isinstance(other, Timeout) and self.as_dict() == other.as_dict() def __repr__(self): if self.connect == self.read == self.write == self.pool: @@ -485,6 +787,124 @@ def apply(self, request): _UNSET = object() +class Limits: + """Connection pool limits. The platform's HTTP client manages its own + connections, so these are recorded and not enforced.""" + + def __init__(self, *, max_connections=None, max_keepalive_connections=None, keepalive_expiry=5.0): + self.max_connections = max_connections + self.max_keepalive_connections = max_keepalive_connections + self.keepalive_expiry = keepalive_expiry + + def __repr__(self): + return (f"Limits(max_connections={self.max_connections}, " + f"max_keepalive_connections={self.max_keepalive_connections}, " + f"keepalive_expiry={self.keepalive_expiry})") + + +class Proxy: + """A proxy setting. The platform's network stack applies the device's own + proxy configuration; an explicit proxy is recorded and not used.""" + + def __init__(self, url, *, ssl_context=None, auth=None, headers=None): + self.url = URL(url) + self.auth = auth + self.headers = Headers(headers) + + +class Auth: + """httpx's authentication flow: a generator that may modify the request + and receive the response. The first request the flow yields is sent.""" + requires_request_body = False + requires_response_body = False + + def auth_flow(self, request): + yield request + + def sync_auth_flow(self, request): + return self.auth_flow(request) + + def apply(self, request): + flow = self.sync_auth_flow(request) + try: + next(flow) + except StopIteration: + pass + + +class FunctionAuth(Auth): + def __init__(self, func): + self._func = func + + def auth_flow(self, request): + yield self._func(request) + + +DEFAULT_TIMEOUT_CONFIG = None +DEFAULT_LIMITS = Limits(max_connections=100, max_keepalive_connections=20) +DEFAULT_MAX_REDIRECTS = 20 + + +class BaseTransport: + def handle_request(self, request): + raise NotImplementedError("The 'handle_request' method must be implemented.") + + def close(self): + pass + + def __enter__(self): + return self + + def __exit__(self, *args): + self.close() + + +class AsyncBaseTransport: + async def handle_async_request(self, request): + raise NotImplementedError("The 'handle_async_request' method must be implemented.") + + async def aclose(self): + pass + + +class HTTPTransport(BaseTransport): + """The default transport: Codename One's HTTP client. TLS, proxies and + connection reuse are the platform's.""" + + def __init__(self, verify=True, cert=None, trust_env=True, http1=True, http2=False, limits=None, + proxy=None, uds=None, local_address=None, retries=0, socket_options=None, **kwargs): + self.retries = retries + + def handle_request(self, request): + ext = request.extensions or {} + return _transport(request, ext.get("timeout"), False) + + +class AsyncHTTPTransport(AsyncBaseTransport): + def __init__(self, *args, **kwargs): + self._sync = HTTPTransport(*args, **kwargs) + + async def handle_async_request(self, request): + return self._sync.handle_request(request) + + +class MockTransport(BaseTransport, AsyncBaseTransport): + def __init__(self, handler): + self.handler = handler + + def handle_request(self, request): + r = self.handler(request) + r._request = request + return r + + async def handle_async_request(self, request): + r = self.handler(request) + if hasattr(r, "__await__"): + r = await r + r._request = request + return r + + def _transport(request, timeout, follow_redirects): scheme = request.url.scheme if not scheme: @@ -509,7 +929,14 @@ def _transport(request, timeout, follow_redirects): class Client: def __init__(self, *, auth=None, params=None, headers=None, cookies=None, timeout=5.0, - follow_redirects=False, base_url="", **kwargs): + follow_redirects=False, base_url="", transport=None, mounts=None, limits=None, + max_redirects=DEFAULT_MAX_REDIRECTS, event_hooks=None, trust_env=True, **kwargs): + self._transport = transport + self.max_redirects = max_redirects + self.event_hooks = {"request": [], "response": []} + if event_hooks: + self.event_hooks.update({k: list(v) for k, v in event_hooks.items()}) + self.trust_env = trust_env self.base_url = URL(base_url) if base_url else URL("") self.headers = Headers([("Accept", "*/*"), ("User-Agent", "python-httpx/" + __version__)]) if headers: @@ -544,15 +971,32 @@ def build_request(self, method, url, *, content=None, data=None, files=None, jso return Request(method, self._merge_url(url), params=merged, headers=h, content=content, data=data, json=json, files=files, cookies=jar or None, extensions=extensions) - def send(self, request, *, auth=_UNSET, follow_redirects=_UNSET, timeout=_UNSET): + def _prepare(self, request, auth, timeout): a = self.auth if auth is _UNSET else auth if isinstance(a, tuple): a = BasicAuth(a[0], a[1]) + elif a is not None and callable(a) and not hasattr(a, "apply"): + a = FunctionAuth(a) if a is not None: a.apply(request) - follow = self.follow_redirects if follow_redirects is _UNSET else follow_redirects t = self.timeout if timeout is _UNSET else timeout - r = _transport(request, t, follow) + if request.extensions is None: + request.extensions = {} + request.extensions.setdefault("timeout", t) + for hook in self.event_hooks["request"]: + hook(request) + return t + + def send(self, request, *, stream=False, auth=_UNSET, follow_redirects=_UNSET, timeout=_UNSET): + t = self._prepare(request, auth, timeout) + follow = self.follow_redirects if follow_redirects is _UNSET else follow_redirects + if self._transport is not None: + r = self._transport.handle_request(request) + r._request = request + else: + r = _transport(request, t, follow) + for hook in self.event_hooks["response"]: + hook(r) for value in r.headers.get_list("set-cookie"): name, _, rest = value.partition("=") self.cookies[name.strip()] = rest.split(";", 1)[0] @@ -565,6 +1009,11 @@ def request(self, method, url, *, content=None, data=None, files=None, json=None headers=headers, cookies=cookies, extensions=extensions) return self.send(req, auth=auth, follow_redirects=follow_redirects, timeout=timeout) + def stream(self, method, url, **kwargs): + """The response, as a context manager. Its body has already been + read (see the module documentation).""" + return _StreamContext(self.request(method, url, **kwargs)) + def get(self, url, **kwargs): return self.request("GET", url, **kwargs) @@ -596,16 +1045,41 @@ def __exit__(self, *args): self.close() +class _StreamContext: + def __init__(self, response): + self._response = response + + def __enter__(self): + return self._response + + def __exit__(self, *args): + self._response.close() + + async def __aenter__(self): + return self._response + + async def __aexit__(self, *args): + self._response.close() + + class AsyncClient(Client): - async def send(self, request, *, auth=_UNSET, follow_redirects=_UNSET, timeout=_UNSET): + async def send(self, request, *, stream=False, auth=_UNSET, follow_redirects=_UNSET, timeout=_UNSET): + if self._transport is not None and hasattr(self._transport, "handle_async_request"): + self._prepare(request, auth, timeout) + r = await self._transport.handle_async_request(request) + r._request = request + return r return Client.send(self, request, auth=auth, follow_redirects=follow_redirects, timeout=timeout) + def stream(self, method, url, **kwargs): + return _AsyncStreamContext(self, method, url, kwargs) + async def request(self, method, url, *, content=None, data=None, files=None, json=None, params=None, headers=None, cookies=None, auth=_UNSET, follow_redirects=_UNSET, timeout=_UNSET, extensions=None): req = self.build_request(method, url, content=content, data=data, files=files, json=json, params=params, headers=headers, cookies=cookies, extensions=extensions) - return Client.send(self, req, auth=auth, follow_redirects=follow_redirects, timeout=timeout) + return await self.send(req, auth=auth, follow_redirects=follow_redirects, timeout=timeout) async def get(self, url, **kwargs): return await self.request("GET", url, **kwargs) @@ -671,3 +1145,118 @@ def patch(url, **kwargs): def delete(url, **kwargs): return request("DELETE", url, **kwargs) + + +class _AsyncStreamContext: + def __init__(self, client, method, url, kwargs): + self._client = client + self._args = (method, url, kwargs) + self._response = None + + async def __aenter__(self): + method, url, kwargs = self._args + self._response = await self._client.request(method, url, **kwargs) + return self._response + + async def __aexit__(self, *args): + self._response.close() + + +class Cookies: + """A name to value jar, as a mapping; domains and paths are kept but not + matched -- the platform's HTTP stack keeps the session's own cookies.""" + + def __init__(self, cookies=None): + self._jar = {} + if isinstance(cookies, Cookies): + self._jar = dict(cookies._jar) + elif cookies: + items = cookies.items() if hasattr(cookies, "items") else cookies + for k, v in items: + self.set(k, v) + + def set(self, name, value, domain="", path="/"): + self._jar[name] = (value, domain, path) + + def get(self, name, default=None, domain=None, path=None): + v = self._jar.get(name) + return default if v is None else v[0] + + def delete(self, name, domain=None, path=None): + self._jar.pop(name, None) + + def clear(self, domain=None, path=None): + self._jar.clear() + + def update(self, cookies=None): + for k, v in Cookies(cookies).items(): + self.set(k, v) + + def extract_cookies(self, response): + self.update(response.cookies) + + def set_cookie_header(self, request): + if self._jar: + request.headers["Cookie"] = "; ".join(f"{k}={v}" for k, v in self.items()) + + def items(self): + return [(k, v[0]) for k, v in self._jar.items()] + + def keys(self): + return list(self._jar) + + def values(self): + return [v[0] for v in self._jar.values()] + + def __getitem__(self, name): + return self._jar[name][0] + + def __setitem__(self, name, value): + self.set(name, value) + + def __delitem__(self, name): + del self._jar[name] + + def __contains__(self, name): + return name in self._jar + + def __iter__(self): + return iter(self._jar) + + def __len__(self): + return len(self._jar) + + def __bool__(self): + return bool(self._jar) + + def __repr__(self): + return "" % ", ".join("" % (k, v) for k, v in self.items()) + + +class SyncByteStream: + def __iter__(self): + raise NotImplementedError("The '__iter__' method must be implemented.") + yield b"" + + def close(self): + pass + + +class AsyncByteStream: + async def __aiter__(self): + raise NotImplementedError("The '__aiter__' method must be implemented.") + yield b"" + + async def aclose(self): + pass + + +class ByteStream(SyncByteStream, AsyncByteStream): + def __init__(self, stream=b""): + self._stream = stream + + def __iter__(self): + yield self._stream + + async def __aiter__(self): + yield self._stream diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/site/httpx2/__init__.py b/maven/python-transpiler/src/main/resources/com/codename1/python/site/httpx2/__init__.py new file mode 100644 index 00000000000..a84a85b0210 --- /dev/null +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/site/httpx2/__init__.py @@ -0,0 +1,11 @@ +# Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. +# Licensed under the GNU General Public License version 2 with the Classpath +# exception, as the rest of the Codename One Python runtime. +"""httpx2, the name the httpx 2 series is published under, as the httpx +module itself: the same API over Codename One's HTTP client.""" +from httpx import * # noqa: F401,F403 +from httpx import __version__, _transport # noqa: F401 +from httpx import (Auth, BaseTransport, AsyncBaseTransport, HTTPTransport, AsyncHTTPTransport, # noqa: F401 + MockTransport, Limits, Proxy, FunctionAuth, StreamConsumed, StreamClosed, ResponseNotRead, + RequestNotRead, LocalProtocolError, RemoteProtocolError, ProxyError, WriteError, CloseError) +from httpx2 import _config # noqa: F401 diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/site/httpx2/_config.py b/maven/python-transpiler/src/main/resources/com/codename1/python/site/httpx2/_config.py new file mode 100644 index 00000000000..090e6f43692 --- /dev/null +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/site/httpx2/_config.py @@ -0,0 +1,5 @@ +# Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. +# Licensed under the GNU General Public License version 2 with the Classpath +# exception, as the rest of the Codename One Python runtime. +"""httpx's configuration defaults.""" +from httpx import DEFAULT_LIMITS, DEFAULT_MAX_REDIRECTS, DEFAULT_TIMEOUT_CONFIG, Limits, Proxy, Timeout # noqa: F401 diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/site/jinja2/__init__.py b/maven/python-transpiler/src/main/resources/com/codename1/python/site/jinja2/__init__.py index 063313ec963..5779ca405c4 100644 --- a/maven/python-transpiler/src/main/resources/com/codename1/python/site/jinja2/__init__.py +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/site/jinja2/__init__.py @@ -3,6 +3,12 @@ # exception, as the rest of the Codename One Python runtime. """Clean-room subset of Jinja2, interpreted (no code generation, no eval). +Attribute access is not looked up by name: the build parses every template +whose source is a literal (``Jinja2Lowering``) and writes one accessor per +``.name`` and ``['literal']`` site into ``_cn1_jinja2_tables``, keyed by the +template source and then by tag and position. The tokenizer hands each site +its accessor; a template the build did not see cannot use either form. + Supported: ``{{ expr }}`` with filters and tests, ``{% if/elif/else %}``, ``{% for %}`` (tuple targets, ``loop.*``, ``else``, inline ``if``), ``{% set %}``, ``{% extends %}``/``{% block %}`` with ``super()``, @@ -11,9 +17,11 @@ """ import os as _os +import _cn1_jinja2_tables + from markupsafe import Markup, escape -__all__ = ["Environment", "Template", "DictLoader", "FileSystemLoader", "BaseLoader", +__all__ = ["Environment", "Template", "DictLoader", "FileSystemLoader", "PackageLoader", "BaseLoader", "select_autoescape", "Markup", "escape", "Undefined", "TemplateNotFound", "TemplateSyntaxError", "UndefinedError", "TemplateError"] @@ -130,13 +138,25 @@ def get_source(self, environment, template): if ".." in parts: raise TemplateNotFound(template) for base in self.searchpath: - fn = _os.path.join(base, *parts) - if _os.path.isfile(fn): - with open(fn, "r", encoding=self.encoding) as f: - return f.read(), fn, lambda: True + # A relative search path is the project's own directory, which + # the build packs as package data under /cn1python/. + roots = [base] if base.startswith("/") else [base, "/cn1python/" + base] + for root in roots: + fn = _os.path.join(root, *parts) + if _os.path.isfile(fn): + with open(fn, "r", encoding=self.encoding) as f: + return f.read(), fn, lambda: True raise TemplateNotFound(template) +class PackageLoader(FileSystemLoader): + """The templates a package ships: its data files, under /cn1python/.""" + + def __init__(self, package_name, package_path="templates", encoding="utf-8"): + FileSystemLoader.__init__(self, "/cn1python/" + package_name.replace(".", "/") + "/" + package_path, + encoding) + + class ChoiceLoader(BaseLoader): def __init__(self, loaders): self.loaders = loaders @@ -292,9 +312,28 @@ def _tokenize(s): toks.append(("op", c)) i += 1 toks.append(("end", None)) + # Accessors the build generated for this tag, in token order: one per + # "." site and one per "[" str "]" site (Jinja2Lowering mirrors this). + cur = _CUR + for i in range(len(toks) - 1): + t = toks[i] + if t[0] != "op": + continue + if t[1] == "." or (t[1] == "[" and toks[i + 1][0] == "str" and i + 2 < len(toks) + and toks[i + 2] == ("op", "]")): + if cur[1] >= len(cur[0]): + raise TemplateSyntaxError("attribute or item access in a template the build did not" + " compile; give its source as a literal") + nt = toks[i + 1] + toks[i + 1] = (nt[0], nt[1], cur[0][cur[1]]) + cur[1] += 1 return toks +# [accessors of the tag being parsed, next index] +_CUR = [(), 0] + + class _P: def __init__(self, s): self.t = _tokenize(s) @@ -420,8 +459,14 @@ def postfix(self, e): while True: if self.accept("op", "."): tok = self.next() - e = ("getattr", e, str(tok[1])) + e = ("getattr", e, str(tok[1]), tok[2]) elif self.accept("op", "["): + nt = self.peek() + if nt[0] == "str" and len(nt) == 3 and self.peek(1) == ("op", "]"): + self.next() + self.next() + e = ("getlit", e, nt[1], nt[2]) + continue k = self.expr() self.expect("op", "]") e = ("getitem", e, k) @@ -450,7 +495,8 @@ def postfix(self, e): def primary(self): tok = self.next() - k, v = tok + k = tok[0] + v = tok[1] if k in ("num", "str"): if k == "str": while self.at("str"): @@ -530,7 +576,16 @@ def _params(p): return params -def _parse(tokens): +def _parse(tokens, table=()): + # The build's accessors per lexed tag (text tags hold none). + tags = [] + ti = 0 + for t in tokens: + if t[0] == "text": + tags.append(()) + else: + tags.append(table[ti] if ti < len(table) else ()) + ti += 1 pos = [0] blocks = {} meta = {"extends": None} @@ -543,8 +598,12 @@ def body(ends): if kind == "text": nodes.append(("text", val)) elif kind == "var": + _CUR[0] = tags[pos[0] - 1] + _CUR[1] = 0 nodes.append(("out", _parse_expr(val))) else: + _CUR[0] = tags[pos[0] - 1] + _CUR[1] = 0 word = val.split(None, 1)[0] if val else "" if "(" in word: word = word[:word.index("(")] @@ -598,9 +657,9 @@ def stmt(word, rest): e = ("tuple", items) return ("set", targets, e) filt = None - if p.accept("op", "|"): - fp = _P("__cn1_body|" + rest.split("|", 1)[1]) - filt = fp.expr() + if p.at("op", "|"): + # The filters continue this tag's tokens, never re-tokenized. + filt = p.postfix(("name", "__cn1_body")) b, _, _ = body(("endset",)) return ("setblock", targets[0], b, filt) if word == "block": @@ -682,6 +741,18 @@ class _TemplateModule: def __init__(self, name): self._name = name self._body = "" + self._exports = {} + + def __getitem__(self, key): + return self._exports[key] + + def __getattr__(self, name): + # A template's exports are data (its macros and top-level sets), + # read by key; nothing here reads an attribute by name. + try: + return self._exports[name] + except KeyError: + raise AttributeError(name) def __str__(self): return self._body @@ -803,12 +874,30 @@ def changed(self, *value): return True return False - index = property(lambda self: self.index0 + 1) - revindex = property(lambda self: self.length - self.index0) - revindex0 = property(lambda self: self.length - self.index0 - 1) - first = property(lambda self: self.index0 == 0) - last = property(lambda self: self.index0 == self.length - 1) - previtem = property(lambda self: self._items[self.index0 - 1] if self.index0 > 0 else Undefined()) + @property + def index(self): + return self.index0 + 1 + + @property + def revindex(self): + return self.length - self.index0 + + @property + def revindex0(self): + return self.length - self.index0 - 1 + + @property + def first(self): + return self.index0 == 0 + + @property + def last(self): + return self.index0 == self.length - 1 + + @property + def previtem(self): + return self._items[self.index0 - 1] if self.index0 > 0 else Undefined() + nextitem = property(lambda self: self._items[self.index0 + 1] if self.index0 + 1 < self.length else Undefined()) @@ -816,31 +905,19 @@ def cycle(self, *args): return args[self.index0 % len(args)] -def _attr(obj, name): - if isinstance(obj, Undefined): - obj._fail() - try: - return getattr(obj, name) - except AttributeError: - pass - try: - return obj[name] - except (TypeError, LookupError, AttributeError): - return Undefined(name=name) - - def _item(obj, key): + """``obj[key]`` with a key computed at render time. Jinja falls back to + the attribute of that name; a computed name has no literal accessor, so + for an object that is no container that is an error, not a guess.""" if isinstance(obj, Undefined): obj._fail() try: return obj[key] except (TypeError, LookupError, AttributeError): pass - if isinstance(key, str): - try: - return getattr(obj, key) - except AttributeError: - pass + if isinstance(key, str) and not isinstance(obj, (dict, list, tuple, str, _TemplateModule)): + raise UndefinedError("%r has no item %r; an attribute needs a literal name in the template" + % (type(obj).__name__, key)) return Undefined(name=key) @@ -853,7 +930,7 @@ def _do_default(v, default="", boolean=False): def _do_join(env_ae, v, d="", attribute=None): items = list(v) if attribute is not None: - items = [_attr(x, attribute) for x in items] + items = [_item(x, attribute) for x in items] if env_ae: return escape(d).join(items) return str(d).join(str(x) for x in items) @@ -1017,11 +1094,12 @@ def _setup(self, env, source, name, filename): self.environment = env self.name = name self.filename = filename + table = _cn1_jinja2_tables.TABLES.get(source, ()) if not env.keep_trailing_newline and source.endswith("\n"): source = source[:-1] if source.endswith("\r"): source = source[:-1] - self._nodes, self._blocks, self._extends = _parse(_lex(source)) + self._nodes, self._blocks, self._extends = _parse(_lex(source), table) ae = env.autoescape self.autoescape = bool(ae(name)) if callable(ae) else bool(ae) @@ -1111,7 +1189,7 @@ def _exec(self, n, fr): elif k == "fromimport": mod = self._module(self._eval(n[1], fr)) for name, alias in n[2]: - v = getattr(mod, name, None) + v = mod._exports.get(name) if v is None or name.startswith("_"): v = Undefined(hint="the template %r does not export the requested name %r" % (mod._name, name), name=name) @@ -1148,7 +1226,7 @@ def _module(self, t): for k, v in vars.items(): if k not in self.environment.globals or vars[k] is not self.environment.globals[k]: if not k.startswith("_"): - setattr(mod, k, v) + mod._exports[k] = v mod._body = "".join(out) return mod @@ -1220,8 +1298,14 @@ def _eval(self, e, fr): if name in fr.vars: return fr.vars[name] return Undefined(name=name) - if k == "getattr": - return _attr(self._eval(e[1], fr), e[2]) + if k == "getattr" or k == "getlit": + obj = self._eval(e[1], fr) + if isinstance(obj, Undefined): + obj._fail() + v = e[3](obj) + if v is _cn1_jinja2_tables.MISS: + return Undefined(name=e[2]) + return v if k == "getitem": return _item(self._eval(e[1], fr), self._eval(e[2], fr)) if k == "call": diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/site/jiter/__init__.py b/maven/python-transpiler/src/main/resources/com/codename1/python/site/jiter/__init__.py new file mode 100644 index 00000000000..eebbc8a9b52 --- /dev/null +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/site/jiter/__init__.py @@ -0,0 +1,331 @@ +# Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. +# Licensed under the GNU General Public License version 2 with the Classpath +# exception, as the rest of the Codename One Python runtime. +"""jiter: JSON parsing with a partial mode, for reading a JSON document +while it is still streaming in (the openai SDK's structured outputs). + +The PyPI package is a Rust extension; this is the same API in Python. With +partial_mode on, an unfinished array or object is closed where the input +stops; an unfinished string is dropped ('on') or kept ('trailing-strings'); +an unfinished number, literal or key is dropped. +""" + +import decimal as _decimal + +__all__ = ["from_json", "cache_clear", "cache_usage", "LosslessFloat"] +__version__ = "0.12.0" + + +class LosslessFloat: + def __init__(self, json_float): + self._raw = bytes(json_float) + float(self._raw) + + def as_decimal(self): + return _decimal.Decimal(self._raw.decode("ascii")) + + def __float__(self): + return float(self._raw) + + def __bytes__(self): + return self._raw + + def __str__(self): + return self._raw.decode("ascii") + + def __repr__(self): + return "LosslessFloat(%s)" % (self._raw.decode("ascii"),) + + +class _Incomplete(Exception): + """The input ended inside the value being parsed.""" + + +_WS = " \t\n\r" +_ESC = {'"': '"', "\\": "\\", "/": "/", "b": "\b", "f": "\f", "n": "\n", "r": "\r", "t": "\t"} + + +class _Parser: + def __init__(self, s, allow_inf_nan, partial, trailing, dup, float_mode): + self.s = s + self.n = len(s) + self.i = 0 + self.allow_inf_nan = allow_inf_nan + self.partial = partial + self.trailing = trailing + self.dup = dup + self.float_mode = float_mode + + def error(self, msg): + line = self.s.count("\n", 0, self.i) + 1 + col = self.i - (self.s.rfind("\n", 0, self.i) + 1) + 1 + return ValueError("%s at line %d column %d" % (msg, line, col)) + + def ws(self): + s, i, n = self.s, self.i, self.n + while i < n and s[i] in _WS: + i += 1 + self.i = i + + def eof(self): + if self.partial: + raise _Incomplete() + raise self.error("EOF while parsing a value") + + def value(self): + self.ws() + if self.i >= self.n: + self.eof() + c = self.s[self.i] + if c == "{": + return self.obj() + if c == "[": + return self.arr() + if c == '"': + return self.string(False) + if c == "t": + return self.literal("true", True) + if c == "f": + return self.literal("false", False) + if c == "n": + return self.literal("null", None) + if c == "N": + return self.special("NaN", float("nan")) + if c == "I": + return self.special("Infinity", float("inf")) + if c == "-" and self.s.startswith("-I", self.i): + return self.special("-Infinity", float("-inf")) + if c == "-" or c.isdigit(): + return self.number() + raise self.error("expected value") + + def literal(self, word, value): + end = self.i + len(word) + if self.s[self.i:end] == word: + self.i = end + return value + if end > self.n and word.startswith(self.s[self.i:]): + self.eof() + raise self.error("expected ident") + + def special(self, word, value): + if not self.allow_inf_nan: + raise self.error("expected value") + return self.literal(word, value) + + def number(self): + s, i, n = self.s, self.i, self.n + start = i + if s[i] == "-": + i += 1 + is_float = False + while i < n and s[i].isdigit(): + i += 1 + if i < n and s[i] == ".": + is_float = True + i += 1 + while i < n and s[i].isdigit(): + i += 1 + if i < n and s[i] in "eE": + is_float = True + i += 1 + if i < n and s[i] in "+-": + i += 1 + while i < n and s[i].isdigit(): + i += 1 + text = s[start:i] + digits = text.lstrip("-") + if len(digits) > 1 and digits[0] == "0" and digits[1].isdigit(): + self.i = i + raise self.error("invalid number") + if not digits or digits[0] == "." or digits.endswith((".", "e", "E", "+", "-")) \ + or (len(digits) > 1 and digits[0] == "0" and digits[1].isdigit()): + if i >= n and self.partial: + # Not a number yet; the next chunk may finish it. + raise _Incomplete() + self.i = i + raise self.error("invalid number") + self.i = i + if not is_float: + return int(text) + if self.float_mode == "decimal": + return _decimal.Decimal(text) + if self.float_mode == "lossless-float": + return LosslessFloat(text.encode("ascii")) + return float(text) + + def string(self, key): + s, n = self.s, self.n + i = self.i + 1 + out = [] + start = i + while True: + j = s.find('"', i) + k = s.find("\\", i, j if j >= 0 else n) + if k >= 0: + out.append(s[start:k]) + if k + 1 >= n: + return self.unfinished(out, key) + e = s[k + 1] + if e == "u": + h = s[k + 2:k + 6] + if len(h) < 4: + return self.unfinished(out, key) + cp = int(h, 16) + nxt = k + 6 + if 0xD800 <= cp < 0xDC00 and n - nxt < 6 and "\\u"[:n - nxt] == s[nxt:nxt + 2]: + # Half of a surrogate pair: the rest is in the next chunk. + return self.unfinished(out, key) + if 0xD800 <= cp < 0xDC00 and s.startswith("\\u", nxt): + h2 = s[nxt + 2:nxt + 6] + if len(h2) < 4: + return self.unfinished(out, key) + lo = int(h2, 16) + if 0xDC00 <= lo < 0xE000: + cp = 0x10000 + ((cp - 0xD800) << 10) + (lo - 0xDC00) + nxt += 6 + out.append(chr(cp)) + i = start = nxt + elif e in _ESC: + out.append(_ESC[e]) + i = start = k + 2 + else: + self.i = k + 1 + raise self.error("invalid escape") + continue + if j < 0: + out.append(s[start:]) + return self.unfinished(out, key) + out.append(s[start:j]) + self.i = j + 1 + return "".join(out) + + def unfinished(self, out, key): + self.i = self.n + if self.partial and self.trailing and not key: + return _Trailing("".join(out)) + self.eof() + + def obj(self): + self.i += 1 + result = {} + self.ws() + if self.i >= self.n: + if self.partial: + return result + self.eof() + if self.s[self.i] == "}": + self.i += 1 + return result + while True: + self.ws() + if self.i >= self.n: + return self.close(result) + if self.s[self.i] != '"': + raise self.error("key must be a string") + try: + k = self.string(True) + self.ws() + if self.i >= self.n: + raise _Incomplete() + if self.s[self.i] != ":": + raise self.error("expected ':'") + self.i += 1 + v = self.value() + except _Incomplete: + return self.close(result) + if self.dup and k in result: + raise self.error('Detected duplicate key "%s"' % (k,)) + if isinstance(v, _Trailing): + result[k] = v.text + return self.close(result) + result[k] = v + self.ws() + if self.i >= self.n: + return self.close(result) + c = self.s[self.i] + self.i += 1 + if c == "}": + return result + if c != ",": + self.i -= 1 + raise self.error("expected ',' or '}'") + + def arr(self): + self.i += 1 + result = [] + self.ws() + if self.i >= self.n: + if self.partial: + return result + self.eof() + if self.s[self.i] == "]": + self.i += 1 + return result + while True: + try: + v = self.value() + except _Incomplete: + return self.close(result) + if isinstance(v, _Trailing): + result.append(v.text) + return self.close(result) + result.append(v) + self.ws() + if self.i >= self.n: + return self.close(result) + c = self.s[self.i] + self.i += 1 + if c == "]": + return result + if c != ",": + self.i -= 1 + raise self.error("expected ',' or ']'") + + def close(self, result): + if not self.partial: + self.eof() + self.i = self.n + return result + + +class _Trailing: + def __init__(self, text): + self.text = text + + +def from_json(json_data, /, *, allow_inf_nan=True, cache_mode="all", partial_mode=False, + catch_duplicate_keys=False, float_mode="float"): + if isinstance(json_data, (bytes, bytearray, memoryview)): + text = bytes(json_data).decode("utf-8") + elif isinstance(json_data, str): + text = json_data + else: + raise TypeError("Expected bytes, bytearray or str") + if partial_mode in (True, "on"): + partial, trailing = True, False + elif partial_mode == "trailing-strings": + partial, trailing = True, True + elif partial_mode in (False, "off"): + partial, trailing = False, False + else: + raise ValueError("Invalid partial mode, should be `'off'`, `'on'`, `'trailing-strings'` or a `bool`") + p = _Parser(text, allow_inf_nan, partial, trailing, catch_duplicate_keys, float_mode) + try: + v = p.value() + except _Incomplete: + raise p.error("EOF while parsing a value") + if isinstance(v, _Trailing): + v = v.text + p.ws() + if p.i < p.n: + raise p.error("trailing characters") + return v + + +def cache_clear(): + pass + + +def cache_usage(): + return 0 diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/site/lxml/__init__.py b/maven/python-transpiler/src/main/resources/com/codename1/python/site/lxml/__init__.py new file mode 100644 index 00000000000..be00857ec17 --- /dev/null +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/site/lxml/__init__.py @@ -0,0 +1,13 @@ +# Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. +# Licensed under the GNU General Public License version 2 with the Classpath +# exception, as the rest of the Codename One Python runtime. +"""lxml: a pure-Python subset of the lxml package, providing lxml.etree. + +Only lxml.etree is provided (see that module for what it covers). The C +extensions of the real package -- objectify, html, isoschematron, XSLT -- are +not. +""" + + +def get_include(): + return [] diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/site/lxml/_xpath.py b/maven/python-transpiler/src/main/resources/com/codename1/python/site/lxml/_xpath.py new file mode 100644 index 00000000000..ef3979335bd --- /dev/null +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/site/lxml/_xpath.py @@ -0,0 +1,990 @@ +# Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. +# Licensed under the GNU General Public License version 2 with the Classpath +# exception, as the rest of the Codename One Python runtime. +"""An XPath 1.0 evaluator over lxml.etree's pure-Python elements. + +Location paths on every axis but namespace, following and preceding; +predicates (positional and boolean); unions; the operators; and the core +function library. Variables are not supported. It also evaluates +ElementPath expressions for find()/findall(), which are a subset of XPath +plus the "{uri}local" and "{*}local" name tests. + +Nodes are the elements themselves (kind "e", comments "c", processing +instructions "p", told apart by their _xkind), plus three helper kinds made +on demand: _Doc (the document node above the root), _Attr and _Text. +""" +import math as _math +import re as _re + + +class XPathError(Exception): + pass + + +class XPathEvalError(XPathError): + pass + + +class XPathSyntaxError(XPathError, SyntaxError): + pass + + +_TOKEN = _re.compile( + r"\s*(?:(\d+(?:\.\d*)?|\.\d+)|(\"[^\"]*\"|'[^']*')|(//|::|\.\.|!=|<=|>=|[/()\[\]@,|.=<>+\-*$])" + r"|(\{[^}]*\}(?:[A-Za-z_][\w.\-]*|\*)|[A-Za-z_][\w.\-]*(?::(?:[A-Za-z_][\w.\-]*|\*))?))") + +_AXES = ("ancestor", "ancestor-or-self", "attribute", "child", "descendant", "descendant-or-self", + "following-sibling", "parent", "preceding-sibling", "self") +_REVERSE = ("ancestor", "ancestor-or-self", "preceding-sibling", "parent") +_NODE_TYPES = ("node", "text", "comment", "processing-instruction") +_OPS_BEFORE = ("@", "::", "(", "[", ",", "/", "//", "|", "and", "or", "mod", "div", "*", "=", "!=", + "<", "<=", ">", ">=", "+", "-") + + +def _tokenize(expr): + toks = [] + pos = 0 + n = len(expr) + while pos < n: + m = _TOKEN.match(expr, pos) + if m is None or m.end() == pos: + if expr[pos:].strip() == "": + break + raise XPathSyntaxError("Invalid expression") + pos = m.end() + if m.group(1) is not None: + toks.append(("num", float(m.group(1)))) + elif m.group(2) is not None: + toks.append(("str", m.group(2)[1:-1])) + elif m.group(3) is not None: + op = m.group(3) + if op == "*" and toks and not _is_op_ctx(toks[-1]): + toks.append(("op", "mul")) + else: + toks.append(("op", op)) + else: + name = m.group(4) + if name in ("and", "or", "div", "mod") and toks and not _is_op_ctx(toks[-1]): + toks.append(("op", name)) + else: + toks.append(("name", name)) + toks.append(("end", None)) + return toks + + +def _is_op_ctx(tok): + kind, val = tok + return kind == "op" and val in _OPS_BEFORE + + +class _Parser: + def __init__(self, expr): + self.toks = _tokenize(expr) + self.i = 0 + + def peek(self, off=0): + return self.toks[self.i + off] + + def next(self): + t = self.toks[self.i] + self.i += 1 + return t + + def accept(self, val): + t = self.toks[self.i] + if t[0] == "op" and t[1] == val: + self.i += 1 + return True + return False + + def expect(self, val): + if not self.accept(val): + raise XPathSyntaxError("Invalid expression") + + def parse(self): + e = self.or_expr() + if self.peek()[0] != "end": + raise XPathSyntaxError("Invalid expression") + return e + + def or_expr(self): + e = self.and_expr() + while self.accept("or"): + e = ("or", e, self.and_expr()) + return e + + def and_expr(self): + e = self.eq_expr() + while self.accept("and"): + e = ("and", e, self.eq_expr()) + return e + + def eq_expr(self): + e = self.rel_expr() + while True: + t = self.peek() + if t[0] == "op" and t[1] in ("=", "!="): + self.i += 1 + e = ("cmp", t[1], e, self.rel_expr()) + else: + return e + + def rel_expr(self): + e = self.add_expr() + while True: + t = self.peek() + if t[0] == "op" and t[1] in ("<", "<=", ">", ">="): + self.i += 1 + e = ("cmp", t[1], e, self.add_expr()) + else: + return e + + def add_expr(self): + e = self.mul_expr() + while True: + t = self.peek() + if t[0] == "op" and t[1] in ("+", "-"): + self.i += 1 + e = ("arith", t[1], e, self.mul_expr()) + else: + return e + + def mul_expr(self): + e = self.unary() + while True: + t = self.peek() + if t[0] == "op" and t[1] in ("mul", "div", "mod"): + self.i += 1 + e = ("arith", t[1], e, self.unary()) + else: + return e + + def unary(self): + if self.accept("-"): + return ("neg", self.unary()) + e = self.path_expr() + while self.accept("|"): + e = ("union", e, self.path_expr()) + return e + + def path_expr(self): + t = self.peek() + if t[0] == "op" and t[1] == "/": + self.i += 1 + if self._step_start(): + return ("path", "/", None, self.rel_path([])) + return ("path", "/", None, []) + if t[0] == "op" and t[1] == "//": + self.i += 1 + return ("path", "/", None, self.rel_path([("descendant-or-self", ("node",), [])])) + if self._primary_start(): + prim = self.primary() + preds = [] + while self.peek() == ("op", "["): + preds.append(self.predicate()) + if preds: + prim = ("filter", prim, preds) + t = self.peek() + if t[0] == "op" and t[1] in ("/", "//"): + self.i += 1 + steps = [("descendant-or-self", ("node",), [])] if t[1] == "//" else [] + return ("path", None, prim, self.rel_path(steps)) + return prim + return ("path", None, None, self.rel_path([])) + + def _step_start(self): + t = self.peek() + return t[0] == "name" or (t[0] == "op" and t[1] in ("@", ".", "..", "*")) + + def _primary_start(self): + t = self.peek() + if t[0] in ("num", "str"): + return True + if t[0] == "op" and t[1] in ("(", "$"): + return True + if t[0] == "name" and self.peek(1) == ("op", "(") and t[1] not in _NODE_TYPES: + return True + return False + + def primary(self): + t = self.next() + if t[0] == "num": + return ("num", t[1]) + if t[0] == "str": + return ("str", t[1]) + if t[1] == "(": + e = self.or_expr() + self.expect(")") + return e + if t[1] == "$": + raise XPathEvalError("Undefined variable") + name = t[1] + self.expect("(") + args = [] + if not self.accept(")"): + args.append(self.or_expr()) + while self.accept(","): + args.append(self.or_expr()) + self.expect(")") + return ("call", name, args) + + def predicate(self): + self.expect("[") + e = self.or_expr() + self.expect("]") + return e + + def rel_path(self, steps): + steps.append(self.step()) + while True: + if self.accept("/"): + steps.append(self.step()) + elif self.accept("//"): + steps.append(("descendant-or-self", ("node",), [])) + steps.append(self.step()) + else: + return steps + + def step(self): + if self.accept("."): + return ("self", ("node",), []) + if self.accept(".."): + return ("parent", ("node",), []) + axis = "child" + if self.accept("@"): + axis = "attribute" + else: + t = self.peek() + if t[0] == "name" and self.peek(1) == ("op", "::"): + if t[1] not in _AXES: + raise XPathEvalError("Unsupported axis " + t[1]) + axis = t[1] + self.i += 2 + t = self.next() + if t == ("op", "*") or t == ("op", "mul"): + test = ("name", None, "*", False) + elif t[0] == "name": + name = t[1] + if name in _NODE_TYPES and self.peek() == ("op", "("): + self.i += 1 + arg = None + if self.peek()[0] == "str": + arg = self.next()[1] + self.expect(")") + test = ("pi", arg) if name == "processing-instruction" else (name,) + elif name[:1] == "{": + j = name.index("}") + uri = name[1:j] + if uri == "*": + test = ("name", None, name[j + 1:], True) + else: + test = ("uri", uri or None, name[j + 1:]) + elif ":" in name: + j = name.index(":") + test = ("name", name[:j], name[j + 1:], False) + else: + test = ("name", None, name, False) + else: + raise XPathSyntaxError("Invalid expression") + preds = [] + while self.peek() == ("op", "["): + preds.append(self.predicate()) + return (axis, test, preds) + + +_CACHE = {} + + +def compile_expr(expr): + ast = _CACHE.get(expr) + if ast is None: + ast = _optimize(_Parser(expr).parse()) + if len(_CACHE) > 500: + _CACHE.clear() + _CACHE[expr] = ast + return ast + + +def _optimize(e): + """Fold descendant-or-self::node()/child::x (no predicates) into descendant::x.""" + if isinstance(e, tuple) and e and e[0] == "path": + steps = [] + for s in e[3]: + if (steps and s[0] == "child" and not s[2] and steps[-1] == ("descendant-or-self", ("node",), [])): + steps[-1] = ("descendant", s[1], [_optimize(p) for p in s[2]]) + else: + steps.append((s[0], s[1], [_optimize(p) for p in s[2]])) + return ("path", e[1], _optimize(e[2]) if e[2] is not None else None, steps) + if isinstance(e, tuple) and e and e[0] in ("or", "and", "union"): + return (e[0], _optimize(e[1]), _optimize(e[2])) + if isinstance(e, tuple) and e and e[0] in ("cmp", "arith"): + return (e[0], e[1], _optimize(e[2]), _optimize(e[3])) + if isinstance(e, tuple) and e and e[0] == "call": + return ("call", e[1], [_optimize(a) for a in e[2]]) + if isinstance(e, tuple) and e and e[0] == "filter": + return ("filter", _optimize(e[1]), [_optimize(p) for p in e[2]]) + if isinstance(e, tuple) and e and e[0] == "neg": + return ("neg", _optimize(e[1])) + return e + + +class _Doc: + _xkind = "d" + + def __init__(self, root): + self.root = root + + +class _Attr: + _xkind = "a" + + def __init__(self, owner, name, value, index): + self.owner = owner + self.name = name + self.value = value + self.index = index + + +class _Text: + _xkind = "t" + + def __init__(self, holder, value, is_tail): + self.holder = holder + self.value = value + self.is_tail = is_tail + + +def _top(el): + while el._xparent is not None: + el = el._xparent + return el + + +def _node_root(n): + k = n._xkind + if k == "d": + return n.root + if k == "a": + return _top(n.owner) + if k == "t": + return _top(n.holder) + return _top(n) + + +def _same(a, b): + if a is b: + return True + if a._xkind != b._xkind: + return False + k = a._xkind + if k == "a": + return a.owner is b.owner and a.name == b.name + if k == "t": + return a.holder is b.holder and a.is_tail == b.is_tail + if k == "d": + return a.root is b.root + return False + + +def _ident(n): + k = n._xkind + if k == "a": + return (id(n.owner), "a", n.name) + if k == "t": + return (id(n.holder), "t", n.is_tail) + if k == "d": + return (id(n.root), "d") + return (id(n), "e") + + +def _children(el, with_text): + if el._xkind == "d": + return [el.root] + if el._xkind != "e": + return [] + if not with_text: + return list(el._xkids) + out = [] + if el._xtext: + out.append(_Text(el, el._xtext, False)) + for c in el._xkids: + out.append(c) + if c._xtail: + out.append(_Text(c, c._xtail, True)) + return out + + +def _descendants(el, with_text, out): + for c in _children(el, with_text): + out.append(c) + if c._xkind == "e": + _descendants(c, with_text, out) + return out + + +def _parent(n): + k = n._xkind + if k == "a": + return n.owner + if k == "t": + return n.holder._xparent if n.is_tail else n.holder + if k == "d": + return None + p = n._xparent + if p is None: + return _Doc(n) + return p + + +def _siblings(n, following, with_text): + if n._xkind in ("a", "d"): + return [] + p = _parent(n) + if p is None: + return [] + sibs = _children(p, with_text) + idx = -1 + for i in range(len(sibs)): + if _same(sibs[i], n): + idx = i + break + if idx < 0: + return [] + if following: + return sibs[idx + 1:] + r = sibs[:idx] + r.reverse() + return r + + +def _axis(n, axis, with_text): + if axis == "child": + return _children(n, with_text) + if axis == "attribute": + if n._xkind != "e": + return [] + out = [] + i = 0 + for k, v in n._xattrib.items(): + out.append(_Attr(n, k, v, i)) + i += 1 + return out + if axis == "self": + return [n] + if axis == "descendant": + return _descendants(n, with_text, []) + if axis == "descendant-or-self": + return _descendants(n, with_text, [n]) + if axis == "parent": + p = _parent(n) + return [] if p is None else [p] + if axis == "ancestor" or axis == "ancestor-or-self": + out = [n] if axis == "ancestor-or-self" else [] + p = _parent(n) + while p is not None: + out.append(p) + p = _parent(p) + return out + if axis == "following-sibling": + return _siblings(n, True, with_text) + return _siblings(n, False, with_text) + + +def _split(tag): + if tag[:1] == "{": + j = tag.index("}") + return tag[1:j], tag[j + 1:] + return None, tag + + +def _test(n, axis, test, env): + k = n._xkind + kind = test[0] + if kind == "node": + return True + if kind == "text": + return k == "t" + if kind == "comment": + return k == "c" + if kind == "pi": + return k == "p" and (test[1] is None or n._xtarget == test[1]) + # The tag is compared in its Clark form, "{uri}local", in place: splitting + # it made two strings and a tuple for every node a step visited. + if axis == "attribute": + if k != "a": + return False + tag = n.name + else: + if k != "e": + return False + tag = n._xtag + if kind == "uri": + return _named(tag, test[1], test[2]) + prefix, lname, anyns = test[1], test[2], test[3] + if prefix is not None and prefix != "xml" and prefix not in env.namespaces: + raise XPathEvalError("Undefined namespace prefix") + if anyns: + return lname == "*" or _local_is(tag, lname) + if prefix is None: + if lname == "*": + return True + want = env.default_ns if axis != "attribute" else None + elif prefix == "xml": + want = "http://www.w3.org/XML/1998/namespace" + else: + want = env.namespaces.get(prefix) + if want is None: + raise XPathEvalError("Undefined namespace prefix") + return _named(tag, want, lname) + + +def _exact_name(axis, test, env): + """The one Clark-form tag an element must have to pass `test` on a + non-attribute axis, resolved once per step instead of per node; None + when the test is not a single name or its prefix does not resolve (the + general path, which raises where _test raises).""" + if axis == "attribute": + return None + kind = test[0] + if kind == "uri": + uri, local = test[1], test[2] + elif kind == "name": + prefix, local, anyns = test[1], test[2], test[3] + if anyns: + return None + if prefix is None: + uri = env.default_ns + elif prefix == "xml": + uri = "http://www.w3.org/XML/1998/namespace" + else: + uri = env.namespaces.get(prefix) + if uri is None: + return None + else: + return None + if local == "*": + return None + return local if uri is None else "{" + uri + "}" + local + + +def _named(tag, uri, local): + """Whether the Clark-form `tag` is in namespace `uri` (None for none) + with local name `local` ("*" for any), as _split(tag) == (uri, local).""" + if uri is None: + if tag[:1] == "{": + return False + return local == "*" or tag == local + lu = len(uri) + if len(tag) < lu + 2 or tag[0] != "{" or tag[lu + 1] != "}" or not tag.startswith(uri, 1): + return False + if local == "*": + return True + return len(tag) == lu + 2 + len(local) and tag.endswith(local) + + +def _local_is(tag, local): + """Whether the local part of the Clark-form `tag` is `local`.""" + if tag[:1] != "{": + return tag == local + n = len(tag) - len(local) + return n >= 2 and tag[n - 1] == "}" and tag.endswith(local) and tag.index("}") == n - 1 + + +class Env: + def __init__(self, namespaces, default_ns=None): + self.namespaces = namespaces or {} + self.default_ns = default_ns + + +def _doc_order(nodes): + if len(nodes) < 2: + return nodes + roots = [] + for n in nodes: + r = _node_root(n) + found = False + for x in roots: + if x is r: + found = True + break + if not found: + roots.append(r) + order = {} + counter = [0] + for r in roots: + order[(id(r), "d")] = counter[0] + counter[0] += 1 + _number(r, order, counter) + nodes.sort(key=lambda x: order.get(_ident(x), 0)) + return nodes + + +def _number(el, order, counter): + order[(id(el), "e")] = counter[0] + counter[0] += 1 + if el._xkind != "e": + return + for k in el._xattrib: + order[(id(el), "a", k)] = counter[0] + counter[0] += 1 + order[(id(el), "t", False)] = counter[0] + counter[0] += 1 + for c in el._xkids: + _number(c, order, counter) + order[(id(c), "t", True)] = counter[0] + counter[0] += 1 + + +def _dedupe(nodes): + seen = set() + out = [] + for n in nodes: + key = _ident(n) + if key not in seen: + seen.add(key) + out.append(n) + return out + + +def evaluate(ast, node, env): + return _eval(ast, node, 1, 1, env) + + +def _eval(e, node, pos, size, env): + op = e[0] + if op == "path": + return _eval_path(e, node, pos, size, env) + if op == "num": + return e[1] + if op == "str": + return e[1] + if op == "union": + a = _eval(e[1], node, pos, size, env) + b = _eval(e[2], node, pos, size, env) + if not isinstance(a, list) or not isinstance(b, list): + raise XPathEvalError("Invalid type") + return _doc_order(_dedupe(a + b)) + if op == "or": + return to_bool(_eval(e[1], node, pos, size, env)) or to_bool(_eval(e[2], node, pos, size, env)) + if op == "and": + return to_bool(_eval(e[1], node, pos, size, env)) and to_bool(_eval(e[2], node, pos, size, env)) + if op == "cmp": + return _compare(e[1], _eval(e[2], node, pos, size, env), _eval(e[3], node, pos, size, env)) + if op == "arith": + a = to_num(_eval(e[2], node, pos, size, env)) + b = to_num(_eval(e[3], node, pos, size, env)) + o = e[1] + if o == "+": + return a + b + if o == "-": + return a - b + if o == "mul": + return a * b + if o == "div": + if b == 0: + if a == 0 or a != a: + return float("nan") + return float("inf") if (a > 0) == (_math.copysign(1.0, b) > 0) else float("-inf") + return a / b + if b == 0: + return float("nan") + return _math.fmod(a, b) + if op == "neg": + return -to_num(_eval(e[1], node, pos, size, env)) + if op == "filter": + v = _eval(e[1], node, pos, size, env) + if not isinstance(v, list): + raise XPathEvalError("Invalid type") + for p in e[2]: + v = _apply_pred(v, p, env) + return v + if op == "call": + return _call(e[1], e[2], node, pos, size, env) + raise XPathEvalError("Invalid expression") + + +def _eval_path(e, node, pos, size, env): + if e[1] == "/": + nodes = [_Doc(_node_root(node))] + elif e[2] is not None: + nodes = _eval(e[2], node, pos, size, env) + if not isinstance(nodes, list): + raise XPathEvalError("Invalid type") + else: + nodes = [node] + for axis, test, preds in e[3]: + with_text = test[0] in ("text", "node") + exact = _exact_name(axis, test, env) + out = [] + for n in nodes: + if exact is not None: + cand = [c for c in _axis(n, axis, False) if c._xkind == "e" and c._xtag == exact] + else: + cand = [c for c in _axis(n, axis, with_text) if _test(c, axis, test, env)] + for p in preds: + cand = _apply_pred(cand, p, env) + out.extend(cand) + if len(nodes) > 1: + out = _doc_order(_dedupe(out)) + elif axis in _REVERSE: + out.reverse() + nodes = out + return nodes + + +def _apply_pred(cand, pred, env): + size = len(cand) + out = [] + for i in range(size): + v = _eval(pred, cand[i], i + 1, size, env) + if isinstance(v, float) and not isinstance(v, bool): + if v == i + 1: + out.append(cand[i]) + elif to_bool(v): + out.append(cand[i]) + return out + + +def string_value(n): + k = n._xkind + if k == "a": + return n.value + if k == "t": + return n.value + if k == "d": + return string_value(n.root) + if k != "e": + return n._xtext or "" + parts = [] + _collect_text(n, parts) + return "".join(parts) + + +def _collect_text(el, parts): + if el._xtext: + parts.append(el._xtext) + for c in el._xkids: + if c._xkind == "e": + _collect_text(c, parts) + if c._xtail: + parts.append(c._xtail) + + +def to_bool(v): + if isinstance(v, list): + return len(v) > 0 + if isinstance(v, bool): + return v + if isinstance(v, float): + return v == v and v != 0 + return len(v) > 0 + + +def _str_to_num(s): + s = s.strip(" \t\r\n") + if not s or not _re.match(r"^-?(\d+(\.\d*)?|\.\d+)$", s): + return float("nan") + return float(s) + + +def to_num(v): + if isinstance(v, list): + return _str_to_num(to_str(v)) + if isinstance(v, bool): + return 1.0 if v else 0.0 + if isinstance(v, float): + return v + if isinstance(v, int): + return float(v) + return _str_to_num(v) + + +def num_to_str(f): + if f != f: + return "NaN" + if f == float("inf"): + return "Infinity" + if f == float("-inf"): + return "-Infinity" + if f == int(f): + return str(int(f)) + return repr(f) + + +def to_str(v): + if isinstance(v, list): + return string_value(v[0]) if v else "" + if isinstance(v, bool): + return "true" if v else "false" + if isinstance(v, float): + return num_to_str(v) + return v + + +def _cmp_atoms(op, a, b): + if op in ("=", "!="): + if isinstance(a, bool) or isinstance(b, bool): + r = to_bool(a) == to_bool(b) + elif isinstance(a, float) or isinstance(b, float): + r = to_num(a) == to_num(b) + else: + r = to_str(a) == to_str(b) + return r if op == "=" else not r + x = to_num(a) + y = to_num(b) + if op == "<": + return x < y + if op == "<=": + return x <= y + if op == ">": + return x > y + return x >= y + + +def _compare(op, a, b): + la = isinstance(a, list) + lb = isinstance(b, list) + if la and lb: + sb = [string_value(y) for y in b] + for x in a: + sx = string_value(x) + for y in sb: + if _cmp_atoms(op, sx, y): + return True + return False + if la or lb: + nodes, other, flip = (a, b, False) if la else (b, a, True) + if isinstance(other, bool): + return _cmp_atoms(op, other, to_bool(nodes)) if flip else _cmp_atoms(op, to_bool(nodes), other) + for x in nodes: + s = string_value(x) + if isinstance(other, float): + s = _str_to_num(s) + if (_cmp_atoms(op, other, s) if flip else _cmp_atoms(op, s, other)): + return True + return False + return _cmp_atoms(op, a, b) + + +def _local_name(n): + k = n._xkind + if k == "e": + return _split(n._xtag)[1] + if k == "a": + return _split(n.name)[1] + if k == "p": + return n._xtarget + return "" + + +def _ns_uri(n): + k = n._xkind + if k == "e": + return _split(n._xtag)[0] or "" + if k == "a": + return _split(n.name)[0] or "" + return "" + + +def _call(name, args, node, pos, size, env): + vals = [_eval(a, node, pos, size, env) for a in args] + if name == "count": + return float(len(vals[0])) + if name == "last": + return float(size) + if name == "position": + return float(pos) + if name == "string": + return to_str(vals[0]) if vals else string_value(node) + if name == "number": + return to_num(vals[0]) if vals else _str_to_num(string_value(node)) + if name == "boolean": + return to_bool(vals[0]) + if name == "not": + return not to_bool(vals[0]) + if name == "true": + return True + if name == "false": + return False + if name == "local-name" or name == "name" or name == "namespace-uri": + target = node + if vals: + if not vals[0]: + return "" + target = vals[0][0] + if name == "namespace-uri": + return _ns_uri(target) + if name == "name" and target._xkind == "e": + p = target.prefix + ln = _local_name(target) + return p + ":" + ln if p else ln + return _local_name(target) + if name == "concat": + return "".join(to_str(v) for v in vals) + if name == "contains": + return to_str(vals[1]) in to_str(vals[0]) + if name == "starts-with": + return to_str(vals[0]).startswith(to_str(vals[1])) + if name == "ends-with": + return to_str(vals[0]).endswith(to_str(vals[1])) + if name == "string-length": + return float(len(to_str(vals[0]) if vals else string_value(node))) + if name == "normalize-space": + s = to_str(vals[0]) if vals else string_value(node) + return " ".join(s.split()) + if name == "sum": + t = 0.0 + for n in vals[0]: + t += _str_to_num(string_value(n)) + return t + if name == "floor": + return float(_math.floor(to_num(vals[0]))) + if name == "ceiling": + return float(_math.ceil(to_num(vals[0]))) + if name == "round": + f = to_num(vals[0]) + if f != f or f in (float("inf"), float("-inf")): + return f + return float(_math.floor(f + 0.5)) + if name == "substring-before": + s = to_str(vals[0]) + t = to_str(vals[1]) + i = s.find(t) + return s[:i] if i >= 0 else "" + if name == "substring-after": + s = to_str(vals[0]) + t = to_str(vals[1]) + i = s.find(t) + return s[i + len(t):] if i >= 0 else "" + if name == "substring": + s = to_str(vals[0]) + start = to_num(vals[1]) + if start != start: + return "" + start = _math.floor(start + 0.5) + if len(vals) > 2: + ln = to_num(vals[2]) + if ln != ln: + return "" + end = start + _math.floor(ln + 0.5) + else: + end = float("inf") + out = [] + for i in range(len(s)): + p = i + 1 + if p >= start and p < end: + out.append(s[i]) + return "".join(out) + if name == "translate": + s = to_str(vals[0]) + src = to_str(vals[1]) + dst = to_str(vals[2]) + out = [] + for ch in s: + i = src.find(ch) + if i < 0: + out.append(ch) + elif i < len(dst): + out.append(dst[i]) + return "".join(out) + raise XPathEvalError("Unregistered function") diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/site/lxml/etree.py b/maven/python-transpiler/src/main/resources/com/codename1/python/site/lxml/etree.py new file mode 100644 index 00000000000..9a7dac3107a --- /dev/null +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/site/lxml/etree.py @@ -0,0 +1,1907 @@ +# Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. +# Licensed under the GNU General Public License version 2 with the Classpath +# exception, as the rest of the Codename One Python runtime. +"""lxml.etree: a pure-Python subset of lxml's ElementTree API. + +Written from lxml's documented API and its observed output, over the +runtime's pure-Python expat. What it covers: + +- Elements with lxml's tree model: getparent(), siblings, addnext() and + addprevious(), tails that travel with their element, nsmap and prefix, + namespace declarations that follow an element moved between trees the way + lxml's do, and comments and processing instructions as tree nodes. +- ElementBase subclasses chosen per element by ElementNamespaceClassLookup + or ElementDefaultClassLookup, for parsed and for created elements. +- XMLParser (remove_blank_text, remove_comments, remove_pis, recover, + target= parsers fed incrementally), fromstring/XML/parse/iterparse. +- tostring() byte-compatible with libxml2's serializer: namespace + declarations, empty elements, escaping, pretty_print, declarations. +- xpath() with XPath 1.0 location paths, predicates, unions and the core + functions; find/findall/iterfind/findtext. +- A small HTMLParser over html.parser, for target parsers only in spirit: + it does not repair documents the way libxml2's HTML parser does. + +Not provided: XSLT, schemas, objectify, C14N, DTD validation, variables in +XPath, and LXML_VERSION (so that code probing for the C library keeps its +pure-Python fallback). +""" +import html.parser as _htmlparser +from xml.parsers import expat as _expat + +from lxml import _xpath + +import _cn1xml + +__version__ = "5.3.0" + +XML_NS = "http://www.w3.org/XML/1998/namespace" +_NOTFOUND = object() +_NOHINT = object() + + +class Error(Exception): + pass + + +class LxmlError(Error): + def __init__(self, message="", error_log=None): + Error.__init__(self, message) + self.msg = message + self.error_log = error_log + + +class LxmlSyntaxError(LxmlError, SyntaxError): + pass + + +class ParseError(LxmlSyntaxError): + def __init__(self, message="", code=0, line=0, column=0, filename=None): + LxmlSyntaxError.__init__(self, message) + self.code = code + self.position = (line, column) + self.lineno = line + self.offset = column + self.filename = filename + + +class XMLSyntaxError(ParseError): + pass + + +class ParserError(LxmlError): + pass + + +class DocumentInvalid(LxmlError): + pass + + +XPathError = _xpath.XPathError +XPathEvalError = _xpath.XPathEvalError +XPathSyntaxError = _xpath.XPathSyntaxError + + +def _split(tag): + if tag[:1] == "{": + j = tag.find("}") + if j < 0: + raise ValueError("Invalid tag name %r" % tag) + return tag[1:j] or None, tag[j + 1:] + return None, tag + + +def _tagstr(tag): + if isinstance(tag, QName): + return tag.text + if isinstance(tag, bytes): + tag = tag.decode("utf-8") + if not isinstance(tag, str): + raise TypeError("Invalid tag name %r" % (tag,)) + if tag[:2] == "{}": + tag = tag[2:] + _, local = _split(tag) + if not local or ":" in local or " " in local: + raise ValueError("Invalid tag name %r" % tag) + return tag + + +def _valstr(v): + if isinstance(v, QName): + return v.text + if isinstance(v, bytes): + return v.decode("utf-8") + if not isinstance(v, str): + raise TypeError("Argument must be bytes or unicode, got '%s'" % type(v).__name__) + return v + + +# ---------------------------------------------------------------- namespaces + +def _resolve(el, prefix): + n = el + while n is not None: + ns = n._xns + if prefix in ns: + return ns[prefix] + n = n._xparent + if prefix == "xml": + return XML_NS + return None + + +def _prefix_for(el, uri, is_attr): + """The prefix under which `uri` is in scope at `el`, or _NOTFOUND.""" + if uri == XML_NS: + return "xml" + if not is_attr: + hint = el._xpfx + if hint is not _NOHINT and _resolve(el, hint) == uri: + return hint + seen = set() + n = el + while n is not None: + ns = n._xns + for k in ns: + if k not in seen and ns[k] == uri and (k is not None or not is_attr): + if is_attr or _resolve(el, k) == uri: + return k + for k in ns: + seen.add(k) + n = n._xparent + return _NOTFOUND + + +def _free_prefix(el): + # lxml numbers generated prefixes with one counter per document + cnt = el._xcnt + while True: + p = "ns%d" % cnt[0] + cnt[0] += 1 + if _resolve(el, p) is None: + return p + + +def _ensure_ns(el, uri, is_attr): + if uri is None or uri == XML_NS: + return + if _prefix_for(el, uri, is_attr) is _NOTFOUND: + el._xns[_free_prefix(el)] = uri + + +def _walk(el): + yield el + for c in el._xkids: + if c._xkind == "e": + for d in _walk(c): + yield d + + +def _take_out(el): + """Detach `el` from its parent, declaring on it what it used from above.""" + parent = el._xparent + if parent is None: + return + if el._xkind == "e": + declared = set() + for n in _walk(el): + for v in n._xns.values(): + declared.add(v) + add = [] + added = set() + for n in _walk(el): + uri = _split(n._xtag)[0] + if uri is not None and uri != XML_NS and uri not in declared and uri not in added: + add.append((_prefix_for(n, uri, False), uri)) + added.add(uri) + for k in n._xattrib: + uri = _split(k)[0] + if uri is not None and uri != XML_NS and uri not in declared and uri not in added: + add.append((_prefix_for(n, uri, True), uri)) + added.add(uri) + else: + add = [] + parent._xkids.remove(el) + el._xparent = None + for p, uri in add: + if p is None or p is _NOTFOUND: + p = _free_prefix(el) + el._xns[p] = uri + + +def _put_in(parent, el, index): + if not isinstance(el, _Element): + raise TypeError("Argument must be an element") + if parent._xkind != "e": + raise TypeError("Comments and processing instructions have no children") + n = parent + while n is not None: + if n is el: + raise ValueError("cannot append parent to itself") + n = n._xparent + if el._xparent is not None: + if el._xparent is parent: + old = parent._xkids.index(el) + parent._xkids.pop(old) + if index is not None and index > old: + index -= 1 + el._xparent = None + else: + _take_out(el) + if index is None: + parent._xkids.append(el) + else: + parent._xkids.insert(index, el) + el._xparent = parent + for k in list(el._xns.keys()): + v = el._xns[k] + if _prefix_for(parent, v, False) is not _NOTFOUND: + del el._xns[k] + if el._xdoc is not None: + el._xdoc = None + + +# ---------------------------------------------------------------- creation + +def _class_for(lookup, kind, tag): + if lookup is not None: + cls = lookup._lookup_class(kind, tag) + if cls is not None: + return cls + if kind == "c": + return _Comment + if kind == "p": + return _ProcessingInstruction + return _Element + + +def _blank(cls, kind, lookup): + el = cls.__new__(cls) + el._xkind = kind + el._xtag = None + el._xattrib = {} + el._xns = {} + el._xkids = [] + el._xparent = None + el._xtext = None + el._xtail = None + el._xpfx = _NOHINT + el._xlookup = lookup + el._xdoc = None + el._xtarget = None + el._xcnt = [0] + return el + + +def _call_init(el): + init = getattr(el, "_init", None) + if init is not None: + init() + + +def _new(lookup, tag, attrib, nsmap, extra, parent=None): + tag = _tagstr(tag) + cls = _class_for(lookup, "e", tag) + el = _blank(cls, "e", lookup) + el._xtag = tag + if nsmap: + for k in nsmap: + v = nsmap[k] + if k == "": + k = None + if v is not None: + el._xns[k] = _valstr(v) + if parent is not None: + el._xparent = parent + el._xcnt = parent._xcnt + parent._xkids.append(el) + _ensure_ns(el, _split(tag)[0], False) + if attrib: + for k in attrib: + el._set_attr(k, attrib[k]) + if extra: + for k in extra: + el._set_attr(k, extra[k]) + _call_init(el) + return el + + +def Element(_tag, attrib=None, nsmap=None, **_extra): + return _new(_default_lookup(), _tag, attrib, nsmap, _extra) + + +def SubElement(_parent, _tag, attrib=None, nsmap=None, **_extra): + if _parent._xkind != "e": + raise TypeError("Comments and processing instructions have no children") + return _new(_parent._xlookup, _tag, attrib, nsmap, _extra, _parent) + + +def Comment(text=None): + el = _blank(_class_for(_default_lookup(), "c", None), "c", None) + if text is not None: + text = _valstr(text) + if "--" in text or text.endswith("-"): + raise ValueError("Comment may not contain '--' or end with '-'") + el._xtext = text + _call_init(el) + return el + + +def ProcessingInstruction(target, text=None): + el = _blank(_class_for(_default_lookup(), "p", None), "p", None) + el._xtarget = _valstr(target) + el._xtext = None if text is None else _valstr(text) + _call_init(el) + return el + + +PI = ProcessingInstruction + + +def Entity(name): + raise NotImplementedError("Entity nodes are not supported") + + +def iselement(element): + return isinstance(element, _Element) + + +# ---------------------------------------------------------------- tag matching + +def _matcher(tags): + flat = [] + for t in tags: + if t is None: + continue + if isinstance(t, (list, tuple)): + flat.extend(t) + else: + flat.append(t) + if not flat: + return None + tests = [] + for t in flat: + if t is Comment: + tests.append(("c",)) + elif t is ProcessingInstruction: + tests.append(("p",)) + elif t is Element: + tests.append(("e",)) + else: + t = t.text if isinstance(t, QName) else t + if t == "*": + tests.append(("e",)) + elif t[:1] == "{": + j = t.index("}") + uri = t[1:j] + tests.append(("n", None if uri == "" else uri, t[j + 1:], uri == "*")) + else: + tests.append(("n", None, t, False)) + + def match(el): + k = el._xkind + for test in tests: + if test[0] == "c" or test[0] == "p" or test[0] == "e": + if k == test[0]: + return True + elif k == "e": + uri, local = _split(el._xtag) + if (test[2] == "*" or test[2] == local) and (test[3] or uri == test[1]): + return True + return False + return match + + +# ---------------------------------------------------------------- elements + +class _Element(object): + """An element (and, as subclasses, a comment or processing instruction).""" + + def __init__(self, *args, **kwargs): + raise TypeError("cannot create '_Element' instances directly; use Element()") + + # -- naming + @property + def tag(self): + return self._xtag + + @tag.setter + def tag(self, value): + value = _tagstr(value) + self._xtag = value + self._xpfx = _NOHINT + _ensure_ns(self, _split(value)[0], False) + + @property + def prefix(self): + uri = _split(self._xtag)[0] + if uri is None: + return None + p = _prefix_for(self, uri, False) + return None if p is _NOTFOUND else p + + @property + def nsmap(self): + out = {} + chain = [] + n = self + while n is not None: + chain.append(n) + n = n._xparent + chain.reverse() + for n in chain: + for k in n._xns: + out[k] = n._xns[k] + return out + + @property + def text(self): + return self._xtext + + @text.setter + def text(self, value): + self._xtext = None if value is None else _valstr(value) + + @property + def tail(self): + return self._xtail + + @tail.setter + def tail(self, value): + self._xtail = None if value is None else _valstr(value) + + @property + def attrib(self): + return self._xattrib + + @property + def sourceline(self): + return None + + @property + def base(self): + return None + + # -- attributes + def _set_attr(self, key, value): + key = _tagstr(key) + value = _valstr(value) + _ensure_ns(self, _split(key)[0], True) + self._xattrib[key] = value + + def get(self, key, default=None): + if isinstance(key, QName): + key = key.text + return self._xattrib.get(key, default) + + def set(self, key, value): + if self._xkind != "e": + raise TypeError("Comments and processing instructions have no attributes") + self._set_attr(key, value) + + def keys(self): + return list(self._xattrib.keys()) + + def values(self): + return list(self._xattrib.values()) + + def items(self): + return list(self._xattrib.items()) + + # -- children + def __len__(self): + return len(self._xkids) + + def __bool__(self): + return len(self._xkids) > 0 + + def __iter__(self): + return iter(list(self._xkids)) + + def __reversed__(self): + return iter(list(reversed(self._xkids))) + + def __contains__(self, el): + for c in self._xkids: + if c is el: + return True + return False + + def __getitem__(self, index): + if isinstance(index, slice): + return self._xkids[index] + return self._xkids[index] + + def __setitem__(self, index, value): + if isinstance(index, slice): + olds = self._xkids[index] + start = index.start or 0 + if start < 0: + start += len(self._xkids) + for o in olds: + _take_out(o) + for v in list(value): + _put_in(self, v, start) + start += 1 + return + old = self._xkids[index] + if old is value: + return + pos = self._xkids.index(old) + _take_out(old) + _put_in(self, value, pos) + + def __delitem__(self, index): + if isinstance(index, slice): + for o in self._xkids[index]: + _take_out(o) + else: + _take_out(self._xkids[index]) + + def __copy__(self): + return self.__deepcopy__({}) + + def __deepcopy__(self, memo): + el = _copy_tree(self, None) + if self._xparent is not None and self._xkind == "e": + inherited = self.nsmap + for k in inherited: + if k not in el._xns: + el._xns[k] = inherited[k] + return el + + def append(self, element): + _put_in(self, element, None) + + def extend(self, elements): + for e in list(elements): + _put_in(self, e, None) + + def insert(self, index, element): + n = len(self._xkids) + if index < 0: + index = max(0, n + index) + elif index > n: + index = n + _put_in(self, element, index) + + def remove(self, element): + if element._xparent is not self: + raise ValueError("Element is not a child of this node.") + _take_out(element) + + def replace(self, old_element, new_element): + if old_element._xparent is not self: + raise ValueError("Element is not a child of this node.") + pos = self._xkids.index(old_element) + _take_out(old_element) + _put_in(self, new_element, pos) + + def clear(self, keep_tail=False): + self._xattrib.clear() + self._xtext = None + if not keep_tail: + self._xtail = None + for c in list(self._xkids): + _take_out(c) + + def index(self, child, start=None, stop=None): + kids = self._xkids + lo = 0 if start is None else start + hi = len(kids) if stop is None else stop + for i in range(lo, min(hi, len(kids))): + if kids[i] is child: + return i + raise ValueError("Element is not a child of this node.") + + def getchildren(self): + return list(self._xkids) + + def getparent(self): + return self._xparent + + def getnext(self): + p = self._xparent + if p is None: + return None + i = p._xkids.index(self) + return p._xkids[i + 1] if i + 1 < len(p._xkids) else None + + def getprevious(self): + p = self._xparent + if p is None: + return None + i = p._xkids.index(self) + return p._xkids[i - 1] if i > 0 else None + + def addnext(self, element): + p = self._xparent + if p is None: + raise TypeError("Only processing instructions and comments can be siblings of the root element") + if element is self: + return + _take_out(element) if element._xparent is not None else None + _put_in(p, element, p._xkids.index(self) + 1) + + def addprevious(self, element): + p = self._xparent + if p is None: + raise TypeError("Only processing instructions and comments can be siblings of the root element") + if element is self: + return + _take_out(element) if element._xparent is not None else None + _put_in(p, element, p._xkids.index(self)) + + def makeelement(self, _tag, attrib=None, nsmap=None, **_extra): + return _new(self._xlookup, _tag, attrib, nsmap, _extra) + + def getroottree(self): + n = self + while n._xparent is not None: + n = n._xparent + return _ElementTree(n) + + # -- iteration + def iterchildren(self, tag=None, *tags, **kw): + m = _matcher((tag,) + tags) + kids = list(self._xkids) + if kw.get("reversed"): + kids.reverse() + return iter([c for c in kids if m is None or m(c)]) + + def itersiblings(self, tag=None, *tags, **kw): + m = _matcher((tag,) + tags) + p = self._xparent + if p is None: + return iter([]) + i = p._xkids.index(self) + sibs = list(reversed(p._xkids[:i])) if kw.get("preceding") else p._xkids[i + 1:] + return iter([c for c in sibs if m is None or m(c)]) + + def iterancestors(self, tag=None, *tags): + m = _matcher((tag,) + tags) + out = [] + n = self._xparent + while n is not None: + if m is None or m(n): + out.append(n) + n = n._xparent + return iter(out) + + def iter(self, tag=None, *tags): + m = _matcher((tag,) + tags) + out = [] + _collect(self, m, out) + return iter(out) + + def iterdescendants(self, tag=None, *tags): + m = _matcher((tag,) + tags) + out = [] + for c in self._xkids: + _collect(c, m, out) + return iter(out) + + def getiterator(self, tag=None, *tags): + return self.iter(tag, *tags) + + def itertext(self, tag=None, *tags, **kw): + with_tail = kw.get("with_tail", True) + m = _matcher((tag,) + tags) + out = [] + _itertext(self, m, with_tail, out, True) + return iter(out) + + # -- searching + def xpath(self, _path, namespaces=None, extensions=None, smart_strings=True, **_variables): + if namespaces and None in namespaces: + raise TypeError("empty namespace prefix is not supported in XPath") + return _xpath_result(_xpath.evaluate(_xpath.compile_expr(_path), self, _xpath.Env(namespaces)), + smart_strings) + + def find(self, path, namespaces=None): + for el in self.iterfind(path, namespaces): + return el + return None + + def findall(self, path, namespaces=None): + return list(self.iterfind(path, namespaces)) + + def iterfind(self, path, namespaces=None): + if isinstance(path, QName): + path = path.text + if path[:1] == "/": + raise SyntaxError("cannot use absolute path on element") + ns = dict(namespaces) if namespaces else {} + default = None + if None in ns: + default = ns.pop(None) + if "" in ns: + default = ns.pop("") + res = _xpath.evaluate(_xpath.compile_expr(path), self, _xpath.Env(ns, default)) + if not isinstance(res, list): + raise SyntaxError("invalid path") + return iter([r for r in res if isinstance(r, _Element)]) + + def findtext(self, path, default=None, namespaces=None): + el = self.find(path, namespaces) + if el is None: + return default + return el._xtext or "" + + def __repr__(self): + return "" % (self._xtag, id(self)) + + +class ElementBase(_Element): + """Base class for custom element classes chosen by a class lookup.""" + + def __init__(self, *children, **kw): + attrib = kw.pop("attrib", None) + nsmap = kw.pop("nsmap", None) + tag = getattr(type(self), "TAG", None) or type(self).__name__ + tag = _tagstr(tag) + self._xkind = "e" + self._xtag = tag + self._xattrib = {} + self._xns = {} + self._xkids = [] + self._xparent = None + self._xtext = None + self._xtail = None + self._xpfx = _NOHINT + self._xlookup = None + self._xdoc = None + self._xtarget = None + self._xcnt = [0] + if nsmap: + for k in nsmap: + self._xns[k] = nsmap[k] + _ensure_ns(self, _split(tag)[0], False) + if attrib: + for k in attrib: + self._set_attr(k, attrib[k]) + for k in kw: + self._set_attr(k, kw[k]) + for c in children: + if isinstance(c, dict): + for k in c: + self._set_attr(k, c[k]) + elif isinstance(c, str): + if self._xkids: + last = self._xkids[-1] + last._xtail = (last._xtail or "") + c + else: + self._xtext = (self._xtext or "") + c + else: + self.append(c) + _call_init(self) + + +class _Comment(_Element): + @property + def tag(self): + return Comment + + def __repr__(self): + return "" % (self._xtext or "") + + +class _ProcessingInstruction(_Element): + @property + def tag(self): + return ProcessingInstruction + + @property + def target(self): + return self._xtarget + + @target.setter + def target(self, value): + self._xtarget = _valstr(value) + + def __repr__(self): + return "" % (self._xtarget, self._xtext or "") + + +class CommentBase(_Comment): + pass + + +class PIBase(_ProcessingInstruction): + pass + + +def _collect(el, m, out): + if m is None or m(el): + out.append(el) + for c in el._xkids: + _collect(c, m, out) + + +def _itertext(el, m, with_tail, out, top): + if el._xkind == "e": + if (m is None or m(el)) and el._xtext: + out.append(el._xtext) + for c in el._xkids: + _itertext(c, m, with_tail, out, False) + if not top and with_tail and el._xtail and (m is None or (el._xparent is not None and m(el._xparent))): + out.append(el._xtail) + + +def _copy_tree(el, parent): + c = _blank(type(el), el._xkind, el._xlookup) + c._xtag = el._xtag + c._xattrib = dict(el._xattrib) + c._xns = dict(el._xns) + c._xtext = el._xtext + c._xtail = el._xtail + c._xpfx = el._xpfx + c._xtarget = el._xtarget + if parent is not None: + c._xparent = parent + parent._xkids.append(c) + for k in el._xkids: + _copy_tree(k, c) + _call_init(c) + return c + + +class _ElementUnicodeResult(str): + """An XPath string result that knows where it came from.""" + + def getparent(self): + return self._xowner + + +def _smart(value, owner, attrname, is_text, is_tail): + # Results are plain str: the runtime does not yet take a str subclass + # everywhere a str is accepted (int(), float(), ...), and the consumers + # here never ask a result for its parent. + return value + + +def _smart_result(value, owner, attrname, is_text, is_tail): + s = _ElementUnicodeResult(value) + s._xowner = owner + s.attrname = attrname + s.is_attribute = attrname is not None + s.is_text = is_text + s.is_tail = is_tail + return s + + +def _xpath_result(res, smart): + if not isinstance(res, list): + return res + out = [] + for n in res: + k = n._xkind + if k == "a": + out.append(_smart(n.value, n.owner, n.name, False, False) if smart else n.value) + elif k == "t": + owner = n.holder._xparent if n.is_tail else n.holder + out.append(_smart(n.value, owner, None, True, n.is_tail) if smart else n.value) + elif k == "d": + out.append(_ElementTree(n.root)) + else: + out.append(n) + return out + + +class XPath(object): + def __init__(self, path, namespaces=None, extensions=None, regexp=True, smart_strings=True): + self.path = path + self._ast = _xpath.compile_expr(path) + self._ns = namespaces + self._smart = smart_strings + + def __call__(self, _etree_or_element, **_variables): + node = _etree_or_element + if isinstance(node, _ElementTree): + node = _xpath._Doc(node.getroot()) + return _xpath_result(_xpath.evaluate(self._ast, node, _xpath.Env(self._ns)), self._smart) + + +class QName(object): + def __init__(self, text_or_uri_or_element, tag=None): + v = text_or_uri_or_element + if isinstance(v, _Element): + v = v._xtag + elif isinstance(v, QName): + v = v.text + elif isinstance(v, bytes): + v = v.decode("utf-8") + if tag is not None: + if isinstance(tag, bytes): + tag = tag.decode("utf-8") + v = "{%s}%s" % (v, tag) if v else tag + self.text = v + self.namespace, self.localname = _split(v) + + def __str__(self): + return self.text + + def __repr__(self): + return "QName(%r)" % self.text + + def __hash__(self): + return hash(self.text) + + def __eq__(self, other): + if isinstance(other, QName): + return self.text == other.text + return self.text == other + + def __ne__(self, other): + return not self.__eq__(other) + + +# ---------------------------------------------------------------- class lookup + +class ElementClassLookup(object): + def _lookup_class(self, kind, tag): + return None + + +class ElementDefaultClassLookup(ElementClassLookup): + def __init__(self, element=None, comment=None, pi=None, entity=None): + self.element_class = element + self.comment_class = comment + self.pi_class = pi + + def _lookup_class(self, kind, tag): + if kind == "c": + return self.comment_class + if kind == "p": + return self.pi_class + return self.element_class + + +class FallbackElementClassLookup(ElementClassLookup): + def __init__(self, fallback=None): + self.fallback = fallback + + def set_fallback(self, lookup): + self.fallback = lookup + _LOOKUP_GEN[0] += 1 + + def _fall(self, kind, tag): + if self.fallback is not None: + return self.fallback._lookup_class(kind, tag) + return None + + +# Bumped by everything that can change the class a lookup answers for a +# tag: lxml makes a lookup's own classes and fallback read-only, so that is +# set_fallback and the namespace registries. The tag -> class caches the +# fast parse keeps per lookup (_class_cache) are good while it holds. +_LOOKUP_GEN = [0] +_CLASS_CACHES = {} + + +def _class_cache(lookup): + entry = _CLASS_CACHES.get(id(lookup)) + if entry is None or entry[0] is not lookup or entry[1] != _LOOKUP_GEN[0]: + entry = (lookup, _LOOKUP_GEN[0], {}) + _CLASS_CACHES[id(lookup)] = entry + return entry[2] + + +class _NamespaceRegistry(dict): + def __init__(self, uri): + dict.__init__(self) + self._uri = uri + + def __setitem__(self, key, value): + dict.__setitem__(self, key, value) + _LOOKUP_GEN[0] += 1 + + def __delitem__(self, key): + dict.__delitem__(self, key) + _LOOKUP_GEN[0] += 1 + + def update(self, *args, **kwargs): + dict.update(self, *args, **kwargs) + _LOOKUP_GEN[0] += 1 + + def clear(self): + dict.clear(self) + _LOOKUP_GEN[0] += 1 + + def pop(self, *args): + _LOOKUP_GEN[0] += 1 + return dict.pop(self, *args) + + def popitem(self): + _LOOKUP_GEN[0] += 1 + return dict.popitem(self) + + def setdefault(self, key, default=None): + _LOOKUP_GEN[0] += 1 + return dict.setdefault(self, key, default) + + def __call__(self, obj): + self[getattr(obj, "__name__", None)] = obj + return obj + + +class ElementNamespaceClassLookup(FallbackElementClassLookup): + def __init__(self, fallback=None): + FallbackElementClassLookup.__init__(self, fallback) + self._namespaces = {} + + def get_namespace(self, ns_uri): + if isinstance(ns_uri, bytes): + ns_uri = ns_uri.decode("utf-8") + reg = self._namespaces.get(ns_uri) + if reg is None: + reg = _NamespaceRegistry(ns_uri) + self._namespaces[ns_uri] = reg + return reg + + def _lookup_class(self, kind, tag): + if kind == "e": + uri, local = _split(tag) + reg = self._namespaces.get(uri) + if reg is not None: + cls = reg.get(local) + if cls is None: + cls = reg.get(None) + if cls is not None: + return cls + return self._fall(kind, tag) + + +class CustomElementClassLookup(FallbackElementClassLookup): + def lookup(self, type, doc, namespace, name): + return None + + def _lookup_class(self, kind, tag): + t = {"e": "element", "c": "comment", "p": "PI"}[kind] + uri, local = (None, None) if tag is None else _split(tag) + cls = self.lookup(t, None, uri, local) + if cls is not None: + return cls + return self._fall(kind, tag) + + +_GLOBAL_LOOKUP = [None] + + +def set_element_class_lookup(lookup=None): + _GLOBAL_LOOKUP[0] = lookup + + +def _default_lookup(): + return _GLOBAL_LOOKUP[0] + + +# ---------------------------------------------------------------- parsing + +class _TreeSink(object): + """Builds elements from parse events.""" + + def __init__(self, lookup, events=None): + self.lookup = lookup + self.stack = [] + self.root = None + self.pre = [] + self.post = [] + self.events = events + self.cnt = [0] + + def start(self, tag, attrib, nsmap, hint): + cls = _class_for(self.lookup, "e", tag) + el = _blank(cls, "e", self.lookup) + el._xtag = tag + el._xpfx = hint + el._xcnt = self.cnt + for k in nsmap: + el._xns[k] = nsmap[k] + el._xattrib = attrib + if self.stack: + parent = self.stack[-1] + el._xparent = parent + parent._xkids.append(el) + elif self.root is None: + self.root = el + self.stack.append(el) + _call_init(el) + if self.events is not None: + self.events.append(("start", el)) + + def end(self, tag): + el = self.stack.pop() + if self.events is not None: + self.events.append(("end", el)) + return el + + def data(self, text): + top = self.stack[-1] + if top._xkids: + last = top._xkids[-1] + last._xtail = (last._xtail or "") + text + else: + top._xtext = (top._xtext or "") + text + + def _misc(self, el): + if self.stack: + el._xparent = self.stack[-1] + self.stack[-1]._xkids.append(el) + elif self.root is None: + self.pre.append(el) + else: + self.post.append(el) + _call_init(el) + if self.events is not None: + self.events.append(("comment" if el._xkind == "c" else "pi", el)) + + def comment(self, text): + el = _blank(_class_for(self.lookup, "c", None), "c", self.lookup) + el._xtext = text + self._misc(el) + + def pi(self, target, data): + el = _blank(_class_for(self.lookup, "p", None), "p", self.lookup) + el._xtarget = target + el._xtext = data or None + self._misc(el) + + def doctype(self, name, pubid, system): + self.doctype_info = (name, pubid, system) + + def close(self): + if self.root is None: + raise XMLSyntaxError("Document is empty") + if self.pre or self.post: + self.root._xdoc = (self.pre, self.post) + return self.root + + +class _TargetSink(object): + """Hands parse events to a user's parser target.""" + + def __init__(self, target): + self.target = target + self._start = getattr(target, "start", None) + self._end = getattr(target, "end", None) + self._data = getattr(target, "data", None) + self._comment = getattr(target, "comment", None) + self._pi = getattr(target, "pi", None) + self._doctype = getattr(target, "doctype", None) + self._close = getattr(target, "close", None) + + def start(self, tag, attrib, nsmap, hint): + if self._start is not None: + self._start(tag, attrib, nsmap) + + def end(self, tag): + if self._end is not None: + self._end(tag) + + def data(self, text): + if self._data is not None: + self._data(text) + + def comment(self, text): + if self._comment is not None: + self._comment(text) + + def pi(self, target, data): + if self._pi is not None: + self._pi(target, data) + + def doctype(self, name, pubid, system): + if self._doctype is not None: + self._doctype(name, pubid, system) + + def close(self): + if self._close is not None: + return self._close() + return None + + +def _qname(raw): + parts = raw.split(" ") + if len(parts) == 1: + return raw, _NOHINT + if len(parts) == 2: + return "{%s}%s" % (parts[0], parts[1]), None + return "{%s}%s" % (parts[0], parts[1]), parts[2] + + +class _XMLDriver(object): + """Runs the pure-Python expat over a document and feeds a sink.""" + + def __init__(self, opts, sink): + self.opts = opts + self.sink = sink + self.text = [] + self.depth = 0 + self.state = [] + self.pending = [] + self.open_tags = [] + + def flush(self, next_is_end): + if not self.text: + return + text = "".join(self.text) + self.text = [] + if self.depth == 0 or not text: + return + st = self.state[-1] + if self.opts.remove_blank_text and text.strip(" \t\r\n") == "": + if not st[0]: + if not next_is_end: + return + elif not st[1]: + return + if not st[0]: + st[1] = True + self.sink.data(text) + + def on_ns(self, prefix, uri): + if uri: + self.pending.append((prefix or None, uri)) + + def on_start(self, name, attrs): + self.flush(False) + if self.state: + self.state[-1][0] = True + tag, hint = _qname(name) + attrib = {} + for i in range(0, len(attrs), 2): + attrib[_qname(attrs[i])[0]] = attrs[i + 1] + nsmap = {} + for p, u in self.pending: + nsmap[p] = u + self.pending = [] + self.sink.start(tag, attrib, nsmap, hint) + self.open_tags.append(tag) + self.depth += 1 + self.state.append([False, False]) + + def on_end(self, name): + self.flush(True) + self.depth -= 1 + self.state.pop() + self.sink.end(self.open_tags.pop()) + + def on_data(self, data): + self.text.append(data) + + def on_comment(self, data): + self.flush(False) + if self.opts.remove_comments: + return + if self.state: + self.state[-1][0] = True + self.sink.comment(data) + + def on_pi(self, target, data): + self.flush(False) + if self.opts.remove_pis: + return + if self.state: + self.state[-1][0] = True + self.sink.pi(target, data) + + def on_doctype(self, name, sysid, pubid, has_internal): + self.sink.doctype(name, pubid, sysid) + + def _fast(self, data): + return _fast_parse(self, data) + + def run(self, data): + root = self._fast(data) + if root is not None: + return root + enc = self.opts.encoding if isinstance(data, bytes) else None + p = _expat.ParserCreate(enc, " ") + p.namespace_prefixes = True + p.ordered_attributes = True + p.StartNamespaceDeclHandler = self.on_ns + p.StartElementHandler = self.on_start + p.EndElementHandler = self.on_end + p.CharacterDataHandler = self.on_data + p.CommentHandler = self.on_comment + p.ProcessingInstructionHandler = self.on_pi + p.StartDoctypeDeclHandler = self.on_doctype + try: + p.Parse(data, True) + except _expat.ExpatError as e: + if not self.opts.recover: + raise XMLSyntaxError(str(e), getattr(e, "code", 0), getattr(e, "lineno", 0), + getattr(e, "offset", 0)) + self.flush(True) + while self.open_tags: + self.depth -= 1 + self.state.pop() + self.sink.end(self.open_tags.pop()) + return self.sink.close() + + +_PURE_LOOKUPS = (ElementClassLookup, ElementDefaultClassLookup, ElementNamespaceClassLookup) +_NOT_UTF8_STARTS = (b"\xff\xfe", b"\xfe\xff", b"<\x00", b"\x00<") + + +def _pure_lookup(lookup): + """Whether the class a lookup answers depends only on the tag.""" + while lookup is not None: + if type(lookup) not in _PURE_LOOKUPS: + return False + lookup = getattr(lookup, "fallback", None) + return True + + +def _fast_parse(driver, data): + # The tree a plain document parses to, built in one Java pass, as lxml + # builds it in C: per element the Python path ran the expat wrapper, + # on_start, _qname, _TreeSink.start, _class_for and _blank. It answers + # None for anything it does not reproduce exactly -- a comment, a PI, a + # DOCTYPE, CDATA, any error -- and the expat path below runs as before. + sink = driver.sink + opts = driver.opts + if type(sink) is not _TreeSink or sink.events is not None or opts.recover \ + or not _pure_lookup(sink.lookup): + return None + if isinstance(data, str): + src = data + elif isinstance(data, (bytes, bytearray)) and not data.startswith(_NOT_UTF8_STARTS) \ + and opts.encoding in (None, "utf-8", "UTF-8", "utf8"): + try: + src = bytes(data).decode("utf-8") + except UnicodeDecodeError: + return None + else: + return None + lookup = sink.lookup + + def class_for(tag): + return _class_for(lookup, "e", tag) + + return _cn1xml.lxml_build(src, not isinstance(data, str), class_for, lookup, _NOHINT, sink.cnt, + opts.remove_blank_text, _class_cache(lookup)) + + +class _BaseParser(object): + _html = False + + def __init__(self, encoding=None, remove_blank_text=False, remove_comments=False, remove_pis=False, + strip_cdata=True, recover=False, target=None, **kw): + self.encoding = encoding + self.remove_blank_text = remove_blank_text + self.remove_comments = remove_comments + self.remove_pis = remove_pis + self.strip_cdata = strip_cdata + self.recover = recover + self.target = target + self.resolve_entities = kw.get("resolve_entities", True) + self._lookup = None + self._feed = [] + self.error_log = [] + self.version = "libxml2 2.12.0" + + def set_element_class_lookup(self, lookup=None): + self._lookup = lookup + + def makeelement(self, _tag, attrib=None, nsmap=None, **_extra): + return _new(self._lookup if self._lookup is not None else _default_lookup(), _tag, attrib, nsmap, + _extra) + + def copy(self): + p = self.__class__.__new__(self.__class__) + p.__dict__.update(self.__dict__) + p._feed = [] + return p + + def _sink(self, events=None): + if self.target is not None: + return _TargetSink(self.target) + return _TreeSink(self._lookup if self._lookup is not None else _default_lookup(), events) + + def _parse(self, data, events=None): + sink = self._sink(events) + if self._html: + return _HTMLDriver(self, sink).run(data) + return _XMLDriver(self, sink).run(data) + + def feed(self, data): + self._feed.append(data) + + def close(self): + chunks = self._feed + self._feed = [] + if not chunks: + data = "" + elif isinstance(chunks[0], bytes): + data = b"".join(c if isinstance(c, bytes) else c.encode("utf-8") for c in chunks) + else: + data = "".join(c if isinstance(c, str) else c.decode(self.encoding or "utf-8") for c in chunks) + return self._parse(data) + + +class XMLParser(_BaseParser): + pass + + +class ETCompatXMLParser(XMLParser): + pass + + +class XMLPullParser(XMLParser): + pass + + +_HTML_VOID = ("area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "param", "source", + "track", "wbr", "basefont", "frame", "isindex", "keygen") + + +class _HTMLDriver(_htmlparser.HTMLParser): + """A plain HTML tokenizer feeding a sink; it does not repair markup as libxml2 does.""" + + def __init__(self, opts, sink): + _htmlparser.HTMLParser.__init__(self, convert_charrefs=True) + self.opts = opts + self.sink = sink + self.open_tags = [] + + def handle_starttag(self, tag, attrs): + if self.open_tags == [] and getattr(self.sink, "root", None) is not None: + return + attrib = {} + for k, v in attrs: + attrib[k] = "" if v is None else v + self.sink.start(tag, attrib, {}, _NOHINT) + if tag in _HTML_VOID: + self.sink.end(tag) + else: + self.open_tags.append(tag) + + def handle_startendtag(self, tag, attrs): + self.handle_starttag(tag, attrs) + if tag not in _HTML_VOID and self.open_tags and self.open_tags[-1] == tag: + self.open_tags.pop() + self.sink.end(tag) + + def handle_endtag(self, tag): + if tag not in self.open_tags: + return + while self.open_tags: + t = self.open_tags.pop() + self.sink.end(t) + if t == tag: + break + + def handle_data(self, data): + if self.open_tags: + self.sink.data(data) + + def handle_comment(self, data): + if not self.opts.remove_comments: + self.sink.comment(data) + + def handle_decl(self, decl): + parts = decl.split() + if parts and parts[0].upper() == "DOCTYPE": + self.sink.doctype(parts[1] if len(parts) > 1 else "html", None, None) + + def run(self, data): + if isinstance(data, bytes): + data = data.decode(self.opts.encoding or "utf-8", "replace") + self.feed(data) + _htmlparser.HTMLParser.close(self) + while self.open_tags: + self.sink.end(self.open_tags.pop()) + return self.sink.close() + + +class HTMLParser(_BaseParser): + _html = True + + def __init__(self, encoding=None, remove_blank_text=False, remove_comments=False, remove_pis=False, + strip_cdata=True, recover=True, target=None, **kw): + _BaseParser.__init__(self, encoding, remove_blank_text, remove_comments, remove_pis, strip_cdata, + recover, target, **kw) + + +class HTMLPullParser(HTMLParser): + pass + + +_DEFAULT_PARSER = [None] + + +def set_default_parser(parser=None): + _DEFAULT_PARSER[0] = parser + + +def get_default_parser(): + p = _DEFAULT_PARSER[0] + if p is None: + p = XMLParser() + _DEFAULT_PARSER[0] = p + return p + + +def fromstring(text, parser=None, base_url=None): + if parser is None: + parser = get_default_parser() + if isinstance(text, str) and text.lstrip().startswith("", 1)[0] \ + and not parser._html: + raise ValueError("Unicode strings with encoding declaration are not supported. " + "Please use bytes input or XML fragments without declaration.") + return parser._parse(text) + + +XML = fromstring + + +def HTML(text, parser=None, base_url=None): + return fromstring(text, parser if parser is not None else HTMLParser()) + + +def _read_source(source): + if hasattr(source, "read"): + return source.read() + if hasattr(source, "__fspath__"): + source = source.__fspath__() + with open(source, "rb") as f: + return f.read() + + +def parse(source, parser=None, base_url=None): + if parser is None: + parser = get_default_parser() + root = parser._parse(_read_source(source)) + if parser.target is not None: + return root + return _ElementTree(root) + + +def iterparse(source, events=("end",), tag=None, html=False, recover=None, encoding=None, + remove_blank_text=False, remove_comments=False, remove_pis=False, strip_cdata=True, **kw): + parser = (HTMLParser if html else XMLParser)(encoding=encoding, remove_blank_text=remove_blank_text, + remove_comments=remove_comments, remove_pis=remove_pis, + recover=bool(recover)) + record = [] + parser._parse(_read_source(source), record) + m = _matcher((tag,)) + out = [] + for ev, el in record: + if ev in events and (m is None or m(el)): + out.append((ev, el)) + return iter(out) + + +# ---------------------------------------------------------------- trees + +class _ElementTree(object): + def __init__(self, root=None): + self._root = root + + def getroot(self): + return self._root + + def _setroot(self, root): + self._root = root + + @property + def docinfo(self): + return _DocInfo(self) + + def xpath(self, _path, namespaces=None, extensions=None, smart_strings=True, **_variables): + node = _xpath._Doc(self._root) + return _xpath_result(_xpath.evaluate(_xpath.compile_expr(_path), node, _xpath.Env(namespaces)), + smart_strings) + + def _fix(self, path): + if path[:1] == "/": + path = "." + path + return path + + def find(self, path, namespaces=None): + return self._root.find(self._fix(path), namespaces) + + def findall(self, path, namespaces=None): + return self._root.findall(self._fix(path), namespaces) + + def iterfind(self, path, namespaces=None): + return self._root.iterfind(self._fix(path), namespaces) + + def findtext(self, path, default=None, namespaces=None): + return self._root.findtext(self._fix(path), default, namespaces) + + def iter(self, tag=None, *tags): + return self._root.iter(tag, *tags) + + def getiterator(self, tag=None, *tags): + return self._root.iter(tag, *tags) + + def getpath(self, element): + parts = [] + n = element + while n is not None: + p = n._xparent + name = n.prefix + ":" + _split(n._xtag)[1] if n.prefix else _split(n._xtag)[1] + if p is not None: + same = [c for c in p._xkids if c._xkind == "e" and c._xtag == n._xtag] + if len(same) > 1: + name += "[%d]" % (same.index(n) + 1) + parts.append(name) + n = p + parts.reverse() + return "/" + "/".join(parts) + + def write(self, file, encoding=None, method="xml", pretty_print=False, xml_declaration=None, + with_tail=True, standalone=None, doctype=None, compression=0, **kw): + data = tostring(self, encoding=encoding, method=method, pretty_print=pretty_print, + xml_declaration=xml_declaration, with_tail=with_tail, standalone=standalone) + if isinstance(data, str): + data = data.encode("utf-8") + if hasattr(file, "write"): + file.write(data) + else: + if hasattr(file, "__fspath__"): + file = file.__fspath__() + with open(file, "wb") as f: + f.write(data) + + +class _DocInfo(object): + def __init__(self, tree): + self._tree = tree + self.xml_version = "1.0" + self.encoding = "UTF-8" + self.standalone = None + self.doctype = "" + self.URL = None + + @property + def root_name(self): + r = self._tree.getroot() + return None if r is None else _split(r._xtag)[1] + + +def ElementTree(element=None, file=None, parser=None): + if file is not None: + return parse(file, parser) + return _ElementTree(element) + + +# ---------------------------------------------------------------- serializing + +def _esc_text(s): + if "&" in s: + s = s.replace("&", "&") + if "<" in s: + s = s.replace("<", "<") + if ">" in s: + s = s.replace(">", ">") + if "\r" in s: + s = s.replace("\r", " ") + return s + + +def _esc_attr(s): + s = _esc_text(s) + if '"' in s: + s = s.replace('"', """) + if "\n" in s: + s = s.replace("\n", " ") + if "\t" in s: + s = s.replace("\t", " ") + return s + + +def _name(el, tag, is_attr, extra_decls): + uri, local = _split(tag) + if uri is None: + return local + p = _prefix_for(el, uri, is_attr) + if p is _NOTFOUND: + for q, u in extra_decls: + if u == uri and (q is not None or not is_attr): + p = q + break + if p is _NOTFOUND: + p = "ns%d" % len(extra_decls) if is_attr else None + extra_decls.append((p, uri)) + return local if p is None else p + ":" + local + + +def _write(el, out, decls, pretty, level): + k = el._xkind + if k == "c": + out.append("") + return + if k == "p": + out.append("") + return + extra = [] + qn = _name(el, el._xtag, False, extra) + attrs = [] + for key in el._xattrib: + attrs.append(" " + _name(el, key, True, extra) + '="' + _esc_attr(el._xattrib[key]) + '"') + out.append("<" + qn) + for p, u in list(el._xns.items()) + list(decls) + extra: + out.append((' xmlns="' if p is None else " xmlns:" + p + '="') + _esc_attr(u) + '"') + out.extend(attrs) + kids = el._xkids + if not kids and el._xtext is None: + out.append("/>") + return + out.append(">") + if el._xtext: + out.append(_esc_text(el._xtext)) + fmt = pretty and kids and el._xtext is None + if fmt: + for c in kids: + if c._xtail is not None: + fmt = False + break + for c in kids: + if fmt: + out.append("\n" + " " * (level + 1)) + _write(c, out, (), fmt, level + 1) + if c._xtail: + out.append(_esc_text(c._xtail)) + if fmt: + out.append("\n" + " " * level) + out.append("") + + +def _inherited_decls(el): + """In-scope declarations from above `el` that it does not redeclare, used ones first.""" + if el._xparent is None or el._xkind != "e": + return [] + chain = [] + n = el._xparent + while n is not None: + chain.append(n) + n = n._xparent + chain.reverse() + order = [] + final = {} + for n in chain: + for k in n._xns: + if k in el._xns: + continue + if k not in final: + order.append(k) + final[k] = n._xns[k] + found = [(k, final[k]) for k in order] + used = [] + uri = _split(el._xtag)[0] + if uri is not None: + used.append(uri) + for key in el._xattrib: + u = _split(key)[0] + if u is not None and u not in used: + used.append(u) + first = [] + rest = [] + for p, u in found: + if u in used: + first.append((p, u)) + else: + rest.append((p, u)) + first.sort(key=lambda d: used.index(d[1])) + return first + rest + + +def tostring(element_or_tree, encoding=None, method="xml", xml_declaration=None, pretty_print=False, + with_tail=True, standalone=None, doctype=None, exclusive=False, inclusive_ns_prefixes=None, + with_comments=True, strip_text=False): + is_tree = isinstance(element_or_tree, _ElementTree) + el = element_or_tree.getroot() if is_tree else element_or_tree + if el is None: + raise ValueError("Cannot serialize an empty tree") + if not isinstance(el, _Element): + raise TypeError("Type '%s' cannot be serialized." % type(element_or_tree).__name__) + to_unicode = encoding is str or (isinstance(encoding, str) and encoding.lower() == "unicode") + if method == "text": + s = "".join(el.itertext()) + if with_tail and not is_tree and el._xtail: + s += el._xtail + return s if to_unicode else s.encode(encoding or "ascii", "xmlcharrefreplace") + out = [] + if is_tree and el._xdoc is not None: + for c in el._xdoc[0]: + _write(c, out, (), pretty_print, 0) + if pretty_print: + out.append("\n") + _write(el, out, () if is_tree else _inherited_decls(el), pretty_print, 0) + if is_tree and el._xdoc is not None: + for c in el._xdoc[1]: + if pretty_print: + out.append("\n") + _write(c, out, (), pretty_print, 0) + if pretty_print: + out.append("\n") + if with_tail and not is_tree and el._xtail: + out.append(_esc_text(el._xtail)) + body = "".join(out) + if to_unicode: + if xml_declaration: + raise ValueError("Serialisation to unicode must not request an XML declaration") + return body + enc = encoding or "ASCII" + write_decl = xml_declaration + if standalone is not None: + write_decl = True + if write_decl is None: + write_decl = enc.upper().replace("_", "-") not in ("ASCII", "UTF-8", "UTF8", "US-ASCII") + if write_decl: + decl = "\n" + body + lower = enc.lower().replace("_", "-") + if lower in ("ascii", "us-ascii"): + return body.encode("ascii", "xmlcharrefreplace") + return body.encode(enc, "xmlcharrefreplace") + + +def tounicode(element_or_tree, method="xml", pretty_print=False, with_tail=True, doctype=None): + return tostring(element_or_tree, encoding="unicode", method=method, pretty_print=pretty_print, + with_tail=with_tail) + + +def tostringlist(element_or_tree, *args, **kwargs): + return [tostring(element_or_tree, *args, **kwargs)] + + +def dump(elem, pretty_print=True, with_tail=True): + import sys + sys.stdout.write(tostring(elem, encoding="unicode", pretty_print=pretty_print, with_tail=with_tail)) + + +def cleanup_namespaces(tree_or_element, top_nsmap=None, keep_ns_prefixes=None): + root = tree_or_element.getroot() if isinstance(tree_or_element, _ElementTree) else tree_or_element + used = set() + for n in _walk(root): + u = _split(n._xtag)[0] + if u is not None: + used.add(u) + for k in n._xattrib: + u = _split(k)[0] + if u is not None: + used.add(u) + keep = set(keep_ns_prefixes or ()) + for n in _walk(root): + for k in list(n._xns.keys()): + if n._xns[k] not in used and k not in keep: + del n._xns[k] + + +def strip_tags(tree_or_element, *tag_names): + root = tree_or_element.getroot() if isinstance(tree_or_element, _ElementTree) else tree_or_element + m = _matcher(tag_names) + if m is None: + return + for el in list(root.iterdescendants()): + p = el._xparent + if p is None or not m(el): + continue + i = p._xkids.index(el) + text = el._xtext if el._xkind == "e" else None + kids = list(el._xkids) + tail = el._xtail + p._xkids.pop(i) + el._xparent = None + prev = p._xkids[i - 1] if i > 0 else None + + def add(s, prev=prev): + if not s: + return + if prev is None: + p._xtext = (p._xtext or "") + s + else: + prev._xtail = (prev._xtail or "") + s + add(text) + for c in kids: + c._xparent = p + p._xkids.insert(i, c) + i += 1 + prev = c + add(tail, prev) diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/site/magika/__init__.py b/maven/python-transpiler/src/main/resources/com/codename1/python/site/magika/__init__.py new file mode 100644 index 00000000000..e63b3b84f88 --- /dev/null +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/site/magika/__init__.py @@ -0,0 +1,412 @@ +# Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. +# Licensed under the GNU General Public License version 2 with the Classpath +# exception, as the rest of the Codename One Python runtime. +"""magika: content-type detection with Magika's result shape. + +Google's Magika runs a neural model through onnxruntime, which no +Codename One target ships. This answers the same questions from file +signatures and a few text heuristics instead: container formats are told +apart by what is inside them (the parts of a ZIP, the streams of an OLE +file), and text by its first bytes. A content it cannot place is reported +as "unknown", which callers already treat as "no opinion".""" + +import io as _io +import json as _json +import os as _os + +__version__ = "0.6.0" + +__all__ = ["Magika", "MagikaResult", "MagikaPrediction", "ContentTypeInfo", "ContentTypeLabel", + "PredictionMode", "Status"] + + +class Status: + OK = "ok" + FILE_NOT_FOUND_ERROR = "file_not_found_error" + PERMISSION_ERROR = "permission_error" + UNKNOWN = "unknown" + + +class PredictionMode: + BEST_GUESS = "best_guess" + MEDIUM_CONFIDENCE = "medium_confidence" + HIGH_CONFIDENCE = "high_confidence" + + +class ContentTypeInfo: + def __init__(self, label, mime_type, group, description, extensions, is_text): + self.label = label + self.mime_type = mime_type + self.group = group + self.description = description + self.extensions = extensions + self.is_text = is_text + + @property + def ct_label(self): + return self.label + + def __repr__(self): + return "ContentTypeInfo(label=%r, mime_type=%r, group=%r, description=%r, extensions=%r, is_text=%r)" % ( + self.label, self.mime_type, self.group, self.description, self.extensions, self.is_text) + + +_TYPES = {} + + +def _t(label, mime, group, description, exts, is_text): + _TYPES[label] = ContentTypeInfo(label, mime, group, description, exts, is_text) + + +_t("unknown", "application/octet-stream", "unknown", "Unknown binary data", [], False) +_t("empty", "inode/x-empty", "inode", "Empty file", [], False) +_t("txt", "text/plain", "text", "Generic text document", ["txt"], True) +_t("pdf", "application/pdf", "document", "PDF document", ["pdf"], False) +_t("zip", "application/zip", "archive", "ZIP archive data", ["zip"], False) +_t("docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "document", + "Microsoft Word 2007+ document", ["docx", "docm"], False) +_t("xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "document", + "Microsoft Excel 2007+ spreadsheet", ["xlsx", "xlsm"], False) +_t("pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation", "document", + "Microsoft PowerPoint 2007+ document", ["pptx", "pptm"], False) +_t("epub", "application/epub+zip", "document", "EPUB document", ["epub"], False) +_t("jar", "application/java-archive", "archive", "Java archive data (JAR)", ["jar"], False) +_t("apk", "application/vnd.android.package-archive", "executable", "Android package", ["apk"], False) +_t("odt", "application/vnd.oasis.opendocument.text", "document", "OpenDocument Text", ["odt"], False) +_t("ods", "application/vnd.oasis.opendocument.spreadsheet", "document", "OpenDocument Spreadsheet", ["ods"], False) +_t("odp", "application/vnd.oasis.opendocument.presentation", "document", "OpenDocument Presentation", ["odp"], + False) +_t("doc", "application/msword", "document", "Microsoft Word CDF document", ["doc"], False) +_t("xls", "application/vnd.ms-excel", "document", "Microsoft Excel CDF document", ["xls"], False) +_t("ppt", "application/vnd.ms-powerpoint", "document", "Microsoft PowerPoint CDF document", ["ppt"], False) +_t("outlook", "application/vnd.ms-outlook", "application", "MS Outlook Message", [], False) +_t("png", "image/png", "image", "PNG image data", ["png"], False) +_t("jpeg", "image/jpeg", "image", "JPEG image data", ["jpg", "jpeg"], False) +_t("gif", "image/gif", "image", "GIF image data", ["gif"], False) +_t("webp", "image/webp", "image", "WebP media file", ["webp"], False) +_t("bmp", "image/bmp", "image", "BMP image data", ["bmp"], False) +_t("tiff", "image/tiff", "image", "TIFF image data", ["tiff", "tif"], False) +_t("heif", "image/heif", "image", "HEIF image data", ["heif", "heic"], False) +_t("svg", "image/svg+xml", "image", "SVG Scalable Vector Graphics image data", ["svg"], True) +_t("wav", "audio/x-wav", "audio", "Waveform Audio file (WAV)", ["wav"], False) +_t("mp3", "audio/mpeg", "audio", "MP3 media file", ["mp3"], False) +_t("mp4", "video/mp4", "video", "MP4 media file", ["mp4"], False) +_t("ogg", "audio/ogg", "audio", "Ogg data", ["ogg"], False) +_t("flac", "audio/flac", "audio", "FLAC audio bitstream data", ["flac"], False) +_t("gzip", "application/gzip", "archive", "gzip compressed data", ["gz", "gzip"], False) +_t("html", "text/html", "code", "HTML document", ["html", "htm", "xhtml", "xht"], True) +_t("xml", "text/xml", "code", "XML document", ["xml"], True) +_t("rss", "application/rss+xml", "text", "RSS feed", ["rss"], True) +_t("json", "application/json", "code", "JSON document", ["json"], True) +_t("jsonl", "application/json", "code", "JSONL document", ["jsonl"], True) +_t("ipynb", "application/json", "code", "Jupyter notebook", ["ipynb"], True) +_t("csv", "text/csv", "code", "CSV document", ["csv"], True) +_t("markdown", "text/markdown", "text", "Markdown document", ["md", "markdown"], True) +_t("python", "text/x-python", "code", "Python source", ["py", "pyi"], True) +_t("rtf", "text/rtf", "text", "Rich Text Format document", ["rtf"], True) + + +class ContentTypeLabel: + UNKNOWN = "unknown" + EMPTY = "empty" + TXT = "txt" + PDF = "pdf" + ZIP = "zip" + DOCX = "docx" + XLSX = "xlsx" + PPTX = "pptx" + EPUB = "epub" + HTML = "html" + XML = "xml" + JSON = "json" + CSV = "csv" + MARKDOWN = "markdown" + PNG = "png" + JPEG = "jpeg" + + +class MagikaPrediction: + def __init__(self, dl, output, score, overwrite_reason="none"): + self.dl = dl + self.output = output + self.score = score + self.overwrite_reason = overwrite_reason + + +class MagikaResult: + def __init__(self, path, status, prediction=None): + self.path = path + self.status = status + self._prediction = prediction + + @property + def ok(self): + return self.status == Status.OK + + @property + def prediction(self): + if self._prediction is None: + raise ValueError("prediction is not available: status is %s" % self.status) + return self._prediction + + @property + def dl(self): + return self.prediction.dl + + @property + def output(self): + return self.prediction.output + + @property + def score(self): + return self.prediction.score + + +_SAMPLE = 64 * 1024 + + +def _zip_names(data, stream): + import zipfile + try: + src = stream if stream is not None else _io.BytesIO(data) + with zipfile.ZipFile(src) as z: + names = z.namelist() + mimetype = None + if "mimetype" in names: + mimetype = z.read("mimetype").strip() + return names, mimetype + except Exception: + return None, None + + +def _classify_zip(data, stream): + names, mimetype = _zip_names(data, stream) + if names is None: + return "zip" + if mimetype == b"application/epub+zip": + return "epub" + if mimetype in (b"application/vnd.oasis.opendocument.text", ): + return "odt" + if mimetype in (b"application/vnd.oasis.opendocument.spreadsheet", ): + return "ods" + if mimetype in (b"application/vnd.oasis.opendocument.presentation", ): + return "odp" + has = set(n.split("/", 1)[0] for n in names) + if "[Content_Types].xml" in names: + if "word" in has: + return "docx" + if "xl" in has: + return "xlsx" + if "ppt" in has: + return "pptx" + if "AndroidManifest.xml" in names and "classes.dex" in names: + return "apk" + if "META-INF/MANIFEST.MF" in names: + return "jar" + return "zip" + + +def _utf16(name): + return name.encode("utf-16-le") + + +def _classify_ole(data): + if _utf16("__substg1.0_") in data or _utf16("__properties_version1.0") in data: + return "outlook" + if _utf16("WordDocument") in data: + return "doc" + if _utf16("Workbook") in data or _utf16("Book") in data: + return "xls" + if _utf16("PowerPoint Document") in data: + return "ppt" + return "unknown" + + +def _decode_text(data): + if data.startswith(b"\xef\xbb\xbf"): + data = data[3:] + try: + return data.decode("utf-8") + except UnicodeDecodeError as e: + if e.start >= len(data) - 3 and len(data) >= _SAMPLE: + return data[:e.start].decode("utf-8") + try: + import charset_normalizer + best = charset_normalizer.from_bytes(data).best() + if best is not None: + return str(best) + except Exception: + pass + # Text in an encoding this runtime cannot decode (Shift-JIS, cp1252) is + # still text: no NUL and few control bytes. Latin-1 maps every byte, so + # the ASCII structure a classifier looks at (commas, tags) survives. + if b"\0" not in data: + ctl = sum(1 for b in data if b < 32 and b not in (9, 10, 12, 13)) + if ctl * 100 <= len(data): + return data.decode("latin-1") + return None + + +def _classify_text(text, truncated): + s = text.lstrip() + low = s[:2048].lower() + if not s: + return "txt" + if s[0] in "{[": + try: + obj = _json.loads(text) + if isinstance(obj, dict) and "cells" in obj and "nbformat" in obj: + return "ipynb" + return "json" + except ValueError: + if truncated: + return "json" + lines = [ln for ln in text.splitlines() if ln.strip()] + ok = 0 + for ln in lines[:20]: + try: + _json.loads(ln) + ok += 1 + except ValueError: + pass + if lines and ok == min(len(lines), 20): + return "jsonl" + if low.startswith("{\\rtf"): + return "rtf" + if "" in low or "= 2: + for sep in (",", "\t", ";"): + counts = [ln.count(sep) for ln in lines[:20] if ln.strip()] + if len(counts) >= 2 and counts[0] > 0 and all(c == counts[0] for c in counts): + return "csv" + md = 0 + for ln in lines[:200]: + t = ln.lstrip() + if t.startswith("#") and t[1:2] in (" ", "#"): + md += 2 + elif t.startswith("```") or t.startswith("- ") or t.startswith("* ") or t.startswith("> "): + md += 1 + elif "](" in t and "[" in t: + md += 1 + if md >= 3: + return "markdown" + py = 0 + for ln in lines[:200]: + t = ln.strip() + if t.startswith("def ") or t.startswith("import ") or t.startswith("from ") or t.startswith("class "): + py += 1 + if py >= 3: + return "python" + return "txt" + + +def _classify(data, stream=None, truncated=False): + if not data: + return "empty" + if data.startswith(b"%PDF-"): + return "pdf" + if data.startswith(b"PK\x03\x04") or data.startswith(b"PK\x05\x06"): + return _classify_zip(data, stream) + if data.startswith(b"\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1"): + return _classify_ole(data) + if data.startswith(b"\x89PNG\r\n\x1a\n"): + return "png" + if data.startswith(b"\xff\xd8\xff"): + return "jpeg" + if data.startswith(b"GIF87a") or data.startswith(b"GIF89a"): + return "gif" + if data[:4] == b"RIFF" and data[8:12] == b"WEBP": + return "webp" + if data[:4] == b"RIFF" and data[8:12] == b"WAVE": + return "wav" + if data.startswith(b"BM") and len(data) > 14: + return "bmp" + if data.startswith(b"II*\x00") or data.startswith(b"MM\x00*"): + return "tiff" + if data[4:8] == b"ftyp": + brand = data[8:12] + if brand in (b"heic", b"heix", b"mif1", b"msf1", b"heim", b"heis"): + return "heif" + return "mp4" + if data.startswith(b"ID3") or (len(data) > 1 and data[0] == 0xFF and (data[1] & 0xE0) == 0xE0): + return "mp3" + if data.startswith(b"OggS"): + return "ogg" + if data.startswith(b"fLaC"): + return "flac" + if data.startswith(b"\x1f\x8b"): + return "gzip" + sample = data[:_SAMPLE] + if b"\x00" in sample and not (sample.startswith(b"\xff\xfe") or sample.startswith(b"\xfe\xff")): + return "unknown" + text = _decode_text(sample) + if text is None: + return "unknown" + return _classify_text(text, truncated or len(data) > _SAMPLE) + + +def _result(path, label): + info = _TYPES[label] + return MagikaResult(path, Status.OK, MagikaPrediction(info, info, 1.0 if label != "unknown" else 0.0)) + + +class Magika: + def __init__(self, model_dir=None, prediction_mode=PredictionMode.HIGH_CONFIDENCE, no_dereference=False, + verbose=False, debug=False, use_colors=False): + self._prediction_mode = prediction_mode + + def get_model_name(self): + return "signatures" + + def get_module_version(self): + return __version__ + + def identify_bytes(self, content): + if not isinstance(content, (bytes, bytearray)): + raise TypeError("Input content should be of type 'bytes'.") + return _result("-", _classify(bytes(content))) + + def identify_stream(self, stream): + pos = stream.tell() + try: + data = stream.read() + finally: + stream.seek(pos) + if data[:4] == b"PK\x03\x04" or data[:4] == b"PK\x05\x06": + return _result("-", _classify_zip(data, _io.BytesIO(data))) + return _result("-", _classify(data)) + + def identify_path(self, path): + path = _os.fspath(path) + if not _os.path.exists(path): + return MagikaResult(path, Status.FILE_NOT_FOUND_ERROR) + if _os.path.isdir(path): + info = ContentTypeInfo("directory", "inode/directory", "inode", "A directory", [], False) + return MagikaResult(path, Status.OK, MagikaPrediction(info, info, 1.0)) + with open(path, "rb") as f: + data = f.read() + r = _result(path, _classify(data)) + return r + + def identify_paths(self, paths): + return [self.identify_path(p) for p in paths] + + def identify_bytes_list(self, contents): + return [self.identify_bytes(c) for c in contents] + + def get_output_content_types(self): + return list(_TYPES.keys()) + + def get_model_content_types(self): + return list(_TYPES.keys()) diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/site/numpy/__init__.py b/maven/python-transpiler/src/main/resources/com/codename1/python/site/numpy/__init__.py index 7cd5642d2af..673e422e7b1 100644 --- a/maven/python-transpiler/src/main/resources/com/codename1/python/site/numpy/__init__.py +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/site/numpy/__init__.py @@ -134,8 +134,9 @@ def item(self): return self._v -float32 = float16 = float_ = double = float64 +float32 = float16 = float_ = double = half = single = longdouble = float64 int32 = int16 = int8 = uint8 = uint16 = uint32 = uint64 = intp = int_ = int64 +short = ushort = intc = uintc = uint = longlong = ulonglong = uintp = int64 _TYPE_NAMES = {float: "float64", int: "int64", _b.bool: "bool", float64: "float64", int64: "int64", bool_: "bool"} number = object floating = float64 @@ -753,6 +754,48 @@ def array(obj, dtype=None, copy=True, ndmin=0): return r +_BUFFER_CODES = { + "f8": "d", "f4": "f", "f2": "e", "i8": "q", "i4": "i", "i2": "h", "i1": "b", + "u8": "Q", "u4": "I", "u2": "H", "u1": "B", "b1": "?", + "float64": "d", "float32": "f", "float16": "e", "double": "d", "single": "f", "half": "e", + "int64": "q", "int32": "i", "int16": "h", "int8": "b", + "uint64": "Q", "uint32": "I", "uint16": "H", "uint8": "B", "bool": "?", + "float": "d", "int": "q", +} + + +def frombuffer(buffer, dtype=float, count=-1, offset=0, *, like=None): + """A 1-d array of the values packed in a bytes-like object. Any byte + order and width is read ("i2", "uint8", ...); the values are + then held as float64, int64 or bool like every array here, so the + result is a copy rather than a view of the buffer.""" + import struct as _struct + if isinstance(dtype, type): + spec = {float: "float64", int: "int64", _b.bool: "bool"}.get(dtype, getattr(dtype, "__name__", "")) + else: + spec = str(dtype) + order = "<" + if spec[:1] in "<>=|": + order = {"<": "<", ">": ">", "=": "=", "|": "<"}[spec[0]] + spec = spec[1:] + code = _BUFFER_CODES.get(spec) + if code is None and spec[:1] in "fiub" and spec[1:].isdigit(): + code = _BUFFER_CODES.get(spec[0] + spec[1:]) + if code is None: + raise TypeError("data type %r not understood" % (dtype,)) + data = bytes(memoryview(buffer))[offset:] + size = _struct.calcsize(code) + if count < 0: + if len(data) % size: + raise ValueError("buffer size must be a multiple of element size") + count = len(data) // size + elif count * size > len(data): + raise ValueError("buffer is smaller than requested size") + values = list(_struct.unpack(order + code * count, data[:count * size])) + kind = "float64" if code in "dfe" else "bool" if code == "?" else "int64" + return array(values, dtype=kind) + + def asarray(obj, dtype=None): if isinstance(obj, ndarray) and dtype is None: return obj diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/site/pandas/__init__.py b/maven/python-transpiler/src/main/resources/com/codename1/python/site/pandas/__init__.py index 6a518eaeb88..bd877f01b64 100644 --- a/maven/python-transpiler/src/main/resources/com/codename1/python/site/pandas/__init__.py +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/site/pandas/__init__.py @@ -1256,7 +1256,7 @@ def _reduce(self, name, numeric_only=False): if numeric_only and not _numeric(c._dt): continue names.append(c.name) - vals.append(getattr(c, name)()) + vals.append(_series_reduce(c, name)) return Series._make(vals, Index(names)) def sum(self, numeric_only=False): return self._reduce("sum", numeric_only) @@ -1395,6 +1395,45 @@ def to_dict(self, orient="dict"): for i in range(len(self._index))} return {c.name: dict(zip(self._index._v, c._v)) for c in self._cols} + def to_html(self, buf=None, index=True, header=True, na_rep="NaN", escape=True, border=1): + """pandas' HTML table: the classic `dataframe` table, cells formatted + as the text repr formats them.""" + def esc(t): + if not escape: + return t + return t.replace("&", "&").replace("<", "<").replace(">", ">") + out = ['' % border] + if header: + out.append(" ") + out.append(' ') + if index: + out.append(" ") + for n in self._names(): + out.append(" ") + out.append(" ") + out.append(" ") + out.append(" ") + cells = [[x.strip() for x in _fmt_values(c._v, c._dt)] for c in self._cols] + for r in range(len(self._index)): + out.append(" ") + if index: + out.append(" ") + for col in cells: + v = col[r] + out.append(" ") + out.append(" ") + out.append(" ") + out.append("
" + esc(_label(n)) + "
" + esc(_label(self._index._v[r])) + "" + esc(na_rep if v == "NaN" else v) + "
") + text = "\n".join(out) + if buf is None: + return text + if isinstance(buf, str): + with open(buf, "w") as f: + f.write(text) + return None + buf.write(text) + return None + def to_csv(self, path_or_buf=None, index=True, sep=",", header=True): out = [] @@ -1583,6 +1622,32 @@ def __setitem__(self, key, value): # ---- groupby -------------------------------------------------------------- +def _series_reduce(s, name): + """A Series reduction by its name, each called by its own name: a + computed getattr cannot be typed, and the reductions are this set.""" + if name == "sum": + return s.sum() + if name == "count": + return s.count() + if name == "mean": + return s.mean() + if name == "median": + return s.median() + if name == "std": + return s.std() + if name == "var": + return s.var() + if name == "min": + return s.min() + if name == "max": + return s.max() + if name == "nunique": + return s.nunique() + if name == "prod": + return s.prod() + raise AttributeError("'Series' has no reduction " + repr(name)) + + def _agg_one(series, how): if callable(how): return how(series) @@ -1592,7 +1657,7 @@ def _agg_one(series, how): return series._v[0] if how == "last": return series._v[-1] - return getattr(series, how)() + return _series_reduce(series, how) class GroupBy: @@ -1858,6 +1923,71 @@ def read_csv(filepath_or_buffer, sep=",", header=0, names=None, index_col=None, df = df.set_index(key) return df +def _excel_cell(cell): + # pandas' openpyxl reader: an empty cell is "", a whole float is an int + v = cell.value + if v is None: + return "" + if cell.data_type == "e": + return nan + if cell.data_type == "n" and isinstance(v, float): + return int(v) if v == int(v) else v + if isinstance(v, bool) or not isinstance(v, float): + return v + return v + + +def _excel_sheet(ws, header): + rows = [] + for row in ws.rows: + vals = [_excel_cell(c) for c in row] + while vals and vals[-1] == "": + vals.pop() + rows.append(vals) + while rows and not rows[-1]: + rows.pop() + if not rows: + return DataFrame() + width = max(len(r) for r in rows) + rows = [r + [""] * (width - len(r)) for r in rows] + if header is None: + names = list(range(width)) + body = rows + else: + names = [] + seen = {} + for j, v in enumerate(rows[header]): + n = "Unnamed: %d" % j if v == "" else v + if n in seen: + seen[n] += 1 + n = "%s.%d" % (n, seen[n]) + else: + seen[n] = 0 + names.append(n) + body = rows[header + 1:] + data = {} + for j, n in enumerate(names): + data[n] = [None if r[j] == "" else r[j] for r in body] + return DataFrame(data) + + +def read_excel(io, sheet_name=0, header=0, engine=None, **kwargs): + """Sheets of an .xlsx workbook through openpyxl, the engine pandas uses + for them; `sheet_name=None` reads every sheet into a dict.""" + if engine not in (None, "openpyxl"): + raise ValueError("Unknown engine: %s" % engine) + import openpyxl + wb = openpyxl.load_workbook(io, read_only=True, data_only=True, keep_links=False) + try: + names = wb.sheetnames + if sheet_name is None: + return {n: _excel_sheet(wb[n], header) for n in names} + if isinstance(sheet_name, list): + return {n: _excel_sheet(wb[names[n] if isinstance(n, int) else n], header) for n in sheet_name} + return _excel_sheet(wb[names[sheet_name] if isinstance(sheet_name, int) else sheet_name], header) + finally: + wb.close() + def read_json(path_or_buf, orient=None): if isinstance(path_or_buf, str): @@ -1911,3 +2041,36 @@ def conv(v): def unique(values): return Series(values).unique() + + +import datetime as _dt + + +class Timestamp(_dt.datetime): + """A point in time: a datetime that also parses an ISO 8601 string. + + Nanoseconds, time zone names and the frequency arguments are not + supported; a Timestamp is the type code keys on (sqlite-utils maps it to + a column type) and the value a parsed date column holds. + """ + + def __new__(cls, value=None, *args, **kwargs): + if isinstance(value, str): + d = _dt.datetime.fromisoformat(value) + elif isinstance(value, _dt.datetime): + d = value + elif isinstance(value, _dt.date): + d = _dt.datetime(value.year, value.month, value.day) + elif isinstance(value, (int, float)) and not args: + d = _dt.datetime.fromtimestamp(value, _dt.timezone.utc).replace(tzinfo=None) + else: + return _dt.datetime.__new__(cls, value, *args, **kwargs) + return _dt.datetime.__new__(cls, d.year, d.month, d.day, d.hour, d.minute, d.second, + d.microsecond, d.tzinfo) + + @classmethod + def now(cls, tz=None): + return cls(_dt.datetime.now(tz)) + + def isoformat(self, sep="T", timespec="auto"): + return _dt.datetime.isoformat(self, sep, timespec) diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/site/pydantic/__init__.py b/maven/python-transpiler/src/main/resources/com/codename1/python/site/pydantic/__init__.py index b72213e80d2..dc3311794b8 100644 --- a/maven/python-transpiler/src/main/resources/com/codename1/python/site/pydantic/__init__.py +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/site/pydantic/__init__.py @@ -434,13 +434,12 @@ def _is_classvar(ann): def _resolve_forward(tp, c): text = tp if isinstance(tp, str) else tp.__forward_arg__ ns = {} + hints = {} cls = c.cls if cls is not None: - m = _sys.modules.get(cls.__module__) - if m is not None: - ns.update(getattr(m, "__dict__", {})) + hints = _typing._module_hints(cls.__module__) ns[cls.__name__] = cls - return _typing._resolve_hint(text, ns) + return _typing._resolve_hint(text, ns, hints) # -------------------------------------------------------------------------- @@ -471,6 +470,17 @@ def _parse_duration(s): def _v(tp, val, loc, c): + # The common case first: a value already of the exact scalar type its + # field declares, which every branch below would hand back unchanged + # after a dozen hasattr and typing lookups. A str only when no config + # transforms strings. + tv = type(val) + if tv is tp: + if tv is int or tv is float or tv is bool or tv is bytes: + return val + if tv is str and not (c.cfg.get("str_strip_whitespace") or c.cfg.get("str_to_lower") + or c.cfg.get("str_to_upper")): + return val if tp is None: tp = _NoneType if isinstance(tp, str) or hasattr(tp, "__forward_arg__"): @@ -500,13 +510,48 @@ def _v(tp, val, loc, c): return _E(c, loc, "literal_error", val, {"expected": exp}, "Input should be " + exp) if org is not None: return _vgeneric(org, _typing.get_args(tp), val, loc, c) - if isinstance(tp, ModelMetaclass): + if _is_model(tp): return _vmodel(tp, val, loc, c) + if _typing.is_typeddict(tp): + return _vtypeddict(tp, val, loc, c) if isinstance(tp, type): return _vplain(tp, val, loc, c) return val +def _vtypeddict(tp, val, loc, c): + """A TypedDict: a dict holding every required key, each declared key's + value validated against its annotation. Undeclared keys are dropped, + as pydantic's default extra='ignore' drops them.""" + if not isinstance(val, dict): + return _E(c, loc, "dict_type", val, None, "Input should be an object" if c.json else None) + saved = c.cls + c.cls = tp + try: + out = {} + bad = False + required = getattr(tp, "__required_keys__", frozenset()) + for key, hint in tp.__annotations__.items(): + if isinstance(hint, str) or hasattr(hint, "__forward_arg__"): + hint = _resolve_forward(hint, c) + form = _typing.get_origin(hint) + if form is _typing.Required or form is _typing.NotRequired: + hint = _typing.get_args(hint)[0] + if key not in val: + if key in required: + _E(c, loc + (key,), "missing", val, None, "Field required") + bad = True + continue + r = _v(hint, val[key], loc + (key,), c) + if r is _BAD: + bad = True + else: + out[key] = r + return _BAD if bad else out + finally: + c.cls = saved + + def _join_or(items): if len(items) == 1: return items[0] @@ -1019,9 +1064,19 @@ def _merge_annotation(fi, tp): fi.metadata = [m for m in metas if not isinstance(m, FieldInfo)] for m in metas: if isinstance(m, FieldInfo): - for k in ("alias", "validation_alias", "serialization_alias", "title", "description", "examples"): - if getattr(fi, k) is None and getattr(m, k) is not None: - setattr(fi, k, getattr(m, k)) + # One literal attribute per line, never a computed name. + if fi.alias is None: + fi.alias = m.alias + if fi.validation_alias is None: + fi.validation_alias = m.validation_alias + if fi.serialization_alias is None: + fi.serialization_alias = m.serialization_alias + if fi.title is None: + fi.title = m.title + if fi.description is None: + fi.description = m.description + if fi.examples is None: + fi.examples = m.examples if fi.default is PydanticUndefined and fi.default_factory is None: fi.default = m.default fi.default_factory = m.default_factory @@ -1033,8 +1088,10 @@ def _complete(cls): if cls.__dict__.get("__pydantic_complete__"): return True try: - hints = _typing.get_type_hints(cls, include_extras=True) - except Exception: + # Literal per-class table (PydanticLowering), evaluated now so a + # forward reference resolves once its class exists. + hints = cls.__cn1_pd_ann__() + except NameError: return False for name, fi in cls.model_fields.items(): if name in hints: @@ -1045,6 +1102,31 @@ def _complete(cls): return True +def _core_schema(tp): + org = _typing.get_origin(tp) + if org is Annotated: + return _core_schema(_typing.get_args(tp)[0]) + if org is Literal: + return {"type": "literal", "expected": list(_typing.get_args(tp))} + if org is Union: + args = [a for a in _typing.get_args(tp) if a is not type(None)] + if len(args) < len(_typing.get_args(tp)): + inner = _core_schema(args[0]) if len(args) == 1 else \ + {"type": "union", "choices": [_core_schema(a) for a in args]} + return {"type": "nullable", "schema": inner} + return {"type": "union", "choices": [_core_schema(a) for a in args]} + if org in (list, tuple, set, frozenset): + return {"type": org.__name__ if org is not frozenset else "frozenset"} + if org is dict: + return {"type": "dict"} + names = {str: "str", int: "int", float: "float", bool: "bool", bytes: "bytes"} + if tp in names: + return {"type": names[tp]} + if _is_model(tp): + return {"type": "model", "cls": tp} + return {"type": "any"} + + def _ensure(cls): if not cls.__dict__.get("__pydantic_complete__"): if not _complete(cls): @@ -1065,90 +1147,118 @@ class PydanticUndefinedAnnotation(NameError): pass -class ModelMetaclass(type): - def __new__(mcs, name, bases, ns, **kwargs): - if not any(isinstance(b, ModelMetaclass) for b in bases): - return type.__new__(mcs, name, bases, ns) - annotations = ns.get("__annotations__", {}) - config = {} - for b in reversed(bases): - config.update(getattr(b, "model_config", {})) - config.update(ns.get("model_config", {})) - config.update(kwargs) - ns["model_config"] = config - own = {} - privates = {} - for fname in list(annotations): - ann = annotations[fname] - if _is_classvar(ann): - continue - if _is_private(fname): - d = ns.get(fname, PydanticUndefined) - if isinstance(d, _PrivateAttr): - ns.pop(fname) - privates[fname] = d - elif d is not PydanticUndefined: - privates[fname] = _PrivateAttr(d, None) - continue - d = ns.pop(fname, PydanticUndefined) - if isinstance(d, FieldInfo): - fi = d - else: - fi = FieldInfo(d) - fi.annotation = ann - own[fname] = fi - for k in list(ns): - v = ns[k] - if isinstance(v, _PrivateAttr): - ns.pop(k) - privates[k] = v - decls = {"field": [], "model": [], "fser": [], "mser": []} - for b in bases: - bd = getattr(b, "__pydantic_decorators__", None) - if bd: - for kind in decls: - decls[kind].extend(bd[kind]) - computed = {} - for b in bases: - computed.update(getattr(b, "__pydantic_computed__", {})) - for k in list(ns): - v = ns[k] - if isinstance(v, _Decl): - f = getattr(v.func, "__func__", v.func) - decls[v.kind].append(_Decl(v.kind, f, v.fields, v.mode, v.extra)) - if v.kind == "model" and v.mode == "after": - ns[k] = f - elif v.kind in ("field", "model"): - ns[k] = classmethod(f) - else: - ns[k] = f - elif isinstance(v, property): - for (g, alias, rep) in _COMPUTED: - if g is v.fget: - computed[k] = (alias, rep) - cls = type.__new__(mcs, name, bases, ns) - fields = {} - for b in reversed(bases): - for k, fi in getattr(b, "model_fields", {}).items(): - fields[k] = fi - for k, fi in own.items(): +def _is_model(tp): + return isinstance(tp, type) and issubclass(tp, BaseModel) + + +def _setup_model(cls): + """Builds a model class's tables once the class exists. It was the + metaclass's __new__, which rewrote the class namespace; a class whose + metaclass does that has no layout. Here the namespace is only read and + every table goes under a name no class body binds. Field names, their + annotations and the private attribute names come from the hooks + PydanticLowering writes into the class (__cn1_pd_ann__, + __cn1_pd_privates__); a merged model_config is written by the lowering + into the class body too.""" + ns = cls.__dict__ + bases = cls.__bases__ + annotations = cls.__cn1_pd_ann__() + own = {} + privates = {} + for fname in annotations: + ann = annotations[fname] + d = ns.get(fname, PydanticUndefined) + if isinstance(d, property): + # A frozen/validate_assignment field PydanticLowering turned + # into a property; its default moved beside it. + d = ns.get("_cn1pd_default_" + fname, PydanticUndefined) + if isinstance(d, FieldInfo): + fi = d + else: + fi = FieldInfo(d) + fi.annotation = ann + own[fname] = fi + for k in cls.__cn1_pd_privates__: + d = ns.get(k, PydanticUndefined) + if isinstance(d, _PrivateAttr): + privates[k] = d + elif d is not PydanticUndefined: + privates[k] = _PrivateAttr(d, None) + decls = {"field": [], "model": [], "fser": [], "mser": []} + for b in bases: + bd = b.__dict__.get("__pydantic_decorators__") + if bd: + for kind in decls: + decls[kind].extend(bd[kind]) + computed = {} + for b in bases: + computed.update(b.__dict__.get("__pydantic_computed__", {})) + for k in ns: + v = ns[k] + if isinstance(v, _Decl): + f = v.func.__func__ if isinstance(v.func, (classmethod, staticmethod)) else v.func + decls[v.kind].append(_Decl(v.kind, f, v.fields, v.mode, v.extra)) + elif isinstance(v, property): + for (g, alias, rep) in _COMPUTED: + if g is v.fget: + computed[k] = (alias, rep) + fields = {} + for b in reversed(bases): + for k, fi in b.__dict__.get("model_fields", {}).items(): fields[k] = fi - pv = {} - for b in bases: - pv.update(getattr(b, "__private_attributes__", {})) - pv.update(privates) - type.__setattr__(cls, "model_fields", fields) - type.__setattr__(cls, "__pydantic_decorators__", decls) - type.__setattr__(cls, "__pydantic_computed__", computed) - type.__setattr__(cls, "__private_attributes__", pv) - type.__setattr__(cls, "__pydantic_complete__", False) - _complete(cls) - if config.get("frozen") and "__hash__" not in ns: - type.__setattr__(cls, "__hash__", BaseModel._frozen_hash) - return cls - - def __init__(cls, name, bases, ns, **kwargs): - type.__init__(cls, name, bases, ns) + for k, fi in own.items(): + fields[k] = fi + pv = {} + for b in bases: + pv.update(b.__dict__.get("__private_attributes__", {})) + pv.update(privates) + type.__setattr__(cls, "model_fields", fields) + # The setters PydanticLowering writes reach a field's plan entry by its + # literal position in the build's field list: hold the two orders equal. + names = cls.__dict__.get("__cn1_pd_names__") + if names is not None and tuple(fields) != names: + raise TypeError("model class %s: field order %r differs from the build's %r" + % (cls.__name__, tuple(fields), names)) + type.__setattr__(cls, "__pydantic_decorators__", decls) + type.__setattr__(cls, "__pydantic_computed__", computed) + type.__setattr__(cls, "__private_attributes__", pv) + type.__setattr__(cls, "__pydantic_complete__", False) + _complete(cls) + return cls + + +def _make_model(name, bases, ns): + """A model class made at run time (RootModel[T], create_model). It has + no class statement to lower, so only RootModel's own literal hooks can + serve it; any other field-bearing one raises on first use.""" + if "__annotations__" in ns: + ann = dict(ns["__annotations__"]) + ns["__cn1_pd_ann__"] = classmethod(lambda c: ann) + ns.setdefault("__cn1_pd_privates__", ()) + cls = type(name, bases, ns) + return _setup_model(cls) + + +class ModelMetaclass(type): + """Kept for code that names it; model classes are plain classes.""" + + + +def _core_schema_of(cls): + # The shape pydantic-core gives a model, enough for code that walks + # it (the openai SDK reads field types and aliases from it). Nothing + # here validates through it; validation is this module's own. + _ensure(cls) + fields = {} + for name, fi in cls.model_fields.items(): + f = {"type": "model-field", "schema": _core_schema(fi.annotation)} + alias = fi.serialization_alias or fi.alias + if alias is not None: + f["serialization_alias"] = alias + fields[name] = f + return {"type": "model", "cls": cls, "schema": { + "type": "model-fields", "fields": fields, "model_name": cls.__name__, + "computed_fields": []}} class _Opts: @@ -1161,10 +1271,48 @@ def __init__(self, mode="python", by_alias=False, exclude_unset=False, exclude_d self.exclude_none = exclude_none +class _Plan: + """What validating a class needs that does not change per call: read + once per class instead of once per field of every instance. The + sqlite-backed llm app validated a model per prompt, and the config + lookups, the MRO walk of _is_root and a ValidationInfo per field (with a + copy of the values so far) were most of what that cost.""" + __slots__ = ("fields_obj", "cfg", "by_name", "root", "extra_mode", "fields", "model_decls") + + def __init__(self, cls): + cfg = cls.model_config + self.fields_obj = cls.model_fields + self.cfg = cfg + self.by_name = cfg.get("populate_by_name") or cfg.get("validate_by_name") + self.root = _is_root(cls) + self.extra_mode = cfg.get("extra") or "ignore" + fdecls = cls.__pydantic_decorators__["field"] + fields = [] + for name, fi in cls.model_fields.items(): + alias = fi.validation_alias if fi.validation_alias is not None else fi.alias + # The field validators naming this field, resolved once per + # class; None when there are none. + hooked = [d for d in fdecls if name in d.fields or "*" in d.fields] or None + fields.append((name, fi, alias, hooked)) + self.fields = fields + self.model_decls = cls.__pydantic_decorators__["model"] + + +def _plan(cls): + p = cls.__dict__.get("__pydantic_plan__") + # Kept while the class still has the same field table and config: a + # model_rebuild, or a program that replaces either, gets a new plan. + if p is None or p.fields_obj is not cls.model_fields or p.cfg is not cls.model_config: + p = _Plan(cls) + type.__setattr__(cls, "__pydantic_plan__", p) + return p + + def _fill(cls, data, loc, c): """Validates a mapping against cls's fields. Returns (values, fields_set, extras) or None, with the problems appended to c.errs.""" - cfg = cls.model_config + plan = _plan(cls) + cfg = plan.cfg saved_cfg = c.cfg saved_cls = c.cls c.cfg = cfg @@ -1173,10 +1321,9 @@ def _fill(cls, data, loc, c): values = {} fset = set() used = set() - by_name = cfg.get("populate_by_name") or cfg.get("validate_by_name") - root = _is_root(cls) - for name, fi in cls.model_fields.items(): - alias = fi.validation_alias if fi.validation_alias is not None else fi.alias + by_name = plan.by_name + root = plan.root + for name, fi, alias, hooked in plan.fields: key = _MISSING_KEY if alias is not None and alias in data: key = alias @@ -1192,18 +1339,20 @@ def _fill(cls, data, loc, c): if isinstance(d, (list, dict, set, bytearray)): d = _copy.deepcopy(d) if fi.validate_default or cfg.get("validate_default"): - d = _vfield(cls, fi, name, d, loc + (name,), c, values) + d = _vfield(cls, fi, name, d, loc + (name,), c, values, hooked) if d is _BAD: continue values[name] = d continue used.add(key) - v = _vfield(cls, fi, name, data[key], loc if root else loc + (key,), c, values) + v = _vfield(cls, fi, name, data[key], loc if root else loc + (key,), c, values, hooked) if v is not _BAD: values[name] = v fset.add(name) - extra_mode = cfg.get("extra") or "ignore" + extra_mode = plan.extra_mode extras = {} + if extra_mode == "ignore": + data = () for k in data: if k in used: continue @@ -1221,18 +1370,38 @@ def _fill(cls, data, loc, c): _MISSING_KEY = _Undefined() -def _vfield(cls, fi, name, raw, loc, c, values): +def _vfield(cls, fi, name, raw, loc, c, values, hooked): + """hooked: the field validators that name this field (_Plan), or None.""" + if not hooked: + # No validator names this field: nothing can read a ValidationInfo. + was = c.strict + if fi.strict is not None: + c.strict = fi.strict + elif c.cfg.get("strict"): + c.strict = True + full = fi._full if fi._full is not None else Any + v = _v(full, raw, loc, c) + c.strict = was + if v is _BAD: + return _BAD + if fi.constraints and v is not None: + v = _constrain(v, fi.constraints, loc, c) + if v is _BAD: + return _BAD + if c.cfg.get("use_enum_values") and isinstance(v, _enum.Enum): + v = v.value + return v info = ValidationInfo(c, name, dict(values)) - decls = cls.__pydantic_decorators__["field"] + decls = hooked v = raw for d in decls: - if d.mode == "before" and (name in d.fields or "*" in d.fields): + if d.mode == "before": v = _guard(c, loc, raw, lambda d=d, v=v: _invoke(d.func, (cls, v), info)) if v is _BAD: return _BAD plain = None for d in decls: - if d.mode == "plain" and (name in d.fields or "*" in d.fields): + if d.mode == "plain": plain = d if plain is not None: v = _guard(c, loc, raw, lambda: _invoke(plain.func, (cls, v), info)) @@ -1254,7 +1423,7 @@ def _vfield(cls, fi, name, raw, loc, c, values): if v is _BAD: return _BAD for d in decls: - if d.mode == "after" and (name in d.fields or "*" in d.fields): + if d.mode == "after": v = _guard(c, loc, raw, lambda d=d, v=v: _invoke(d.func, (cls, v), info)) if v is _BAD: return _BAD @@ -1264,15 +1433,22 @@ def _vfield(cls, fi, name, raw, loc, c, values): def _populate(obj, cls, values, fset, extras): - for k, v in values.items(): - object.__setattr__(obj, k, v) - object.__setattr__(obj, "__pydantic_fields_set__", fset) - object.__setattr__(obj, "__pydantic_extra__", extras if cls.model_config.get("extra") == "allow" else None) - for k, p in cls.__private_attributes__.items(): - if p.factory is not None: - object.__setattr__(obj, k, p.factory()) - elif p.default is not PydanticUndefined: - object.__setattr__(obj, k, _copy.deepcopy(p.default)) + # The model's own generated hooks store each field and private + # attribute under its literal name (PydanticLowering). + obj.__cn1_pd_store__(values) + obj._cn1_pd_state(fset, extras if cls.model_config.get("extra") == "allow" else None) + obj.__cn1_pd_init_private__() + + +def _private_value(cls, k): + """The initial value of private attribute k, for the generated + __cn1_pd_init_private__; _BAD when it has none.""" + p = cls.__private_attributes__[k] + if p.factory is not None: + return p.factory() + if p.default is not PydanticUndefined: + return _copy.deepcopy(p.default) + return _BAD def _is_root(cls): @@ -1302,9 +1478,8 @@ def _vmodel(cls, val, loc, c): elif (c.from_attributes or cls.model_config.get("from_attributes")) and v is not None \ and not isinstance(v, (str, int, float, bool, list, tuple, set)): data = {} - for name, fi in cls.model_fields.items(): - if hasattr(v, name): - data[name] = getattr(v, name) + # Per-class generated hook: reads each field of v by its literal name. + data = cls.__cn1_pd_from_attrs__(v) else: return _E(c, loc, "model_type", v, {"class_name": cls.__name__}, "Input should be an object" if c.json else None) @@ -1329,18 +1504,31 @@ def _finish(c, title, r): return r -class BaseModel(metaclass=ModelMetaclass): +class BaseModel: """Base class of validated models.""" model_config = {} + model_fields = {} + __pydantic_decorators__ = {"field": [], "model": [], "fser": [], "mser": []} + __pydantic_computed__ = {} + __private_attributes__ = {} + __cn1_pd_privates__ = () + + @classmethod + def __cn1_pd_ann__(cls): + return {} + + @classmethod + def __cn1_pd_setup__(cls): + _setup_model(cls) def __init__(self, **data): cls = type(self) _ensure(cls) c = _Ctx() c.cls = cls - info = ValidationInfo(c) decls = cls.__pydantic_decorators__["model"] + info = ValidationInfo(c) if decls else None v = data for d in decls: if d.mode == "before": @@ -1424,58 +1612,109 @@ def model_fields_set(self): def model_extra(self): return self.__pydantic_extra__ + # The per-class hooks PydanticLowering writes into every model class, + # each naming the class's fields literally. These are the answers for a + # class with no fields; a model class the build could not lower never + # reaches them, since the build refuses it. + def _cn1_pd_state(self, fset, extras): + self.__pydantic_fields_set__ = fset + self.__pydantic_extra__ = extras + + def _cn1_pd_private(self, k): + return _private_value(type(self), k) + + def _cn1_pd_has(self, v): + return v is not _BAD + + def _cn1_pd_copy(self, v, deep): + return _copy.deepcopy(v) if deep else v + + def _cn1_pd_hash(self): + return self._frozen_hash() + + def _cn1_pd_unlowered(self): + if type(self).model_fields: + raise TypeError("model class %s has fields but no generated hooks; " + "only a class statement the build sees is supported" % type(self).__name__) + + def __cn1_pd_load__(self): + self._cn1_pd_unlowered() + return {} + + def __cn1_pd_store__(self, values): + self._cn1_pd_unlowered() + + def __cn1_pd_init_private__(self): + pass + + def __cn1_pd_computed__(self): + if type(self).__pydantic_computed__: + raise TypeError("model class %s has computed fields but no generated hooks" % type(self).__name__) + return {} + + @classmethod + def __cn1_pd_from_attrs__(cls, v): + if cls.model_fields: + raise TypeError("model class %s has fields but no generated hooks" % cls.__name__) + return {} + def __getattr__(self, name): if name.startswith("__pydantic_"): raise AttributeError(name) - ex = self.__dict__.get("__pydantic_extra__") + ex = self.__pydantic_extra__ if ex is not None and name in ex: return ex[name] raise AttributeError("'%s' object has no attribute '%s'" % (type(self).__name__, name)) - def __setattr__(self, name, value): - cls = type(self) + def __cn1_new_attr__(self, name, value): + """Asked by the runtime before an instance gains an attribute it + never had (PyType.newAttrHook): what BaseModel.__setattr__ did for a + name that is not a field. True when the value went to the extras.""" if name.startswith("_"): - object.__setattr__(self, name, value) - return - fi = cls.model_fields.get(name) + return False + cls = type(self) + if name in cls.model_fields: + return False + if cls.model_config.get("extra") == "allow": + self.__pydantic_extra__[name] = value + return True + raise ValueError('"%s" object has no field "%s"' % (cls.__name__, name)) + + def _cn1_pd_assign(self, i, name, value): + """What storing field `name` does, for the property PydanticLowering + writes in place of a field of a frozen or validate_assignment model + (a class binding __setattr__ has no layout). Returns the value to + store. The generated setter passes the field's literal position in + the class's plan and its literal name, used only as error location + and as the model_fields_set entry: nothing is looked up by name.""" + cls = type(self) + fname, fi, alias, hooked = _plan(cls).fields[i] cfg = cls.model_config if cfg.get("frozen") or (fi is not None and fi.frozen): c = _Ctx() _E(c, (name,), "frozen_instance", value) raise ValidationError(cls.__name__, c.errs) - if fi is None: - if cfg.get("extra") == "allow": - self.__pydantic_extra__[name] = value - return - if isinstance(getattr(cls, name, None), property): - object.__setattr__(self, name, value) - return - raise ValueError('"%s" object has no field "%s"' % (cls.__name__, name)) if cfg.get("validate_assignment"): c = _Ctx() c.cls = cls c.cfg = cfg - v = _vfield(cls, fi, name, value, (name,), c, dict(self.__dict__)) + v = _vfield(cls, fi, name, value, (name,), c, self.__cn1_pd_load__(), hooked) if c.errs: raise ValidationError(cls.__name__, c.errs) value = v - object.__setattr__(self, name, value) self.__pydantic_fields_set__.add(name) - - def __delattr__(self, name): - object.__delattr__(self, name) + return value def _frozen_hash(self): - return hash(tuple([_hashable(getattr(self, k)) for k in type(self).model_fields])) + return hash(tuple([_hashable(v) for v in self.__cn1_pd_load__().values()])) def __eq__(self, other): if not isinstance(other, BaseModel): return NotImplemented if type(self) is not type(other): return False - for k in type(self).model_fields: - if getattr(self, k) != getattr(other, k): - return False + if self.__cn1_pd_load__() != other.__cn1_pd_load__(): + return False return self.__pydantic_extra__ == other.__pydantic_extra__ def __ne__(self, other): @@ -1487,20 +1726,24 @@ def __ne__(self, other): __hash__ = None def __iter__(self): - for k in type(self).model_fields: - yield k, getattr(self, k) + for k, v in self.__cn1_pd_load__().items(): + yield k, v if self.__pydantic_extra__: for k, v in self.__pydantic_extra__.items(): yield k, v def __repr_args__(self): out = [] + vals = self.__cn1_pd_load__() for k, fi in type(self).model_fields.items(): if fi.repr: - out.append((k, getattr(self, k))) - for k, (alias, rep) in type(self).__pydantic_computed__.items(): - if rep: - out.append((k, getattr(self, k))) + out.append((k, vals[k])) + comp = type(self).__pydantic_computed__ + if comp: + cv = self.__cn1_pd_computed__() + for k, (alias, rep) in comp.items(): + if rep: + out.append((k, cv[k])) if self.__pydantic_extra__: for k, v in self.__pydantic_extra__.items(): out.append((k, v)) @@ -1522,8 +1765,7 @@ def model_copy(self, *, update=None, deep=False): cls = type(self) obj = object.__new__(cls) vals = {} - for k in cls.model_fields: - v = getattr(self, k) + for k, v in self.__cn1_pd_load__().items(): vals[k] = _copy.deepcopy(v) if deep else v fset = set(self.__pydantic_fields_set__) ex = self.__pydantic_extra__ @@ -1536,14 +1778,14 @@ def model_copy(self, *, update=None, deep=False): fset.add(k) elif ex is not None: ex[k] = v - _populate(obj, cls, vals, fset, ex or {}) - object.__setattr__(obj, "__pydantic_extra__", ex) - for k in cls.__private_attributes__: - if k in self.__dict__: - v = self.__dict__[k] - object.__setattr__(obj, k, _copy.deepcopy(v) if deep else v) + obj.__cn1_pd_store__(vals) + obj._cn1_pd_state(fset, ex) + obj.__cn1_pd_copy_private__(self, deep) return obj + def __cn1_pd_copy_private__(self, src, deep): + pass + def model_dump(self, *, mode="python", include=None, exclude=None, by_alias=False, exclude_unset=False, exclude_defaults=False, exclude_none=False, round_trip=False, warnings=True, **kw): @@ -1585,6 +1827,22 @@ class RootModel(BaseModel): __pydantic_root__ = True + # The one field every root model has, written literally (a root model + # made by RootModel[...] has no class statement to lower). + def __cn1_pd_load__(self): + return {"root": self.root} + + def __cn1_pd_store__(self, values): + if "root" in values: + self.root = values["root"] + + @classmethod + def __cn1_pd_from_attrs__(cls, v): + d = {} + if hasattr(v, "root"): + d["root"] = v.root + return d + def __init__(self, root=PydanticUndefined, **data): cls = type(self) _ensure(cls) @@ -1606,7 +1864,7 @@ def __init__(self, root=PydanticUndefined, **data): @classmethod def __class_getitem__(cls, tp): name = cls.__name__ + "[" + _tname(tp) + "]" - return ModelMetaclass(name, (cls,), {"__annotations__": {"root": tp}, "__module__": cls.__module__}) + return _make_model(name, (cls,), {"__annotations__": {"root": tp}, "__module__": cls.__module__}) @classmethod def model_validate_json(cls, json_data, *, strict=None, context=None): @@ -1647,6 +1905,7 @@ def _dump_model(m, o, include, exclude): if _is_root(cls): return _dump(m.root, o, include, exclude) out = {} + vals = m.__cn1_pd_load__() fsers = cls.__pydantic_decorators__["fser"] for name, fi in cls.model_fields.items(): if fi.exclude: @@ -1654,7 +1913,7 @@ def _dump_model(m, o, include, exclude): keep, si, se = _pick(include, exclude, name) if not keep: continue - v = getattr(m, name) + v = vals[name] if o.exclude_unset and name not in m.__pydantic_fields_set__: continue if o.exclude_defaults and not fi.is_required(): @@ -1682,11 +1941,12 @@ def _dump_model(m, o, include, exclude): if a is not None: key = a out[key] = r + comp = m.__cn1_pd_computed__() if cls.__pydantic_computed__ else None for k, (alias, rep) in cls.__pydantic_computed__.items(): keep, si, se = _pick(include, exclude, k) if not keep: continue - v = _dump(getattr(m, k), o, si, se) + v = _dump(comp[k], o, si, se) out[alias if (o.by_alias and alias is not None) else k] = v ex = m.__pydantic_extra__ if ex: @@ -1981,7 +2241,7 @@ def _schema(tp, defs): s["additionalProperties"] = _schema(args[1], defs) return s return {} - if isinstance(tp, ModelMetaclass): + if _is_model(tp): return _model_schema(tp, defs) if isinstance(tp, type): if tp is bool: @@ -2173,3 +2433,40 @@ def __str__(self): class SecretBytes(SecretStr): def __repr__(self): return "SecretBytes(b'" + ("**********" if self._secret_value else "") + "')" + + +def create_model(model_name, /, *, __config__=None, __doc__=None, __base__=None, __module__="pydantic.main", + __validators__=None, __cls_kwargs__=None, **field_definitions): + """A model class built at run time from field definitions: each one a + type, a ``(type, default)`` pair (``...`` for a required field) or a + ``(type, Field(...))`` pair.""" + if __base__ is None: + bases = (BaseModel,) + elif isinstance(__base__, tuple): + bases = __base__ + else: + bases = (__base__,) + annotations = {} + ns = {"__annotations__": annotations, "__module__": __module__, "__qualname__": model_name} + if __doc__: + ns["__doc__"] = __doc__ + if __config__ is not None: + ns["model_config"] = __config__ + if __validators__: + ns.update(__validators__) + for name, definition in field_definitions.items(): + if isinstance(definition, tuple): + if len(definition) != 2: + raise PydanticUserError( + f"Field definition for {name!r} should a single element representing the type or a two-tuple, " + "the first element being the type and the second element the assigned value " + "(either a default or the `Field()` function).") + tp, default = definition + annotations[name] = tp + if default is not ...: + ns[name] = default + else: + annotations[name] = definition + if __cls_kwargs__: + raise PydanticUserError("create_model class keywords are not supported; pass __config__") + return _make_model(model_name, bases, ns) diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/site/pydantic/dataclasses.py b/maven/python-transpiler/src/main/resources/com/codename1/python/site/pydantic/dataclasses.py index 25625c8cc7c..4d9c330c449 100644 --- a/maven/python-transpiler/src/main/resources/com/codename1/python/site/pydantic/dataclasses.py +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/site/pydantic/dataclasses.py @@ -12,25 +12,29 @@ from pydantic import _Ctx, _v, _BAD, ValidationError, Field +def _cn1_validate(self, npos, fields): + """Validates and coerces each field of a constructed pydantic dataclass. + `fields` is the class's own (name, load, store) rows, each accessor + naming its field literally (written by the transpiler, DataclassInit).""" + hints = _typing.get_type_hints(type(self), include_extras=True) + ctx = _Ctx() + ctx.cls = type(self) + i = 0 + for name, load, store in fields: + v = _v(hints.get(name, Any), load(self), (i if i < npos else name,), ctx) + i += 1 + if v is not _BAD: + store(self, v) + if ctx.errs: + raise ValidationError(type(self).__name__, ctx.errs) + + def dataclass(cls=None, **kw): def wrap(c): c = _dc.dataclass(c, **kw) - orig = c.__init__ - - def __init__(self, *a, **k): - orig(self, *a, **k) - hints = _typing.get_type_hints(type(self), include_extras=True) - ctx = _Ctx() - ctx.cls = type(self) - i = 0 - for f in _dc.fields(self): - v = _v(hints.get(f.name, Any), getattr(self, f.name), (i if i < len(a) else f.name,), ctx) - i += 1 - if v is not _BAD: - object.__setattr__(self, f.name, v) - if ctx.errs: - raise ValidationError(type(self).__name__, ctx.errs) - c.__init__ = __init__ + if not c.__dict__.get("__cn1_pd_validated__"): + raise TypeError("pydantic.dataclasses.dataclass: %s was not lowered at build time; apply " + "the decorator by name in a class statement" % c.__name__) return c if cls is None: return wrap diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/site/pydantic/fields.py b/maven/python-transpiler/src/main/resources/com/codename1/python/site/pydantic/fields.py new file mode 100644 index 00000000000..bfe4ec3de59 --- /dev/null +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/site/pydantic/fields.py @@ -0,0 +1,8 @@ +# Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. +# Licensed under the GNU General Public License version 2 with the Classpath +# exception, as the rest of the Codename One Python runtime. +"""pydantic.fields: where code that inspects a model's fields finds FieldInfo.""" + +from pydantic import FieldInfo, Field, PrivateAttr, PydanticUndefined, computed_field + +__all__ = ["FieldInfo", "Field", "PrivateAttr", "PydanticUndefined", "computed_field"] diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/site/pydantic_core/__init__.py b/maven/python-transpiler/src/main/resources/com/codename1/python/site/pydantic_core/__init__.py new file mode 100644 index 00000000000..4fbb23a50fc --- /dev/null +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/site/pydantic_core/__init__.py @@ -0,0 +1,30 @@ +# Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. +# Licensed under the GNU General Public License version 2 with the Classpath +# exception, as the rest of the Codename One Python runtime. +"""pydantic_core: the names code imports from it beside pydantic. + +The real package is a Rust extension that compiles a model into a core +schema. Here pydantic validates in Python and has no core schema, so only +the sentinel and the error types exist; importing CoreSchema or +core_schema raises ImportError, which is how libraries that build their own +schemas (the openai SDK) detect a pydantic without one. +""" + +from pydantic import PydanticUndefined, ValidationError + +PydanticUndefinedType = type(PydanticUndefined) + + +class PydanticSerializationError(ValueError): + pass + + +class PydanticCustomError(ValueError): + def __init__(self, error_type, message_template, context=None): + ValueError.__init__(self, message_template.format(**(context or {}))) + self.type = error_type + self.message_template = message_template + self.context = context + + +__version__ = "2.41.5" diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/site/pypdfium2/__init__.py b/maven/python-transpiler/src/main/resources/com/codename1/python/site/pypdfium2/__init__.py new file mode 100644 index 00000000000..4c9e4f5c0a7 --- /dev/null +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/site/pypdfium2/__init__.py @@ -0,0 +1,33 @@ +# Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. +# Licensed under the GNU General Public License version 2 with the Classpath +# exception, as the rest of the Codename One Python runtime. +"""pypdfium2: present so that importing it succeeds, with no renderer. + +The real package is ctypes bindings to Google's PDFium, a native library a +translated program cannot load. Its users here (pdfplumber's `to_image`) +render a page to a bitmap; text, tables and layout come from pdfminer and +need none of it. Opening a document therefore raises PdfiumError, which +those callers already handle as "this PDF cannot be rendered". +""" + +V_PYPDFIUM2 = "5.14.0" +V_LIBPDFIUM = "0" + + +class PdfiumError(RuntimeError): + pass + + +class PdfDocument: + def __init__(self, input, password=None, autoclose=False): + raise PdfiumError("PDF page rendering is not available on this platform") + + +class PdfPage: + def __init__(self, *args, **kwargs): + raise PdfiumError("PDF page rendering is not available on this platform") + + +class PdfBitmap: + def __init__(self, *args, **kwargs): + raise PdfiumError("PDF page rendering is not available on this platform") diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/site/pytest/__init__.py b/maven/python-transpiler/src/main/resources/com/codename1/python/site/pytest/__init__.py index e0a18149554..eeb3027879b 100644 --- a/maven/python-transpiler/src/main/resources/com/codename1/python/site/pytest/__init__.py +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/site/pytest/__init__.py @@ -8,24 +8,28 @@ mark.parametrize / skip / skipif / xfail (other marks are accepted and ignored), param(..., id=, marks=), fixture (function scope, found by parameter name from the test's class, the module or the fixtures registered so far; yield fixtures run their teardown; -fixtures may use other fixtures; autouse is honoured), the built-in -monkeypatch fixture (capsys, tmp_path and the rest are absent), and run_module(module) / +fixtures may use other fixtures; autouse is honoured, and a conftest module's +autouse fixtures apply to every module once it is imported; params= runs a +test once per value), async def tests (each on a fresh asyncio loop), the +built-in monkeypatch, tmp_path, tmpdir and request (param, addfinalizer, +getfixturevalue) fixtures (capsys and the rest are absent), the httpx_mock +fixture of the bundled pytest_httpx2, and run_module(module) / main([...]) which run every test_* function and Test* class of a module object and print a summary such as "3 passed, 1 failed". -Not supported: collecting files from disk, conftest.py, plugins, fixture +Not supported: collecting files from disk (a conftest module is imported by +the test runner's code like any other), plugin entry points, async fixtures, fixture scopes above function (accepted, treated as function), assertion rewriting (a failed assert reports its message only), capture of stdout, and the long traceback report. Plain `assert` is Python's assert. """ import sys import re -import inspect import math __all__ = ["raises", "approx", "fail", "skip", "xfail", "mark", "fixture", "main", "run_module", "param", "Failed", "Skipped", "XFailed", - "ExceptionInfo", "warns", "importorskip"] + "ExceptionInfo", "warns", "importorskip", "FixtureRequest", "MonkeyPatch"] class Failed(BaseException): @@ -288,16 +292,164 @@ def __call__(self, func): class _FixtureDef: - def __init__(self, func, name, autouse): + def __init__(self, func, name, autouse, params=None, ids=None): self.func = func self.name = name self.autouse = autouse + self.params = params + self.ids = ids + # set by the _Table of the module defining it: the fixture names it + # asks for and the call passing them + self.deps = None + self.call = None + + +class FixtureRequest: + """The `request` a fixture or test asks for: `param` (a parametrized + fixture's current value), `fixturename`, `addfinalizer` and + `getfixturevalue`. The node, config and scope objects are absent.""" + + def __init__(self, param=None, fixturename=None, session=None, instance=None, cache=None): + self.param = param + self.fixturename = fixturename + self._session = session + self._instance = instance + self._cache = cache + + def addfinalizer(self, finalizer): + self._session.teardowns.append(finalizer) + + def getfixturevalue(self, argname): + return self._session.make(argname, self._instance, self._cache, []) + + +class _LocalPath: + """tmpdir's value: the py.path.local subset tests use, over a string + path. `/` and join give another, str() and os.fspath the path.""" + + def __init__(self, path): + import os + self.strpath = os.fspath(path) + + def __fspath__(self): + return self.strpath + + def __str__(self): + return self.strpath + + def __repr__(self): + return "local(%r)" % self.strpath + + def __eq__(self, other): + import os + try: + return self.strpath == os.fspath(other) + except TypeError: + return NotImplemented + + def __hash__(self): + return hash(self.strpath) + + def __truediv__(self, other): + return self.join(other) + + def join(self, *parts): + import os + return _LocalPath(os.path.join(self.strpath, *[str(p) for p in parts])) + + @property + def basename(self): + import os + return os.path.basename(self.strpath) + + @property + def dirname(self): + import os + return os.path.dirname(self.strpath) + + def dirpath(self): + return _LocalPath(self.dirname) + + def mkdir(self, *parts): + import os + target = self.join(*parts) if parts else self + os.mkdir(target.strpath) + return target + + def ensure(self, *parts, dir=False): + import os + target = self.join(*parts) if parts else self + if dir: + os.makedirs(target.strpath, exist_ok=True) + else: + os.makedirs(os.path.dirname(target.strpath), exist_ok=True) + if not os.path.exists(target.strpath): + open(target.strpath, "a").close() + return target + + def exists(self): + import os + return os.path.exists(self.strpath) + + def check(self, file=None, dir=None, exists=None): + import os + if file: + return os.path.isfile(self.strpath) + if dir: + return os.path.isdir(self.strpath) + return os.path.exists(self.strpath) + + def isdir(self): + import os + return os.path.isdir(self.strpath) + + def isfile(self): + import os + return os.path.isfile(self.strpath) + + def listdir(self): + import os + return [self.join(n) for n in sorted(os.listdir(self.strpath))] + + def read(self, mode="r"): + with open(self.strpath, mode) as f: + return f.read() + + def read_text(self, encoding="utf-8"): + with open(self.strpath, encoding=encoding) as f: + return f.read() + + def read_binary(self): + with open(self.strpath, "rb") as f: + return f.read() + + def write(self, data, mode="w", ensure=False): + if ensure: + self.dirpath().ensure(dir=True) + if isinstance(data, bytes) and "b" not in mode: + mode += "b" + with open(self.strpath, mode) as f: + f.write(data) + + def write_text(self, data, encoding="utf-8", ensure=False): + self.write(data.encode(encoding), "wb", ensure) + + def write_binary(self, data, ensure=False): + self.write(data, "wb", ensure) + + def remove(self): + import os + import shutil + if os.path.isdir(self.strpath): + shutil.rmtree(self.strpath) + else: + os.remove(self.strpath) def fixture(func=None, *, scope="function", params=None, autouse=False, ids=None, name=None): def register(f): fname = name or f.__name__ - f.__cn1_fixture__ = _FixtureDef(f, fname, autouse) + f.__cn1_fixture__ = _FixtureDef(f, fname, autouse, params, ids) _registry[fname] = f.__cn1_fixture__ return f if func is not None: @@ -305,27 +457,88 @@ def register(f): return register +_MISSING = object() +_NOTSET = object() +_ENV = object() +_CWD = object() +_SYSPATH = object() +_ATTR = object() + + class _MonkeyPatch: def __init__(self): self._undo = [] - def setattr(self, target, name, value=None, raising=True): - if value is None and isinstance(target, str): - raise TypeError("monkeypatch.setattr with a string target is not supported") - old = getattr(target, name, _MISSING) + # The attribute is named by the accessors PytestLowering writes at each + # call site, `_cn1_acc=(name, get, set, delete, owner)`: the build refuses + # a name it cannot read, so nothing stores by computed name here. + def setattr(self, target, name, value=_NOTSET, raising=True, _cn1_acc=None): + if _cn1_acc is None: + raise TypeError("monkeypatch.setattr: the call was not lowered at build time; write the " + "attribute name as a literal") + attr, get, put, drop, owner = _cn1_acc + if isinstance(target, str): + # "package.module.attr": the module must already be imported + if value is not _NOTSET: + raise TypeError("use setattr(target, name, value) or setattr(target, value) with target " + "being a dotted import string") + value = name + target = owner() + old = get(target, _MISSING) if old is _MISSING and raising: - raise AttributeError("%r has no attribute %r" % (target, name)) - self._undo.append((target, name, old)) - setattr(target, name, value) - - def delattr(self, target, name, raising=True): - old = getattr(target, name, _MISSING) + raise AttributeError("%r has no attribute %r" % (target, attr)) + self._undo.append((_ATTR, (target, _cn1_acc), old)) + put(target, value) + + def delattr(self, target, name, raising=True, _cn1_acc=None): + if _cn1_acc is None: + raise TypeError("monkeypatch.delattr: the call was not lowered at build time; write the " + "attribute name as a literal") + old = _cn1_acc[1](target, _MISSING) if old is _MISSING: if raising: - raise AttributeError(name) + raise AttributeError(_cn1_acc[0]) + return + self._undo.append((_ATTR, (target, _cn1_acc), old)) + _cn1_acc[3](target) + + def setenv(self, name, value, prepend=None): + import os + value = str(value) + if prepend and name in os.environ: + value = value + prepend + os.environ[name] + self._undo.append((_ENV, name, os.environ.get(name, _MISSING))) + os.environ[name] = value + + def delenv(self, name, raising=True): + import os + if name not in os.environ: + if raising: + raise KeyError(name) return - self._undo.append((target, name, old)) - delattr(target, name) + self._undo.append((_ENV, name, os.environ[name])) + del os.environ[name] + + def chdir(self, path): + import os + self._undo.append((_CWD, None, os.getcwd())) + os.chdir(os.fspath(path)) + + def syspath_prepend(self, path): + self._undo.append((_SYSPATH, None, list(sys.path))) + sys.path.insert(0, str(path)) + + def context(self): + import contextlib + + @contextlib.contextmanager + def ctx(): + m = _MonkeyPatch() + try: + yield m + finally: + m.undo() + return ctx() def setitem(self, dic, name, value): self._undo.append((dic, name, dic.get(name, _MISSING))) @@ -342,29 +555,71 @@ def delitem(self, dic, name, raising=True): def undo(self): while self._undo: target, name, old = self._undo.pop() - if isinstance(target, dict): + if target is _ENV: + import os + if old is _MISSING: + os.environ.pop(name, None) + else: + os.environ[name] = old + elif target is _CWD: + import os + os.chdir(old) + elif target is _SYSPATH: + sys.path[:] = old + elif isinstance(target, dict): if old is _MISSING: target.pop(name, None) else: target[name] = old - elif old is _MISSING: - delattr(target, name) - else: - setattr(target, name, old) + elif target is _ATTR: + obj, acc = name + if old is _MISSING: + acc[3](obj) + else: + acc[2](obj, old) -_MISSING = object() +MonkeyPatch = _MonkeyPatch -# -- running ---------------------------------------------------------------- +class _PatchCall: + # One lowered call site's accessors bound to its MonkeyPatch. + def __init__(self, mp, acc): + self.mp = mp + self.acc = acc + + def setattr(self, target, name, value=_NOTSET, raising=True): + return self.mp.setattr(target, name, value, raising, _cn1_acc=self.acc) -def _param_names(func, skip_self): - names = list(inspect.signature(func).parameters) - if skip_self and names: - names = names[1:] - return names + def delattr(self, target, name, raising=True): + return self.mp.delattr(target, name, raising, _cn1_acc=self.acc) + + +def _cn1_mp(r, delete, acc): + # PytestLowering routes every `r.setattr(...)`/`r.delattr(...)` statement + # with a literal name here: the accessors reach `r` only when it really + # is a MonkeyPatch, any other receiver gets its own method untouched. + if isinstance(r, _MonkeyPatch): + r = _PatchCall(r, acc) + if delete: + return r.delattr + return r.setattr + + +def _dotted(path, candidates): + """The object a dotted monkeypatch target names: `candidates` are the + (module name, literal attribute load) pairs PytestLowering wrote for + each module prefix of `path`, longest first.""" + for modname, load in candidates: + mod = sys.modules.get(modname) + if mod is not None: + return load(mod) + raise ImportError("monkeypatch target %r is not imported" % path) + +# -- running ---------------------------------------------------------------- + def _split_argnames(argnames): if isinstance(argnames, str): return [a.strip() for a in argnames.split(",") if a.strip()] @@ -465,51 +720,137 @@ def summary(self): return ", ".join(parts) if parts else "no tests ran" +class _Table: + """A module's tests and fixtures, as PytestLowering lists them at build + time in dir() order: ("f", name, function, fixture names, call) for a + module-level function, where call(resolve) passes each fixture name + literally, and ("c", name, class, members) for a Test* class, each member + (name, function, fixture names, call(instance, resolve), bound(instance)).""" + + def __init__(self, entries): + self.entries = entries + self.fixtures = {} + for e in entries: + if e[0] == "f": + d = getattr(e[2], "__cn1_fixture__", None) + if d is not None: + d.deps = e[3] + d.call = e[4] + self.fixtures[d.name] = e + + class _Session: - def __init__(self, module, quiet): + def __init__(self, module, quiet, table): self.module = module self.quiet = quiet + self.table = table self.result = _Result() self.teardowns = [] - - # fixture lookup: class attribute, module attribute, then the registry - def find_fixture(self, name, instance): - if instance is not None: - f = getattr(type(instance), name, None) - if f is not None and hasattr(f, "__cn1_fixture__"): - return f, True - f = getattr(self.module, name, None) - if f is not None and hasattr(f, "__cn1_fixture__"): - return f, False + self.fixture_params = {} + # the fixtures of the Test* class running, by fixture name + self.class_fixtures = None + + def param_fixtures(self, deps): + """The parametrized fixtures a test reaches, directly or through + other fixtures, in the order first met.""" + found = [] + seen = set() + todo = list(deps) + while todo: + n = todo.pop(0) + if n in seen: + continue + seen.add(n) + f = self.find_fixture(n) + if f is None: + continue + d = f[3] + if d.params is not None: + found.append(d) + todo.extend(f[0] or ()) + return found + + def expand(self, func, deps): + """_expand_params, multiplied by each parametrized fixture's params; + the fixture values ride in the dict under a ("fixture", name) key.""" + combos = _expand_params(func) + for d in self.param_fixtures(deps): + nxt = [] + for base_id, vals, marks in combos: + for i, p in enumerate(d.params): + pid = str(d.ids[i]) if d.ids is not None and i < len(d.ids) \ + else _idpart(p, d.name, i) + v = dict(vals) + v[("fixture", d.name)] = p + nxt.append((pid if not base_id else base_id + "-" + pid, v, marks)) + combos = nxt + return combos + + # fixture lookup: the running class's, the module's, then the registry; + # (fixture names, call, is_method, definition) or None + def find_fixture(self, name): + if self.class_fixtures is not None: + m = self.class_fixtures.get(name) + if m is not None: + return m[2], m[3], True, m[1].__cn1_fixture__ + e = self.table.fixtures.get(name) + if e is not None: + return e[3], e[4], False, e[2].__cn1_fixture__ d = _registry.get(name) + if d is None and name in ("httpx_mock", "httpx2_mock"): + # A plugin's fixture, used without importing the plugin: pytest + # would have loaded it through its entry point. + import pytest_httpx2 # noqa: F401 + d = _registry.get(name) if d is not None: - return d.func, False - return None, False + return d.deps, d.call, False, d + return None def make(self, name, instance, cache, stack): - if name in cache: + if name in cache and name != "request": return cache[name] if name == "monkeypatch": mp = _MonkeyPatch() self.teardowns.append(mp.undo) cache[name] = mp return mp - func, is_method = self.find_fixture(name, instance) - if func is None: + if name == "request": + req = FixtureRequest(self.fixture_params.get(stack[-1]) if stack else None, + stack[-1] if stack else None, self, instance, cache) + cache[name] = req + return req + if name == "tmpdir": + # tmp_path's directory, as py.path.local: pytest gives both the same one + value = _LocalPath(self.make("tmp_path", instance, cache, stack)) + cache[name] = value + return value + if name == "tmp_path": + # A fresh directory per test under the system temporary directory, + # as pytest's tmp_path is; it is left in place, as pytest keeps + # the last few runs' directories. + import tempfile + import pathlib + path = pathlib.Path(tempfile.mkdtemp(prefix="pytest-")) + cache[name] = path + return path + found = self.find_fixture(name) + if found is None: raise Failed("fixture '%s' not found" % name) + call = found[1] + if call is None: + raise Failed("fixture '%s' is defined where the build lists no fixtures (only module and " + "Test* class level ones are)" % name) if name in stack: raise Failed("recursive dependency involving fixture '%s'" % name) stack.append(name) - names = _param_names(func, is_method) - kwargs = {} - for n in names: - kwargs[n] = self.make(n, instance, cache, stack) - stack.pop() - if is_method: - bound = getattr(instance, func.__name__) - value = bound(**kwargs) + + def resolve(n): + return self.make(n, instance, cache, stack) + if found[2]: + value = call(instance, resolve) else: - value = func(**kwargs) + value = call(resolve) + stack.pop() if _is_generator(value): gen = value value = next(gen) @@ -527,22 +868,23 @@ def run_teardowns(self): errors.append(e) return errors - def autouse_names(self, instance): - names = [] - for n in dir(self.module): - f = getattr(self.module, n) - d = getattr(f, "__cn1_fixture__", None) - if d is not None and d.autouse: - names.append(d.name) - if instance is not None: - for n in dir(type(instance)): - f = getattr(type(instance), n) - d = getattr(f, "__cn1_fixture__", None) + def autouse_names(self): + # conftest's autouse fixtures apply to every module, as pytest's do + names = [d.name for d in _registry.values() + if d.autouse and getattr(d.func, "__module__", "").rpartition(".")[2] == "conftest"] + for e in self.table.entries: + if e[0] == "f": + d = getattr(e[2], "__cn1_fixture__", None) if d is not None and d.autouse and d.name not in names: names.append(d.name) + if self.class_fixtures is not None: + for m in self.class_fixtures.values(): + d = m[1].__cn1_fixture__ + if d.autouse and d.name not in names: + names.append(d.name) return names - def run_one(self, nodeid, func, instance, is_method, extra_marks, values): + def run_one(self, nodeid, func, instance, call, extra_marks, values): marks = _marks_of(func) + extra_marks if instance is not None: marks = marks + _marks_of(type(instance)) @@ -562,23 +904,27 @@ def run_one(self, nodeid, func, instance, is_method, extra_marks, values): if cond: xfail_mark = m cache = {} + self.fixture_params = dict((k[1], v) for k, v in values.items() if isinstance(k, tuple)) outcome = None detail = "" + + def resolve(n): + if n in values: + return values[n] + return self.make(n, instance, cache, []) try: try: - for n in self.autouse_names(instance): + for n in self.autouse_names(): self.make(n, instance, cache, []) - names = _param_names(func, is_method) - kwargs = {} - for n in names: - if n in values: - kwargs[n] = values[n] - else: - kwargs[n] = self.make(n, instance, cache, []) - if is_method: - getattr(instance, func.__name__)(**kwargs) + if instance is not None: + ret = call(instance, resolve) else: - func(**kwargs) + ret = call(resolve) + if type(ret).__name__ == "coroutine": + # An async test runs to completion on a fresh loop, as + # pytest-asyncio's function-scoped loop runs it. + import asyncio + asyncio.run(ret) outcome = "passed" except Skipped as e: outcome = "skipped" @@ -611,35 +957,42 @@ def run_one(self, nodeid, func, instance, is_method, extra_marks, values): self.result.record(nodeid, outcome, detail) return {"passed": ".", "failed": "F", "skipped": "s", "xfailed": "x", "xpassed": "X"}[outcome] - def run_function(self, prefix, func, instance, is_method, extra_marks): + def run_function(self, prefix, entry): + name, func, deps, call = entry[1], entry[2], entry[3], entry[4] out = "" - for pid, values, pmarks in _expand_params(func): - nodeid = prefix + func.__name__ + ("[" + pid + "]" if pid else "") - out += self.run_one(nodeid, func, instance, is_method, extra_marks + pmarks, values) + for pid, values, pmarks in self.expand(func, deps): + nodeid = prefix + name + ("[" + pid + "]" if pid else "") + out += self.run_one(nodeid, func, None, call, pmarks, values) return out - def run_class(self, name, cls): + def run_class(self, name, cls, members): out = "" - for attr in dir(cls): - if not attr.startswith("test"): - continue - member = getattr(cls, attr) - if not callable(member): - continue - for pid, values, pmarks in _expand_params(member): - nodeid = "%s::%s::%s%s" % (self.module_name(), name, attr, "[" + pid + "]" if pid else "") - instance = cls() - if hasattr(instance, "setup_method"): - instance.setup_method(getattr(instance, attr)) - out += self.run_one(nodeid, member, instance, True, pmarks, values) - if hasattr(instance, "teardown_method"): - instance.teardown_method(getattr(instance, attr)) + self.class_fixtures = {} + for m in members: + d = getattr(m[1], "__cn1_fixture__", None) + if d is not None: + self.class_fixtures[d.name] = m + try: + for attr, member, deps, call, bound in members: + if not attr.startswith("test") or not callable(member): + continue + for pid, values, pmarks in self.expand(member, deps): + nodeid = "%s::%s::%s%s" % (self.module_name(), name, attr, "[" + pid + "]" if pid else "") + instance = cls() + if hasattr(instance, "setup_method"): + instance.setup_method(bound(instance)) + out += self.run_one(nodeid, member, instance, call, pmarks, values) + if hasattr(instance, "teardown_method"): + instance.teardown_method(bound(instance)) + finally: + self.class_fixtures = None return out def module_name(self): return getattr(self.module, "__name__", "module") + def _is_generator(value): return type(value).__name__ == "generator" @@ -661,19 +1014,26 @@ def _describe(e): def run_module(module, quiet=False): - """Run every test_* function and Test* class of a module object. Prints + """Run every test_* function and Test* class of a module object, as the + table PytestLowering wrote into it at build time lists them. Prints one line per test when not quiet, then the summary; returns the exit code pytest would use (0 all passed, 1 failures).""" - session = _Session(module, quiet) + table = getattr(module, "__cn1_pytest__", None) + if table is None: + raise TypeError("pytest.run_module(%r): the module has no test table; only a module that " + "imports pytest and defines tests at its top level gets one" % (module,)) + session = _Session(module, quiet, table) prefix = session.module_name() + "::" line = "" - for name in dir(module): - obj = getattr(module, name) - if name.startswith("test") and callable(obj) and not isinstance(obj, type) and \ - not hasattr(obj, "__cn1_fixture__"): - line += session.run_function(prefix, obj, None, False, []) - elif isinstance(obj, type) and name.startswith("Test"): - line += session.run_class(name, obj) + for e in table.entries: + name = e[1] + obj = e[2] + if e[0] == "f": + if name.startswith("test") and callable(obj) and not isinstance(obj, type) and \ + not hasattr(obj, "__cn1_fixture__"): + line += session.run_function(prefix, e) + elif isinstance(obj, type): + line += session.run_class(name, obj, e[3]) result = session.result if not quiet: print(line) diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/site/pytest_httpx/__init__.py b/maven/python-transpiler/src/main/resources/com/codename1/python/site/pytest_httpx/__init__.py new file mode 100644 index 00000000000..c21e595fb7a --- /dev/null +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/site/pytest_httpx/__init__.py @@ -0,0 +1,5 @@ +# Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. +# Licensed under the GNU General Public License version 2 with the Classpath +# exception, as the rest of the Codename One Python runtime. +"""pytest_httpx, the httpx 1 name of the same fixture: see pytest_httpx2.""" +from pytest_httpx2 import HTTPXMock, IteratorStream, httpx_mock # noqa: F401 diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/site/pytest_httpx2/__init__.py b/maven/python-transpiler/src/main/resources/com/codename1/python/site/pytest_httpx2/__init__.py new file mode 100644 index 00000000000..f39836f187f --- /dev/null +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/site/pytest_httpx2/__init__.py @@ -0,0 +1,241 @@ +# Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. +# Licensed under the GNU General Public License version 2 with the Classpath +# exception, as the rest of the Codename One Python runtime. +"""pytest_httpx2: the httpx2_mock (and httpx_mock) fixture, over the bundled +httpx. + +Every request any client sends -- through the default transport, an +explicit HTTPTransport or AsyncHTTPTransport -- is answered from the +responses registered with add_response or add_callback instead of the +network. Matching is by url (str, httpx.URL or compiled pattern; query +parameters compare as a multiset), method, match_headers (a subset), +match_content, match_json and match_params. The first matching response +not yet used answers; once all are used, the last reusable one does. A +request nothing matches raises httpx.TimeoutException, as pytest_httpx's +does, and the fixture's teardown fails the test when a registered, +non-optional response was never requested. + +A stream= body (IteratorStream or any iterable of bytes) is read whole +when the request arrives, so a client sees the same bytes, in one piece. +The options pytest_httpx reads from an httpx_mock marker are ignored. +""" + +import json as _json +import re as _re +from urllib.parse import parse_qsl as _parse_qsl, urlsplit as _urlsplit + +import httpx +import pytest + +__all__ = ["HTTPXMock", "IteratorStream", "httpx_mock", "httpx2_mock"] + + +class IteratorStream(httpx.SyncByteStream, httpx.AsyncByteStream): + """A response body produced chunk by chunk, sync or async.""" + + def __init__(self, stream): + self._chunks = stream + + def __iter__(self): + yield from self._chunks + + async def __aiter__(self): + for chunk in self._chunks: + yield chunk + + +def _split_url(url): + text = str(url) + parts = _urlsplit(text) + base = (parts.scheme.lower(), parts.netloc.lower(), parts.path or "/") + return base, sorted(_parse_qsl(parts.query, keep_blank_values=True)) + + +class _Matcher: + def __init__(self, url=None, method=None, match_headers=None, match_content=None, + match_json=None, match_params=None, match_data=None, match_files=None, + match_extensions=None, proxy_url=None, is_optional=False, is_reusable=False): + if match_content is not None and match_json is not None: + raise ValueError("Only one way of matching against the body can be provided. " + "If you want to match against the JSON decoded representation, use match_json. " + "Otherwise, use match_content.") + self.url = url + self.method = method.upper() if method else None + self.headers = match_headers + self.content = match_content + self.json = match_json + self.params = match_params + self.optional = is_optional + self.reusable = is_reusable + self.nb_calls = 0 + + def match(self, request): + if self.url is not None: + if isinstance(self.url, _re.Pattern): + if not self.url.match(str(request.url)): + return False + else: + want_base, want_query = _split_url(self.url) + if self.params is not None: + want_query = sorted(want_query + [(k, str(v)) for k, vs in self.params.items() + for v in (vs if isinstance(vs, list) else [vs])]) + if (want_base, want_query) != _split_url(request.url): + return False + if self.method is not None and request.method.upper() != self.method: + return False + if self.headers is not None: + for k, v in self.headers.items(): + if request.headers.get(k) != v: + return False + if self.content is not None and request.content != self.content: + return False + if self.json is not None: + try: + if _json.loads(request.content.decode("utf-8")) != self.json: + return False + except ValueError: + return False + return True + + def describe(self): + bits = [] + if self.method: + bits.append(self.method) + bits.append("request" if not self.url else "request on " + str(self.url)) + return "Match " + " ".join(bits) + + +class HTTPXMock: + def __init__(self): + self._callbacks = [] + self._requests = [] + + def add_response(self, status_code=200, http_version="HTTP/1.1", headers=None, content=None, + text=None, html=None, stream=None, json=None, **matchers): + import copy + if json is not None: + json = copy.deepcopy(json) + + def respond(request): + body = content + if stream is not None: + body = b"".join(bytes(c) for c in stream) + if html is not None: + h = httpx.Headers(headers) + h.setdefault("Content-Type", "text/html; charset=utf-8") + return httpx.Response(status_code, headers=h, content=html.encode("utf-8")) + return httpx.Response(status_code, headers=headers, content=body, text=text, json=json) + self.add_callback(respond, **matchers) + + def add_callback(self, callback, **matchers): + self._callbacks.append((_Matcher(**matchers), callback)) + + def add_exception(self, exception, **matchers): + def raise_it(request): + if isinstance(exception, httpx.RequestError): + exception.request = request + raise exception + self.add_callback(raise_it, **matchers) + + def _find(self, request): + found = [(m, c) for m, c in self._callbacks if m.match(request)] + if not found: + return None + for m, c in found: + if not m.nb_calls: + m.nb_calls += 1 + return c + m, c = found[-1] + if m.reusable: + m.nb_calls += 1 + return c + return None + + def _handle(self, request): + self._requests.append(request) + callback = self._find(request) + if callback is None: + raise httpx.TimeoutException("No response can be found for %s request on %s" + % (request.method, request.url), request=request) + response = callback(request) + if response is None: + raise TypeError("The callback did not return a response") + response._request = request + return response + + async def _handle_async(self, request): + self._requests.append(request) + callback = self._find(request) + if callback is None: + raise httpx.TimeoutException("No response can be found for %s request on %s" + % (request.method, request.url), request=request) + response = callback(request) + if hasattr(response, "__await__"): + response = await response + if response is None: + raise TypeError("The callback did not return a response") + response._request = request + return response + + def get_requests(self, **matchers): + m = _Matcher(**matchers) + return [r for r in self._requests if m.match(r)] + + def get_request(self, **matchers): + found = self.get_requests(**matchers) + assert len(found) <= 1, \ + "More than one request (%d) matched, use get_requests instead or refine your filters." % len(found) + return found[0] if found else None + + def reset(self): + self._callbacks.clear() + self._requests.clear() + + def _unused(self): + return [m for m, _ in self._callbacks if not m.nb_calls and not m.optional] + + +def _install(mock): + """Routes every transport through the mock; returns the undo.""" + saved = (httpx._transport, httpx.HTTPTransport.handle_request, + httpx.AsyncHTTPTransport.handle_async_request) + + def module_transport(request, timeout, follow): + return mock._handle(request) + + def handle_request(self, request): + return mock._handle(request) + + async def handle_async_request(self, request): + return await mock._handle_async(request) + httpx._transport = module_transport + httpx.HTTPTransport.handle_request = handle_request + httpx.AsyncHTTPTransport.handle_async_request = handle_async_request + + def undo(): + httpx._transport, httpx.HTTPTransport.handle_request, \ + httpx.AsyncHTTPTransport.handle_async_request = saved + return undo + + +def _fixture(): + mock = HTTPXMock() + undo = _install(mock) + try: + yield mock + finally: + undo() + unused = mock._unused() + if unused: + raise AssertionError("The following responses are mocked but not requested:\n" + + "\n".join(" - " + m.describe() for m in unused)) + + +@pytest.fixture +def httpx2_mock(): + yield from _fixture() + + +@pytest.fixture +def httpx_mock(): + yield from _fixture() diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/site/requests/__init__.py b/maven/python-transpiler/src/main/resources/com/codename1/python/site/requests/__init__.py index 31789e3fdef..bf84ce268e7 100644 --- a/maven/python-transpiler/src/main/resources/com/codename1/python/site/requests/__init__.py +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/site/requests/__init__.py @@ -36,13 +36,23 @@ def __init__(self): 405: ("method_not_allowed",), 409: ("conflict",), 410: ("gone",), 418: ("im_a_teapot", "teapot"), 422: ("unprocessable_entity",), 429: ("too_many_requests",), 500: ("internal_server_error",), 502: ("bad_gateway",), 503: ("service_unavailable", "unavailable"), 504: ("gateway_timeout",)} + # A table read by name: every code is an int, and `codes.ok` comes + # through __getattr__ typed as one, where an attribute per name set + # by a computed setattr could hold anything. + self._by_name = {} for code, names in table.items(): for n in names: - setattr(self, n, code) - setattr(self, n.upper(), code) + self._by_name[n] = code + self._by_name[n.upper()] = code + + def __getattr__(self, name): + code = self._by_name.get(name) + if code is None: + raise AttributeError(name) + return code def __getitem__(self, name): - return getattr(self, name, None) + return self._by_name.get(name) codes = _Codes() @@ -65,7 +75,10 @@ def __init__(self): self.reason = None self.url = None self.headers = CaseInsensitiveDict() - self._content = b"" + # None until read: a Response built by hand may carry its body in + # .raw, a file-like object, as one requests itself would return. + self._content = None + self.raw = None self.encoding = None self.history = [] self.request = None @@ -74,6 +87,8 @@ def __init__(self): @property def content(self): + if self._content is None: + self._content = self.raw.read() if self.raw is not None else b"" return self._content @property @@ -84,9 +99,9 @@ def apparent_encoding(self): def text(self): enc = self.encoding or "utf-8" try: - return self._content.decode(enc, "replace") + return self.content.decode(enc, "replace") except LookupError: - return self._content.decode("utf-8", "replace") + return self.content.decode("utf-8", "replace") def json(self, **kwargs): try: @@ -125,14 +140,14 @@ def raise_for_status(self): raise HTTPError(msg, response=self) def iter_content(self, chunk_size=1, decode_unicode=False): - data = self.text if decode_unicode else self._content + data = self.text if decode_unicode else self.content if chunk_size is None: chunk_size = len(data) or 1 for i in range(0, len(data), chunk_size): yield data[i:i + chunk_size] def iter_lines(self, chunk_size=512, decode_unicode=False, delimiter=None): - data = self.text if decode_unicode else self._content + data = self.text if decode_unicode else self.content lines = data.split(delimiter) if delimiter is not None else data.splitlines() for line in lines: yield line diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/site/sqlalchemy/_cn1dbapi.py b/maven/python-transpiler/src/main/resources/com/codename1/python/site/sqlalchemy/_cn1dbapi.py index afe80140936..d0d77efc4d0 100644 --- a/maven/python-transpiler/src/main/resources/com/codename1/python/site/sqlalchemy/_cn1dbapi.py +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/site/sqlalchemy/_cn1dbapi.py @@ -15,20 +15,12 @@ paramstyle = "qmark" -class Error(_sqlite3.Error): - pass - - -class OperationalError(Error, _sqlite3.OperationalError): - pass - - -class ProgrammingError(Error, _sqlite3.ProgrammingError): - pass - - -class IntegrityError(Error, _sqlite3.IntegrityError): - pass +# The sqlite3 classes themselves: the engine maps them into sqlalchemy.exc, +# and a class with two exception bases could have no layout. +Error = _sqlite3.Error +OperationalError = _sqlite3.OperationalError +ProgrammingError = _sqlite3.ProgrammingError +IntegrityError = _sqlite3.IntegrityError _INTEGRITY = ("duplicate", "unique", "foreign key", "violates", "cannot be null", "not-null") diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/site/sqlalchemy/orm/__init__.py b/maven/python-transpiler/src/main/resources/com/codename1/python/site/sqlalchemy/orm/__init__.py index 94d2e668005..bed5df8f2bb 100644 --- a/maven/python-transpiler/src/main/resources/com/codename1/python/site/sqlalchemy/orm/__init__.py +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/site/sqlalchemy/orm/__init__.py @@ -1,11 +1,21 @@ """SQLAlchemy 2.0 declarative ORM subset: DeclarativeBase, Mapped, mapped_column, relationship (one-to-many, many-to-one, many-to-many through ``secondary``) and Session. -Mapping is done by a metaclass reading the class body's ``__annotations__``; nothing is -evaluated with ``exec``. Instance state lives in ``obj.__dict__``: a column attribute that -is absent from it is *expired* and is reloaded from the database on access, which is how -``expire_on_commit``, ``refresh`` and ``rollback`` work. Changes are found at flush time by -comparing the attribute values with a snapshot taken at load, so no attribute events. +There is no metaclass and nothing is looked up by a computed name. The build +(``SqlAlchemyLowering``) rewrites every module-level mapped class: each column and +relationship becomes a descriptor naming its key and its slot number literally +(``_sa_col``/``_sa_rel``), the class gets literal tables (``__cn1_sa_cols__``, +``__cn1_sa_rels__``, ``__cn1_sa_parent__``, ``__cn1_sa_table__``, ``__cn1_sa_args__``, +``__cn1_sa_nslots__``), a keyword-only ``__init__`` storing each column's slot literally +(unless the user wrote one) and a keyword hook ``__cn1_sa_kw__``, ``back_populates`` pairs are +linked with ``_sa_pair`` and the class is mapped by ``M.__cn1_sa_map__()`` right after +its definition. + +Instance state lives in a declared slot list ``obj._sa_v`` indexed by those slot +numbers: a slot holding ``_UNSET`` is *expired* and is reloaded from the database on +access, which is how ``expire_on_commit``, ``refresh`` and ``rollback`` work. Changes are +found at flush time by comparing the slots with a snapshot taken at load, so no +attribute events. Also: cascades (save-update, delete, delete-orphan; deleting a parent nulls its children's foreign keys unless ``passive_deletes``), ``selectinload``/``joinedload`` and ``lazy=`` eager @@ -14,11 +24,10 @@ ``aliased()`` and ``any()``/``has()`` on relationships. Unsupported: chained loader options, concrete-table inheritance, joins along a many-to-many -relationship, hybrid properties. +relationship, hybrid properties, mapped classes not defined at module level. """ import datetime as _dt -import typing as _typing import sqlalchemy as _sa from sqlalchemy import (Column, ForeignKey, Integer, String, Float, Boolean, DateTime, Date, LargeBinary, @@ -30,93 +39,40 @@ "declarative_base", "registry", "selectinload", "joinedload", "subqueryload", "lazyload", "aliased"] -_PY_TYPES = {int: Integer, str: String, float: Float, bool: Boolean, bytes: LargeBinary, - _dt.datetime: DateTime, _dt.date: Date} _PY_NAMES = {"int": Integer, "str": String, "float": Float, "bool": Boolean, "bytes": LargeBinary, "datetime": DateTime, "datetime.datetime": DateTime, "date": Date, "datetime.date": Date} -class _MappedAnnotation: - def __init__(self, arg): - self.arg = arg +class _Unset: + def __repr__(self): + return "" + + +# The value of a slot that holds nothing: never loaded, or expired. +_UNSET = _Unset() class Mapped: def __class_getitem__(cls, item): - return _MappedAnnotation(item) + return cls WriteOnlyMapped = Mapped DynamicMapped = Mapped -def _name_of(t): - if isinstance(t, str): - return t.strip().strip("'\"") - fa = getattr(t, "__forward_arg__", None) - if fa is not None: - return fa - return getattr(t, "__name__", None) - - -def _strip(s, prefix): - for p in prefix: - if s.startswith(p + "[") and s.endswith("]"): - return s[len(p) + 1:-1].strip() - return None - - -def _analyze(ann): - """Returns (python type or class name, optional flag, is_list) for an annotation.""" - if isinstance(ann, _MappedAnnotation): - ann = ann.arg - elif isinstance(ann, str): - inner = _strip(ann.strip(), ("Mapped", "orm.Mapped", "WriteOnlyMapped", "DynamicMapped")) - if inner is None: - return None, False, False - ann = inner - if isinstance(ann, str): - s = ann.strip() - inner = _strip(s, ("Optional", "typing.Optional")) - if inner is not None: - t, _, lst = _analyze_str(inner) - return t, True, lst - if s.endswith("| None"): - t, _, lst = _analyze_str(s[:-6].strip()) - return t, True, lst - return _analyze_str(s) - origin = _typing.get_origin(ann) - args = _typing.get_args(ann) - if origin is _typing.Union or (args and type(None) in args and origin is not list): - rest = [a for a in args if a is not type(None)] - t, _, lst = _analyze(rest[0]) if rest else (None, False, False) - return t, True, lst - if origin in (list, set): - return _name_of(args[0]) if args else None, False, True - return ann, False, False - - -def _analyze_str(s): - inner = _strip(s, ("List", "list", "typing.List", "Set", "set")) - if inner is not None: - return _name_of(inner), False, True - return _name_of(s), False, False - - -def _sql_type(pytype, tmap=None): - if pytype is None: +def _sql_type(name, tmap=None): + if name is None: return None if tmap: # DeclarativeBase.type_annotation_map: {str: String(100)} is how a model # gives every Mapped[str] a length, which MySQL's VARCHAR demands. + short = name.split(".")[-1] for k in tmap: - if k is pytype or (isinstance(pytype, str) and getattr(k, "__name__", None) == pytype): + if getattr(k, "__name__", None) == short: v = tmap[k] return v() if isinstance(v, type) else v - if isinstance(pytype, str): - t = _PY_NAMES.get(pytype) - else: - t = _PY_TYPES.get(pytype) + t = _PY_NAMES.get(name) return t() if t is not None else None @@ -151,26 +107,69 @@ def mapped_column(*args, **kw): return _MappedColumnSpec(args, kw) +def _peek(obj, i): + """Slot ``i`` of ``obj`` without loading it: None when it holds nothing.""" + v = obj._sa_v[i] + return None if v is _UNSET else v + + +def _get(obj, i): + """Slot ``i`` of ``obj``, reloading the row first when it is expired.""" + v = obj._sa_v[i] + if v is not _UNSET: + return v + st = obj._sa_state + if st.session is not None and st.persistent: + st.session._load_expired(obj) + return _peek(obj, i) + return None + + class _ColumnAttr: - def __init__(self, key, column): + """A mapped column: the class reads the Column, an instance reads slot ``idx``.""" + + def __init__(self, idx, key, pytype, optional, spec): + self.idx = idx self.key = key - self.column = column + self.pytype = pytype + self.optional = optional + self.spec = spec + self.column = None + + def _build(self, owner, tmap): + spec = self.spec + if isinstance(spec, _MappedColumnSpec): + col = spec._make(self.key, self.pytype, self.optional, tmap) + elif isinstance(spec, Column): + col = spec + if col.name is None: + col.name = col.key = self.key + else: + t = _sql_type(self.pytype, tmap) + if t is None: + raise exc.ArgumentError("Could not locate SQLAlchemy type for %s.%s" % (owner.__name__, self.key)) + col = Column(self.key, t, nullable=self.optional) + self.column = col + return col def __get__(self, obj, owner=None): if obj is None: return self.column - d = obj.__dict__ - if self.key in d: - return d[self.key] - st = d.get("_sa_state") - if st is not None and st.session is not None and st.persistent: - st.session._load_expired(obj) - # obj.__dict__ may be a snapshot taken when read: read it again after the load. - return obj.__dict__.get(self.key) - return None + return _get(obj, self.idx) def __set__(self, obj, value): - obj.__dict__[self.key] = value + obj._sa_v[self.idx] = value + + +def _sa_col(idx, key, pytype, optional, spec): + return _ColumnAttr(idx, key, pytype, optional, spec) + + +class _Thunk: + """A value the build wrote as a deferred expression (``order_by="Book.id"``).""" + + def __init__(self, fn): + self.fn = fn _ONETOMANY = "ONETOMANY" @@ -219,7 +218,7 @@ def remove(self, x): def _removed(self, x): self._prop._back_set(self._owner, x, False) if self._prop.delete_orphan: - sess = _state(self._owner).session + sess = self._owner._sa_state.session if sess is not None: sess._orphans.append((x, self._prop)) @@ -260,6 +259,9 @@ class RelationshipProperty: def __init__(self, argument=None, back_populates=None, uselist=None, lazy="select", order_by=None, foreign_keys=None, cascade=None, backref=None, viewonly=False, secondary=None, passive_deletes=False, **kw): + if backref is not None: + raise exc.ArgumentError("relationship(backref=...) is not supported; declare both sides" + " with back_populates") self.argument = argument self.back_populates = back_populates self.uselist = uselist @@ -274,35 +276,26 @@ def __init__(self, argument=None, back_populates=None, uselist=None, lazy="selec self.cascade_delete = "delete" in parts self.delete_orphan = "delete-orphan" in parts self.key = None + self.idx = -1 self.parent = None - self._target_name = None + self._target_fn = None self._list_ann = None - self._ann = None + self._back = None self._ready = False def _setup(self): if self._ready: return - arg = self.argument - if arg is None: - arg = self._target_name - if callable(arg) and not isinstance(arg, type): - arg = arg() - if isinstance(arg, str): - arg = self.parent._sa_registry[arg] + arg = self._target_fn() self.target = arg - if arg is None: - raise exc.ArgumentError("Could not determine the target class of relationship %s.%s (%r)" - % (self.parent.__name__ if self.parent is not None else None, self.key, - self._ann)) pt = self.parent.__table__ tt = arg.__table__ self.direction = None sec = self.secondary if isinstance(sec, str): sec = self.parent.metadata.tables[sec] - elif sec is not None and not isinstance(sec, Table) and callable(sec): - sec = sec() + elif isinstance(sec, _Thunk): + sec = sec.fn() self.secondary = sec if sec is not None: self.sec_local = None @@ -334,18 +327,21 @@ def _setup(self): if self.direction is None: raise exc.ArgumentError("Could not determine join condition for relationship %s.%s" % (self.parent.__name__, self.key)) - if isinstance(self.order_by, str): - cname, aname = self.order_by.split(".") - self.order_by = getattr(self.parent._sa_registry[cname], aname) + if isinstance(self.order_by, _Thunk): + self.order_by = self.order_by.fn() if self.uselist is None: self.uselist = self.direction != _MANYTOONE if self._list_ann is None else self._list_ann self._ready = True def _other(self): self._setup() - if self.back_populates: - return self.target.__sa_mapper__.relationships[self.back_populates] - return None + b = self._back + if b is not None: + # Its uselist is decided by its own setup: read before it, a + # collection side looked scalar (a fresh Author's books set to the + # Book itself by `Book(author=a)`). + b._setup() + return b def _join_info(self): self._setup() @@ -380,18 +376,18 @@ def has(self, criterion=None, **kw): def __get__(self, obj, owner=None): if obj is None: return self - d = obj.__dict__ - if self.key in d: - return d[self.key] + v = obj._sa_v[self.idx] + if v is not _UNSET: + return v self._setup() - st = d.get("_sa_state") - if st is not None and st.session is not None and st.persistent: + st = obj._sa_state + if st.session is not None and st.persistent: value = st.session._lazy_load(obj, self) elif self.uselist: value = InstrumentedList(obj, self) else: value = None - d[self.key] = value + obj._sa_v[self.idx] = value return value def __set__(self, obj, value): @@ -401,24 +397,24 @@ def __set__(self, obj, value): if self.direction == _MANYTOMANY: old = self.__get__(obj) lst._db = list(old._db) - obj.__dict__[self.key] = lst + obj._sa_v[self.idx] = lst for x in value: lst.append(x) return - old = obj.__dict__.get(self.key) - obj.__dict__[self.key] = value + old = _peek(obj, self.idx) + obj._sa_v[self.idx] = value other = self._other() if other is None: return if other.uselist: if old is not None and old is not value: - ol = old.__dict__.get(other.key) + ol = old._sa_v[other.idx] if isinstance(ol, InstrumentedList): ol._items = [i for i in ol._items if i is not obj] if value is not None: - getattr(value, other.key)._raw_add(obj) + other.__get__(value)._raw_add(obj) elif value is not None: - value.__dict__[other.key] = obj + value._sa_v[other.idx] = obj def _back_set(self, owner, child, add): """``child`` was added to or removed from ``owner``'s collection: update the other side.""" @@ -426,21 +422,36 @@ def _back_set(self, owner, child, add): if other is None: return if self.direction == _MANYTOMANY: - lst = child.__dict__.get(other.key) + lst = child._sa_v[other.idx] if add: - if lst is None: - lst = getattr(child, other.key) + if not isinstance(lst, InstrumentedList): + lst = other.__get__(child) lst._raw_add(owner) - elif lst is not None: + elif isinstance(lst, InstrumentedList): lst._raw_remove(owner) return - child.__dict__[other.key] = owner if add else None + child._sa_v[other.idx] = owner if add else None def relationship(argument=None, **kw): return RelationshipProperty(argument, **kw) +def _sa_rel(idx, key, target, is_list, rel): + """The build's form of a relationship: ``target`` returns the class it names.""" + rel.idx = idx + rel.key = key + rel._target_fn = target + rel._list_ann = is_list + return rel + + +def _sa_pair(a, b): + """Links two relationships that name each other in back_populates.""" + a._back = b + b._back = a + + class _LoaderOption: def __init__(self, rel, strategy): self.rel = rel @@ -477,9 +488,11 @@ def _slot(self): from_=self.alias, key=self.alias.name) def __getattr__(self, name): + # The mapped attributes are data here: a list of (key, column) the + # mapper holds, compared by value, never an attribute lookup. if name.startswith("_"): raise AttributeError(name) - for k, c in self._m.attrs: + for k, c, i in self._m.attrs: if k == name: return self.alias.corresponding_column(c) raise AttributeError(name) @@ -493,16 +506,12 @@ class _State: def __init__(self): self.session = None self.persistent = False + # Slot number -> the value the database last held. self.snapshot = {} def _state(obj): - d = obj.__dict__ - st = d.get("_sa_state") - if st is None: - st = _State() - d["_sa_state"] = st - return st + return obj._sa_state class Mapper: @@ -510,8 +519,9 @@ def __init__(self, cls, table, attrs, relationships, inherits=None, args=None, i args = args or {} self.class_ = cls self.table = table + # (key, column, slot number) for every mapped column, the inherited ones first. self.attrs = attrs - self.columns = [c for k, c in attrs] + self.columns = [c for k, c, i in attrs] self.relationships = relationships self.inherits = inherits self.base = inherits.base if inherits is not None else self @@ -522,7 +532,7 @@ def __init__(self, cls, table, attrs, relationships, inherits=None, args=None, i self.pk = inherits.pk self.tables = list(inherits.tables) else: - self.pk = [(k, c) for k, c in attrs if c.primary_key] + self.pk = [(k, c, i) for k, c, i in attrs if c.primary_key] self.tables = [] if not any(t is table for t in self.tables): self.tables.append(table) @@ -549,23 +559,14 @@ def poly_filter(self, cols): return self.polymorphic_on.in_(ids) def _identity(self, obj): - return tuple(obj.__dict__.get(k) for k, c in self.pk) - - def _populate(self, obj, values): - d = obj.__dict__ - st = _state(obj) - for i in range(len(self.attrs)): - k, c = self.attrs[i] - v = c.type.result(values[i]) - d[k] = v - st.snapshot[k] = v + return tuple(_peek(obj, i) for k, c, i in self.pk) def _load_row(self, session, values, cols=None): if cols is None: cols = self.columns origs = [getattr(c, "_proxied", c) for c in cols] ident = [] - for k, pc in self.pk: + for k, pc, pi in self.pk: for i in range(len(origs)): if origs[i] is pc: ident.append(values[i]) @@ -583,14 +584,15 @@ def _load_row(self, session, values, cols=None): fresh = obj is None if fresh: obj = m.class_.__new__(m.class_) - st = _state(obj) - d = obj.__dict__ + obj._sa_alloc() + st = obj._sa_state + sv = obj._sa_v for i in range(len(origs)): - k = _attr_key(m, origs[i]) - if fresh or k not in d: + j = _attr_idx(m, origs[i]) + if fresh or sv[j] is _UNSET: v = origs[i].type.result(values[i]) - d[k] = v - st.snapshot[k] = v + sv[j] = v + st.snapshot[j] = v if fresh and session is not None: st.session = session st.persistent = True @@ -598,126 +600,95 @@ def _load_row(self, session, values, cols=None): return obj -class DeclarativeMeta(type): - def __new__(mcs, name, bases, ns, **kw): - cls = type.__new__(mcs, name, bases, ns) - if ns.get("_sa_root"): - return cls - if not any(b.__dict__.get("_sa_registry") is not None for b in cls.__mro__[1:]) \ - or "_sa_registry" in ns: - if "metadata" not in ns: - cls.metadata = MetaData() - cls._sa_registry = {} - cls.registry = cls._sa_registry - return cls - parent = getattr(cls, "__sa_mapper__", None) - if parent is None and "__tablename__" not in ns and "__table__" not in ns: - return cls - _map_class(cls, ns, parent) - return cls - - -def _map_class(cls, ns, parent=None): - ann = ns.get("__annotations__", {}) - tmap = getattr(cls, "type_annotation_map", None) +def _map_class(cls): + """What the metaclass did, from the literal tables the build wrote into ``cls``.""" + pcls = cls.__cn1_sa_parent__ + parent = pcls.__sa_mapper__ if pcls is not None else None + tmap = cls.type_annotation_map attrs = [] + for a in cls.__cn1_sa_cols__: + attrs.append((a.key, a._build(cls, tmap), a.idx)) rels = {} - specs = [] - for key in ann: - a = ann[key] - v = ns.get(key) - if isinstance(v, RelationshipProperty): - pyt, optional, is_list = _analyze(a) - v._target_name = pyt if isinstance(pyt, str) else _name_of(pyt) - v._list_ann = is_list if pyt is not None else None - v._ann = a - v.key = key - v.parent = cls - rels[key] = v - continue - pyt, optional, is_list = _analyze(a) - if isinstance(v, _MappedColumnSpec): - col = v._make(key, pyt, optional, tmap) - specs.append((v, col)) - elif isinstance(v, Column): - col = v - if col.name is None: - col.name = col.key = key - elif v is None and (isinstance(a, _MappedAnnotation) or (isinstance(a, str) and "Mapped" in a)): - t = _sql_type(pyt, tmap) - if t is None: - raise exc.ArgumentError("Could not locate SQLAlchemy type for %s.%s" % (cls.__name__, key)) - col = Column(key, t, nullable=optional) - else: - continue - attrs.append((key, col)) - for key in ns: - v = ns[key] - if key not in ann: - if isinstance(v, _MappedColumnSpec): - col = v._make(key, None, False) - specs.append((v, col)) - attrs.append((key, col)) - elif isinstance(v, Column): - if v.name is None: - v.name = v.key = key - attrs.append((key, v)) - elif isinstance(v, RelationshipProperty): - v.key = key - v.parent = cls - rels[key] = v - args = dict(ns.get("__mapper_args__", {})) + for r in cls.__cn1_sa_rels__: + r.parent = cls + rels[r.key] = r + margs = cls.__cn1_sa_args__ + args = dict(margs) if margs is not None else {} + tablename = cls.__cn1_sa_table__ inherit_cols = [] - own = [k for k, c in attrs] if parent is None: - table = Table(cls.__tablename__, cls.metadata, *[c for k, c in attrs]) + table = Table(tablename, cls.metadata, *[c for k, c, i in attrs]) all_attrs = attrs all_rels = rels else: all_rels = dict(parent.relationships) all_rels.update(rels) - if "__tablename__" not in ns and "__table__" not in ns: + if tablename is None: # Single-table inheritance: the subclass's columns join the parent's table. table = parent.table - for k, c in attrs: + for k, c, i in attrs: c.table = table table.c._add(c) all_attrs = parent.attrs + attrs else: - table = Table(ns["__tablename__"], cls.metadata, *[c for k, c in attrs]) - pkeys = [k for k, c in parent.attrs] - for k, c in attrs: - for pk_, pc in parent.attrs: + table = Table(tablename, cls.metadata, *[c for k, c, i in attrs]) + pkeys = [k for k, c, i in parent.attrs] + for k, c, i in attrs: + for pk_, pc, pi in parent.attrs: if k == pk_: inherit_cols.append((c, pc)) - all_attrs = parent.attrs + [(k, c) for k, c in attrs if k not in pkeys] + all_attrs = parent.attrs + [(k, c, i) for k, c, i in attrs if k not in pkeys] on = args.get("polymorphic_on") if on is not None: if isinstance(on, str): - on = [c for k, c in all_attrs if k == on][0] - elif isinstance(on, _MappedColumnSpec): - on = [c for sp, c in specs if sp is on][0] + on = [c for k, c, i in all_attrs if k == on][0] elif isinstance(on, _ColumnAttr): on = on.column + elif isinstance(on, _MappedColumnSpec): + on = [a.column for a in cls.__cn1_sa_cols__ if a.spec is on][0] args["polymorphic_on"] = on cls.__table__ = table cls.__sa_mapper__ = Mapper(cls, table, all_attrs, all_rels, parent, args, inherit_cols) - for k, c in all_attrs: - if k in own: - setattr(cls, k, _ColumnAttr(k, c)) - cls._sa_registry[cls.__name__] = cls -class DeclarativeBase(metaclass=DeclarativeMeta): - _sa_root = True +class DeclarativeBase: + metadata = None + type_annotation_map = None + __table__ = None + __sa_mapper__ = None + # The tables SqlAlchemyLowering writes into every mapped class. + __cn1_sa_cols__ = () + __cn1_sa_rels__ = () + __cn1_sa_parent__ = None + __cn1_sa_table__ = None + __cn1_sa_args__ = None + __cn1_sa_nslots__ = 0 def __init__(self, **kw): - m = type(self).__sa_mapper__ - _state(self) + self._sa_new() + self.__cn1_sa_kw__(kw) for k in kw: - if not any(k == a for a, c in m.attrs) and k not in m.relationships: - raise TypeError("%r is an invalid keyword argument for %s" % (k, type(self).__name__)) - setattr(self, k, kw[k]) + raise TypeError("%r is an invalid keyword argument for %s" % (k, type(self).__name__)) + + def _sa_new(self): + # The start of every constructor: the keyword one above, and the + # keyword-only __init__ the build writes into each model. + if type(self).__sa_mapper__ is None: + raise exc.InvalidRequestError("class %s was not mapped at build time: a model must be defined at" + " module level, deriving from a DeclarativeBase subclass of the same" + " module" % type(self).__name__) + self._sa_alloc() + + def _sa_alloc(self): + self._sa_v = [_UNSET] * self.__cn1_sa_nslots__ + self._sa_state = _State() + + def __cn1_sa_kw__(self, kw): + pass + + @classmethod + def __cn1_sa_map__(cls): + _map_class(cls) def __repr__(self): m = type(self).__sa_mapper__ @@ -732,10 +703,8 @@ class MappedAsDataclass: def declarative_base(metadata=None): - ns = {"_sa_registry": {}} - if metadata is not None: - ns["metadata"] = metadata - return DeclarativeMeta("Base", (DeclarativeBase,), ns) + raise exc.InvalidRequestError("declarative_base() is compiled by the build: assign it to a name at" + " module level (Base = declarative_base())") class _SessionTx: @@ -790,13 +759,13 @@ def close(self): def expunge_all(self): for obj in list(self._identity.values()) + self._new: - _state(obj).session = None + obj._sa_state.session = None self._identity = {} self._new = [] self._deleted = [] def expunge(self, obj): - st = _state(obj) + st = obj._sa_state st.session = None self._new = [o for o in self._new if o is not obj] for k in list(self._identity): @@ -805,7 +774,7 @@ def expunge(self, obj): # -- unit of work def add(self, obj, _warn=True): - st = _state(obj) + st = obj._sa_state if st.persistent and st.session is self: return if any(o is obj for o in self._new): @@ -821,7 +790,7 @@ def add_all(self, objs): def _cascade(self, obj): m = type(obj).__sa_mapper__ for key in m.relationships: - v = obj.__dict__.get(key) + v = _peek(obj, m.relationships[key].idx) if v is None: continue if isinstance(v, InstrumentedList): @@ -831,13 +800,13 @@ def _cascade(self, obj): self._cascade_one(v) def _cascade_one(self, x): - st = _state(x) + st = x._sa_state if st.persistent and st.session is self: return self.add(x) def delete(self, obj): - st = _state(obj) + st = obj._sa_state if not st.persistent: self._new = [o for o in self._new if o is not obj] return @@ -850,26 +819,26 @@ def delete(self, obj): rel._setup() if rel.direction != _ONETOMANY: continue - if key not in obj.__dict__ and rel.passive_deletes: + if obj._sa_v[rel.idx] is _UNSET and rel.passive_deletes: # The database's ON DELETE takes care of rows that were never loaded. continue - v = getattr(obj, key) + v = rel.__get__(obj) if isinstance(v, InstrumentedList): children = list(v._items) else: children = [] if v is None else [v] other = rel._other() - rk = _attr_key(rel.target.__sa_mapper__, rel.remote) + rk = _attr_idx(rel.target.__sa_mapper__, rel.remote) for c in children: if rel.cascade_delete: self.delete(c) else: - c.__dict__[rk] = None + c._sa_v[rk] = None if other is not None: - c.__dict__[other.key] = None + c._sa_v[other.idx] = None def __contains__(self, obj): - st = _state(obj) + st = obj._sa_state return st.session is self def _sync(self, obj): @@ -877,16 +846,16 @@ def _sync(self, obj): for key in m.relationships: rel = m.relationships[key] rel._setup() - v = obj.__dict__.get(key) + v = _peek(obj, rel.idx) if v is None: continue if rel.direction == _MANYTOONE and not isinstance(v, InstrumentedList): - obj.__dict__[_attr_key(m, rel.local)] = v.__dict__.get(_attr_key(rel.target.__sa_mapper__, rel.remote)) + obj._sa_v[_attr_idx(m, rel.local)] = _peek(v, _attr_idx(rel.target.__sa_mapper__, rel.remote)) elif rel.direction == _ONETOMANY and isinstance(v, InstrumentedList): - pk = obj.__dict__.get(_attr_key(m, rel.local)) + pk = _peek(obj, _attr_idx(m, rel.local)) tm = rel.target.__sa_mapper__ for child in v._items: - child.__dict__[_attr_key(tm, rel.remote)] = pk + child._sa_v[_attr_idx(tm, rel.remote)] = pk def _is_deleted(self, obj): return any(o is obj for o in self._deleted) @@ -896,7 +865,7 @@ def flush(self, objects=None): self._orphans = [] for x, prop in orphans: other = prop._other() - if other is not None and x.__dict__.get(other.key) is not None: + if other is not None and _peek(x, other.idx) is not None: continue self.delete(x) for obj in list(self._identity.values()): @@ -941,13 +910,13 @@ def flush(self, objects=None): rel._setup() if rel.direction == _MANYTOMANY: conn.execute(rel.secondary.delete().where( - rel.sec_local == obj.__dict__.get(_attr_key(m, rel.local)))) + rel.sec_local == _peek(obj, _attr_idx(m, rel.local)))) for t in reversed(m.tables): conn.execute(t.delete().where(*self._pk_where(m, t, obj))) key = (m.identity_class, m._identity(obj)) if key in self._identity: del self._identity[key] - _state(obj).persistent = False + obj._sa_state.persistent = False self._tx_deleted.append(obj) def _sync_m2m(self, conn, obj, done): @@ -957,10 +926,10 @@ def _sync_m2m(self, conn, obj, done): rel._setup() if rel.direction != _MANYTOMANY: continue - lst = obj.__dict__.get(key) + lst = obj._sa_v[rel.idx] if not isinstance(lst, InstrumentedList): continue - mine = obj.__dict__.get(_attr_key(m, rel.local)) + mine = _peek(obj, _attr_idx(m, rel.local)) for x in lst._items: if not any(x is y for y in lst._db): self._assoc(conn, rel, mine, x, True, done) @@ -970,7 +939,7 @@ def _sync_m2m(self, conn, obj, done): lst._db = list(lst._items) def _assoc(self, conn, rel, mine, other, add, done): - theirs = other.__dict__.get(_attr_key(rel.target.__sa_mapper__, rel.remote)) + theirs = _peek(other, _attr_idx(rel.target.__sa_mapper__, rel.remote)) pair = sorted([(rel.sec_local.name, mine), (rel.sec_remote.name, theirs)]) sig = (rel.secondary.name, add, pair[0], pair[1]) if sig in done: @@ -982,48 +951,49 @@ def _assoc(self, conn, rel, mine, other, add, done): conn.execute(rel.secondary.delete().where(rel.sec_local == mine, rel.sec_remote == theirs)) def _pk_where(self, m, t, obj): - st = _state(obj) - d = obj.__dict__ + st = obj._sa_state if t is m.tables[0]: - return [c == st.snapshot.get(k, d.get(k)) for k, c in m.pk] + return [c == st.snapshot.get(i, _peek(obj, i)) for k, c, i in m.pk] out = [] for sub, par in m.inherit_cols: if sub.table is t: - k = _attr_key(m, par) - out.append(sub == st.snapshot.get(k, d.get(k))) + i = _attr_idx(m, par) + out.append(sub == st.snapshot.get(i, _peek(obj, i))) return out def _insert(self, conn, obj): m = type(obj).__sa_mapper__ - st = _state(obj) - d = obj.__dict__ + st = obj._sa_state + sv = obj._sa_v if m.polymorphic_on is not None and m.polymorphic_identity is not None: - dk = _attr_key(m, m.polymorphic_on) - if d.get(dk) is None: - d[dk] = m.polymorphic_identity + dk = _attr_idx(m, m.polymorphic_on) + if _peek(obj, dk) is None: + sv[dk] = m.polymorphic_identity for t in m.tables: values = {} - for k, c in m.attrs: + for k, c, i in m.attrs: if c.table is not t: continue - v = d.get(k) + present = sv[i] is not _UNSET + v = sv[i] if present else None if v is None and c.default is not None: v = c._default_value() - d[k] = v - if v is not None or k in d: + sv[i] = v + present = True + if present: values[c.key] = v for sub, par in m.inherit_cols: if sub.table is t: - values[sub.key] = d.get(_attr_key(m, par)) + values[sub.key] = _peek(obj, _attr_idx(m, par)) res = conn.execute(t.insert().values(values)) if t is m.tables[0]: - for k, c in m.pk: - if d.get(k) is None: - d[k] = res.lastrowid - for k, c in m.attrs: - if k not in d: - d[k] = None - st.snapshot[k] = d[k] + for k, c, i in m.pk: + if _peek(obj, i) is None: + sv[i] = res.lastrowid + for k, c, i in m.attrs: + if sv[i] is _UNSET: + sv[i] = None + st.snapshot[i] = sv[i] st.persistent = True st.session = self self._identity[(m.identity_class, m._identity(obj))] = obj @@ -1031,23 +1001,23 @@ def _insert(self, conn, obj): def _update(self, conn, obj): m = type(obj).__sa_mapper__ - st = _state(obj) - d = obj.__dict__ + st = obj._sa_state + sv = obj._sa_v changed = [] - for k, c in m.attrs: - if k in d and (k not in st.snapshot or st.snapshot[k] != d[k]): - changed.append((k, c)) + for k, c, i in m.attrs: + if sv[i] is not _UNSET and (i not in st.snapshot or st.snapshot[i] != sv[i]): + changed.append((c, i)) if not changed: return for t in m.tables: ch = {} - for k, c in changed: + for c, i in changed: if c.table is t: - ch[c.key] = d[k] + ch[c.key] = sv[i] if ch: conn.execute(t.update().where(*self._pk_where(m, t, obj)).values(ch)) - for k, c in changed: - st.snapshot[k] = d[k] + for c, i in changed: + st.snapshot[i] = sv[i] def commit(self): self.flush() @@ -1066,19 +1036,19 @@ def rollback(self): key = (m.identity_class, m._identity(obj)) if self._identity.get(key) is obj: del self._identity[key] - st = _state(obj) + st = obj._sa_state st.persistent = False st.session = None - for k, c in m.pk: + for k, c, i in m.pk: if c.autoincrement and isinstance(c.type, Integer): - obj.__dict__[k] = None + obj._sa_v[i] = None for obj in self._tx_deleted: - st = _state(obj) + st = obj._sa_state st.persistent = True m = type(obj).__sa_mapper__ self._identity[(m.identity_class, m._identity(obj))] = obj for obj in self._new: - _state(obj).session = None + obj._sa_state.session = None self._new = [] self._deleted = [] self._orphans = [] @@ -1092,16 +1062,14 @@ def expire_all(self): def expire(self, obj, attribute_names=None): m = type(obj).__sa_mapper__ - d = obj.__dict__ - pk = [k for k, c in m.pk] - for k, c in m.attrs: + sv = obj._sa_v + pk = [k for k, c, i in m.pk] + for k, c, i in m.attrs: if k not in pk and (attribute_names is None or k in attribute_names): - if k in d: - del d[k] + sv[i] = _UNSET for k in m.relationships: if attribute_names is None or k in attribute_names: - if k in d: - del d[k] + sv[m.relationships[k].idx] = _UNSET def refresh(self, obj, attribute_names=None): self.expire(obj, attribute_names) @@ -1109,24 +1077,24 @@ def refresh(self, obj, attribute_names=None): def _load_expired(self, obj): m = type(obj).__sa_mapper__ - st = _state(obj) - where = [c == st.snapshot.get(k, obj.__dict__.get(k)) for k, c in m.pk] + st = obj._sa_state + where = [c == st.snapshot.get(i, _peek(obj, i)) for k, c, i in m.pk] stmt = select(*m.columns).select_from(m.local_from).where(*where) row = stmt._execute_on(self.connection(), None).first() if row is None: raise exc.InvalidRequestError("Instance has been deleted, or its row is otherwise not present.") - d = obj.__dict__ - for i in range(len(m.attrs)): - k = m.attrs[i][0] - d[k] = row[i] - st.snapshot[k] = row[i] + sv = obj._sa_v + for j in range(len(m.attrs)): + i = m.attrs[j][2] + sv[i] = row[j] + st.snapshot[i] = row[j] def _lazy_load(self, obj, rel): m = type(obj).__sa_mapper__ tm = rel.target.__sa_mapper__ if rel.direction == _MANYTOMANY: lst = InstrumentedList(obj, rel) - pk = getattr(obj, _attr_key(m, rel.local)) + pk = _get(obj, _attr_idx(m, rel.local)) stmt = select(rel.target).select_from(tm.local_from, rel.secondary).where( rel.sec_local == pk, rel.remote == rel.sec_remote) if rel.order_by is not None: @@ -1137,7 +1105,7 @@ def _lazy_load(self, obj, rel): return lst if rel.direction == _ONETOMANY: lst = InstrumentedList(obj, rel) - pk = getattr(obj, _attr_key(m, rel.local)) + pk = _get(obj, _attr_idx(m, rel.local)) stmt = select(rel.target).where(rel.remote == pk) if rel.order_by is not None: stmt = stmt.order_by(rel.order_by) @@ -1146,7 +1114,7 @@ def _lazy_load(self, obj, rel): if rel.uselist: return lst return lst._items[0] if lst._items else None - fk = getattr(obj, _attr_key(m, rel.local)) + fk = _get(obj, _attr_idx(m, rel.local)) if fk is None: return None key = (tm.identity_class, (fk,)) @@ -1198,17 +1166,17 @@ def _eager_load(self, objs, rel): rel._setup() todo = [] for o in objs: - if o is not None and rel.key not in o.__dict__ and not any(o is x for x in todo): + if o is not None and o._sa_v[rel.idx] is _UNSET and not any(o is x for x in todo): todo.append(o) if not todo: return tm = rel.target.__sa_mapper__ if rel.direction == _MANYTOMANY: for o in todo: - o.__dict__[rel.key] = self._lazy_load(o, rel) + o._sa_v[rel.idx] = self._lazy_load(o, rel) return - rk = _attr_key(tm, rel.remote) - keys = [o.__dict__.get(_attr_key(type(o).__sa_mapper__, rel.local)) for o in todo] + rk = _attr_idx(tm, rel.remote) + keys = [_peek(o, _attr_idx(type(o).__sa_mapper__, rel.local)) for o in todo] wanted = [] for k in keys: if k is not None and k not in wanted: @@ -1219,7 +1187,7 @@ def _eager_load(self, objs, rel): if rel.direction == _ONETOMANY and rel.order_by is not None: stmt = stmt.order_by(rel.order_by) for x in stmt._execute_on(self.connection(), None, self).scalars(): - k = x.__dict__.get(rk) + k = _peek(x, rk) if k not in groups: groups[k] = [] groups[k].append(x) @@ -1229,9 +1197,9 @@ def _eager_load(self, objs, rel): if rel.direction == _ONETOMANY: lst = InstrumentedList(o, rel) lst._items = list(found) - o.__dict__[rel.key] = lst if rel.uselist else (found[0] if found else None) + o._sa_v[rel.idx] = lst if rel.uselist else (found[0] if found else None) else: - o.__dict__[rel.key] = found[0] if found else None + o._sa_v[rel.idx] = found[0] if found else None # -- queries def _autoflush(self): @@ -1251,7 +1219,7 @@ def scalar(self, statement, params=None, **kw): def get(self, entity, ident, **kw): m = entity.__sa_mapper__ if isinstance(ident, dict): - ident = tuple(ident[k] for k, c in m.pk) + ident = tuple(ident[k] for k, c, i in m.pk) if not isinstance(ident, tuple): ident = (ident,) obj = self._identity.get((m.identity_class, ident)) @@ -1282,20 +1250,25 @@ def deleted(self): def dirty(self): out = [] for obj in self._identity.values(): - st = _state(obj) + st = obj._sa_state m = type(obj).__sa_mapper__ - for k, c in m.attrs: - if k in obj.__dict__ and k in st.snapshot and st.snapshot[k] != obj.__dict__[k]: + for k, c, i in m.attrs: + if obj._sa_v[i] is not _UNSET and i in st.snapshot and st.snapshot[i] != obj._sa_v[i]: out.append(obj) break return out -def _attr_key(mapper, col): - for k, c in mapper.attrs: +def _attr_idx(mapper, col): + """The slot of ``col`` in ``mapper``'s instances; a joined-inheritance subclass's own + copy of an inherited key (its primary key) shares the inherited slot.""" + for k, c, i in mapper.attrs: if c is col: - return k - return col.key + return i + for k, c, i in mapper.attrs: + if k == col.key: + return i + raise exc.InvalidRequestError("Column %s is not mapped by %s" % (col.key, mapper.class_.__name__)) class sessionmaker: @@ -1313,4 +1286,4 @@ def begin(self): def registry(): - return {} + raise exc.InvalidRequestError("registry() is not supported; derive the base from DeclarativeBase") diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/site/starlette/datastructures.py b/maven/python-transpiler/src/main/resources/com/codename1/python/site/starlette/datastructures.py index 4c2fd96b569..7d37a5543ab 100644 --- a/maven/python-transpiler/src/main/resources/com/codename1/python/site/starlette/datastructures.py +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/site/starlette/datastructures.py @@ -228,17 +228,14 @@ def __hash__(self): class State: + # An attribute stored on a state is an ordinary instance attribute; the + # mapping it was made with answers the names never stored. Binding + # __setattr__ to route stores into the mapping gave the class no layout. def __init__(self, state=None): - self.__dict__["_state"] = dict(state or {}) - - def __setattr__(self, key, value): - self._state[key] = value + self._state = dict(state or {}) def __getattr__(self, key): try: - return self.__dict__["_state"][key] + return self._state[key] except KeyError: raise AttributeError("'State' object has no attribute '%s'" % key) - - def __delattr__(self, key): - del self._state[key] diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/site/typing_extensions/__init__.py b/maven/python-transpiler/src/main/resources/com/codename1/python/site/typing_extensions/__init__.py index f4eba8764ed..152ecbe228e 100644 --- a/maven/python-transpiler/src/main/resources/com/codename1/python/site/typing_extensions/__init__.py +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/site/typing_extensions/__init__.py @@ -98,3 +98,26 @@ def get_annotations(obj, globals=None, locals=None, eval_str=False): CapsuleType = object NoDefault = object() NoExtraItems = object() + + +class sentinel: + """A unique object with a readable repr (PEP 661): undefined = sentinel("undefined").""" + + def __init__(self, name, repr=None): + self._name = name + self._repr = repr if repr is not None else "<" + name + ">" + + def __repr__(self): + return self._repr + + def __reduce__(self): + return self._name + + def __or__(self, other): + return Union[self, other] + + def __ror__(self, other): + return Union[other, self] + + +Sentinel = sentinel diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/site/yaml/__init__.py b/maven/python-transpiler/src/main/resources/com/codename1/python/site/yaml/__init__.py index 7f15d00aa1f..e51435b4e96 100644 --- a/maven/python-transpiler/src/main/resources/com/codename1/python/site/yaml/__init__.py +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/site/yaml/__init__.py @@ -1,6 +1,26 @@ -# Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. -# Licensed under the GNU General Public License version 2 with the Classpath -# exception, as the rest of the Codename One Python runtime. +# Copyright (c) 2017-2021 Ingy döt Net +# Copyright (c) 2006-2016 Kirill Simonov +# +# Permission is hereby granted, free of charge, to any person obtaining a copy of +# this software and associated documentation files (the "Software"), to deal in +# the Software without restriction, including without limitation the rights to +# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +# of the Software, and to permit persons to whom the Software is furnished to do +# so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. +# +# Derived from PyYAML's lib/yaml. Changes: combined into one module and rewritten +# for the Codename One Python runtime. """YAML 1.1 loading and dumping with the interface of the PyYAML package. This is an independent implementation written from the YAML 1.1 specification @@ -1803,21 +1823,20 @@ def add_implicit_resolver(cls, tag, regexp, first): def _std_constructors(): - c = _LoaderCore return { - "tag:yaml.org,2002:null": c.construct_yaml_null, - "tag:yaml.org,2002:bool": c.construct_yaml_bool, - "tag:yaml.org,2002:int": c.construct_yaml_int, - "tag:yaml.org,2002:float": c.construct_yaml_float, - "tag:yaml.org,2002:binary": c.construct_yaml_binary, - "tag:yaml.org,2002:timestamp": c.construct_yaml_timestamp, - "tag:yaml.org,2002:omap": c.construct_yaml_omap, - "tag:yaml.org,2002:pairs": c.construct_yaml_pairs, - "tag:yaml.org,2002:set": c.construct_yaml_set, - "tag:yaml.org,2002:str": c.construct_yaml_str, - "tag:yaml.org,2002:seq": c.construct_yaml_seq, - "tag:yaml.org,2002:map": c.construct_yaml_map, - None: c.construct_undefined, + "tag:yaml.org,2002:null": _LoaderCore.construct_yaml_null, + "tag:yaml.org,2002:bool": _LoaderCore.construct_yaml_bool, + "tag:yaml.org,2002:int": _LoaderCore.construct_yaml_int, + "tag:yaml.org,2002:float": _LoaderCore.construct_yaml_float, + "tag:yaml.org,2002:binary": _LoaderCore.construct_yaml_binary, + "tag:yaml.org,2002:timestamp": _LoaderCore.construct_yaml_timestamp, + "tag:yaml.org,2002:omap": _LoaderCore.construct_yaml_omap, + "tag:yaml.org,2002:pairs": _LoaderCore.construct_yaml_pairs, + "tag:yaml.org,2002:set": _LoaderCore.construct_yaml_set, + "tag:yaml.org,2002:str": _LoaderCore.construct_yaml_str, + "tag:yaml.org,2002:seq": _LoaderCore.construct_yaml_seq, + "tag:yaml.org,2002:map": _LoaderCore.construct_yaml_map, + None: _LoaderCore.construct_undefined, } @@ -2887,21 +2906,20 @@ def _write_plain(self, text, split=True): def _std_representers(full): - c = _DumperCore table = { - type(None): c.represent_none, - str: c.represent_str, - bytes: c.represent_binary, - bool: c.represent_bool, - int: c.represent_int, - float: c.represent_float, - list: c.represent_list, - tuple: c.represent_tuple if full else c.represent_list, - dict: c.represent_dict, - set: c.represent_set, - datetime.date: c.represent_date, - datetime.datetime: c.represent_datetime, - None: c.represent_undefined, + type(None): _DumperCore.represent_none, + str: _DumperCore.represent_str, + bytes: _DumperCore.represent_binary, + bool: _DumperCore.represent_bool, + int: _DumperCore.represent_int, + float: _DumperCore.represent_float, + list: _DumperCore.represent_list, + tuple: _DumperCore.represent_tuple if full else _DumperCore.represent_list, + dict: _DumperCore.represent_dict, + set: _DumperCore.represent_set, + datetime.date: _DumperCore.represent_date, + datetime.datetime: _DumperCore.represent_datetime, + None: _DumperCore.represent_undefined, } return table @@ -3022,45 +3040,73 @@ def warnings(settings=None): # Submodule-style namespaces, so that yaml.constructor.ConstructorError and -# friends resolve as they do in PyYAML. -error = _NS() -error.YAMLError = YAMLError -error.MarkedYAMLError = MarkedYAMLError -error.Mark = Mark -reader = _NS() -reader.ReaderError = ReaderError -scanner = _NS() -scanner.ScannerError = ScannerError -parser = _NS() -parser.ParserError = ParserError -composer = _NS() -composer.ComposerError = ComposerError -constructor = _NS() -constructor.ConstructorError = ConstructorError -constructor.SafeConstructor = SafeLoader -constructor.FullConstructor = FullLoader -constructor.Constructor = Loader -representer = _NS() -representer.RepresenterError = RepresenterError -representer.SafeRepresenter = SafeDumper -representer.Representer = Dumper -emitter = _NS() -emitter.EmitterError = EmitterError -serializer = _NS() -serializer.SerializerError = SerializerError -nodes = _NS() -nodes.Node = Node -nodes.ScalarNode = ScalarNode -nodes.CollectionNode = CollectionNode -nodes.SequenceNode = SequenceNode -nodes.MappingNode = MappingNode -loader = _NS() -loader.Loader = Loader -loader.SafeLoader = SafeLoader -loader.FullLoader = FullLoader -loader.BaseLoader = BaseLoader -loader.UnsafeLoader = UnsafeLoader -dumper = _NS() -dumper.Dumper = Dumper -dumper.SafeDumper = SafeDumper -dumper.BaseDumper = BaseDumper +# friends resolve as they do in PyYAML. Each is a class whose body binds its +# names: `loader.SafeLoader = SafeLoader` stored on an instance was an +# attribute store named SafeLoader, which the build must take as one that may +# rebind the global -- and a global that may be rebound is no base a class of +# another module can be laid out over (`class MyLoader(yaml.SafeLoader)`). +class error: + YAMLError = YAMLError + MarkedYAMLError = MarkedYAMLError + Mark = Mark + + +class reader: + ReaderError = ReaderError + + +class scanner: + ScannerError = ScannerError + + +class parser: + ParserError = ParserError + + +class composer: + ComposerError = ComposerError + + +class constructor: + ConstructorError = ConstructorError + SafeConstructor = SafeLoader + FullConstructor = FullLoader + Constructor = Loader + + +class representer: + RepresenterError = RepresenterError + SafeRepresenter = SafeDumper + Representer = Dumper + + +class emitter: + EmitterError = EmitterError + + +class serializer: + SerializerError = SerializerError + + +class nodes: + Node = Node + ScalarNode = ScalarNode + CollectionNode = CollectionNode + SequenceNode = SequenceNode + MappingNode = MappingNode + + +class loader: + Loader = Loader + SafeLoader = SafeLoader + FullLoader = FullLoader + BaseLoader = BaseLoader + UnsafeLoader = UnsafeLoader + + +class dumper: + Dumper = Dumper + SafeDumper = SafeDumper + BaseDumper = BaseDumper + + diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/_interpqueues.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/_interpqueues.py new file mode 100644 index 00000000000..e34a80a78b0 --- /dev/null +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/_interpqueues.py @@ -0,0 +1,41 @@ +# Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. +# Licensed under the GNU General Public License version 2 with the Classpath +# exception, as the rest of the Codename One Python runtime. +"""_interpqueues: the queues between subinterpreters, which a translated +program cannot start (see _interpreters); creating one raises QueueError.""" + + +class QueueError(RuntimeError): + pass + + +class QueueNotFoundError(QueueError): + pass + + +class QueueEmpty(QueueError): + pass + + +class QueueFull(QueueError): + pass + + +def create(maxsize, unboundop=0, fallback=0): + raise QueueError("interpreter queues are not available in a translated program") + + +def destroy(qid): + raise QueueNotFoundError(qid) + + +def get(qid): + raise QueueNotFoundError(qid) + + +def put(qid, obj, unboundop=0, fallback=0): + raise QueueNotFoundError(qid) + + +def list_all(): + return [] diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/_interpreters.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/_interpreters.py new file mode 100644 index 00000000000..ac5b8315493 --- /dev/null +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/_interpreters.py @@ -0,0 +1,59 @@ +# Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. +# Licensed under the GNU General Public License version 2 with the Classpath +# exception, as the rest of the Codename One Python runtime. +"""_interpreters: subinterpreters (PEP 734). A translated program is one +compiled image with no interpreter to start a second copy of, so create() +raises InterpreterError; libraries that offer an interpreter pool import +and fall back to threads.""" + + +class InterpreterError(Exception): + pass + + +class InterpreterNotFoundError(InterpreterError): + pass + + +class NotShareableError(ValueError): + pass + + +def _unavailable(): + raise InterpreterError("subinterpreters are not available in a translated program") + + +def create(config=None, *, reqrefs=False): + _unavailable() + + +def destroy(id, *, restrict=False): + raise InterpreterNotFoundError(id) + + +def list_all(*, require_ready=False): + return [] + + +def get_current(): + return (0, 0) + + +def get_main(): + return (0, 0) + + +def set___main___attrs(id, updates, *, restrict=False): + raise InterpreterNotFoundError(id) + + +def exec(id, code, shared=None, *, restrict=False): + raise InterpreterNotFoundError(id) + + +def call(id, callable, args=None, kwargs=None, *, preserve_exc=False, restrict=False): + raise InterpreterNotFoundError(id) + + +def is_shareable(obj): + return obj is None or isinstance(obj, (bool, int, float, str, bytes)) diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/_markupbase.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/_markupbase.py new file mode 100644 index 00000000000..861a56793f3 --- /dev/null +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/_markupbase.py @@ -0,0 +1,41 @@ +# Copyright (c) 2001 Python Software Foundation; All Rights Reserved +# Licensed under the Python Software Foundation License Version 2; the full +# text is in maven/python-transpiler/third-party/cpython/LICENSE.txt. +# +# Derived from CPython's Lib/_markupbase.py. Changes: rewritten for the Codename One +# Python runtime, trimmed to what the transpiler supports and reorganised; +# the C accelerators and platform-specific branches are left out. +"""_markupbase: the position bookkeeping html.parser.HTMLParser builds on.""" + + +class ParserBase: + """Line and column tracking for a parser over self.rawdata.""" + + def __init__(self): + if self.__class__ is ParserBase: + raise RuntimeError("_markupbase.ParserBase must be subclassed") + + def reset(self): + self.lineno = 1 + self.offset = 0 + + def getpos(self): + return self.lineno, self.offset + + def updatepos(self, i, j): + if i >= j: + return j + rawdata = self.rawdata + nlines = rawdata.count("\n", i, j) + if nlines: + self.lineno = self.lineno + nlines + pos = rawdata.rindex("\n", i, j) + self.offset = j - (pos + 1) + else: + self.offset = self.offset + j - i + return j + + _decl_otherchars = "" + + def error(self, message): + raise NotImplementedError("subclasses of ParserBase must override error()") diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/abc.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/abc.py index 0556e9cdc1c..fa8f6033240 100644 --- a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/abc.py +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/abc.py @@ -3,66 +3,21 @@ # exception, as the rest of the Codename One Python runtime. """Abstract base classes.""" +# ABCMeta is the runtime's own metaclass (runtime class Abc), as CPython's +# is C code in _abc: a class it governs is compiled with a layout, its +# __abstractmethods__ are computed once when the class is made, constructing +# it with any left raises TypeError, and isinstance/issubclass consult +# __subclasshook__, register() and the subclasses' registries. A metaclass +# written here in Python would leave every abstract class without a layout +# and read the abstract names with a computed getattr. +from _cn1op import ABCMeta + def abstractmethod(funcobj): funcobj.__isabstractmethod__ = True return funcobj -def _is_abstract(value): - if isinstance(value, (classmethod, staticmethod)): - value = value.__func__ - elif isinstance(value, property): - return any(getattr(f, "__isabstractmethod__", False) for f in (value.fget, value.fset, value.fdel)) - return getattr(value, "__isabstractmethod__", False) - - -class ABCMeta(type): - def __new__(mcls, name, bases, namespace, **kwargs): - cls = super().__new__(mcls, name, bases, namespace, **kwargs) - abstracts = {n for n, v in namespace.items() if _is_abstract(v)} - for base in bases: - for n in getattr(base, "__abstractmethods__", ()): - if _is_abstract(getattr(cls, n, None)): - abstracts.add(n) - cls.__abstractmethods__ = frozenset(abstracts) - cls._abc_registry = [] - return cls - - def __call__(cls, *args, **kwargs): - missing = cls.__abstractmethods__ - if missing: - names = sorted(missing) - raise TypeError("Can't instantiate abstract class %s without an implementation for abstract method%s %s" - % (cls.__name__, "s" if len(names) > 1 else "", ", ".join("'" + n + "'" for n in names))) - return super().__call__(*args, **kwargs) - - def register(cls, subclass): - if not cls.__subclasscheck__(subclass): - cls._abc_registry.append(subclass) - return subclass - - def __instancecheck__(cls, instance): - return cls.__subclasscheck__(type(instance)) - - def __subclasscheck__(cls, subclass): - if cls in subclass.__mro__: - return True - hook = getattr(cls, "__subclasshook__", None) - if hook is not None: - ok = hook(subclass) - if ok is not NotImplemented: - return bool(ok) - for k in subclass.__mro__: - for r in cls._abc_registry: - if k is r or issubclass(k, r): - return True - for sub in cls.__subclasses__() if hasattr(cls, "__subclasses__") else (): - if issubclass(subclass, sub): - return True - return False - - class ABC(metaclass=ABCMeta): __slots__ = () diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/argparse.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/argparse.py index 734fa6a087b..087d946f1c5 100644 --- a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/argparse.py +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/argparse.py @@ -75,9 +75,14 @@ def _colorize(message, file, prog, headings): class Namespace: """Holds the parsed values as attributes.""" - def __init__(self, **kwargs): - for name in kwargs: - setattr(self, name, kwargs[name]) + def __init__(self, _cn1_init=(), **kwargs): + # Namespace(a=1) arrives as _cn1_init=((store_a, 1),), each store + # naming its attribute literally (ArgparseLowering). + if kwargs: + raise TypeError("argparse.Namespace: keyword names must be literal at the call so " + "the transpiler can write their stores") + for store, value in _cn1_init: + store(self, value) def __repr__(self): parts = [] @@ -497,6 +502,32 @@ def _default_metavar_for_positional(self, action): # ---------------------------------------------------------------- actions +def _cn1_need(action): + acc = action._cn1_acc + if acc is None: + # The build refuses such an argument on any parser that may parse + # (codegen.ArgparseLowering); only one it saw used for help alone + # keeps it, and that one is never stored. + raise TypeError("argparse: the destination %r is not a literal the build could see; " + "pass literal option strings (or dest=\"name\") to add_argument so the " + "transpiler can write its store" % (action.dest,)) + return acc + + +def _store(action, namespace, value): + _cn1_need(action)[0](namespace, value) + + +def _load(action, namespace, default): + return _cn1_need(action)[1](namespace, default) + + +def _has(action, namespace): + # A dest with no accessor was never stored: only _store writes one. + acc = action._cn1_acc + return acc is not None and acc[2](namespace) + + class Action: """What an argument does when it is seen. Subclass it and implement __call__(self, parser, namespace, values, option_string=None).""" @@ -514,6 +545,9 @@ def __init__(self, option_strings, dest, nargs=None, const=None, default=None, t self.help = help self.metavar = metavar self.deprecated = deprecated + # (store, load, has) over the literal dest, written at the + # add_argument call site by the transpiler (ArgparseLowering). + self._cn1_acc = None def _get_subactions(self): return [] @@ -540,7 +574,7 @@ def __init__(self, option_strings, dest, default=None, required=False, help=None def __call__(self, parser, namespace, values, option_string=None): if option_string in self.option_strings: - setattr(namespace, self.dest, not option_string.startswith("--no-")) + _store(self, namespace, not option_string.startswith("--no-")) def format_usage(self): return " | ".join(self.option_strings) @@ -558,7 +592,7 @@ def __init__(self, option_strings, dest, nargs=None, const=None, default=None, t required, help, metavar, deprecated) def __call__(self, parser, namespace, values, option_string=None): - setattr(namespace, self.dest, values) + _store(self, namespace, values) class _StoreConstAction(Action): @@ -568,7 +602,7 @@ def __init__(self, option_strings, dest, const=None, default=None, required=Fals help, metavar, deprecated) def __call__(self, parser, namespace, values, option_string=None): - setattr(namespace, self.dest, self.const) + _store(self, namespace, self.const) class _StoreTrueAction(_StoreConstAction): @@ -604,9 +638,9 @@ def __init__(self, option_strings, dest, nargs=None, const=None, default=None, t required, help, metavar, deprecated) def __call__(self, parser, namespace, values, option_string=None): - items = _copy_items(getattr(namespace, self.dest, None)) + items = _copy_items(_load(self, namespace, None)) items.append(values) - setattr(namespace, self.dest, items) + _store(self, namespace, items) class _AppendConstAction(Action): @@ -616,9 +650,9 @@ def __init__(self, option_strings, dest, const=None, default=None, required=Fals help, metavar, deprecated) def __call__(self, parser, namespace, values, option_string=None): - items = _copy_items(getattr(namespace, self.dest, None)) + items = _copy_items(_load(self, namespace, None)) items.append(self.const) - setattr(namespace, self.dest, items) + _store(self, namespace, items) class _CountAction(Action): @@ -628,17 +662,17 @@ def __init__(self, option_strings, dest, default=None, required=False, help=None help, None, deprecated) def __call__(self, parser, namespace, values, option_string=None): - count = getattr(namespace, self.dest, None) + count = _load(self, namespace, None) if count is None: count = 0 - setattr(namespace, self.dest, count + 1) + _store(self, namespace, count + 1) class _ExtendAction(_AppendAction): def __call__(self, parser, namespace, values, option_string=None): - items = _copy_items(getattr(namespace, self.dest, None)) + items = _copy_items(_load(self, namespace, None)) items.extend(values) - setattr(namespace, self.dest, items) + _store(self, namespace, items) class _HelpAction(Action): @@ -717,7 +751,7 @@ def __call__(self, parser, namespace, values, option_string=None): parser_name = values[0] arg_strings = values[1:] if self.dest is not SUPPRESS: - setattr(namespace, self.dest, parser_name) + _store(self, namespace, parser_name) if parser_name not in self._name_parser_map: choices = ", ".join(self._name_parser_map) raise ArgumentError(self, "unknown parser %r (choices: %s)" % (parser_name, choices)) @@ -725,12 +759,19 @@ def __call__(self, parser, namespace, values, option_string=None): if parser_name in self._deprecated: parser._warning("command '%s' is deprecated" % parser_name) subnamespace, arg_strings = sub.parse_known_args(arg_strings, None) - for key, value in subnamespace.__dict__.items(): - setattr(namespace, key, value) + # Every value the subparser set, copied through each one's own + # literal accessor (never by name). + for sub_action in sub._actions: + acc = sub_action._cn1_acc + if sub_action.dest is not SUPPRESS and acc is not None and acc[2](subnamespace): + acc[0](namespace, acc[1](subnamespace, None)) + for name, acc in sub._cn1_dacc.items(): + if acc[2](subnamespace): + acc[0](namespace, acc[1](subnamespace, None)) if arg_strings: - if _UNRECOGNIZED_ARGS_ATTR not in namespace.__dict__: - setattr(namespace, _UNRECOGNIZED_ARGS_ATTR, []) - getattr(namespace, _UNRECOGNIZED_ARGS_ATTR).extend(arg_strings) + if not hasattr(namespace, "_unrecognized_args"): + namespace._unrecognized_args = [] + namespace._unrecognized_args.extend(arg_strings) class FileType: @@ -773,6 +814,7 @@ def add_argument(self, *args, **kwargs): """add_argument(dest, ..., name=value, ...) or add_argument(option_string, option_string, ..., name=value, ...)""" chars = self._parser_ref().prefix_chars + acc = kwargs.pop("_cn1_acc", None) if not args or len(args) == 1 and args[0] and args[0][0] not in chars: if args and "dest" in kwargs: raise TypeError("dest supplied twice for positional argument, did you mean metavar?") @@ -794,6 +836,7 @@ def add_argument(self, *args, **kwargs): if not callable(action_class): raise ValueError("unknown action %r" % (action_class,)) action = action_class(**kwargs) + action._cn1_acc = acc type_func = action.type if type_func is not None and not callable(type_func): raise TypeError("%r is not callable" % (type_func,)) @@ -850,7 +893,13 @@ def add_mutually_exclusive_group(self, required=False): def set_defaults(self, **kwargs): parser = self._parser_ref() + accs = kwargs.pop("_cn1_accs", None) + if kwargs and (accs is None or len(accs) != len(kwargs)): + raise TypeError("argparse: set_defaults needs literal keyword names the build can see " + "(no **mapping) so the transpiler can write their stores") parser._defaults.update(kwargs) + for name, acc in accs or (): + parser._cn1_dacc[name] = acc for action in parser._actions: if action.dest in kwargs: action.default = kwargs[action.dest] @@ -930,6 +979,7 @@ def __init__(self, prog=None, usage=None, description=None, epilog=None, parents self._action_groups = [] self._mutually_exclusive_groups = [] self._defaults = {} + self._cn1_dacc = {} self._has_negative_number_optionals = [] self._subparsers = None self._positionals = self.add_argument_group("positional arguments") @@ -941,6 +991,7 @@ def __init__(self, prog=None, usage=None, description=None, epilog=None, parents for parent in parents: self._add_container_actions(parent) self._defaults.update(parent._defaults) + self._cn1_dacc.update(parent._cn1_dacc) def _parser_ref(self): return self @@ -1020,7 +1071,9 @@ def add_subparsers(self, **kwargs): formatter.add_usage(None, positionals, self._mutually_exclusive_groups, "") kwargs["prog"] = formatter.format_help().strip() action_class = kwargs.pop("action", _SubParsersAction) + acc = kwargs.pop("_cn1_acc", None) action = action_class(option_strings=[], **kwargs) + action._cn1_acc = acc self._subparsers._add_action(action) return action @@ -1041,11 +1094,11 @@ def parse_known_args(self, args=None, namespace=None): namespace = Namespace() for action in self._actions: if action.dest is not SUPPRESS and action.default is not SUPPRESS: - if not hasattr(namespace, action.dest): - setattr(namespace, action.dest, action.default) - for dest in self._defaults: - if not hasattr(namespace, dest): - setattr(namespace, dest, self._defaults[dest]) + if not _has(action, namespace): + _store(action, namespace, action.default) + for dest, acc in self._cn1_dacc.items(): + if not acc[2](namespace): + acc[0](namespace, self._defaults[dest]) if self.exit_on_error: try: namespace, args = self._parse_known_args(args, namespace) @@ -1053,9 +1106,9 @@ def parse_known_args(self, args=None, namespace=None): self.error(str(err)) else: namespace, args = self._parse_known_args(args, namespace) - if _UNRECOGNIZED_ARGS_ATTR in namespace.__dict__: - args.extend(getattr(namespace, _UNRECOGNIZED_ARGS_ATTR)) - delattr(namespace, _UNRECOGNIZED_ARGS_ATTR) + if hasattr(namespace, "_unrecognized_args"): + args.extend(namespace._unrecognized_args) + del namespace._unrecognized_args return namespace, args def _parse_known_args(self, arg_strings, namespace): @@ -1191,9 +1244,9 @@ def consume_positionals(start_index): if action.required: required.append(_action_name(action)) elif (action.default is not None and isinstance(action.default, str) - and hasattr(namespace, action.dest) - and action.default is getattr(namespace, action.dest)): - setattr(namespace, action.dest, self._get_value(action, action.default)) + and _has(action, namespace) + and action.default is _load(action, namespace, None)): + _store(action, namespace, self._get_value(action, action.default)) if required: raise ArgumentError(None, "the following arguments are required: %s" % ", ".join(required)) diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/array.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/array.py new file mode 100644 index 00000000000..38d5f4dd63c --- /dev/null +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/array.py @@ -0,0 +1,309 @@ +# Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. +# Licensed under the GNU General Public License version 2 with the Classpath +# exception, as the rest of the Codename One Python runtime. +"""array: typed arrays of numbers, stored as a list and checked against +their type code on every store. The byte layout of tobytes/frombytes is the +machine's native one, little-endian on every Codename One target.""" + +import struct as _struct + +typecodes = "bBuhHiIlLqQfd" + +_SIZES = {"b": 1, "B": 1, "u": 4, "w": 4, "h": 2, "H": 2, "i": 4, "I": 4, "l": 8, "L": 8, "q": 8, "Q": 8, + "f": 4, "d": 8} +_FMT = {"b": "b", "B": "B", "h": "h", "H": "H", "i": "i", "I": "I", "l": "q", "L": "Q", "q": "q", "Q": "Q", + "f": "f", "d": "d"} + +__all__ = ["array", "ArrayType", "typecodes"] + + +class array: + __slots__ = ("_tc", "_a") + + def __new__(cls, typecode, initializer=None): + if not isinstance(typecode, str) or len(typecode) != 1: + raise TypeError("array() argument 1 must be a unicode character, not %s" % type(typecode).__name__) + if typecode not in _SIZES: + raise ValueError("bad typecode (must be b, B, u, w, h, H, i, I, l, L, q, Q, f or d)") + self = object.__new__(cls) + self._tc = typecode + self._a = [] + if initializer is not None: + if isinstance(initializer, (bytes, bytearray)): + self.frombytes(initializer) + elif isinstance(initializer, str): + if typecode not in "uw": + raise TypeError("cannot use a str to initialize an array with typecode '%s'" % typecode) + self._a.extend(initializer) + elif isinstance(initializer, array) and initializer._tc in "uw" and typecode not in "uw": + raise TypeError("cannot use a unicode array to initialize an array with typecode '%s'" % typecode) + else: + self.extend(initializer) + return self + + def __init__(self, *args, **kwargs): + pass + + @property + def typecode(self): + return self._tc + + @property + def itemsize(self): + return _SIZES[self._tc] + + def _check(self, v): + tc = self._tc + if tc in "uw": + if not isinstance(v, str) or len(v) != 1: + raise TypeError("array item must be a unicode character, not %s" % type(v).__name__) + return v + if tc in "fd": + if not isinstance(v, (int, float)): + raise TypeError("must be real number, not %s" % type(v).__name__) + v = float(v) + if tc == "f": + v = _struct.unpack(" hi: + if tc in "bB": + raise OverflowError("%s is %s than %s" % ( + "signed char" if tc == "b" else "unsigned byte integer", "less" if v < lo else "greater", + "minimum" if v < lo else "maximum")) + raise OverflowError("%s %s is %s than %s" % ( + "signed" if tc in "bhilq" else "unsigned", + {"h": "short integer", "H": "short integer", "i": "integer", "I": "integer", + "l": "integer", "L": "integer", "q": "integer", "Q": "integer"}[tc], + "less" if v < lo else "greater", "minimum" if v < lo else "maximum")) + return v + + def __len__(self): + return len(self._a) + + def __iter__(self): + return iter(self._a) + + def __reversed__(self): + return reversed(self._a) + + def __contains__(self, v): + return v in self._a + + def __getitem__(self, i): + if isinstance(i, slice): + r = array(self._tc) + r._a = self._a[i] + return r + return self._a[i] + + def __setitem__(self, i, v): + if isinstance(i, slice): + if not isinstance(v, array): + raise TypeError("can only assign array (not \"%s\") to array slice" % type(v).__name__) + if v._tc != self._tc: + raise TypeError("bad argument type for built-in operation") + self._a[i] = list(v._a) + else: + self._a[i] = self._check(v) + + def __delitem__(self, i): + del self._a[i] + + def __eq__(self, other): + if not isinstance(other, array): + return NotImplemented + return self._a == other._a + + def __ne__(self, other): + if not isinstance(other, array): + return NotImplemented + return self._a != other._a + + def __lt__(self, other): + if not isinstance(other, array): + return NotImplemented + return self._a < other._a + + def __le__(self, other): + if not isinstance(other, array): + return NotImplemented + return self._a <= other._a + + def __gt__(self, other): + if not isinstance(other, array): + return NotImplemented + return self._a > other._a + + def __ge__(self, other): + if not isinstance(other, array): + return NotImplemented + return self._a >= other._a + + __hash__ = None + + def __add__(self, other): + if not isinstance(other, array): + raise TypeError("can only append array (not \"%s\") to array" % type(other).__name__) + if other._tc != self._tc: + raise TypeError("bad argument type for built-in operation") + r = array(self._tc) + r._a = self._a + other._a + return r + + def __iadd__(self, other): + if not isinstance(other, array): + raise TypeError("can only extend array with array (not \"%s\")" % type(other).__name__) + self.extend(other) + return self + + def __mul__(self, n): + r = array(self._tc) + r._a = self._a * n + return r + + __rmul__ = __mul__ + + def __imul__(self, n): + self._a *= n + return self + + def __copy__(self): + return array(self._tc, self) + + def __deepcopy__(self, memo): + return array(self._tc, self) + + def __reduce_ex__(self, protocol): + return (array, (self._tc, list(self._a))) + + def __repr__(self): + name = type(self).__name__ + if not self._a: + return "%s('%s')" % (name, self._tc) + if self._tc in "uw": + return "%s('%s', %r)" % (name, self._tc, "".join(self._a)) + return "%s('%s', %r)" % (name, self._tc, self._a) + + def __bytes__(self): + return self.tobytes() + + def append(self, v): + self._a.append(self._check(v)) + + def extend(self, it): + if isinstance(it, array): + if it._tc != self._tc: + raise TypeError("can only extend with array of same kind") + self._a.extend(it._a) + return + for v in it: + self._a.append(self._check(v)) + + def insert(self, i, v): + self._a.insert(i, self._check(v)) + + def pop(self, i=-1): + if not self._a: + raise IndexError("pop from empty array") + return self._a.pop(i) + + def remove(self, v): + try: + self._a.remove(v) + except ValueError: + raise ValueError("array.remove(x): x not in array") from None + + def index(self, v, start=0, stop=None): + a = self._a + n = len(a) + if stop is None or stop > n: + stop = n + for i in range(start if start >= 0 else max(0, n + start), stop if stop >= 0 else n + stop): + if a[i] == v: + return i + raise ValueError("array.index(x): x not in array") + + def count(self, v): + return self._a.count(v) + + def reverse(self): + self._a.reverse() + + def buffer_info(self): + return (id(self), len(self._a)) + + def byteswap(self): + if self._tc in "uw": + data = self.tobytes() + sz = 4 + else: + data = self.tobytes() + sz = _SIZES[self._tc] + out = bytearray() + for k in range(0, len(data), sz): + out += data[k:k + sz][::-1] + self._a = [] + self.frombytes(bytes(out)) + + def tobytes(self): + tc = self._tc + if tc in "uw": + return "".join(self._a).encode("utf-32-le") if self._a else b"" + if not self._a: + return b"" + return _struct.pack("<%d%s" % (len(self._a), _FMT[tc]), *self._a) + + def frombytes(self, b): + b = bytes(b) + sz = _SIZES[self._tc] + if len(b) % sz: + raise ValueError("bytes length not a multiple of item size") + if self._tc in "uw": + self._a.extend(b.decode("utf-32-le")) + return + n = len(b) // sz + if n: + self._a.extend(_struct.unpack("<%d%s" % (n, _FMT[self._tc]), b)) + + def tolist(self): + return list(self._a) + + def fromlist(self, lst): + if not isinstance(lst, list): + raise TypeError("arg must be list") + vals = [self._check(v) for v in lst] + self._a.extend(vals) + + def tounicode(self): + if self._tc not in "uw": + raise ValueError("tounicode() may only be called on unicode type arrays ('u' or 'w')") + return "".join(self._a) + + def fromunicode(self, s): + if self._tc not in "uw": + raise ValueError("fromunicode() may only be called on unicode type arrays ('u' or 'w')") + self._a.extend(s) + + def tofile(self, f): + f.write(self.tobytes()) + + def fromfile(self, f, n): + sz = _SIZES[self._tc] + data = f.read(n * sz) + if len(data) < n * sz: + self.frombytes(data[:len(data) - len(data) % sz]) + raise EOFError("read() didn't return enough bytes") + self.frombytes(data) + + +ArrayType = array diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/ast.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/ast.py new file mode 100644 index 00000000000..36e314ad345 --- /dev/null +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/ast.py @@ -0,0 +1,133 @@ +# Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. +# Licensed under the GNU General Public License version 2 with the Classpath +# exception, as the rest of the Codename One Python runtime. +"""The node classes of Python's syntax tree, without a parser. + +A translated program carries no Python parser: the source was parsed when the +application was built. parse() therefore raises SyntaxError, which is what a +caller that sniffs whether some text is Python (puremagic's scanner) already +treats as "it is not"; the node classes exist so that isinstance checks and +annotations that name them still work. +""" + + +class AST: + _fields = () + _attributes = ("lineno", "col_offset", "end_lineno", "end_col_offset") + + def __init__(self, *args, **kwargs): + for name, value in zip(self._fields, args): + setattr(self, name, value) + for name, value in kwargs.items(): + setattr(self, name, value) + + +def _node(name, fields=(), base=AST): + return type(name, (base,), {"_fields": fields}) + + +mod = _node("mod") +stmt = _node("stmt") +expr = _node("expr") +expr_context = _node("expr_context") +Module = _node("Module", ("body", "type_ignores"), mod) +Expression = _node("Expression", ("body",), mod) +Interactive = _node("Interactive", ("body",), mod) +FunctionDef = _node("FunctionDef", ("name", "args", "body", "decorator_list", "returns"), stmt) +AsyncFunctionDef = _node("AsyncFunctionDef", ("name", "args", "body", "decorator_list", "returns"), stmt) +ClassDef = _node("ClassDef", ("name", "bases", "keywords", "body", "decorator_list"), stmt) +Return = _node("Return", ("value",), stmt) +Delete = _node("Delete", ("targets",), stmt) +Assign = _node("Assign", ("targets", "value"), stmt) +AugAssign = _node("AugAssign", ("target", "op", "value"), stmt) +AnnAssign = _node("AnnAssign", ("target", "annotation", "value", "simple"), stmt) +For = _node("For", ("target", "iter", "body", "orelse"), stmt) +AsyncFor = _node("AsyncFor", ("target", "iter", "body", "orelse"), stmt) +While = _node("While", ("test", "body", "orelse"), stmt) +If = _node("If", ("test", "body", "orelse"), stmt) +With = _node("With", ("items", "body"), stmt) +AsyncWith = _node("AsyncWith", ("items", "body"), stmt) +Match = _node("Match", ("subject", "cases"), stmt) +Raise = _node("Raise", ("exc", "cause"), stmt) +Try = _node("Try", ("body", "handlers", "orelse", "finalbody"), stmt) +TryStar = _node("TryStar", ("body", "handlers", "orelse", "finalbody"), stmt) +Assert = _node("Assert", ("test", "msg"), stmt) +Import = _node("Import", ("names",), stmt) +ImportFrom = _node("ImportFrom", ("module", "names", "level"), stmt) +Global = _node("Global", ("names",), stmt) +Nonlocal = _node("Nonlocal", ("names",), stmt) +Expr = _node("Expr", ("value",), stmt) +Pass = _node("Pass", (), stmt) +Break = _node("Break", (), stmt) +Continue = _node("Continue", (), stmt) +BoolOp = _node("BoolOp", ("op", "values"), expr) +NamedExpr = _node("NamedExpr", ("target", "value"), expr) +BinOp = _node("BinOp", ("left", "op", "right"), expr) +UnaryOp = _node("UnaryOp", ("op", "operand"), expr) +Lambda = _node("Lambda", ("args", "body"), expr) +IfExp = _node("IfExp", ("test", "body", "orelse"), expr) +Dict = _node("Dict", ("keys", "values"), expr) +Set = _node("Set", ("elts",), expr) +ListComp = _node("ListComp", ("elt", "generators"), expr) +SetComp = _node("SetComp", ("elt", "generators"), expr) +DictComp = _node("DictComp", ("key", "value", "generators"), expr) +GeneratorExp = _node("GeneratorExp", ("elt", "generators"), expr) +Await = _node("Await", ("value",), expr) +Yield = _node("Yield", ("value",), expr) +YieldFrom = _node("YieldFrom", ("value",), expr) +Compare = _node("Compare", ("left", "ops", "comparators"), expr) +Call = _node("Call", ("func", "args", "keywords"), expr) +FormattedValue = _node("FormattedValue", ("value", "conversion", "format_spec"), expr) +JoinedStr = _node("JoinedStr", ("values",), expr) +Constant = _node("Constant", ("value", "kind"), expr) +Attribute = _node("Attribute", ("value", "attr", "ctx"), expr) +Subscript = _node("Subscript", ("value", "slice", "ctx"), expr) +Starred = _node("Starred", ("value", "ctx"), expr) +Name = _node("Name", ("id", "ctx"), expr) +List = _node("List", ("elts", "ctx"), expr) +Tuple = _node("Tuple", ("elts", "ctx"), expr) +Slice = _node("Slice", ("lower", "upper", "step"), expr) +Load = _node("Load", (), expr_context) +Store = _node("Store", (), expr_context) +Del = _node("Del", (), expr_context) +arguments = _node("arguments", ("posonlyargs", "args", "vararg", "kwonlyargs", "kw_defaults", "kwarg", + "defaults")) +arg = _node("arg", ("arg", "annotation")) +keyword = _node("keyword", ("arg", "value")) +alias = _node("alias", ("name", "asname")) + + +def parse(source, filename="", mode="exec", **kwargs): + raise SyntaxError("ast.parse is not available in a translated program: the source it would parse was not" + " compiled with the application") + + +def iter_fields(node): + for field in node._fields: + try: + yield field, getattr(node, field) + except AttributeError: + pass + + +def iter_child_nodes(node): + for name, field in iter_fields(node): + if isinstance(field, AST): + yield field + elif isinstance(field, list): + for item in field: + if isinstance(item, AST): + yield item + + +def walk(node): + from collections import deque + todo = deque([node]) + while todo: + node = todo.popleft() + todo.extend(iter_child_nodes(node)) + yield node + + +def literal_eval(node_or_string): + raise ValueError("ast.literal_eval is not available in a translated program") diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/asyncio.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/asyncio/__init__.py similarity index 73% rename from maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/asyncio.py rename to maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/asyncio/__init__.py index c1d4fa40f01..75e9de3c6f2 100644 --- a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/asyncio.py +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/asyncio/__init__.py @@ -7,8 +7,10 @@ There is no selector: a loop with nothing ready sleeps until its next timer, or until another thread hands it work through ``call_soon_threadsafe`` / ``run_coroutine_threadsafe``. Each thread has its -own running loop. Networking, subprocesses and executors are not part of -this module. +own running loop. ``to_thread`` and +``loop.run_in_executor`` run a function on another thread and resume the +awaiting coroutine on the loop when it returns. Networking and subprocesses +are not part of this module. """ import _thread @@ -21,9 +23,21 @@ "Task", "TimeoutError", "all_tasks", "as_completed", "create_task", "current_task", "ensure_future", "gather", "get_event_loop", "get_running_loop", "iscoroutine", "iscoroutinefunction", "new_event_loop", "run", "set_event_loop", "shield", "sleep", "wait", "wait_for", "FIRST_COMPLETED", "FIRST_EXCEPTION", - "ALL_COMPLETED", "timeout", "run_coroutine_threadsafe", + "ALL_COMPLETED", "timeout", "run_coroutine_threadsafe", "to_thread", "Runner", + "AbstractEventLoopPolicy", "DefaultEventLoopPolicy", "get_event_loop_policy", "set_event_loop_policy", + "eager_task_factory", "create_eager_task_factory", "future_add_to_awaited_by", + "future_discard_from_awaited_by", "BaseProtocol", "BaseTransport", "BufferedProtocol", + "DatagramProtocol", "DatagramTransport", "IncompleteReadError", "LimitOverrunError", "Protocol", + "ReadTransport", "StreamReader", "StreamWriter", "SubprocessProtocol", "SubprocessTransport", + "Transport", "WriteTransport", "create_subprocess_exec", "create_subprocess_shell", ] +from asyncio._transports import ( # noqa: E402 + BaseProtocol, BaseTransport, BufferedProtocol, DatagramProtocol, DatagramTransport, + IncompleteReadError, LimitOverrunError, Protocol, ReadTransport, StreamReader, StreamWriter, + SubprocessProtocol, SubprocessTransport, Transport, WriteTransport, +) + FIRST_COMPLETED = "FIRST_COMPLETED" FIRST_EXCEPTION = "FIRST_EXCEPTION" ALL_COMPLETED = "ALL_COMPLETED" @@ -65,6 +79,7 @@ def iscoroutinefunction(func): # ---- futures -------------------------------------------------------------- class Future: + __class_getitem__ = classmethod(type(list[int])) _asyncio_future_blocking = False def __init__(self, *, loop=None): @@ -125,13 +140,15 @@ def set_exception(self, exception): self._schedule_callbacks() def add_done_callback(self, fn, *, context=None): + # (callback, context) pairs, as CPython keeps them: anyio reads + # _callbacks to find the task run_until_complete is waiting for. if self._state != _PENDING: - self._loop.call_soon(fn, self) + self._loop.call_soon(fn, self, context=context) else: - self._callbacks.append(fn) + self._callbacks.append((fn, context)) def remove_done_callback(self, fn): - kept = [f for f in self._callbacks if f != fn] + kept = [f for f in self._callbacks if f[0] != fn] removed = len(self._callbacks) - len(kept) self._callbacks = kept return removed @@ -139,8 +156,8 @@ def remove_done_callback(self, fn): def _schedule_callbacks(self): callbacks = self._callbacks self._callbacks = [] - for fn in callbacks: - self._loop.call_soon(fn, self) + for fn, context in callbacks: + self._loop.call_soon(fn, self, context=context) def _make_cancelled_error(self): if self._cancel_message is None: @@ -173,6 +190,7 @@ def __await__(self): class Task(Future): + __class_getitem__ = classmethod(type(list[int])) _counter = 0 def __init__(self, coro, *, loop=None, name=None, context=None): @@ -182,6 +200,7 @@ def __init__(self, coro, *, loop=None, name=None, context=None): self._coro = coro self._fut_waiter = None self._must_cancel = False + self._num_cancels_requested = 0 Task._counter += 1 self._name = name if name is not None else "Task-" + str(Task._counter) self._loop.call_soon(self._step) @@ -196,9 +215,23 @@ def set_name(self, value): def get_coro(self): return self._coro + def cancelling(self): + """The cancellations requested and not yet uncancelled (3.11).""" + return self._num_cancels_requested + + def uncancel(self): + """Withdraws one cancellation request, as a structured-concurrency + scope does when the cancellation it caused is handled (3.11).""" + if self._num_cancels_requested > 0: + self._num_cancels_requested -= 1 + if self._num_cancels_requested == 0: + self._must_cancel = False + return self._num_cancels_requested + def cancel(self, msg=None): if self.done(): return False + self._num_cancels_requested += 1 if self._fut_waiter is not None: if self._fut_waiter.cancel(msg): return True @@ -267,10 +300,11 @@ def __repr__(self): # ---- the loop ------------------------------------------------------------- class Handle: - def __init__(self, callback, args, loop): + def __init__(self, callback, args, loop, context=None): self._callback = callback self._args = args self._loop = loop + self._context = context self._cancelled = False def cancel(self): @@ -280,12 +314,15 @@ def cancelled(self): return self._cancelled def _run(self): - self._callback(*self._args) + if self._context is None: + self._callback(*self._args) + else: + self._context.run(self._callback, *self._args) class TimerHandle(Handle): - def __init__(self, when, callback, args, loop): - Handle.__init__(self, callback, args, loop) + def __init__(self, when, callback, args, loop, context=None): + Handle.__init__(self, callback, args, loop, context) self._when = when def when(self): @@ -296,6 +333,16 @@ class AbstractEventLoop: pass +def _run_until_complete_cb(fut): + """The callback run_until_complete adds, as CPython names it in + asyncio.base_events: anyio recognises a loop's own future by it.""" + if not fut.cancelled(): + exc = fut.exception() + if isinstance(exc, (SystemExit, KeyboardInterrupt)): + return + fut.get_loop().stop() + + class BaseEventLoop(AbstractEventLoop): def __init__(self): self._ready = [] @@ -312,12 +359,12 @@ def time(self): return _time.monotonic() def call_soon(self, callback, *args, context=None): - h = Handle(callback, args, self) + h = Handle(callback, args, self, context) self._ready.append(h) return h def call_soon_threadsafe(self, callback, *args, context=None): - h = Handle(callback, args, self) + h = Handle(callback, args, self, context) self._inbox().put(h) return h @@ -330,20 +377,64 @@ def _inbox(self): return q def call_later(self, delay, callback, *args, context=None): - return self.call_at(self.time() + delay, callback, *args) + return self.call_at(self.time() + delay, callback, *args, context=context) def call_at(self, when, callback, *args, context=None): - h = TimerHandle(when, callback, args, self) + h = TimerHandle(when, callback, args, self, context) self._seq += 1 _heappush(self._scheduled, (when, self._seq, h)) return h + def run_in_executor(self, executor, func, *args): + """Runs func(*args) on another thread -- the executor's, when one is + given, otherwise a new thread -- and answers a future of the loop + that completes with its result.""" + fut = self.create_future() + # The inbox is made here, on the loop's thread, before the work can + # post to it: made lazily by the worker, it raced the loop, which + # read no inbox, had nothing to wait on and spun, and two threads + # could each make one and lose the result in the other. + self._inbox() + + def settle(ok, value): + if fut.cancelled(): + return + if ok: + fut.set_result(value) + else: + fut.set_exception(value) + + def work(): + try: + value = func(*args) + except BaseException as e: + self.call_soon_threadsafe(settle, False, e) + return + self.call_soon_threadsafe(settle, True, value) + if executor is not None: + executor.submit(work) + else: + _thread.start_new_thread(work, ()) + return fut + def create_future(self): return Future(loop=self) + _task_factory = None + def create_task(self, coro, *, name=None, context=None): + if self._task_factory is not None: + return self._task_factory(self, coro, name=name, context=context) return Task(coro, loop=self, name=name) + def set_task_factory(self, factory): + if factory is not None and not callable(factory): + raise TypeError("task factory must be a callable or None") + self._task_factory = factory + + def get_task_factory(self): + return self._task_factory + def is_running(self): return self._running @@ -386,11 +477,7 @@ def run_forever(self): def run_until_complete(self, future): future = ensure_future(future, loop=self) - - def done(f): - self.stop() - - future.add_done_callback(done) + future.add_done_callback(_run_until_complete_cb) self.run_forever() if not future.done(): raise RuntimeError("Event loop stopped before Future completed.") @@ -403,6 +490,11 @@ def _run_once(self): q = self._threadsafe if q is not None: self._drain(q, False, None) + if q is None and not self._ready and not scheduled and not self._stopping: + # Nothing to run and nothing to wait for but another thread: + # block on the inbox, as CPython blocks in select(), rather than + # spinning until call_soon_threadsafe posts. + q = self._inbox() if not self._ready and not self._stopping: if q is not None: if scheduled: @@ -468,7 +560,59 @@ def get_event_loop(): def new_event_loop(): - return BaseEventLoop() + return _policy.new_event_loop() + + +class AbstractEventLoopPolicy: + pass + + +class DefaultEventLoopPolicy(AbstractEventLoopPolicy): + """The one policy there is: a BaseEventLoop, and get_event_loop's.""" + + def get_event_loop(self): + return get_event_loop() + + def set_event_loop(self, loop): + set_event_loop(loop) + + def new_event_loop(self): + return BaseEventLoop() + + +_policy = DefaultEventLoopPolicy() + + +def get_event_loop_policy(): + return _policy + + +def set_event_loop_policy(policy): + global _policy + _policy = policy if policy is not None else DefaultEventLoopPolicy() + + +def eager_task_factory(loop, coro, *, name=None, context=None): + """Python 3.12's factory for tasks that start running before create_task + returns. Here the task starts on the loop's next turn, as every task + does: the result and the order of completion are the same, only the + first step runs later.""" + return Task(coro, loop=loop, name=name) + + +def create_eager_task_factory(custom_task_constructor): + def factory(loop, coro, *, name=None, context=None): + return custom_task_constructor(coro, loop=loop, name=name) + return factory + + +def future_add_to_awaited_by(fut, waiter): + """Python 3.14's record of which task awaits which, read only by + asyncio's call-graph introspection, which this runtime does not have.""" + + +def future_discard_from_awaited_by(fut, waiter): + """See future_add_to_awaited_by.""" def set_event_loop(loop): @@ -513,20 +657,76 @@ def run(main, *, debug=None): raise RuntimeError("asyncio.run() cannot be called from a running event loop") if not iscoroutine(main): raise ValueError("a coroutine was expected, got " + repr(main)) - loop = new_event_loop() - set_event_loop(loop) - try: - return loop.run_until_complete(main) - finally: + with Runner(debug=debug) as runner: + return runner.run(main) + + +def _cancel_pending(loop): + pending = [t for t in _all_tasks if t._loop is loop and not t.done()] + for t in pending: + t.cancel() + if pending: + loop.run_until_complete(gather(*pending, return_exceptions=True)) + + +class Runner: + """A loop kept across several run() calls, closed on leaving the + with block, as Python 3.11's asyncio.Runner: asyncio.run is one + Runner's single run. A context is accepted and not used: tasks here + run in the caller's context.""" + + def __init__(self, *, debug=None, loop_factory=None): + self._debug = debug + self._loop_factory = loop_factory + self._loop = None + self._closed = False + + def __enter__(self): + self._lazy_init() + return self + + def __exit__(self, exc_type, exc, tb): + self.close() + + def close(self): + if self._loop is None or self._closed: + self._closed = True + return + loop = self._loop try: - pending = [t for t in _all_tasks if t._loop is loop and not t.done()] - for t in pending: - t.cancel() - if pending: - loop.run_until_complete(gather(*pending, return_exceptions=True)) + _cancel_pending(loop) finally: - set_event_loop(None) + if self._loop_factory is None: + set_event_loop(None) loop.close() + self._loop = None + self._closed = True + + def get_loop(self): + self._lazy_init() + return self._loop + + def run(self, coro, *, context=None): + if _get_running() is not None: + raise RuntimeError("Runner.run() cannot be called from a running event loop") + self._lazy_init() + if not iscoroutine(coro): + if isinstance(coro, Future) or hasattr(coro, "__await__"): + coro = _wrap_awaitable(coro) + else: + raise TypeError("a coroutine was expected, got " + repr(coro)) + return self._loop.run_until_complete(coro) + + def _lazy_init(self): + if self._closed: + raise RuntimeError("Runner is closed") + if self._loop is not None: + return + if self._loop_factory is None: + self._loop = new_event_loop() + set_event_loop(self._loop) + else: + self._loop = self._loop_factory() async def sleep(delay, result=None): @@ -889,6 +1089,7 @@ def release(self): class Queue: + __class_getitem__ = classmethod(type(list[int])) def __init__(self, maxsize=0): self._maxsize = maxsize self._items = [] @@ -979,6 +1180,12 @@ async def join(self): await self._finished.wait() +async def to_thread(func, /, *args, **kwargs): + """Runs func(*args, **kwargs) on a separate thread and awaits its result.""" + loop = get_running_loop() + return await loop.run_in_executor(None, lambda: func(*args, **kwargs)) + + def run_coroutine_threadsafe(coro, loop): """Runs ``coro`` on ``loop`` from another thread; answers a concurrent future.""" if not iscoroutine(coro): @@ -1002,3 +1209,9 @@ def start(): loop.call_soon_threadsafe(start) return result + + +# Submodules imported as attributes of the package, as CPython's asyncio +# does: libraries write asyncio.subprocess.Process and asyncio.futures.Future. +from asyncio import base_events, futures, subprocess # noqa: E402,F401 +from asyncio.subprocess import create_subprocess_exec, create_subprocess_shell # noqa: E402,F401 diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/asyncio/_transports.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/asyncio/_transports.py new file mode 100644 index 00000000000..fe81f25d183 --- /dev/null +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/asyncio/_transports.py @@ -0,0 +1,364 @@ +# Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. +# Licensed under the GNU General Public License version 2 with the Classpath +# exception, as the rest of the Codename One Python runtime. +"""asyncio's protocol and transport interfaces, and the stream reader and +writer over them, as CPython defines them (asyncio.protocols, +asyncio.transports, asyncio.streams). + +The interfaces are what a library subclasses or annotates with. This +runtime's event loop opens no sockets of its own -- network I/O goes +through Codename One's networking, on threads -- so nothing here hands a +library a transport; a StreamReader fed by the caller works as it does +under CPython.""" + + +class BaseProtocol: + __slots__ = () + + def connection_made(self, transport): + pass + + def connection_lost(self, exc): + pass + + def pause_writing(self): + pass + + def resume_writing(self): + pass + + +class Protocol(BaseProtocol): + __slots__ = () + + def data_received(self, data): + pass + + def eof_received(self): + pass + + +class BufferedProtocol(BaseProtocol): + __slots__ = () + + def get_buffer(self, sizehint): + raise NotImplementedError + + def buffer_updated(self, nbytes): + raise NotImplementedError + + def eof_received(self): + pass + + +class DatagramProtocol(BaseProtocol): + __slots__ = () + + def datagram_received(self, data, addr): + pass + + def error_received(self, exc): + pass + + +class SubprocessProtocol(BaseProtocol): + __slots__ = () + + def pipe_data_received(self, fd, data): + pass + + def pipe_connection_lost(self, fd, exc): + pass + + def process_exited(self): + pass + + +class BaseTransport: + __slots__ = ("_extra",) + + def __init__(self, extra=None): + if extra is None: + extra = {} + self._extra = extra + + def get_extra_info(self, name, default=None): + return self._extra.get(name, default) + + def is_closing(self): + raise NotImplementedError + + def close(self): + raise NotImplementedError + + def set_protocol(self, protocol): + raise NotImplementedError + + def get_protocol(self): + raise NotImplementedError + + +class ReadTransport(BaseTransport): + __slots__ = () + + def is_reading(self): + raise NotImplementedError + + def pause_reading(self): + raise NotImplementedError + + def resume_reading(self): + raise NotImplementedError + + +class WriteTransport(BaseTransport): + __slots__ = () + + def set_write_buffer_limits(self, high=None, low=None): + raise NotImplementedError + + def get_write_buffer_size(self): + raise NotImplementedError + + def get_write_buffer_limits(self): + raise NotImplementedError + + def write(self, data): + raise NotImplementedError + + def writelines(self, list_of_data): + self.write(b"".join(list_of_data)) + + def write_eof(self): + raise NotImplementedError + + def can_write_eof(self): + raise NotImplementedError + + def abort(self): + raise NotImplementedError + + +class Transport(ReadTransport, WriteTransport): + __slots__ = () + + +class DatagramTransport(BaseTransport): + __slots__ = () + + def sendto(self, data, addr=None): + raise NotImplementedError + + def abort(self): + raise NotImplementedError + + +class SubprocessTransport(BaseTransport): + __slots__ = () + + def get_pid(self): + raise NotImplementedError + + def get_returncode(self): + raise NotImplementedError + + def get_pipe_transport(self, fd): + raise NotImplementedError + + def send_signal(self, signal): + raise NotImplementedError + + def terminate(self): + raise NotImplementedError + + def kill(self): + raise NotImplementedError + + +class IncompleteReadError(EOFError): + def __init__(self, partial, expected): + r_expected = "undefined" if expected is None else repr(expected) + super().__init__("%d bytes read on a total of %s expected bytes" % (len(partial), r_expected)) + self.partial = partial + self.expected = expected + + +class LimitOverrunError(Exception): + def __init__(self, message, consumed): + super().__init__(message) + self.consumed = consumed + + +_DEFAULT_LIMIT = 2 ** 16 + + +class StreamReader: + """Bytes fed by feed_data() and read by coroutines, as CPython's.""" + + def __init__(self, limit=_DEFAULT_LIMIT, loop=None): + if limit <= 0: + raise ValueError("Limit cannot be <= 0") + self._limit = limit + self._loop = loop + self._buffer = bytearray() + self._eof = False + self._waiter = None + self._exception = None + self._transport = None + + def exception(self): + return self._exception + + def set_exception(self, exc): + self._exception = exc + self._wake() + + def set_transport(self, transport): + self._transport = transport + + def _wake(self): + w = self._waiter + if w is not None: + self._waiter = None + if not w.done(): + w.set_result(None) + + def feed_eof(self): + self._eof = True + self._wake() + + def at_eof(self): + return self._eof and not self._buffer + + def feed_data(self, data): + if not data: + return + self._buffer.extend(data) + self._wake() + + async def _wait_for_data(self, func_name): + if self._waiter is not None: + raise RuntimeError("%s() called while another coroutine is already waiting for incoming data" + % func_name) + import asyncio + self._waiter = asyncio.get_running_loop().create_future() + try: + await self._waiter + finally: + self._waiter = None + + async def readline(self): + try: + return await self.readuntil(b"\n") + except IncompleteReadError as e: + return e.partial + + async def readuntil(self, separator=b"\n"): + if not separator: + raise ValueError("Separator should be at least one-byte string") + while True: + if self._exception is not None: + raise self._exception + i = self._buffer.find(separator) + if i >= 0: + end = i + len(separator) + if end > self._limit: + raise LimitOverrunError("Separator is found, but chunk is longer than limit", i) + chunk = bytes(self._buffer[:end]) + del self._buffer[:end] + return chunk + if len(self._buffer) > self._limit: + raise LimitOverrunError("Separator is not found, and chunk exceed the limit", + len(self._buffer)) + if self._eof: + chunk = bytes(self._buffer) + self._buffer.clear() + raise IncompleteReadError(chunk, None) + await self._wait_for_data("readuntil") + + async def read(self, n=-1): + if self._exception is not None: + raise self._exception + if n == 0: + return b"" + if n < 0: + while not self._eof: + await self._wait_for_data("read") + if self._exception is not None: + raise self._exception + data = bytes(self._buffer) + self._buffer.clear() + return data + while not self._buffer and not self._eof: + await self._wait_for_data("read") + if self._exception is not None: + raise self._exception + data = bytes(self._buffer[:n]) + del self._buffer[:n] + return data + + async def readexactly(self, n): + if n < 0: + raise ValueError("readexactly size can not be less than zero") + while len(self._buffer) < n: + if self._exception is not None: + raise self._exception + if self._eof: + incomplete = bytes(self._buffer) + self._buffer.clear() + raise IncompleteReadError(incomplete, n) + await self._wait_for_data("readexactly") + data = bytes(self._buffer[:n]) + del self._buffer[:n] + return data + + def __aiter__(self): + return self + + async def __anext__(self): + val = await self.readline() + if val == b"": + raise StopAsyncIteration + return val + + +class StreamWriter: + """Writes to a transport, as CPython's.""" + + def __init__(self, transport, protocol, reader, loop): + self._transport = transport + self._protocol = protocol + self._reader = reader + self._loop = loop + + @property + def transport(self): + return self._transport + + def write(self, data): + self._transport.write(data) + + def writelines(self, data): + self._transport.writelines(data) + + def write_eof(self): + return self._transport.write_eof() + + def can_write_eof(self): + return self._transport.can_write_eof() + + def close(self): + return self._transport.close() + + def is_closing(self): + return self._transport.is_closing() + + async def wait_closed(self): + pass + + def get_extra_info(self, name, default=None): + return self._transport.get_extra_info(name, default) + + async def drain(self): + if self._reader is not None and self._reader.exception() is not None: + raise self._reader.exception() diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/asyncio/base_events.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/asyncio/base_events.py new file mode 100644 index 00000000000..3b6f2e573bc --- /dev/null +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/asyncio/base_events.py @@ -0,0 +1,9 @@ +# Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. +# Licensed under the GNU General Public License version 2 with the Classpath +# exception, as the rest of the Codename One Python runtime. +"""asyncio.base_events: the names libraries import from it by that path. +The event loop itself is in asyncio.""" + +from asyncio import BaseEventLoop, _run_until_complete_cb # noqa: F401 + +__all__ = ["BaseEventLoop"] diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/asyncio/futures.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/asyncio/futures.py new file mode 100644 index 00000000000..f88513565f3 --- /dev/null +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/asyncio/futures.py @@ -0,0 +1,15 @@ +# Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. +# Licensed under the GNU General Public License version 2 with the Classpath +# exception, as the rest of the Codename One Python runtime. +"""asyncio.futures: the names libraries import from it by that path. +Futures themselves are in asyncio.""" + +from asyncio import CancelledError, Future, InvalidStateError, future_add_to_awaited_by # noqa: F401 +from asyncio import future_discard_from_awaited_by # noqa: F401 + + +def isfuture(obj): + return isinstance(obj, Future) + + +__all__ = ["CancelledError", "Future", "InvalidStateError", "isfuture"] diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/asyncio/subprocess.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/asyncio/subprocess.py new file mode 100644 index 00000000000..8da52915d0f --- /dev/null +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/asyncio/subprocess.py @@ -0,0 +1,83 @@ +# Copyright (c) 2001 Python Software Foundation; All Rights Reserved +# Licensed under the Python Software Foundation License Version 2; the full +# text is in maven/python-transpiler/third-party/cpython/LICENSE.txt. +# +# Derived from CPython's Lib/asyncio/subprocess.py. Changes: rewritten for the Codename One +# Python runtime, trimmed to what the transpiler supports and reorganised; +# the C accelerators and platform-specific branches are left out. +"""asyncio.subprocess: the API, over the same rule as subprocess. A mobile +application cannot start another program, so create_subprocess_exec and +create_subprocess_shell raise FileNotFoundError, as CPython does for a +command that is not installed. The classes are here for libraries that +subclass or annotate with them.""" + +from subprocess import DEVNULL, PIPE, STDOUT # noqa: F401 + +from asyncio._transports import Protocol, StreamReader, SubprocessProtocol + +__all__ = ["create_subprocess_exec", "create_subprocess_shell", "Process", "PIPE", "STDOUT", "DEVNULL"] + + +class SubprocessStreamProtocol(Protocol, SubprocessProtocol): + def __init__(self, limit, loop): + self._limit = limit + self._loop = loop + self.stdin = self.stdout = self.stderr = None + self._transport = None + + def connection_made(self, transport): + self._transport = transport + if transport.get_pipe_transport(1): + self.stdout = StreamReader(limit=self._limit, loop=self._loop) + if transport.get_pipe_transport(2): + self.stderr = StreamReader(limit=self._limit, loop=self._loop) + + def pipe_data_received(self, fd, data): + reader = self.stdout if fd == 1 else self.stderr if fd == 2 else None + if reader is not None: + reader.feed_data(data) + + def pipe_connection_lost(self, fd, exc): + reader = self.stdout if fd == 1 else self.stderr if fd == 2 else None + if reader is not None: + if exc is None: + reader.feed_eof() + else: + reader.set_exception(exc) + + +class Process: + def __init__(self, transport, protocol, loop): + self._transport = transport + self._protocol = protocol + self._loop = loop + self.stdin = protocol.stdin + self.stdout = protocol.stdout + self.stderr = protocol.stderr + self.pid = transport.get_pid() + + @property + def returncode(self): + return self._transport.get_returncode() + + def send_signal(self, signal): + self._transport.send_signal(signal) + + def terminate(self): + self._transport.terminate() + + def kill(self): + self._transport.kill() + + +def _no_process(program): + return FileNotFoundError(2, "No such file or directory: %r (an application cannot start programs)" + % (program,)) + + +async def create_subprocess_exec(program, *args, stdin=None, stdout=None, stderr=None, limit=2 ** 16, **kwds): + raise _no_process(program) + + +async def create_subprocess_shell(cmd, stdin=None, stdout=None, stderr=None, limit=2 ** 16, **kwds): + raise _no_process(cmd) diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/binascii.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/binascii.py index 6c2cb225fbe..598222762ba 100644 --- a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/binascii.py +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/binascii.py @@ -3,6 +3,8 @@ # exception, as the rest of the Codename One Python runtime. """Conversions between binary data and ASCII encodings.""" +import _cn1binascii + __all__ = ["Error", "Incomplete", "hexlify", "unhexlify", "b2a_hex", "a2b_hex", "b2a_base64", "a2b_base64", "crc32", "crc_hqx"] @@ -22,7 +24,6 @@ class Incomplete(Exception): _B64_REV = [-1] * 256 for _i in range(64): _B64_REV[_B64[_i]] = _i -_HEX = b"0123456789abcdef" def _bytes(data, name): @@ -67,31 +68,17 @@ def b2a_base64(data, *, newline=True): if isinstance(data, str): raise TypeError("a bytes-like object is required, not 'str'") data = _bytes(data, "data") - out = bytearray() - n = len(data) - i = 0 - t = _B64 - while i + 2 < n: - v = (data[i] << 16) | (data[i + 1] << 8) | data[i + 2] - out.append(t[v >> 18]) - out.append(t[(v >> 12) & 63]) - out.append(t[(v >> 6) & 63]) - out.append(t[v & 63]) - i += 3 - rest = n - i - if rest == 1: - v = data[i] << 16 - out += bytes((t[v >> 18], t[(v >> 12) & 63], 61, 61)) - elif rest == 2: - v = (data[i] << 16) | (data[i + 1] << 8) - out += bytes((t[v >> 18], t[(v >> 12) & 63], t[(v >> 6) & 63], 61)) - if newline: - out.append(10) - return bytes(out) + # In Java, as CPython runs it in C. + return _cn1binascii.b2a_base64(data, newline) def a2b_base64(data, *, strict_mode=False): data = _bytes(data, "data") + if not strict_mode: + # None when the input ends mid-quantum: the loop below reports it. + r = _cn1binascii.a2b_base64(data) + if r is not None: + return r out = bytearray() rev = _B64_REV acc = 0 @@ -137,28 +124,11 @@ def a2b_base64(data, *, strict_mode=False): return bytes(out) -_CRC_TABLE = [] -for _n in range(256): - _c = _n - for _k in range(8): - _c = (0xEDB88320 ^ (_c >> 1)) if _c & 1 else _c >> 1 - _CRC_TABLE.append(_c) - - def crc32(data, crc=0): data = _bytes(data, "data") - crc = ~crc & 0xFFFFFFFF - t = _CRC_TABLE - for b in data: - crc = t[(crc ^ b) & 0xFF] ^ (crc >> 8) - return ~crc & 0xFFFFFFFF + return _cn1binascii.crc32(data, crc) def crc_hqx(data, value): data = _bytes(data, "data") - crc = value & 0xFFFF - for b in data: - crc ^= b << 8 - for _ in range(8): - crc = ((crc << 1) ^ 0x1021) & 0xFFFF if crc & 0x8000 else (crc << 1) & 0xFFFF - return crc + return _cn1binascii.crc_hqx(data, value) diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/bisect.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/bisect.py index 163d15fe62c..3b530050c12 100644 --- a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/bisect.py +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/bisect.py @@ -4,43 +4,7 @@ """Bisection algorithms over sorted lists.""" -def bisect_left(a, x, lo=0, hi=None, *, key=None): - if lo < 0: - raise ValueError("lo must be non-negative") - if hi is None: - hi = len(a) - while lo < hi: - mid = (lo + hi) // 2 - v = a[mid] if key is None else key(a[mid]) - if v < x: - lo = mid + 1 - else: - hi = mid - return lo - - -def bisect_right(a, x, lo=0, hi=None, *, key=None): - if lo < 0: - raise ValueError("lo must be non-negative") - if hi is None: - hi = len(a) - while lo < hi: - mid = (lo + hi) // 2 - v = a[mid] if key is None else key(a[mid]) - if x < v: - hi = mid - else: - lo = mid + 1 - return lo - - -def insort_left(a, x, lo=0, hi=None, *, key=None): - a.insert(bisect_left(a, x if key is None else key(x), lo, hi, key=key), x) - - -def insort_right(a, x, lo=0, hi=None, *, key=None): - a.insert(bisect_right(a, x if key is None else key(x), lo, hi, key=key), x) - +from _cn1bisect import bisect_left, bisect_right, insort_left, insort_right bisect = bisect_right insort = insort_right diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/calendar.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/calendar.py new file mode 100644 index 00000000000..5785b5549b5 --- /dev/null +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/calendar.py @@ -0,0 +1,164 @@ +# Copyright (c) 2001 Python Software Foundation; All Rights Reserved +# Licensed under the Python Software Foundation License Version 2; the full +# text is in maven/python-transpiler/third-party/cpython/LICENSE.txt. +# +# Derived from CPython's Lib/calendar.py. Changes: rewritten for the Codename One +# Python runtime, trimmed to what the transpiler supports and reorganised; +# the C accelerators and platform-specific branches are left out. +"""calendar: leap years, month lengths, weekdays, timegm and month grids, +with English day and month names. The text and HTML calendars are not +provided.""" + +import datetime as _dt +import enum as _enum + + +class IllegalMonthError(ValueError): + def __init__(self, month): + self.month = month + + def __str__(self): + return "bad month number %r; must be 1-12" % (self.month,) + + +class IllegalWeekdayError(ValueError): + def __init__(self, weekday): + self.weekday = weekday + + def __str__(self): + return "bad weekday number %r; must be 0 (Monday) to 6 (Sunday)" % (self.weekday,) + + +class Day(_enum.IntEnum): + MONDAY = 0 + TUESDAY = 1 + WEDNESDAY = 2 + THURSDAY = 3 + FRIDAY = 4 + SATURDAY = 5 + SUNDAY = 6 + + +class Month(_enum.IntEnum): + JANUARY = 1 + FEBRUARY = 2 + MARCH = 3 + APRIL = 4 + MAY = 5 + JUNE = 6 + JULY = 7 + AUGUST = 8 + SEPTEMBER = 9 + OCTOBER = 10 + NOVEMBER = 11 + DECEMBER = 12 + + +MONDAY = Day.MONDAY +TUESDAY = Day.TUESDAY +WEDNESDAY = Day.WEDNESDAY +THURSDAY = Day.THURSDAY +FRIDAY = Day.FRIDAY +SATURDAY = Day.SATURDAY +SUNDAY = Day.SUNDAY +JANUARY = Month.JANUARY +FEBRUARY = Month.FEBRUARY + +mdays = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] +day_name = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] +day_abbr = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"] +month_name = ["", "January", "February", "March", "April", "May", "June", "July", "August", "September", + "October", "November", "December"] +month_abbr = ["", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] + +_firstweekday = 0 + + +def isleap(year): + return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0) + + +def leapdays(y1, y2): + y1 -= 1 + y2 -= 1 + return (y2 // 4 - y1 // 4) - (y2 // 100 - y1 // 100) + (y2 // 400 - y1 // 400) + + +def weekday(year, month, day): + if not 1 <= year <= 9999: + year = 2000 + year % 400 + return Day(_dt.date(year, month, day).weekday()) + + +def _monthlen(year, month): + return mdays[month] + (month == 2 and isleap(year)) + + +def monthrange(year, month): + if not 1 <= month <= 12: + raise IllegalMonthError(month) + return weekday(year, month, 1), _monthlen(year, month) + + +def timegm(tuple): + year, month, day, hour, minute, second = tuple[:6] + days = _dt.date(year, month, 1).toordinal() - _dt.date(1970, 1, 1).toordinal() + day - 1 + return ((days * 24 + hour) * 60 + minute) * 60 + second + + +def firstweekday(): + return _firstweekday + + +def setfirstweekday(firstweekday): + global _firstweekday + if not MONDAY <= firstweekday <= SUNDAY: + raise IllegalWeekdayError(firstweekday) + _firstweekday = firstweekday + + +class Calendar: + def __init__(self, firstweekday=0): + self.firstweekday = firstweekday + + def iterweekdays(self): + for i in range(self.firstweekday, self.firstweekday + 7): + yield i % 7 + + def itermonthdays3(self, year, month): + first = _dt.date(year, month, 1) + before = (first.weekday() - self.firstweekday) % 7 + start = first - _dt.timedelta(days=before) + n = _monthlen(year, month) + after = (self.firstweekday - (first.weekday() + n)) % 7 + for i in range(before + n + after): + d = start + _dt.timedelta(days=i) + yield d.year, d.month, d.day + + def itermonthdates(self, year, month): + for y, m, d in self.itermonthdays3(year, month): + yield _dt.date(y, m, d) + + def itermonthdays(self, year, month): + for y, m, d in self.itermonthdays3(year, month): + yield d if m == month else 0 + + def itermonthdays2(self, year, month): + for i, d in enumerate(self.itermonthdays(year, month), self.firstweekday): + yield d, i % 7 + + def monthdatescalendar(self, year, month): + dates = list(self.itermonthdates(year, month)) + return [dates[i:i + 7] for i in range(0, len(dates), 7)] + + def monthdayscalendar(self, year, month): + days = list(self.itermonthdays(year, month)) + return [days[i:i + 7] for i in range(0, len(days), 7)] + + def monthdays2calendar(self, year, month): + days = list(self.itermonthdays2(year, month)) + return [days[i:i + 7] for i in range(0, len(days), 7)] + + +def monthcalendar(year, month): + return Calendar(_firstweekday).monthdayscalendar(year, month) diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/codecs.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/codecs.py new file mode 100644 index 00000000000..897ade0e608 --- /dev/null +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/codecs.py @@ -0,0 +1,196 @@ +# Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. +# Licensed under the GNU General Public License version 2 with the Classpath +# exception, as the rest of the Codename One Python runtime. +"""The codec registry, over the encodings str.encode and bytes.decode know. + +The runtime supports UTF-8, ASCII and Latin-1 (and their aliases); lookup() +of anything else raises LookupError, as CPython does for an unknown name. +""" + +BOM_UTF8 = b"\xef\xbb\xbf" +BOM_UTF16_LE = BOM_LE = b"\xff\xfe" +BOM_UTF16_BE = BOM_BE = b"\xfe\xff" +BOM_UTF32_LE = b"\xff\xfe\x00\x00" +BOM_UTF32_BE = b"\x00\x00\xfe\xff" +BOM = BOM_UTF16_LE +BOM_UTF16 = BOM_UTF16_LE +BOM_UTF32 = BOM_UTF32_LE + +_ALIASES = { + "utf-8": "utf-8", "utf8": "utf-8", "u8": "utf-8", "utf": "utf-8", "cp65001": "utf-8", + "utf-8-sig": "utf-8-sig", "utf8-sig": "utf-8-sig", + "ascii": "ascii", "us-ascii": "ascii", "646": "ascii", "us": "ascii", + "latin-1": "iso8859-1", "latin1": "iso8859-1", "latin": "iso8859-1", "l1": "iso8859-1", + "iso-8859-1": "iso8859-1", "iso8859-1": "iso8859-1", "8859": "iso8859-1", "cp819": "iso8859-1", +} + + +def _canonical(encoding): + key = str(encoding).strip().lower().replace("_", "-").replace(" ", "-") + name = _ALIASES.get(key) + if name is None: + raise LookupError(f"unknown encoding: {encoding}") + return name + + +def _encode(input, errors="strict", name="utf-8"): + if name == "utf-8-sig": + return BOM_UTF8 + input.encode("utf-8", errors), len(input) + return input.encode(name, errors), len(input) + + +def _decode(input, errors="strict", name="utf-8"): + data = bytes(input) + if name == "utf-8-sig": + if data.startswith(BOM_UTF8): + data = data[3:] + return data.decode("utf-8", errors), len(input) + return data.decode(name, errors), len(input) + + +class IncrementalEncoder: + def __init__(self, errors="strict"): + self.errors = errors + + def encode(self, input, final=False): + return _encode(input, self.errors, self._name)[0] + + def reset(self): + pass + + def getstate(self): + return 0 + + def setstate(self, state): + pass + + +class IncrementalDecoder: + def __init__(self, errors="strict"): + self.errors = errors + self._buffer = b"" + + def decode(self, input, final=False): + data = self._buffer + bytes(input) + if self._name in ("utf-8", "utf-8-sig") and not final: + # Hold back an incomplete trailing sequence for the next call. + cut = len(data) + i = len(data) - 1 + while i >= 0 and i >= len(data) - 4 and (data[i] & 0xC0) == 0x80: + i -= 1 + if i >= 0 and data[i] >= 0xC0: + need = 2 if data[i] < 0xE0 else 3 if data[i] < 0xF0 else 4 + if len(data) - i < need: + cut = i + self._buffer = data[cut:] + data = data[:cut] + else: + self._buffer = b"" + if self._name == "utf-8-sig": + if not getattr(self, "_seen_bom", False) and len(data) >= 3: + self._seen_bom = True + if data.startswith(BOM_UTF8): + data = data[3:] + return data.decode("utf-8", self.errors) + return data.decode(self._name, self.errors) + + def reset(self): + self._buffer = b"" + + def getstate(self): + return (self._buffer, 0) + + def setstate(self, state): + self._buffer = state[0] + + +class CodecInfo(tuple): + def __new__(cls, encode, decode, streamreader=None, streamwriter=None, incrementalencoder=None, + incrementaldecoder=None, name=None): + self = tuple.__new__(cls, (encode, decode, streamreader, streamwriter)) + self.name = name + self.encode = encode + self.decode = decode + self.incrementalencoder = incrementalencoder + self.incrementaldecoder = incrementaldecoder + self.streamreader = streamreader + self.streamwriter = streamwriter + return self + + def __repr__(self): + return f"" + + +# One CodecInfo per encoding, as CPython's codec registry caches a lookup. +# Making one per call also made two classes per call, and every class made +# drops every attribute cache in the program. +_cache = {} + + +def lookup(encoding): + info = _cache.get(encoding) + if info is not None: + return info + name = _canonical(encoding) + info = _cache.get(name) + if info is None: + enc = type("IncrementalEncoder", (IncrementalEncoder,), {"_name": name}) + dec = type("IncrementalDecoder", (IncrementalDecoder,), {"_name": name}) + info = CodecInfo(lambda s, errors="strict": _encode(s, errors, name), + lambda b, errors="strict": _decode(b, errors, name), + incrementalencoder=enc, incrementaldecoder=dec, name=name) + _cache[name] = info + if isinstance(encoding, str): + _cache[encoding] = info + return info + + +def encode(obj, encoding="utf-8", errors="strict"): + return lookup(encoding).encode(obj, errors)[0] + + +def decode(obj, encoding="utf-8", errors="strict"): + return lookup(encoding).decode(obj, errors)[0] + + +def getencoder(encoding): + return lookup(encoding).encode + + +def getdecoder(encoding): + return lookup(encoding).decode + + +def getincrementalencoder(encoding): + return lookup(encoding).incrementalencoder + + +def getincrementaldecoder(encoding): + return lookup(encoding).incrementaldecoder + + +_ERRORS = {} + + +def register_error(name, handler): + _ERRORS[name] = handler + + +def lookup_error(name): + if name in _ERRORS: + return _ERRORS[name] + if name in ("strict", "ignore", "replace", "surrogateescape", "backslashreplace", "xmlcharrefreplace"): + return name + raise LookupError(f"unknown error handler name {name!r}") + + +def register(search_function): + pass + + +def utf_8_decode(data, errors="strict", final=False): + return bytes(data).decode("utf-8", errors), len(data) + + +def utf_8_encode(s, errors="strict"): + return s.encode("utf-8", errors), len(s) diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/collections/__init__.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/collections/__init__.py index e6dc5937644..eb8afe738f6 100644 --- a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/collections/__init__.py +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/collections/__init__.py @@ -6,12 +6,14 @@ from operator import itemgetter as _itemgetter from itertools import chain as _chain, repeat as _repeat, starmap as _starmap import heapq as _heapq +from _cn1collections import tuplegetter as _tuplegetter, nt_new as _nt_new, dd_init as _dd_init, dd_missing as _dd_missing __all__ = ["ChainMap", "Counter", "OrderedDict", "UserDict", "UserList", "UserString", "defaultdict", "deque", "namedtuple"] class deque: + __class_getitem__ = classmethod(type(list[int])) """A double-ended queue over a circular buffer.""" def __init__(self, iterable=(), maxlen=None): @@ -221,18 +223,10 @@ def __repr__(self): class defaultdict(dict): - def __init__(self, default_factory=None, *args, **kwargs): - if default_factory is not None and not callable(default_factory): - raise TypeError("first argument must be callable or None") - super().__init__(*args, **kwargs) - self.default_factory = default_factory - - def __missing__(self, key): - if self.default_factory is None: - raise KeyError(key) - value = self.default_factory() - self[key] = value - return value + __class_getitem__ = classmethod(type(list[int])) + # In Java, as CPython has them in C: see PyCollections. + __init__ = _dd_init + __missing__ = _dd_missing def copy(self): return defaultdict(self.default_factory, self) @@ -255,6 +249,7 @@ def __or__(self, other): class OrderedDict(dict): + __class_getitem__ = classmethod(type(list[int])) def move_to_end(self, key, last=True): value = self.pop(key) if last: @@ -302,6 +297,7 @@ def fromkeys(cls, iterable, value=None): class Counter(dict): + __class_getitem__ = classmethod(type(list[int])) def __init__(self, iterable=None, /, **kwds): super().__init__() self.update(iterable, **kwds) @@ -469,23 +465,9 @@ def namedtuple(typename, field_names, *, rename=False, defaults=None, module=Non field_defaults = dict(zip(field_names[len(field_names) - len(defaults):], defaults)) n = len(field_names) - def __new__(cls, *args, **kwargs): - if len(args) > n: - raise TypeError("%s.__new__() takes %d positional arguments but %d were given" % (typename, n + 1, len(args) + 1)) - values = list(args) - for name in field_names[len(args):]: - if name in kwargs: - values.append(kwargs.pop(name)) - elif name in field_defaults: - values.append(field_defaults[name]) - else: - raise TypeError("%s.__new__() missing 1 required positional argument: %r" % (typename, name)) - if kwargs: - name = next(iter(kwargs)) - if name in field_names: - raise TypeError("%s.__new__() got multiple values for argument %r" % (typename, name)) - raise TypeError("%s.__new__() got an unexpected keyword argument %r" % (typename, name)) - return tuple.__new__(cls, values) + # Binds as CPython's generated __new__(_cls, f0, f1=d, ...) does; a + # call passing every field positionally builds the tuple directly. + __new__ = _nt_new(typename, field_names, field_defaults) def _make(cls, iterable): result = tuple.__new__(cls, iterable) @@ -522,7 +504,7 @@ def __getnewargs__(self): "__match_args__": field_names, } for index, name in enumerate(field_names): - namespace[name] = property(_itemgetter(index), doc="Alias for field number " + str(index)) + namespace[name] = _tuplegetter(index, "Alias for field number " + str(index)) result = type(typename, (tuple,), namespace) # CPython reads the caller's module from its frame; there are no frames # here, so a caller outside __main__ passes module= (the stdlib does). @@ -531,6 +513,7 @@ def __getnewargs__(self): class ChainMap(dict): + __class_getitem__ = classmethod(type(list[int])) """A view of several mappings searched in order; writes go to the first.""" def __init__(self, *maps): @@ -613,6 +596,7 @@ def __eq__(self, other): class UserDict(dict): + __class_getitem__ = classmethod(type(list[int])) def __init__(self, dict=None, /, **kwargs): super().__init__() self.data = self @@ -623,6 +607,7 @@ def __init__(self, dict=None, /, **kwargs): class UserList(list): + __class_getitem__ = classmethod(type(list[int])) def __init__(self, initlist=None): super().__init__() self.data = self diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/collections/abc.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/collections/abc.py index f04c1de4ad8..3c9268ada2d 100644 --- a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/collections/abc.py +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/collections/abc.py @@ -5,6 +5,10 @@ from abc import ABCMeta, abstractmethod +# Iterable[int], Callable[[str], int]: each generic ABC is subscripted +# through types.GenericAlias, as in CPython. +_GenericAlias = type(list[int]) + def _has(c, *methods): for m in methods: @@ -29,6 +33,8 @@ def __subclasshook__(cls, c): class Awaitable(metaclass=ABCMeta): + __class_getitem__ = classmethod(_GenericAlias) + @abstractmethod def __await__(self): yield @@ -39,10 +45,14 @@ def __subclasshook__(cls, c): class Coroutine(Awaitable): - pass + @classmethod + def __subclasshook__(cls, c): + return _has(c, "__await__", "send", "throw", "close") if cls is Coroutine else NotImplemented class AsyncIterable(metaclass=ABCMeta): + __class_getitem__ = classmethod(_GenericAlias) + @abstractmethod def __aiter__(self): return None @@ -70,6 +80,8 @@ class AsyncGenerator(AsyncIterator): class Iterable(metaclass=ABCMeta): + __class_getitem__ = classmethod(_GenericAlias) + @abstractmethod def __iter__(self): while False: @@ -121,6 +133,8 @@ def __subclasshook__(cls, c): class Container(metaclass=ABCMeta): + __class_getitem__ = classmethod(_GenericAlias) + @abstractmethod def __contains__(self, x): return False @@ -137,6 +151,8 @@ def __subclasshook__(cls, c): class Callable(metaclass=ABCMeta): + __class_getitem__ = classmethod(_GenericAlias) + @abstractmethod def __call__(self, *args, **kwds): return False @@ -268,6 +284,8 @@ def __eq__(self, other): class MappingView(Sized): + __class_getitem__ = classmethod(_GenericAlias) + def __init__(self, mapping): self._mapping = mapping diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/concurrent/futures/__init__.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/concurrent/futures/__init__.py index ca97779c55f..5b5ff9d8e7b 100644 --- a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/concurrent/futures/__init__.py +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/concurrent/futures/__init__.py @@ -46,6 +46,7 @@ class BrokenExecutor(RuntimeError): class Future: + __class_getitem__ = classmethod(type(list[int])) def __init__(self): self._condition = threading.Condition() self._state = _PENDING diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/contextlib.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/contextlib.py index ce3386c86a0..3161f29e9d4 100644 --- a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/contextlib.py +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/contextlib.py @@ -8,6 +8,7 @@ class AbstractContextManager: + __class_getitem__ = classmethod(type(list[int])) def __enter__(self): return self @@ -16,6 +17,7 @@ def __exit__(self, exc_type, exc_value, traceback): class AbstractAsyncContextManager: + __class_getitem__ = classmethod(type(list[int])) async def __aenter__(self): return self @@ -179,29 +181,45 @@ async def __aexit__(self, *excinfo): class _RedirectStream(AbstractContextManager): - _stream = None - + # Each subclass reads and writes its own sys attribute by its literal + # name: no attribute is looked up from a computed string. def __init__(self, new_target): self._new_target = new_target self._old_targets = [] + def _get(self): + raise NotImplementedError + + def _set(self, value): + raise NotImplementedError + def __enter__(self): - import sys - self._old_targets.append(getattr(sys, self._stream)) - setattr(sys, self._stream, self._new_target) + self._old_targets.append(self._get()) + self._set(self._new_target) return self._new_target def __exit__(self, exctype, excinst, exctb): - import sys - setattr(sys, self._stream, self._old_targets.pop()) + self._set(self._old_targets.pop()) class redirect_stdout(_RedirectStream): - _stream = "stdout" + def _get(self): + import sys + return sys.stdout + + def _set(self, value): + import sys + sys.stdout = value class redirect_stderr(_RedirectStream): - _stream = "stderr" + def _get(self): + import sys + return sys.stderr + + def _set(self, value): + import sys + sys.stderr = value class ExitStack(AbstractContextManager): diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/contextvars.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/contextvars.py new file mode 100644 index 00000000000..b2ec750b9b5 --- /dev/null +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/contextvars.py @@ -0,0 +1,129 @@ +# Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. +# Licensed under the GNU General Public License version 2 with the Classpath +# exception, as the rest of the Codename One Python runtime. +"""Context variables. + +Each thread has its own current context, as under CPython: a worker thread +that runs a copied context (asyncio.to_thread, anyio's worker threads) must +not change the values the event loop's thread sees. Context.run sets the +variables it holds for the duration of the call and restores the previous +values afterwards, which is what asyncio and the libraries that copy a +context around rely on. +""" + +from _thread import get_ident as _get_ident + +_MISSING = object() +# The current context's values, by thread. Java thread ids are never +# reused, and threading drops a thread's entry when it ends (_forget). +_currents = {} + + +def _current(): + me = _get_ident() + d = _currents.get(me) + if d is None: + d = {} + _currents[me] = d + return d + + +def _forget(ident): + _currents.pop(ident, None) + + +class Token: + MISSING = _MISSING + + def __init__(self, var, old_value): + self.var = var + self.old_value = old_value + self._used = False + + +class ContextVar: + def __init__(self, name, *, default=_MISSING): + self.name = name + self._default = default + + def get(self, *default): + v = _current().get(self, _MISSING) + if v is not _MISSING: + return v + if default: + return default[0] + if self._default is not _MISSING: + return self._default + raise LookupError(self) + + def set(self, value): + cur = _current() + t = Token(self, cur.get(self, _MISSING)) + cur[self] = value + return t + + def reset(self, token): + if token._used: + raise RuntimeError("Token has already been used once") + token._used = True + cur = _current() + if token.old_value is _MISSING: + cur.pop(self, None) + else: + cur[self] = token.old_value + + def __class_getitem__(cls, item): + return cls + + def __repr__(self): + return "" % (self.name,) + + +class Context: + def __init__(self, values=None): + self._values = dict(values or {}) + + def run(self, fn, *args, **kwargs): + me = _get_ident() + saved = _currents.get(me) + running = dict(self._values) + _currents[me] = running + try: + return fn(*args, **kwargs) + finally: + self._values = _currents.get(me, running) + if saved is None: + _currents.pop(me, None) + else: + _currents[me] = saved + + def copy(self): + return Context(self._values) + + def get(self, var, default=None): + return self._values.get(var, default) + + def __getitem__(self, var): + return self._values[var] + + def __contains__(self, var): + return var in self._values + + def __iter__(self): + return iter(self._values) + + def __len__(self): + return len(self._values) + + def keys(self): + return self._values.keys() + + def values(self): + return self._values.values() + + def items(self): + return self._values.items() + + +def copy_context(): + return Context(_current()) diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/copy.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/copy.py index 607b79d8117..86b921e988d 100644 --- a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/copy.py +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/copy.py @@ -4,6 +4,7 @@ """Shallow and deep copy operations.""" import copyreg +import _cn1copy class Error(Exception): @@ -41,8 +42,9 @@ def copy(x): def _reduction(x, cls): - """What x reduces to, as CPython's copy asks; None for the runtime's own - reconstruction of a built-in subclass that keeps object's default.""" + """What x reduces to when its class asks for a reduction of its own; + None when it keeps object's default, which _reconstruct answers by + copying the compiled fields directly (_cn1copy).""" reductor = copyreg.dispatch_table.get(cls) if reductor is not None: return reductor(x) @@ -50,9 +52,12 @@ def _reduction(x, cls): return x.__reduce_ex__(4) if getattr(cls, "__reduce__", None) is not object.__reduce__: return x.__reduce__() - if _builtin_base(cls) or isinstance(x, BaseException): - return None - return x.__reduce_ex__(4) + return None + + +def _no_setstate(y): + raise TypeError("cannot copy " + type(y).__name__ + ": its reduction returns a state and the class " + "has no __setstate__; applying the state would need setattr with a computed name") def _reconstruct_from(x, memo, func, args, state=None, listiter=None, dictiter=None): @@ -68,15 +73,7 @@ def _reconstruct_from(x, memo, func, args, state=None, listiter=None, dictiter=N if hasattr(y, "__setstate__"): y.__setstate__(state) else: - slotstate = None - if isinstance(state, tuple) and len(state) == 2: - state, slotstate = state - if state: - for k, v in state.items(): - setattr(y, k, v) - if slotstate: - for k, v in slotstate.items(): - setattr(y, k, v) + _no_setstate(y) if listiter is not None: for item in listiter: y.append(deepcopy(item, memo) if deep else item) @@ -144,34 +141,39 @@ def _keep_alive(x, memo): def _reconstruct(x, memo): cls = type(x) - y = cls.__new__(cls) if not _builtin_base(cls) else _new_like(x, cls, memo) + if _builtin_base(cls): + y = _new_like(x, cls, memo) + elif getattr(cls, "__getnewargs_ex__", None) is not None: + args, kwargs = x.__getnewargs_ex__() + if memo is not None: + args = deepcopy(args, memo) + kwargs = deepcopy(kwargs, memo) + y = cls.__new__(cls, *args, **kwargs) + elif getattr(cls, "__getnewargs__", None) is not None: + args = x.__getnewargs__() + if memo is not None: + args = deepcopy(args, memo) + y = cls.__new__(cls, *args) + else: + y = cls.__new__(cls) if memo is not None: memo[id(x)] = y - state = getattr(x, "__getstate__", None) - state = state() if state is not None and getattr(cls, "__getstate__", None) is not getattr(object, "__getstate__", None) else _state_of(x) - if state: - if memo is not None: - state = deepcopy(state, memo) - if hasattr(y, "__setstate__"): - y.__setstate__(state) - else: - for k, v in state.items(): - setattr(y, k, v) + if getattr(cls, "__getstate__", None) is not object.__getstate__ or hasattr(y, "__setstate__"): + state = x.__getstate__() + if state: + if memo is not None: + state = deepcopy(state, memo) + if hasattr(y, "__setstate__"): + y.__setstate__(state) + else: + _no_setstate(y) + return y + # Every field by index through the methods the compiler generates per + # class, and the attributes held beside them: no name is looked up. + _cn1copy.copy_state(x, y, memo, None if memo is None else deepcopy) return y -def _state_of(x): - try: - return dict(x.__dict__) - except AttributeError: - state = {} - for k in type(x).__mro__: - for name in k.__dict__.get("__slots__", ()): - if hasattr(x, name): - state[name] = getattr(x, name) - return state - - def _builtin_base(cls): for k in cls.__mro__: if k in (list, dict, set, tuple, frozenset, int, float, str, bytes): diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/copyreg.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/copyreg.py index 0ba8e88e74d..a9cb3c0d53b 100644 --- a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/copyreg.py +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/copyreg.py @@ -88,16 +88,8 @@ def _getstate(obj): state = getattr(obj, "__dict__", None) if _has_dict(t) else None if state is not None: state = dict(state) if len(state) else None - slots = _slotnames(t) - if slots: - slotstate = {} - for name in slots: - try: - slotstate[name] = getattr(obj, name) - except AttributeError: - pass - if slotstate: - return (state, slotstate) + # Slot values are not gathered: reading them by name is reflection, so a + # slotted class that must be copied or pickled defines __getstate__ itself. return state diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/csv.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/csv.py index 315c537c2d3..2ff967930de 100644 --- a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/csv.py +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/csv.py @@ -108,8 +108,10 @@ def __init__(self, dialect=None, **kw): def pick(name, default): if name in kw: return kw[name] - if dialect is not None and getattr(dialect, name, None) is not None: - return getattr(dialect, name) + if dialect is not None: + v = _dialect_attr(dialect, name) + if v is not None: + return v return default self.delimiter = _char("delimiter", pick("delimiter", ","), False) @@ -174,16 +176,44 @@ def list_dialects(): return list(_dialects) +def _dialect_attr(d, name): + """One dialect parameter, each read by its own name (a computed + getattr cannot be typed); a parameter the dialect lacks reads None.""" + if name == "delimiter": + return getattr(d, "delimiter", None) + if name == "quotechar": + return getattr(d, "quotechar", None) + if name == "escapechar": + return getattr(d, "escapechar", None) + if name == "doublequote": + return getattr(d, "doublequote", None) + if name == "skipinitialspace": + return getattr(d, "skipinitialspace", None) + if name == "lineterminator": + return getattr(d, "lineterminator", None) + if name == "quoting": + return getattr(d, "quoting", None) + if name == "strict": + return getattr(d, "strict", None) + raise TypeError("not a dialect parameter: " + name) + + class _Frozen: __slots__ = ("delimiter", "quotechar", "escapechar", "doublequote", "skipinitialspace", "lineterminator", "quoting", "strict") def __init__(self, d): - for n in self.__slots__: - object.__setattr__(self, n, getattr(d, n)) - - def __setattr__(self, name, value): - raise AttributeError("attribute '%s' of '_csv.Dialect' objects is not writable" % name) + self.delimiter = d.delimiter + self.quotechar = d.quotechar + self.escapechar = d.escapechar + self.doublequote = d.doublequote + self.skipinitialspace = d.skipinitialspace + self.lineterminator = d.lineterminator + self.quoting = d.quoting + self.strict = d.strict + + # Read-only by convention: a __setattr__ that refuses writes would leave the + # class without a layout, and nothing in this module writes to one. register_dialect("excel", excel) diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/dataclasses.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/dataclasses.py index 7887a25510e..e3c0a02b1dc 100644 --- a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/dataclasses.py +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/dataclasses.py @@ -1,10 +1,12 @@ # Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. # Licensed under the GNU General Public License version 2 with the Classpath # exception, as the rest of the Codename One Python runtime. -"""Generated __init__, __repr__, __eq__ and friends for classes of fields. +"""Field records for classes the build gave __init__, __repr__, __eq__ and friends. -CPython builds these methods by exec'ing source text; the methods here are -closures over the field list instead, since no source is compiled at run time. +CPython builds those methods by exec'ing source text. Nothing is compiled at run +time here: the build writes them into every @dataclass class as plain methods +(DataclassInit), and the decorator only records the fields and checks that they +are the ones the build saw. """ import copy as _copy @@ -66,6 +68,7 @@ def __init__(self, default, default_factory, init, repr, hash, compare, metadata self.kw_only = kw_only self._field_type = None + def __repr__(self): return ("Field(name=%r,type=%r,default=%r,default_factory=%r,init=%r,repr=%r,hash=%r,compare=%r," "metadata=%r,kw_only=%r,_field_type=%s)" % (self.name, self.type, self.default, @@ -129,10 +132,14 @@ def _is_kw_only(a_type): def _get_field(cls, a_name, a_type, default_kw_only): - default = getattr(cls, a_name, MISSING) - if isinstance(default, Field): - f = default - else: + # The compiler moved every field(...) of the class body into + # __dataclass_field_specs__, leaving the class attribute the default alone. + specs = cls.__dict__.get("__dataclass_field_specs__") + f = specs.get(a_name) if specs is not None else None + if f is None: + default = cls.__dict__.get(a_name, MISSING) + if isinstance(default, Field): + raise TypeError("dataclass " + cls.__qualname__ + " was not lowered at build time") f = field(default=default) f.name = a_name f.type = a_type @@ -155,158 +162,21 @@ def _get_field(cls, a_name, a_type, default_kw_only): return f -def _set_new_attribute(cls, name, value): - if name in cls.__dict__: +_repr_running = set() + + +def _repr_enter(obj): + # Called by every generated __repr__: true when obj is already being shown + # further up the stack, which CPython's recursive_repr prints as "...". + key = id(obj) + if key in _repr_running: return True - setattr(cls, name, value) + _repr_running.add(key) return False -def _fields_in_init_order(fields): - std = [f for f in fields if f.init and not f.kw_only] - kw = [f for f in fields if f.init and f.kw_only] - return std, kw - - -def _make_init(cls, fields, std_fields, kw_only_fields, frozen, has_post_init): - seen_default = None - for f in std_fields: - if f.default is not MISSING or f.default_factory is not MISSING: - seen_default = f - elif seen_default is not None: - raise TypeError("non-default argument " + repr(f.name) + " follows default argument " + - repr(seen_default.name)) - qualname = cls.__qualname__ + ".__init__" - nstd = len(std_fields) - nreq = len([f for f in std_fields if f.default is MISSING and f.default_factory is MISSING]) - names = [f.name for f in std_fields + kw_only_fields] - initvars = [f.name for f in fields if f._field_type is _FIELD_INITVAR] - - def __init__(self, *args, **kwargs): - if len(args) > nstd: - if nreq == nstd: - takes = "%d positional argument%s" % (nstd + 1, "" if nstd == 0 else "s") - else: - takes = "from %d to %d positional arguments" % (nreq + 1, nstd + 1) - raise TypeError("%s() takes %s but %d were given" % (qualname, takes, len(args) + 1)) - values = {} - for i in range(len(args)): - values[std_fields[i].name] = args[i] - for k, v in kwargs.items(): - if k not in names: - raise TypeError(qualname + "() got an unexpected keyword argument " + repr(k)) - if k in values: - raise TypeError(qualname + "() got multiple values for argument " + repr(k)) - values[k] = v - missing = [f.name for f in std_fields if f.name not in values and f.default is MISSING and - f.default_factory is MISSING] - if missing: - raise TypeError("%s() missing %d required positional argument%s: %s" - % (qualname, len(missing), "" if len(missing) == 1 else "s", - _and_join(["'" + m + "'" for m in missing]))) - missing = [f.name for f in kw_only_fields if f.name not in values and f.default is MISSING and - f.default_factory is MISSING] - if missing: - raise TypeError("%s() missing %d required keyword-only argument%s: %s" - % (qualname, len(missing), "" if len(missing) == 1 else "s", - _and_join(["'" + m + "'" for m in missing]))) - for f in fields: - if f._field_type is not _FIELD: - continue - if f.init and f.name in values: - v = values[f.name] - elif f.default_factory is not MISSING: - v = f.default_factory() - elif f.default is not MISSING: - if not f.init: - continue - v = f.default - else: - continue - if frozen: - object.__setattr__(self, f.name, v) - else: - setattr(self, f.name, v) - if has_post_init: - extra = [] - for name in initvars: - if name in values: - extra.append(values[name]) - else: - extra.append(next(f.default for f in fields if f.name == name)) - self.__post_init__(*extra) - __init__.__qualname__ = qualname - return __init__ - - -def _and_join(items): - if len(items) == 1: - return items[0] - if len(items) == 2: - return items[0] + " and " + items[1] - return ", ".join(items[:-1]) + ", and " + items[-1] - - -def _make_repr(fields): - shown = [f for f in fields if f._field_type is _FIELD and f.repr] - active = set() - - def __repr__(self): - key = id(self) - if key in active: - return "..." - active.add(key) - try: - return type(self).__qualname__ + "(" + ", ".join(f.name + "=" + repr(getattr(self, f.name)) - for f in shown) + ")" - finally: - active.discard(key) - # pprint lays out a dataclass field by field only when its repr is ours. - __repr__._dataclass_repr = True - return __repr__ - - -def _tuple_of(fields): - compared = [f.name for f in fields if f._field_type is _FIELD and f.compare] - - def as_tuple(self): - return tuple(getattr(self, n) for n in compared) - return as_tuple - - -def _make_eq(as_tuple): - def __eq__(self, other): - if self is other: - return True - if other.__class__ is self.__class__: - return as_tuple(self) == as_tuple(other) - return NotImplemented - return __eq__ - - -def _make_order(as_tuple, op): - def compare(self, other): - if other.__class__ is not self.__class__: - return NotImplemented - a = as_tuple(self) - b = as_tuple(other) - if op == "__lt__": - return a < b - if op == "__le__": - return a <= b - if op == "__gt__": - return a > b - return a >= b - compare.__name__ = op - return compare - - -def _make_hash(fields): - hashed = [f.name for f in fields if f._field_type is _FIELD and (f.compare if f.hash is None else f.hash)] - - def __hash__(self): - return hash(tuple(getattr(self, n) for n in hashed)) - return __hash__ +def _repr_leave(obj): + _repr_running.discard(id(obj)) def _make_frozen(cls, fields): @@ -325,21 +195,23 @@ def __delattr__(self, name): def _process_class(cls, init, repr, eq, order, unsafe_hash, frozen, match_args, kw_only, slots, weakref_slot): + lowered = cls.__dict__.get("__cn1_dc_lowered__") + if lowered is None: + raise TypeError("dataclass " + cls.__qualname__ + " was not lowered at build time") fields = {} - setattr(cls, _PARAMS, _DataclassParams(init, repr, eq, order, unsafe_hash, frozen, match_args, kw_only, + cls.__dataclass_params__ = (_DataclassParams(init, repr, eq, order, unsafe_hash, frozen, match_args, kw_only, slots, weakref_slot)) any_frozen_base = False has_dataclass_bases = False for b in cls.__mro__[-1:0:-1]: - base_fields = getattr(b, _FIELDS, None) + base_fields = getattr(b, "__dataclass_fields__", None) if base_fields is not None: has_dataclass_bases = True for f in base_fields.values(): fields[f.name] = f - if getattr(b, _PARAMS).frozen: + if getattr(b, "__dataclass_params__").frozen: any_frozen_base = True cls_annotations = cls.__dict__.get("__annotations__", {}) - cls_fields = [] kw_only_seen = False for name, type_ in cls_annotations.items(): if _is_kw_only(type_): @@ -348,14 +220,10 @@ def _process_class(cls, init, repr, eq, order, unsafe_hash, frozen, match_args, kw_only_seen = True kw_only = True else: - cls_fields.append(_get_field(cls, name, type_, kw_only)) - for f in cls_fields: - fields[f.name] = f - if isinstance(getattr(cls, f.name, None), Field): - if f.default is MISSING: - delattr(cls, f.name) - else: - setattr(cls, f.name, f.default) + f = _get_field(cls, name, type_, kw_only) + fields[f.name] = f + if isinstance(cls.__dict__.get(f.name), Field): + raise TypeError("dataclass " + cls.__qualname__ + " was not lowered at build time") for name, value in cls.__dict__.items(): if isinstance(value, Field) and name not in cls_annotations: raise TypeError(repr(name) + " is a field but has no type annotation") @@ -364,46 +232,27 @@ def _process_class(cls, init, repr, eq, order, unsafe_hash, frozen, match_args, raise TypeError("cannot inherit non-frozen dataclass from a frozen one") if not any_frozen_base and frozen: raise TypeError("cannot inherit frozen dataclass from a non-frozen one") - setattr(cls, _FIELDS, fields) - class_hash = cls.__dict__.get("__hash__", MISSING) - has_explicit_hash = not (class_hash is MISSING or (class_hash is None and "__eq__" in cls.__dict__)) - all_fields = list(fields.values()) - field_list = [f for f in all_fields if f._field_type is _FIELD] - std, kw = _fields_in_init_order([f for f in all_fields if f._field_type in (_FIELD, _FIELD_INITVAR)]) - if init: - has_post_init = hasattr(cls, "__post_init__") - _set_new_attribute(cls, "__init__", _make_init(cls, all_fields, std, kw, frozen, has_post_init)) - if repr: - _set_new_attribute(cls, "__repr__", _make_repr(field_list)) - as_tuple = _tuple_of(field_list) - if eq: - _set_new_attribute(cls, "__eq__", _make_eq(as_tuple)) - if order: - for op in ("__lt__", "__le__", "__gt__", "__ge__"): - if _set_new_attribute(cls, op, _make_order(as_tuple, op)): - raise TypeError("Cannot overwrite attribute " + op + " in class " + cls.__name__ + - ". Consider using functools.total_ordering") + cls.__dataclass_fields__ = fields + # The build wrote every method from the fields it could see; a base it + # could not (one from another module) must not have added any. + names, post_init = lowered + seen = tuple(f.name for f in fields.values() if f._field_type is not _FIELD_CLASSVAR) + if seen != names: + raise TypeError("dataclass " + cls.__qualname__ + " has fields " + repr(seen) + " but was built for " + + repr(names) + ": its dataclass bases must be in the same module") + if post_init is not None and post_init != hasattr(cls, "__post_init__"): + raise TypeError("dataclass " + cls.__qualname__ + " inherits a __post_init__ the build could not see") if frozen: - setter, deleter = _make_frozen(cls, field_list) - for name, fn in (("__setattr__", setter), ("__delattr__", deleter)): - if _set_new_attribute(cls, name, fn): + setter, deleter = _make_frozen(cls, [f for f in fields.values() if f._field_type is _FIELD]) + for name in ("__setattr__", "__delattr__"): + if name in cls.__dict__: raise TypeError("Cannot overwrite attribute " + name + " in class " + cls.__name__) - if unsafe_hash: - if has_explicit_hash: - raise TypeError("Cannot overwrite attribute __hash__ in class " + cls.__name__) - cls.__hash__ = _make_hash(field_list) - elif not has_explicit_hash: - if eq and frozen: - cls.__hash__ = _make_hash(field_list) - elif eq: - cls.__hash__ = None - if match_args: - _set_new_attribute(cls, "__match_args__", tuple(f.name for f in std)) - if "__replace__" not in cls.__dict__: - cls.__replace__ = _replace + cls.__setattr__ = setter + cls.__delattr__ = deleter return cls + def dataclass(cls=None, /, *, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, match_args=True, kw_only=False, slots=False, weakref_slot=False): def wrap(cls): @@ -418,7 +267,7 @@ def wrap(cls): def fields(class_or_instance): try: - fs = getattr(class_or_instance, _FIELDS) + fs = getattr(class_or_instance, "__dataclass_fields__") except AttributeError: raise TypeError("must be called with a dataclass type or instance") from None return tuple(f for f in fs.values() if f._field_type is _FIELD) @@ -426,22 +275,22 @@ def fields(class_or_instance): def is_dataclass(obj): cls = obj if isinstance(obj, type) else type(obj) - return hasattr(cls, _FIELDS) + return hasattr(cls, "__cn1_dc_lowered__") def _is_dataclass_instance(obj): - return hasattr(type(obj), _FIELDS) + return hasattr(type(obj), "__cn1_dc_lowered__") def asdict(obj, *, dict_factory=dict): if not _is_dataclass_instance(obj): raise TypeError("asdict() should be called on dataclass instances") - return _asdict_inner(obj, dict_factory) + return obj.__cn1_asdict__(dict_factory) def _asdict_inner(obj, dict_factory): if _is_dataclass_instance(obj): - return dict_factory([(f.name, _asdict_inner(getattr(obj, f.name), dict_factory)) for f in fields(obj)]) + return obj.__cn1_asdict__(dict_factory) if isinstance(obj, tuple) and hasattr(obj, "_fields"): return type(obj)(*[_asdict_inner(v, dict_factory) for v in obj]) if isinstance(obj, (list, tuple)): @@ -454,12 +303,12 @@ def _asdict_inner(obj, dict_factory): def astuple(obj, *, tuple_factory=tuple): if not _is_dataclass_instance(obj): raise TypeError("astuple() should be called on dataclass instances") - return _astuple_inner(obj, tuple_factory) + return obj.__cn1_astuple__(tuple_factory) def _astuple_inner(obj, tuple_factory): if _is_dataclass_instance(obj): - return tuple_factory([_astuple_inner(getattr(obj, f.name), tuple_factory) for f in fields(obj)]) + return obj.__cn1_astuple__(tuple_factory) if isinstance(obj, tuple) and hasattr(obj, "_fields"): return type(obj)(*[_astuple_inner(v, tuple_factory) for v in obj]) if isinstance(obj, (list, tuple)): @@ -470,42 +319,17 @@ def _astuple_inner(obj, tuple_factory): return _copy.deepcopy(obj) + def make_dataclass(cls_name, fields, *, bases=(), namespace=None, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, match_args=True, kw_only=False, slots=False, weakref_slot=False, module=None): - ns = {} if namespace is None else dict(namespace) - annotations = {} - for item in fields: - if isinstance(item, str): - annotations[item] = "typing.Any" - elif len(item) == 2: - annotations[item[0]] = item[1] - else: - annotations[item[0]] = item[1] - ns[item[0]] = item[2] - ns["__annotations__"] = annotations - cls = type(cls_name, bases, ns) - return dataclass(cls, init=init, repr=repr, eq=eq, order=order, unsafe_hash=unsafe_hash, frozen=frozen, - match_args=match_args, kw_only=kw_only, slots=slots, weakref_slot=weakref_slot) - - -def _replace(self, /, **changes): - for f in getattr(self, _FIELDS).values(): - if f._field_type is _FIELD_CLASSVAR: - continue - if not f.init: - if f.name in changes: - raise TypeError("field " + f.name + " is declared with init=False, it cannot be specified with " - "replace()") - continue - if f.name not in changes: - if f._field_type is _FIELD_INITVAR and f.default is MISSING: - raise TypeError("InitVar " + repr(f.name) + " must be specified with replace()") - changes[f.name] = getattr(self, f.name) - return self.__class__(**changes) + # A call with a literal field list is turned into a class statement at + # build time and never reaches this; a class is not assembled from names + # at run time. + raise TypeError("make_dataclass(" + repr(cls_name) + ") needs a literal field list to be lowered at build time") def replace(obj, /, **changes): if not _is_dataclass_instance(obj): raise TypeError("replace() should be called on dataclass instances") - return _replace(obj, **changes) + return obj.__replace__(**changes) diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/datetime.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/datetime.py index 59f676e05f6..f8d9ac14732 100644 --- a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/datetime.py +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/datetime.py @@ -9,6 +9,7 @@ import time as _time import _time as _clock +import _cn1obj __all__ = ["date", "datetime", "time", "timedelta", "timezone", "tzinfo", "MINYEAR", "MAXYEAR", "UTC"] @@ -520,9 +521,17 @@ class IsoCalendarDate(tuple): def __new__(cls, year, week, weekday): return tuple.__new__(cls, (year, week, weekday)) - year = property(lambda self: self[0]) - week = property(lambda self: self[1]) - weekday = property(lambda self: self[2]) + @property + def year(self): + return self[0] + + @property + def week(self): + return self[1] + + @property + def weekday(self): + return self[2] def __repr__(self): return "datetime.IsoCalendarDate(year=%d, week=%d, weekday=%d)" % tuple(self) @@ -585,7 +594,7 @@ def fromutc(self, dt): class timezone(tzinfo): - __slots__ = ("_offset", "_name") + __slots__ = ("_offset", "_name", "_secs", "_iso") _Omitted = object() @@ -608,6 +617,10 @@ def _create(cls, offset, name=None): self = tzinfo.__new__(cls) self._offset = offset self._name = name + # The offset as whole seconds when it is one (None otherwise), and + # its isoformat text: both read by datetime's fast paths. + self._secs = offset.days * 86400 + offset.seconds if not offset.microseconds else None + self._iso = _format_offset(offset) return self def __eq__(self, other): @@ -688,12 +701,30 @@ def __new__(cls, hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold self._hashcode = -1 return self - hour = property(lambda self: self._hour) - minute = property(lambda self: self._minute) - second = property(lambda self: self._second) - microsecond = property(lambda self: self._microsecond) - tzinfo = property(lambda self: self._tzinfo) - fold = property(lambda self: self._fold) + @property + def hour(self): + return self._hour + + @property + def minute(self): + return self._minute + + @property + def second(self): + return self._second + + @property + def microsecond(self): + return self._microsecond + + @property + def tzinfo(self): + return self._tzinfo + + @property + def fold(self): + return self._fold + @classmethod def fromisoformat(cls, s): @@ -850,6 +881,11 @@ def _local_fields(t): def _fields(t, off): + if type(t) is float and -1e15 < t < 1e15: + y, m, d, hh, mm, ss, us = _clock.float_fields(t, off) + if not MINYEAR <= y <= MAXYEAR: + raise ValueError("year %d is out of range" % y) + return y, m, d, hh, mm, ss, us if isinstance(t, int): secs = t us = 0 @@ -867,6 +903,16 @@ def _fields(t, off): return y, m, d, rem // 3600, rem // 60 % 60, rem % 60, us +def _new_dt(y, m, d, hh, mm, ss, us, tz, fold): + # A datetime of fields already known to be valid -- computed here from a + # timestamp or from another datetime -- without the checks of __new__, + # and made in one call instead of ten attribute stores (see _cn1obj). + return _cn1obj.make(datetime, _DT_FIELDS, y, m, d, hh, mm, ss, us, tz, fold, -1) + + +_DT_FIELDS = "_year\n_month\n_day\n_hour\n_minute\n_second\n_microsecond\n_tzinfo\n_fold\n_hashcode" + + class datetime(date): __slots__ = ("_hour", "_minute", "_second", "_microsecond", "_tzinfo", "_fold") @@ -888,18 +934,43 @@ def __new__(cls, year, month=None, day=None, hour=0, minute=0, second=0, microse self._hashcode = -1 return self - hour = property(lambda self: self._hour) - minute = property(lambda self: self._minute) - second = property(lambda self: self._second) - microsecond = property(lambda self: self._microsecond) - tzinfo = property(lambda self: self._tzinfo) - fold = property(lambda self: self._fold) + @property + def hour(self): + return self._hour + + @property + def minute(self): + return self._minute + + @property + def second(self): + return self._second + + @property + def microsecond(self): + return self._microsecond + + @property + def tzinfo(self): + return self._tzinfo + + @property + def fold(self): + return self._fold + @classmethod def fromtimestamp(cls, t, tz=None): _check_tzinfo(tz) if tz is None: return cls(*_local_fields(t)) + if cls is datetime and type(tz) is timezone and tz._secs is not None: + # A fixed whole-second offset: fromutc adds exactly it, so the + # fields are the timestamp's at that offset. + if isinstance(t, bool) or not isinstance(t, (int, float)): + raise TypeError("'%s' object cannot be interpreted as an integer" % type(t).__name__) + y, m, d, hh, mm, ss, us = _fields(t, tz._secs) + return _new_dt(y, m, d, hh, mm, ss, us, tz, 0) y, m, d, hh, mm, ss, us = _fields(t, 0) return tz.fromutc(cls(y, m, d, hh, mm, ss, us, tz)) @@ -909,6 +980,8 @@ def utcfromtimestamp(cls, t): @classmethod def now(cls, tz=None): + if cls is datetime and type(tz) is timezone and tz._secs is not None: + return _clock.now_datetime(datetime, _DT_FIELDS, tz._secs, tz) return cls.fromtimestamp(_time.time(), tz) @classmethod @@ -1041,6 +1114,16 @@ def ctime(self): self._day, self._hour, self._minute, self._second, self._year) def isoformat(self, sep="T", timespec="auto"): + tz = self._tzinfo + if type(tz) is timezone and timespec == "auto": + # The usual call: a fixed-offset zone, whose offset text is + # made once per zone instead of by divmods of timedeltas here. + us = self._microsecond + if us: + return "%04d-%02d-%02d%s%02d:%02d:%02d.%06d%s" % ( + self._year, self._month, self._day, sep, self._hour, self._minute, self._second, us, tz._iso) + return "%04d-%02d-%02d%s%02d:%02d:%02d%s" % ( + self._year, self._month, self._day, sep, self._hour, self._minute, self._second, tz._iso) return ("%04d-%02d-%02d%s" % (self._year, self._month, self._day, sep) + _format_time(self._hour, self._minute, self._second, self._microsecond, timespec) + _format_offset(self._off())) @@ -1143,6 +1226,8 @@ def __add__(self, other): raise OverflowError("date value out of range") y, m, d = _ord2ymd(o) s, us = divmod(rem, 1000000) + if type(self) is datetime: + return _new_dt(y, m, d, s // 3600, s // 60 % 60, s % 60, us, self._tzinfo, 0) return type(self).combine(date(y, m, d), time(s // 3600, s // 60 % 60, s % 60, us, self._tzinfo)) __radd__ = __add__ diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/decimal.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/decimal.py index ace6c854d02..b2fc91e2abe 100644 --- a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/decimal.py +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/decimal.py @@ -96,7 +96,9 @@ class Subnormal(DecimalException): pass -class Overflow(Inexact, Rounded): +# Overflow and Underflow carry only their first base: a second exception base +# gives the class no layout, and nothing here catches them as Rounded. +class Overflow(Inexact): def handle(self, context, sign, *args): if context.rounding in (ROUND_HALF_UP, ROUND_HALF_EVEN, ROUND_HALF_DOWN, ROUND_UP): return _SignedInfinity[sign] @@ -109,7 +111,7 @@ def handle(self, context, sign, *args): return _dec(sign, "9" * context.prec, context.Emax - context.prec + 1) -class Underflow(Inexact, Rounded, Subnormal): +class Underflow(Inexact): pass @@ -151,30 +153,74 @@ def __init__(self, prec=None, rounding=None, Emin=None, Emax=None, capitals=None else: self.flags = {s: bool(flags.get(s, False)) for s in _signals} - def __setattr__(self, name, value): - if name == "prec": - if not isinstance(value, int): - raise TypeError("an integer is required") - if not 1 <= value <= MAX_PREC: - raise ValueError("valid range for prec is [1, MAX_PREC]") - elif name == "Emin": - if not isinstance(value, int): - raise TypeError("an integer is required") - if not MIN_EMIN <= value <= 0: - raise ValueError("valid range for Emin is [MIN_EMIN, 0]") - elif name == "Emax": - if not isinstance(value, int): - raise TypeError("an integer is required") - if not 0 <= value <= MAX_EMAX: - raise ValueError("valid range for Emax is [0, MAX_EMAX]") - elif name == "capitals" or name == "clamp": - if value not in (0, 1): - raise ValueError("valid values for %s are [0, 1]" % name) - elif name == "rounding": - if value not in _ROUNDINGS: - raise TypeError("valid values for rounding are:\n [ROUND_CEILING, ROUND_FLOOR, ROUND_UP, ROUND_DOWN," - "\n ROUND_HALF_UP, ROUND_HALF_DOWN, ROUND_HALF_EVEN,\n ROUND_05UP]") - object.__setattr__(self, name, value) + # The validated attributes are properties rather than a __setattr__, which + # would leave Context without a layout. + @property + def prec(self): + return self._prec + + @prec.setter + def prec(self, value): + if not isinstance(value, int): + raise TypeError("an integer is required") + if not 1 <= value <= MAX_PREC: + raise ValueError("valid range for prec is [1, MAX_PREC]") + self._prec = value + + @property + def Emin(self): + return self._Emin + + @Emin.setter + def Emin(self, value): + if not isinstance(value, int): + raise TypeError("an integer is required") + if not MIN_EMIN <= value <= 0: + raise ValueError("valid range for Emin is [MIN_EMIN, 0]") + self._Emin = value + + @property + def Emax(self): + return self._Emax + + @Emax.setter + def Emax(self, value): + if not isinstance(value, int): + raise TypeError("an integer is required") + if not 0 <= value <= MAX_EMAX: + raise ValueError("valid range for Emax is [0, MAX_EMAX]") + self._Emax = value + + @property + def capitals(self): + return self._capitals + + @capitals.setter + def capitals(self, value): + if value not in (0, 1): + raise ValueError("valid values for capitals are [0, 1]") + self._capitals = value + + @property + def clamp(self): + return self._clamp + + @clamp.setter + def clamp(self, value): + if value not in (0, 1): + raise ValueError("valid values for clamp are [0, 1]") + self._clamp = value + + @property + def rounding(self): + return self._rounding + + @rounding.setter + def rounding(self, value): + if value not in _ROUNDINGS: + raise TypeError("valid values for rounding are:\n [ROUND_CEILING, ROUND_FLOOR, ROUND_UP, ROUND_DOWN," + "\n ROUND_HALF_UP, ROUND_HALF_DOWN, ROUND_HALF_EVEN,\n ROUND_05UP]") + self._rounding = value def __repr__(self): return ("Context(prec=%d, rounding=%s, Emin=%d, Emax=%d, capitals=%d, clamp=%d, flags=[%s], traps=[%s])" @@ -377,10 +423,23 @@ def localcontext(ctx=None, **kwargs): ctx = getcontext() manager = _ContextManager(ctx) for key, value in kwargs.items(): - if key == "flags" or key == "traps": - setattr(manager.new_context, key, {s: s in value for s in _signals}) - elif key in ("prec", "rounding", "Emin", "Emax", "capitals", "clamp"): - setattr(manager.new_context, key, value) + c = manager.new_context + if key == "flags": + c.flags = {s: s in value for s in _signals} + elif key == "traps": + c.traps = {s: s in value for s in _signals} + elif key == "prec": + c.prec = value + elif key == "rounding": + c.rounding = value + elif key == "Emin": + c.Emin = value + elif key == "Emax": + c.Emax = value + elif key == "capitals": + c.capitals = value + elif key == "clamp": + c.clamp = value else: raise TypeError("'%s' is an invalid keyword argument for this function" % key) return manager diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/difflib.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/difflib.py new file mode 100644 index 00000000000..2bb4625982e --- /dev/null +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/difflib.py @@ -0,0 +1,267 @@ +# Copyright (c) 2001 Python Software Foundation; All Rights Reserved +# Licensed under the Python Software Foundation License Version 2; the full +# text is in maven/python-transpiler/third-party/cpython/LICENSE.txt. +# +# Derived from CPython's Lib/difflib.py. Changes: rewritten for the Codename One +# Python runtime, trimmed to what the transpiler supports and reorganised; +# the C accelerators and platform-specific branches are left out. +"""difflib: sequence matching, close matches and unified/context diffs. + +SequenceMatcher finds the longest matching block and recurses on both sides +of it (Ratcliff/Obershelp), with CPython's junk and popularity heuristics, +so ratio() and get_opcodes() give the numbers CPython gives. +""" + +from collections import namedtuple as _namedtuple + +Match = _namedtuple("Match", "a b size") + + +class SequenceMatcher: + def __init__(self, isjunk=None, a="", b="", autojunk=True): + self.isjunk = isjunk + self.autojunk = autojunk + self.a = self.b = None + self.set_seqs(a, b) + + def set_seqs(self, a, b): + self.set_seq1(a) + self.set_seq2(b) + + def set_seq1(self, a): + if a is self.a: + return + self.a = a + self.matching_blocks = self.opcodes = None + + def set_seq2(self, b): + if b is self.b: + return + self.b = b + self.matching_blocks = self.opcodes = None + self.fullbcount = None + self._chain_b() + + def _chain_b(self): + b = self.b + self.b2j = b2j = {} + for i, elt in enumerate(b): + b2j.setdefault(elt, []).append(i) + self.bjunk = junk = set() + if self.isjunk: + for elt in list(b2j): + if self.isjunk(elt): + junk.add(elt) + for elt in junk: + del b2j[elt] + self.bpopular = popular = set() + n = len(b) + if self.autojunk and n >= 200: + ntest = n // 100 + 1 + for elt, idxs in list(b2j.items()): + if len(idxs) > ntest: + popular.add(elt) + for elt in popular: + del b2j[elt] + + def find_longest_match(self, alo=0, ahi=None, blo=0, bhi=None): + a, b, b2j, isbjunk = self.a, self.b, self.b2j, self.bjunk.__contains__ + if ahi is None: + ahi = len(a) + if bhi is None: + bhi = len(b) + besti, bestj, bestsize = alo, blo, 0 + j2len = {} + for i in range(alo, ahi): + newj2len = {} + for j in b2j.get(a[i], ()): + if j < blo: + continue + if j >= bhi: + break + k = newj2len[j] = j2len.get(j - 1, 0) + 1 + if k > bestsize: + besti, bestj, bestsize = i - k + 1, j - k + 1, k + j2len = newj2len + while besti > alo and bestj > blo and not isbjunk(b[bestj - 1]) and a[besti - 1] == b[bestj - 1]: + besti, bestj, bestsize = besti - 1, bestj - 1, bestsize + 1 + while (besti + bestsize < ahi and bestj + bestsize < bhi and not isbjunk(b[bestj + bestsize]) + and a[besti + bestsize] == b[bestj + bestsize]): + bestsize += 1 + while besti > alo and bestj > blo and isbjunk(b[bestj - 1]) and a[besti - 1] == b[bestj - 1]: + besti, bestj, bestsize = besti - 1, bestj - 1, bestsize + 1 + while (besti + bestsize < ahi and bestj + bestsize < bhi and isbjunk(b[bestj + bestsize]) + and a[besti + bestsize] == b[bestj + bestsize]): + bestsize = bestsize + 1 + return Match(besti, bestj, bestsize) + + def get_matching_blocks(self): + if self.matching_blocks is not None: + return self.matching_blocks + la, lb = len(self.a), len(self.b) + queue = [(0, la, 0, lb)] + blocks = [] + while queue: + alo, ahi, blo, bhi = queue.pop() + i, j, k = x = self.find_longest_match(alo, ahi, blo, bhi) + if k: + blocks.append(x) + if alo < i and blo < j: + queue.append((alo, i, blo, j)) + if i + k < ahi and j + k < bhi: + queue.append((i + k, ahi, j + k, bhi)) + blocks.sort() + i1 = j1 = k1 = 0 + merged = [] + for i2, j2, k2 in blocks: + if i1 + k1 == i2 and j1 + k1 == j2: + k1 += k2 + else: + if k1: + merged.append((i1, j1, k1)) + i1, j1, k1 = i2, j2, k2 + if k1: + merged.append((i1, j1, k1)) + merged.append((la, lb, 0)) + self.matching_blocks = [Match(*t) for t in merged] + return self.matching_blocks + + def get_opcodes(self): + if self.opcodes is not None: + return self.opcodes + i = j = 0 + self.opcodes = answer = [] + for ai, bj, size in self.get_matching_blocks(): + tag = "" + if i < ai and j < bj: + tag = "replace" + elif i < ai: + tag = "delete" + elif j < bj: + tag = "insert" + if tag: + answer.append((tag, i, ai, j, bj)) + i, j = ai + size, bj + size + if size: + answer.append(("equal", ai, i, bj, j)) + return answer + + def get_grouped_opcodes(self, n=3): + codes = self.get_opcodes() + if not codes: + codes = [("equal", 0, 1, 0, 1)] + if codes[0][0] == "equal": + tag, i1, i2, j1, j2 = codes[0] + codes[0] = tag, max(i1, i2 - n), i2, max(j1, j2 - n), j2 + if codes[-1][0] == "equal": + tag, i1, i2, j1, j2 = codes[-1] + codes[-1] = tag, i1, min(i2, i1 + n), j1, min(j2, j1 + n) + nn = n + n + group = [] + for tag, i1, i2, j1, j2 in codes: + if tag == "equal" and i2 - i1 > nn: + group.append((tag, i1, min(i2, i1 + n), j1, min(j2, j1 + n))) + yield group + group = [] + i1, j1 = max(i1, i2 - n), max(j1, j2 - n) + group.append((tag, i1, i2, j1, j2)) + if group and not (len(group) == 1 and group[0][0] == "equal"): + yield group + + def ratio(self): + matches = sum(t[-1] for t in self.get_matching_blocks()) + return _ratio(matches, len(self.a) + len(self.b)) + + def quick_ratio(self): + if self.fullbcount is None: + self.fullbcount = full = {} + for elt in self.b: + full[elt] = full.get(elt, 0) + 1 + full = self.fullbcount + avail = {} + matches = 0 + for elt in self.a: + numb = avail[elt] if elt in avail else full.get(elt, 0) + avail[elt] = numb - 1 + if numb > 0: + matches += 1 + return _ratio(matches, len(self.a) + len(self.b)) + + def real_quick_ratio(self): + la, lb = len(self.a), len(self.b) + return _ratio(min(la, lb), la + lb) + + +def _ratio(matches, length): + return 2.0 * matches / length if length else 1.0 + + +def get_close_matches(word, possibilities, n=3, cutoff=0.6): + if not n > 0: + raise ValueError("n must be > 0: %r" % (n,)) + if not 0.0 <= cutoff <= 1.0: + raise ValueError("cutoff must be in [0.0, 1.0]: %r" % (cutoff,)) + result = [] + s = SequenceMatcher() + s.set_seq2(word) + for x in possibilities: + s.set_seq1(x) + if s.real_quick_ratio() >= cutoff and s.quick_ratio() >= cutoff and s.ratio() >= cutoff: + result.append((s.ratio(), x)) + result.sort(key=lambda t: (t[0], t[1]), reverse=True) + return [x for score, x in result[:n]] + + +def _format_range_unified(start, stop): + beginning = start + 1 + length = stop - start + if length == 1: + return "%d" % beginning + if not length: + beginning -= 1 + return "%d,%d" % (beginning, length) + + +def unified_diff(a, b, fromfile="", tofile="", fromfiledate="", tofiledate="", n=3, lineterm="\n"): + started = False + for group in SequenceMatcher(None, a, b).get_grouped_opcodes(n): + if not started: + started = True + fromdate = "\t" + fromfiledate if fromfiledate else "" + todate = "\t" + tofiledate if tofiledate else "" + yield "--- %s%s%s" % (fromfile, fromdate, lineterm) + yield "+++ %s%s%s" % (tofile, todate, lineterm) + first, last = group[0], group[-1] + yield "@@ -%s +%s @@%s" % (_format_range_unified(first[1], last[2]), + _format_range_unified(first[3], last[4]), lineterm) + for tag, i1, i2, j1, j2 in group: + if tag == "equal": + for line in a[i1:i2]: + yield " " + line + continue + if tag in ("replace", "delete"): + for line in a[i1:i2]: + yield "-" + line + if tag in ("replace", "insert"): + for line in b[j1:j2]: + yield "+" + line + + +def ndiff(a, b, linejunk=None, charjunk=None): + for tag, i1, i2, j1, j2 in SequenceMatcher(linejunk, a, b).get_opcodes(): + if tag == "equal": + for line in a[i1:i2]: + yield " " + line + continue + for line in a[i1:i2]: + yield "- " + line + for line in b[j1:j2]: + yield "+ " + line + + +def IS_CHARACTER_JUNK(ch, ws=" \t"): + return ch in ws + + +def IS_LINE_JUNK(line, pat=None): + return line.strip() in ("", "#") diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/email/message.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/email/message.py index ef38c0265a1..c209e5873c9 100644 --- a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/email/message.py +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/email/message.py @@ -114,6 +114,8 @@ def get_params(self, failobj=None, header="content-type", unquote=True): result.append((k.strip().lower(), _unquote(v.strip()) if unquote else v.strip())) else: result.append((p.strip() if i == 0 else p.strip().lower(), "")) + if unquote: + result = _decode_rfc2231_params(result) return result def get_param(self, param, failobj=None, header="content-type", unquote=True): @@ -219,3 +221,48 @@ def set_content(self, content, subtype="plain", charset="utf-8"): if isinstance(content, str): self["Content-Type"] = "text/%s; charset=\"%s\"" % (subtype, charset) self._payload = content + + +def _decode_rfc2231_params(params): + """RFC 2231 parameters, as email.utils.decode_params gives them: + `name*=charset'lang'%xx`, and continuations `name*0`, `name*1*`, ..., + become one (name, (charset, language, text)) entry, `text` holding the + percent-decoded bytes as latin-1 characters for collapse_rfc2231_value + to decode. The entry takes the place of the first part seen.""" + from urllib.parse import unquote as _pct + out = [] + parts = {} + order = [] + for k, v in params: + if "*" not in k or not out: + out.append((k, v)) + continue + name, _, rest = k.partition("*") + encoded = k.endswith("*") + num = rest[:-1] if encoded else rest + if num and not num.isdigit(): + out.append((k, v)) + continue + if name not in parts: + parts[name] = [] + order.append(name) + out.append((name, None)) + parts[name].append((int(num) if num else 0, encoded, v)) + for name in order: + segs = sorted(parts[name], key=lambda x: x[0]) + charset = language = None + text = [] + for n, encoded, v in segs: + if encoded: + if n == 0 and v.count("'") >= 2: + charset, language, v = v.split("'", 2) + v = _pct(v, encoding="latin-1") + text.append(v) + joined = "".join(text) + value = (charset or "", language or "", joined) if any(e for _, e, _ in segs) else joined + for i, (k, v) in enumerate(out): + if k == name and v is None: + out[i] = (name, value) + break + return out + diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/email/utils.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/email/utils.py new file mode 100644 index 00000000000..ef3f6b573a4 --- /dev/null +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/email/utils.py @@ -0,0 +1,311 @@ +# Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. +# Licensed under the GNU General Public License version 2 with the Classpath +# exception, as the rest of the Codename One Python runtime. +"""email.utils: RFC 2822 dates and addresses -- what HTTP clients read a +Retry-After or Date header with, and what mail-building code formats.""" + +import calendar as _calendar +import datetime as _dt +import time as _time + +_MONTHS = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"] +_DAYS = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"] +_ZONES = {"UT": 0, "UTC": 0, "GMT": 0, "Z": 0, "AST": -400, "ADT": -300, "EST": -500, "EDT": -400, + "CST": -600, "CDT": -500, "MST": -700, "MDT": -600, "PST": -800, "PDT": -700} + + +def _parsedate_tz(data): + if not data: + return None + data = data.split() + if not data: + return None + if data[0].endswith(",") or data[0].lower() in _DAYS: + del data[0] + else: + i = data[0].rfind(",") + if i >= 0: + data[0] = data[0][i + 1:] + if len(data) == 3: + stuff = data[0].split("-") + if len(stuff) == 3: + data = stuff + data[1:] + if len(data) == 4: + s = data[3] + i = s.find("+") + if i == -1: + i = s.find("-") + if i > 0: + data[3:] = [s[:i], s[i:]] + else: + data.append("") + if len(data) < 5: + return None + data = data[:5] + dd, mm, yy, tm, tz = data + if not (dd and mm and yy): + return None + mm = mm.lower() + if mm not in _MONTHS: + dd, mm = mm, dd.lower() + if mm not in _MONTHS: + return None + mm = _MONTHS.index(mm) + 1 + if mm > 12: + mm -= 12 + if dd[-1] == ",": + dd = dd[:-1] + i = yy.find(":") + if i > 0: + yy, tm = tm, yy + if yy[-1] == ",": + yy = yy[:-1] + if not yy: + return None + if not yy[0].isdigit(): + yy, tz = tz, yy + if tm[-1:] == ",": + tm = tm[:-1] + tm = tm.split(":") + if len(tm) == 2: + thh, tmm = tm + tss = "0" + elif len(tm) == 3: + thh, tmm, tss = tm + elif len(tm) == 1 and "." in tm[0]: + tm = tm[0].split(".") + if len(tm) == 2: + thh, tmm = tm + tss = 0 + elif len(tm) == 3: + thh, tmm, tss = tm + else: + return None + else: + return None + try: + yy = int(yy) + dd = int(dd) + thh = int(thh) + tmm = int(tmm) + tss = int(tss) + except ValueError: + return None + if yy < 100: + yy += 1900 if yy > 68 else 2000 + tzoffset = None + tz = tz.upper() + if tz in _ZONES: + tzoffset = _ZONES[tz] + else: + try: + tzoffset = int(tz) + except ValueError: + pass + if tzoffset == 0 and tz.startswith("-"): + tzoffset = None + if tzoffset: + sign = -1 if tzoffset < 0 else 1 + tzoffset = abs(tzoffset) + tzoffset = sign * ((tzoffset // 100) * 3600 + (tzoffset % 100) * 60) + return [yy, mm, dd, thh, tmm, tss, 0, 1, -1, tzoffset] + + +def parsedate_tz(data): + t = _parsedate_tz(data) + if isinstance(t, list): + t = tuple(t) + return t + + +def parsedate(data): + t = parsedate_tz(data) + return t[:9] if isinstance(t, tuple) else t + + +def mktime_tz(data): + if data[9] is None: + return _time.mktime(data[:8] + (-1,)) + return _calendar.timegm(data) - data[9] + + +def parsedate_to_datetime(data): + parsed = _parsedate_tz(data) + if parsed is None: + raise ValueError("Invalid date value or format %r" % (str(data),)) + *dtuple, tz = parsed + if tz is None: + return _dt.datetime(*dtuple[:6]) + return _dt.datetime(*dtuple[:6], tzinfo=_dt.timezone(_dt.timedelta(seconds=tz))) + + +def _format_timetuple_and_zone(timetuple, zone): + return "%s, %02d %s %04d %02d:%02d:%02d %s" % ( + ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"][timetuple[6]], timetuple[2], + ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"][timetuple[1] - 1], + timetuple[0], timetuple[3], timetuple[4], timetuple[5], zone) + + +def formatdate(timeval=None, localtime=False, usegmt=False): + if timeval is None: + timeval = _time.time() + d = _dt.datetime.fromtimestamp(timeval, _dt.timezone.utc) + if localtime: + d = d.astimezone() + usegmt = False + return format_datetime(d, usegmt) + + +def format_datetime(dt, usegmt=False): + now = dt.timetuple() + if usegmt: + if dt.tzinfo is None or dt.tzinfo != _dt.timezone.utc: + raise ValueError("usegmt option requires a UTC datetime") + zone = "GMT" + elif dt.tzinfo is None: + zone = "-0000" + else: + off = dt.utcoffset() + secs = int(off.total_seconds()) + sign = "-" if secs < 0 else "+" + secs = abs(secs) + zone = "%s%02d%02d" % (sign, secs // 3600, (secs // 60) % 60) + return _format_timetuple_and_zone(now, zone) + + +def localtime(dt=None, isdst=-1): + if dt is None: + return _dt.datetime.now(_dt.timezone.utc).astimezone() + if dt.tzinfo is not None: + return dt.astimezone() + return dt.astimezone() + + +def quote(s): + return s.replace("\\", "\\\\").replace('"', '\\"') + + +def unquote(s): + if len(s) > 1: + if s.startswith('"') and s.endswith('"'): + return s[1:-1].replace("\\\\", "\\").replace('\\"', '"') + if s.startswith("<") and s.endswith(">"): + return s[1:-1] + return s + + +_SPECIALS = '()<>@,:;."[]' + + +def formataddr(pair, charset="utf-8"): + name, address = pair + address.encode("ascii") + if name: + try: + name.encode("ascii") + except UnicodeEncodeError: + import base64 + name = "=?%s?b?%s?=" % (charset, base64.b64encode(name.encode(charset)).decode("ascii")) + return "%s <%s>" % (name, address) + if any(c in _SPECIALS for c in name): + name = '"%s"' % quote(name) + return "%s <%s>" % (name, address) + return address + + +def _split_addresses(field): + out, cur, depth, quoted, esc = [], [], 0, False, False + for ch in field: + if esc: + cur.append(ch) + esc = False + continue + if ch == "\\" and quoted: + cur.append(ch) + esc = True + continue + if ch == '"': + quoted = not quoted + elif not quoted and ch in "<(": + depth += 1 + elif not quoted and ch in ">)": + depth -= 1 + elif ch == "," and not quoted and depth <= 0: + out.append("".join(cur)) + cur = [] + continue + cur.append(ch) + out.append("".join(cur)) + return out + + +def _parse_one(text): + text = text.strip() + if not text: + return ("", "") + comment = "" + while "(" in text and ")" in text and text.rfind(")") > text.find("("): + a, b = text.find("("), text.rfind(")") + comment = text[a + 1:b].strip() + text = (text[:a] + text[b + 1:]).strip() + if "<" in text and text.endswith(">"): + i = text.rfind("<") + name = unquote(text[:i].strip()) + return (name, text[i + 1:-1].strip()) + if " " in text and "@" not in text: + return ("", "") + return (comment, text.replace(" ", "")) + + +def parseaddr(addr, *, strict=True): + if not isinstance(addr, str): + addr = str(addr) + parts = [p for p in _split_addresses(addr) if p.strip()] + if len(parts) != 1: + return ("", "") if parts else ("", "") + return _parse_one(parts[0]) + + +def getaddresses(fieldvalues, *, strict=True): + out = [] + for v in fieldvalues: + for p in _split_addresses(str(v)): + if p.strip(): + out.append(_parse_one(p)) + return out + + +def make_msgid(idstring=None, domain=None): + import random + t = int(_time.time() * 100) + pid = 1 + r = random.getrandbits(64) + idstring = "" if idstring is None else "." + idstring + return "<%d.%d.%d%s@%s>" % (t, pid, r, idstring, domain or "localhost") + + +def decode_rfc2231(s): + parts = s.split("'", 2) + if len(parts) <= 2: + return None, None, s + return parts + + +def encode_rfc2231(s, charset=None, language=None): + from urllib.parse import quote as _q + s = _q(s, safe="", encoding=charset or "ascii") + if charset is None and language is None: + return s + return "%s'%s'%s" % (charset or "", language or "", s) + + +def collapse_rfc2231_value(value, errors="replace", fallback_charset="us-ascii"): + if not isinstance(value, tuple) or len(value) != 3: + return unquote(value) + charset, language, text = value + # text holds the parameter's bytes as latin-1 characters (get_params + # decoded the percent escapes); an unknown charset gives them back as is + try: + return text.encode("latin-1", "replace").decode(charset or fallback_charset, errors) + except LookupError: + return unquote(text) diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/encodings/__init__.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/encodings/__init__.py new file mode 100644 index 00000000000..0ed20d1b946 --- /dev/null +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/encodings/__init__.py @@ -0,0 +1,45 @@ +# Copyright (c) 2001 Python Software Foundation; All Rights Reserved +# Licensed under the Python Software Foundation License Version 2; the full +# text is in maven/python-transpiler/third-party/cpython/LICENSE.txt. +# +# Derived from CPython's Lib/encodings/__init__.py. Changes: rewritten for the Codename One +# Python runtime, trimmed to what the transpiler supports and reorganised; +# the C accelerators and platform-specific branches are left out. +"""encodings: the codec package. Codename One supports UTF-8, ASCII and +Latin-1 only (see codecs), so the package holds those codecs' modules and an +alias table naming nothing else. Code that walks the table to try every +encoding -- charset_normalizer does -- therefore tries only these.""" + +import codecs + +from encodings import aliases as _aliases_module + + +class CodecRegistryError(LookupError, SystemError): + pass + + +def normalize_encoding(encoding): + if isinstance(encoding, bytes): + encoding = str(encoding, "ascii") + chars = [] + punct = False + for c in encoding: + if c.isalnum() or c == ".": + if punct and chars: + chars.append("_") + if c.isascii(): + chars.append(c) + punct = False + else: + punct = True + return "".join(chars) + + +def search_function(encoding): + norm = normalize_encoding(encoding).lower() + name = _aliases_module.aliases.get(norm, norm) + try: + return codecs.lookup(name) + except LookupError: + return None diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/encodings/aliases.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/encodings/aliases.py new file mode 100644 index 00000000000..35cc1055b02 --- /dev/null +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/encodings/aliases.py @@ -0,0 +1,38 @@ +# Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. +# Licensed under the GNU General Public License version 2 with the Classpath +# exception, as the rest of the Codename One Python runtime. +"""encodings.aliases: normalized alias -> codec module name, for the +codecs Codename One supports.""" + +aliases = { + "646": "ascii", + "ansi_x3.4_1968": "ascii", + "ansi_x3_4_1968": "ascii", + "ansi_x3.4_1986": "ascii", + "cp367": "ascii", + "csascii": "ascii", + "ibm367": "ascii", + "iso646_us": "ascii", + "iso_646.irv_1991": "ascii", + "iso_ir_6": "ascii", + "us": "ascii", + "us_ascii": "ascii", + "8859": "latin_1", + "cp819": "latin_1", + "csisolatin1": "latin_1", + "ibm819": "latin_1", + "iso8859": "latin_1", + "iso8859_1": "latin_1", + "iso_8859_1": "latin_1", + "iso_8859_1_1987": "latin_1", + "iso_ir_100": "latin_1", + "l1": "latin_1", + "latin": "latin_1", + "latin1": "latin_1", + "u8": "utf_8", + "utf": "utf_8", + "utf8": "utf_8", + "utf8_ucs2": "utf_8", + "utf8_ucs4": "utf_8", + "cp65001": "utf_8", +} diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/encodings/ascii.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/encodings/ascii.py new file mode 100644 index 00000000000..4062114b2b2 --- /dev/null +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/encodings/ascii.py @@ -0,0 +1,23 @@ +# Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. +# Licensed under the GNU General Public License version 2 with the Classpath +# exception, as the rest of the Codename One Python runtime. +"""encodings.ascii: the ascii codec.""" + +import codecs + +_info = codecs.lookup("ascii") + +IncrementalEncoder = _info.incrementalencoder +IncrementalDecoder = _info.incrementaldecoder + + +def encode(input, errors="strict"): + return _info.encode(input, errors) + + +def decode(input, errors="strict"): + return _info.decode(input, errors) + + +def getregentry(): + return _info diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/encodings/latin_1.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/encodings/latin_1.py new file mode 100644 index 00000000000..37a4c4b27e4 --- /dev/null +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/encodings/latin_1.py @@ -0,0 +1,23 @@ +# Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. +# Licensed under the GNU General Public License version 2 with the Classpath +# exception, as the rest of the Codename One Python runtime. +"""encodings.latin_1: the latin-1 codec.""" + +import codecs + +_info = codecs.lookup("latin-1") + +IncrementalEncoder = _info.incrementalencoder +IncrementalDecoder = _info.incrementaldecoder + + +def encode(input, errors="strict"): + return _info.encode(input, errors) + + +def decode(input, errors="strict"): + return _info.decode(input, errors) + + +def getregentry(): + return _info diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/encodings/utf_8.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/encodings/utf_8.py new file mode 100644 index 00000000000..026e8bbd87e --- /dev/null +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/encodings/utf_8.py @@ -0,0 +1,23 @@ +# Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. +# Licensed under the GNU General Public License version 2 with the Classpath +# exception, as the rest of the Codename One Python runtime. +"""encodings.utf_8: the utf-8 codec.""" + +import codecs + +_info = codecs.lookup("utf-8") + +IncrementalEncoder = _info.incrementalencoder +IncrementalDecoder = _info.incrementaldecoder + + +def encode(input, errors="strict"): + return _info.encode(input, errors) + + +def decode(input, errors="strict"): + return _info.decode(input, errors) + + +def getregentry(): + return _info diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/encodings/utf_8_sig.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/encodings/utf_8_sig.py new file mode 100644 index 00000000000..731d337990d --- /dev/null +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/encodings/utf_8_sig.py @@ -0,0 +1,23 @@ +# Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. +# Licensed under the GNU General Public License version 2 with the Classpath +# exception, as the rest of the Codename One Python runtime. +"""encodings.utf_8_sig: the utf-8-sig codec.""" + +import codecs + +_info = codecs.lookup("utf-8-sig") + +IncrementalEncoder = _info.incrementalencoder +IncrementalDecoder = _info.incrementaldecoder + + +def encode(input, errors="strict"): + return _info.encode(input, errors) + + +def decode(input, errors="strict"): + return _info.decode(input, errors) + + +def getregentry(): + return _info diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/enum.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/enum.py index cb33f065871..63c67844956 100644 --- a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/enum.py +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/enum.py @@ -9,6 +9,7 @@ _MIXINS = (int, str, float, bytes) builtins_property = property +from _cn1op import EnumType, enum_install # The library's own bases, whose __new__ never builds a member. _BASES = [] @@ -66,199 +67,130 @@ def _mixin_of(bases): return None -class EnumType(type): - @classmethod - def __prepare__(metacls, cls, bases, **kwds): - return {} - - def __new__(metacls, cls, bases, classdict, *, boundary=None, _simple=False, **kwds): - enum_class = super().__new__(metacls, cls, bases, classdict, **kwds) - type.__setattr__(enum_class, "_member_names_", []) - type.__setattr__(enum_class, "_member_map_", {}) - type.__setattr__(enum_class, "_value2member_map_", {}) - type.__setattr__(enum_class, "_unhashable_values_", []) - mixin = _mixin_of(bases) - type.__setattr__(enum_class, "_member_type_", mixin if mixin is not None else object) - flag = Flag is not None and any(isinstance(b, EnumType) and issubclass(b, Flag) for b in bases) - type.__setattr__(enum_class, "_is_flag_", flag) - type.__setattr__(enum_class, "_boundary_", boundary) - if any(isinstance(b, EnumType) and b._member_names_ for b in bases): - raise TypeError( - " cannot extend %s" % (cls, ", ".join("" % b.__name__ for b in bases - if isinstance(b, EnumType) and b._member_names_))) - last_values = [] - all_bits = 0 - for name, value in list(classdict.items()): - if isinstance(value, nonmember): - type.__setattr__(enum_class, name, value.value) - continue - if isinstance(value, member): - value = value.value - elif _is_dunder(name) or _is_sunder(name) or _is_private(cls, name) or _is_descriptor(value): +# EnumType is the runtime's own metaclass (runtime class EnumMeta), as +# ABCMeta is abc's: a class it makes is an ordinary class with a layout, and +# its class-level protocol (call, iteration, in, len, [name], __members__) is +# Java over the tables below. Right after making one, the runtime calls +# _finish, which sets those tables up; the compiler then defines every +# member once, in definition order (_member). + + +def _finish(enum_class, boundary): + cls = enum_class.__name__ + bases = enum_class.__bases__ + type.__setattr__(enum_class, "_member_names_", []) + type.__setattr__(enum_class, "_member_map_", {}) + type.__setattr__(enum_class, "_value2member_map_", {}) + type.__setattr__(enum_class, "_unhashable_values_", []) + mixin = _mixin_of(bases) + type.__setattr__(enum_class, "_member_type_", mixin if mixin is not None else object) + flag = len(_FLAG) > 0 and any(isinstance(b, EnumType) and issubclass(b, _FLAG[0]) for b in bases) + type.__setattr__(enum_class, "_is_flag_", flag) + type.__setattr__(enum_class, "_boundary_", boundary) + if any(isinstance(b, EnumType) and b._member_names_ for b in bases): + raise TypeError( + " cannot extend %s" % (cls, ", ".join("" % b.__name__ for b in bases + if isinstance(b, EnumType) and b._member_names_))) + type.__setattr__(enum_class, "_last_values_", []) + for name, value in enum_class.__dict__.items(): + if not (_is_dunder(name) or _is_sunder(name) or _is_private(cls, name) or _is_descriptor(value)): + # The compiler defines every member after the class statement + # (EnumLowering); a value left in the body is one it missed. + raise TypeError("enum %s: member %r was not defined by the compiler" % (cls, name)) + if mixin is not None: + # The mixin type comes first in the MRO, so its __repr__ and + # __str__ would shadow the enum's: take the nearest enum's own. Its + # hash stays the mixin's, as the MRO has it. + for dunder in ("__repr__", "__str__", "__format__"): + if dunder in enum_class.__dict__: continue - if name in enum_class._member_map_: - raise TypeError("%r already defined as %r" % (name, enum_class._member_map_[name])) - if isinstance(value, auto): - if value.value is None: - value = enum_class._generate_next_value_(name, 1, len(enum_class._member_names_), - last_values[:]) - else: - value = value.value - elif isinstance(value, tuple) and any(isinstance(v, auto) for v in value): - value = tuple(enum_class._generate_next_value_(name, 1, len(enum_class._member_names_), - last_values[:]) if isinstance(v, auto) else v - for v in value) - last_values.append(value) - m = metacls._make_member(enum_class, name, value, mixin) - canonical = None - for other in enum_class._member_names_: - o = enum_class._member_map_[other] - if o._value_ == m._value_: - canonical = o + for k in enum_class.__mro__: + if isinstance(k, EnumType) and dunder in k.__dict__: + type.__setattr__(enum_class, dunder, k.__dict__[dunder]) break - if canonical is not None: - m = canonical - else: - enum_class._member_names_.append(name) - if flag and isinstance(m._value_, int): - all_bits |= m._value_ - enum_class._member_map_[name] = m - try: - enum_class._value2member_map_.setdefault(m._value_, m) - except TypeError: - enum_class._unhashable_values_.append(m._value_) - type.__setattr__(enum_class, name, m) - if mixin is not None: - # The mixin type comes first in the MRO, so its __repr__ and - # __str__ would shadow the enum's: take the nearest enum's own. - for dunder in ("__repr__", "__str__", "__format__"): - if dunder in classdict: - continue - for k in enum_class.__mro__: - if isinstance(k, EnumType) and dunder in k.__dict__: - type.__setattr__(enum_class, dunder, k.__dict__[dunder]) - break - type.__setattr__(enum_class, "_flag_mask_", all_bits) - type.__setattr__(enum_class, "_all_bits_", all_bits) - return enum_class - - @staticmethod - def _make_member(enum_class, name, value, mixin): - args = value if isinstance(value, tuple) else (value,) - custom_new = enum_class.__dict__.get("_new_member_", None) - new = None - for k in enum_class.__mro__: - if "__new__" in k.__dict__ and k not in _BASES and k is not object: - if k not in _MIXINS: - new = k.__dict__["__new__"] - break - if new is not None: - m = new(enum_class, *args) - elif mixin is None: - m = object.__new__(enum_class) + if "__hash__" not in enum_class.__dict__: + type.__setattr__(enum_class, "__hash__", mixin.__hash__) + type.__setattr__(enum_class, "_flag_mask_", 0) + type.__setattr__(enum_class, "_all_bits_", 0) + + +def _make_member(enum_class, name, value, mixin): + args = value if isinstance(value, tuple) else (value,) + new = None + for k in enum_class.__mro__: + if "__new__" in k.__dict__ and k not in _BASES and k is not object: + if k not in _MIXINS: + new = k.__dict__["__new__"] + break + if new is not None: + m = new(enum_class, *args) + elif mixin is None: + m = object.__new__(enum_class) + else: + m = mixin.__new__(enum_class, *args) + if not hasattr(m, "_value_"): + if mixin is None: + m._value_ = value else: - m = mixin.__new__(enum_class, *args) - if not hasattr(m, "_value_"): - if mixin is None: - m._value_ = value - else: - m._value_ = mixin(*args) - m._name_ = name - m._sort_order_ = len(enum_class._member_names_) - init = getattr(enum_class, "__init__", None) - if init is not None and init is not Enum.__init__: - m.__init__(*args) - return m - - def __call__(cls, value, names=None, *values, module=None, qualname=None, type=None, start=1, boundary=None): - if names is None: - return cls.__new_member_lookup__(value) - return cls._create_(value, names, module=module, qualname=qualname, type=type, start=start, - boundary=boundary) - - def __new_member_lookup__(cls, value): - if isinstance(value, cls): - return value - try: - return cls._value2member_map_[value] - except (KeyError, TypeError): - pass - for m in cls._member_map_.values(): - if m._value_ == value: - return m - result = cls._missing_(value) - if isinstance(result, cls): - return result - if result is None: - raise ValueError("%r is not a valid %s" % (value, cls.__qualname__)) - raise TypeError("error in %s._missing_: returned %r instead of None or a valid member" - % (cls.__name__, result)) - - def _create_(cls, class_name, names, *, module=None, qualname=None, type=None, start=1, boundary=None): - bases = (cls,) if type is None else (type, cls) - classdict = {} - if isinstance(names, str): - names = names.replace(",", " ").split() - if isinstance(names, (tuple, list)) and names and isinstance(names[0], str): - original, names, last = names, [], [] - for count, name in enumerate(original): - value = cls._generate_next_value_(name, start, count, last[:]) - last.append(value) - names.append((name, value)) - if isinstance(names, dict): - names = list(names.items()) - for name, value in names: - classdict[name] = value - return EnumType(class_name, bases, classdict, boundary=boundary) - - def __contains__(cls, value): - if isinstance(value, cls): - return True - try: - if value in cls._value2member_map_: - return True - except TypeError: - pass - return value in cls._unhashable_values_ - - def __delattr__(cls, attr): - if attr in cls._member_map_: - raise AttributeError("%r cannot delete member %r." % (cls.__name__, attr)) - super().__delattr__(attr) - - def __getitem__(cls, name): - return cls._member_map_[name] - - def __iter__(cls): - return (cls._member_map_[name] for name in cls._member_names_) - - def __reversed__(cls): - return (cls._member_map_[name] for name in reversed(cls._member_names_)) - - def __len__(cls): - return len(cls._member_names_) - - def __bool__(cls): - return True - - @builtins_property - def __members__(cls): - return dict(cls._member_map_) - - def __repr__(cls): - if Flag is not None and issubclass(cls, Flag): - return "" % cls.__name__ - return "" % cls.__name__ - - def __setattr__(cls, name, value): - member_map = cls.__dict__.get("_member_map_", {}) - if name in member_map: - raise AttributeError("cannot reassign member %r" % (name,)) - super().__setattr__(name, value) + m._value_ = mixin(*args) + m._name_ = name + m._sort_order_ = len(enum_class._member_names_) + init = getattr(enum_class, "__init__", None) + if init is not None and init is not Enum.__init__: + # The function found on the class, called with the member: what + # m.__init__(*args) runs, but read off the class, which only a + # loose class's __init__ can answer -- through the member, any + # __init__ of the program could. + init(m, *args) + return m + + +def _member(enum_class, name, value): + """Defines member `name` of `value`: the compiler calls it once per + member, in definition order, right after the class statement.""" + if name in enum_class._member_map_: + raise TypeError("%r already defined as %r" % (name, enum_class._member_map_[name])) + last_values = enum_class._last_values_ + if isinstance(value, auto): + if value.value is None: + value = enum_class._generate_next_value_(name, 1, len(enum_class._member_names_), last_values[:]) + else: + value = value.value + elif isinstance(value, tuple) and any(isinstance(v, auto) for v in value): + value = tuple(enum_class._generate_next_value_(name, 1, len(enum_class._member_names_), + last_values[:]) if isinstance(v, auto) else v + for v in value) + last_values.append(value) + m = _make_member(enum_class, name, value, _mixin_of(enum_class.__bases__)) + canonical = None + for other in enum_class._member_names_: + o = enum_class._member_map_[other] + if o._value_ == m._value_: + canonical = o + break + if canonical is not None: + m = canonical + else: + enum_class._member_names_.append(name) + if enum_class._is_flag_ and isinstance(m._value_, int): + bits = enum_class._all_bits_ | m._value_ + type.__setattr__(enum_class, "_flag_mask_", bits) + type.__setattr__(enum_class, "_all_bits_", bits) + enum_class._member_map_[name] = m + try: + enum_class._value2member_map_.setdefault(m._value_, m) + except TypeError: + enum_class._unhashable_values_.append(m._value_) + return m + + +enum_install(_finish) EnumMeta = EnumType -Flag = None +# Flag once it exists; a list, so the name Flag is bound once (by its class) +# and keeps a layout its subclasses extend. +_FLAG = [] class Enum(metaclass=EnumType): @@ -330,13 +262,17 @@ def __format__(self, format_spec): class IntEnum(int, ReprEnum): - pass + __str__ = ReprEnum.__str__ + __format__ = ReprEnum.__format__ _BASES.extend((ReprEnum, IntEnum)) class StrEnum(str, ReprEnum): + __str__ = ReprEnum.__str__ + __format__ = ReprEnum.__format__ + @staticmethod def _generate_next_value_(name, start, count, last_values): return name.lower() @@ -473,7 +409,13 @@ def __invert__(self): __rxor__ = __xor__ -class IntFlag(int, ReprEnum, Flag, boundary=KEEP): +_FLAG.append(Flag) + + +# CPython's bases are (int, ReprEnum, Flag); ReprEnum adds only the two +# methods the body takes from it, so it is left out of the bases, which keeps +# the class to one compiled base after its builtin. +class IntFlag(int, Flag, boundary=KEEP): __str__ = ReprEnum.__str__ __format__ = ReprEnum.__format__ __repr__ = Flag.__repr__ @@ -481,6 +423,7 @@ class IntFlag(int, ReprEnum, Flag, boundary=KEEP): __and__ = __rand__ = Flag.__and__ __xor__ = __rxor__ = Flag.__xor__ __invert__ = Flag.__invert__ + __bool__ = Flag.__bool__ _BASES.extend((Flag, IntFlag)) diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/errno.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/errno.py new file mode 100644 index 00000000000..d3569813959 --- /dev/null +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/errno.py @@ -0,0 +1,127 @@ +# Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. +# Licensed under the GNU General Public License version 2 with the Classpath +# exception, as the rest of the Codename One Python runtime. +"""Symbolic error numbers. The values are Linux's on every target: no +translated program receives a raw errno from the platform, so they only have +to agree with the OSError numbers the runtime itself raises.""" + +EPERM = 1 +ENOENT = 2 +ESRCH = 3 +EINTR = 4 +EIO = 5 +ENXIO = 6 +E2BIG = 7 +ENOEXEC = 8 +EBADF = 9 +ECHILD = 10 +EAGAIN = 11 +ENOMEM = 12 +EACCES = 13 +EFAULT = 14 +ENOTBLK = 15 +EBUSY = 16 +EEXIST = 17 +EXDEV = 18 +ENODEV = 19 +ENOTDIR = 20 +EISDIR = 21 +EINVAL = 22 +ENFILE = 23 +EMFILE = 24 +ENOTTY = 25 +ETXTBSY = 26 +EFBIG = 27 +ENOSPC = 28 +ESPIPE = 29 +EROFS = 30 +EMLINK = 31 +EPIPE = 32 +EDOM = 33 +ERANGE = 34 +EDEADLK = 35 +ENAMETOOLONG = 36 +ENOLCK = 37 +ENOSYS = 38 +ENOTEMPTY = 39 +ELOOP = 40 +ENOMSG = 42 +ENOTSUP = 95 +EOPNOTSUPP = 95 +EADDRINUSE = 98 +EADDRNOTAVAIL = 99 +ENETDOWN = 100 +ENETUNREACH = 101 +ECONNABORTED = 103 +ECONNRESET = 104 +ENOBUFS = 105 +EISCONN = 106 +ENOTCONN = 107 +ETIMEDOUT = 110 +ECONNREFUSED = 111 +EHOSTUNREACH = 113 +EALREADY = 114 +EINPROGRESS = 115 +ECANCELED = 125 +EWOULDBLOCK = 11 +EDEADLOCK = 35 + +errorcode = { + 1: "EPERM", + 2: "ENOENT", + 3: "ESRCH", + 4: "EINTR", + 5: "EIO", + 6: "ENXIO", + 7: "E2BIG", + 8: "ENOEXEC", + 9: "EBADF", + 10: "ECHILD", + 11: "EAGAIN", + 12: "ENOMEM", + 13: "EACCES", + 14: "EFAULT", + 15: "ENOTBLK", + 16: "EBUSY", + 17: "EEXIST", + 18: "EXDEV", + 19: "ENODEV", + 20: "ENOTDIR", + 21: "EISDIR", + 22: "EINVAL", + 23: "ENFILE", + 24: "EMFILE", + 25: "ENOTTY", + 26: "ETXTBSY", + 27: "EFBIG", + 28: "ENOSPC", + 29: "ESPIPE", + 30: "EROFS", + 31: "EMLINK", + 32: "EPIPE", + 33: "EDOM", + 34: "ERANGE", + 35: "EDEADLK", + 36: "ENAMETOOLONG", + 37: "ENOLCK", + 38: "ENOSYS", + 39: "ENOTEMPTY", + 40: "ELOOP", + 42: "ENOMSG", + 95: "ENOTSUP", + 98: "EADDRINUSE", + 99: "EADDRNOTAVAIL", + 100: "ENETDOWN", + 101: "ENETUNREACH", + 103: "ECONNABORTED", + 104: "ECONNRESET", + 105: "ENOBUFS", + 106: "EISCONN", + 107: "ENOTCONN", + 110: "ETIMEDOUT", + 111: "ECONNREFUSED", + 113: "EHOSTUNREACH", + 114: "EALREADY", + 115: "EINPROGRESS", + 125: "ECANCELED", +} diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/fractions.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/fractions.py index adbc7d95a5d..5f2ee83d4f4 100644 --- a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/fractions.py +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/fractions.py @@ -1,6 +1,9 @@ -# Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. -# Licensed under the GNU General Public License version 2 with the Classpath -# exception, as the rest of the Codename One Python runtime. +# Copyright (c) 2001 Python Software Foundation; All Rights Reserved +# Licensed under the Python Software Foundation License Version 2; the full +# text is in maven/python-transpiler/third-party/cpython/LICENSE.txt. +# +# Derived from CPython's Lib/fractions.py. Changes: rewritten for the Codename One Python runtime, trimmed to what the +# transpiler supports. """Rational numbers.""" import math diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/functools.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/functools.py index ba7078a795e..2970c4b0cd4 100644 --- a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/functools.py +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/functools.py @@ -7,6 +7,8 @@ WRAPPER_UPDATES = ("__dict__",) _MISSING = object() +from _cn1functools import _lru_cache_wrapper + def reduce(function, iterable, initial=_MISSING): it = iter(iterable) @@ -23,6 +25,7 @@ def reduce(function, iterable, initial=_MISSING): class partial: + __class_getitem__ = classmethod(type(list[int])) def __init__(self, func, *args, **keywords): if not callable(func): raise TypeError("the first argument must be callable") @@ -56,13 +59,38 @@ def __repr__(self): def update_wrapper(wrapper, wrapped, assigned=WRAPPER_ASSIGNMENTS, updated=WRAPPER_UPDATES): + # Each attribute by its own name: a computed getattr/setattr cannot be + # typed, and these are the only names a wrapper is given. A name + # outside them is refused rather than copied blind. for attr in assigned: + if attr not in WRAPPER_ASSIGNMENTS: + raise TypeError("update_wrapper copies only " + repr(WRAPPER_ASSIGNMENTS)) + for attr in updated: + if attr not in WRAPPER_UPDATES: + raise TypeError("update_wrapper updates only " + repr(WRAPPER_UPDATES)) + if "__module__" in assigned: + try: + wrapper.__module__ = wrapped.__module__ + except (AttributeError, TypeError): + pass + if "__name__" in assigned: try: - value = getattr(wrapped, attr) - except AttributeError: - continue + wrapper.__name__ = wrapped.__name__ + except (AttributeError, TypeError): + pass + if "__qualname__" in assigned: try: - setattr(wrapper, attr, value) + wrapper.__qualname__ = wrapped.__qualname__ + except (AttributeError, TypeError): + pass + if "__doc__" in assigned: + try: + wrapper.__doc__ = wrapped.__doc__ + except (AttributeError, TypeError): + pass + if "__dict__" in updated: + try: + wrapper.__dict__.update(wrapped.__dict__) except (AttributeError, TypeError): pass wrapper.__wrapped__ = wrapped @@ -101,26 +129,37 @@ def __ge__(self, other): return K +def _own(own, base): + return own is not None and own is not base + + def total_ordering(cls): - def has(name): - own = cls.__dict__.get(name) - return own is not None and own is not getattr(object, name, None) - roots = [op for op in ("__lt__", "__le__", "__gt__", "__ge__") if has(op)] + # Every name is written out: no getattr or setattr with a computed name. + d = cls.__dict__ + roots = [] + if _own(d.get("__lt__"), getattr(object, "__lt__", None)): + roots.append("__lt__") + if _own(d.get("__le__"), getattr(object, "__le__", None)): + roots.append("__le__") + if _own(d.get("__gt__"), getattr(object, "__gt__", None)): + roots.append("__gt__") + if _own(d.get("__ge__"), getattr(object, "__ge__", None)): + roots.append("__ge__") if not roots: raise ValueError("must define at least one ordering operation: < > <= >=") root = roots[0] def lt_from(self, other): - r = getattr(self, root)(other) - if r is NotImplemented: - return r if root == "__lt__": - return r + return self.__lt__(other) if root == "__le__": - return r and self != other + r = self.__le__(other) + return r if r is NotImplemented else (r and self != other) if root == "__gt__": - return not r and self != other - return not r + r = self.__gt__(other) + return r if r is NotImplemented else (not r and self != other) + r = self.__ge__(other) + return r if r is NotImplemented else not r def le(self, other): r = lt_from(self, other) @@ -134,9 +173,14 @@ def ge(self, other): r = lt_from(self, other) return r if r is NotImplemented else not r - for name, fn in (("__lt__", lt_from), ("__le__", le), ("__gt__", gt), ("__ge__", ge)): - if name not in roots: - setattr(cls, name, fn) + if "__lt__" not in roots: + cls.__lt__ = lt_from + if "__le__" not in roots: + cls.__le__ = le + if "__gt__" not in roots: + cls.__gt__ = gt + if "__ge__" not in roots: + cls.__ge__ = ge return cls @@ -144,28 +188,25 @@ class _CacheInfo(tuple): def __new__(cls, hits, misses, maxsize, currsize): return tuple.__new__(cls, (hits, misses, maxsize, currsize)) - hits = property(lambda self: self[0]) - misses = property(lambda self: self[1]) - maxsize = property(lambda self: self[2]) - currsize = property(lambda self: self[3]) + @property + def hits(self): + return self[0] - def __repr__(self): - return "CacheInfo(hits=%r, misses=%r, maxsize=%r, currsize=%r)" % tuple(self) + @property + def misses(self): + return self[1] + + @property + def maxsize(self): + return self[2] + + @property + def currsize(self): + return self[3] -def _make_key(args, kwds, typed): - key = args - if kwds: - key = key + (_MISSING,) - for item in kwds.items(): - key = key + item - if typed: - key = key + tuple(type(v) for v in args) - if kwds: - key = key + tuple(type(v) for v in kwds.values()) - elif len(key) == 1 and type(key[0]) in (int, str): - return key[0] - return key + def __repr__(self): + return "CacheInfo(hits=%r, misses=%r, maxsize=%r, currsize=%r)" % tuple(self) def lru_cache(maxsize=128, typed=False): @@ -175,34 +216,8 @@ def lru_cache(maxsize=128, typed=False): maxsize = 0 def decorating(user_function): - cache = {} - stats = [0, 0] - - def wrapper(*args, **kwds): - key = _make_key(args, kwds, typed) - if key in cache: - stats[0] += 1 - result = cache.pop(key) - cache[key] = result - return result - stats[1] += 1 - result = user_function(*args, **kwds) - if maxsize != 0: - cache[key] = result - if maxsize is not None and len(cache) > maxsize: - del cache[next(iter(cache))] - return result - - def cache_info(): - return _CacheInfo(stats[0], stats[1], maxsize, len(cache)) - - def cache_clear(): - cache.clear() - stats[0] = 0 - stats[1] = 0 - - wrapper.cache_info = cache_info - wrapper.cache_clear = cache_clear + wrapper = _lru_cache_wrapper(user_function, maxsize, typed, _CacheInfo) + wrapper.cache_parameters = lambda: {"maxsize": maxsize, "typed": typed} return update_wrapper(wrapper, user_function) return decorating @@ -212,6 +227,7 @@ def cache(user_function): class cached_property: + __class_getitem__ = classmethod(type(list[int])) def __init__(self, func): self.func = func self.attrname = None diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/gettext.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/gettext.py new file mode 100644 index 00000000000..0db5f3d77eb --- /dev/null +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/gettext.py @@ -0,0 +1,85 @@ +# Copyright (c) 2001 Python Software Foundation; All Rights Reserved +# Licensed under the Python Software Foundation License Version 2; the full +# text is in maven/python-transpiler/third-party/cpython/LICENSE.txt. +# +# Derived from CPython's Lib/gettext.py. Changes: rewritten for the Codename One +# Python runtime, trimmed to what the transpiler supports and reorganised; +# the C accelerators and platform-specific branches are left out. +"""Message catalogs. A translated program ships no .mo files, so every +lookup answers the message it was given, as CPython does when no catalog is +found; an application localizes through Codename One's resource bundles.""" + + +class NullTranslations: + def __init__(self, fp=None): + self._fallback = None + + def add_fallback(self, fallback): + self._fallback = fallback + + def gettext(self, message): + return message + + def ngettext(self, msgid1, msgid2, n): + return msgid1 if n == 1 else msgid2 + + def pgettext(self, context, message): + return message + + def npgettext(self, context, msgid1, msgid2, n): + return msgid1 if n == 1 else msgid2 + + def info(self): + return {} + + def charset(self): + return None + + def install(self, names=None): + import builtins + builtins._ = self.gettext + + +GNUTranslations = NullTranslations + + +def translation(domain, localedir=None, languages=None, fallback=False): + if fallback: + return NullTranslations() + raise FileNotFoundError(2, "No translation file found for domain", domain) + + +def install(domain, localedir=None, names=None): + NullTranslations().install(names) + + +def textdomain(domain=None): + return domain or "messages" + + +def bindtextdomain(domain, localedir=None): + return localedir + + +def gettext(message): + return message + + +def dgettext(domain, message): + return message + + +def ngettext(msgid1, msgid2, n): + return msgid1 if n == 1 else msgid2 + + +def dngettext(domain, msgid1, msgid2, n): + return msgid1 if n == 1 else msgid2 + + +def pgettext(context, message): + return message + + +def npgettext(context, msgid1, msgid2, n): + return msgid1 if n == 1 else msgid2 diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/hashlib.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/hashlib.py index c9bcaeb0713..4e027128b12 100644 --- a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/hashlib.py +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/hashlib.py @@ -1,288 +1,144 @@ # Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. # Licensed under the GNU General Public License version 2 with the Classpath # exception, as the rest of the Codename One Python runtime. -"""Message digests: MD5 (RFC 1321), SHA-1 and the SHA-2 family (FIPS 180-4).""" +"""Message digests: MD5 (RFC 1321), SHA-1 and the SHA-2 family (FIPS 180-4) and +BLAKE2 (RFC 7693), computed by the runtime's _cn1hash.""" -__all__ = ["md5", "sha1", "sha224", "sha256", "sha384", "sha512", "new", "algorithms_available", +__all__ = ["md5", "sha1", "sha224", "sha256", "sha384", "sha512", "blake2b", "blake2s", "new", "algorithms_available", "algorithms_guaranteed", "pbkdf2_hmac", "file_digest"] -algorithms_guaranteed = frozenset(["md5", "sha1", "sha224", "sha256", "sha384", "sha512"]) +algorithms_guaranteed = frozenset(["md5", "sha1", "sha224", "sha256", "sha384", "sha512", "blake2b", + "blake2s"]) algorithms_available = algorithms_guaranteed -_M32 = 0xFFFFFFFF -_M64 = 0xFFFFFFFFFFFFFFFF - - -def _rotl32(x, n): - return ((x << n) | (x >> (32 - n))) & _M32 - - -def _rotr32(x, n): - return ((x >> n) | (x << (32 - n))) & _M32 - - -def _rotr64(x, n): - return ((x >> n) | (x << (64 - n))) & _M64 +import _cn1hash def _as_bytes(data): + # bytes already: handed over as it is. bytes(data) copied it, and every + # hash passes its data through here, plus the key, salt and person. + if type(data) is bytes: + return data if isinstance(data, str): raise TypeError("Strings must be encoded before hashing") return bytes(data) class _Hash: - """Buffers input into blocks and hands each full block to `_compress`.""" + """A digest whose compression function runs in the runtime (_cn1hash).""" - def __init__(self, data=b""): - self._buf = b"" - self._count = 0 - self._h = list(self._IV) + def __init__(self, data=b"", *, usedforsecurity=True): + self._s = _cn1hash.new(self.name, 0, b"", b"", b"") if data: self.update(data) def update(self, data): - data = _as_bytes(data) - self._count += len(data) - buf = self._buf + data - bs = self.block_size - n = len(buf) - len(buf) % bs - for i in range(0, n, bs): - self._compress(buf[i:i + bs]) - self._buf = buf[n:] + _cn1hash.update(self._s, _as_bytes(data)) def copy(self): c = type(self).__new__(type(self)) - c._buf = self._buf - c._count = self._count - c._h = list(self._h) + c._s = _cn1hash.copy(self._s) + if "digest_size" in self.__dict__: + c.digest_size = self.digest_size return c - def _padded(self, length_bytes, order): - bs = self.block_size - bits = self._count * 8 - tail = self._buf + b"\x80" - pad = (bs - length_bytes - len(tail)) % bs - return tail + b"\x00" * pad + bits.to_bytes(length_bytes, order) - def digest(self): - c = self.copy() - tail = c._padded(self._LEN_BYTES, self._ORDER) - for i in range(0, len(tail), self.block_size): - c._compress(tail[i:i + self.block_size]) - w = self._WORD - out = b"".join(v.to_bytes(w, self._ORDER) for v in c._h) - return out[:self.digest_size] + return _cn1hash.digest(self._s) def hexdigest(self): - return self.digest().hex() + return _cn1hash.hexdigest(self._s) class _MD5(_Hash): name = "md5" digest_size = 16 block_size = 64 - _IV = (0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476) - _LEN_BYTES = 8 - _ORDER = "little" - _WORD = 4 - _S = (7, 12, 17, 22) * 4 + (5, 9, 14, 20) * 4 + (4, 11, 16, 23) * 4 + (6, 10, 15, 21) * 4 - _K = (0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, 0xf57c0faf, 0x4787c62a, 0xa8304613, - 0xfd469501, 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, 0x6b901122, 0xfd987193, - 0xa679438e, 0x49b40821, 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, 0xd62f105d, - 0x02441453, 0xd8a1e681, 0xe7d3fbc8, 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed, - 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a, 0xfffa3942, 0x8771f681, 0x6d9d6122, - 0xfde5380c, 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70, 0x289b7ec6, 0xeaa127fa, - 0xd4ef3085, 0x04881d05, 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665, 0xf4292244, - 0x432aff97, 0xab9423a7, 0xfc93a039, 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1, - 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, - 0xeb86d391) - - def _compress(self, block): - m = [int.from_bytes(block[i:i + 4], "little") for i in range(0, 64, 4)] - a, b, c, d = self._h - for i in range(64): - if i < 16: - f = (b & c) | (~b & d) - g = i - elif i < 32: - f = (d & b) | (~d & c) - g = (5 * i + 1) % 16 - elif i < 48: - f = b ^ c ^ d - g = (3 * i + 5) % 16 - else: - f = c ^ (b | (~d & _M32)) - g = (7 * i) % 16 - f = (f + a + self._K[i] + m[g]) & _M32 - a = d - d = c - c = b - b = (b + _rotl32(f, self._S[i])) & _M32 - h = self._h - self._h = [(h[0] + a) & _M32, (h[1] + b) & _M32, (h[2] + c) & _M32, (h[3] + d) & _M32] class _SHA1(_Hash): name = "sha1" digest_size = 20 block_size = 64 - _IV = (0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0) - _LEN_BYTES = 8 - _ORDER = "big" - _WORD = 4 - - def _compress(self, block): - w = [int.from_bytes(block[i:i + 4], "big") for i in range(0, 64, 4)] - for i in range(16, 80): - w.append(_rotl32(w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16], 1)) - a, b, c, d, e = self._h - for i in range(80): - if i < 20: - f = (b & c) | (~b & d) - k = 0x5A827999 - elif i < 40: - f = b ^ c ^ d - k = 0x6ED9EBA1 - elif i < 60: - f = (b & c) | (b & d) | (c & d) - k = 0x8F1BBCDC - else: - f = b ^ c ^ d - k = 0xCA62C1D6 - t = (_rotl32(a, 5) + (f & _M32) + e + k + w[i]) & _M32 - e = d - d = c - c = _rotl32(b, 30) - b = a - a = t - self._h = [(x + y) & _M32 for x, y in zip(self._h, (a, b, c, d, e))] - - -_K256 = (0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, - 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, - 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, - 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, - 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, - 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, - 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, - 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, - 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, - 0xc67178f2) + + +class _SHA224(_Hash): + name = "sha224" + digest_size = 28 + block_size = 64 class _SHA256(_Hash): name = "sha256" digest_size = 32 block_size = 64 - _IV = (0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, - 0x5be0cd19) - _LEN_BYTES = 8 - _ORDER = "big" - _WORD = 4 - - def _compress(self, block): - w = [int.from_bytes(block[i:i + 4], "big") for i in range(0, 64, 4)] - for i in range(16, 64): - x = w[i - 15] - y = w[i - 2] - s0 = _rotr32(x, 7) ^ _rotr32(x, 18) ^ (x >> 3) - s1 = _rotr32(y, 17) ^ _rotr32(y, 19) ^ (y >> 10) - w.append((w[i - 16] + s0 + w[i - 7] + s1) & _M32) - a, b, c, d, e, f, g, h = self._h - for i in range(64): - s1 = _rotr32(e, 6) ^ _rotr32(e, 11) ^ _rotr32(e, 25) - ch = (e & f) ^ (~e & g) - t1 = (h + s1 + ch + _K256[i] + w[i]) & _M32 - s0 = _rotr32(a, 2) ^ _rotr32(a, 13) ^ _rotr32(a, 22) - maj = (a & b) ^ (a & c) ^ (b & c) - t2 = (s0 + maj) & _M32 - h = g - g = f - f = e - e = (d + t1) & _M32 - d = c - c = b - b = a - a = (t1 + t2) & _M32 - self._h = [(x + y) & _M32 for x, y in zip(self._h, (a, b, c, d, e, f, g, h))] - - -class _SHA224(_SHA256): - name = "sha224" - digest_size = 28 - _IV = (0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, - 0xbefa4fa4) - - -_K512 = (0x428a2f98d728ae22, 0x7137449123ef65cd, 0xb5c0fbcfec4d3b2f, 0xe9b5dba58189dbbc, - 0x3956c25bf348b538, 0x59f111f1b605d019, 0x923f82a4af194f9b, 0xab1c5ed5da6d8118, - 0xd807aa98a3030242, 0x12835b0145706fbe, 0x243185be4ee4b28c, 0x550c7dc3d5ffb4e2, - 0x72be5d74f27b896f, 0x80deb1fe3b1696b1, 0x9bdc06a725c71235, 0xc19bf174cf692694, - 0xe49b69c19ef14ad2, 0xefbe4786384f25e3, 0x0fc19dc68b8cd5b5, 0x240ca1cc77ac9c65, - 0x2de92c6f592b0275, 0x4a7484aa6ea6e483, 0x5cb0a9dcbd41fbd4, 0x76f988da831153b5, - 0x983e5152ee66dfab, 0xa831c66d2db43210, 0xb00327c898fb213f, 0xbf597fc7beef0ee4, - 0xc6e00bf33da88fc2, 0xd5a79147930aa725, 0x06ca6351e003826f, 0x142929670a0e6e70, - 0x27b70a8546d22ffc, 0x2e1b21385c26c926, 0x4d2c6dfc5ac42aed, 0x53380d139d95b3df, - 0x650a73548baf63de, 0x766a0abb3c77b2a8, 0x81c2c92e47edaee6, 0x92722c851482353b, - 0xa2bfe8a14cf10364, 0xa81a664bbc423001, 0xc24b8b70d0f89791, 0xc76c51a30654be30, - 0xd192e819d6ef5218, 0xd69906245565a910, 0xf40e35855771202a, 0x106aa07032bbd1b8, - 0x19a4c116b8d2d0c8, 0x1e376c085141ab53, 0x2748774cdf8eeb99, 0x34b0bcb5e19b48a8, - 0x391c0cb3c5c95a63, 0x4ed8aa4ae3418acb, 0x5b9cca4f7763e373, 0x682e6ff3d6b2b8a3, - 0x748f82ee5defb2fc, 0x78a5636f43172f60, 0x84c87814a1f0ab72, 0x8cc702081a6439ec, - 0x90befffa23631e28, 0xa4506cebde82bde9, 0xbef9a3f7b2c67915, 0xc67178f2e372532b, - 0xca273eceea26619c, 0xd186b8c721c0c207, 0xeada7dd6cde0eb1e, 0xf57d4f7fee6ed178, - 0x06f067aa72176fba, 0x0a637dc5a2c898a6, 0x113f9804bef90dae, 0x1b710b35131c471b, - 0x28db77f523047d84, 0x32caab7b40c72493, 0x3c9ebe0a15c9bebc, 0x431d67c49c100d4c, - 0x4cc5d4becb3e42b6, 0x597f299cfc657e2a, 0x5fcb6fab3ad6faec, 0x6c44198c4a475817) + + +class _SHA384(_Hash): + name = "sha384" + digest_size = 48 + block_size = 128 class _SHA512(_Hash): name = "sha512" digest_size = 64 block_size = 128 - _IV = (0x6a09e667f3bcc908, 0xbb67ae8584caa73b, 0x3c6ef372fe94f82b, 0xa54ff53a5f1d36f1, - 0x510e527fade682d1, 0x9b05688c2b3e6c1f, 0x1f83d9abfb41bd6b, 0x5be0cd19137e2179) - _LEN_BYTES = 16 - _ORDER = "big" - _WORD = 8 - - def _compress(self, block): - w = [int.from_bytes(block[i:i + 8], "big") for i in range(0, 128, 8)] - for i in range(16, 80): - x = w[i - 15] - y = w[i - 2] - s0 = _rotr64(x, 1) ^ _rotr64(x, 8) ^ (x >> 7) - s1 = _rotr64(y, 19) ^ _rotr64(y, 61) ^ (y >> 6) - w.append((w[i - 16] + s0 + w[i - 7] + s1) & _M64) - a, b, c, d, e, f, g, h = self._h - for i in range(80): - s1 = _rotr64(e, 14) ^ _rotr64(e, 18) ^ _rotr64(e, 41) - ch = (e & f) ^ (~e & g) - t1 = (h + s1 + ch + _K512[i] + w[i]) & _M64 - s0 = _rotr64(a, 28) ^ _rotr64(a, 34) ^ _rotr64(a, 39) - maj = (a & b) ^ (a & c) ^ (b & c) - t2 = (s0 + maj) & _M64 - h = g - g = f - f = e - e = (d + t1) & _M64 - d = c - c = b - b = a - a = (t1 + t2) & _M64 - self._h = [(x + y) & _M64 for x, y in zip(self._h, (a, b, c, d, e, f, g, h))] - - -class _SHA384(_SHA512): - name = "sha384" - digest_size = 48 - _IV = (0xcbbb9d5dc1059ed8, 0x629a292a367cd507, 0x9159015a3070dd17, 0x152fecd8f70e5939, - 0x67332667ffc00b31, 0x8eb44a8768581511, 0xdb0c2e0d64f98fa7, 0x47b5481dbefa4fa4) + + +class _Blake2(_Hash): + """BLAKE2 (RFC 7693), sequential mode: key, salt, person and digest size. + The tree-hashing parameters are accepted at their defaults only.""" + + def __init__(self, data=b"", *, digest_size=None, key=b"", salt=b"", person=b"", fanout=1, depth=1, + leaf_size=0, node_offset=0, node_depth=0, inner_size=0, last_node=False, + usedforsecurity=True): + if digest_size is None: + digest_size = self.MAX_DIGEST_SIZE + if not 1 <= digest_size <= self.MAX_DIGEST_SIZE: + raise ValueError("digest_size must be between 1 and %d bytes" % self.MAX_DIGEST_SIZE) + # The usual call names none of the three; empty values need no checks. + if key or salt or person: + key = _as_bytes(key) + salt = _as_bytes(salt) + person = _as_bytes(person) + if len(key) > self.MAX_KEY_SIZE: + raise ValueError("maximum key length is %d bytes" % self.MAX_KEY_SIZE) + if len(salt) > self.SALT_SIZE: + raise ValueError("maximum salt length is %d bytes" % self.SALT_SIZE) + if len(person) > self.PERSON_SIZE: + raise ValueError("maximum person length is %d bytes" % self.PERSON_SIZE) + else: + key = salt = person = b"" + if (fanout != 1 or depth != 1 or leaf_size != 0 or node_offset != 0 or node_depth != 0 + or inner_size != 0 or last_node): + raise ValueError("tree hashing is not supported") + self.digest_size = digest_size + self._s = _cn1hash.new(self.name, digest_size, key, salt, person) + if data: + self.update(data) + + +class blake2b(_Blake2): + name = "blake2b" + block_size = 128 + MAX_DIGEST_SIZE = 64 + MAX_KEY_SIZE = 64 + SALT_SIZE = 16 + PERSON_SIZE = 16 + + +class blake2s(_Blake2): + name = "blake2s" + block_size = 64 + MAX_DIGEST_SIZE = 32 + MAX_KEY_SIZE = 32 + SALT_SIZE = 8 + PERSON_SIZE = 8 _BY_NAME = {"md5": _MD5, "sha1": _SHA1, "sha224": _SHA224, "sha256": _SHA256, - "sha384": _SHA384, "sha512": _SHA512} + "sha384": _SHA384, "sha512": _SHA512, "blake2b": blake2b, + "blake2s": blake2s} def md5(data=b"", *, usedforsecurity=True): @@ -313,7 +169,7 @@ def new(name, data=b"", **kwargs): cls = _BY_NAME.get(name.lower().replace("-", "")) if isinstance(name, str) else None if cls is None: raise ValueError("unsupported hash type " + str(name)) - return cls(data) + return cls(data, **kwargs) if kwargs else cls(data) def file_digest(fileobj, digest, /): @@ -325,34 +181,13 @@ def file_digest(fileobj, digest, /): h.update(chunk) -def _hmac(cls, key, msg): - bs = cls.block_size - if len(key) > bs: - key = cls(key).digest() - key = key + b"\x00" * (bs - len(key)) - inner = cls(bytes(b ^ 0x36 for b in key)) - inner.update(msg) - outer = cls(bytes(b ^ 0x5C for b in key)) - outer.update(inner.digest()) - return outer.digest() - - def pbkdf2_hmac(hash_name, password, salt, iterations, dklen=None): - cls = new(hash_name).__class__ password = _as_bytes(password) salt = _as_bytes(salt) if iterations < 1: raise ValueError("iteration value must be greater than 0.") if dklen is None: - dklen = cls.digest_size - out = b"" - block = 1 - while len(out) < dklen: - u = _hmac(cls, password, salt + block.to_bytes(4, "big")) - acc = int.from_bytes(u, "big") - for _ in range(iterations - 1): - u = _hmac(cls, password, u) - acc ^= int.from_bytes(u, "big") - out += acc.to_bytes(cls.digest_size, "big") - block += 1 - return out[:dklen] + dklen = new(hash_name).digest_size + if dklen < 1: + raise ValueError("key length must be greater than 0.") + return _cn1hash.pbkdf2(hash_name, password, salt, iterations, dklen) diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/heapq.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/heapq.py index 195625f6e7d..e6a462406f9 100644 --- a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/heapq.py +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/heapq.py @@ -4,70 +4,12 @@ """Heap queue algorithm: a list kept as a binary min-heap.""" __all__ = ["heappush", "heappop", "heapify", "heapreplace", "heappushpop", "nlargest", "nsmallest", - "merge"] + "merge", "heappush_max", "heappop_max", "heapify_max", + "heapreplace_max", "heappushpop_max"] -def _up(heap, start, pos): - item = heap[pos] - while pos > start: - parent = (pos - 1) >> 1 - p = heap[parent] - if item < p: - heap[pos] = p - pos = parent - else: - break - heap[pos] = item - - -def _down(heap, pos): - end = len(heap) - start = pos - item = heap[pos] - child = 2 * pos + 1 - while child < end: - right = child + 1 - if right < end and not heap[child] < heap[right]: - child = right - heap[pos] = heap[child] - pos = child - child = 2 * pos + 1 - heap[pos] = item - _up(heap, start, pos) - - -def heappush(heap, item): - heap.append(item) - _up(heap, 0, len(heap) - 1) - - -def heappop(heap): - last = heap.pop() - if heap: - item = heap[0] - heap[0] = last - _down(heap, 0) - return item - return last - - -def heapreplace(heap, item): - top = heap[0] - heap[0] = item - _down(heap, 0) - return top - - -def heappushpop(heap, item): - if heap and heap[0] < item: - item, heap[0] = heap[0], item - _down(heap, 0) - return item - - -def heapify(x): - for i in reversed(range(len(x) // 2)): - _down(x, i) +from _cn1heapq import (heappush, heappop, heapify, heapreplace, heappushpop, heappush_max, heappop_max, + heapify_max, heapreplace_max, heappushpop_max) def nsmallest(n, iterable, key=None): diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/html/parser.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/html/parser.py new file mode 100644 index 00000000000..340e7623d8b --- /dev/null +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/html/parser.py @@ -0,0 +1,451 @@ +# Copyright (c) 2001 Python Software Foundation; All Rights Reserved +# Licensed under the Python Software Foundation License Version 2; the full +# text is in maven/python-transpiler/third-party/cpython/LICENSE.txt. +# +# Derived from CPython's Lib/html/parser.py. Changes: rewritten for the Codename One +# Python runtime, trimmed to what the transpiler supports and reorganised; +# the C accelerators and platform-specific branches are left out. +"""html.parser: a tolerant, event-driven HTML tokenizer. + +Tags, attributes, comments, declarations and character references are read +the way the HTML5 tokenizer reads them; the text of script and style (and +the other raw-text elements) is reported verbatim up to its end tag.""" + +import re as _re +from html import unescape +import _markupbase + +__all__ = ["HTMLParser"] + +_WS = " \t\n\r\f" +_TAG_END = " \t\n\r\f/>" +_starttagopen = _re.compile(r"<[a-zA-Z]") +_charref = _re.compile(r"&#(?:[0-9]+|[xX][0-9a-fA-F]+)[^0-9a-fA-F]") +_entityref = _re.compile(r"&([a-zA-Z][-.a-zA-Z0-9]*)[^a-zA-Z0-9]") +_interesting_normal = _re.compile(r"[&<]") +_incomplete = _re.compile(r"&[a-zA-Z#]") +_amp_end = _re.compile(r"[\t\n\r\f ;]") +_entity_tail = _re.compile(r"&([a-zA-Z][-.a-zA-Z0-9]*)\Z") +_charref_tail = _re.compile(r"&#([0-9]+|[xX][0-9a-fA-F]+)\Z") + +CDATA_CONTENT_ELEMENTS = ("script", "style") +RCDATA_CONTENT_ELEMENTS = ("textarea", "title") + + +class HTMLParser(_markupbase.ParserBase): + CDATA_CONTENT_ELEMENTS = CDATA_CONTENT_ELEMENTS + RCDATA_CONTENT_ELEMENTS = RCDATA_CONTENT_ELEMENTS + + def __init__(self, *, convert_charrefs=True): + super().__init__() + self.convert_charrefs = convert_charrefs + self.reset() + + def reset(self): + self.rawdata = "" + self.lasttag = "???" + self.interesting = _interesting_normal + self.cdata_elem = None + self._escapable = True + self._support_cdata = True + self.__starttag_text = None + super().reset() + + def feed(self, data): + self.rawdata = self.rawdata + data + self.goahead(False) + + def close(self): + self.goahead(True) + + __starttag_text = None + + def get_starttag_text(self): + return self.__starttag_text + + def set_cdata_mode(self, elem, *, escapable=False): + self.cdata_elem = elem.lower() + self._escapable = escapable + if escapable and not self.convert_charrefs: + self.interesting = _re.compile(r"&|])" % self.cdata_elem, _re.IGNORECASE | _re.ASCII) + else: + self.interesting = _re.compile(r"])" % self.cdata_elem, _re.IGNORECASE | _re.ASCII) + + def clear_cdata_mode(self): + self.interesting = _interesting_normal + self.cdata_elem = None + self._escapable = True + + def _set_support_cdata(self, flag=True): + self._support_cdata = flag + + def _data(self, text): + if self.convert_charrefs and (self.cdata_elem is None or self._escapable): + text = unescape(text) + self.handle_data(text) + + def goahead(self, end): + rawdata = self.rawdata + i = 0 + n = len(rawdata) + while i < n: + if self.convert_charrefs and not self.cdata_elem: + j = rawdata.find("<", i) + if j < 0: + amppos = rawdata.rfind("&", max(i, n - 34)) + if amppos >= 0 and not _amp_end.search(rawdata, amppos) and not end: + break + j = n + else: + m = self.interesting.search(rawdata, i) + if m: + j = m.start() + elif self.cdata_elem is not None: + # Raw text runs to its end tag: wait for it. + if not end: + break + j = n + else: + j = n + if i < j: + self._data(rawdata[i:j]) + i = self.updatepos(i, j) + if i == n: + break + if rawdata.startswith("<", i): + if _starttagopen.match(rawdata, i): + k = self.parse_starttag(i) + elif rawdata.startswith("", i + 9) + if j < 0: + return -1 + self.unknown_decl(rawdata[i + 3:j]) + return j + 3 + if rawdata[i:i + 9].lower() == "", i + 9) + if gtpos == -1: + return -1 + self.handle_decl(rawdata[i + 2:gtpos]) + return gtpos + 1 + return self.parse_bogus_comment(i) + + def parse_comment(self, i, report=True): + rawdata = self.rawdata + if rawdata[i:i + 4] != "", k): + end = k + close = k + 3 + break + if rawdata.startswith("--!>", k): + end = k + close = k + 4 + break + if k + 2 >= len(rawdata) or (rawdata[k + 2] == "!" and k + 3 >= len(rawdata)): + return -1 + k += 1 + if report: + self.handle_comment(rawdata[j:end]) + return close + + def parse_bogus_comment(self, i, report=True): + rawdata = self.rawdata + if rawdata[i:i + 2] not in ("", i + 2) + if pos == -1: + return -1 + if report: + self.handle_comment(rawdata[i + 2:pos]) + return pos + 1 + + def parse_pi(self, i): + rawdata = self.rawdata + if rawdata[i:i + 2] != "", i + 2) + if j < 0: + return -1 + self.handle_pi(rawdata[i + 2:j]) + return j + 1 + + def _scan_starttag(self, i): + """Reads the start tag at i: (tag, attrs, end, selfclosing), or None + when its closing '>' has not arrived yet.""" + rawdata = self.rawdata + n = len(rawdata) + k = i + 1 + while k < n and rawdata[k] not in _TAG_END: + k += 1 + tag = rawdata[i + 1:k].lower() + attrs = [] + selfclosing = False + while True: + while k < n and (rawdata[k] in _WS or rawdata[k] == "/"): + if rawdata[k] == "/" and k + 1 < n and rawdata[k + 1] == ">": + selfclosing = True + k += 1 + break + k += 1 + if k >= n: + return None + if rawdata[k] == ">": + return tag, attrs, k + 1, selfclosing + start = k + k += 1 + while k < n and rawdata[k] not in " \t\n\r\f/>=": + k += 1 + name = rawdata[start:k].lower() + p = k + while p < n and rawdata[p] in _WS: + p += 1 + if p < n and rawdata[p] == "=": + p += 1 + while p < n and rawdata[p] in _WS: + p += 1 + if p >= n: + return None + q = rawdata[p] + if q == '"' or q == "'": + e = rawdata.find(q, p + 1) + if e < 0: + return None + value = rawdata[p + 1:e] + k = e + 1 + else: + e = p + while e < n and rawdata[e] not in _WS and rawdata[e] != ">": + e += 1 + value = rawdata[p:e] + k = e + attrs.append((name, unescape(value))) + else: + if p >= n: + return None + attrs.append((name, None)) + k = p if p > k else k + + def parse_starttag(self, i): + scanned = self._scan_starttag(i) + if scanned is None: + return -1 + tag, attrs, endpos, selfclosing = scanned + self.__starttag_text = self.rawdata[i:endpos] + self.lasttag = tag + if selfclosing: + self.handle_startendtag(tag, attrs) + else: + self.handle_starttag(tag, attrs) + if tag in self.CDATA_CONTENT_ELEMENTS: + self.set_cdata_mode(tag) + elif tag in self.RCDATA_CONTENT_ELEMENTS: + self.set_cdata_mode(tag, escapable=True) + return endpos + + def check_for_whole_start_tag(self, i): + scanned = self._scan_starttag(i) + if scanned is None: + return -1 + return scanned[2] + + def parse_endtag(self, i): + rawdata = self.rawdata + n = len(rawdata) + if rawdata[i:i + 2] != "= n: + return -1 + c = rawdata[i + 2] + if c == ">": + return i + 3 + if not (c.isascii() and c.isalpha()): + if self.cdata_elem is not None: + self.handle_data(rawdata[i:i + 2]) + return i + 2 + return self.parse_bogus_comment(i) + k = i + 2 + while k < n and rawdata[k] not in _TAG_END: + k += 1 + tag = rawdata[i + 2:k].lower() + scanned = self._scan_endtag_rest(k) + if scanned < 0: + return -1 + if self.cdata_elem is not None and tag != self.cdata_elem: + self.handle_data(rawdata[i:scanned]) + return scanned + self.handle_endtag(tag) + self.clear_cdata_mode() + return scanned + + def _scan_endtag_rest(self, k): + """Skips the attributes an end tag may (wrongly) carry, honouring + quotes the way a start tag does; answers the index after '>'.""" + rawdata = self.rawdata + n = len(rawdata) + while k < n: + c = rawdata[k] + if c == ">": + return k + 1 + if c == "=": + p = k + 1 + while p < n and rawdata[p] in _WS: + p += 1 + if p < n and rawdata[p] in "\"'": + e = rawdata.find(rawdata[p], p + 1) + if e < 0: + return -1 + k = e + 1 + continue + k = p + continue + k += 1 + return -1 + + def handle_startendtag(self, tag, attrs): + self.handle_starttag(tag, attrs) + self.handle_endtag(tag) + + def handle_starttag(self, tag, attrs): + pass + + def handle_endtag(self, tag): + pass + + def handle_charref(self, name): + pass + + def handle_entityref(self, name): + pass + + def handle_data(self, data): + pass + + def handle_comment(self, data): + pass + + def handle_decl(self, decl): + pass + + def handle_pi(self, data): + pass + + def unknown_decl(self, data): + pass diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/http/__init__.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/http/__init__.py index 5ed674893ee..88117f6a705 100644 --- a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/http/__init__.py +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/http/__init__.py @@ -49,20 +49,104 @@ _PHRASES = {code: phrase for code, _, phrase in _CODES} -HTTPStatus = IntEnum("HTTPStatus", [(name, code) for code, name, _ in _CODES]) +# Class statements, not the functional API: every member is defined once by +# the compiler and is a typed static of its class. +class HTTPStatus(IntEnum): + CONTINUE = 100 + SWITCHING_PROTOCOLS = 101 + PROCESSING = 102 + EARLY_HINTS = 103 + OK = 200 + CREATED = 201 + ACCEPTED = 202 + NON_AUTHORITATIVE_INFORMATION = 203 + NO_CONTENT = 204 + RESET_CONTENT = 205 + PARTIAL_CONTENT = 206 + MULTI_STATUS = 207 + ALREADY_REPORTED = 208 + IM_USED = 226 + MULTIPLE_CHOICES = 300 + MOVED_PERMANENTLY = 301 + FOUND = 302 + SEE_OTHER = 303 + NOT_MODIFIED = 304 + USE_PROXY = 305 + TEMPORARY_REDIRECT = 307 + PERMANENT_REDIRECT = 308 + BAD_REQUEST = 400 + UNAUTHORIZED = 401 + PAYMENT_REQUIRED = 402 + FORBIDDEN = 403 + NOT_FOUND = 404 + METHOD_NOT_ALLOWED = 405 + NOT_ACCEPTABLE = 406 + PROXY_AUTHENTICATION_REQUIRED = 407 + REQUEST_TIMEOUT = 408 + CONFLICT = 409 + GONE = 410 + LENGTH_REQUIRED = 411 + PRECONDITION_FAILED = 412 + CONTENT_TOO_LARGE = 413 + URI_TOO_LONG = 414 + UNSUPPORTED_MEDIA_TYPE = 415 + RANGE_NOT_SATISFIABLE = 416 + EXPECTATION_FAILED = 417 + IM_A_TEAPOT = 418 + MISDIRECTED_REQUEST = 421 + UNPROCESSABLE_CONTENT = 422 + LOCKED = 423 + FAILED_DEPENDENCY = 424 + TOO_EARLY = 425 + UPGRADE_REQUIRED = 426 + PRECONDITION_REQUIRED = 428 + TOO_MANY_REQUESTS = 429 + REQUEST_HEADER_FIELDS_TOO_LARGE = 431 + UNAVAILABLE_FOR_LEGAL_REASONS = 451 + INTERNAL_SERVER_ERROR = 500 + NOT_IMPLEMENTED = 501 + BAD_GATEWAY = 502 + SERVICE_UNAVAILABLE = 503 + GATEWAY_TIMEOUT = 504 + HTTP_VERSION_NOT_SUPPORTED = 505 + VARIANT_ALSO_NEGOTIATES = 506 + INSUFFICIENT_STORAGE = 507 + LOOP_DETECTED = 508 + NOT_EXTENDED = 510 + NETWORK_AUTHENTICATION_REQUIRED = 511 + @property + def phrase(self): + return _PHRASES.get(self.value, "") -def _phrase(self): - return _PHRASES.get(self.value, "") + @property + def is_informational(self): + return 100 <= self.value < 200 + @property + def is_success(self): + return 200 <= self.value < 300 -HTTPStatus.phrase = property(_phrase) -HTTPStatus.is_informational = property(lambda self: 100 <= self.value < 200) -HTTPStatus.is_success = property(lambda self: 200 <= self.value < 300) -HTTPStatus.is_redirection = property(lambda self: 300 <= self.value < 400) -HTTPStatus.is_client_error = property(lambda self: 400 <= self.value < 500) -HTTPStatus.is_server_error = property(lambda self: 500 <= self.value < 600) + @property + def is_redirection(self): + return 300 <= self.value < 400 -HTTPMethod = StrEnum("HTTPMethod", [(m, m) for m in - ("CONNECT", "DELETE", "GET", "HEAD", "OPTIONS", "PATCH", "POST", "PUT", - "TRACE")]) + @property + def is_client_error(self): + return 400 <= self.value < 500 + + @property + def is_server_error(self): + return 500 <= self.value < 600 + + +class HTTPMethod(StrEnum): + CONNECT = "CONNECT" + DELETE = "DELETE" + GET = "GET" + HEAD = "HEAD" + OPTIONS = "OPTIONS" + PATCH = "PATCH" + POST = "POST" + PUT = "PUT" + TRACE = "TRACE" diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/importlib/__init__.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/importlib/__init__.py new file mode 100644 index 00000000000..2d0038f4d03 --- /dev/null +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/importlib/__init__.py @@ -0,0 +1,43 @@ +# Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. +# Licensed under the GNU General Public License version 2 with the Classpath +# exception, as the rest of the Codename One Python runtime. +"""import_module over the translated program's module registry. + +Every module is compiled into the program and registered by name before +__main__ runs, so importing by a computed name is a lookup. A name that was +not part of the build raises ModuleNotFoundError, as a missing module does in +CPython; nothing is ever loaded from a path. +""" +import sys +import _cn1imp + + +def _resolve_name(name, package, level): + bits = package.rsplit(".", level - 1) + if len(bits) < level: + raise ImportError("attempted relative import beyond top-level package") + base = bits[0] + return f"{base}.{name}" if name else base + + +def import_module(name, package=None): + level = 0 + if name.startswith("."): + if not package: + raise TypeError( + f"the 'package' argument is required to perform a relative import for {name!r}") + for character in name: + if character != ".": + break + level += 1 + name = _resolve_name(name[level:], package, level) + return _cn1imp.load(name) + + +def invalidate_caches(): + pass + + +def reload(module): + # A module body runs once; there is no source to read again. + return module diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/importlib/machinery.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/importlib/machinery.py new file mode 100644 index 00000000000..c6e0cdc7d42 --- /dev/null +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/importlib/machinery.py @@ -0,0 +1,29 @@ +# Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. +# Licensed under the GNU General Public License version 2 with the Classpath +# exception, as the rest of the Codename One Python runtime. +"""The module spec type importlib.util hands out.""" + + +class ModuleSpec: + def __init__(self, name, loader, *, origin=None, loader_state=None, is_package=None): + self.name = name + self.loader = loader + self.origin = origin + self.loader_state = loader_state + self.submodule_search_locations = [] if is_package else None + self.cached = None + self.has_location = False + + @property + def parent(self): + if self.submodule_search_locations is None: + return self.name.rpartition(".")[0] + return self.name + + def __repr__(self): + return f"ModuleSpec(name={self.name!r}, loader={self.loader!r}, origin={self.origin!r})" + + +SOURCE_SUFFIXES = [".py"] +EXTENSION_SUFFIXES = [] +BYTECODE_SUFFIXES = [] diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/importlib/metadata/__init__.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/importlib/metadata/__init__.py new file mode 100644 index 00000000000..8c04c33ff49 --- /dev/null +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/importlib/metadata/__init__.py @@ -0,0 +1,257 @@ +# Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. +# Licensed under the GNU General Public License version 2 with the Classpath +# exception, as the rest of the Codename One Python runtime. +"""Installed-distribution metadata, recorded at build time. + +A translated program has no site-packages to scan. The build writes the +metadata of every PyPI package it installed into the module +_cn1_distributions (python-packages/_cn1_distributions.py): each one's name, +version, top-level packages, requirements and the text of its +entry_points.txt. Plugin systems that discover their plugins through entry +points (pluggy's load_setuptools_entrypoints, llm's plugin loader) therefore +find every plugin that was installed with the application, and only those. +""" +import re as _re + +try: + from _cn1_distributions import DISTRIBUTIONS as _DISTRIBUTIONS +except ImportError: + _DISTRIBUTIONS = {} + + +class PackageNotFoundError(ModuleNotFoundError): + def __str__(self): + return f"No package metadata was found for {self.name}" + + @property + def name(self): + return self.args[0] + + +def _normalize(name): + return _re.sub(r"[-_.]+", "-", name).lower() + + +class EntryPoint: + def __init__(self, name, value, group): + self.name = name + self.value = value + self.group = group + self.dist = None + + @property + def module(self): + return self.value.partition(":")[0].strip() + + @property + def attr(self): + return self.value.partition(":")[2].partition("[")[0].strip() + + @property + def extras(self): + m = _re.search(r"\[(.*)\]", self.value) + return [x.strip() for x in m.group(1).split(",")] if m else [] + + def load(self): + # Every target the bundled metadata declares is a literal import in + # the generated _cn1_entry_points, one function per group; there is + # no site-packages to import an undeclared one from. + try: + from _cn1_entry_points import GROUPS + except ImportError: + GROUPS = {} + attr = self.attr + target = self.module + ":" + attr if attr else self.module + resolve = GROUPS.get(self.group) + value = resolve(target) if resolve is not None else None + if value is None: + raise ImportError(f"entry point {self.value!r} of group {self.group!r} is not part of the program") + return value + + def matches(self, **params): + # The entry point's own fields, each by name. + for k, v in params.items(): + if k == "name": + mine = self.name + elif k == "group": + mine = self.group + elif k == "value": + mine = self.value + elif k == "module": + mine = self.module + elif k == "attr": + mine = self.attr + else: + raise AttributeError(k) + if mine != v: + return False + return True + + def __iter__(self): + return iter((self.name, self)) + + def __eq__(self, other): + return isinstance(other, EntryPoint) and (self.name, self.value, self.group) == ( + other.name, other.value, other.group) + + def __hash__(self): + return hash((self.name, self.value, self.group)) + + def __repr__(self): + return f"EntryPoint(name={self.name!r}, value={self.value!r}, group={self.group!r})" + + +class EntryPoints(tuple): + def __getitem__(self, name): + if isinstance(name, int): + return tuple.__getitem__(self, name) + for ep in self: + if ep.name == name: + return ep + raise KeyError(name) + + def select(self, **params): + return EntryPoints(ep for ep in self if ep.matches(**params)) + + @property + def names(self): + return {ep.name for ep in self} + + @property + def groups(self): + return {ep.group for ep in self} + + +def _parse_entry_points(text): + group = None + out = [] + for raw in (text or "").splitlines(): + line = raw.strip() + if not line or line.startswith(("#", ";")): + continue + if line.startswith("[") and line.endswith("]"): + group = line[1:-1].strip() + continue + name, sep, value = line.partition("=") + if sep and group is not None: + out.append(EntryPoint(name.strip(), value.strip(), group)) + return out + + +class _Metadata(dict): + def get_all(self, name, failobj=None): + v = self.get(name) + if v is None: + return failobj + return v if isinstance(v, list) else [v] + + @property + def json(self): + return dict(self) + + +class Distribution: + def __init__(self, name, record): + self._name = name + self._record = record + + @classmethod + def from_name(cls, name): + if not name: + raise ValueError("A distribution name is required.") + key = _normalize(name) + for n, record in _DISTRIBUTIONS.items(): + if _normalize(n) == key: + return cls(n, record) + raise PackageNotFoundError(name) + + @classmethod + def discover(cls, **kwargs): + return [cls(n, r) for n, r in _DISTRIBUTIONS.items()] + + @property + def name(self): + return self._name + + @property + def version(self): + return self._record.get("version", "") + + @property + def metadata(self): + m = _Metadata() + m["Name"] = self._name + m["Version"] = self.version + for k, v in self._record.get("metadata", {}).items(): + m[k] = v + if self._record.get("requires"): + m["Requires-Dist"] = list(self._record["requires"]) + return m + + @property + def entry_points(self): + eps = _parse_entry_points(self._record.get("entry_points", "")) + for ep in eps: + ep.dist = self + return EntryPoints(eps) + + @property + def requires(self): + return list(self._record.get("requires", [])) or None + + @property + def files(self): + return None + + def read_text(self, filename): + if filename == "entry_points.txt": + return self._record.get("entry_points") + if filename == "top_level.txt": + return "\n".join(self._record.get("top_level", [])) + return None + + def locate_file(self, path): + return path + + +def distribution(distribution_name): + return Distribution.from_name(distribution_name) + + +def distributions(**kwargs): + return iter(Distribution.discover(**kwargs)) + + +def metadata(distribution_name): + return Distribution.from_name(distribution_name).metadata + + +def version(distribution_name): + return Distribution.from_name(distribution_name).version + + +def requires(distribution_name): + return Distribution.from_name(distribution_name).requires + + +def files(distribution_name): + return Distribution.from_name(distribution_name).files + + +def entry_points(**params): + eps = [] + seen = set() + for dist in Distribution.discover(): + if _normalize(dist.name) in seen: + continue + seen.add(_normalize(dist.name)) + eps.extend(dist.entry_points) + return EntryPoints(eps).select(**params) + + +def packages_distributions(): + out = {} + for n, record in _DISTRIBUTIONS.items(): + for top in record.get("top_level", []): + out.setdefault(top, []).append(n) + return out diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/importlib/util.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/importlib/util.py new file mode 100644 index 00000000000..c095c7aa74c --- /dev/null +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/importlib/util.py @@ -0,0 +1,53 @@ +# Copyright (c) 2001 Python Software Foundation; All Rights Reserved +# Licensed under the Python Software Foundation License Version 2; the full +# text is in maven/python-transpiler/third-party/cpython/LICENSE.txt. +# +# Derived from CPython's Lib/importlib/util.py. Changes: rewritten for the Codename One +# Python runtime, trimmed to what the transpiler supports and reorganised; +# the C accelerators and platform-specific branches are left out. +"""find_spec answers whether a module is part of the program.""" +import sys +import _cn1imp +from importlib import _resolve_name +from importlib.machinery import ModuleSpec + + +class _RegistryLoader: + def create_module(self, spec): + return None + + def exec_module(self, module): + pass + + +def resolve_name(name, package): + if not name.startswith("."): + return name + if not package: + raise ImportError(f"no package specified for {name!r} (required for relative module names)") + level = 0 + for character in name: + if character != ".": + break + level += 1 + return _resolve_name(name[level:], package, level) + + +def find_spec(name, package=None): + fullname = resolve_name(name, package) if name.startswith(".") else name + if fullname in sys.modules: + module = sys.modules[fullname] + spec = getattr(module, "__spec__", None) + if spec is not None: + return spec + return ModuleSpec(fullname, _RegistryLoader()) + parent = fullname.rpartition(".")[0] + if parent and not _cn1imp.available(parent): + raise ModuleNotFoundError(f"No module named {parent!r}", name=parent) + if not _cn1imp.available(fullname): + return None + return ModuleSpec(fullname, _RegistryLoader()) + + +def module_from_spec(spec): + return _cn1imp.load(spec.name) diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/inspect.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/inspect.py index e0353e32b09..26c0ecf85e9 100644 --- a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/inspect.py +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/inspect.py @@ -1,8 +1,9 @@ # Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. # Licensed under the GNU General Public License version 2 with the Classpath # exception, as the rest of the Codename One Python runtime. -"""inspect: signatures and the is* predicates. There are no frames or -source to read, so what needs them (stack, getsource) is absent.""" +"""inspect: signatures and the is* predicates. A translated program ships +no source, so getsource raises OSError; currentframe is sys._getframe's +frame, which carries globals but no locals.""" import types as _types @@ -155,13 +156,22 @@ def _bind(self, args, kwargs, partial): def __str__(self): parts = [] star = False + positional_only = False for p in self._params.values(): + if p.kind == POSITIONAL_ONLY: + positional_only = True + elif positional_only: + # The "/" closes the positional-only parameters. + parts.append("/") + positional_only = False if p.kind == VAR_POSITIONAL: star = True elif p.kind == KEYWORD_ONLY and not star: parts.append("*") star = True parts.append(str(p)) + if positional_only: + parts.append("/") s = "(" + ", ".join(parts) + ")" if self.return_annotation is not _empty: s += " -> " + _formatannotation(self.return_annotation) @@ -225,9 +235,10 @@ def _function_signature(f, skip_first): ann = getattr(f, "__annotations__", {}) or {} params = [] first_default = npos - len(defaults) + nposonly = code.co_posonlyargcount for i in range(npos): n = names[i] - params.append(Parameter(n, POSITIONAL_OR_KEYWORD, + params.append(Parameter(n, POSITIONAL_ONLY if i < nposonly else POSITIONAL_OR_KEYWORD, default=defaults[i - first_default] if i >= first_default else _empty, annotation=ann.get(n, _empty))) at = npos + nkw @@ -263,6 +274,12 @@ def signature(obj, *, follow_wrapped=True): if "__init__" in base.__dict__ and isfunction(base.__dict__["__init__"]): return _function_signature(base.__dict__["__init__"], True) return Signature([]) + if obj is object.__init__: + # What CPython reads from object.__init__'s text signature; a class + # that defines no __init__ of its own hands this one on. + return Signature([Parameter("self", POSITIONAL_ONLY), + Parameter("args", VAR_POSITIONAL), + Parameter("kwargs", VAR_KEYWORD)]) call = getattr(type(obj), "__call__", None) if call is not None and isfunction(call): return _function_signature(call, True) @@ -314,6 +331,39 @@ def isasyncgenfunction(obj): return bool(getattr(obj, "__code__", None) and obj.__code__.co_flags & 0x200) +def isasyncgen(obj): + return type(obj).__name__ == "async_generator" + + +CORO_CREATED = "CORO_CREATED" +CORO_RUNNING = "CORO_RUNNING" +CORO_SUSPENDED = "CORO_SUSPENDED" +CORO_CLOSED = "CORO_CLOSED" +GEN_CREATED = "GEN_CREATED" +GEN_RUNNING = "GEN_RUNNING" +GEN_SUSPENDED = "GEN_SUSPENDED" +GEN_CLOSED = "GEN_CLOSED" + + +def _state(obj, prefix): + if getattr(obj, prefix.lower() + "_running", False): + return prefix + "_RUNNING" + frame = getattr(obj, prefix.lower() + "_frame", 0) + if frame is None: + return prefix + "_CLOSED" + if getattr(obj, "_started", True) is False: + return prefix + "_CREATED" + return prefix + "_SUSPENDED" + + +def getcoroutinestate(coroutine): + return _state(coroutine, "CORO") + + +def getgeneratorstate(generator): + return _state(generator, "GEN") + + def isawaitable(obj): return hasattr(obj, "__await__") @@ -368,3 +418,76 @@ def unwrap(func): while hasattr(func, "__wrapped__"): func = func.__wrapped__ return func + + +_sentinel = object() + + +def getattr_static(obj, attr, default=_sentinel): + """Looks attr up without running descriptors or __getattr__: the + instance's own __dict__ first, then each class of the MRO.""" + klass = obj if isinstance(obj, type) else type(obj) + if not isinstance(obj, type): + try: + d = object.__getattribute__(obj, "__dict__") + except AttributeError: + d = None + if isinstance(d, dict) and attr in d: + return d[attr] + for k in klass.__mro__: + kd = k.__dict__ + if attr in kd: + return kd[attr] + if default is not _sentinel: + return default + raise AttributeError(attr) + + +def isdatadescriptor(obj): + t = type(obj) + return hasattr(t, "__set__") or hasattr(t, "__delete__") + + +def ismethoddescriptor(obj): + t = type(obj) + return hasattr(t, "__get__") and not hasattr(t, "__set__") and not isclass(obj) and not isfunction(obj) + + +# A translated program ships no source, so asking for it raises OSError, as +# CPython does for code whose file it cannot read; callers that fall back on +# that (anyio's lazy importer, doctest-style tooling) take their fallback. +def _no_source(obj): + raise OSError("source code not available") + + +def getsource(obj): + _no_source(obj) + + +def getsourcelines(obj): + _no_source(obj) + + +def getsourcefile(obj): + return None + + +def getfile(obj): + f = getattr(obj, "__file__", None) + if f is None: + mod = getattr(obj, "__module__", None) + import sys + m = sys.modules.get(mod) if mod else None + f = getattr(m, "__file__", None) + if f is None: + raise TypeError("%r has no source file" % (obj,)) + return f + + +def currentframe(): + import sys + return sys._getframe(1) + + +def stack(context=1): + return [] diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/io.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/io.py index 7cd649c989b..1c069c70819 100644 --- a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/io.py +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/io.py @@ -235,10 +235,27 @@ def truncate(self, size): class StringIO(TextIOBase): + """newline works as CPython's: None translates \\r\\n and \\r to \\n on + write, '' keeps every ending and reads a line up to any of them, and + '\\r' or '\\r\\n' write \\n as that ending and read lines ending in it.""" + def __init__(self, initial_value="", newline="\n"): if initial_value is not None and not isinstance(initial_value, str): raise TypeError("initial_value must be str or None, not " + type(initial_value).__name__) - self._b = _Buffer(initial_value or "", "") + if newline is not None and not isinstance(newline, str): + raise TypeError("newline must be str or None, not " + type(newline).__name__) + if newline not in (None, "", "\n", "\r", "\r\n"): + raise ValueError("illegal newline value: %r" % (newline,)) + self._newline = newline + self._b = _Buffer(self._translate(initial_value or ""), "") + + def _translate(self, s): + nl = self._newline + if nl is None: + return s.replace("\r\n", "\n").replace("\r", "\n") + if nl in ("\r", "\r\n"): + return s.replace("\n", nl) + return s def readable(self): self._check() @@ -260,7 +277,8 @@ def write(self, s): self._check() if not isinstance(s, str): raise TypeError("string argument expected, got '" + type(s).__name__ + "'") - return self._b.write(s, lambda n: "\0" * n) + self._b.write(self._translate(s), lambda n: "\0" * n) + return len(s) def read(self, size=-1): self._check() @@ -268,7 +286,25 @@ def read(self, size=-1): def readline(self, size=-1): self._check() - return self._b.readline(size, "\n") + nl = self._newline + if nl == "": + return self._readline_any(size) + return self._b.readline(size, "\n" if nl is None else nl) + + def _readline_any(self, size): + b = self._b + buf = b._flat() + start = b._pos + n = len(buf) + lf = buf.find("\n", start) + cr = buf.find("\r", start) + i = n if lf < 0 and cr < 0 else lf if cr < 0 else cr if lf < 0 else min(lf, cr) + if i < n: + i += 2 if buf[i] == "\r" and i + 1 < n and buf[i + 1] == "\n" else 1 + if size is not None and size >= 0: + i = min(i, start + size) + b._pos = max(i, start) + return buf[start:i] def seek(self, pos, whence=0): self._check() diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/ipaddress.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/ipaddress.py new file mode 100644 index 00000000000..f1afbc5eeb3 --- /dev/null +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/ipaddress.py @@ -0,0 +1,493 @@ +# Copyright (c) 2001 Python Software Foundation; All Rights Reserved +# Licensed under the Python Software Foundation License Version 2; the full +# text is in maven/python-transpiler/third-party/cpython/LICENSE.txt. +# +# Derived from CPython's Lib/ipaddress.py. Changes: rewritten for the Codename One +# Python runtime, trimmed to what the transpiler supports and reorganised; +# the C accelerators and platform-specific branches are left out. +"""ipaddress: IPv4 and IPv6 addresses, networks and interfaces -- parsing, +comparison, membership, packing and the common address classes.""" + +import functools as _functools + +IPV4LENGTH = 32 +IPV6LENGTH = 128 + + +class AddressValueError(ValueError): + pass + + +class NetmaskValueError(ValueError): + pass + + +def _parse_v4(s): + parts = s.split(".") + if len(parts) != 4: + raise AddressValueError("Expected 4 octets in %r" % (s,)) + n = 0 + for p in parts: + if not p or not p.isdigit() or len(p) > 3 or (len(p) > 1 and p[0] == "0"): + raise AddressValueError("Invalid octet %r in %r" % (p, s)) + v = int(p) + if v > 255: + raise AddressValueError("Octet %d (> 255) not permitted in %r" % (v, s)) + n = (n << 8) | v + return n + + +def _parse_v6(s): + if "%" in s: + s = s.split("%", 1)[0] + tail = [] + if "." in s: + head, _, v4 = s.rpartition(":") + n4 = _parse_v4(v4) + s = head + ":" + "%x:%x" % (n4 >> 16, n4 & 0xFFFF) + if s.count("::") > 1: + raise AddressValueError("At most one '::' permitted in %r" % (s,)) + if "::" in s: + a, b = s.split("::") + left = a.split(":") if a else [] + right = b.split(":") if b else [] + missing = 8 - len(left) - len(right) + if missing < 1: + raise AddressValueError("Too many parts in %r" % (s,)) + groups = left + ["0"] * missing + right + else: + groups = s.split(":") + if len(groups) != 8: + raise AddressValueError("Exactly 8 parts expected in %r" % (s,)) + n = 0 + for g in groups: + if not g or len(g) > 4: + raise AddressValueError("Invalid part %r in %r" % (g, s)) + try: + v = int(g, 16) + except ValueError: + raise AddressValueError("Invalid part %r in %r" % (g, s)) + n = (n << 16) | v + return n + + +@_functools.total_ordering +class _BaseAddress: + __slots__ = () + + def __int__(self): + return self._ip + + def __index__(self): + return self._ip + + def __eq__(self, other): + return type(other) is type(self) and other._ip == self._ip + + def __lt__(self, other): + if not isinstance(other, _BaseAddress) or other.version != self.version: + return NotImplemented + return self._ip < other._ip + + def __hash__(self): + return hash((self.version, self._ip)) + + def __add__(self, n): + return type(self)(self._ip + int(n)) + + def __sub__(self, n): + return type(self)(self._ip - int(n)) + + def __repr__(self): + return "%s(%r)" % (type(self).__name__, str(self)) + + def __format__(self, spec): + return format(str(self), spec) + + @property + def packed(self): + return self._ip.to_bytes(self.max_prefixlen // 8, "big") + + def _in(self, nets): + for n in nets: + if self in ip_network(n): + return True + return False + + +class IPv4Address(_BaseAddress): + __slots__ = ("_ip",) + version = 4 + max_prefixlen = IPV4LENGTH + + def __init__(self, address): + if isinstance(address, int): + if not 0 <= address < 1 << 32: + raise AddressValueError("%d out of range" % address) + self._ip = address + elif isinstance(address, (bytes, bytearray)): + if len(address) != 4: + raise AddressValueError("%r (len %d != 4) is not permitted as an IPv4 address" + % (address, len(address))) + self._ip = int.from_bytes(bytes(address), "big") + else: + s = str(address) + if "/" in s: + raise AddressValueError("Unexpected '/' in %r" % (s,)) + self._ip = _parse_v4(s) + + def __str__(self): + n = self._ip + return "%d.%d.%d.%d" % ((n >> 24) & 255, (n >> 16) & 255, (n >> 8) & 255, n & 255) + + @property + def is_private(self): + return self._in(("0.0.0.0/8", "10.0.0.0/8", "127.0.0.0/8", "169.254.0.0/16", "172.16.0.0/12", + "192.0.0.0/29", "192.0.0.170/31", "192.0.2.0/24", "192.168.0.0/16", + "198.18.0.0/15", "198.51.100.0/24", "203.0.113.0/24", "240.0.0.0/4", + "255.255.255.255/32")) + + @property + def is_global(self): + return not self.is_private and not self._in(("100.64.0.0/10",)) + + @property + def is_loopback(self): + return self._in(("127.0.0.0/8",)) + + @property + def is_link_local(self): + return self._in(("169.254.0.0/16",)) + + @property + def is_multicast(self): + return self._in(("224.0.0.0/4",)) + + @property + def is_reserved(self): + return self._in(("240.0.0.0/4",)) + + @property + def is_unspecified(self): + return self._ip == 0 + + @property + def reverse_pointer(self): + return ".".join(reversed(str(self).split("."))) + ".in-addr.arpa" + + +class IPv6Address(_BaseAddress): + __slots__ = ("_ip", "_scope") + version = 6 + max_prefixlen = IPV6LENGTH + + def __init__(self, address): + self._scope = None + if isinstance(address, int): + if not 0 <= address < 1 << 128: + raise AddressValueError("%d out of range" % address) + self._ip = address + elif isinstance(address, (bytes, bytearray)): + if len(address) != 16: + raise AddressValueError("%r (len %d != 16) is not permitted as an IPv6 address" + % (address, len(address))) + self._ip = int.from_bytes(bytes(address), "big") + else: + s = str(address) + if "/" in s: + raise AddressValueError("Unexpected '/' in %r" % (s,)) + if "%" in s: + s, self._scope = s.split("%", 1) + self._ip = _parse_v6(s) + + def __str__(self): + if (self._ip >> 32) == 0xFFFF: + return "::ffff:" + str(IPv4Address(self._ip & 0xFFFFFFFF)) + ("%" + self._scope if self._scope else "") + groups = [(self._ip >> (16 * (7 - i))) & 0xFFFF for i in range(8)] + best, best_len, cur, cur_len = -1, 0, -1, 0 + for i, g in enumerate(groups): + if g == 0: + if cur < 0: + cur, cur_len = i, 1 + else: + cur_len += 1 + if cur_len > best_len: + best, best_len = cur, cur_len + else: + cur, cur_len = -1, 0 + hexes = ["%x" % g for g in groups] + if best_len > 1: + hexes[best:best + best_len] = [""] + if best == 0: + hexes.insert(0, "") + if best + best_len == 8: + hexes.append("") + s = ":".join(hexes) + return s + ("%" + self._scope if self._scope else "") + + @property + def scope_id(self): + return self._scope + + @property + def ipv4_mapped(self): + if (self._ip >> 32) != 0xFFFF: + return None + return IPv4Address(self._ip & 0xFFFFFFFF) + + @property + def is_loopback(self): + return self._ip == 1 + + @property + def is_unspecified(self): + return self._ip == 0 + + @property + def is_link_local(self): + return self._in(("fe80::/10",)) + + @property + def is_multicast(self): + return self._in(("ff00::/8",)) + + @property + def is_private(self): + m = self.ipv4_mapped + if m is not None: + return m.is_private + return self._in(("::1/128", "::/128", "::ffff:0:0/96", "100::/64", "2001::/23", "2001:db8::/32", + "2001:10::/28", "fc00::/7", "fe80::/10")) + + @property + def is_global(self): + return not self.is_private + + @property + def is_reserved(self): + return self._in(("::/8", "100::/8", "200::/7", "400::/6", "800::/5", "1000::/4", "4000::/3", + "6000::/3", "8000::/3", "a000::/3", "c000::/3", "e000::/4", "f000::/5", + "f800::/6", "fe00::/9")) + + @property + def is_site_local(self): + return self._in(("fec0::/10",)) + + +@_functools.total_ordering +class _BaseNetwork: + def __init__(self, address, strict=True): + if isinstance(address, tuple): + addr, prefix = address + addr = self._address_class(addr) + prefix = str(prefix) + else: + s = str(address) if not isinstance(address, (int, bytes, bytearray)) else None + if s is None: + addr, prefix = self._address_class(address), str(self._address_class.max_prefixlen) + else: + a, _, prefix = s.partition("/") + addr = self._address_class(a) + prefix = prefix or str(self._address_class.max_prefixlen) + bits = self._address_class.max_prefixlen + if prefix.isdigit(): + plen = int(prefix) + elif self._address_class.version == 4: + # A netmask (contiguous ones from the top) or a hostmask + # (contiguous ones from the bottom), as CPython accepts. + m = _parse_v4(prefix) + inv = m ^ ((1 << 32) - 1) + if (inv & (inv + 1)) == 0: + plen = bits - inv.bit_length() + elif (m & (m + 1)) == 0: + plen = bits - m.bit_length() + else: + raise NetmaskValueError("%r is not a valid netmask" % (prefix,)) + else: + raise NetmaskValueError("%r is not a valid netmask" % (prefix,)) + if not 0 <= plen <= bits: + raise NetmaskValueError("%r is not a valid netmask" % (prefix,)) + self._prefixlen = plen + mask = ((1 << bits) - 1) ^ ((1 << (bits - plen)) - 1) + net = int(addr) & mask + if strict and net != int(addr): + raise ValueError("%s has host bits set" % (address,)) + self._net = net + self._mask = mask + + @property + def network_address(self): + return self._address_class(self._net) + + @property + def broadcast_address(self): + bits = self._address_class.max_prefixlen + return self._address_class(self._net | (((1 << bits) - 1) ^ self._mask)) + + @property + def netmask(self): + return self._address_class(self._mask) + + @property + def hostmask(self): + bits = self._address_class.max_prefixlen + return self._address_class(((1 << bits) - 1) ^ self._mask) + + @property + def prefixlen(self): + return self._prefixlen + + @property + def num_addresses(self): + return 1 << (self._address_class.max_prefixlen - self._prefixlen) + + @property + def with_prefixlen(self): + return "%s/%d" % (self.network_address, self._prefixlen) + + @property + def with_netmask(self): + return "%s/%s" % (self.network_address, self.netmask) + + def __contains__(self, other): + if not isinstance(other, _BaseAddress) or other.version != self.version: + return False + return (int(other) & self._mask) == self._net + + def overlaps(self, other): + return self.network_address in other or other.network_address in self + + def subnet_of(self, other): + return self._prefixlen >= other._prefixlen and self.network_address in other + + def supernet_of(self, other): + return other.subnet_of(self) + + def __iter__(self): + for i in range(self.num_addresses): + yield self._address_class(self._net + i) + + def hosts(self): + n = self.num_addresses + if n <= 2: + return iter(self) + return (self._address_class(self._net + i) for i in range(1, n - 1)) + + def __getitem__(self, i): + n = self.num_addresses + if i < 0: + i += n + if not 0 <= i < n: + raise IndexError("address out of range") + return self._address_class(self._net + i) + + def __eq__(self, other): + return type(other) is type(self) and (self._net, self._prefixlen) == (other._net, other._prefixlen) + + def __lt__(self, other): + if type(other) is not type(self): + return NotImplemented + return (self._net, self._prefixlen) < (other._net, other._prefixlen) + + def __hash__(self): + return hash((self.version, self._net, self._prefixlen)) + + def __str__(self): + return self.with_prefixlen + + def __repr__(self): + return "%s(%r)" % (type(self).__name__, str(self)) + + @property + def is_private(self): + return self.network_address.is_private and self.broadcast_address.is_private + + @property + def is_loopback(self): + return self.network_address.is_loopback and self.broadcast_address.is_loopback + + @property + def is_global(self): + return not self.is_private + + +class IPv4Network(_BaseNetwork): + _address_class = IPv4Address + version = 4 + max_prefixlen = IPV4LENGTH + + +class IPv6Network(_BaseNetwork): + _address_class = IPv6Address + version = 6 + max_prefixlen = IPV6LENGTH + + +class _BaseInterface: + def __init__(self, address): + s = str(address) if not isinstance(address, tuple) else "%s/%s" % address + a, _, p = s.partition("/") + self._addr = self._address_class(a) + self.network = self._network_class(s, strict=False) + + @property + def ip(self): + return self._addr + + def __str__(self): + return "%s/%d" % (self._addr, self.network.prefixlen) + + def __repr__(self): + return "%s(%r)" % (type(self).__name__, str(self)) + + def __eq__(self, other): + return type(other) is type(self) and str(other) == str(self) + + def __hash__(self): + return hash(str(self)) + + +class IPv4Interface(_BaseInterface): + _address_class = IPv4Address + _network_class = IPv4Network + version = 4 + + +class IPv6Interface(_BaseInterface): + _address_class = IPv6Address + _network_class = IPv6Network + version = 6 + + +def _either(address, kinds, what): + for k in kinds: + try: + return k(address) + except (AddressValueError, NetmaskValueError): + pass + raise ValueError("%r does not appear to be an IPv4 or IPv6 %s" % (address, what)) + + +def ip_address(address): + return _either(address, (IPv4Address, IPv6Address), "address") + + +def ip_network(address, strict=True): + for k in (IPv4Network, IPv6Network): + try: + return k(address, strict) + except (AddressValueError, NetmaskValueError): + pass + raise ValueError("%r does not appear to be an IPv4 or IPv6 network" % (address,)) + + +def ip_interface(address): + return _either(address, (IPv4Interface, IPv6Interface), "interface") + + +def v4_int_to_packed(address): + return int(address).to_bytes(4, "big") + + +def v6_int_to_packed(address): + return int(address).to_bytes(16, "big") diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/itertools.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/itertools.py index 7670a389a9c..9a713b047a7 100644 --- a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/itertools.py +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/itertools.py @@ -1,288 +1,11 @@ # Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. # Licensed under the GNU General Public License version 2 with the Classpath # exception, as the rest of the Codename One Python runtime. -"""Iterator building blocks.""" +"""Iterator building blocks. +CPython implements this module in C; here it is Java (`_cn1itertools`). +""" -def count(start=0, step=1): - n = start - while True: - yield n - n += step - - -def cycle(iterable): - saved = [] - for x in iterable: - yield x - saved.append(x) - while saved: - for x in saved: - yield x - - -def repeat(obj, times=None): - if times is None: - while True: - yield obj - else: - for _ in range(times): - yield obj - - -def accumulate(iterable, func=None, *, initial=None): - it = iter(iterable) - total = initial - if initial is None: - try: - total = next(it) - except StopIteration: - return - yield total - for x in it: - total = total + x if func is None else func(total, x) - yield total - - -def batched(iterable, n, *, strict=False): - if n < 1: - raise ValueError("n must be at least one") - it = iter(iterable) - while True: - batch = tuple(islice(it, n)) - if not batch: - return - if strict and len(batch) != n: - raise ValueError("batched(): incomplete batch") - yield batch - - -def chain(*iterables): - for it in iterables: - for x in it: - yield x - - -def _from_iterable(iterables): - for it in iterables: - for x in it: - yield x - - -chain.from_iterable = _from_iterable - - -def compress(data, selectors): - for d, s in zip(data, selectors): - if s: - yield d - - -def dropwhile(predicate, iterable): - it = iter(iterable) - for x in it: - if not predicate(x): - yield x - break - for x in it: - yield x - - -def filterfalse(predicate, iterable): - if predicate is None: - predicate = bool - for x in iterable: - if not predicate(x): - yield x - - -_NO_KEY = object() - - -class groupby: - def __init__(self, iterable, key=None): - self._key = key - self._it = iter(iterable) - self._have = False - self._cur_key = None - self._cur_val = None - self._tgt = _NO_KEY - - def __iter__(self): - return self - - def __next__(self): - while True: - if not self._have: - self._fetch() - if self._tgt is _NO_KEY or self._cur_key != self._tgt: - break - self._have = False - self._tgt = self._cur_key - return (self._cur_key, self._grouper(self._tgt)) - - def _fetch(self): - self._cur_val = next(self._it) - self._cur_key = self._cur_val if self._key is None else self._key(self._cur_val) - self._have = True - - def _grouper(self, tgt): - while True: - if not self._have: - try: - self._fetch() - except StopIteration: - return - if self._tgt is not tgt or self._cur_key != tgt: - return - self._have = False - yield self._cur_val - - -def islice(iterable, *args): - s = slice(*args) - start = 0 if s.start is None else s.start - stop = s.stop - step = 1 if s.step is None else s.step - if start < 0 or (stop is not None and stop < 0) or step <= 0: - raise ValueError("Indices for islice() must be None or an integer: 0 <= x <= sys.maxsize.") - it = iter(iterable) - i = 0 - nxt = start - while stop is None or i < stop: - try: - x = next(it) - except StopIteration: - return - if i == nxt: - yield x - nxt += step - i += 1 - - -def pairwise(iterable): - it = iter(iterable) - try: - a = next(it) - except StopIteration: - return - for b in it: - yield (a, b) - a = b - - -def starmap(function, iterable): - for args in iterable: - yield function(*args) - - -def takewhile(predicate, iterable): - for x in iterable: - if not predicate(x): - return - yield x - - -def tee(iterable, n=2): - it = iter(iterable) - buffers = [[] for _ in range(n)] - - def gen(mine): - while True: - if not mine: - try: - v = next(it) - except StopIteration: - return - for b in buffers: - b.append(v) - yield mine.pop(0) - return tuple(gen(b) for b in buffers) - - -def zip_longest(*iterables, fillvalue=None): - its = [iter(i) for i in iterables] - active = len(its) - if not active: - return - while True: - row = [] - for i in range(len(its)): - try: - row.append(next(its[i])) - except StopIteration: - active -= 1 - if not active: - return - its[i] = repeat(fillvalue) - row.append(fillvalue) - yield tuple(row) - - -def product(*iterables, repeat=1): - pools = [tuple(p) for p in iterables] * repeat - 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 - if r > n: - return - indices = list(range(n)) - cycles = list(range(n, n - r, -1)) - yield tuple(pool[i] for i in indices[:r]) - while n: - for i in reversed(range(r)): - cycles[i] -= 1 - if cycles[i] == 0: - indices[i:] = indices[i + 1:] + indices[i:i + 1] - cycles[i] = n - i - else: - j = cycles[i] - indices[i], indices[-j] = indices[-j], indices[i] - yield tuple(pool[i] for i in indices[:r]) - break - else: - return - - -def combinations(iterable, r): - pool = tuple(iterable) - n = len(pool) - if r > n: - return - indices = list(range(r)) - yield tuple(pool[i] for i in indices) - while True: - for i in reversed(range(r)): - if indices[i] != i + n - r: - break - else: - return - indices[i] += 1 - for j in range(i + 1, r): - indices[j] = indices[j - 1] + 1 - yield tuple(pool[i] for i in indices) - - -def combinations_with_replacement(iterable, r): - pool = tuple(iterable) - n = len(pool) - if not n and r: - return - indices = [0] * r - yield tuple(pool[i] for i in indices) - while True: - for i in reversed(range(r)): - if indices[i] != n - 1: - break - else: - return - indices[i:] = [indices[i] + 1] * (r - i) - yield tuple(pool[i] for i in indices) +from _cn1itertools import (accumulate, batched, chain, combinations, combinations_with_replacement, + compress, count, cycle, dropwhile, filterfalse, groupby, islice, pairwise, + permutations, product, repeat, starmap, takewhile, tee, zip_longest) diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/json.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/json.py index 03fd3ebbba7..75fdff651bd 100644 --- a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/json.py +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/json.py @@ -3,6 +3,10 @@ # exception, as the rest of the Codename One Python runtime. """JSON encoding and decoding (RFC 8259), with the json module's interface.""" +import _cn1json + +_NATIVE_KW = frozenset(("strict", "object_hook", "object_pairs_hook")) + __all__ = ["dump", "dumps", "load", "loads", "JSONDecoder", "JSONDecodeError", "JSONEncoder"] _ESC = {'"': '\\"', "\\": "\\\\", "\n": "\\n", "\r": "\\r", "\t": "\\t", "\b": "\\b", "\f": "\\f"} @@ -80,8 +84,29 @@ def default(self, o): raise TypeError("Object of type %s is not JSON serializable" % type(o).__name__) def encode(self, o): + if type(self) is JSONEncoder: + # The builtin types are written in Java; every other value comes + # back to _other, so isinstance and default decide as below. + opts = self.__dict__.get("_cn1opts") + if opts is None: + # The settings, made into one value the first time this encoder + # is used (they may be assigned after __init__), so each encode + # passes two arguments rather than ten. + opts = _cn1json.options(self.ensure_ascii, self.check_circular, self.allow_nan, self.sort_keys, + self.indent, self.item_separator, self.key_separator, self.skipkeys, + self._other) + self._cn1opts = opts + return _cn1json.encode(o, opts) return "".join(self.iterencode(o)) + def _other(self, o, markers, level): + # level -1: a dict key that is a subclass of str, int or float. + if level < 0: + return self._key(o) + out = [] + self._enc(o, out, level, markers if self.check_circular else None) + return "".join(out) + def iterencode(self, o, _one_shot=False): out = [] self._enc(o, out, 0, [] if self.check_circular else None) @@ -383,6 +408,24 @@ def _array(self, s, i): def dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw): + # CPython's own shortcut: with every default, its shared encoder. + if (not skipkeys and ensure_ascii and check_circular and allow_nan and cls is None and indent is None + and separators is None and default is None and not sort_keys and not kw): + return _default_encoder.encode(obj) + if (cls is None and indent is None and default is None and not kw + and (separators is None or type(separators) is tuple)): + # Any other fixed set of options: an encoder holds nothing but them, so + # one per set is kept rather than built and initialised on every call -- + # a canonical form (sorted keys, compact separators) is asked for this + # way once per value hashed. + key = (skipkeys, ensure_ascii, check_circular, allow_nan, sort_keys, separators) + enc = _encoders.get(key) + if enc is None: + enc = JSONEncoder(skipkeys=skipkeys, ensure_ascii=ensure_ascii, check_circular=check_circular, + allow_nan=allow_nan, separators=separators, sort_keys=sort_keys) + if len(_encoders) < 32: + _encoders[key] = enc + return enc.encode(obj) if cls is None: cls = JSONEncoder return cls(skipkeys=skipkeys, ensure_ascii=ensure_ascii, check_circular=check_circular, @@ -390,6 +433,10 @@ def dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_ sort_keys=sort_keys, **kw).encode(obj) +_default_encoder = JSONEncoder() +_encoders = {} + + def dump(obj, fp, **kw): fp.write(dumps(obj, **kw)) @@ -399,6 +446,12 @@ def loads(s, *, cls=None, **kw): s = s.decode("utf-8") if not isinstance(s, str): raise TypeError("the JSON object must be str, bytes or bytearray, not " + type(s).__name__) + if cls is None and all(k in _NATIVE_KW for k in kw): + # Codename One's strict reader builds the values in Java; anything it + # refuses is decoded again below, which raises CPython's own error. + r = _cn1json.loads(s, kw.get("strict", True), kw.get("object_hook"), kw.get("object_pairs_hook")) + if r is not _cn1json.FAILED: + return r if cls is None: cls = JSONDecoder return cls(**kw).decode(s) diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/keyword.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/keyword.py new file mode 100644 index 00000000000..8018cb232b0 --- /dev/null +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/keyword.py @@ -0,0 +1,23 @@ +# Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. +# Licensed under the GNU General Public License version 2 with the Classpath +# exception, as the rest of the Codename One Python runtime. +"""keyword: the reserved words and soft keywords of Python 3.14.""" + +__all__ = ["iskeyword", "issoftkeyword", "kwlist", "softkwlist"] + +kwlist = ["False", "None", "True", "and", "as", "assert", "async", "await", "break", "class", "continue", "def", + "del", "elif", "else", "except", "finally", "for", "from", "global", "if", "import", "in", "is", + "lambda", "nonlocal", "not", "or", "pass", "raise", "return", "try", "while", "with", "yield"] + +softkwlist = ["_", "case", "match", "type"] + +_kw = frozenset(kwlist) +_soft = frozenset(softkwlist) + + +def iskeyword(s): + return s in _kw + + +def issoftkeyword(s): + return s in _soft diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/locale.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/locale.py new file mode 100644 index 00000000000..265f5df7a28 --- /dev/null +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/locale.py @@ -0,0 +1,80 @@ +# Copyright (c) 2001 Python Software Foundation; All Rights Reserved +# Licensed under the Python Software Foundation License Version 2; the full +# text is in maven/python-transpiler/third-party/cpython/LICENSE.txt. +# +# Derived from CPython's Lib/locale.py. Changes: rewritten for the Codename One +# Python runtime, trimmed to what the transpiler supports and reorganised; +# the C accelerators and platform-specific branches are left out. +"""locale: Codename One text is UTF-8 and formatting is the C locale's; +the device's language reaches an application through its L10N resources.""" + +LC_CTYPE = 0 +LC_NUMERIC = 1 +LC_TIME = 2 +LC_COLLATE = 3 +LC_MONETARY = 4 +LC_MESSAGES = 5 +LC_ALL = 6 +CHAR_MAX = 127 + + +class Error(Exception): + pass + + +def setlocale(category, locale=None): + if locale not in (None, "", "C", "POSIX", "C.UTF-8", "en_US.UTF-8"): + raise Error("unsupported locale setting") + return "C.UTF-8" + + +def getlocale(category=LC_CTYPE): + return (None, None) + + +def getdefaultlocale(envvars=("LC_ALL", "LC_CTYPE", "LANG", "LANGUAGE")): + return (None, "UTF-8") + + +def getpreferredencoding(do_setlocale=True): + return "UTF-8" + + +def getencoding(): + return "UTF-8" + + +def localeconv(): + return {"decimal_point": ".", "thousands_sep": "", "grouping": [], "int_curr_symbol": "", + "currency_symbol": "", "mon_decimal_point": "", "mon_thousands_sep": "", "mon_grouping": [], + "positive_sign": "", "negative_sign": "", "int_frac_digits": CHAR_MAX, "frac_digits": CHAR_MAX, + "p_cs_precedes": CHAR_MAX, "p_sep_by_space": CHAR_MAX, "n_cs_precedes": CHAR_MAX, + "n_sep_by_space": CHAR_MAX, "p_sign_posn": CHAR_MAX, "n_sign_posn": CHAR_MAX} + + +def strcoll(a, b): + return (a > b) - (a < b) + + +def strxfrm(s): + return s + + +def normalize(localename): + return localename + + +def format_string(f, val, grouping=False, monetary=False): + return f % val + + +def str(val): + return "%.12g" % val + + +def atof(s, func=float): + return func(s) + + +def atoi(s): + return int(s) diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/logging/__init__.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/logging/__init__.py index 8b93deca863..82825c3901a 100644 --- a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/logging/__init__.py +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/logging/__init__.py @@ -1,6 +1,24 @@ -# Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. -# Licensed under the GNU General Public License version 2 with the Classpath -# exception, as the rest of the Codename One Python runtime. +# Copyright (c) 2001 Python Software Foundation; All Rights Reserved +# Licensed under the Python Software Foundation License Version 2; the full +# text is in maven/python-transpiler/third-party/cpython/LICENSE.txt. +# +# Derived from CPython's Lib/logging/__init__.py. Changes: rewritten for the Codename One Python runtime: no locks (single threaded +# EDT), no frames in tracebacks, trimmed to what the transpiler supports. +# +# Copyright 2001-2022 by Vinay Sajip. All Rights Reserved. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose and without fee is hereby granted, +# provided that the above copyright notice appear in all copies and that +# both that copyright notice and this permission notice appear in +# supporting documentation, and that the name of Vinay Sajip +# not be used in advertising or publicity pertaining to distribution +# of the software without specific, written prior permission. +# VINAY SAJIP DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING +# ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL +# VINAY SAJIP BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR +# ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER +# IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT """Logging, with the API and output formats of CPython's logging package. Every application is single threaded on the EDT, so handlers take no @@ -176,7 +194,10 @@ def _values(self, record): values = dict(self._defaults) values.update(record.__dict__) return values - return record.__dict__ + # A copy, as above: only read by the format, and a dict handed on + # out of an instance may be written, which the compiler has to + # assume of every field of the program. + return dict(record.__dict__) def _format(self, record): return self._fmt % self._values(record) diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/mimetypes.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/mimetypes.py new file mode 100644 index 00000000000..4560a1e218e --- /dev/null +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/mimetypes.py @@ -0,0 +1,291 @@ +# Copyright (c) 2001 Python Software Foundation; All Rights Reserved +# Licensed under the Python Software Foundation License Version 2; the full +# text is in maven/python-transpiler/third-party/cpython/LICENSE.txt. +# +# Derived from CPython's Lib/mimetypes.py. Changes: rewritten for the Codename One +# Python runtime, trimmed to what the transpiler supports and reorganised; +# the C accelerators and platform-specific branches are left out. +"""mimetypes: guess a MIME type from a file name and back. + +The tables are built in; a device has no mime.types file to read, so +knownfiles is empty and init() only reads the files it is given.""" + +import os as _os + +__all__ = ["knownfiles", "inited", "MimeTypes", "guess_type", "guess_file_type", "guess_all_extensions", + "guess_extension", "add_type", "init", "read_mime_types", "suffix_map", "encodings_map", "types_map", + "common_types"] + +knownfiles = [] +inited = False +_db = None + +_suffix_map_default = { + ".svgz": ".svg.gz", ".tgz": ".tar.gz", ".taz": ".tar.gz", ".tz": ".tar.gz", ".tbz2": ".tar.bz2", + ".txz": ".tar.xz", +} + +_encodings_map_default = { + ".gz": "gzip", ".Z": "compress", ".bz2": "bzip2", ".xz": "xz", ".br": "br", +} + +# The preferred extension of each type comes first, so guess_extension +# answers with it. +_types_map_default = [ + (".js", "text/javascript"), (".mjs", "text/javascript"), + (".epub", "application/epub+zip"), (".gz", "application/gzip"), + (".json", "application/json"), (".webmanifest", "application/manifest+json"), + (".doc", "application/msword"), (".dot", "application/msword"), (".wiz", "application/msword"), + (".nq", "application/n-quads"), (".nt", "application/n-triples"), + (".bin", "application/octet-stream"), (".a", "application/octet-stream"), (".dll", "application/octet-stream"), + (".exe", "application/octet-stream"), (".o", "application/octet-stream"), (".obj", "application/octet-stream"), + (".so", "application/octet-stream"), (".oda", "application/oda"), (".ogx", "application/ogg"), + (".pdf", "application/pdf"), (".p7c", "application/pkcs7-mime"), (".ps", "application/postscript"), + (".ai", "application/postscript"), (".eps", "application/postscript"), + (".trig", "application/trig"), (".m3u", "application/vnd.apple.mpegurl"), + (".m3u8", "application/vnd.apple.mpegurl"), (".xls", "application/vnd.ms-excel"), + (".xlb", "application/vnd.ms-excel"), (".eot", "application/vnd.ms-fontobject"), + (".ppt", "application/vnd.ms-powerpoint"), (".pot", "application/vnd.ms-powerpoint"), + (".ppa", "application/vnd.ms-powerpoint"), (".pps", "application/vnd.ms-powerpoint"), + (".pwz", "application/vnd.ms-powerpoint"), + (".odg", "application/vnd.oasis.opendocument.graphics"), + (".odp", "application/vnd.oasis.opendocument.presentation"), + (".ods", "application/vnd.oasis.opendocument.spreadsheet"), + (".odt", "application/vnd.oasis.opendocument.text"), + (".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"), + (".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"), + (".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"), + (".rar", "application/vnd.rar"), (".wasm", "application/wasm"), (".7z", "application/x-7z-compressed"), + (".bcpio", "application/x-bcpio"), (".cpio", "application/x-cpio"), (".csh", "application/x-csh"), + (".deb", "application/x-debian-package"), (".dvi", "application/x-dvi"), (".gtar", "application/x-gtar"), + (".hdf", "application/x-hdf"), (".h5", "application/x-hdf5"), (".latex", "application/x-latex"), + (".mif", "application/x-mif"), (".cdf", "application/x-netcdf"), (".nc", "application/x-netcdf"), + (".p12", "application/x-pkcs12"), (".php", "application/x-httpd-php"), (".pfx", "application/x-pkcs12"), + (".ram", "application/x-pn-realaudio"), (".pyc", "application/x-python-code"), + (".pyo", "application/x-python-code"), (".rpm", "application/x-rpm"), (".sh", "application/x-sh"), + (".shar", "application/x-shar"), (".swf", "application/x-shockwave-flash"), + (".sv4cpio", "application/x-sv4cpio"), (".sv4crc", "application/x-sv4crc"), (".tar", "application/x-tar"), + (".tcl", "application/x-tcl"), (".tex", "application/x-tex"), (".texi", "application/x-texinfo"), + (".texinfo", "application/x-texinfo"), (".roff", "application/x-troff"), (".t", "application/x-troff"), + (".tr", "application/x-troff"), (".man", "application/x-troff-man"), (".me", "application/x-troff-me"), + (".ms", "application/x-troff-ms"), (".ustar", "application/x-ustar"), (".src", "application/x-wais-source"), + (".xsl", "application/xml"), (".rdf", "application/xml"), (".wsdl", "application/xml"), + (".xpdl", "application/xml"), (".yaml", "application/yaml"), (".yml", "application/yaml"), + (".zip", "application/zip"), + (".3gp", "audio/3gpp"), (".3gpp", "audio/3gpp"), (".3g2", "audio/3gpp2"), (".3gpp2", "audio/3gpp2"), + (".aac", "audio/aac"), (".adts", "audio/aac"), (".loas", "audio/aac"), (".ass", "audio/aac"), + (".au", "audio/basic"), (".snd", "audio/basic"), (".flac", "audio/flac"), (".mka", "audio/matroska"), + (".m4a", "audio/mp4"), (".mp3", "audio/mpeg"), (".mp2", "audio/mpeg"), (".ogg", "audio/ogg"), + (".opus", "audio/opus"), (".aif", "audio/x-aiff"), (".aifc", "audio/x-aiff"), (".aiff", "audio/x-aiff"), + (".ra", "audio/x-pn-realaudio"), (".wav", "audio/vnd.wave"), (".otf", "font/otf"), (".ttf", "font/ttf"), + (".weba", "audio/webm"), (".woff", "font/woff"), (".woff2", "font/woff2"), + (".avif", "image/avif"), (".bmp", "image/bmp"), (".emf", "image/emf"), (".fits", "image/fits"), + (".g3", "image/g3fax"), (".gif", "image/gif"), (".ief", "image/ief"), (".jp2", "image/jp2"), + (".jpg", "image/jpeg"), (".jpe", "image/jpeg"), (".jpeg", "image/jpeg"), + (".jpm", "image/jpm"), (".jpx", "image/jpx"), (".heic", "image/heic"), (".heif", "image/heif"), + (".png", "image/png"), (".svg", "image/svg+xml"), (".t38", "image/t38"), (".tiff", "image/tiff"), + (".tif", "image/tiff"), (".tfx", "image/tiff-fx"), (".ico", "image/vnd.microsoft.icon"), + (".webp", "image/webp"), (".wmf", "image/wmf"), (".ras", "image/x-cmu-raster"), + (".pnm", "image/x-portable-anymap"), (".pbm", "image/x-portable-bitmap"), + (".pgm", "image/x-portable-graymap"), (".ppm", "image/x-portable-pixmap"), (".rgb", "image/x-rgb"), + (".xbm", "image/x-xbitmap"), (".xpm", "image/x-xpixmap"), (".xwd", "image/x-xwindowdump"), + (".eml", "message/rfc822"), (".mht", "message/rfc822"), (".mhtml", "message/rfc822"), + (".nws", "message/rfc822"), (".gltf", "model/gltf+json"), (".glb", "model/gltf-binary"), + (".stl", "model/stl"), (".css", "text/css"), (".csv", "text/csv"), (".html", "text/html"), + (".htm", "text/html"), (".md", "text/markdown"), (".markdown", "text/markdown"), (".n3", "text/n3"), + (".txt", "text/plain"), (".bat", "text/plain"), (".c", "text/plain"), (".h", "text/plain"), + (".ksh", "text/plain"), (".pl", "text/plain"), (".srt", "text/plain"), (".rtx", "text/richtext"), + (".rtf", "text/rtf"), (".tsv", "text/tab-separated-values"), (".vtt", "text/vtt"), (".py", "text/x-python"), + (".rst", "text/x-rst"), (".etx", "text/x-setext"), (".sgm", "text/x-sgml"), (".sgml", "text/x-sgml"), + (".vcf", "text/x-vcard"), (".xml", "text/xml"), (".mkv", "video/matroska"), (".mk3d", "video/matroska-3d"), + (".mp4", "video/mp4"), (".mpeg", "video/mpeg"), (".m1v", "video/mpeg"), (".mpa", "video/mpeg"), + (".mpe", "video/mpeg"), (".mpg", "video/mpeg"), (".ogv", "video/ogg"), (".mov", "video/quicktime"), + (".qt", "video/quicktime"), (".webm", "video/webm"), (".avi", "video/vnd.avi"), (".m4v", "video/x-m4v"), + (".wmv", "video/x-ms-wmv"), (".movie", "video/x-sgi-movie"), +] + +_common_types_default = [ + (".rtf", "application/rtf"), (".apk", "application/vnd.android.package-archive"), + (".midi", "audio/midi"), (".mid", "audio/midi"), (".jpg", "image/jpg"), (".pict", "image/pict"), + (".pct", "image/pict"), (".pic", "image/pict"), (".webp", "image/webp"), (".xul", "text/xul"), +] + + +class MimeTypes: + def __init__(self, filenames=(), strict=True): + self.encodings_map = dict(_encodings_map_default) + self.suffix_map = dict(_suffix_map_default) + self.types_map = ({}, {}) + self.types_map_inv = ({}, {}) + for ext, t in _types_map_default: + self.add_type(t, ext, True) + for ext, t in _common_types_default: + self.add_type(t, ext, False) + for name in filenames: + self.read(name, strict) + + def add_type(self, type, ext, strict=True): + if ext and not ext.startswith("."): + raise ValueError("Extensions should start with a '.' or be empty: %r" % ext) + if not type: + return + self.types_map[strict][ext] = type + exts = self.types_map_inv[strict].setdefault(type, []) + if ext not in exts: + exts.append(ext) + + def guess_type(self, url, strict=True): + url = _os.fspath(url) + lower = url[:5].lower() if isinstance(url, str) else "" + if lower.startswith("data:"): + comma = url.find(",") + if comma < 0: + return None, None + semi = url.find(";", 0, comma) + if semi >= 0: + type = url[5:semi] + else: + type = url[5:comma] + if "=" in type or "/" not in type: + type = "text/plain" + return type, None + scheme_end = url.find(":") + if scheme_end > 1 and "/" not in url[:scheme_end] and "\\" not in url[:scheme_end]: + rest = url[scheme_end + 1:] + for c in "?#": + k = rest.find(c) + if k >= 0: + rest = rest[:k] + url = rest + return self._guess_file_type(url, strict, _posix_splitext) + + def guess_file_type(self, path, strict=True): + path = _os.fsdecode(path) if isinstance(path, bytes) else _os.fspath(path) + path = _os.path.splitdrive(path)[1] + return self._guess_file_type(path, strict, _os.path.splitext) + + def _guess_file_type(self, path, strict, splitext): + base, ext = splitext(path) + while (ext_lower := ext.lower()) in self.suffix_map: + base, ext = splitext(base + self.suffix_map[ext_lower]) + if ext in self.encodings_map: + encoding = self.encodings_map[ext] + base, ext = splitext(base) + else: + encoding = None + ext = ext.lower() + types_map = self.types_map[True] + if ext in types_map: + return types_map[ext], encoding + if strict: + return None, encoding + types_map = self.types_map[False] + if ext in types_map: + return types_map[ext], encoding + return None, encoding + + def guess_all_extensions(self, type, strict=True): + type = type.lower() + extensions = list(self.types_map_inv[True].get(type, [])) + if not strict: + for ext in self.types_map_inv[False].get(type, []): + if ext not in extensions: + extensions.append(ext) + return extensions + + def guess_extension(self, type, strict=True): + extensions = self.guess_all_extensions(type, strict) + if not extensions: + return None + return extensions[0] + + def read(self, filename, strict=True): + with open(filename, encoding="utf-8") as fp: + self.readfp(fp, strict) + + def readfp(self, fp, strict=True): + for line in fp: + words = line.split() + for i in range(len(words)): + if words[i][0] == "#": + del words[i:] + break + if not words: + continue + type, suffixes = words[0], words[1:] + for suff in suffixes: + self.add_type(type, "." + suff, strict) + + +def _posix_splitext(p): + sep = p.rfind("/") + dot = p.rfind(".") + if dot > sep: + i = sep + 1 + while i < dot: + if p[i] != ".": + return p[:dot], p[dot:] + i += 1 + return p, p[:0] + + +def _get_db(): + global _db, inited + if _db is None: + _db = MimeTypes() + inited = True + _sync() + return _db + + +def _sync(): + global suffix_map, encodings_map, types_map, common_types + suffix_map = _db.suffix_map + encodings_map = _db.encodings_map + types_map = _db.types_map[True] + common_types = _db.types_map[False] + + +def guess_type(url, strict=True): + return _get_db().guess_type(url, strict) + + +def guess_file_type(path, *, strict=True): + return _get_db().guess_file_type(path, strict) + + +def guess_all_extensions(type, strict=True): + return _get_db().guess_all_extensions(type, strict) + + +def guess_extension(type, strict=True): + return _get_db().guess_extension(type, strict) + + +def add_type(type, ext, strict=True): + return _get_db().add_type(type, ext, strict) + + +def init(files=None): + global _db, inited + db = MimeTypes() + for f in (files or ()): + if _os.path.isfile(f): + db.read(f) + _db = db + inited = True + _sync() + + +def read_mime_types(file): + try: + f = open(file, encoding="utf-8") + except OSError: + return None + with f: + db = MimeTypes() + db.readfp(f, True) + return db.types_map[True] + + +_get_db() diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/ntpath.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/ntpath.py new file mode 100644 index 00000000000..af0bef51f58 --- /dev/null +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/ntpath.py @@ -0,0 +1,169 @@ +# Copyright (c) 2001 Python Software Foundation; All Rights Reserved +# Licensed under the Python Software Foundation License Version 2; the full +# text is in maven/python-transpiler/third-party/cpython/LICENSE.txt. +# +# Derived from CPython's Lib/ntpath.py. Changes: rewritten for the Codename One +# Python runtime, trimmed to what the transpiler supports and reorganised; +# the C accelerators and platform-specific branches are left out. +"""ntpath: Windows path operations on strings (or bytes). Only the lexical +functions; nothing here touches a file system.""" + +sep = "\\" +altsep = "/" +extsep = "." +pathsep = ";" +curdir = "." +pardir = ".." +defpath = ".;C:\\bin" +devnull = "nul" + +__all__ = ["normcase", "isabs", "join", "splitdrive", "splitroot", "split", "splitext", "basename", "dirname", + "normpath", "abspath", "commonprefix", "sep", "altsep", "extsep", "pathsep", "curdir", "pardir", "devnull"] + + +def _seps(p): + if isinstance(p, bytes): + return b"\\", b"/", b":", b"", b".", b".." + return "\\", "/", ":", "", ".", ".." + + +def normcase(s): + bs, fs = _seps(s)[:2] + return s.replace(fs, bs).lower() + + +def splitroot(p): + bs, fs, colon, empty = _seps(p)[:4] + normp = p.replace(fs, bs) + if normp[:1] == bs: + if normp[1:2] == bs: + start = 8 if normp[:8].upper() == (b"\\\\?\\UNC\\" if isinstance(p, bytes) else "\\\\?\\UNC\\") else 2 + index = normp.find(bs, start) + if index == -1: + return p, empty, empty + index2 = normp.find(bs, index + 1) + if index2 == -1: + return p, empty, empty + return p[:index2], p[index2:index2 + 1], p[index2 + 1:] + return empty, p[:1], p[1:] + if normp[1:2] == colon: + if normp[2:3] == bs: + return p[:2], p[2:3], p[3:] + return p[:2], empty, p[2:] + return empty, empty, p + + +def splitdrive(p): + drive, root, tail = splitroot(p) + return drive, root + tail + + +def isabs(s): + bs, fs = _seps(s)[:2] + s = s[:3].replace(fs, bs) + return s[:2] == bs + bs or s[1:3] == (b":" if isinstance(s, bytes) else ":") + bs + + +def join(path, *paths): + bs, fs, colon, empty = _seps(path)[:4] + seps = bs + fs + result_drive, result_root, result_path = splitroot(path) + for p in paths: + p_drive, p_root, p_path = splitroot(p) + if p_root: + if p_drive or not result_drive: + result_drive = p_drive + result_root = p_root + result_path = p_path + continue + elif p_drive and p_drive != result_drive: + if p_drive.lower() != result_drive.lower(): + result_drive = p_drive + result_root = p_root + result_path = p_path + continue + result_drive = p_drive + if result_path and result_path[-1:] not in seps: + result_path = result_path + bs + result_path = result_path + p_path + if (result_path and not result_root and result_drive and result_drive[-1:] not in colon + seps): + return result_drive + bs + result_path + return result_drive + result_root + result_path + + +def split(p): + bs, fs = _seps(p)[:2] + seps = bs + fs + d, r, p = splitroot(p) + i = len(p) + while i and p[i - 1:i] not in seps: + i -= 1 + head, tail = p[:i], p[i:] + return d + r + head.rstrip(seps), tail + + +def splitext(p): + bs, fs, colon, empty, dot = _seps(p)[:5] + sepIndex = max(p.rfind(bs), p.rfind(fs)) + dotIndex = p.rfind(dot) + if dotIndex > sepIndex: + filenameIndex = sepIndex + 1 + while filenameIndex < dotIndex: + if p[filenameIndex:filenameIndex + 1] != dot: + return p[:dotIndex], p[dotIndex:] + filenameIndex += 1 + return p, p[:0] + + +def basename(p): + return split(p)[1] + + +def dirname(p): + return split(p)[0] + + +def normpath(path): + bs, fs, colon, empty, curdir_, pardir_ = _seps(path) + drive, root, path = splitroot(path) + prefix = drive + root + comps = path.replace(fs, bs).split(bs) + i = 0 + while i < len(comps): + if not comps[i] or comps[i] == curdir_: + del comps[i] + elif comps[i] == pardir_: + if i > 0 and comps[i - 1] != pardir_: + del comps[i - 1:i + 1] + i -= 1 + elif i == 0 and root: + del comps[i] + else: + i += 1 + else: + i += 1 + if not prefix and not comps: + comps.append(curdir_) + return prefix.replace(fs, bs) + bs.join(comps) + + +def abspath(path): + """The absolute form of a path: an absolute one normalised, a relative + one joined onto the current directory first -- as CPython's ntpath does + off Windows, where the current directory is a POSIX path.""" + if not isabs(path): + import os + cwd = os.getcwdb() if isinstance(path, bytes) else os.getcwd() + path = join(cwd, path) + return normpath(path) + + +def commonprefix(m): + if not m: + return "" + s1 = min(m) + s2 = max(m) + for i, c in enumerate(s1): + if c != s2[i]: + return s1[:i] + return s1 diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/nturl2path.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/nturl2path.py new file mode 100644 index 00000000000..dbf0df311af --- /dev/null +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/nturl2path.py @@ -0,0 +1,41 @@ +# Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. +# Licensed under the GNU General Public License version 2 with the Classpath +# exception, as the rest of the Codename One Python runtime. +"""nturl2path: the Windows forms of url2pathname and pathname2url. + +Present so code that converts a Windows file URL by name (and tests that +simulate Windows on another host) can import it; urllib.request uses the +POSIX forms on every target Codename One runs on.""" + +from urllib.parse import quote, unquote + + +def url2pathname(url): + """The Windows path of a file URL's path: an empty or localhost + authority is dropped, a drive's '|' becomes ':', '/' becomes '\\', and + the result is percent-decoded after that, as CPython's is.""" + if url[:3] == "///": + url = url[2:] + elif url[:12] == "//localhost/": + url = url[11:] + if url[:3] == "///": + url = url[1:] + else: + if url[:1] == "/" and url[2:3] in (":", "|"): + url = url[1:] + if url[1:2] == "|": + url = url[:1] + ":" + url[2:] + return unquote(url.replace("/", "\\")) + + +def pathname2url(p): + p = p.replace("\\", "/") + if p[:4] == "//?/": + p = p[4:] + if p[:4].upper() == "UNC/": + p = "//" + p[4:] + if p[1:2] == ":": + return quote("///" + p[:2], safe="/:") + quote(p[2:]) + if p[:1] == "/" and p[:2] != "//": + return "//" + quote(p) + return quote(p) diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/operator.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/operator.py index f9915947db3..1415f6dcc51 100644 --- a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/operator.py +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/operator.py @@ -3,44 +3,17 @@ # exception, as the rest of the Codename One Python runtime. """Standard operators as functions.""" +from _cn1op import (lt, le, eq, ne, ge, gt, not_, truth, is_, is_not, is_none, is_not_none, add, + sub, mul, truediv, floordiv, mod, pow, lshift, rshift, and_, or_, xor, neg, pos, inv, + invert, contains, getitem, setitem, itemgetter, attrgetter, methodcaller) -def lt(a, b): return a < b -def le(a, b): return a <= b -def eq(a, b): return a == b -def ne(a, b): return a != b -def ge(a, b): return a >= b -def gt(a, b): return a > b -def not_(a): return not a -def truth(a): return bool(a) -def is_(a, b): return a is b -def is_not(a, b): return a is not b -def is_none(a): return a is None -def is_not_none(a): return a is not None -def abs(a): return a.__abs__() if hasattr(a, "__abs__") else (a if a >= 0 else -a) -def add(a, b): return a + b -def and_(a, b): return a & b -def floordiv(a, b): return a // b + +from builtins import abs def index(a): return a.__index__() -def inv(a): return ~a -invert = inv -def lshift(a, b): return a << b -def mod(a, b): return a % b -def mul(a, b): return a * b def matmul(a, b): return a @ b -def neg(a): return -a -def or_(a, b): return a | b -def pos(a): return +a -def pow(a, b): return a ** b -def rshift(a, b): return a >> b -def sub(a, b): return a - b -def truediv(a, b): return a / b -def xor(a, b): return a ^ b def concat(a, b): return a + b -def contains(a, b): return b in a def countOf(a, b): return sum(1 for x in a if x is b or x == b) def delitem(a, b): del a[b] -def getitem(a, b): return a[b] -def setitem(a, b, c): a[b] = c def indexOf(a, b): @@ -77,46 +50,5 @@ def iconcat(a, b): return a -class attrgetter: - def __init__(self, attr, *attrs): - self._attrs = (attr,) + attrs - - def _one(self, obj, name): - for part in name.split("."): - obj = getattr(obj, part) - return obj - - def __call__(self, obj): - if len(self._attrs) == 1: - return self._one(obj, self._attrs[0]) - return tuple(self._one(obj, n) for n in self._attrs) - - def __repr__(self): - return "operator.attrgetter(" + ", ".join(repr(a) for a in self._attrs) + ")" - - -class itemgetter: - def __init__(self, item, *items): - self._items = (item,) + items - - def __call__(self, obj): - if len(self._items) == 1: - return obj[self._items[0]] - return tuple(obj[i] for i in self._items) - - def __repr__(self): - return "operator.itemgetter(" + ", ".join(repr(a) for a in self._items) + ")" - - -class methodcaller: - def __init__(self, name, *args, **kwargs): - self._name = name - self._args = args - self._kwargs = kwargs - - def __call__(self, obj): - return getattr(obj, self._name)(*self._args, **self._kwargs) - - def call(obj, *args, **kwargs): return obj(*args, **kwargs) diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/os/__init__.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/os/__init__.py index c9e9f6c176c..26db3ab0cde 100644 --- a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/os/__init__.py +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/os/__init__.py @@ -30,31 +30,71 @@ W_OK = 2 X_OK = 1 -environ = _cn1fs.environ() _unset = set() error = OSError +class _Environ(dict): + """The process environment. ParparVM cannot enumerate it, so the mapping + starts with what the platform could list and reads any other variable by + name on first use; a variable unset here stays unset.""" + + def __missing__(self, key): + v = None if key in _unset or not isinstance(key, str) else _cn1fs.getenv(key) + if v is None: + raise KeyError(key) + dict.__setitem__(self, key, v) + return v + + def __contains__(self, key): + if dict.__contains__(self, key): + return True + try: + self.__missing__(key) + except KeyError: + return False + return True + + def get(self, key, default=None): + try: + return self[key] + except KeyError: + return default + + def __setitem__(self, key, value): + dict.__setitem__(self, key, value) + _unset.discard(key) + + def __delitem__(self, key): + if not dict.__contains__(self, key): + self.__missing__(key) + dict.__delitem__(self, key) + _unset.add(key) + + def pop(self, key, *default): + _unset.add(key) + return dict.pop(self, key, *default) + + +environ = _Environ(_cn1fs.environ()) + + def getenv(key, default=None): - if key in environ: - return environ[key] - # ParparVM cannot enumerate the environment, so environ may lack a - # variable that is still readable by name. - v = None if key in _unset else _cn1fs.getenv(key) - return default if v is None else v + return environ.get(key, default) def putenv(key, value): environ[key] = value - _unset.discard(key) def unsetenv(key): environ.pop(key, None) - _unset.add(key) -class PathLike: +import abc as _abc + + +class PathLike(metaclass=_abc.ABCMeta): def __fspath__(self): raise NotImplementedError @@ -62,6 +102,11 @@ def __fspath__(self): def __subclasshook__(cls, C): return hasattr(C, "__fspath__") or NotImplemented + def __class_getitem__(cls, item): + # os.PathLike[str] in annotations, as CPython allows; an + # annotation only needs something that evaluates. + return cls + def fspath(p): if isinstance(p, (str, bytes)): @@ -209,16 +254,46 @@ class stat_result(tuple): def __new__(cls, seq): return tuple.__new__(cls, seq) - st_mode = property(lambda self: self[0]) - st_ino = property(lambda self: self[1]) - st_dev = property(lambda self: self[2]) - st_nlink = property(lambda self: self[3]) - st_uid = property(lambda self: self[4]) - st_gid = property(lambda self: self[5]) - st_size = property(lambda self: self[6]) - st_atime = property(lambda self: self[10]) - st_mtime = property(lambda self: self[10]) - st_ctime = property(lambda self: self[10]) + @property + def st_mode(self): + return self[0] + + @property + def st_ino(self): + return self[1] + + @property + def st_dev(self): + return self[2] + + @property + def st_nlink(self): + return self[3] + + @property + def st_uid(self): + return self[4] + + @property + def st_gid(self): + return self[5] + + @property + def st_size(self): + return self[6] + + @property + def st_atime(self): + return self[10] + + @property + def st_mtime(self): + return self[10] + + @property + def st_ctime(self): + return self[10] + def __repr__(self): return ("os.stat_result(st_mode=%d, st_ino=0, st_dev=0, st_nlink=1, st_uid=0, st_gid=0, " @@ -240,11 +315,32 @@ def stat(p, *, dir_fd=None, follow_symlinks=True): lstat = stat +def fstat(fd): + # A translated program's files are streams over the platform's storage, + # not descriptors: there is nothing to stat by number. + raise OSError(9, "Bad file descriptor") + + def access(p, mode, *, dir_fd=None, effective_ids=False, follow_symlinks=True): return path.exists(p) +def chmod(p, mode, *, dir_fd=None, follow_symlinks=True): + """Permissions are the platform's to set on an application's files.""" + if not path.exists(p): + raise FileNotFoundError(2, "No such file or directory", p) + + +def chown(p, uid, gid, *, dir_fd=None, follow_symlinks=True): + chmod(p, 0) + + +def umask(mask): + return 0o022 + + class DirEntry: + __class_getitem__ = classmethod(type(list[int])) def __init__(self, parent, name): self.name = name self.path = path.join(parent, name) @@ -341,13 +437,19 @@ def get_terminal_size(fd=1): class terminal_size(tuple): - columns = property(lambda self: self[0]) - lines = property(lambda self: self[1]) + @property + def columns(self): + return self[0] + + @property + def lines(self): + return self[1] + def urandom(n): - import random as _random - return _random.SystemRandom().randbytes(n) + import _cn1hash + return _cn1hash.urandom(n) def strerror(code): diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/pathlib.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/pathlib.py index 64460b95314..aaf7098bb5b 100644 --- a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/pathlib.py +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/pathlib.py @@ -14,6 +14,8 @@ class PurePath: __slots__ = ("_raw", "_str", "_parts_cache") + # The flavour module (posixpath in CPython): the path functions. + parser = _p def __new__(cls, *args): if cls is PurePath: @@ -69,7 +71,9 @@ def __repr__(self): def as_uri(self): if not self.is_absolute(): raise ValueError("relative path can't be expressed as a file URI") - return "file://" + str(self) + # Quoted as CPython's pathname2url quotes: UTF-8, with '/' kept. + from urllib.parse import quote + return "file://" + quote(str(self), safe="/") def __hash__(self): return hash(str(self)) @@ -277,6 +281,23 @@ def __new__(cls, *args, **kwargs): cls = PosixPath return object.__new__(cls) + @classmethod + def from_uri(cls, uri): + if not uri.startswith("file:"): + raise ValueError("URI does not start with 'file:': %r" % (uri,)) + from urllib.parse import unquote + rest = uri[5:] + if rest.startswith("//"): + rest = rest[2:] + if rest.startswith("localhost/"): + rest = rest[9:] + elif not rest.startswith("/"): + raise ValueError("URI is not local: %r" % (uri,)) + path = cls(unquote(rest)) + if not path.is_absolute(): + raise ValueError("URI is not absolute: %r" % (uri,)) + return path + @classmethod def cwd(cls): return cls(os.getcwd()) diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/pickle.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/pickle.py index c5880e7eb4a..e34fb8c68cc 100644 --- a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/pickle.py +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/pickle.py @@ -1,6 +1,9 @@ -# Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. -# Licensed under the GNU General Public License version 2 with the Classpath -# exception, as the rest of the Codename One Python runtime. +# Copyright (c) 2001 Python Software Foundation; All Rights Reserved +# Licensed under the Python Software Foundation License Version 2; the full +# text is in maven/python-transpiler/third-party/cpython/LICENSE.txt. +# +# Derived from CPython's Lib/pickle.py. Changes: rewritten for the Codename One Python runtime in pure Python, with no C +# accelerator; the stream format is CPython's. """Create portable serialized representations of Python objects. The stream is the one CPython writes: `dumps` produces the same bytes for diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/platform.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/platform.py new file mode 100644 index 00000000000..f7eda59018d --- /dev/null +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/platform.py @@ -0,0 +1,130 @@ +# Copyright (c) 2001 Python Software Foundation; All Rights Reserved +# Licensed under the Python Software Foundation License Version 2; the full +# text is in maven/python-transpiler/third-party/cpython/LICENSE.txt. +# +# Derived from CPython's Lib/platform.py. Changes: rewritten for the Codename One +# Python runtime, trimmed to what the transpiler supports and reorganised; +# the C accelerators and platform-specific branches are left out. +# +# Original notice: +# +# +# Copyright (c) 1999-2000, Marc-Andre Lemburg; mailto:mal@lemburg.com +# Copyright (c) 2000-2010, eGenix.com Software GmbH; mailto:info@egenix.com +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose and without fee or royalty is hereby granted, +# provided that the above copyright notice appear in all copies and that +# both that copyright notice and this permission notice appear in +# supporting documentation or portions thereof, including modifications, +# that you make. +# +# EGENIX.COM SOFTWARE GMBH DISCLAIMS ALL WARRANTIES WITH REGARD TO +# THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS, IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, +# INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING +# FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, +# NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION +# WITH THE USE OR PERFORMANCE OF THIS SOFTWARE ! +# +# + +"""platform: what is known about the device. system() is the platform +name the port reports (iOS, Android, ...), and the Python identity is the +translator's: implementation "CodenameOne" at the language version it +compiles.""" + +import sys as _sys + + +def _platform_name(): + try: + from java.com.codename1.ui import Display + n = Display.getInstance().getPlatformName() + return {"ios": "iOS", "and": "Android", "win": "Windows", "mac": "Darwin", "se": "Java", + "HTML5": "Emscripten"}.get(str(n), str(n)) + except Exception: + return "Java" + + +def system(): + return _platform_name() + + +def node(): + return "localhost" + + +def release(): + return "" + + +def version(): + return "" + + +def machine(): + return "" + + +def processor(): + return "" + + +def architecture(executable=None, bits="", linkage=""): + return ("64bit", "") + + +def uname(): + import collections + r = collections.namedtuple("uname_result", "system node release version machine processor") + return r(system(), node(), release(), version(), machine(), processor()) + + +def platform(aliased=False, terse=False): + return system() + + +def python_implementation(): + return "CodenameOne" + + +def python_version_tuple(): + v = _sys.version_info + return (str(v[0]), str(v[1]), str(v[2])) + + +def python_version(): + return ".".join(python_version_tuple()) + + +def python_build(): + return ("", "") + + +def python_compiler(): + return "Codename One Python transpiler" + + +def python_branch(): + return "" + + +def python_revision(): + return "" + + +def mac_ver(release="", versioninfo=("", "", ""), machine=""): + return (release, versioninfo, machine) + + +def win32_ver(release="", version="", csd="", ptype=""): + return (release, version, csd, ptype) + + +def libc_ver(executable=None, lib="", version="", chunksize=16384): + return (lib, version) + + +def freedesktop_os_release(): + raise OSError("no os-release file") diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/posixpath.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/posixpath.py new file mode 100644 index 00000000000..e919553970b --- /dev/null +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/posixpath.py @@ -0,0 +1,45 @@ +# Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. +# Licensed under the GNU General Public License version 2 with the Classpath +# exception, as the rest of the Codename One Python runtime. +"""posixpath: POSIX path operations. os.path is the POSIX module on every +Codename One target, so this names the same functions.""" + +import os.path as _p + +sep = _p.sep +altsep = _p.altsep +extsep = _p.extsep +pathsep = _p.pathsep +curdir = _p.curdir +pardir = _p.pardir +defpath = _p.defpath +devnull = _p.devnull +supports_unicode_filenames = _p.supports_unicode_filenames +normcase = _p.normcase +isabs = _p.isabs +join = _p.join +split = _p.split +splitext = _p.splitext +splitdrive = _p.splitdrive +splitroot = _p.splitroot +basename = _p.basename +dirname = _p.dirname +normpath = _p.normpath +abspath = _p.abspath +realpath = _p.realpath +relpath = _p.relpath +commonprefix = _p.commonprefix +commonpath = _p.commonpath +exists = _p.exists +lexists = _p.lexists +isdir = _p.isdir +isfile = _p.isfile +islink = _p.islink +ismount = _p.ismount +getsize = _p.getsize +getmtime = _p.getmtime +getatime = _p.getatime +getctime = _p.getctime +samefile = _p.samefile +expanduser = _p.expanduser +expandvars = _p.expandvars diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/pprint.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/pprint.py index 9fbdcb8b631..4978378b4a3 100644 --- a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/pprint.py +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/pprint.py @@ -1,6 +1,9 @@ -# Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. -# Licensed under the GNU General Public License version 2 with the Classpath -# exception, as the rest of the Codename One Python runtime. +# Copyright (c) 2001 Python Software Foundation; All Rights Reserved +# Licensed under the Python Software Foundation License Version 2; the full +# text is in maven/python-transpiler/third-party/cpython/LICENSE.txt. +# +# Derived from CPython's Lib/pprint.py. Changes: rewritten for the Codename One Python runtime, trimmed to what the +# transpiler supports; output layout is CPython's. """Pretty printing of data structures, laid out as CPython's pprint does.""" import collections as _collections @@ -135,7 +138,7 @@ def _format(self, object, stream, indent, allowance, context, level): def _pprint_dataclass(self, object, stream, indent, allowance, context, level): cls_name = object.__class__.__name__ indent += len(cls_name) + 1 - items = [(f.name, getattr(object, f.name)) for f in _dataclasses.fields(object) if f.repr] + items = object.__cn1_repr_items__() stream.write(cls_name + "(") self._format_namespace_items(items, stream, indent, allowance, context, level) stream.write(")") diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/queue.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/queue.py index c0cc263d85c..b518d2eb917 100644 --- a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/queue.py +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/queue.py @@ -28,6 +28,7 @@ class ShutDown(Exception): class Queue: + __class_getitem__ = classmethod(type(list[int])) def __init__(self, maxsize=0): self.maxsize = maxsize self._init(maxsize) @@ -151,6 +152,7 @@ def _get(self): class PriorityQueue(Queue): + __class_getitem__ = classmethod(type(list[int])) def _init(self, maxsize): self.queue = [] @@ -165,6 +167,7 @@ def _get(self): class LifoQueue(Queue): + __class_getitem__ = classmethod(type(list[int])) def _init(self, maxsize): self.queue = [] @@ -179,6 +182,7 @@ def _get(self): class SimpleQueue: + __class_getitem__ = classmethod(type(list[int])) def __init__(self): self._queue = deque() self._count = threading.Semaphore(0) diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/random.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/random.py index aefbea6402e..8c948c4036b 100644 --- a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/random.py +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/random.py @@ -13,6 +13,7 @@ from math import floor as _floor, ceil as _ceil, isfinite as _isfinite, acos as _acos from itertools import accumulate as _accumulate, repeat as _repeat from bisect import bisect as _bisect +from _cn1hash import urandom as _urandom __all__ = ["Random", "SystemRandom", "seed", "random", "uniform", "randint", "choice", "sample", "randrange", "shuffle", "normalvariate", "lognormvariate", "expovariate", @@ -449,8 +450,24 @@ def _lgamma(x): class SystemRandom(Random): """Draws from the platform's entropy rather than a seeded sequence.""" + def __init__(self, x=None): + # No sequence to seed: every draw below reads the platform. + self.gauss_next = None + def seed(self, *args, **kwds): - Random.seed(self, None) + return None + + def random(self): + return (int.from_bytes(_urandom(7), "big") >> 3) * (1.0 / 9007199254740992.0) + + def getrandbits(self, k): + if k < 0: + raise ValueError("number of bits must be non-negative") + numbytes = (k + 7) // 8 + return int.from_bytes(_urandom(numbytes), "big") >> (numbytes * 8 - k) + + def randbytes(self, n): + return _urandom(n) def getstate(self, *args, **kwds): raise NotImplementedError("System entropy source does not have state.") diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/re/__init__.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/re/__init__.py index 8389e845337..a0309762500 100644 --- a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/re/__init__.py +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/re/__init__.py @@ -12,6 +12,7 @@ from enum import IntFlag as _IntFlag from re import _parser from re import _engine +import _cn1re __all__ = ["match", "fullmatch", "search", "sub", "subn", "split", "findall", "finditer", "compile", "purge", "escape", "error", "Pattern", "Match", "A", "I", "L", "M", "S", "X", "U", @@ -64,6 +65,15 @@ def __repr__(self): PatternError = error + +def _sliceable(string): + """The subject the pieces are cut from: a bytearray or memoryview as + bytes, since split, sub and findall answer bytes for any buffer, as sre + does.""" + if isinstance(string, (bytearray, memoryview)): + return bytes(string) + return string + class Pattern: def __init__(self, pattern, flags, code): self.pattern = pattern @@ -71,6 +81,8 @@ def __init__(self, pattern, flags, code): self.flags = flags self.groups = code.groups self.groupindex = dict(code.groupindex) + self._templates = {} + self._prog = _engine.native(code) def __repr__(self): p = repr(self.pattern) @@ -96,54 +108,37 @@ def _check(self, string): elif isinstance(string, str): raise TypeError("cannot use a bytes pattern on a string-like object") - def _run(self, string, pos, endpos, mode): - self._check(string) - n = len(string) - if endpos is None or endpos > n: - endpos = n - if endpos < 0: - endpos = 0 - if pos < 0: - pos = 0 - if pos > endpos: - return None - text = string - if not isinstance(string, str): - text = string.decode("latin-1") - regs = _engine.run(self._code, text, pos, endpos, mode) - if regs is None: - return None - return Match(self, string, pos, endpos, regs) - - def match(self, string, pos=0, endpos=None): - return self._run(string, pos, endpos, 0) - - def fullmatch(self, string, pos=0, endpos=None): - return self._run(string, pos, endpos, 1) - - def search(self, string, pos=0, endpos=None): - return self._run(string, pos, endpos, 2) + # Java builtins on the class, called with the pattern prepended: the + # checks, the bounds, the run and the Match are one call, as sre's are C. + match = _cn1re.pattern_match + fullmatch = _cn1re.pattern_fullmatch + search = _cn1re.pattern_search def finditer(self, string, pos=0, endpos=None): - self._check(string) - n = len(string) - if endpos is None or endpos > n: - endpos = n - text = string if isinstance(string, str) else string.decode("latin-1") + prog = self._prog forbid = -1 - at = pos - while at <= endpos: - regs = _engine.run(self._code, text, at, endpos, 2, forbid) - if regs is None: + at = pos if pos > 0 else 0 + while True: + m = _cn1re.iter(prog, self, string, pos, endpos, at, forbid) + if m is None: return - yield Match(self, string, pos, endpos, regs) - s, e = regs[0], regs[1] + yield m + s, e = m.span() # After an empty match the next one may not be empty at the # same place; after a non-empty one it may. forbid = e if s == e else -1 at = e def findall(self, string, pos=0, endpos=None): + string = _sliceable(string) + if isinstance(string, str) and isinstance(self.pattern, str): + # The loop in Java, without a Match per hit. + n = len(string) + if endpos is None or endpos > n: + endpos = n + if pos < 0: + pos = 0 + return _engine.findall(self._code, string, pos, endpos) out = [] for m in self.finditer(string, pos, endpos): if self.groups == 0: @@ -155,6 +150,11 @@ def findall(self, string, pos=0, endpos=None): return out def split(self, string, maxsplit=0): + if isinstance(string, str) and isinstance(self.pattern, str): + # The loop in Java, without a Match per piece. + return _cn1re.split(self._prog, string, maxsplit) + self._check(string) + string = _sliceable(string) out = [] last = 0 n = 0 @@ -169,7 +169,16 @@ def split(self, string, maxsplit=0): out.append(string[last:]) return out + # A str template over a str is Java's from end to end (_cn1re.sub), with + # the template compiled once per pattern as sre caches it; _subn is the + # general loop for a callable or bytes. def subn(self, repl, string, count=0): + return _cn1re.sub(self._prog, self, repl, string, count, True) + + def sub(self, repl, string, count=0): + return _cn1re.sub(self._prog, self, repl, string, count, False) + + def _subn(self, repl, string, count): if callable(repl): fn = repl else: @@ -179,6 +188,7 @@ def subn(self, repl, string, count=0): fn = lambda m: literal else: fn = lambda m: _expand(template, m) + string = _sliceable(string) out = [] last = 0 n = 0 @@ -193,9 +203,6 @@ def subn(self, repl, string, count=0): out.append(string[last:]) return string[:0].join(out), n - def sub(self, repl, string, count=0): - return self.subn(repl, string, count)[0] - def scanner(self, string, pos=0, endpos=None): raise NotImplementedError("Pattern.scanner is not supported") @@ -206,82 +213,7 @@ def __deepcopy__(self, memo): return self -class Match: - def __init__(self, pattern, string, pos, endpos, regs): - self.re = pattern - self.string = string - self.pos = pos - self.endpos = endpos - self._regs = regs - last = regs[-1] - self.lastindex = last if last > 0 else None - self.lastgroup = None - if self.lastindex is not None: - for name, idx in pattern.groupindex.items(): - if idx == self.lastindex: - self.lastgroup = name - - def _index(self, g): - if isinstance(g, int): - if 0 <= g <= self.re.groups: - return g - elif isinstance(g, str): - idx = self.re.groupindex.get(g) - if idx is not None: - return idx - raise IndexError("no such group") - - def _get(self, idx, default=None): - s = self._regs[2 * idx] - e = self._regs[2 * idx + 1] - if s < 0 or e < 0: - return default - return self.string[s:e] - - def group(self, *groups): - if not groups: - return self._get(0) - if len(groups) == 1: - return self._get(self._index(groups[0])) - return tuple(self._get(self._index(g)) for g in groups) - - def __getitem__(self, g): - return self._get(self._index(g)) - - def groups(self, default=None): - return tuple(self._get(i, default) for i in range(1, self.re.groups + 1)) - - def groupdict(self, default=None): - return {name: self._get(idx, default) for name, idx in self.re.groupindex.items()} - - def start(self, group=0): - return self._regs[2 * self._index(group)] - - def end(self, group=0): - return self._regs[2 * self._index(group) + 1] - - def span(self, group=0): - i = self._index(group) - return (self._regs[2 * i], self._regs[2 * i + 1]) - - @property - def regs(self): - return tuple((self._regs[2 * i], self._regs[2 * i + 1]) for i in range(self.re.groups + 1)) - - def expand(self, template): - return _expand(_compile_template(self.re, template), self) - - def __repr__(self): - return "" % (self.span(), self.group()) - - def __bool__(self): - return True - - def __copy__(self): - return self - - def __deepcopy__(self, memo): - return self +Match = _cn1re.Match _cache = {} @@ -298,15 +230,17 @@ def _compile(pattern, flags): raise TypeError("first argument must be string or compiled pattern") key = (type(pattern), pattern, flags) p = _cache.get(key) - if p is not None: + if isinstance(p, Pattern): + # Only patterns are cached; the test lets a compiled program type + # what compile() returns. return p text = pattern if isinstance(pattern, str) else pattern.decode("latin-1") code = _parser.compile(text, flags, isinstance(pattern, str)) - p = Pattern(pattern, code.flags, code) + made = Pattern(pattern, code.flags, code) if len(_cache) >= 512: _cache.clear() - _cache[key] = p - return p + _cache[key] = made + return made def compile(pattern, flags=0): @@ -453,3 +387,7 @@ def _expand(template, m): else: out.append(p) return empty.join(out) + + +_cn1re.set_hooks(lambda m, template: _expand(_compile_template(m.re, template), m), _compile_template, + Pattern._subn) diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/re/_engine.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/re/_engine.py index 35cf24014f9..abfdab79542 100644 --- a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/re/_engine.py +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/re/_engine.py @@ -37,10 +37,25 @@ MIN_REPEAT_ONE = 18 -def run(code, text, pos, endpos, mode, forbid=-1): - """mode 0 = match, 1 = fullmatch, 2 = search. Returns registers or None.""" +def native(code): + """The Java program for `code`, compiled on first use.""" prog = getattr(code, "_native", None) if prog is None: prog = _cn1re.compile(code.prog, code.groups, code.marks, code.prefix, code.anchored) code._native = prog - return _cn1re.run(prog, text, pos, endpos, mode, forbid) + return prog + + +def run(code, text, pos, endpos, mode, forbid=-1): + """mode 0 = match, 1 = fullmatch, 2 = search. Returns registers or None.""" + return _cn1re.run(native(code), text, pos, endpos, mode, forbid) + + +def subn(code, text, template, count): + """Pattern.subn of a str with a compiled template: (result, count).""" + return _cn1re.subn(native(code), text, template, count) + + +def findall(code, text, pos, endpos): + """Pattern.findall of a str over [pos, endpos].""" + return _cn1re.findall(native(code), text, pos, endpos) diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/readline.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/readline.py new file mode 100644 index 00000000000..467bc6b2e96 --- /dev/null +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/readline.py @@ -0,0 +1,160 @@ +# Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. +# Licensed under the GNU General Public License version 2 with the Classpath +# exception, as the rest of the Codename One Python runtime. +"""readline: the history and completion API, kept in memory. + +An application has no terminal to edit lines in, so nothing here changes +how input() reads; the module exists so a program that configures readline +when it starts -- most command-line tools do -- imports and runs unchanged. +History is a list the program can add to and read back, and history files +are read and written as plain lines. +""" + +_history = [] +_length = -1 +_completer = None +_delims = " \t\n`~!@#$%^&*()-=+[{]}\\|;:'\",<>/?" +_hooks = {} + +__all__ = [ + "add_history", "clear_history", "get_begidx", "get_completer", "get_completer_delims", "get_completion_type", + "get_current_history_length", "get_endidx", "get_history_item", "get_history_length", "get_line_buffer", + "insert_text", "parse_and_bind", "read_history_file", "read_init_file", "redisplay", "remove_history_item", + "replace_history_item", "set_auto_history", "set_completer", "set_completer_delims", + "set_completion_display_matches_hook", "set_history_length", "set_pre_input_hook", "set_startup_hook", + "write_history_file", "append_history_file", +] + +backend = "editline" + + +def parse_and_bind(string): + pass + + +def read_init_file(filename=None): + pass + + +def get_line_buffer(): + return "" + + +def insert_text(string): + pass + + +def redisplay(): + pass + + +def _trim(): + if _length >= 0 and len(_history) > _length: + del _history[:len(_history) - _length] + + +def read_history_file(filename=None): + import os + with open(filename or os.path.expanduser("~/.history"), encoding="utf-8") as f: + _history.extend(line.rstrip("\n") for line in f) + _trim() + + +def write_history_file(filename=None): + import os + with open(filename or os.path.expanduser("~/.history"), "w", encoding="utf-8") as f: + for line in _history: + f.write(line + "\n") + + +def append_history_file(nelements, filename=None): + import os + with open(filename or os.path.expanduser("~/.history"), "a", encoding="utf-8") as f: + for line in _history[-nelements:] if nelements else []: + f.write(line + "\n") + + +def get_history_length(): + return _length + + +def set_history_length(length): + global _length + _length = length + _trim() + + +def get_current_history_length(): + return len(_history) + + +def get_history_item(index): + # one-based, as GNU readline's + return _history[index - 1] if 1 <= index <= len(_history) else None + + +def remove_history_item(pos): + if not 0 <= pos < len(_history): + raise ValueError("No history item at position %d" % pos) + del _history[pos] + + +def replace_history_item(pos, line): + if not 0 <= pos < len(_history): + raise ValueError("No history item at position %d" % pos) + _history[pos] = line + + +def add_history(line): + _history.append(line) + _trim() + + +def clear_history(): + del _history[:] + + +def set_auto_history(enabled): + pass + + +def set_startup_hook(function=None): + _hooks["startup"] = function + + +def set_pre_input_hook(function=None): + _hooks["pre_input"] = function + + +def set_completer(function=None): + global _completer + _completer = function + + +def get_completer(): + return _completer + + +def get_completion_type(): + return 0 + + +def get_begidx(): + return 0 + + +def get_endidx(): + return 0 + + +def set_completer_delims(string): + global _delims + _delims = string + + +def get_completer_delims(): + return _delims + + +def set_completion_display_matches_hook(function=None): + _hooks["display"] = function diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/runpy.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/runpy.py new file mode 100644 index 00000000000..145fa239918 --- /dev/null +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/runpy.py @@ -0,0 +1,15 @@ +# Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. +# Licensed under the GNU General Public License version 2 with the Classpath +# exception, as the rest of the Codename One Python runtime. +"""runpy: running a module as a script means executing its code again, +under __main__; a translated module is compiled to run once, when it is +imported, so both functions raise NotImplementedError.""" + + +def run_module(mod_name, init_globals=None, run_name=None, alter_sys=False): + raise NotImplementedError("runpy.run_module(%r): a translated program cannot re-run a module as a script" + % (mod_name,)) + + +def run_path(path_name, init_globals=None, run_name=None): + raise NotImplementedError("runpy.run_path(%r): a translated program cannot run a file" % (path_name,)) diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/selectors.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/selectors.py new file mode 100644 index 00000000000..59db13108ad --- /dev/null +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/selectors.py @@ -0,0 +1,71 @@ +# Copyright (c) 2001 Python Software Foundation; All Rights Reserved +# Licensed under the Python Software Foundation License Version 2; the full +# text is in maven/python-transpiler/third-party/cpython/LICENSE.txt. +# +# Derived from CPython's Lib/selectors.py. Changes: rewritten for the Codename One +# Python runtime, trimmed to what the transpiler supports and reorganised; +# the C accelerators and platform-specific branches are left out. +"""selectors: the API shape. There are no raw sockets to wait on (see +socket), so a selector holds registrations and select() reports none ready.""" + +from collections import namedtuple as _namedtuple + +EVENT_READ = 1 +EVENT_WRITE = 2 + +SelectorKey = _namedtuple("SelectorKey", ["fileobj", "fd", "events", "data"]) + + +def _fileobj_to_fd(fileobj): + if isinstance(fileobj, int): + return fileobj + return int(fileobj.fileno()) + + +class BaseSelector: + def __init__(self): + self._keys = {} + + def register(self, fileobj, events, data=None): + if not events or events & ~(EVENT_READ | EVENT_WRITE): + raise ValueError("Invalid events: %r" % (events,)) + if fileobj in self._keys: + raise KeyError("%r is already registered" % (fileobj,)) + key = SelectorKey(fileobj, _fileobj_to_fd(fileobj), events, data) + self._keys[fileobj] = key + return key + + def unregister(self, fileobj): + return self._keys.pop(fileobj) + + def modify(self, fileobj, events, data=None): + self.unregister(fileobj) + return self.register(fileobj, events, data) + + def select(self, timeout=None): + return [] + + def close(self): + self._keys.clear() + + def get_key(self, fileobj): + return self._keys[fileobj] + + def get_map(self): + return dict(self._keys) + + def __enter__(self): + return self + + def __exit__(self, *exc): + self.close() + + +class SelectSelector(BaseSelector): + pass + + +PollSelector = SelectSelector +EpollSelector = SelectSelector +KqueueSelector = SelectSelector +DefaultSelector = SelectSelector diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/shutil.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/shutil.py index 5cb44fd56f9..3da28dd2948 100644 --- a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/shutil.py +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/shutil.py @@ -1,53 +1,195 @@ -# Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. -# Licensed under the GNU General Public License version 2 with the Classpath -# exception, as the rest of the Codename One Python runtime. +# Copyright (c) 2001 Python Software Foundation; All Rights Reserved +# Licensed under the Python Software Foundation License Version 2; the full +# text is in maven/python-transpiler/third-party/cpython/LICENSE.txt. +# +# Derived from CPython's Lib/shutil.py. Changes: rewritten for the Codename One +# Python runtime, trimmed to what the transpiler supports and reorganised; +# the C accelerators and platform-specific branches are left out. +"""shutil over the application's file system: copying, moving and removing +files and trees. which() finds nothing, since a device runs no programs.""" -"""shutil: the parts of CPython's module that make sense here.""" -import os +import os as _os +import collections as _collections -__all__ = ["get_terminal_size", "copyfileobj", "copyfile", "copy"] + +class Error(OSError): + pass + + +class SameFileError(Error): + pass + + +class SpecialFileError(OSError): + pass + + +class ReadError(OSError): + pass + + +class RegistryError(Exception): + pass + + +COPY_BUFSIZE = 64 * 1024 + + +def copyfileobj(fsrc, fdst, length=0): + length = length or COPY_BUFSIZE + while True: + buf = fsrc.read(length) + if not buf: + break + fdst.write(buf) + + +def copyfile(src, dst, *, follow_symlinks=True): + src, dst = _os.fspath(src), _os.fspath(dst) + if _os.path.abspath(src) == _os.path.abspath(dst): + raise SameFileError("%r and %r are the same file" % (src, dst)) + with open(src, "rb") as f, open(dst, "wb") as g: + copyfileobj(f, g) + return dst + + +def copymode(src, dst, *, follow_symlinks=True): + pass + + +def copystat(src, dst, *, follow_symlinks=True): + pass + + +def copy(src, dst, *, follow_symlinks=True): + dst = _os.fspath(dst) + if _os.path.isdir(dst): + dst = _os.path.join(dst, _os.path.basename(_os.fspath(src))) + return copyfile(src, dst) + + +copy2 = copy + + +def ignore_patterns(*patterns): + import fnmatch + + def _ignore(path, names): + out = set() + for p in patterns: + out.update(fnmatch.filter(names, p)) + return out + return _ignore + + +def copytree(src, dst, symlinks=False, ignore=None, copy_function=copy2, ignore_dangling_symlinks=False, + dirs_exist_ok=False): + src, dst = _os.fspath(src), _os.fspath(dst) + names = _os.listdir(src) + skip = ignore(src, names) if ignore is not None else set() + _os.makedirs(dst, exist_ok=dirs_exist_ok) + for n in names: + if n in skip: + continue + s, d = _os.path.join(src, n), _os.path.join(dst, n) + if _os.path.isdir(s): + copytree(s, d, symlinks, ignore, copy_function, ignore_dangling_symlinks, dirs_exist_ok) + else: + copy_function(s, d) + return dst + + +def rmtree(path, ignore_errors=False, onerror=None, *, onexc=None, dir_fd=None): + path = _os.fspath(path) + try: + for n in _os.listdir(path): + p = _os.path.join(path, n) + if _os.path.isdir(p): + rmtree(p, ignore_errors, onerror, onexc=onexc) + else: + _os.remove(p) + _os.rmdir(path) + except OSError as e: + if ignore_errors: + return + if onexc is not None: + onexc(rmtree, path, e) + elif onerror is not None: + onerror(rmtree, path, (type(e), e, e.__traceback__)) + else: + raise + + +def move(src, dst, copy_function=copy2): + src, dst = _os.fspath(src), _os.fspath(dst) + if _os.path.isdir(dst): + dst = _os.path.join(dst, _os.path.basename(src.rstrip("/"))) + try: + _os.rename(src, dst) + except OSError: + if _os.path.isdir(src): + copytree(src, dst, copy_function=copy_function) + rmtree(src) + else: + copy_function(src, dst) + _os.remove(src) + return dst + + +_ntuple_diskusage = _collections.namedtuple("usage", "total used free") + + +def disk_usage(path): + return _ntuple_diskusage(0, 0, 0) + + +def which(cmd, mode=None, path=None): + return None def get_terminal_size(fallback=(80, 24)): """COLUMNS and LINES when set, else the terminal on standard output, else `fallback` -- in that order, as CPython does.""" try: - columns = int(os.getenv("COLUMNS", "")) + columns = int(_os.getenv("COLUMNS", "")) except ValueError: columns = 0 try: - lines = int(os.getenv("LINES", "")) + lines = int(_os.getenv("LINES", "")) except ValueError: lines = 0 if columns <= 0 or lines <= 0: try: - size = os.get_terminal_size(1) + size = _os.get_terminal_size(1) except OSError: - size = os.terminal_size(fallback) + size = _os.terminal_size(fallback) if columns <= 0: columns = size.columns or fallback[0] if lines <= 0: lines = size.lines or fallback[1] - return os.terminal_size((columns, lines)) + return _os.terminal_size((columns, lines)) -def copyfileobj(fsrc, fdst, length=0): - size = length if length and length > 0 else 65536 - while True: - buf = fsrc.read(size) - if not buf: - break - fdst.write(buf) +def chown(path, user=None, group=None): + pass -def copyfile(src, dst, *, follow_symlinks=True): - with open(src, "rb") as fsrc, open(dst, "wb") as fdst: - copyfileobj(fsrc, fdst) - return dst +def make_archive(base_name, format, root_dir=None, base_dir=None, verbose=0, dry_run=0, owner=None, + group=None, logger=None): + if format != "zip": + raise ValueError("unknown archive format '%s'" % (format,)) + import zipfile + root_dir = root_dir or _os.getcwd() + out = base_name + ".zip" + with zipfile.ZipFile(out, "w") as z: + for d, ds, fs in _os.walk(_os.path.join(root_dir, base_dir or "")): + for f in fs: + full = _os.path.join(d, f) + z.write(full, _os.path.relpath(full, root_dir)) + return out -def copy(src, dst, *, follow_symlinks=True): - if os.path.isdir(dst): - dst = os.path.join(dst, os.path.basename(src)) - return copyfile(src, dst) - +def unpack_archive(filename, extract_dir=None, format=None, *, filter=None): + import zipfile + with zipfile.ZipFile(filename) as z: + z.extractall(extract_dir or _os.getcwd()) diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/signal.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/signal.py new file mode 100644 index 00000000000..20773ecd20b --- /dev/null +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/signal.py @@ -0,0 +1,118 @@ +# Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. +# Licensed under the GNU General Public License version 2 with the Classpath +# exception, as the rest of the Codename One Python runtime. +"""signal: the numbers and the handler table. + +A mobile application receives no POSIX signals -- the operating system +suspends and resumes it through the lifecycle callbacks -- so a handler is +recorded and answered by getsignal but never called, and raise_signal runs +it directly, which is what a program that signals itself observes. +""" + +import enum as _enum + + +class Signals(_enum.IntEnum): + SIGHUP = 1 + SIGINT = 2 + SIGQUIT = 3 + SIGILL = 4 + SIGTRAP = 5 + SIGABRT = 6 + SIGBUS = 7 + SIGFPE = 8 + SIGKILL = 9 + SIGUSR1 = 10 + SIGSEGV = 11 + SIGUSR2 = 12 + SIGPIPE = 13 + SIGALRM = 14 + SIGTERM = 15 + SIGCHLD = 17 + SIGCONT = 18 + SIGSTOP = 19 + SIGTSTP = 20 + SIGWINCH = 28 + + +class Handlers(_enum.IntEnum): + SIG_DFL = 0 + SIG_IGN = 1 + + +SIG_DFL = Handlers.SIG_DFL +SIG_IGN = Handlers.SIG_IGN +NSIG = 65 +SIGHUP = Signals.SIGHUP +SIGINT = Signals.SIGINT +SIGQUIT = Signals.SIGQUIT +SIGILL = Signals.SIGILL +SIGTRAP = Signals.SIGTRAP +SIGABRT = Signals.SIGABRT +SIGBUS = Signals.SIGBUS +SIGFPE = Signals.SIGFPE +SIGKILL = Signals.SIGKILL +SIGUSR1 = Signals.SIGUSR1 +SIGSEGV = Signals.SIGSEGV +SIGUSR2 = Signals.SIGUSR2 +SIGPIPE = Signals.SIGPIPE +SIGALRM = Signals.SIGALRM +SIGTERM = Signals.SIGTERM +SIGCHLD = Signals.SIGCHLD +SIGCONT = Signals.SIGCONT +SIGSTOP = Signals.SIGSTOP +SIGTSTP = Signals.SIGTSTP +SIGWINCH = Signals.SIGWINCH + +_handlers = {} + + +def default_int_handler(signalnum, frame): + raise KeyboardInterrupt + + +def signal(signalnum, handler): + signalnum = int(signalnum) + if signalnum in (9, 19): + raise OSError(22, "Invalid argument") + old = _handlers.get(signalnum, default_int_handler if signalnum == 2 else SIG_DFL) + _handlers[signalnum] = handler + return old + + +def getsignal(signalnum): + signalnum = int(signalnum) + return _handlers.get(signalnum, default_int_handler if signalnum == 2 else SIG_DFL) + + +def raise_signal(signalnum): + h = getsignal(signalnum) + if callable(h): + h(int(signalnum), None) + + +def strsignal(signalnum): + try: + return Signals(signalnum).name + except ValueError: + return None + + +def valid_signals(): + return set(Signals) + + +def set_wakeup_fd(fd, *, warn_on_full_buffer=True): + return -1 + + +def alarm(seconds): + return 0 + + +def pause(): + pass + + +def siginterrupt(signalnum, flag): + pass diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/socket.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/socket.py new file mode 100644 index 00000000000..bf9c93b6393 --- /dev/null +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/socket.py @@ -0,0 +1,259 @@ +# Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. +# Licensed under the GNU General Public License version 2 with the Classpath +# exception, as the rest of the Codename One Python runtime. +"""socket: the names, the errors and host lookups; no raw sockets. + +A Codename One application talks to the network through the platform's HTTP +and WebSocket stacks (urllib, http.client, requests, httpx), which handle +proxies, certificates and radio state the way the device expects. A socket +object can be created and configured, so code that builds one up front +imports and runs; connecting it raises OSError. +""" + +import enum as _enum + + +class AddressFamily(_enum.IntEnum): + AF_UNSPEC = 0 + AF_UNIX = 1 + AF_INET = 2 + AF_INET6 = 10 + + +class SocketKind(_enum.IntEnum): + SOCK_STREAM = 1 + SOCK_DGRAM = 2 + SOCK_RAW = 3 + + +class AddressInfo(_enum.IntFlag): + AI_PASSIVE = 1 + AI_CANONNAME = 2 + AI_NUMERICHOST = 4 + AI_ADDRCONFIG = 32 + + +class MsgFlag(_enum.IntFlag): + MSG_OOB = 1 + MSG_PEEK = 2 + MSG_DONTWAIT = 64 + + +AF_UNSPEC = AddressFamily.AF_UNSPEC +AF_UNIX = AddressFamily.AF_UNIX +AF_INET = AddressFamily.AF_INET +AF_INET6 = AddressFamily.AF_INET6 +SOCK_STREAM = SocketKind.SOCK_STREAM +SOCK_DGRAM = SocketKind.SOCK_DGRAM +SOCK_RAW = SocketKind.SOCK_RAW +AI_PASSIVE = AddressInfo.AI_PASSIVE +AI_CANONNAME = AddressInfo.AI_CANONNAME +AI_NUMERICHOST = AddressInfo.AI_NUMERICHOST +AI_ADDRCONFIG = AddressInfo.AI_ADDRCONFIG +MSG_OOB = MsgFlag.MSG_OOB +MSG_PEEK = MsgFlag.MSG_PEEK +MSG_DONTWAIT = MsgFlag.MSG_DONTWAIT + +SOL_SOCKET = 1 +SO_REUSEADDR = 2 +SO_KEEPALIVE = 9 +SO_RCVBUF = 8 +SO_SNDBUF = 7 +IPPROTO_TCP = 6 +IPPROTO_UDP = 17 +IPPROTO_IPV6 = 41 +TCP_NODELAY = 1 +NI_NUMERICHOST = 1 +NI_NUMERICSERV = 2 +SHUT_RD = 0 +SHUT_WR = 1 +SHUT_RDWR = 2 +SOMAXCONN = 4096 +has_ipv6 = True + +error = OSError + + +class herror(OSError): + pass + + +class gaierror(OSError): + pass + + +timeout = TimeoutError + +_default_timeout = None + + +def getdefaulttimeout(): + return _default_timeout + + +def setdefaulttimeout(t): + global _default_timeout + _default_timeout = t + + +def _unavailable(): + raise OSError(95, "Raw sockets are not available; use the HTTP client") + + +class socket: + def __init__(self, family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None): + self.family = family + self.type = type + self.proto = proto + self._timeout = _default_timeout + self._closed = False + + def settimeout(self, t): + self._timeout = t + + def gettimeout(self): + return self._timeout + + def setblocking(self, flag): + self._timeout = None if flag else 0.0 + + def setsockopt(self, *args): + pass + + def getsockopt(self, *args): + return 0 + + def connect(self, address): + _unavailable() + + connect_ex = connect + + def bind(self, address): + _unavailable() + + def listen(self, backlog=0): + _unavailable() + + def accept(self): + _unavailable() + + def send(self, data, flags=0): + _unavailable() + + sendall = send + sendto = send + + def recv(self, n, flags=0): + _unavailable() + + recvfrom = recv + recv_into = recv + + def fileno(self): + return -1 + + def shutdown(self, how): + pass + + def close(self): + self._closed = True + + def detach(self): + return -1 + + def __enter__(self): + return self + + def __exit__(self, *exc): + self.close() + + +SocketType = socket + + +def create_connection(address, timeout=None, source_address=None, *, all_errors=False): + _unavailable() + + +def create_server(address, *, family=AF_INET, backlog=None, reuse_port=False, dualstack_ipv6=False): + _unavailable() + + +def socketpair(family=AF_UNIX, type=SOCK_STREAM, proto=0): + _unavailable() + + +def gethostname(): + return "localhost" + + +def getfqdn(name=""): + return name or "localhost" + + +def _numeric(host): + import ipaddress + try: + return ipaddress.ip_address(host) + except ValueError: + return None + + +def gethostbyname(host): + if host in ("localhost", ""): + return "127.0.0.1" + a = _numeric(host) + if a is not None and a.version == 4: + return str(a) + raise gaierror(-2, "Name or service not known") + + +def getaddrinfo(host, port, family=0, type=0, proto=0, flags=0): + """Numeric hosts and localhost only: names resolve inside the HTTP stack.""" + if host is None or host == "localhost": + host = "127.0.0.1" + a = _numeric(host) + if a is None: + raise gaierror(-2, "Name or service not known") + fam = AF_INET if a.version == 4 else AF_INET6 + if family not in (0, fam): + raise gaierror(-9, "Address family for hostname not supported") + addr = (str(a), int(port or 0)) if fam == AF_INET else (str(a), int(port or 0), 0, 0) + return [(fam, type or SOCK_STREAM, proto or IPPROTO_TCP, "", addr)] + + +def inet_aton(s): + import ipaddress + try: + return ipaddress.IPv4Address(s).packed + except ValueError: + raise OSError("illegal IP address string passed to inet_aton") + + +def inet_ntoa(b): + import ipaddress + return str(ipaddress.IPv4Address(bytes(b))) + + +def inet_pton(family, s): + import ipaddress + return (ipaddress.IPv4Address(s) if family == AF_INET else ipaddress.IPv6Address(s)).packed + + +def inet_ntop(family, b): + import ipaddress + return str(ipaddress.IPv4Address(bytes(b)) if family == AF_INET else ipaddress.IPv6Address(bytes(b))) + + +def htons(x): + return ((x & 0xFF) << 8) | ((x >> 8) & 0xFF) + + +ntohs = htons + + +def htonl(x): + return int.from_bytes(int(x).to_bytes(4, "little"), "big") + + +ntohl = htonl diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/sqlite3/__init__.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/sqlite3/__init__.py index 1ef24c69e8b..8f1208798da 100644 --- a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/sqlite3/__init__.py +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/sqlite3/__init__.py @@ -12,14 +12,25 @@ `executescript`, `iterdump` and the exception hierarchy behave as in CPython. -Not provided, raising `NotSupportedError`: user-defined SQL functions, -aggregates and collations, `backup`, `blobopen`, loading extensions. +`create_function` works where the platform's SQLite lets one be +registered (the JVM); elsewhere it raises `NotSupportedError`. Not provided, +raising `NotSupportedError`: aggregates and collations, `backup`, +`blobopen`, loading extensions. """ import datetime as _datetime import _cn1sql +# The two builtins every execute and fetchone calls, read as globals: a +# module's attribute is a lookup by name on each call, a global is a slot. +_fast_execute = _cn1sql.execute +_fast_fetchone = _cn1sql.fetchone +# A cursor's rows still to read let the connection keep its read lock between +# statements, as CPython's pending statement does (PySql.Connection.pending). +_pending = _cn1sql.pending +_drained = _cn1sql.drained + apilevel = "2.0" threadsafety = 1 paramstyle = "qmark" @@ -85,11 +96,16 @@ class PrepareProtocol: Binary = memoryview adapters = {} +# Whether no adapter is registered for a storage type, by the size of `adapters` +# it was worked out for; register_adapter clears it. Asked on every execute, and +# building the five keys each time was most of a short INSERT. +_plain_state = [False, -1] converters = {} def register_adapter(type_, adapter): adapters[(type_, PrepareProtocol)] = adapter + _plain_state[1] = -1 def register_converter(name, converter): @@ -153,6 +169,12 @@ def _engine_error(e): i -= 1 if i > 0: msg = msg[i + 1:-1] + elif msg.startswith("Failed to "): + # The native ports (iOS, Linux, Windows) write ": + # "; the context ends at the first ": ". + sep = msg.find(": ") + if sep > 0: + msg = msg[sep + 2:] low = msg.lower() if "constraint failed" in low or "constraint violation" in low or "not unique" in low: return IntegrityError(msg) @@ -161,7 +183,7 @@ def _engine_error(e): return OperationalError(msg) -def _skip_space(sql, i): +def _skip_space(sql: str, i: int) -> int: n = len(sql) while i < n: c = sql[i] @@ -178,7 +200,7 @@ def _skip_space(sql, i): return i -def _first_word(sql): +def _first_word(sql: str) -> str: i = _skip_space(sql, 0) j = i n = len(sql) @@ -189,9 +211,61 @@ def _first_word(sql): _QUERY_WORDS = ("SELECT", "PRAGMA", "WITH", "VALUES", "EXPLAIN") _DML_WORDS = ("INSERT", "UPDATE", "DELETE", "REPLACE") +_PLAIN = (int, float, str, bytes) + +# What _run needs to know about a scanned statement, by its text: the first +# word, whether it returns rows, and whether a ROLLBACK names a savepoint. +# Computed once per text for the reason _SCANNED is. +_KINDS = {} + +# A cursor's rows when it has none. Never changed in place (the rows are only +# read), so every cursor shares this one. +_NO_ROWS = () + + + +def _plain_free(): + n = len(adapters) + if _plain_state[1] != n: + _plain_state[0] = all((t, PrepareProtocol) not in adapters for t in (int, str, float, bytes, type(None))) + _plain_state[1] = n + return _plain_state[0] + + +def _kind(stmt: str): + k = _KINDS.get(stmt) + if k is None: + if len(_KINDS) >= _SCANNED_MAX: + _KINDS.clear() + word = _first_word(stmt) + upper = stmt.upper() + query = word in _QUERY_WORDS or " RETURNING " in (" " + upper.replace("\n", " ") + " ") + if word == "BEGIN": + control = 1 + elif word == "COMMIT" or word == "END": + control = 2 + elif word == "ROLLBACK" and "TO" not in upper.split(): + control = 3 + else: + control = 0 + # (returns rows, transaction control 0-3, DML, DDL, INSERT/REPLACE, a query word) + k = (query, control, word in _DML_WORDS, word in ("CREATE", "DROP", "ALTER"), + word in ("INSERT", "REPLACE"), word in _QUERY_WORDS) + _KINDS[stmt] = k + return k + +# _scan's answers by SQL text. An application runs the same few statements +# over and over, and CPython keeps a cache of prepared statements for the same +# reason (``cached_statements``); scanning character by character in Python +# was most of what a short statement cost. Callers only read the answer. +_SCANNED = {} +# The bound of _cn1sql's cache of plans, for its reason: texts seen once must not +# keep emptying the cache of the ones that repeat. +_SCANNED_MAX = 2048 -def _scan(sql): + +def _scan(sql: str): """Splits off the first statement and finds its parameters. Answers (statement with every placeholder written as ``?``, the @@ -199,14 +273,28 @@ def _scan(sql): name for ``:name``, ``@name`` and ``$name`` -- the rest after the statement's ``;``, and whether the statement creates a trigger). """ + r = _SCANNED.get(sql) + if r is None: + if len(_SCANNED) >= _SCANNED_MAX: + _SCANNED.clear() + r = _scan_text(sql) + _SCANNED[sql] = r + return r + + +def _scan_text(sql: str): + trigger = _first_word(sql) == "CREATE" and _is_trigger(sql) + # ASCII, nearly every statement, is scanned by _cn1sql, to the letter as below; + # it answers None for any other text. + r = _cn1sql.scan(sql, trigger) + if r is not None: + return r out = [] params = [] n = len(sql) i = 0 start = 0 - trigger = _first_word(sql) == "CREATE" and _is_trigger(sql) depth_begin = 0 - word = "" while i < n: c = sql[i] if c == "'" or c == '"' or c == "`" or c == "[": @@ -233,8 +321,8 @@ def _scan(sql): j = i while j < n and (sql[j].isalnum() or sql[j] == "_"): j += 1 - word = sql[i:j].upper() if trigger: + word = sql[i:j].upper() if word == "BEGIN" or word == "CASE": depth_begin += 1 elif word == "END": @@ -269,7 +357,7 @@ def _scan(sql): return "".join(out), params, "", trigger -def _is_trigger(sql): +def _is_trigger(sql: str) -> bool: words = [] i = 0 n = len(sql) @@ -285,18 +373,22 @@ def _is_trigger(sql): return "TRIGGER" in words -def _is_blank(sql): +def _is_blank(sql: str) -> bool: return _skip_space(sql, 0) >= len(sql) def complete_statement(statement): + # Complete when every statement ends at a top-level ";". The "x" after + # the text tells a terminated last statement (its rest is "x") from one + # that runs to the end -- a trigger whose BEGIN has no END yet ends with + # a ";" that is not its terminator. rest = statement while not _is_blank(rest): - stmt, params, after, trig = _scan(rest) - if after == "" and not rest.rstrip().endswith(";"): + stmt, params, after, trig = _scan(rest + "\nx") + if after == "": return False - rest = after - return statement.rstrip().endswith(";") or _is_blank(statement) + rest = after[:-2] + return not _is_blank(statement) class Row: @@ -350,7 +442,7 @@ def __init__(self, connection): self.description = None self.rowcount = -1 self.lastrowid = None - self._rows = [] + self._rows = _NO_ROWS self._pos = 0 self._closed = False self._inited = True @@ -362,7 +454,9 @@ def _check(self): def close(self): self._closed = True - self._rows = [] + if self._rows and not self.connection._closed: + _drained(self.connection._handle, self._rows) + self._rows = _NO_ROWS def setinputsizes(self, sizes): pass @@ -371,6 +465,16 @@ def setoutputsize(self, size, column=None): pass def execute(self, sql, parameters=()): + # The common call (a statement seen before, plain values) runs whole in + # _cn1sql.execute; it answers None for anything it does not handle, + # before changing anything, and the code below does the rest. A failure + # comes back as the engine's message rather than raised, so this method + # sets up no handler: a frame with one pays for it on every call. + done = _fast_execute(self, sql, parameters) + if done is self: + return self + if done is not None: + raise _engine_error(done) from None self._check() if not isinstance(sql, str): raise TypeError("execute() argument 1 must be str, not " + type(sql).__name__) @@ -378,6 +482,10 @@ def execute(self, sql, parameters=()): if not _is_blank(rest): raise ProgrammingError("You can only execute one statement at a time.") self._run(stmt, names, parameters, False) + if names.count(None) == len(names): + query, control, dml, ddl, inserts, query_word = _kind(stmt) + if not control and not ddl: + _cn1sql.plan(sql, stmt, len(names), query, dml, inserts, query_word) return self def executemany(self, sql, seq_of_parameters): @@ -397,7 +505,7 @@ def executemany(self, sql, seq_of_parameters): total += self.rowcount self.rowcount = total if any_run else 0 self.description = None - self._rows = [] + self._rows = _NO_ROWS self._pos = 0 return self @@ -415,10 +523,18 @@ def executescript(self, sql_script): continue self._run(stmt, [], (), False, script=True) self.description = None - self._rows = [] + self._rows = _NO_ROWS return self def _bind(self, names, parameters): + t = type(parameters) + if (t is list or t is tuple) and names and names.count(None) == len(names): + # Only bare ? placeholders and a plain sequence, the common call: no names to look + # up and nothing to renumber. + if len(parameters) != len(names): + raise ProgrammingError("Incorrect number of bindings supplied. The current statement uses %d, " + "and there are %d supplied." % (len(names), len(parameters))) + return parameters if not names: if parameters is None: return [] @@ -497,53 +613,58 @@ def _adapt(self, v): def _run(self, stmt, names, parameters, many, script=False): conn = self.connection values = self._bind(names, parameters) - bound = [] - for i, v in enumerate(values): - try: - bound.append(self._adapt(v)) - except ProgrammingError: - raise ProgrammingError("Error binding parameter %d: type '%s' is not supported" - % (i + 1, type(v).__name__)) from None - word = _first_word(stmt) - self._rows = [] + bound = None + if _plain_free(): + # No adapter for a storage type (the default ones are for dates), and every value + # is one: binds as it is. + bound = _cn1sql.plain(values) + if bound is None: + bound = [] + for i, v in enumerate(values): + try: + bound.append(self._adapt(v)) + except ProgrammingError: + raise ProgrammingError("Error binding parameter %d: type '%s' is not supported" + % (i + 1, type(v).__name__)) from None + bound = tuple(bound) + query, control, dml, ddl, inserts, query_word = _kind(stmt) + if self._rows: + _drained(conn._handle, self._rows) + self._rows = _NO_ROWS self._pos = 0 - if word == "BEGIN": - conn._begin() - self.description = None - self.rowcount = -1 - return - if word == "COMMIT" or word == "END": - conn._commit_raw() - self.description = None - self.rowcount = -1 - return - if word == "ROLLBACK" and "TO" not in stmt.upper().split(): - conn._rollback_raw() + if control: + if control == 1: + conn._begin() + elif control == 2: + conn._commit_raw() + else: + conn._rollback_raw() self.description = None self.rowcount = -1 return - if word in _DML_WORDS and conn._autocommit == LEGACY_TRANSACTION_CONTROL \ + # A script's statements run as written: CPython's executescript never + # opens an implicit transaction, so an INSERT in one autocommits. + if not script and dml and conn._autocommit == LEGACY_TRANSACTION_CONTROL \ and conn._isolation_level is not None and not conn.in_transaction: conn._begin() - query = word in _QUERY_WORDS or " RETURNING " in (" " + stmt.upper().replace("\n", " ") + " ") try: - cols, rows, changes, rowid = _cn1sql.run(conn._handle, stmt, tuple(bound), query) + cols, rows, changes, rowid = _cn1sql.run(conn._handle, stmt, bound, query) except OSError as e: raise _engine_error(e) from None - if word in ("CREATE", "DROP", "ALTER"): + if ddl: conn._decltypes = {} - if word in _DML_WORDS: + if dml: conn.total_changes += max(changes, 0) if cols: self.description = tuple((self._colname(c), None, None, None, None, None, None) for c in cols) self._rows = self._convert(stmt, cols, rows) - self.rowcount = -1 if word in _QUERY_WORDS else len(rows) + if self._rows: + _pending(conn._handle, self._rows) + self.rowcount = -1 if query_word else len(rows) else: self.description = None - self.rowcount = changes if word in _DML_WORDS else -1 - if word in ("INSERT", "REPLACE") and not many: - self.lastrowid = rowid - elif word in ("INSERT", "REPLACE") and many: + self.rowcount = changes if dml else -1 + if inserts: self.lastrowid = rowid def _colname(self, name): @@ -570,6 +691,9 @@ def _convert(self, stmt, cols, rows): kind = kind.split("(")[0].strip().split(" ")[0] convs[i] = converters.get(kind.upper()) tf = conn.text_factory + if tf is str and not any(convs): + # The rows already are tuples of the storage values: nothing to do. + return rows out = [] for row in rows: vals = list(row) @@ -596,10 +720,18 @@ def _make(self, values): return rf(self, values) def fetchone(self): + r = _fast_fetchone(self) + if r is not None: + return r self._check() - if self._pos >= len(self._rows): + rows = self._rows + if self._pos >= len(rows): + # Asked past the end, which is where CPython's statement finishes + # and lets the lock go; a for loop always asks once more. + if rows: + _drained(self.connection._handle, rows) return None - r = self._rows[self._pos] + r = rows[self._pos] self._pos += 1 return self._make(r) @@ -615,17 +747,28 @@ def fetchmany(self, size=None): return out def fetchall(self): - out = [] - while True: - r = self.fetchone() - if r is None: - return out - out.append(r) + # fetchone's checks once for the whole rest, not once per row. + self._check() + rows = self._rows + pos = self._pos + self._pos = len(rows) + if rows: + _drained(self.connection._handle, rows) + rest = rows[pos:] + rf = self.row_factory + if rf is None: + rf = self.connection.row_factory + if rf is None: + return rest + return [rf(self, r) for r in rest] def __iter__(self): return self def __next__(self): + r = _fast_fetchone(self) + if r is not None: + return r r = self.fetchone() if r is None: raise StopIteration @@ -756,12 +899,14 @@ def _declared(self, stmt): def cursor(self, factory=Cursor): self._check() - c = factory(self) - if self.row_factory is not None and c.row_factory is None: - pass - return c + return factory(self) def execute(self, sql, parameters=()): + # CPython calls self.cursor(), which a subclass may override. A plain + # Connection skips that call: Cursor.execute checks the connection + # itself and raises the same error for a closed one. + if type(self) is Connection: + return Cursor(self).execute(sql, parameters) return self.cursor().execute(sql, parameters) def executemany(self, sql, parameters): @@ -842,7 +987,13 @@ def iterdump(self): yield "COMMIT;" def create_function(self, name, narg, func, *, deterministic=False): - raise NotSupportedError("user-defined SQL functions are not supported on this platform") + self._check() + if func is None: + # Removing a function needs the engine's own hook; none of the + # platforms offers it, so a removed name stays callable. + return + if not _cn1sql.create_function(self._handle, name, narg, func): + raise NotSupportedError("user-defined SQL functions are not supported on this platform") def create_aggregate(self, name, n_arg, aggregate_class): raise NotSupportedError("user-defined aggregates are not supported on this platform") @@ -912,3 +1063,8 @@ def connect(database, timeout=5.0, detect_types=0, isolation_level="", check_sam factory=Connection, cached_statements=128, uri=False, *, autocommit=LEGACY_TRANSACTION_CONTROL): return factory(database, timeout, detect_types, isolation_level, check_same_thread, None, cached_statements, uri, autocommit=autocommit) + +# What _cn1sql.execute needs to decide, as _plain_free does, that no adapter +# applies, and to recognize the default text factory and transaction mode. +_cn1sql.setup(adapters, tuple((t, PrepareProtocol) for t in (int, str, float, bytes, type(None))), str, + LEGACY_TRANSACTION_CONTROL) diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/ssl.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/ssl.py new file mode 100644 index 00000000000..7aca2366de0 --- /dev/null +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/ssl.py @@ -0,0 +1,240 @@ +# Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. +# Licensed under the GNU General Public License version 2 with the Classpath +# exception, as the rest of the Codename One Python runtime. +"""ssl: contexts and their settings, for code that builds one to hand on. + +TLS is the platform's: the HTTP stack verifies certificates against the +device's trust store, so a context here records what was asked of it and is +accepted by the HTTP clients, but cannot wrap a socket. +""" + +import enum as _enum +import socket as _socket + +OPENSSL_VERSION = "Codename One platform TLS" +OPENSSL_VERSION_INFO = (3, 0, 0, 0, 0) +HAS_SNI = True +HAS_ALPN = True +HAS_NEVER_CHECK_COMMON_NAME = True + + +class VerifyMode(_enum.IntEnum): + CERT_NONE = 0 + CERT_OPTIONAL = 1 + CERT_REQUIRED = 2 + + +CERT_NONE = VerifyMode.CERT_NONE +CERT_OPTIONAL = VerifyMode.CERT_OPTIONAL +CERT_REQUIRED = VerifyMode.CERT_REQUIRED + + +class VerifyFlags(_enum.IntFlag): + VERIFY_DEFAULT = 0 + VERIFY_CRL_CHECK_LEAF = 4 + VERIFY_CRL_CHECK_CHAIN = 12 + VERIFY_X509_STRICT = 32 + VERIFY_X509_TRUSTED_FIRST = 32768 + VERIFY_X509_PARTIAL_CHAIN = 524288 + + +VERIFY_DEFAULT = VerifyFlags.VERIFY_DEFAULT +VERIFY_X509_STRICT = VerifyFlags.VERIFY_X509_STRICT +VERIFY_X509_PARTIAL_CHAIN = VerifyFlags.VERIFY_X509_PARTIAL_CHAIN +VERIFY_X509_TRUSTED_FIRST = VerifyFlags.VERIFY_X509_TRUSTED_FIRST + + +class _SSLMethod(_enum.IntEnum): + PROTOCOL_TLS = 2 + PROTOCOL_TLS_CLIENT = 16 + PROTOCOL_TLS_SERVER = 17 + + +PROTOCOL_TLS = _SSLMethod.PROTOCOL_TLS +PROTOCOL_SSLv23 = PROTOCOL_TLS +PROTOCOL_TLS_CLIENT = _SSLMethod.PROTOCOL_TLS_CLIENT +PROTOCOL_TLS_SERVER = _SSLMethod.PROTOCOL_TLS_SERVER + + +class Options(_enum.IntFlag): + OP_ALL = 0x80000054 + OP_NO_SSLv2 = 0 + OP_NO_SSLv3 = 0x2000000 + OP_NO_TLSv1 = 0x4000000 + OP_NO_TLSv1_1 = 0x10000000 + OP_NO_TLSv1_2 = 0x8000000 + OP_NO_TLSv1_3 = 0x20000000 + OP_NO_COMPRESSION = 0x20000 + OP_NO_RENEGOTIATION = 0x40000000 + + +OP_ALL = Options.OP_ALL +OP_NO_SSLv2 = Options.OP_NO_SSLv2 +OP_NO_SSLv3 = Options.OP_NO_SSLv3 +OP_NO_TLSv1 = Options.OP_NO_TLSv1 +OP_NO_TLSv1_1 = Options.OP_NO_TLSv1_1 +OP_NO_TLSv1_2 = Options.OP_NO_TLSv1_2 +OP_NO_TLSv1_3 = Options.OP_NO_TLSv1_3 +OP_NO_COMPRESSION = Options.OP_NO_COMPRESSION +OP_NO_RENEGOTIATION = Options.OP_NO_RENEGOTIATION + + +class TLSVersion(_enum.IntEnum): + MINIMUM_SUPPORTED = -2 + SSLv3 = 768 + TLSv1 = 769 + TLSv1_1 = 770 + TLSv1_2 = 771 + TLSv1_3 = 772 + MAXIMUM_SUPPORTED = -1 + + +class Purpose(_enum.Enum): + SERVER_AUTH = "1.3.6.1.5.5.7.3.1" + CLIENT_AUTH = "1.3.6.1.5.5.7.3.2" + + +class SSLError(OSError): + pass + + +class SSLZeroReturnError(SSLError): + pass + + +class SSLWantReadError(SSLError): + pass + + +class SSLWantWriteError(SSLError): + pass + + +class SSLSyscallError(SSLError): + pass + + +class SSLEOFError(SSLError): + pass + + +class SSLCertVerificationError(SSLError, ValueError): + pass + + +CertificateError = SSLCertVerificationError + + +class SSLContext: + def __init__(self, protocol=PROTOCOL_TLS_CLIENT): + self.protocol = protocol + client = protocol in (PROTOCOL_TLS_CLIENT,) + self.verify_mode = CERT_REQUIRED if client else CERT_NONE + self.check_hostname = client + self.verify_flags = VERIFY_DEFAULT + self.options = Options.OP_ALL | Options.OP_NO_SSLv3 + self.minimum_version = TLSVersion.MINIMUM_SUPPORTED + self.maximum_version = TLSVersion.MAXIMUM_SUPPORTED + self.post_handshake_auth = False + self.keylog_filename = None + self._alpn = [] + self._ca = [] + self._chain = None + + def load_default_certs(self, purpose=Purpose.SERVER_AUTH): + pass + + def load_verify_locations(self, cafile=None, capath=None, cadata=None): + self._ca.append((cafile, capath, cadata)) + + def load_cert_chain(self, certfile, keyfile=None, password=None): + self._chain = (certfile, keyfile) + + def set_default_verify_paths(self): + pass + + def set_alpn_protocols(self, protocols): + self._alpn = list(protocols) + + def set_ciphers(self, ciphers): + pass + + def get_ciphers(self): + return [] + + def set_npn_protocols(self, protocols): + pass + + def get_ca_certs(self, binary_form=False): + return [] + + def cert_store_stats(self): + return {"x509": 0, "crl": 0, "x509_ca": 0} + + def wrap_socket(self, sock, server_side=False, do_handshake_on_connect=True, + suppress_ragged_eofs=True, server_hostname=None, session=None): + raise SSLError("TLS over a raw socket is not available; the HTTP client handles TLS") + + def wrap_bio(self, incoming, outgoing, server_side=False, server_hostname=None, session=None): + raise SSLError("memory BIO TLS is not available; the HTTP client handles TLS") + + +class MemoryBIO: + def __init__(self): + self._buf = b"" + self.eof = False + + def write(self, b): + self._buf += bytes(b) + return len(b) + + def read(self, n=-1): + if n < 0: + n = len(self._buf) + r, self._buf = self._buf[:n], self._buf[n:] + return r + + def write_eof(self): + self.eof = True + + @property + def pending(self): + return len(self._buf) + + +class SSLSocket(_socket.socket): + pass + + +class SSLObject: + pass + + +def create_default_context(purpose=Purpose.SERVER_AUTH, *, cafile=None, capath=None, cadata=None): + ctx = SSLContext(PROTOCOL_TLS_CLIENT if purpose == Purpose.SERVER_AUTH else PROTOCOL_TLS_SERVER) + if cafile or capath or cadata: + ctx.load_verify_locations(cafile, capath, cadata) + return ctx + + +_create_default_https_context = create_default_context + + +def _create_unverified_context(*args, **kwargs): + ctx = SSLContext(PROTOCOL_TLS_CLIENT) + ctx.check_hostname = False + ctx.verify_mode = CERT_NONE + return ctx + + +class DefaultVerifyPaths: + cafile = None + capath = None + openssl_cafile_env = "SSL_CERT_FILE" + openssl_cafile = "" + openssl_capath_env = "SSL_CERT_DIR" + openssl_capath = "" + + +def get_default_verify_paths(): + return DefaultVerifyPaths() diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/string.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/string.py index c36c9cb81d3..f0704fbd1fc 100644 --- a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/string.py +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/string.py @@ -209,6 +209,16 @@ def _field_name_split(name): return first, iter(rest) +class _AttrField: + """A replacement field with an attribute part: the value it starts from + and the rest of the field (".real", ".a[1]").""" + __slots__ = ("base", "tail") + + def __init__(self, base, tail): + self.base = base + self.tail = tail + + class Formatter: def format(self, format_string, /, *args, **kwargs): return self.vformat(format_string, args, kwargs) @@ -238,6 +248,14 @@ def _vformat(self, format_string, args, kwargs, used_args, recursion_depth, auto auto_arg_index = False obj, arg_used = self.get_field(field_name, args, kwargs) used_args.add(arg_used) + if isinstance(obj, _AttrField): + # The attribute part goes to str.format, whose own field + # lookup reads it: nothing here names it at run time. + format_spec, auto_arg_index = self._vformat(format_spec, args, kwargs, used_args, + recursion_depth - 1, auto_arg_index=auto_arg_index) + conv = "" if conversion is None else "!" + conversion + result.append(("{0" + obj.tail + conv + ":" + format_spec + "}").format(obj.base)) + continue obj = self.convert_field(obj, conversion) format_spec, auto_arg_index = self._vformat(format_spec, args, kwargs, used_args, recursion_depth - 1, auto_arg_index=auto_arg_index) @@ -272,9 +290,14 @@ def parse(self, format_string): def get_field(self, field_name, args, kwargs): first, rest = _field_name_split(field_name) obj = self.get_value(first, args, kwargs) + tail = None for is_attr, i in rest: - if is_attr: - obj = getattr(obj, i) + if is_attr or tail is not None: + # From the first attribute part on, the field is resolved by + # str.format itself (see _vformat). + tail = (tail or "") + ("." + i if is_attr else "[" + str(i) + "]") else: obj = obj[i] + if tail is not None: + return _AttrField(obj, tail), first return obj, first diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/stringprep.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/stringprep.py new file mode 100644 index 00000000000..db90952a699 --- /dev/null +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/stringprep.py @@ -0,0 +1,133 @@ +# Copyright (c) 2001 Python Software Foundation; All Rights Reserved +# Licensed under the Python Software Foundation License Version 2; the full +# text is in maven/python-transpiler/third-party/cpython/LICENSE.txt. +# +# Derived from CPython's Lib/stringprep.py. Changes: rewritten for the Codename One +# Python runtime, trimmed to what the transpiler supports and reorganised; +# the C accelerators and platform-specific branches are left out. +"""stringprep: the RFC 3454 tables, as membership tests. + +The tables that RFC 3454 defines from Unicode 3.2 properties ask +unicodedata, which answers with its current version; a character assigned +after 3.2 is therefore not reported unassigned by in_table_a1. Table B.2 +and B.3 are approximated by full case folding.""" + +from unicodedata import ucd_3_2_0 as unicodedata + +assert unicodedata.unidata_version + + +def in_table_a1(code): + if unicodedata.category(code) != "Cn": + return False + c = ord(code) + if 0xFDD0 <= c < 0xFDF0: + return False + return (c & 0xFFFF) not in (0xFFFE, 0xFFFF) + + +b1_set = set([173, 847, 6150, 6155, 6156, 6157, 8203, 8204, 8205, 8288, 65279] + list(range(65024, 65040))) + + +def in_table_b1(code): + return ord(code) in b1_set + + +def map_table_b3(code): + return code.casefold() + + +def map_table_b2(a): + al = map_table_b3(a) + b = unicodedata.normalize("NFKC", al) + bl = "".join([map_table_b3(ch) for ch in b]) + c = unicodedata.normalize("NFKC", bl) + if b != c: + return c + return al + + +def in_table_c11(code): + return code == " " + + +def in_table_c12(code): + return unicodedata.category(code) == "Zs" and code != " " + + +def in_table_c11_c12(code): + return unicodedata.category(code) == "Zs" + + +def in_table_c21(code): + return ord(code) < 128 and unicodedata.category(code) == "Cc" + + +c22_specials = set([1757, 1807, 6158, 8204, 8205, 8232, 8233, 65279] + list(range(8288, 8292)) + + list(range(8298, 8304)) + list(range(65529, 65533)) + list(range(119155, 119163))) + + +def in_table_c22(code): + c = ord(code) + if c < 128: + return False + if unicodedata.category(code) == "Cc": + return True + return c in c22_specials + + +def in_table_c21_c22(code): + return unicodedata.category(code) == "Cc" or ord(code) in c22_specials + + +def in_table_c3(code): + return unicodedata.category(code) == "Co" + + +def in_table_c4(code): + c = ord(code) + if c < 0xFDD0: + return False + if c < 0xFDF0: + return True + return (ord(code) & 0xFFFF) in (0xFFFE, 0xFFFF) + + +def in_table_c5(code): + return unicodedata.category(code) == "Cs" + + +c6_set = set(range(65529, 65534)) + + +def in_table_c6(code): + return ord(code) in c6_set + + +c7_set = set(range(12272, 12284)) + + +def in_table_c7(code): + return ord(code) in c7_set + + +c8_set = set([832, 833, 8206, 8207] + list(range(8234, 8239)) + list(range(8298, 8304))) + + +def in_table_c8(code): + return ord(code) in c8_set + + +c9_set = set([917505] + list(range(917536, 917632))) + + +def in_table_c9(code): + return ord(code) in c9_set + + +def in_table_d1(code): + return unicodedata.bidirectional(code) in ("R", "AL") + + +def in_table_d2(code): + return unicodedata.bidirectional(code) == "L" diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/struct.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/struct.py index da2ddad8a23..6c1e6fd077f 100644 --- a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/struct.py +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/struct.py @@ -9,6 +9,8 @@ import math as _math +import _cn1struct + __all__ = ["calcsize", "pack", "pack_into", "unpack", "unpack_from", "iter_unpack", "Struct", "error"] @@ -215,8 +217,16 @@ class Struct: def __init__(self, format): self._items, self.size, self._little = _parse(format) self.format = format.decode("ascii") if isinstance(format, bytes) else format + # The items again for the Java loops, which do what CPython does in C + # and answer None whenever the Python code below has to run instead. + self._plan = _cn1struct.plan("".join(c for c, _, _ in self._items), + tuple(o for _, o, _ in self._items), + tuple(s for _, _, s in self._items), self._little) def pack(self, *args): + r = _cn1struct.pack(self._plan, self.size, args) + if r is not None: + return r return _pack_items(self._items, self.size, self._little, args) def pack_into(self, buffer, offset, *args): @@ -231,6 +241,9 @@ def pack_into(self, buffer, offset, *args): def unpack(self, buffer): if len(buffer) != self.size: raise error("unpack requires a buffer of %d bytes" % self.size) + r = _cn1struct.unpack(self._plan, buffer, 0) + if r is not None: + return r return _unpack_items(self._items, self._little, buffer, 0) def unpack_from(self, buffer, offset=0): @@ -239,6 +252,9 @@ def unpack_from(self, buffer, offset=0): if len(buffer) - offset < self.size: raise error("unpack_from requires a buffer of at least %d bytes for unpacking %d bytes at offset %d " "(actual buffer size is %d)" % (self.size + offset, self.size, offset, len(buffer))) + r = _cn1struct.unpack(self._plan, buffer, offset) + if r is not None: + return r return _unpack_items(self._items, self._little, buffer, offset) def iter_unpack(self, buffer): diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/subprocess.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/subprocess.py new file mode 100644 index 00000000000..2f6efd9f632 --- /dev/null +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/subprocess.py @@ -0,0 +1,113 @@ +# Copyright (c) 2001 Python Software Foundation; All Rights Reserved +# Licensed under the Python Software Foundation License Version 2; the full +# text is in maven/python-transpiler/third-party/cpython/LICENSE.txt. +# +# Derived from CPython's Lib/subprocess.py. Changes: rewritten for the Codename One +# Python runtime, trimmed to what the transpiler supports and reorganised; +# the C accelerators and platform-specific branches are left out. +# +# subprocess - Subprocesses with accessible I/O streams +# +# For more information about this module, see PEP 324. +# +# Copyright (c) 2003-2005 by Peter Astrand +# +# Licensed to PSF under a Contributor Agreement. + +"""subprocess: the API and its errors. A mobile application cannot start +another program, so Popen (and run, call, check_output over it) raises +FileNotFoundError, as CPython does for a command that is not installed; +code that probes for an optional tool takes its fallback.""" + +PIPE = -1 +STDOUT = -2 +DEVNULL = -3 + + +class SubprocessError(Exception): + pass + + +class CalledProcessError(SubprocessError): + def __init__(self, returncode, cmd, output=None, stderr=None): + self.returncode = returncode + self.cmd = cmd + self.output = output + self.stderr = stderr + + @property + def stdout(self): + return self.output + + def __str__(self): + return "Command '%s' returned non-zero exit status %d." % (self.cmd, self.returncode) + + +class TimeoutExpired(SubprocessError): + def __init__(self, cmd, timeout, output=None, stderr=None): + self.cmd = cmd + self.timeout = timeout + self.output = output + self.stderr = stderr + + def __str__(self): + return "Command '%s' timed out after %s seconds" % (self.cmd, self.timeout) + + +class CompletedProcess: + def __init__(self, args, returncode, stdout=None, stderr=None): + self.args = args + self.returncode = returncode + self.stdout = stdout + self.stderr = stderr + + def check_returncode(self): + if self.returncode: + raise CalledProcessError(self.returncode, self.args, self.stdout, self.stderr) + + +def _name(args): + if isinstance(args, (str, bytes)): + return args.split()[0] if args.split() else args + return list(args)[0] if args else "" + + +class Popen: + def __init__(self, args, *a, **kw): + self.args = args + raise FileNotFoundError(2, "No such file or directory: %r (a mobile application cannot run programs)" + % (_name(args),)) + + +def run(*popenargs, input=None, capture_output=False, timeout=None, check=False, **kwargs): + Popen(*popenargs, **kwargs) + + +def call(*popenargs, timeout=None, **kwargs): + Popen(*popenargs, **kwargs) + + +def check_call(*popenargs, **kwargs): + Popen(*popenargs, **kwargs) + + +def check_output(*popenargs, timeout=None, **kwargs): + Popen(*popenargs, **kwargs) + + +def getstatusoutput(cmd): + return (127, "/bin/sh: %s: command not found" % (_name(cmd),)) + + +def getoutput(cmd): + return getstatusoutput(cmd)[1] + + +def list2cmdline(seq): + out = [] + for a in seq: + if not a or " " in a or "\t" in a: + out.append('"' + a.replace('"', '\\"') + '"') + else: + out.append(a) + return " ".join(out) diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/tempfile.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/tempfile.py new file mode 100644 index 00000000000..62f35eb9130 --- /dev/null +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/tempfile.py @@ -0,0 +1,246 @@ +# Copyright (c) 2001 Python Software Foundation; All Rights Reserved +# Licensed under the Python Software Foundation License Version 2; the full +# text is in maven/python-transpiler/third-party/cpython/LICENSE.txt. +# +# Derived from CPython's Lib/tempfile.py. Changes: rewritten for the Codename One +# Python runtime, trimmed to what the transpiler supports and reorganised; +# the C accelerators and platform-specific branches are left out. +"""tempfile over the application's file system: temporary files live in +a tmp directory under the application's home, which the platform may clear +while the application is not running.""" + +import os as _os +import secrets as _secrets + +TMP_MAX = 10000 +template = "tmp" +tempdir = None + + +def gettempdir(): + global tempdir + if tempdir is None: + d = _os.environ.get("TMPDIR") or _os.path.join(_os.path.expanduser("~"), "tmp") + _os.makedirs(d, exist_ok=True) + tempdir = d + return tempdir + + +def gettempdirb(): + return gettempdir().encode() + + +def gettempprefix(): + return template + + +def _name(prefix, suffix, dir): + if dir is None: + dir = gettempdir() + for _ in range(TMP_MAX): + p = _os.path.join(dir, (prefix if prefix is not None else template) + _secrets.token_hex(4) + + (suffix or "")) + if not _os.path.exists(p): + return p + raise FileExistsError("No usable temporary file name found") + + +def mkstemp(suffix=None, prefix=None, dir=None, text=False): + """Answers (None, path): there are no file descriptors, so open the path.""" + p = _name(prefix, suffix, dir) + open(p, "wb").close() + return (None, _os.path.abspath(p)) + + +def mkdtemp(suffix=None, prefix=None, dir=None): + p = _name(prefix, suffix, dir) + _os.mkdir(p) + return _os.path.abspath(p) + + +def mktemp(suffix="", prefix=template, dir=None): + return _name(prefix, suffix, dir) + + +class _TemporaryFileWrapper: + def __init__(self, file, name, delete=True): + self.file = file + self.name = name + self.delete = delete + + # The file API by name, each forwarded: a __getattr__ that forwards + # any name hands back a value of no type. + def read(self, *a): + return self.file.read(*a) + + def readline(self, *a): + return self.file.readline(*a) + + def readlines(self, *a): + return self.file.readlines(*a) + + def write(self, s): + return self.file.write(s) + + def writelines(self, lines): + return self.file.writelines(lines) + + def seek(self, *a): + return self.file.seek(*a) + + def tell(self): + return self.file.tell() + + def flush(self): + return self.file.flush() + + def truncate(self, *a): + return self.file.truncate(*a) + + def fileno(self): + return self.file.fileno() + + def readable(self): + return self.file.readable() + + def writable(self): + return self.file.writable() + + def seekable(self): + return self.file.seekable() + + @property + def closed(self): + return self.file.closed + + @property + def mode(self): + return self.file.mode + + def __iter__(self): + return iter(self.file) + + def close(self): + if not self.file.closed: + self.file.close() + if self.delete and _os.path.exists(self.name): + _os.remove(self.name) + + def __enter__(self): + self.file.__enter__() + return self + + def __exit__(self, *exc): + self.close() + return False + + +def NamedTemporaryFile(mode="w+b", buffering=-1, encoding=None, newline=None, suffix=None, prefix=None, + dir=None, delete=True, *, errors=None, delete_on_close=True): + p = _name(prefix, suffix, dir) + open(p, "wb").close() + f = open(p, mode.replace("x", "w") if "+" in mode or "w" in mode else mode + "+", encoding=encoding, + newline=newline) if "b" not in mode else open(p, mode) + return _TemporaryFileWrapper(f, _os.path.abspath(p), delete) + + +TemporaryFile = NamedTemporaryFile + + +class SpooledTemporaryFile: + def __init__(self, max_size=0, mode="w+b", buffering=-1, encoding=None, newline=None, suffix=None, + prefix=None, dir=None, *, errors=None): + import io + self._file = io.BytesIO() if "b" in mode else io.StringIO() + self._rolled = False + + # The file API by name, each forwarded: a __getattr__ that forwards + # any name hands back a value of no type. + def read(self, *a): + return self._file.read(*a) + + def readline(self, *a): + return self._file.readline(*a) + + def readlines(self, *a): + return self._file.readlines(*a) + + def write(self, s): + return self._file.write(s) + + def writelines(self, lines): + return self._file.writelines(lines) + + def seek(self, *a): + return self._file.seek(*a) + + def tell(self): + return self._file.tell() + + def flush(self): + return self._file.flush() + + def truncate(self, *a): + return self._file.truncate(*a) + + def fileno(self): + return self._file.fileno() + + def readable(self): + return self._file.readable() + + def writable(self): + return self._file.writable() + + def seekable(self): + return self._file.seekable() + + @property + def closed(self): + return self._file.closed + + @property + def mode(self): + return self._file.mode + + def close(self): + return self._file.close() + + def getvalue(self): + return self._file.getvalue() + + def rollover(self): + self._rolled = True + + def __iter__(self): + return iter(self._file) + + def __enter__(self): + return self + + def __exit__(self, *exc): + self._file.close() + return False + + +class TemporaryDirectory: + def __init__(self, suffix=None, prefix=None, dir=None, ignore_cleanup_errors=False, *, delete=True): + self.name = mkdtemp(suffix, prefix, dir) + self._ignore = ignore_cleanup_errors + self._delete = delete + + def cleanup(self): + import shutil + if _os.path.exists(self.name): + shutil.rmtree(self.name, ignore_errors=self._ignore) + + def __enter__(self): + return self.name + + def __exit__(self, *exc): + if self._delete: + self.cleanup() + return False + + def __repr__(self): + return "" % (self.name,) diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/threading.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/threading.py index e9f11e53bc1..3dd20e94e29 100644 --- a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/threading.py +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/threading.py @@ -369,7 +369,10 @@ def excepthook(args): class Thread: - def __init__(self, group=None, target=None, name=None, args=(), kwargs=None, *, daemon=None): + def __init__(self, group=None, target=None, name=None, args=(), kwargs=None, *, daemon=None, context=None): + # Python 3.14: the contextvars.Context run() runs in; None is a new, + # empty one, which is what 3.14 does unless told to inherit. + self._context = context self._target = target self._args = args self._kwargs = kwargs if kwargs is not None else {} @@ -432,11 +435,16 @@ def _bootstrap(self): _active[self._ident] = self self._started.set() try: - self.run() + if self._context is None: + import contextvars + self._context = contextvars.Context() + self._context.run(self.run) except BaseException as e: excepthook(ExceptHookArgs(type(e), e, None, self)) finally: _active.pop(self._ident, None) + import contextvars + contextvars._forget(self._ident) self._done.set() def run(self): diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/time.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/time.py index 0370006a4d5..d28614ad23b 100644 --- a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/time.py +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/time.py @@ -54,17 +54,50 @@ def __new__(cls, seq, zone=None, gmtoff=None): self._gmtoff = seq[10] if len(seq) > 10 else gmtoff return self - tm_year = property(lambda self: self[0]) - tm_mon = property(lambda self: self[1]) - tm_mday = property(lambda self: self[2]) - tm_hour = property(lambda self: self[3]) - tm_min = property(lambda self: self[4]) - tm_sec = property(lambda self: self[5]) - tm_wday = property(lambda self: self[6]) - tm_yday = property(lambda self: self[7]) - tm_isdst = property(lambda self: self[8]) - tm_zone = property(lambda self: self._zone) - tm_gmtoff = property(lambda self: self._gmtoff) + @property + def tm_year(self): + return self[0] + + @property + def tm_mon(self): + return self[1] + + @property + def tm_mday(self): + return self[2] + + @property + def tm_hour(self): + return self[3] + + @property + def tm_min(self): + return self[4] + + @property + def tm_sec(self): + return self[5] + + @property + def tm_wday(self): + return self[6] + + @property + def tm_yday(self): + return self[7] + + @property + def tm_isdst(self): + return self[8] + + @property + def tm_zone(self): + return self._zone + + @property + def tm_gmtoff(self): + return self._gmtoff + def __repr__(self): return ("time.struct_time(tm_year=%d, tm_mon=%d, tm_mday=%d, tm_hour=%d, tm_min=%d, " diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/types.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/types.py index 1d5c8ba60b8..4dedb2676b0 100644 --- a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/types.py +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/types.py @@ -38,19 +38,47 @@ def _m(self): MethodType = type(_C()._m) BuiltinFunctionType = type(len) BuiltinMethodType = type([].append) +WrapperDescriptorType = type(object.__init__) +MethodWrapperType = type(object().__str__) +MethodDescriptorType = type(str.join) +ClassMethodDescriptorType = type(dict.fromkeys) + + +class MemberDescriptorType: + """The type of a __slots__ member descriptor. A slot here is stored + with the instance and has no descriptor on the class, so nothing is an + instance of this type: an isinstance check against it answers False, as + it does in CPython for anything that is not a slot.""" + + +class GetSetDescriptorType: + """The type of a built-in getset descriptor; as MemberDescriptorType, + there are none to be instances of it.""" NoneType = type(None) NotImplementedType = type(NotImplemented) EllipsisType = type(...) GenericAlias = type(list[int]) UnionType = type(int | str) +import sys as _sys +ModuleType = type(_sys) + + +def _traceback_type(): + try: + raise ValueError + except ValueError as e: + return type(e.__traceback__) + + +TracebackType = _traceback_type() class SimpleNamespace: def __init__(self, mapping=None, /, **kwargs): if mapping is not None: kwargs = {**dict(mapping), **kwargs} - for k, v in kwargs.items(): - setattr(self, k, v) + # A namespace is its dict: the names are the caller's data. + self.__dict__.update(kwargs) def __repr__(self): items = ("%s=%r" % (k, v) for k, v in self.__dict__.items()) diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/typing.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/typing.py index 1b00ff76a14..032bf93cc51 100644 --- a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/typing.py +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/typing.py @@ -25,6 +25,52 @@ def _type_repr(obj): return repr(obj) +# Subscriptions are memoized, as CPython's typing does with _tp_cache: code +# that writes cast(List[X], v) in a loop builds the alias once. The type of +# the parameters is part of the key (Literal[1] is not Literal[True]), and an +# unhashable subscription is simply not cached. +_tp_cache = {} + + +# One dict per kind, of one dict per owner, for a subscript by a single +# class (`List[str]` in a `cast` that runs in a loop): a class hashes and +# compares by identity, so it is the key by itself -- no key tuple, and no +# closure made on every hit as `_cached` needs. +_by_class = ({}, {}, {}, {}) + + +def _cached_class(kind, owner, params, make): + per = _by_class[kind].get(owner) + if per is None: + per = {} + if len(_by_class[kind]) >= 4096: + _by_class[kind].clear() + _by_class[kind][owner] = per + hit = per.get(params) + if hit is None: + hit = make(owner, params) + per[params] = hit + return hit + + +def _form_getitem(form, params): + return form._getitem(form, params) + + +def _cached(kind, owner, params, make): + key = (kind, owner, params, type(params)) + try: + hit = _tp_cache.get(key) + except TypeError: + return make() + if hit is None: + hit = make() + if len(_tp_cache) >= 4096: + _tp_cache.clear() + _tp_cache[key] = hit + return hit + + class _Final: __slots__ = () @@ -70,7 +116,9 @@ def __repr__(self): def __getitem__(self, params): if self._getitem is None: raise TypeError(self._name + " is not subscriptable") - return self._getitem(self, params) + if type(params) is type: + return _cached_class(0, self, params, _form_getitem) + return _cached(0, self, params, lambda: self._getitem(self, params)) def __call__(self, *args, **kwds): raise TypeError("Cannot instantiate " + repr(self)) @@ -123,6 +171,11 @@ def __call__(self, *args, **kwargs): return result def __getitem__(self, params): + if type(params) is type: + return _cached_class(1, self, params, type(self)._subscript) + return _cached(1, self, params, lambda: self._subscript(params)) + + def _subscript(self, params): if not isinstance(params, tuple): params = (params,) subst = dict(zip(self.__parameters__, params)) @@ -242,6 +295,11 @@ def __repr__(self): return "typing." + self._name def __getitem__(self, params): + if type(params) is type: + return _cached_class(2, self, params, _SpecialGenericAlias._subscript) + return _cached(2, self, params, lambda: self._subscript(params)) + + def _subscript(self, params): if self._name == "Callable" and isinstance(params, tuple) and len(params) == 2: args, result = params if args is ...: @@ -326,6 +384,15 @@ def _lazy_collections(): AnyStr = None +def _lazy_re(): + import re + return re + + +Pattern = _SpecialGenericAlias(_lazy_re().Pattern, "Pattern", 1) +Match = _SpecialGenericAlias(_lazy_re().Match, "Match", 1) + + class TypeVar(_Final): def __init__(self, name, *constraints, bound=None, covariant=False, contravariant=False, infer_variance=False, default=None): @@ -400,31 +467,28 @@ class Generic: __slots__ = () def __class_getitem__(cls, params): - if not isinstance(params, tuple): - params = (params,) - if cls is Generic or cls is Protocol: - return _GenericAlias(cls, params, cls.__name__) - return _GenericAlias(cls, params) + if type(params) is type: + return _cached_class(3, cls, params, _generic_alias) + return _cached(3, cls, params, lambda: _generic_alias(cls, params)) def __init_subclass__(cls, *args, **kwargs): super().__init_subclass__(*args, **kwargs) -class _ProtocolMeta(type(_abc.Sized)): - def __instancecheck__(cls, instance): - if not cls.__dict__.get("_is_runtime_protocol", False) and not cls.__dict__.get("_is_protocol", False): - return super().__instancecheck__(instance) - if super().__instancecheck__(instance): - return True - if cls.__dict__.get("_is_protocol", False) and not cls.__dict__.get("_is_runtime_protocol", False): - raise TypeError("Instance and class checks can only be used with @runtime_checkable protocols") - for attr in cls.__protocol_attrs__: - if not hasattr(instance, attr): - return False - return True +def _generic_alias(cls, params): + if not isinstance(params, tuple): + params = (params,) + if cls is Generic or cls is Protocol: + return _GenericAlias(cls, params, cls.__name__) + return _GenericAlias(cls, params) -class Protocol(Generic, metaclass=_ProtocolMeta): +# Protocol has no metaclass. isinstance and issubclass against a protocol +# class are answered by the runtime (PyType.protocolCheck) through the +# member check the transpiler generates for each protocol body from its +# literal member names (ProtocolChecks): no member is looked up by a +# computed name. +class Protocol(Generic): __slots__ = () _is_protocol = True @@ -432,22 +496,6 @@ def __init_subclass__(cls, *args, **kwargs): super().__init_subclass__(*args, **kwargs) if not cls.__dict__.get("_is_protocol", False): cls._is_protocol = any(b is Protocol for b in cls.__bases__) - attrs = set() - for base in cls.__mro__[:-1]: - if base.__name__ in ("Protocol", "Generic", "object"): - continue - for name in list(base.__dict__.keys()) + list(base.__dict__.get("__annotations__", {}).keys()): - if not name.startswith("_abc_") and name not in ("__module__", "__qualname__", "__doc__", - "__annotations__", "__dict__", "__weakref__", - "__init__", "__slots__", "_is_protocol", - "__abstractmethods__", "__parameters__", - "__orig_bases__", "__protocol_attrs__", - "_is_runtime_protocol", "__init_subclass__", - "__subclasshook__", "__match_args__", - "__firstlineno__", "__static_attributes__", - "_abc_registry"): - attrs.add(name) - cls.__protocol_attrs__ = attrs def runtime_checkable(cls): @@ -455,8 +503,9 @@ def runtime_checkable(cls): return cls -def cast(typ, val): - return val +# A builtin, so that a call the compiler can see is this one skips building +# its type argument (see StdModules.CAST). +from _cn1op import cast def assert_type(val, typ, /): @@ -562,10 +611,11 @@ class _HintParser: `X[...]`, `|`, `None`, `...` and string literals, which is the grammar annotations are written in.""" - def __init__(self, text, ns): + def __init__(self, text, ns, hints): self.text = text self.pos = 0 self.ns = ns + self.hints = hints def _ws(self): while self.pos < len(self.text) and self.text[self.pos] == " ": @@ -594,7 +644,7 @@ def _primary(self): end = self.text.index(c, self.pos + 1) inner = self.text[self.pos + 1:end] self.pos = end + 1 - return _HintParser(inner, self.ns).parse() + return _HintParser(inner, self.ns, self.hints).parse() if self.text.startswith("...", self.pos): self.pos += 3 return ... @@ -625,24 +675,33 @@ def _items(self, close): return items def _lookup(self, name): - parts = name.split(".") - if parts[0] == "None": + # A forward reference resolves to what the build resolved it to: + # `self.hints` is the module's `__cn1_hints__` table, which the + # compiler writes from every string annotation in the module, each + # entry a compiled reference. `self.ns` holds only what the caller + # handed over (globalns/localns, the class being read). Nothing is + # looked up in a module's or class's namespace by the string. + if name == "None": return None - if parts[0] in self.ns: - value = self.ns[parts[0]] - else: - import builtins - if not hasattr(builtins, parts[0]): - raise NameError("name '" + parts[0] + "' is not defined") - value = getattr(builtins, parts[0]) - for p in parts[1:]: - value = getattr(value, p) - return value + if "." not in name and name in self.ns: + return self.ns[name] + if name in self.hints: + return self.hints[name] + raise NameError("forward reference " + repr(name) + " in annotation " + repr(self.text) + + " was not resolved at build time: only names a string annotation of the" + + " module spells, bound in its globals or builtins, are resolvable") + + +def _module_hints(modname): + import sys + m = sys.modules.get(modname) if modname is not None else None + table = getattr(m, "__cn1_hints__", None) if m is not None else None + return table() if table is not None else {} -def _resolve_hint(value, ns): +def _resolve_hint(value, ns, hints): if isinstance(value, str): - return _HintParser(value, ns).parse() + return _HintParser(value, ns, hints).parse() return value @@ -651,18 +710,31 @@ def get_type_hints(obj, globalns=None, localns=None, include_extras=False): hints = {} if isinstance(obj, type): for base in reversed(obj.__mro__): - ns = dict(globalns) if globalns is not None else dict(getattr(sys.modules.get(base.__module__), "__dict__", {})) + ns = dict(globalns) if globalns is not None else {} ns.setdefault(base.__name__, base) if localns: ns.update(localns) + table = None for k, v in base.__dict__.get("__annotations__", {}).items(): - hints[k] = _resolve_hint(v, ns) + if table is None and isinstance(v, str): + table = _module_hints(base.__module__) + hints[k] = _resolve_hint(v, ns, table) else: - ns = dict(globalns) if globalns is not None else dict(getattr(obj, "__globals__", {})) + # As CPython does: a bound method or a decorated function is read + # through to the function it wraps, whose module the names are in. + while True: + inner = getattr(obj, "__wrapped__", None) or getattr(obj, "__func__", None) + if inner is None or inner is obj: + break + obj = inner + ns = dict(globalns) if globalns is not None else {} if localns: ns.update(localns) + table = None for k, v in getattr(obj, "__annotations__", {}).items(): - hints[k] = _resolve_hint(v, ns) + if table is None and isinstance(v, str): + table = _module_hints(getattr(obj, "__module__", None)) + hints[k] = _resolve_hint(v, ns, table) if not include_extras: for k, v in list(hints.items()): if isinstance(v, _AnnotatedAlias): @@ -706,20 +778,28 @@ def __getitem__(self, params): return _GenericAlias(self, params) -class _NamedTupleMeta(type): - def __new__(cls, typename, bases, ns): - import collections - types = ns.get("__annotations__", {}) - default_names = [n for n in types if n in ns] - nm_tpl = collections.namedtuple(typename, list(types.keys()), - defaults=[ns[n] for n in default_names], - module=ns.get("__module__", "__main__")) - nm_tpl.__annotations__ = types - for key, val in ns.items(): - if key not in ("__annotations__", "__module__", "__qualname__") and key not in types and \ - key not in ("__slots__", "_fields", "__new__", "__init__"): - setattr(nm_tpl, key, val) +def __NamedTupleMeta__new__(cls, typename, bases, ns): + import collections + types = ns.get("__annotations__", {}) + default_names = [n for n in types if n in ns] + nm_tpl = collections.namedtuple(typename, list(types.keys()), + defaults=[ns[n] for n in default_names], + module=ns.get("__module__", "__main__")) + nm_tpl.__annotations__ = types + # The body's own members go on a subclass built from them, rather than + # being stored onto the tuple class one computed name at a time. + extra = {key: val for key, val in ns.items() + if key not in ("__annotations__", "__module__", "__qualname__") and key not in types + and key not in ("__slots__", "_fields", "__new__", "__init__")} + if not extra: return nm_tpl + extra["__slots__"] = () + return type(typename, (nm_tpl,), extra) + + +# Made by a call rather than a class statement: a class deriving from +# `type` has no layout, and this metaclass is only ever used dynamically. +_NamedTupleMeta = type("_NamedTupleMeta", (type,), {"__new__": staticmethod(__NamedTupleMeta__new__)}) def NamedTuple(typename, fields=None, /, **kwargs): @@ -742,27 +822,46 @@ def _namedtuple_mro_entries(bases): NamedTuple.__mro_entries__ = _namedtuple_mro_entries -class _TypedDictMeta(type): - def __new__(cls, name, bases, ns, total=True): - annotations = {} - for base in bases: - annotations.update(base.__dict__.get("__annotations__", {})) - annotations.update(ns.get("__annotations__", {})) - tp_dict = type.__new__(_TypedDictMeta, name, (dict,), ns) - tp_dict.__annotations__ = annotations - tp_dict.__total__ = total - tp_dict.__required_keys__ = frozenset(annotations) if total else frozenset() - tp_dict.__optional_keys__ = frozenset() if total else frozenset(annotations) - return tp_dict +def __TypedDictMeta__new__(cls, name, bases, ns, total=True): + annotations = {} + required = set() + optional = set() + for base in bases: + annotations.update(base.__dict__.get("__annotations__", {})) + required.update(base.__dict__.get("__required_keys__", ())) + optional.update(base.__dict__.get("__optional_keys__", ())) + own = ns.get("__annotations__", {}) + annotations.update(own) + # Each key takes its class's totality, unless Required[...] or + # NotRequired[...] (possibly inside Annotated) says otherwise. + for key, hint in own.items(): + form = get_origin(hint) + if form is Annotated: + form = get_origin(get_args(hint)[0]) + if form is Required or (form is not NotRequired and total): + required.add(key) + optional.discard(key) + else: + optional.add(key) + required.discard(key) + tp_dict = type.__new__(_TypedDictMeta, name, (dict,), ns) + tp_dict.__annotations__ = annotations + tp_dict.__total__ = total + tp_dict.__required_keys__ = frozenset(required) + tp_dict.__optional_keys__ = frozenset(optional) + return tp_dict + +def __TypedDictMeta__call__(cls, *args, **kwargs): + # A TypedDict describes a plain dict; instances are exactly that. + return dict(*args, **kwargs) - def __call__(cls, *args, **kwargs): - # A TypedDict describes a plain dict; instances are exactly that. - return dict(*args, **kwargs) +def __TypedDictMeta__instancecheck__(cls, other): + raise TypeError("TypedDict does not support instance and class checks") - def __instancecheck__(cls, other): - raise TypeError("TypedDict does not support instance and class checks") - __subclasscheck__ = __instancecheck__ +# Made by a call rather than a class statement: a class deriving from +# `type` has no layout, and this metaclass is only ever used dynamically. +_TypedDictMeta = type("_TypedDictMeta", (type,), {"__new__": staticmethod(__TypedDictMeta__new__), "__call__": __TypedDictMeta__call__, "__instancecheck__": __TypedDictMeta__instancecheck__, "__subclasscheck__": __TypedDictMeta__instancecheck__}) def TypedDict(typename, fields=None, /, *, total=True, **kwargs): @@ -812,3 +911,18 @@ def __round__(self, ndigits=0): runtime_checkable(SupportsIndex) runtime_checkable(SupportsAbs) runtime_checkable(SupportsRound) + + +class IO(Generic[AnyStr]): + """The type of a file object, for annotations; the runtime's files are + not subclasses of it, as CPython's are not either.""" + __slots__ = () + + +class BinaryIO(IO[bytes]): + __slots__ = () + + +class TextIO(IO[str]): + __slots__ = () + diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/unicodedata.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/unicodedata.py new file mode 100644 index 00000000000..53fc87dbd1c --- /dev/null +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/unicodedata.py @@ -0,0 +1,543 @@ +# Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. +# Licensed under the GNU General Public License version 2 with the Classpath +# exception, as the rest of the Codename One Python runtime. +"""unicodedata: character properties and normalization. + +The tables at the end of this file are derived from the Unicode Character +Database (https://www.unicode.org/ucd/), copyright Unicode, Inc., and are +used under the Unicode License v3. They are generated by +scripts/python/gen-unicodedata.py; do not edit them by hand. + +Every table is zlib-compressed and base64 encoded, and is decompressed only +by the first call that needs it: + +- properties: runs of code points sharing one (category, bidi, combining, + mirrored, east asian width) record, searched with bisect; +- names: front coded (each name stores how many leading characters it + shares with the previous one) and decoded whole on first use; names that end in the code point's hex (CJK and other ideographs) are + stored as ranges, and Hangul syllable names are computed; +- decompositions and numeric values: one text line per code point. +""" + +import zlib as _zlib +import base64 as _base64 +from bisect import bisect_right as _bisect_right + + +def _blob(chunks): + return _zlib.decompress(_base64.b64decode("".join(chunks))) + + +def _varints(data): + out = [] + v = 0 + shift = 0 + for x in data: + v = v | ((x & 127) << shift) + if x & 128: + shift = shift + 7 + else: + out.append(v) + v = 0 + shift = 0 + return out + + +_props = None + + +def _load_props(): + global _props + if _props is None: + recs = [] + for line in _blob(_D_RECORDS).decode("ascii").split("\n"): + f = line.split(",") + recs.append((f[0], f[1], int(f[2]), int(f[3]), f[4])) + nums = _varints(_blob(_D_RUNS)) + starts = [] + ids = [] + pos = 0 + i = 0 + while i < len(nums): + starts.append(pos) + pos = pos + nums[i] + ids.append(recs[nums[i + 1]]) + i = i + 2 + _props = (starts, ids) + return _props + + +def _cp(chr, fname): + if not isinstance(chr, str): + raise TypeError(fname + "() argument must be a unicode character, not " + type(chr).__name__) + if len(chr) != 1: + raise TypeError(fname + "() argument must be a unicode character, not str") + return ord(chr) + + +def _rec(cp): + p = _props + if p is None: + p = _load_props() + return p[1][_bisect_right(p[0], cp) - 1] + + +def category(chr): + return _rec(_cp(chr, "category"))[0] + + +def bidirectional(chr): + return _rec(_cp(chr, "bidirectional"))[1] + + +def combining(chr): + return _rec(_cp(chr, "combining"))[2] + + +def mirrored(chr): + return _rec(_cp(chr, "mirrored"))[3] + + +def east_asian_width(chr): + return _rec(_cp(chr, "east_asian_width"))[4] + + +# ---------------------------------------------------------------- names + +_JAMO_L = ["G", "GG", "N", "D", "DD", "R", "M", "B", "BB", "S", "SS", "", + "J", "JJ", "C", "K", "T", "P", "H"] +_JAMO_V = ["A", "AE", "YA", "YAE", "EO", "E", "YEO", "YE", "O", "WA", "WAE", + "OE", "YO", "U", "WEO", "WE", "WI", "YU", "EU", "YI", "I"] +_JAMO_T = ["", "G", "GG", "GS", "N", "NJ", "NH", "D", "L", "LG", "LM", "LB", + "LS", "LT", "LP", "LH", "M", "B", "BS", "S", "SS", "NG", "J", "C", + "K", "T", "P", "H"] +_SBASE = 0xAC00 +_LBASE = 0x1100 +_VBASE = 0x1161 +_TBASE = 0x11A7 +_VCOUNT = 21 +_TCOUNT = 28 +_NCOUNT = _VCOUNT * _TCOUNT +_SCOUNT = 19 * _NCOUNT + +_names = None +_lookup_table = None + + +def _load_names(): + global _names + if _names is None: + deltas = _varints(_blob(_D_NAME_CPS)) + cps = [] + cp = -1 + for d in deltas: + cp = cp + d + cps.append(cp) + names = [] + prev = "" + for line in _blob(_D_NAMES).decode("ascii").split("\n"): + prev = prev[:ord(line[0]) - 48] + line[1:] + names.append(prev) + _names = (cps, names) + return _names + + +def _hex(cp): + h = "%X" % cp + while len(h) < 4: + h = "0" + h + return h + + +def _name(cp): + if _SBASE <= cp < _SBASE + _SCOUNT: + s = cp - _SBASE + return ("HANGUL SYLLABLE " + _JAMO_L[s // _NCOUNT] + + _JAMO_V[(s % _NCOUNT) // _TCOUNT] + _JAMO_T[s % _TCOUNT]) + for r in _NAME_RANGES: + if r[1] <= cp <= r[2]: + return r[0] + _hex(cp) + cps, names = _load_names() + i = _bisect_right(cps, cp) - 1 + if i < 0 or cps[i] != cp: + return None + return names[i] + + +def name(chr, *default): + n = _name(_cp(chr, "name")) + if n is None: + if default: + return default[0] + raise ValueError("no such name") + return n + + +def _load_lookup(): + global _lookup_table + if _lookup_table is None: + cps, names = _load_names() + t = {} + i = 0 + while i < len(cps): + t[names[i]] = cps[i] + i = i + 1 + _lookup_table = t + return _lookup_table + + +def _parse_hex(s): + if len(s) < 4 or len(s) > 6: + return -1 + v = 0 + for c in s: + if "0" <= c <= "9": + v = v * 16 + (ord(c) - 48) + elif "A" <= c <= "F": + v = v * 16 + (ord(c) - 55) + else: + return -1 + return v + + +def lookup(name): + if isinstance(name, (bytes, bytearray)): + name = name.decode("ascii") + key = name.upper() + if key.startswith("HANGUL SYLLABLE "): + rest = key[16:] + s = 0 + while s < _SCOUNT: + if _name(_SBASE + s)[16:] == rest: + return chr(_SBASE + s) + s = s + 1 + for r in _NAME_RANGES: + if key.startswith(r[0]): + v = _parse_hex(key[len(r[0]):]) + if r[1] <= v <= r[2] and key == r[0] + _hex(v): + return chr(v) + cp = _load_lookup().get(key) + if cp is None: + raise KeyError("undefined character name '" + name + "'") + return chr(cp) + + +# ------------------------------------------------- decomposition, numbers + +_decomp = None +_numeric = None + + +def _load_decomp(): + global _decomp + if _decomp is None: + t = {} + cp = 0 + for line in _blob(_D_DECOMP).decode("ascii").split("\n"): + sp = line.index(" ") + cp = cp + int(line[:sp], 16) + t[cp] = line[sp + 1:] + _decomp = t + return _decomp + + +def decomposition(chr): + cp = _cp(chr, "decomposition") + if _SBASE <= cp < _SBASE + _SCOUNT: + s = cp - _SBASE + d = _hex(_LBASE + s // _NCOUNT) + " " + _hex(_VBASE + (s % _NCOUNT) // _TCOUNT) + if s % _TCOUNT: + d = d + " " + _hex(_TBASE + s % _TCOUNT) + return d + return _load_decomp().get(cp, "") + + +def _load_numeric(): + global _numeric + if _numeric is None: + t = {} + cp = 0 + for line in _blob(_D_NUMERIC).decode("ascii").split("\n"): + f = line.split(":") + cp = cp + int(f[0], 16) + dec = None + dig = None + if f[1] != "": + dec = int(f[1]) + if f[2] != "": + dig = int(f[2]) + t[cp] = (dec, dig, float(f[3])) + _numeric = t + return _numeric + + +def _num(chr, fname, idx, default): + e = _load_numeric().get(_cp(chr, fname)) + v = None + if e is not None: + v = e[idx] + if v is None: + if default: + return default[0] + if idx == 2: + raise ValueError("not a numeric character") + if idx == 1: + raise ValueError("not a digit") + raise ValueError("not a decimal") + return v + + +def decimal(chr, *default): + return _num(chr, "decimal", 0, default) + + +def digit(chr, *default): + return _num(chr, "digit", 1, default) + + +def numeric(chr, *default): + return _num(chr, "numeric", 2, default) + + +# ---------------------------------------------------------- normalization + +_canon = None +_compat = None +_compose_pairs = None + + +def _hexlist(parts, start): + out = [] + i = start + while i < len(parts): + out.append(int(parts[i], 16)) + i = i + 1 + return out + + +def _load_norm(): + global _canon, _compat, _compose_pairs + if _canon is None: + canon = {} + compat = {} + for cp, d in _load_decomp().items(): + parts = d.split(" ") + if parts[0].startswith("<"): + compat[cp] = _hexlist(parts, 1) + else: + canon[cp] = _hexlist(parts, 0) + excluded = set(_COMPOSITION_EXCLUSIONS) + pairs = {} + for cp, d in canon.items(): + if len(d) == 2 and cp not in excluded: + pairs[d[0] * 0x110000 + d[1]] = cp + _compat = compat + _compose_pairs = pairs + _canon = canon + + +def _decompose_into(cp, out, compat): + if _SBASE <= cp < _SBASE + _SCOUNT: + s = cp - _SBASE + out.append(_LBASE + s // _NCOUNT) + out.append(_VBASE + (s % _NCOUNT) // _TCOUNT) + t = s % _TCOUNT + if t: + out.append(_TBASE + t) + return + d = _canon.get(cp) + if d is None and compat: + d = _compat.get(cp) + if d is None: + out.append(cp) + return + for x in d: + _decompose_into(x, out, compat) + + +def _decompose(s, compat): + out = [] + for ch in s: + _decompose_into(ord(ch), out, compat) + # canonical ordering: stable sort of each run of non-starters + n = len(out) + ccc = [_rec(c)[2] for c in out] + i = 0 + while i < n: + if ccc[i] == 0: + i = i + 1 + continue + j = i + while j < n and ccc[j] != 0: + j = j + 1 + if j - i > 1: + run = sorted(range(i, j), key=lambda k: ccc[k]) + vals = [out[k] for k in run] + cls = [ccc[k] for k in run] + out[i:j] = vals + ccc[i:j] = cls + i = j + return out, ccc + + +def _pair(a, b): + if _LBASE <= a < _LBASE + 19 and _VBASE <= b < _VBASE + _VCOUNT: + return _SBASE + ((a - _LBASE) * _VCOUNT + (b - _VBASE)) * _TCOUNT + if (_SBASE <= a < _SBASE + _SCOUNT and (a - _SBASE) % _TCOUNT == 0 + and _TBASE < b < _TBASE + _TCOUNT): + return a + (b - _TBASE) + return _compose_pairs.get(a * 0x110000 + b) + + +def _compose(cps, ccc): + if not cps: + return cps + out = [cps[0]] + starter_pos = 0 + last = ccc[0] + if last != 0: + last = 256 + i = 1 + while i < len(cps): + c = cps[i] + cl = ccc[i] + comp = _pair(out[starter_pos], c) + if comp is not None and (last < cl or last == 0): + out[starter_pos] = comp + else: + if cl == 0: + starter_pos = len(out) + last = cl + out.append(c) + i = i + 1 + return out + + +def normalize(form, unistr): + if not isinstance(unistr, str): + raise TypeError("normalize() argument 2 must be str, not " + type(unistr).__name__) + if form not in ("NFC", "NFD", "NFKC", "NFKD"): + raise ValueError("invalid normalization form") + if _canon is None: + _load_norm() + cps, ccc = _decompose(unistr, form == "NFKD" or form == "NFKC") + if form == "NFC" or form == "NFKC": + cps = _compose(cps, ccc) + return "".join([chr(c) for c in cps]) + + +def is_normalized(form, unistr): + return normalize(form, unistr) == unistr + + +class UCD: + """A database view. ucd_3_2_0 answers with the current data rather than + Unicode 3.2.0 (only its unidata_version differs): carrying a second set + of tables would double this module's footprint for the IDNA corner cases + that need the old one.""" + + def __init__(self, version): + self.unidata_version = version + + def category(self, chr): + return category(chr) + + def bidirectional(self, chr): + return bidirectional(chr) + + def combining(self, chr): + return combining(chr) + + def mirrored(self, chr): + return mirrored(chr) + + def east_asian_width(self, chr): + return east_asian_width(chr) + + def name(self, chr, *default): + return name(chr, *default) + + def lookup(self, name): + return lookup(name) + + def decomposition(self, chr): + return decomposition(chr) + + def decimal(self, chr, *default): + return decimal(chr, *default) + + def digit(self, chr, *default): + return digit(chr, *default) + + def numeric(self, chr, *default): + return numeric(chr, *default) + + def normalize(self, form, unistr): + return normalize(form, unistr) + + def is_normalized(self, form, unistr): + return is_normalized(form, unistr) + + +ucd_3_2_0 = UCD("3.2.0") + +# --- BEGIN GENERATED DATA --- +# Data derived from the Unicode Character Database, Unicode 16.0.0, +# copyright Unicode, Inc., Unicode License v3. Generated by +# scripts/python/gen-unicodedata.py from CPython's unicodedata. +unidata_version = '16.0.0' +_D_RECORDS = ( + "eNplVk2P2jAQvee35EASoMvRsFhByhqUVLLUW5UFqSoslWj/f00S+70XxGUGz/e8mcmuz7cuX4Sfy3Z93oHcgvTx7x+PRP/MTvf86IjZf49M1xNzeoxixcCcielu+Z6t7cB80osLTPITdMQAImj+5U2S+s2h9Sx1hVTIJrqkZAyFH2hOEmblIWvuk1GTnX6l+LLdJdaWxQca9m+g3T0maijO7HSBSUdmkDBIQzUhIwYhBuG/IG9MpnyofPS/gbjJPr5y133kZTVjS2FLfS3Wwi5EuJC3pWjOnFTKLgd295W/9NIxRJ51j9lK+IE9JzeDeir9J2kD1JofsaWyb8wWIlsUwoliUQm3FG4l3Fq4b8Kp942EpnEXGnZMvZ0XK5Zn/iARlqs4E1EszIGhfpgGhU4VDdXl/3kuzaxplXISfFUmjw2G0xDI59ZKKZq2rJSiVdKWakw6LKeU2zNWN4t1FaX2hMKXjKSNi6jSIuoWZWoxpLDTz5EtWW2ixSjkXibhTXq4KaLYkRKaqRQLxelC4TfD32w2JuTSceDbAK2NDoYGMHU77TbPBypzWKFDfTYRGttZkxT+laJZx2/cWU73HQkrfCbEBJcNRqF92S24GgN9IfqBBkAm3OEr3eQ/ONXBUbsnVw0xp3fLYkcWO75MpOGz+ZzaNJGD9oG1ibHdgT0egLc92Yq3nXZqTVfR8ZVHGw39zYfT0XH1hChPiPJY/nwifVIt5OvG0g3xOHsewXjqn6c+wemTFlx4PQxeQeT1ivgRs+WwW9PbqIfzTGl5DDWRhmZ4UExAfICEcLyhCGYa0zPhsKdc06b2hB1PPfb0LeepgZ5676naluxYkrHUWEuNteTLUjyW/Frav5ZisIQEi28oSwW2lK7F9xTjo6bIaoqsxl6qAaGawGqJrimW+jk8qd4BcqBxVDuQIfJEXiGAq+HoMDk9P3Et0u2ZoLcmFMbvjBGSA/Mf/2HLsQ==", +) +_D_RUNS = ( + "eNrdWnuYZMVV51d17+3bt6fn/bqzO7PTuz0zd3tm2Qfso3q69+4OAUUIwTjQPEICDUlMQmzW9M6MmWhWiJksrJGIaCQalWCMZhMngsCSqJgsJGbzwAdETRTUKHm5AcUEv89P/Z26t4dZsruKn+KX/HHq1uPUqVOnTp2qc+pmzwCgCBqq/QwtOUe58JCBx6+PLFwEyKFN5YI8vy7a0YF25Q51stVlexe60TXUw1IHSx3eGVBDZ6AXfSqDftIZQB8GEWIIa4ixFsPsMYJ1apS1BSVto2xbrzegzytiLEvgdxxjLnN6wilgAgVNUBPK5tWELmBcatCCItOi/Z4KJk6Cc/I+Yyv1Eyfgjq0qT3xHj7HVI6jnlU+geno4+egngFrJ65W8fHVRFZyVfNKmvqOfWoXfqmddJNQcpthoa1enE6eF/3pOyZgJrZVRX1zIpNJIZu+cjMOJDsI2SmJNIVtSk5mSmqJuTmESmzCpN8lXTeJMlLwpR+otuKWMYEyh1DXVtxlbnK3Ygm3uVnWWQ8htdc92tvqbsR2b9Va9WW3FDr2ZOMRUku5UuxLIb17hRagJrwYl6nkZRccoqSlTcoZfIzPpGoPJjKmiW+jiCmQmXDsHWfUXJhc3+U639ICSGWsvjo6N2p3V/r8j/YpbVbtfzPVWp9fE724w40XRDS/eWECMPcqoEHupGTNOFTO6inMw41W9GcWSktJLUMW5OA/fh+/H+fgBXIAL8VJ1EV6Gi/GDeDl+CLO4BJcyZQ+mL/XNmppjnJqazRnvMjWNy9UVuBKvwFUq9Kt4JV6Fq3EVrtFXjdZxbVDHdXg1XpPWvxY/rKpqxk1GnwlehyvU69mzjjdcW2eveqaKyxAKr6iqa4kTJpiqHlyv6+qNqLdfxdlcgzp+ZKSOlI6qasGfQTJH+20BxzOX13MN9jTBDYVaJqG9D6EuYx9lNaN+tL/GEfdlCey9j/poOmZhwpqeYTtzubprBut4k1fn/rrMNTKeU93I+blVd6ZdeG5JlOOTFztnnYzO2eoGmjsiMMV+RLrpN5wm5lSTdjXhvhFEqqHiYJ5rVuogJtuMH3H1CP0RdzOBPY3DckLDabC1KYA5RL5Bk5aAWFoomWCePfd6C6hw9SNS5ZyUjG+8yDmBqloBS9nopmoQo2Hx57RBI8NRZfSMUG1omUccpNSydkScQM1d4dFtIMUTLlkbdcg4lj/ytDfDGo84J5/valqkQTqr55yxlE+cM2cbeQsB6bEHZ6otbw6/ys5AaGoLmtAmkmjK2Cw3ZeYJjx5lSV2Z1wue7J3QJT22Nfx0rgOEztYcZSUN11eAPOHH8GbLD+molbmyPs4sCnd2pvFqSsGJs3yLS3p4i0pkZmmqptdaoWSWUmq2yRo1W/LfGKm5RCuwMhfSqzjS2swstCSUpUZ4UUvi3ZTCYJSsovCbYRlz7NPUdlW4Jhybqy68xG1mi/AfcRV+XLCwl5RKaDg/oUUj5lU8tiJnlzCY5oNWr7dSvg0ZR1rZ0zgHIAPJAE40Kgpe6YgpplhX1IxXCeYDUeCZFH4SuBG4KU1VU6RY5BribcBPgdy+HW7DsbmmreB2nEOsqm7E7W+KMh1S8ioUYMWNnYowPBkpEZqo6n40FTelsBjMe7EXSZ7K0xDBqijT1JxE3i6hanhN8kTRUk1EhSrj9vilqtD8Torp5fF89RK+CquAKt3ASX5j+i2cpI2b35g0fw5BV7Nx74KmwgWhZy4ldU8O/z3f4J6koLoivANDUSISbS6IdKwPwude7Y5k/+JmZE2PZG+GirO2ts3kU62R/NnS2Mw0fLsTstKnoYX92FqOqmgNdWDRM14Ze5wyxXELZSuVG7j82zkU1bexPuJRErnmvCgw64Q8NwaNRTPZYpTWOWLquFghN2A5mB+xapAzU1zAoUiUDJzl+nAgMYnCjFHx9nTjZ0Qd52BZ9ElNNfyqmG7LGiETy5FHiunRht1qpnXQONWtRlZ4cyQr7IpyNFxLlTIRHRK7m4mDigycqWYrOhaJjETW3jSt6ERxFbViytJQ1hyAm0SRgnHiYuSTLbtf92vjkp5YGJmkV6LU7cnsmkkuni76sc9FpYIcgkseHTmkmplD4HrOeCJvjsspUJRThbiUL6C0vjBWUpY3e8L8NPBOcIo/g7EqboV6CfPvAqn8LNJT77v9DvOiQfZ7Yg5+UUyCR+3ymfdPKCc+wXMgre0Fi7mxBbzlG3u330jfoqCn9EpZTznEtXmjp/yCW9RT1OGVdnoeJvcOaBqE24CfA26H2qNvB336Mn4e+AXg3cAvYnVes83pwx3Ae4BfAn4ZeC/wK8CvAr34NfBGKAn6eD1bg/XoU2XCnWDxfanpz5XpkpRxJ4IyrZ/L0Q3uAn4deD/wG/BY8QGgRAMx6n4A6jdB9OTkOJMNzvMrTb6kTXYvfgtqL/p79/KOUlXckFV9CNygu1HVu1lOLpTSwE+H3KuLGOb9VKBov9bH1uL1ttqmKbFQtTDG0i+9KPogH0TianLjF1SoxC05DIe+llOQnqRP30gvqg3eorMBi20fgnMQwYeQPQjrpfKzQYWOccfdYTXtJF0sZAhZDtsbKimPk9x4NxlsC9umWToM9WFIKoUPQx1Gmkp5mnlQOL+NJHsYenoFCeMqyQoRmzjjCS02ulJiJ0vIjhHYep20TifZ7DRSUhbRsfSERtqn26ZJnSs8OgmjyvYb96dTRnsOC0lLKjttEZVIb1BynYfhh6vvCrzHDWdCtQwnJBbF8xHgd5ALz62IpAdD+qBhOB2FHkXnLEOHWIaSZEfYb3Jhn4k29I5edDew2LfhwmEnLFKUncMU/nBgVzcz7POrRAfGnVU5bXOC10nIMu+H7rS6hzNwUzRBd4Q1L9Gk4a7QXxb2bcEN25bRZsfQBIdgtWm8Q7jjjSBlNmED0pGkUOm0n4SwP8x6V5K8pSkjspAZtijMOZKoJHGFiO22VnK9xG+XDJJ6neY6TxDv6dNgQ+8ipOeg9EyopeuVoiVrqmVFHUm0KB1zNsC4Gix65/QBVblpZfeu1L/QVE17Mmw7lUUUKSNFPW33oHs4YUpNn9DNbs+UVct/IH1aSG3TPVajbU1rEyQ5Oyvie9JzUHK5RF2dlYFscVJyvtRFLfWetjvQTcXirBRT8mtkqXrCPu5zEk8WyS7pUKjMaAjz2hC/yzXbUtySxtdOjHE4K3EPnhkl/T1xqquCF7ZKvGnZu5dTxqIqj8t5yJLEz3bx4kofJG7nxXIgytpL+OlgtKqSA4mQHk02zfJWzJY9SSnFOYXKuWVMBmXFW7TFfzfyZSVhiFPp6Z71Zoi7xVxOI2Ae47oOmU6W74W+D7KN7geWgCNI7NmpUtnnp0J4APgo1MeEWpZ0fg/4feAPgAeh/lBa3fuluz7SGisZl3p16RJ4M/g41CegkqYHcIVF0LbI6y5L5pWSqKNwHkJwFKNLGOdARizIEoaPWtZM8BBGjsJ/WEh3fBJrj0LMzFGwfuKo1LSx/zIPdvu51vZad1SwHzxrCXuWcftdMv79+La/RB9op4wQ2Zv3IV6mS7pM32leRb3m/1TtIrkmoBxUubCT/+PQJC/69KAO8t7h0U8YmMpO2ujuKTro/9+dVvJPH1OdVJ/CKvm8QJbdFE6H46waXiXra1I4AbPP6FLChSqhwO0sYaw53rwaA9bLp6sXSrDLW1ASMPsgPPrFTtmn87ot6pRYSsO3fqJnuqsenWyJqVG56AavjdyGnlHxgAQZxKXMGcTDoog6dTpV6kcqac3HEvoI5ukXx66E0kpZaqdrQzheiqYaWXHPJeBEEiqJj8Sd1GUOXWkFw7aJpxzZsGMkMQ5xGqVmUIIwVP6cOJJCLbaz5iQC49HrTuA5gzdZwKfglOgLldSUYy4ubIiSqFgSq4KNisnM76ot0QwN0GHfSjjQ+Uc4sO3TOK5oCY7h9dzax5AptBlXDGwNn0FQ40UyX4NxCawxKoWgVq93vanTfF3V8VlxCzrDPXVldtRpkcNR01bHlTrs3JG5T4wTPiZGhS5+NSPe731QD0B9rtXy305Vi5hDC8Xun7e27PPiOtivtD9wMgv5iG36Y+BPoP4UuCft8WfSwgzv33WYJZB/iYsY9SjwGPAFSSX/58BfAMz8JfBF4EtQX0TwVzbPyr8GHpeUmENPWORHLf7fAH8r6dDf2crHbeXjLWpfBv4e+AeoLyN4EvgKNj0J9RWse5JK5zG7KtFSp75gO5PoVyF5g6/B+TrU1xAY/Q0x58PKtFEVhgg9aeS1g2rSHq03ixGXM6ZRix2zaYGOUmX7P8JZ7AoVb3XcLSYfai7bZrOpgpkbYYYjTf3oMJhZQ1/LjEbOQtb0RpCoFBPXjEdu1TUjEvOKJXzH6tg9iJKJilHhoijRtWLRMcWCQzvucyfKlsrRB+0gZJI3LpPjNu8gZKw3qonVZu5T1Ov+KCDNQeOVYEqEbOlc49WU1cApq4Hkl+UB0cpZ/zgGauqbyBzHuppvssexxfRYLNe4x9Ff845TgigPsYzZPWZXjTv3OFStk4k58zhQ0zbKLVFiOogNVB1214RhGbQKeo4S95oj6YzJzmaknt1mh2v6OEaNX8M3sbaWRMc4YmY2a3aQxUy5n/3JXg9H5qe7ljHObJshoxeb82s7zVlPIW/OeppEyWKx7lR9E7zOI3D8faj1P0W+3SovGvv6nwat1z9RYc26f+byl2R+VbycB3it0+j6TglwzwzXApmNb/rrKn1FcWacZ+Be1W+6a63nFGd23PTVyEQvBciT3Jqi7VG7RKqpIb2LwTzthcQUuRQ23tvclLxWiBXdT2N0G5yYhtMwo0xoXxU8o6vFSEJzNIFzEhB2xGg15V1jQ2R7kZrQ2kJa2cTOOpHQYWPDGimaYvvQIcbZ9C7kTDc1LIwklG0DczcD+9HwYolFo7F7VdAVNugasLNnNsvRQC6IO+daztRp3ib43W/5lGBn62XiZrQeEVyJjLIyU5WVyNlQP+zTALgL7INO0z5/EEceSZz0ocQGHOWtgMixxCe5eo1hs92+HNmXFPuS5ESujbrLRuLlIxoxWxKCCT/yFYlboVA35t8PTi95OHqueSB2JHpru6YhzGYaAua2EwHkyz1mMnm8YruXStJKS5p759eaNTKpFMGx7zTyPkDeFkimkomOcOe1Fo5jIr7OjBZHC/Ic0WZFK1LxU7EORp6Vg32ASiXRtLBfx1lSPc92mWi9gdm3tGTp0VxjX5TUW1QjEpbnhBtETsOPMecnbVSIM6O85ZZHPnu5cd6cL3oY3wuJycftdmLyKDIWJbFnK9R/geAGbOyhHVSxhLD77fJl5Ji2cP6KdoxzLG3fUFTyOkTtU3ZVfUveS/FGI3nxEZwV4ds9ca+ycXs5v+1TFzmRsP16ahQvHKal03N5eTVsXGLf1voW/NDZ2xXmqRF3ZKLXmMZBbnc3zpmjiD7Ta66hPuXNsh913gbuhaiD2/A962jgP+lER7bTJrc15PmPN4X5h/PmiENGJJaf3FZeZnOesZF7GjVKYkuUqcpDikM/CpXAvk1lFmD6SLInWuYVqBTx7qHJ4sOwSz6w4MSvNhfIqw2ntLNJm9bIl/YY8SHus07Gt3iBUt9Gu3l28xLN1mPZJWw0wRKePNc4bDYZSQTdvI83D54zdCSMFm+EuXbjSKdDLL+t27yBbOR5HGVFoKJlFQ4qnDu34EsjdKjCoUpwvWfu0eGF5kzq0gAvXs1KxXxLJjNRUaZSUc9CHwJvXf8K91n4t8CfUfLHwsxIxalOV1TYZ2ZCWsvwzTQ6bRZq4oAMPAS1sMQjtThUGCrKIdVdkHzyi4ay70TyldCqLyE/e28VvJzFkyPOkRBueuS1aricNpCr09qE/vNhLW/DYRHTYQGH4RVeSDb5u2Tb9Qecys6GU9nW8Cm19oq8cblxh5En3Y7GI9RhXqZ7C9TjwqPksArTVVX2y5PFyAm/u1Tg8XeDofmXy1tJWT2SR8kHlRz/1S55/Kny8muw9xFNI8IL6K32DSOYfwwWRd7YbK/4CW13lrNyO4F5SE5xOVVnNpr1T2H90/Cq3GX7aHluoMLOvssz088Ab9RMruRBdqHZJMWOZ/BxEuKtbY085xPs5Y3foJ7UwwIteN1J8wno5+E/H1ptQiOT0mrRE9pdddfScG3+bKOm30lkiddMhI65LmwzHaEiwCRRMjMWBiY3qhZ1OHI3qL1h+W54Nk8n+G7xqLuZD3eZoYo+ytvAFD1kkz3KKwFd7nbjLeMOWjSJIGbFaz9Pkn4pTkqcyJVcVxpB1BKhcz+BOI3wIfyoDYKynJeYKMLBZXRLy5CEnPKSuzS8ZBlbhKy3QkJJ4hj2yAme5vyy8pnnDF8VeqZNWsXRN22s2RVSkVgb8TvCuUudCnfzu1mGDCQ5QuxZyqad7XkhxVrX7FrmLDs4nslxeJOV4m0SmHhFGFz/dt888Vlah9FjeGB0Cd4xXrGtl3LjJtqIY/hImZbjGI7TWNzZcwzv5feJ3DHSOja+BPcYnmCnz92vj+GmA5Fc60fM1bfgAMxT2HHrv2nz7/+hP03k9POf4dgNTQ==", +) +_D_NAMES = ( + "eNrsvdly5LyuLnjPp8gXcIT/tf9VLttlOymJkpgaqNTgrPTp6L7pjujh/e8bHzhoSEnpWmuffc7FiahyiiBIgiAIghP42DUyVuJR/Y5LWclem/pQybYQj+fB9NNwPVSRag+dzmrxmJiylD7QqDZWde9CsqJwJ+tE/NWYrm9Nk1P+pUr7QyNbwstVpzvx2OosX4Bk16tWd1RYUw6dyy82VSXFY36lfOqHStcDYaZDWR663jTisTOlTgBLdKb7w5dqjfhhaiV+9BcjnvJW0WdqhlY86U/67PRv8aQ+VS1+KJAgftSasKmc0lBxnaq0+yxV1z30uawdJeo8yNKTlbVKErXT+POgugnDQDhxRsvyIHvKjZhZH2LZ6J4gpeop9UEKFQkVC5UIIlOlQmVC5UJpoU5CFUKVQlWCaFVGqEaos1CtUJ1QvVCDUJ9CXYT6LdRVqC/xF3jcEZGtOkStjAvCemypqm2nDp5NfzHbl1ixbuOhSkv1+yBjNCbRay6HkjmTtfJTjXCuR1fJclKLOBJxLOJEkCzFqYgzEeci1iI+ibgQcSniSsS1iI2IGxGfRdyKuBNxL+JBxJ8ivoj4t4ivIna1iIe2vI7kURV6HYNtTJAVnQVOr8uE4mrzEFHTFAcn2LpGYpUcbiV8IrSNGerEC9zQkkzGVxe8Kt++UWsKCkSyhZjEnJPrDlqq1spwbJqrpc9GpSRPELCDaRNdUxV0nVBVetPaTvHQGF0TR7NDYoaoJD7XGf296X3GZ9gZ4o/tDWjdTKPTKE98JeMWspsoElDla0e9yfYcn8eAPhq3uukP6CVv3EseZTz0Y0NTP2iNz0GXFLj4QnSSEI2JgeSoRJMumOeJ7kekdPFQblSdWfTNun8OZUbKJqWWZijlfoD8Ur1FkssyFcceFfDAbtLqiz653gkPF93nBxZzUTITRDn2CFFa0SrHVi5bEC0jQwlS6rexzcHzgki5k+OYldJ/gKt60g21TWCJUuaPiX+sBgI2JZpiFOFVzrjMocULKmv4A1KvFtciEd2mJYU70xpdLtvmQFpgxv+TTXGaZHuyVTiNuZ8m/KeYeMH/WN3Lccwq1n+AC/7HM/7H5o+JJ23xqbsl52esmfM9Hv6AxBnfY8t3DxzRfqx3Aac95u20iFtPGWGcWU/ootbTmYx6c7Ge0MctUsbTGs4TzqPW0034tpp4Gr+eA+k9J3urGUyiNyiQt0yeRy3SJdvpkm+kc2K0mtDHLVKqHXlQu/KgtuVB7cmD2uetusdbtSNPalee1DZ31R53szvylN2Vp2ybV9ker7J9XmX3eJXN1eU62T5ykTa/U+v8bq3zHanMd6VSTzXvPOE8aj3dqjTrXWnW2y2k91pI70ij3pVGvd+2BMe05KAnCXUm+4GseX0KyFPQooDTnQY83W3AYk98FpFJeytC5bYCL/cUeLlXbrkvtuV2Jy/3OrmLnFi8q4mn8es5rIp7uSvu9Taf6j0+1Xt8qvf5VG/zaRalmlZRHmRhR9eDHCf6N8q1zpY6FZB1O3O1g5rdDmq2O6jZ66DGdzM771hh8SrGTZ8z6qbPmdvS2u2WbPdast1ryXa/Jdvtlmz3JL7bprXbo7W7o1e6u3ql26ttt1/bbru23V5t+70y+/0y++0y+2+UuaoR+l2NMGwPgMPeADjs9K9ht38N2/1r2OtfLnIyT1tNPI1fz2Gnhw67PXSGszoQD7sD8eWOPF/uyvP1Tg7X7+YwmVZ/bffOr73e+bVvVnzdMxm/tmV9FhWXhlqU5qHRriC72NyYQpS9abCmNs/VYfi4ZRfCGhBWche9J4CX6r5R9cGEhRoud3UCZmOWc9W01bGsD4lQyV3CkxnhMQ0JNaVKVNmv6Gi7OJsclFBdnF+kUEwploI3KU13KM0mcanEwvnCvv68NTgNEZbOF3qKzcKnMbEzX1DPRFZRInfb3HGiCitYvCewUoaPhiTZpdRSbdsM1vJyq1wry0zGU9yuWA96iaxvcJpNXsxifI/dkFWssq7IKoOXJlOXh+xGAenAENOsDxeNLCVyWJWJfrMC/Y4kubhWUWPyvgBj+SXAFT4PO3wemk5jS0V9Tkr0S4QrhF13CPvaGT2/9hc1vnKRB5YuzdKvSVRmu7DUZWgJaql96UZzpvpGs07gvsP5temsND1ywD7WLO+3y7WuxVuiakTHpY4L8VZiu2kMyvJTGezBufDYUBZwsxY0U9O+v2/q8YVO+9qdI51W8zstJzu3c9H6eynr09by4Rqxco9WvZ1O76Uz2+nMXrphO93wjXRh5D/IOtm139Yxv5Prnmm1hvidPHfqu4r4nTzt8vc38rSIfuTdXHr+Bm/lH/BWLkyo+7muYi5z3VuJlftLsdmOpsx2lVm2LbXZntQW2+mKb/SuVSvd7Frps9htlm+j3Y4RO8vB88j4tLv4/rWuZW9U6xb31/pltmfjk/2oW6F48PA21lqnmUeti/E4MdvUEbuYG2K8mo/aq9Rs1N2kZRNrq5PylHGNOasY67mEgXxn82uJs7XrsUmP+gY96hv0qG/Ro+/So79Bj/4GPfpb9Ji79Jhv0GO+QY/5Fj3tXXrab9DTfoOe9lv0DHfpGb5Bz/ANeoZv0ePX2nBm6xCp0lw2FuOmCBvLapt59PfzuJosX84pGLSxm7Wi7PM95b4xRV3dmh3a8lYih6X4DVsTnZXp0dfeWsX+Qo/85j7q+oKo2l8QNd82rMwfGFZmsrJ5N8dbrC2Nss4fc48/5ttmnvkDM++6Y+XN4/yiC4uVP4tiA/004DcKTyKJiM/U8ZtcxOcmfG8Ijl8CineMx3jXeJysCqk+tDNZXjzVXcnO6YTuIjs36Y6/bkA3RtJk8rw0kmZR6yuP45EmS6edK3yGo1urhKrdep92Up52U1rU89irXZVnWdxGr48qq+W3u+Vfd1LO4/ykSopYlk0uR4ANTdd1Y7foGk5nWbk8jGsrJ4s3WQWN7SpofpONmqA5QDtFikuDqCXO2A3m1Ziuk8bu0GIWVmgsAzyTlno943XVuJVVZ1e7PA+of00JT1Q9K0bPSEiw7LpeoN7dY3bnyWjc68VpsTyXYIkrDgutxWSUwvgUV1N6blZhl7mtU7dUT9R/cPzUbKCbG+VhW8pUKiMuNrkOBLc3BJ+dgCzAJys9qe5yV23X6g4xRKyTROUEM6Zd10W2XKzErksQ63InPedB9rOFWk44U8y2fr1IVhdVY6uEErdIGk8XSeOgmU4Xcbpu1Oi6biAsyjlZaiAj6dQ2WVObb9Sd22udKQJ8Gk0j/oE3QXqsZL6tLmGKN+KN6uOc4LF4i3QpIz0uWM4pjjakwnbbjY444UuRbxxbaU1HGT3YYcQxb0sQdlTsKlfmi7ShyTdRbhZR/diLfjoGAnwmM90Eu5tgx2vYKXRNGOXLbiXzUKPQMLi3MXQdWvTDrTVPQAub26m4RQe7ckdgZj9WJtGphr6a8joXsz2pk0hbkYYOX0/jgv4bO2d6EelVHJtWV0oc3STGhVwm9n7IcXIG5RhaxsZJNtBxUJwXK8TRqrwxPJPi42q7ukSk68wlVzIhNM51AhiaaSgxl3oaXrlhYacWN3ybX3Y4OrvvODucf5zdyTjirsY8WeKSJTPEZJ5J32pZZwPvIvCVlyMz5RYMdCj5dsHJfMlJ4kEvqbfb6tvP8S7PcXoHwU4gH0dL+3FyGODRLfc9WiFydzumO/3jNYUF+9rcEB+sSB1ZHYT62szs+J2WIu1E+pvkcb291e++lQ851dju4UBFHxdBGpInIbTCGLLp57Crrg+JamTLlx4YzvcSpET3XYk4Qvdaztaya3QrqV+EjjCVeRS0kLlkJpHJQoCTpQCnKMYZGTOpyaaLBx5Yz0WJ68mtdGyltn2PRSdSGVU68I34gpFzDNp4zyYbPYa6XOF6Bw8L7pvvJYWq8DWrCDdssjl9LzP6Xm6734sl98V1lBcSu5a7zouVzJdRMl/D+YsXNr8t9GUiry9rovliO/jLrGcuEqzFyXlFYlKxLWnsOhnEy2L95WWqBH3Ws8BcF66g2E4tXqaFulWVGQ89jHmPnu0BVo6mENs8fJfHlcd28stcW3hspzN8MGgODwj6wwNGLRJQ7P63/lLWKgukzQygsQRfmdCwY11GuqbrS69uxePF6aVFm7oUUauTLIRCU3nZaGl64POGZAQiFqI5Zkdtd5PbDGqXOzxfWJJDI/j7e17URoBNxQIvr+Klo9bpvWEboPYgzwLoUO1dwiXuEroYLVZqMmWXv5Lo+C0zXPF0cb+9HAW2u87rqjb2XSvFowJ1IjwB4F5cAUNHdw1NQmotjoUhvlHvPiZkFl17XUgkMAS4NiZTlGfFiL6BHTGT+6CjaK306tte4SC41OcWrHw3qUyfK4xfDiLLinT8gYsiojyY85oo8LEvXWSbdHMgm3+qUoeTIXJa3zBB888yHZvLQVPVVtS50AizioTUMzWwBJ9gH07HIQc/3pQzrpM5heRvAy94OxWlL519yaUOnnaQVEin330aaSVHLhSp5EJXmLd63ZXMz0qLyohqEFUsqkRUuagqUbWi6kX1KarffEOYBG254Kz6mzNZauVkGJSFJDHoZNUs1wMWcfVQ8cEQNqt+ENFYn57BlieaKF1+LTVOtOls5ZTYGsK8Jzj8MLiUZJ70fN2UVGZ3rSJTil/Uov1WXEi5g/Rjfnnzdo2/Fz9sP/2x7Lg37MTylD+YxwiyNodelUrf8l7ZifgUPe1nqRUOzc0Ahm/LztKo4TYfxcseM0Lmu2Ih37FGPMParpVQEQRI2XZS9qChUv7E1RdH8p+eJY1pF6qQTUM/pawS+iE5VjX9/61DVYQi4VJkTQvFrULp5RAqRbE5Rcf4QxBXsSljQgUWjBjhC6leNlG80g7JnO3xsh3i9aImPPTrlsy02K3lWab5AkXMTIv5j2UaFyRiy7TYMi0mpsXEtJiYFnumxcS0GEyLU77ybFkXux9w0JPo1r7AwRgcjN2K2BoHN6oVit1mgYPdip0XpULq0N/AkxDgiofQLFM2plxM7GxEtx4WwPOtnWnUD6q3/34aC58SslB0hQHb15Wgi/NrDj0zerGm54B+HWZV5wWoP6+yUuairBXVbGFwAoAxfLnMnystnhZ3oAFa4KU3aOkKVnGbW7GWG1lsSzwLWm6okGlCyvBpsdZtgTc10ZW8qQrDlqdgbogExI2N3J1Co1OvGQVgZTh4mqh9X8pcSF0qrzdCxotRahl/Uzlzc1N9ekp3hbQP3/o3d08AQcWma8fLcndH0fedAfL9O6PoY3xtae5yK456dkteG5EnJyXyDH+GgmbxNQwATaHki/5EVzKIWiwOyvphEi/yK/1HohJ/avzpSa5FXuBzdr0+t/OHAVkCQ1K29IOYDOEECeg/IvGrfQr6IHWXq1LoSuhaUIPkDSGQNUt2e96DZAqlIkeefUfhOOfypDjFgOVk2llzKL+qlpDZj4YFEOJ1ECTnzws7LyXqUvh4AHUpUZcSVSmoy/AtUk9dStSlRF1WCcowNSJt4BmiFRlsB/ocKJSKlChJQV0K6lJQl4O6dKQuZerSkbqUEIk6GhrSeYtlVApaLEWLpbMWS9Fi6WaLpdRiKRKhxVK0WMotlqLF0lmLpb7FUm6x5+VuOI9Zc7Y52NJak/0CjyG3lxGwmIetwOelYRQilvvNuu/J7L8O3SLNNGKrnM3EqxjLvWSdraQM0K0y15PdRi8VPhkJ8yQMWRr3N1jNClZKgQWaBS1p/sp13y1RA3Qd+/bEkV/LWs1mB315TqlY5ADAchecPfmsyeUsZk2O/QmSvjRrIj2LXqZf1s3cUm+th+cVi+K5z80Al1lubfyvsKQZdLctNg4LXey6hawsSZ370NRq4Dk6DMlSj+HEFC1ZikrEOdUdK/iLkuIK2ZvaF7wxVDg1N9m6f14OkMv4ZQ6q0qNOW6Sexy1nY61nfLxs/nnU0p7JnbYcGiySLpLexG6ldlt5G6l97FZqt5zOmxEbWcxQlkfAPFKiOuoRCQ0o81zWEJZ53Mvibg6F3M9hJX4jh7AutsrVTayN3HYz2UgbyS4vNNCWWnsScXOHfb/+K/E398QJBzbE8+KuuAcvlfhd8Wm+IT0yKnLoh/qQ35g2s6ibC2h36tvda+/+jsz1d2WOms9u2w5LZTGJ2EyzIx9bSMtZ0x2Zz+X9Nse6c3fb5h68dA50r6/H9/t6QNnvaNtoN3r/RnIsaFPS4lxtilq8Iumz2P3676OGpcvSxPlKJw6a0q73bqhRF7mhcFb64Txq2ZHKzRFzHrWhcFbKm0dtpFsrr94pj/hayG6j/ZaRyzKr7TKnUelmy8jtdpF7rbK8nLWedhJ900El5krL7mmBG3PlNSL1ruzYA42LPmRha5j7dVpH2TQaNnJZQ9gyGrayuJvD2FsxF93qyRy3663pecdb00bKLaL1PZrNfnpzL304Cvm8fkJyC3+/2E2sjbtEG9ncbbFhh+/DLt+H/ZKHb5Y8c+TxfNfVx/YAukFHfF/us3uDUHZ/EMYCzj4hqxj7E5DxwOnuTGSCtmHQrOSR741h+Z6xne8b24WpNDHqZs7roKvYp3X00wb+1zr+1xZ+spEg2UxRricot/Drdfx6C79bx++28Pt1/H4FPywP32jgWcyG1bJmfZQ7klLe2IrliqnY3mC1+dpqobpZLbyl9LzM6nyb02WZ0WXFkijV0N9OCUfwBoe2p2erGBvW2k4u9f1cmjsKq7k/1crvTXZWMTZqM14nWK/LJP7mwvTXjfHpYEvMWys1WbVNyzsT2Zv4R9nifIO89RF9jbBXUYs805XIE2xGxLnIv/CRC92LvDd24yLXtRZ5qS+E/Jvi8phwCiTFrsVJYq9DJrxBQZEVIrCDUpuL3a/IP43dFcgbIJwYraVgh49PRWg9Z95y5gbJEWz0pUVBBDT0P6WP5+Xh2MV53efJCdJnVTWwyjp3TmrpLv3ZHqZ+nh/KeJYR7F49RVw7OA7+pfwHTEzBxDTBngkxMf3CRy6yXqTERN5fScHElJmYgokpMTEFE1NiYkpMTJmJKTMxBRN5UwNM5G2VlJiY8tYKmJgyE1NiYgompmBiykxMW87cIDmCzMQUTEyJiSnIOobFmjg/MNbRqaT5jZ7n8VGC5+Cfnd2cpzLmg05ethSlrnXvPcyzG/g7OAGetLJysFwR6y/+0KDqa5n3Urx3KsOWJLUyTsyqXrx/ybNKSTn2EgfCZYKtw14TYyRvIWoJlJaU53sjO87jqnr9SUgU2Yr3DDZKLpJDNZwTWQlCkldqwfezpMa94hEHCeRSU8QhU1QA5/VFPepdgi6SuXQocvFeDRQSHzKXjaTwh2ppKkA5F4q4R4kS2WYSGSfVJMuzItKZrFbiDGV9uJrKiHdTKvGuy+FKCVWuqRq6Nq14ghySMHamlexejdCe2Nc8Ntw/pXjLiRfpwXIqbiiAu5EQ947ya/VZvPUdVVq8WZQ3i/LmUN5yqmAlIqpVh50T0x4+5SdFD9GA6ERmuLJB4Iq0CGVWUWtm4udQx/3ge8pZpuIn09TKVM0iqRXU2UV2Oc6MG2pF9ztF7EwK5OHsqjw0jfURK37Zc2D4fGomKeqhdm0hXQG2Tk46nsahLxXvEYSHuqrCNrRkUaKu+Y66ksBcdY1wj2aiP1eTiHd76KWgqr3zH2KTCuBKkcjwHxsmWsQ7/+kIDdJh87SxDZWE/zbUdzKh9nU/Z5NCckkm38EfghNJT0SBu7uA9g4T+iuNnroLkwdQn9OfAwjOHRDfMz45kU+dpFP/k5GOD9NHUJ744GcnIdBPqTF9bXp7yJTE3kdix/e9+pTUDC4tN5S7W/zALyIc4iFSh5ZyEG94qAQ3txD4QZJxDUhoWezWuEcdZE+9wO/muN0b6MRau4Al2Crtp4SPBeCCAT+/QJ2BD5m6p0HG2lS6o678qyMFjn+UPYmCvGKSITuGVuKXg4wA6pQkQwMSOHSSF30IOdT5IH711N8JMnTip70YxHcAiHfRuPRSerd3lK39uJICjr4ktfFbKntiJnUu1OitkKD0Z3itxUsuD0FPuEVAfaNXv3sHIcForIfeQzPrh4icj2lPYW2vyyvSBkzEey4rGqfeRxormST+QH3OsS7wfpHOOeQMOqa0YHvAlHRavoGMDpijd6GsllSLFJL0OmAnhW6UE/feC/5L3ZMwc8mHQnJ0T3SLTtEgRCnwl0ZLwkrQVzge3Q04JDP4oSHPEwJXZ8SnztFy4rc1GOBITmXbMVcWPiE+RbVIW49pLeCpl/1FkUJ5Ckebcqj7icKAjkDtamNYweTMUMe/Shbd0PJQgF4HkWC9xVLBXywY/GUFxkY5OIl5jmYjLVqQ4nniNsw9bdMWeLN1feqGyN0P5iZ5Gk/122y5O4NUmooPNQ1ST18X6mUF9dynT9LB9gyuO0D86TKPQi4L+Hg14Wk822ML4trMG0g8XeTndSZOXltMHkOKcZMmhqfBhJ95ifkxpAR3/GL4ykz4MaTYPoYU82NIPw6zN52eEhXrCtsEowaZbCSPQPi5O/BAi6r1sg3N7G/RQqJTbu7pezFW2m0HkR3chqOak8pZ9nRO/lh12P6Y27SaJWRY6Ugjru3GRA1pFHxFyveu4MeITNCFwPKdKj4WjtHI4tvEuVUKK503C50g7K84YmomIbnOki6LpDLYqo0ZFx37Q5ZTGkchaXi9x92Rox6NU/XigyQaP8Mk4U61MojDrPgWGuTD88VJqMiWhWdedl0wxDBR4+2pbKETSHnlrKXcXdJl8VBao+uMtRzzfqmSftsTvktOktJbqDSLnt+yfLs1SD1uRXmpZiWW+hqB0Iri/V2Hwont5wzrpg6QL6cMl05IstuiC4tsPWR4g2spJV7ssknsbbkZpZ448wK+Qd5ZSDLn3scA+VjJzxUXBu8gOns1aR0VrEPnzS5ip1PfWzsYjDj2+ult2RjEEiNp5kdjt/J9acnP9wDDIOZ0b2ao16QrKmQyAB8YaRzgLb8K3Wa5/oKvg3f8H2h4GkYwvkOKZWfA/zCeTqwB3jTzXWySflIJNUVftmrE2wZKrOinp3GiGux95U/psr4MFlnnO1Bo09koXARZXY+PMJKTfaB73DeneRJNmoDJOjtiIyYaKRcR2yveeJNXGNYYRXoE2yHCgg0xNJpakHyqixcyaaiLhsZeQ2pV3Ps7zDbGd1W+g0TZsdnk6OsMnKsmlsA36Bsm5I0LYBNBvGGAeUMTWSjbpSyUT00pY4UsO3lKQLKqGpq32zvTfOuOWZ1wOst1T3QA+Wv1ZN4nLmU4Nk0ZsEEUhlKv1Cd216hOJ8BHsn4Vl2NnL7emQQnToIRpULFpULJpUME0KGEaVGwalNY0KO07iW4mNB5gv9HWbGfewNjOXELdNIkIy2m+EF6OjLEsRf+1NcrVaN7na/XsrjTriw9ObmCNWI8HZLw1rcQdPDwfN67ORLegEc9OJwKOm13gyPyXsf54LYR/Dl2hLjgkqtLe3aiel3qLNc/ZR7mkZKv17pk7mKNtUSpZHwwxi+ZNx0r1/tNdjovp++l2CW6cxoMNC1OLQRGeMiMNTyIm4kNGCog0reZ5BNmZ4sP1Fhsk6jDVzpWzxO3kIucsevyNJjlchwQAIBdcFJYREyz9YMXITvdVVaAUN7cPQTfjD5YvAqSBkNWZs7J0+Ck/D5kt7yNHTAzmv6hQilcBkeNTQzZzHhS5l04+LE+GOjLdimwj2S3nAu6U/RdqdBglQiRO1VCT3ab69aA6AH3GNjTPuL1IzFTCW5G8bHMeOqwHXymiHYoC02cyu2n4CFblZBzRNqefywExciUYkjqa5U6vmScuqho6HYsnHi+KPMhOZ7IErP3i+WFKpTe8ILrUANHKEDTyBi90rpmHNyP31DAIz0L666w2i//bppwPoPnMNlmanjfzrLnpOrXCF9nepeY96OEbc99XemGdb1EzKm+3kjwxgW+s49EavU9wMPKXvJoQ6rJNbyb/N5byFh8mKwcj5/VNA/db6XkMXiQvb4zCJV0jW+vPickJNxsjP/vNCmczC2/k93aKUVRs0fNe0Et/t///mArpNOutZHP8VuV/gn6XqJvFpz2jAPnaBP8XN58Xjvl6z/dy+H8nOfw/LMauTYMp+718/s8pJaDBGrZ/ksX/N80icGwv7ZTesQXvpnDdbGqYFTeTKOfhhkYmWcvxJAV2bnL5qa8SoygEn6YNLcAR/pRjXCFlOqBJNX4+pfwcbC8a0FQcRwOgLAdeEURaKRGXcdxHHTJCzYAcAF/hqw9fV8l7OT54Cl/xSFHfAynnwgr+2zsCvmy9uKAPSWM5l2d/e0PxhlXa4OzDASM91+DC1SLbRpJVrMVP+rBfTzrS9kOpSCn7OUSD/TAmMsZFRzby5zVSVxcbGZ+bcbl1diHQ+3Ulch/rwkyN5BfDPjPISH5lI/mFjeRXGMkvMJJf2Uh+sUbyCxvJf4cbZK8K7mPoR7wO4tUY8Uu8JjIjM0FjYvtai9eIfhr639P/E/3HriXhiFesxNP/147+Z8BK6X9B/0skpBk7GZAdUVUhSGbCL/pF2gv9v1pYwDkZSkC5H5H7kXL9e/SbY29vjD55kuB/hyzazjskIjEy7KWI98oDNB7TxSFdPEtXk8Hjr6xY+/TdbbuMCv/v0bPSZE/67+A+aQq0FxsPhlpJ1TXxHtwphnbA9992x+Pvm+e+/y7lSRJLSklIZLH10n7/07Smcpsgf/eUxL/L29F3q2kaOZ4HwUJJpHshYTjXQrJ5LKS+CoinkF9EgER8jz/Xgf6gswpCi4AIE1jCBEbzU3dEWgqkmlJ01CuQ0XlI4Y2CDF1ss2KjBzm88DozkB+YjA8TxzQRwDzhw243knTN9/pVQ/NI60wElLwigwXsZbJCza2r+Bl6dqeCoISHAP+B/2OMjyA4Ebd0/cYSJWf5e5hNB08Ct+n0LUVaKHgXEMp2VMuHWp0H0iLiZba16YCpTImXZ5HVGdnbaSQHAvWVxC9NHa6k0EqkvZ02zbKriFCo9zNfdUu/9Bl5+5DEbc5+wFVNSkma3N7ZxKZznqJhU0n9m4p8JEFJ5Dgm08zkLEkVRuKYiWMijjTZIkNfQRt8yC/xQZLzIfteHIsO+z3HkuZ94liLY0dx2Mdp6PNLHM/UjeEgSxwpQRKyKGRCOIT4U6bOY6Ov3s9PEy864s8MU44pYMKCMLEOW2sl95nqQLJrT7JA7eSk/emLCj/VuNCLkys4rgJ/SacS51aoIotJw2iOUFUlu4y0uzVnLIbYNRwLyG3AHYFyBrL1O7eAhZzsTs85ogmXqVxmDmbvAI5qx60Weag4W8c6Y3hM4OzOySp0KHBB83K1eqUGS5SQ1S3RC9TzWmHOHRCWRLcKm6DcK2xEPXsXTthqObvDQ/j223juWQ3M1/t2iAsXbbBMkCxMdj/G9jjRwNt3NAoqnpCODH9y3uMmED80h6nAcho1sem2ZlhheX+yfXG7EL62B7qc04mn0QcVlmifGqZ0sqv/U0s4Qp2BSO/2sxXWi2nhNPnhNHzZFUcGkNYnPVWJrIKOgtcZmE6l26c8kE100hEvMM22zg6VwYH6TnZYo8DImrhlyyc+62VTo5U8eDl3X0yPZ5OjU5ifLdeu+43J83wrZGfSP9/rcK0Q5nLenxOmdOMk8TaT6/rc1Z6FntTka7J2HqZZ/KjafHkdH1hhag39ZFe3ccg58j5lsrKr5ucKYcNpbZdlKaN+tu+vpIXFteUS595WlJfdFU7ecpd5Us8bayEEzGkX1WxH9fOoPuyjLGew3G+/0VK32P7ZxdTvGad2F6hZbk0uifkUH7eQcR8oJJv09wCbLFOvbAU6is7bm1+nbUHtlgJ+Z86etVRnpzTGLSK7/zCGo+WceKF2I9YsneRzNFjek2020bh+PSQcdyArKyhsRrUH6BzsbUyo604ni+jJngVvmEx0XfvQDpGIqIeICPZJhBaNRq1uR2jWhTfASTZ9/tDb1V1YFg+850LWx0Otu1RknSzIGMnOmr4v8kwTpmh5MiuanMx6SnTXDOhisz0n/2anHB1APsHP8vWwdgbpLZxCeQunUN7GUyg8fTH1dLLza6Evf0EJ+W+P6laPF61pUf2iLtyihtJ/hdJ/jaVPhxxqkOkpEh7ho5Eqe0LmZodm4e3P4a67EHxadQ34tO4a8Ck49FvLqguEbBQ2ibcNNYZ55IVwXuS1mx3OeUzUp6xp+tbaY3Kjjp16WT3OAmTbd5844Xr81B0fT31dTHMiPIcgIi1iLSJ4+BKRNbXjQ0smsIhsfjS7imwS+lDoBSHG+Bj6oH80b4jg3otkLcrcL2xuQreBkweS/R3B/k4QwtDOH6hq1DucxOPSL0c0DhC5XxLlCPm0/KoBdmjh4kwk9D/6lKAMHsxsHbG+MJmiGbihUeKVA/WAzneUn9h+WyBi7qRFpuEJJxtwPNvzx7Q43O34k3r+wOsN8ScN/Ek9f+Bch/hji/zUrazmJTWYO/fYCOptliT2r6aiBGSUdc5dJ00UwbWM2tZ+vc4cj7zO/PhOc3f0uMlyOlD96f/reP8kKnJuNf77xY3CTYJbLhH00RWsDtWHfJSzEnxUKUyJdSCaPZJSsMslNjAuTUmsr0gsTUW8NCV5aSrC0pTE0lTES1PSLk1JXpp6nU17eaXDstLuRTf2GDq6ka+UqzJRTS0dGwgujSpU65j+k/C0F/QmyF70hUpSF/28HlDLDCJ7OuFr6lobLIH4kfw9RorkutRkAZy0+Dlhse18b6HzvfnO9zOsrR1puqvFUdMEWhwH8THKVAaXXJgGiw9DPwOmxTgcJT4y94ve9BG7wMkDiegPSAOk9wNE8gfPq3uHk3hc+t+478j9kiR+IAsi94M6zwc6zrGzhOK89aSXvIVe8nPeS0iFJBoqhGofjzUqWxETxyX8BNLP4DJz8v9zvKtNEkI2BM3+B7Io6ozPqWJe7y9btY5WiOHHRAwzEsOfq2KIiMly6Duv6UHmPljm3lnmPjTvo5DMfbDMvVuZe2eZC4XL2X0m/yoQlW0Pq/vwz5YmOM5f7zuL6E8afltVx1fn2bQ3LcZUUYCOkukomI4CwydvXZMKwAFphUVCw4scpGnkJICHwnuc8/ipO2qpVvzMmHszfn0qrAEFKfx523t+4sRCrm2yx2xoq6HI3egiE1kcIMmazGz748X4OYgxNTrJMLUsyTA17JHqckTIGPqlcGHF8Ji5X4gujVA2cPJAas4jRBca+sj9i8E1wA4n8bj0v3HfkfvFEwpXuzJ8JNHF7PP4CenNLYF8a28U3+e50Ca8Spfwol5C9CdEf0L0J3JwyZygvmOFrg+VZ115ZF15/ELpKJ6U5PNE3j7Qzh9o5yO38we385FfrYC8HVnePqy8fbC8Pfe6abR4xly3EM+6pW8cR3pWBUlNIVtH1BWeDfLFHSZu1H+ccKRVH24U0nsQhW+05Nh989KzLAx1Pplt7XmsCbH/08hAtyoH70GN7UnEyIeqFUngQOIEJVQ6WZGYZxq6PTMm6iovy1mRo7qqyn9bfG7l4dlqJPsd3Ch4Xtil6Q97svzdninHFhiV9wBLmnnlZ3VuvjSDEXkPK/BH0+qrvBXC1yCEr14Ig8tUahLxRnpGi7cBJxHfRuarUrwpGnkoytDPgFkK1s7EW+Z+IVZvsQucPJBk4g1i9cFTn8R9QKzeeoeTeFyJu1L2O3K/mCkhC57d8W4kEUX/IVbvnSU4h6vVUaxeg1j9mIsVTGaNvkVmtpzY2KTZyeShWElGkRxcZt46DO7hf0g9GxWf5oPkj8kgyaRjkHybSJ0iqfuxKnVk5f+YSB1mcTx3o6pB6n6x1L1B6n5B6t5Y6n5Zqftlz9y7UcgTcaHKp+4sGM8f4R+fImCzlymJNC8vOGDHcu5HtD53x/lzjxYiOvHYy0p7jv6BHPGBUyc876P8BJmBvIyyEsQDIvFeO7mYysL7RB4+tmRip/V5DuWaPFpp9R+kOH4srKB/t4ncFa4eh0PBb+dVj0xwdxuCSpDuyuaPytRY4+HvKw782c9ERbr3jtkpcQhIfzbfBica58f02tlfqhyywSmF0VHgqB782bKJwvgVGvqXb+hfY1ofOU7inQh8SLQ/2djU/h84ahA6XFpCGj54SRLS8IFtfBx5tsrhPXO/EI732AVOHniVfGSARxPccLAffNDbqZn3xOPy4QP7Hblf2BFXK0Awtb0AYcx6/7THKEi3W/KxyDNRLL+CYnmai9bG5L1oIWWxm6zjLg1Pzp+mgvY00yhLDeOX9SDUCS6QtaxdamwME8sbU5ZTzoK15Yy4UccUJRasggBDAqmLkQC/swDz3UFqMLQ9BPidBfjNCvAbC7A/bospaSWegnoZc+XLrCZJiDAyyTusiXG2KcR9Kw5rVBtxGaufe5mC0s1c1yLHbNdibTX7YagG8VhgIzZxo6if387mmHcmnG+eX9+feR7D5PP4P2j+eWzHTvHx+d9jLpqE6WiyPiOdTD4XneJnOG0z7QQf6X/hjJRzPOn8U1ZDqTEkDY1M8krWHNhSju6c9uO4Fb7QwwtdepyI1kcQrQ8vWi/rs0zJS4obto4uV8c+YiWb+zJzv5Aw6Zbs5MkDqXK83oWFPzZX+QMSJt3EQSYe1y0kysYBIveLJ/WQT2vXDDFP8GuGJEl8bAXr/MLNK6g8PB9j29DvnUY0HjpR+eC3ucoJIMjjy1weaUaRaswoUppXjBypW5xaSZVQko+KpIa+Bl+izfNlvId4aFWTu1j2XPAS/ENpksNDJfIr5heleFmYDy8ze4z+PzgD4IGa+QE2lsYx9Iz0kv2KrfXFkgdAx5cxD/2FTDFGyK2xZtEC2KGlOqXIl8WDB1pPpAHiUM7YNPaSmiImveTID6qhl0juJUfuJRK95IheIrmXHG0vOXIveZnYO3Jq76hg77ysmqgZm6jxwkSN5yZq5kzU+MZEfeHr6pbl87apa6FFzvM/dIQcLwTqGvtBh+21w+uozK+T9cMri/3R/yr7K93vh3Zw9/sxuPDg41v3FfmYcgH4UPOsaUhwH8ZFGB8Rsmhk0/K50MLRRUo9lzdAOSJma4gBWOCg20niYGOniysYQKZRjZWPEWmSW7yWW7yCeFpDDMAepz/nxWYo1piMgcUNMaeVMvp+rZAROkElVbaCGqDHYWhpDGeKHJ4veEw5LXm14LVyV4v1wCRwf1noSlbNWlbNCmK0huiBAb+KJphX/9EuSSs94HPZdl0oJjCvW6YOgPwWOeScug876MryoZTFUC+sDVXKh4bf2IsL6qCaIEmA4HGWGcCi6G6GMAZtdCPnGUzCmSSMMTcavodPjxZC/HFIFF6e+JQ4oj0l0ziiRgD3p6HQvX1ZaAz8LK2vv3/nSv6UWVzyrAqnSWHTQ4zEZ9wgh02DA+ea9KiEwmavcXj7hwxHg20DDKuyF+rCQ2iNjUBsJmSwVM2hzgYcoDBIXtMwTHDFkZ05dMZHGbJ6r+ZwRfRHwsiYxvXmAPc5BReFVXmqESXm6TFc2ucDASmTmsrBUlyCc70Fp+ulcakGLpJLN0wVIRNNkSEZ1xVs7YaKgcFL6A2jf6Q0f4CVzBBKaQG1heClHi62Mge2mw2Wg6mDmEM7SLbqS4PrUhl/01zkIkEdaswWTzt0ZKB1A4TfHHLdcII4hxujD3Ng9lBEbYp8KGCrs/I3GkqAt9Oo+2oSqvqBFELvoXiLKyyeWqMGBg+RrIldg/jh90HcIehIkoT8CI3KmWBZVdnFVGxL6GqgShdEtMaUoOB2vXLVQVNlCuwVayJTRAeFJ8epWZKW36aCrXhBG1Ia+k9JeZEUl2dxTpVSU36WtdSiOE09kfJXSPkrpPwXS/krS/kvSPkrpPwXS/mrlfJXlvJ/jvJJRIJSkPVR5KYayOwupRmdHlKu1Bbc0j3Nzl4b7CNm2HcmkRWvNDGxID5P30GYPNKJka4eYWfd/JW4+NqvF5VwLhQfIaMJDtXTFZa7j9THcELeRK8oESjwQvYBjz+vuGRAY0RXtFgWwuNuHXZ/Xep8lg36/athKAr5W5WlbuBK9O+pXrVixm2E9fvKT1yv4nh109e/nSlMeTpreZoDJyeN8DeeaZidzqZ+TDWY4irOGlPeK77+Jh1DRP7tXt/UkK43SBdWFWPJovU3mWwxkT49qV/rLIOAUWyQsL//zRsZ3BXFE7H977D5VA0HkpQjavHYa7x+hkehiBZ+U7TCNfO2OGTW11t2qEgT9i1pV74sTkr3YagObU2TwCiWOHEp6syu9eQqQ/DN33z3qatkqDkCz91juugjukxGiHiXreoDlPQYDpnYvN8CCZx9AHekiUoOireoK4ZAK1bjHnBGJRQDgmCJcxXxqAhyEm+JKnWlR8oj9tzyZrOsr7pzuY8FO/AU0Gr2D44lFhJRl+Qdpycz9ljHSDFX7yH5GpJD20tCq5Q9SxHj0NTIPRoyTWb6a6OcXY/acgqRlrnM3PdPnLQ1hGqd2PMKDxV3yHBI7wG6xCGeHor8SoXSVPbUJSiQihmQAydqiQWHpCD0LNYZjrXjValuqHBqJrPAjIERYzE+xfy7yxDvfDz3z42BmAu04hl1eHTXVhOL8d0h+qIWIK2mcVN5jenRF/arteP6JE2XGc+xN3hLZpnBEz0PTd7SjCobHOcP2ZVUgpYdZlkZnzvIRthPt7tqG7PDsr//DCcV7qyH/aeshWHR1Sb/ch8Yy7Bvh1Wwh/3TGh+YPeHqwkeqf9MUH84hDsAtsMiNRdxvr5YVvGTl1sx4vcyJ3UlRRxlwneIAAfKqZJZzuA2v8easW7ezbYuZ1AHOKTpcJCSb3IkE5sN1z1suJbyG2URlrH3bXtFc7ruM8R6FtLJQkf3i+mLLH4c2gz3XCTjyC4G3cGwuJHgeIn5eOHGjwyTXLCBlt+miUSAwLJNla38hENSrbeAEALUVG7i4B68hEPwBgcBIwXiJT0z/G/cdud8KeJ1P/uU+SCA0BAIlkEDAUKYhUGgSCM2Px3U2Drj0jwVCTwSC0veUpoc4FAOZjugLQs672E/602s/xtnTVnxIKlJkT51KPt5ov2O0TK8eBio5GiJWYiU1oLX2yCojk48MopaMZJIeiH1Skb5D23sgWslqXZiNA97EgL3cIqE6sOKGNsSbDBmpuBBgkl3gOWhF6L+gHm2KoHjC+JJpHplQMISImqriMWcOH8eMcWSM2oRkv75OB8ObUXINyY+Ycxer3SeNCHrFr+osYitJOELabSaeoniTgblRKsmXIitMkXzfwsH+cgl9rIgb0IjfVIVha+D4n30+7eL2yRAHa/LDakG2GqfbGwqzJFh37jTdVD31fIQdh0MXGtBtDyCh1nisMPZXsH/O957fxsPGYc/lg83QN9lRn/hJs+XO0JSxdwapStimInOLUtdUiTofl/WylvoRzYP+c3YI3ON/nbIuWd78x7Ptj6XB/TocJYlN1RAFCpfvSDGoCku5VCqFMwVZ/xyPwfmBZrJtlPPOUb6+4TEZQ3wW4CrkJD7xW8YRnni+ZZQJzCJpaImhbTkyijrQhWSvhcm22PqZRNHc86cz33GmeoygmWBOI1KhyEo1IdOLgl8amkxcjMPjS33NZV7ALRqVMwye6yu5YLH9L9H/Q/T/Ifq/Rf/PUKSSS2T0h/OVijxn+aLgTEXSYWk853yVOc4w60FoNWugGt0SDpIT4nJCvREjRoIOyIesqYQEz0gnKf0n7ieoJiaEyzbgrFwjLGixPQ3+w4X29wCtQ5yr4wNjcNX/IbL/ENk/RfZDRLGhKQiNAy7C/Ic4setuXOrlC9fhuOWAOReeDIRtl3o7YA7mXP4pnnNZ/5srVDxm0OhXkap07aX/Y24k6R63ewQf9bU9iKvIV80nF7bFY6ZMm625Ya9FHuFPhj9kyGMHReSfeBIWl69zXHrA5a0cc8a8JGMUe3pk0dPglQO9wccXDtrkrcQLsZJTUXBALEcU/BfOdEV+xid7HMpj/NUAnrD3QG0Au4CifzOM0XPJL9dqvF57Yb+wrdAGD8xSJBaQnseaHFGTI2pyRE2O2H5BTY6oyRE1OSKEmhxRkyNqckRNjkBHTY5ckyNqckRNjqjJcUAsR3BNjlyTI2py5JocuSYSQNTkiJpIxvzNMEZHTfCPanKkmhwRLw32jWhouILcUuPTXZbhauBez3PwvzXxDPq4vOkdGhjVGZs7uKNjAvybuEdMV90ETzzm7G0J640d1gIPhb4qU1DVOiwZuUCtFbjQ60INvYvzgZbicKuafipiFP00DsN+S206HHgkSxdfR2SVgUtqiB2i+yY+0m8OPtNHgbvY+Ohz8B95wSUn/eaOoIcZrY5GG+OISx05NhjwmeQHl4ATu0rYCFdGIRtCH+ppBR9chj5uWmuffWozTj0NXO2Tjy0cuLA5ZYExGf15sJxI7U/m+JF6NqSBDb58m0k+YfcRmfnClCVFuTKVrYqyVCubIFCmukCLso2kHDmODuXbRXmClCdIOZ5RE/YDZc656JCfhGhx89qYchSHRtYTuQg89MyzpLp2tKxMQxIm2MmTTX6XcVfVTQXwwQakI9smzydCOaHcAopppC3nwfMlt1yIbV6OiGkOXsAdOUtpClRyGY6lFNPq2ssks8eLtxN2y5VJW+VB4p3ssivEVjydsJjE3dxBcDZC8fmDGPrJiIgC9BPz0c+LBRtgGJydkBeOw0GKKw4N0v8rH9GW8sHAVKWc6CMBtjL4wgn2gfOkEL7MA2WRiPjKk3dOYh6uktfmlT20jGMaNHvE9J6SUSJGBqYFU0ZUBI4mcP4ahDz4gjR9SUw+Y1SKS4iRBalOhbMg/JOCiGzADSrJvPaxD8rWYSC2MFmS/8KaMZ51TkTlVENK1zBW2p0CmEpjDi8m3GjStknqRT2zIp55fcC6wAtu5kXCZ2KRpesPrjz+G429zQm1LT7ycuilVPrMpc9cusxdJSyB+VSRyJnC9brfEev7Y6BazvVtbjO0FX+YcsopbZ9f5VSvnOhkl8pqX5dh5cplrcvflU2YzfViNmq0kUjPhmzaseQsf1f0rEnylax8f/aNMx8VbCM9+LwWDTmnVE6ZHZSfkxSH4ouVM02ZzcRwohE9mm/1oPm0Zdkp5DfXRnKpjax0uOHSs2YmtHLGStfAFj93I5RnVb7QlXIydj9iXDENGd5h2wDzsQEzYZ4Q4y4ML/m5I1K3MfEF202YPbBigAMb3KCx+3cXeztzK1n3tZ2s3Um2GRXv0HHeqhgSzlLs5AJfPtjjxHktewF1g8bP7ah+Oyrejvr9bfL5ouwGf67b/PFXHGl6M2CGcyKME+6liZMRJ2AU3+fg729y8LIpbbD/r3WmmKJqwNpxRTjwiV2LyvDd1H9BCq6bBSbb+SXb+Z22Wyz7PruyrQIgLju12atpsxOHdeSNuHi9Typ7+3errs12VIubtBX+pFfJr3C5o6YT103wn2Hn2dPjivEKaOnv6dmtaLkQfCzgjPT8NSv38lcXHlt5dj9Nq1I4v3bBxdNgaxNBdzXrX7iUNT2LiIOSV6j5ln6OOG5JIZ0igGOEV3uYEUHO4mrPM+LXn2A8Tp/Poap59d2pSPaRIhIrVr4X7bXCGINeF0VrMSli0rWYhls5xDz3hl9EwqLaVX+pXiSJahX7kC7on0jsdXcfosmzpMhC1fihoYlxc52ElA8uUAxtLx7jXMG3jDqMR9Z5b/5osKB7/OSbhLhVeMyUcNemcMqY14nlAlTegqo5iK8T5jXfK8xvkM8D2+wR36CIcL+Clz9vc03sRcVjgoOq9D/B8oLG6ojD4CuJfXmTHW4nLku43OZ/XanI583brLCxM2tsf9J07lP8JWvJrpD9xnl3cO+78SK31H7h2x6Fvz7EOM9q6JNs+BaLHhgG0Let9iIB6HqLRN/QFGMYGc0BmjXLCDD2Zu0EgIMYsiMjSNsA1OMYLZ0iGgFygs8r9zoQjScXplf1Y7sgaR/c1ewjQWjnNmx8RlDDJ9kk6L2GeUAB4Ozt3saK9+L9eZqA+6vhpsf+G/ulHD2vO4dJuoELdA3vxodexqTV0BS6xqKlwH5b3OAIlNT+IJXBqXBfxWbaMDmc3ms8AQcNnVBzxJfAqQZB9NkZTDNsCWSomQMNw5ZAhso5UDJsCZQjzRxoZvGTStD8fafC/bTCiatwv1bh/sJrvnoO0wxbArVdHZ4BDcOWQIbKOVAybAmcCKYNkT6jmjkHkHyuc7uaBQoq1qpVIFjMq8XBYlEtGy7m1eJgsaiWDRfzanGwWFSrmFXLhkihU0frDM08H7qS+tT1gBcnz5r+G/qP1wjjnarGtkVXqgrlEsfzqnIwXlTVhuN5VTkYL6pqw/G8qhyMF1WNZ1W1oRieY666oxalSlU7lapQTLVWqQrBal4pDlaLStlwNa8UB6tFpWy4mleKg9WiUtWsUjZUzRAoTFWDX6VGdjgyUYU601e9U+Xaqu6VKtcI1nPyOFgvyKtn5HEoGXs76d24JuLKHSJKEFGuEVEiWM75zsFywXcbLud852C54LsNl/OKcbBcVMyGyxkIAsQ7afTV7VSpQyHdWpU6BLt5lTjYLapkw928ShzsFlWy4W5eJQ52iyp1s7ayoW4mOR0SiTgqaVSD3zIAqF90ymVQTJIXF1E+0H+MHiU0agn9U3LP7HLlL0u561CCJh9qwYucmZEvuMFh/L0BW7hZgI2F3oAtXC7A0kJvwAznZdObVk0s1pX9iay06RXB67wWHLwu6mDD13kNOHhd0G/D1zn1HLwuaL/O2tSGrtSCmmwdhzFDD6rhSqS0yleunXc8eNC+Ee5JvGFHXWreYeC9a0GdDbczUOhE9JWusdvxeJ5TymG+0wXN5IZsfOMYwAjQDJhBtD1RPhHDxcBvm5/Gh6Tnl5+tiy+slV+ng389wHN9gZdlSj4LR2yojKB606hRinzoYQnlBV7yXa8TFVJOS5iyRYlai9oI9pKWIYOVDiQSaFTXgp0lpGQSMEom3ciWRovGCDIryU4r85WcqL4jNlWGSqfKEAE4RkxVgln+qUuqbzRVCIxbMRaGxUBzVU8DxbQ2jtyc5yCFEViG8gNElg+cG+HbnKUo2oHrpABF/Qh0uQXll9uU/W1uZX+L1tzkVooiuy2iWMmuuAFVNL24TVvdgq63oNMQ2INPz5XTBC3E60k8EXK6rVd5W0BSrqCt8LwHEO2lhLFtZxftFmhfa5zzR+m+qLiv2zTdbZp8jYl9d5s2XiMViAtSE+fwijREWDWiXqi5K2n0Guv7z2BincLv3qLDXGhactai1WQAi9aQCSxwtsu9/ZxPe8BFPBo4KOa7/GruuAVLLbl4KwfdibdUyRZHtuCl+a3m41sDHoV6S6RuxVuva/hPiE0JXxa67cVbNeCd4czgG0uneHvzjb3zpuKt5UwpswqeF5AZZUI4OR63etPGfSgZ2Q9D0QP2LCWQdYqslaxyWcc5ynxrmNgfRCapAPdw8Y9w2ncGfmyHenQRm6p8oD8mpz8HouwTtAxfh6E9DOLt2op38XbBRYuh1Z38wu2pFv7QDNiBW8dvsu4IXxKR3QGuXGL4e1FdDPerdfYQtSDywXQcy9PwB5ryZR5i+KmuGm5cNM6c4my+0vQHHmFws+8NM3L+PhTEUCqV9OZbpiJzyK7pcMhw0YGIHOqTOVyudX2Ar1iZlUQtnh7NykM+p4Ui2ZHpjJwRWMsh0V+H+poc8HmoZ3geZJ/gekBzgC+6o3/0n70inRQVdDiBynZetOTnEaf5AUJ5XCgPagW0ZNvjkpkyeLu7IYaWmUZcmf+mhOaiS3PAy/IZlmMnWXc4ASXex5wt4I0a4gsSihJ63R76K/2fkeAguPOh2kLWeAONio8P0QnvEVBohj6BOiYQlXAfi1+Vc01yGlzeKtzU/DpUPI2ZsaGSSQvYJFcPKuVQUKJSZgNVL2vJPvfFlDjqm1H+4oiOlxFaIlV2IMIN+/GtDySRxBaD3gH/O+g3NDCDlXjjJiZZw1/qhzhDPKXo2s6oQVDHirJMdMyhs3j7DadAeBB++uq3+FENZc/vgc+gcQsBn4FkS5XL3G078aP/1FRp3MpxgEiVGXpWAPhDvSCN6kjVSonaojvEZCOq/mA60tj0n+b7hYxJL1Ove+whyCYbV2s/+OwtvIbgWLA9Etzb073+ZC9O9e6d6J0evONDuTP/HG+NrIakMcl4H975F6CscMRqoMnpfwU9gY7HJidzp2k0Owm4abJXt344e58iGnKdjFS+sbMq9kqVec9UvfVO5j2TwSvZ0iPZ2wVXKG49TrHzDbRNJGliPVlKZwd/dvXc++LrrW8971cPPvWCPz0sWl/skd/nWfYJ3NPklZoeBYfHone49DGogAnu2ALsamyFeuuJ2vAXImoT/LEFZGMr3ExgNJ6/IQ94ECLD4O3TeLdbxrvdYqbQEPxD1wlejEnwEril/CzPfB9CY4tTD+JUYLuz+BR5exUn+M2wP2clNI38moSIb3Fhw+eMFUINP102L13TAIesKU8yCn4t3HxdRXR17k/gScTYUz84j8i+3ni5X5qp569aF3wv9bVVMq+GQrxeB9JMNASTVJEh+loNQ0c4vSFV8tq3moaBBg8w1b2JKZXBIz2viE1w9gSBQhb8dM+rzLuE32KqrqY4dKQmr+w2rdW44BkbjHCUEzse7jglTlESpNU0c8XZzNdYVvUQHxqtD8Uw5HCwW/Dq7GukrleyNV6bvJYE4wu7r4UxRG9Pamlx55ds0NLVWH7KAp5S2K+A+AWZwAL4v+vnzBUE+nADmOprcI1nMFccoNDwFq9pwgVgg3smxQPHlYgrEVch7rEiZW1Kfp9Ts7ubcEX1xW4pvozm4ovdQ3wJDx6Kl94kuF6OR0fsdstLpyM1HrWI4Ipetlfv2f2lwrAwHGzecpJ3rduBJhgvKazNT2oSdxNHlSr2rmRbsKiz90ldLw27lpsJmZf/rpeV0X/odHMK8j5A1hW74pG4UA4XPHDHI8/W0Q+74imtd052zdNb/z0ydk5/vJ8eHIyT1MeClyC+GmdvxeGD3fgA/kVzVUqNB6nAfb6bOeosdsttZ88D/bUOsFNQlhJlaYMHkug/UZZW/HyJSImaFNSkJwDwdhKOzhE5acGY9AckpCctcQ4VKUAWtzQXll2tm21XTuHyz115UF2hIJSRzrJ1rzWJFC/pWUK+rA8jFhWNg+L2uSJKl3NU7B3kh1cWJd8st26qnXsnNPPJ3VaxgQTPhZFCHCKJT9KP/q5bgESyHHBFzTq88SE+D3/C/TeMJCfcecMdHzTHCZcNTvy0Eq64IdDYi2snXEQ7gV4kxKYrt1cglNDNtKIhAhfkzyjoTAWdT/zkEiGf2Uv5mb/wgezPOO5yRi7sk8rnwPt6gzDXldxZtkII9l6ZraChbo/x7bYq6ZCY9H4isWiGP42xoeSCqB6ggoP4qvCndhhxiT+dx8/pQ9GH4oRXj9RyEiwOmpOOKJcDB2peGZyAGGamIMOQOQjLcJi5LlaKAkpDs2VRFDSPFgWWKWgyTs0qYn9l5WJXoNynewyZN6PdPqp9CwmboXHrV/TmK4UGazy8enZBT8QSGj4Mptlw4e9D46IVAZDqlE+3BbMLDeI0zKtDhr1q9B9elQ+LI9PVEURESn7ydiLcbcOH/2SH0e7VisdSw38Ka48HH2t13Wgmf8cBLV8e/Bc8zVq7bu5R9M1eRcR9zZlzUVa8g9W2crQroJENjYfhcqs/JSBFRlnQxAavTYynBwq7eohdaHe7DTut2OPBFjO2t7Bwi+2WJ76hNRQN6QKYDgXu8NjPTj5oOIaggm9eMfwxP2Pzbw70ZNzCM9/U/PztvXayx8rOudr0bjnLiTtOuCtInctNhM/28U+k9J472X/oOw745PAh+k5V+qAPdiX7jtENvkXdPab4P0T8t4j/KeIf4rFWlwPTNgTi+H0CHELECzH4ZQC09288AJO5GAJkBMgYYB+V7PBSDP2/OhQAMvy/BhR7wxcnWCyGxM0dysQjNA6hcgiNQ6g8Qso+gnDjyCJgkYvCWekRkBov1UQOAakpnEWhJkj++9NXA4k5ZN9lGBwcH79mdwT5E7Ng6oqtQM/NYKENZJ+JjMZNiSc6BIrDKEr6L6f/2UD/jf9W9EdfxS+/vsSK6BN3sMVJ6EroQuhE6Iiky18FfPhLpP8QvybiF0H8Ij4EwOIXsfjFEL8I4hez+EVW/CIWv1+wlg/jiTA7AyjhvObTz4ycKdqMlvUbbM1DYRR9si3NX5Sx/Xof4PfIxsLzBH/KhzFRFBJFIVE8JkpkY7+OkzQypJEhTRTSyLGgt37o1XVCZ0szCyaTP5AYH0ykjUJSfDkS8Rl5/MjjxwEf5OHjOKJLjy49euTRZcie5soZ8bybdvYwfcXR1Om0FTbmdErLr9/E1tU830LGSdupr3jrJ559JxzzlWlu4vwRKZwKpNH+Amf89sklf6WWdRELxLTDF87U+41ybPdWv+3NTDvxZqzYYjEGTlnheGYcXOLjKSSH2PL7TVwt4LpgK2uP0E9y6n05jjFeEwBBpQ6pcZdAG+9BH8Crx3YsgqrjY3T4vfhINl07ux/EZZaWgU493DwKgQch0DmO4Y7z8/rVaCrRlKyMqA5kwMPz0/PozCeAFqltv+e3PYOOC0w70GzHQyurx6BUnQN8WZCNMnsCQCQoC/2Aj5/5a+Kjays1ON9WfDrWXQAnTZR491XGvg7AIsHvSXinqvOquAHkLxH/A+PP4G8L/4fQfwv9T7iJhuu2CgMWCKoc1gPGloIku54eqo3ba9MbOE+o8LQ3akW6VU6vxiZ8XRWKTrGiS1jRKSi6BIpOsaJLrKJL3IMUo6L7l/Nw7gdQZZytwdMo1I9qPGOHV+Vg8b4npoAztPewjdCanr0VsYgzB6zHLzwiTtq4IMOOsuk5pDjEXt/eY55vPo6M8e9KsrPWKi3V7/A8kpaqVTSrf2Cr9UVj20b3V5oXm0t9kW3S2be7aEbf8qIr2Pry++G3a/SXi86y8nrgp0AdiJ82s24mLMAt/93ArfMMENKOb9u6d08dCkJo2j2cBnfC+5z0o3+UzZe4EjMF2fQpPzFAg+kLnHzUh9mR0otDqtxVWR9+xWNpIS/t3b/D84R4sWcob2OtA+KXcpnWPqS4ldbGurQdPLJSzVsJR4mhVhMn8x4UprD+8GYb54EJ5dDNkD2/FvDCcdi1/exlrTVu6bpjZ8CZoB4Bp280T7YDl325qxyoHrGq/NtpJKsqVugNQ8uiG2k8dhjuWaOLC3WgWthbl4vwsAhTX28VKbksQErJR+hJ3wWQ4kRHaTM7mkUeWGQ5wDlnY0cWjLCHzLSTh1si0sBuQI0O2Hvyz7fAb2ZPBldcDS0/RhRyQYhhzhVozU5tQnRNhMPpZ88jd3Rg72oY6UBKMoSl6YiUHo3BPKTRt6IkoHnx+ItbsCZ9SQSDH9Hk7ZeW+jtupU8Vvqt7Qu1DvOtkSxob76IQ13Q54GC7Y2wRUANjywDqJTvDOzlUBy4QCjgNP6arffhZJio74M/4rJAks4JssELIHIeo+PPYf+nWfyuPcMR7C/brC7NW+ym7KwmTz8NtjJzQQM+TBwNbjVcGC81OBbCS/W8/PNPAT5B4rbCG93xhL8bPthxsk9RZQYL9wUV+hCIphix/MKIaOnuY2jkLgqNMjRjNl+jQzBRpe4nmBQbJsfaOnWTG870SGoLzUfP3KlO5aLEN0IgW89ShFJ+lFu1JZQb3/h3Qrpp5IGHMAW2ELESbmfBO9QPeK7M6PRkycZWZ6OD0B29qD4X4b8R9fup7gteA+t+guHWYTUlo/43QW4uAelhOHtgNFqbU4OgYQlRE3QPeo7GEPGoXSnZlbRJlcF+Lk1MaL5ZO1mjtOoFdGMAmhHW9HlZkvdt1Xn39Ci7X3bqsc6fOS7Gf1qX61J06r+Ve3GtLv617n5eFlUbtrSEJpSjgS5hSVZq62dQHOHiUoyPmV+6BcFKLls6xxJ7RrJV7UFaroeS2977QK6pWDu/01mX6TcF875hdM7WX0W06O7zqqAb/7jr46PbdOzDB3eYSf3hd0dqnuH+MQQHbEuPOX0eqsKS6DDA9eaFnArFrQ9TQ1hmTWzJ6I60N97F2X3CC3rjlpUmS2q8mjVgXTljQP/7M5rGZexAncctRk6jWrVRNQFhKwWlwrATymznY/fYBrMGMqN2csM4teU0yu/p1tHIOL/37PHisBw9JvlWR3zO1u0m9qRo9WxdTEFeuo9uJ0JB2YpvdpuBP3q6I+DGObkbnj4UAwT9DLn5AOml6QpY1todqbFd5Z7b8fA0NZJXq4YiWurJsIxo3OxGfBhpasIrmEj+WqsFK/Tib5Q1n//hMufL4jHt4ZnxhJrwu41OmLmXkfiv3ixUj+1jN1/j2DC+G5Q7j0y6WcS4XXvl6Wls0xE7D7csz7mEZ+/iMEk8LvhUirfDiTlqLtBEpnkah76uuH2jqlPIcyL54grnML/umx9PUC3QvH1pTwl2r6mmKfTWmCrBYtQ98HaPLjSkOLqj/7Zdm/Ls302d+Hg3cttDwdfg3x0mXOc+Xe9K7gjfHSlguAJFij04iIhPxQiB4MusEtkjqq4CTmxJezWJSyHj4AvvMxxJPtjR4EINAhAMk6LAe6z188SzH8Eq1GageNLxkUtLsWjqA5MH34RbYKhD03ND8sy3wJeEG9XnaNtVAU61EKGc9u+BjfG11CedfM9uYH9/Gg/CK5AEnYUqVZTDPKVzzHAsP5F7wLLfqsC3GL7Pb13I8LsJ8aiq41ymuxMR0qKl8zp2G0ueF36X+pBb35AAZ/fZUvfxsBzhbvvHXdIaXozMMgDO8HJ2pMc/wcnSGl6MzDvWcEYI9eYaXozO8HJ3hFugMdHg5OrOXozO8HJ2xk36Gl6PzgFiOYC9HZ/ZydIaXozN7OTqzlyP0iTO8HJ3h5ahlzN8MY3R4OWrpn6asLwrhluwI+ki1OF9BLns5Ok+8HJ3h5Qim13lk4XnmoWg0KqYtbbUb2V+kB0roMR6MyaSvMdqWMY/lJQ13WDVhO6Is5PidTL6j8fvRvh3DC7OkjuFPC8cUcn7VrSEyi/FtPZ13+Sdsi9erPA2tTVnphCfe2K6AI80fnNUEQWa498erCNPzIB4/XQUWWDMi8tciX92Dj24WPClqJ9Whi3NqmES14ShQyM9NLUPYZzO+7jy6GHxdPqjOe7ETwCtZpp6aLq90q9crgTLaT2lR1zD8a3R2j9hDY09SWKLxGD7Ch0fqb1DHqHlit2+NE6+xx5nAXsfXicgSJkMcT9WyA7tcj6FPEkcfMNPUvW7hIv81V781Oz/l0wHjG4KLYNuzV+AFNJAwRHgzojcHW9IvvBoRHlj3y1ZyCrWS6Z+j5sWFHzfvOL1O33F6xVTavgbIaVt+oolTvobX5wPIZuaXOlZZ9WgXLLyfQFaIXuVJHLL+MVeSVmuQjvmxmiQinU3xEe8QJ6LA4dxyPQ+e2ygcFVjP6sQbzW4O5i7KYtM5yE6Ns/8lcjGLEjoaLy7yiqO9lY2vZtnEnoStaphhSbO/D0yGzfS2sNnIoJnQ2dK035bX4nT7sEXsQCrRrTx+YdDCVQNOVm0U8imKiyi+iMtfOY696RimWfCS0TU07al7HPGGA0LSCsV6O2ey4mP8soIPYjKYizY39NHpybC9mlKVt47wRumBy8CI5uFOJPIEniHzwBf6phlcLnIt8hNePspLkVciryc49G1wKi9v4FGU7KWcvskGsmTgOIwTSJHKssknADIgIpEmfMCHNC3O5ziJS+cCmGYBoknNs2mKuSXO9lvhSSetn85bH+Zrz2eHJs2YhnZLP4ku4n4Kv7pUEreBZXeaqHKENbhRg1NKrj+Sqd3FNAj0i6VEvDeMaxSfvkE3ELm8ypZUoTUrlFBNS5iiD9QnotlT5r0u4fwrWQOma8BqDVivAZs1YLsCPKW6y9mIx2LJHL9by6RfA36tYjrrZ0V8vcCrepVV42puTLl6raKh6ciYzXLxa2Ex6pnq8VvS2viBzOukZo63yGVYzWWgPkrD0Twj15Dwh4oMwMDQkHNgugbM1oDFGrBcA1ZrwHoN2KwB2zVgtwZUXb4G/lwD/l4Dfq0BXaO0ipjJe0IMTqBbVmM8Y4OYWltFrSNblbMeF3TeHhJrsvUovVOkWY8LLFxGDBv4X+v4N53I9hiviq1ijoWTrHhoaeoPyyBd1FmkKelF05eq6w6nmVSnTsuNypqSz7tWZqBPfb/R3tTzGbj8+EqESh64ndJytT7VTCZCloRfja09qnkLY7OQpqQ0cXUA7GjZ/Bb5hxwxMtjh0bCDTKrmtABqHyplRUzTAZYWjU/c/cf8aOz5XKGQRqEvz/1lVV1rfLGrTowasy1SXHk5sJcUv8Ml5/tdXS3DnuPr0FEzduEs10slidv1g/WQ8sLZPFhYiLMeWF4YJcRZTAubIUwiVrfaWr/7iefub8piYNjWm+772v0+k5FJXfjQl86+ZOYz9FuO4mVovcEdNhpXKEkJhgNMTrS9eV+RXYKrhp/E+AOZa/zWWeXHlERU6BYV9uhWDTVv+IQ7OVW5gVoKOMWdYdcbqDX2JY8LPtJ8BXN+UXVUBiSbfr+IfO7LVSRqNjCsYVWlhOPfEbCLPtPBtnIdcWdjm3ocVZ2kvRq+gXshOlxxfqc+FDKBDEvIy9Cwex3fbIX8vBbzd3Azu9+M2fV075oXoMJGWdTqJFPjPn4/3at+VcTD0AVeLT8mSUkEfUpZVqbrD+o84E6oCQcAoDd47StXMvHE2i3wCbjGJvalnoBseme0LNetXO/n1ycYbz4LWYlf5BCFlyLC7HJmcd5Eb6dfI+A2ej395EzFagbT+EUOsRsBbLdjDlpVMs9oG22RX7LPkeQeR5J9jiT3OJLc4UhylyPJrKrryUPkRtpRje7QcIu1yM3ZO1ZTM8+t4p/ntol1N7e1ht7EWs/tTk3Vn9WUdeNeRjOEDYomImoHt3WSbtEW+aX7kpzek+RsyslF4kXcImW+X3J+r+R8vw/l9/pQvhwk1tOP0evp13tQvt+DXPR0TFhNP0NYn11uS5O+L016UcnNDrOHuMjTTRjXcplHrafbas/iXnsWd3RicVcnlvsUlPcoWCLYxYu1nrGLuZ7rZr3K79brjhYrv6nFqu32rfbat9rv79W9/l7tt051r3Xq/fLre+XX++XX3yx/sx3ru+1Yf6sd62+2o5mqh61+v4V0L68trbqHuJ7nHbvAfNMuMN+yC8w37YJmuw80e32g2ZfB5p4Mtvvp2z9IvyY67T0Zbr+t4do/0HDtnZ7R3u0Z3T5funt86fb50t3jSzdpdDc/26VkFXE9z1h6UbyT5yrinXp+J99N5OW5iv026O+1Qb/fBv29NujvSFF/V4r6b+nX/pv6dbkIsZrZFtJ6Xtu23nDf1hu+Vbvhz2q3P3oM3xs9hhutuzV87GIucv2cFL7IZh61nm5LDj/vyeHFIqwNVvOo9XRrfLzsjSmX/XnM5d485rLfby/3+u1ln1+Xe/z6vV/+73vl/96v/+979b/ul3+9V/7XsscsMliJX89hi4Nf9zj4dUfz3cbH+S2oXzIqvkxWBm3d4+stKKwfzh2lx3bteMm9RsuM3wtwS7rGXh+0gZvhKpdtc1i2qN0+/7G+zLnFRHmPiXK6m7ciByvx6zlMdxc29OIu5rdyXdMuu5jfyvVe5XfQv5X/mi7exfxWrneafBt7PXe75nKn6W6Q7uW102A3SPfyutdM65j3ct1pnBuke3ndaZJVxPWFzq2c1L3+rO70Z3W3P6ttA0LtGRDq23pA/YEeUN/WA+oP9ID6Mz2g/lQPqG/rAfUHekD9kR5Qf6gH9B3J0XclR+/Lrr4nu2Y/vflm+s0amLs1MN+WYfMHMmy+LcPmD2TY/JkMmz+VYfNtGTZ/IMPmj2TY/KEMhxZu7y52LXHu5LTTWkucOzndF88VxDt57rTKEudOTnda", + "Yg1vYwFgI6PhXi8e7vTi4W4vHr4hBcO3pGD4hhQM35KC4btSMHxfCoZvSMHwLSkYvikFw7el4Lq9HHDdWw647kvP9Z70XO9Iz/Wu9Fy37Z/rnv1jjwA9XFTZ0QxzeQfgJnYv9ede4s8tiktjmnWCOcafn54ZpuMxT5ys06JOZKelqDlkHyWEy0wHnwJGDPN7jmDDY3yjWt01plK1nqJNwTeW9ZKuxtLVLOlqlnQ1C7qaBV3NOl3NBl1zi2p6+Pg/ma4bW++2rNaW1S7LapdltYuy2mVZ81r1M06XtpRyWUq5LKVclFIuSinXOV1+TwIWVP2Pksu5AWvmRFWWqGpJVLUkqloQVS2IqtaJqr7HqiVZxpJllmSZJVlmQZZZkGXWyTLf4ZWpNC9W/1f0lZWy/jv1leG/owb4Q820HMGnlFmSLpPC/zcu4n/bay+V/c84EtzQ9T/FSDAZnxwTOMt4prUdGRyT9DP00qKPPdfpCQueyfM0l3jYyj+e8GlG0XIk5YpdG5Mp9pC2aIlFxILH+2k3UebtsJ/JFsZqW+1ntY94z+KwWbSmm6SZisYiZo1T26m3cVZ4tZ3NJso2t3ZqtI+5ZzOssLfckqnyvkyV92WqvCtT5V2ZKr8rU+W/KlMrXFpwtd6UqPobElV/Q6Lq+xJV35eo+tsSVf+LErXU8/9LT1XfGg//l57ak6rpON3KOL+K2h3GqjfFYBHcbOmJcXD9swHGkdI4UprpQN4s61MYwsH+/SLiia2hp6mJAs+x114Xd+exM6tjTeMtgpsadFLE5TsK8dZ8abnWab9iu9RLVixNviOjHb8zYXMsrxzLqzmrbHb/zc3FZjOwbZZuzsJcWcaVZdxky04nllbq3TrMTb6F5KxV43+3hl+bm5Vp/dyCnNu9367qGkmtI6mdNqsKRNjSf6zRm1jG2MDmoPBf3V1XbHBbp2xhZ29020lri0dVH86DTMRflfut7dOHANiPR35Q5IGofFABBjdaC1Cnfy+RdDa0yoem3opCzjp85xIONO03XHdRRRLcGGbIa23qB/Z31opX9/vIvht782DPubinDNnxIwH54p6Fufd9Hmt77VQW7KbPAR2NxI2cmcEfVHcLyE2rv0ztvKmIR3elEhcI2Rlmab2R4b4hv3jApbr3xc4D3MyE24eWtK1IB6acHp6XkU84kPPgr2ffxttSHWnrpW5EOvC/VOpfMsNjhn/ZLBIbeoyGkqSUWraFR1C+SOtBcJGDxfFSSfhZenSukkJ4wuvwktNf3Eq21IaaHZ752J1UeDzpER8k200+Bc5FQ1WRShIcgVrIxySiMc0h0a11F08kwAWR7HuOm+cGZ8ytTtQysxHunKXVxopb6AC8XF6W1huo+LuHM/HcDB26PIP+anWlQrM0NuT8T7lQuKVvw88z3Oc5bixbMN7LFmrBTOSjYmti+GRrtI9EJKRwDuufR/Xk3rwm8ki5EEsMuwB+ZB/W3EngZY76DwiEI7GYj/BS8C+QC58eiB0bnJ+z0V3lO3IQqBRpWZuU3Flt55u5n7ba8IyXUkMH3EYIvWT6CMpjCN5WcApZpOo1bCO8P8SeLvtpy+kyhnxYd2789iw3jnVm7mr3g6mdgR75xLflRjHJr1M0IPD7Zo/stJYGQdu7PG6Ht5Eydj7gFFd5ZdcClWpjOJardO3capO0XAZ4G2COjo9MhSZLiQjci5g6GbQV9q7O5o8oYlBph4lQ+ifYZmh/6c+VtF5DzIAhvRc+dovAniS4rzhOBBU9Pvn2iAcMhooS9rlCq7E7Y9s3L6ZNDn5gSVEeaiabpiQsWzAxQ3d4eZ2EtVKdeJm84Aa35Es9oTu4Er1REwGc6rbrD859fIAu9VCI0HWuI93D/3KlUM9Dd5EN+yN+RD+AD73VSJ+QaI0ogn2rdblcpFyNtZqXqLAeNQGniv9FBsgN8LEbSL85xyD2xaA1hz3feTfoV3DyLn6xZFI0ruV72NI7vfh145J+tfBa/COaEvgC36Av8A36ah/mY9JeQdoLSHtl0l4saS/Wi/BI2osl7WVK2o3j/BVv+Xe8Skm8h41XsX8Hjw65qNi5RFWJqmbvDJ2oSB2ooTUP4/ON3HtZ+v1gMnwp0kIuJgVafsB7sbEDlRpuyPkT45L7rOUIppbFjMwGqBsrN3ZRf6k9urrgsfqzf8TvMeFTxvwJCt1noRv31Q+Z9W3OyDDRK18CmRB4G7hRdX0dKfBZZAPe03BvgT/KAW9n+0Lz9vpJ6tZzgTp6qOMnafueWrY2Oug4yrXiZ5MtRarOfMV0za/GTevaD22hsTU+8qUmdQHvlngqwjFQ1rIPjIr8IE+N3XpSqBPGRnu+daYKbeZ9vFgvNbJtjKnnviYWQPty4tQKPYQ3Ivi5pq1IOC6nQSIuLrpT1l2Fz3MDPHrAWPF+4UC/iJpQxJgPn0nfKHoe149+Ml0hQW17AEkvDW78iopu4xJPmfBILsiAk5WpE5HYCLLU48KaBJb4W3onmXV46a4WSaGuNM0SydBgzD0EE8gasiWqbcfbAylknZAWCMQvJwXu7Y9JxetB9/6B1fBWBY+p/FgJezRxjkwmXJ88bhIyezXhtZRbQiYmg5cXe7hXttEhPJcyzXwP7d0V7TyhTLnofaY4+8IRTYNJbIaaLOFU/JUkrerY1b4hI1dB3Z1oUPNG1gMxaSC7x09tY/GXwiGQQ6zKTmMwZX8zyoqv4xwMRGT+j0Qe8BD8I1zMtwc4tO7hXPGRGhOmBhViM0vhHr7OlbZxo7LNxJMvOXcm2MPCZWK+RSpFNCUp0WIs+IPbgJ/0bHQoavR+tV7CLWYpntxgQIrjEKFFfN03iIEuGioV1GwHH84HMh+goNBXTHO13nT+mhfVbOXYiPR8Q1i7UYV2KxdMzEgAOBfrJLzgyUvXEM+wWKDaTx1mEL0qVZObWvmRi2aEU+WKjqfjUm2V9kXTiwETEps8r4Iyd/arCaDVanyxkmcnhLcHkbB6RuOXKj+D7iaNgE7u81wwK9ooJSaBpSlCxb5nfbPOxFKNYglX5YEqD0xvyqq8xBiiqsTDIy7fSPXhOyN7tfz/2Xuz5dZ5Xk34XFfhG0hVkrVWhjeDI2uwZMuSosGOs7/d1Ud91Pd//OMBSIqkKDvr27u7+uCvSmQOIAjOIAkCU0ciuCmurGWny/somnPBDGv9uDoT6g95nPQlLZmZWeTtdhASqOunouXy3dVmmlPMe30DY8r9eDho7l7KRrvf/oa6Q5lbqrV2lb2/mUNUl5KfffIQSqu1jk+jTAiGTtxoX0b7HXprQ/zrcFYHOVpdHo5csT+X3btq/T3thHqap/bxZqKDMaKBxNoAGyyA0V7KcqrZ41htaUybnSt3ebCZQ8GGuPAzsC8ryi5lGxc0fZaYj2H0YpWXOUVyMDt7sYChPWwIw3hkQH0hQY4NFrtVOHO1wMTJxdcrOONj0ox32nDzlBNr29bUX8C1SWDFQe/gqtfMVb8zV70GV/0OrnrNXPW7cNXvzFW/DxxSScxwoqGGdFSKc/QOYgua1LosRdjR8iFKH6BQxYtt2xktf2cIDdVPIUJLqmhJhZbUpiV1aEldWmZUTAc9yUqXw4C/2ydBlnk1O7uQ+lMDmPg5UuFg6Snj/ZyqylUWd9VZQtIpNysTqwB+R+UTWdURdZeX/d9kuOHWY1qiW2GmjNfiT1SIb8Pt1mfYgMNSrcacN1S90kSqQh5g71jH9rBzsrJCHixInz5HJeWMODd2Snpi/YuzAtnBEzDGKdTBsbJxp0rmMRayeeRUUfO4YLFYpeZCoSTOT5ZjQeNTbqfZrPAZtinKa0gHmdV+mtHsswWyRYVpmGyJCyYTKeJwMomzOpbVVC+Bpp6KorROhjqzlrZup5O7aDvlP6+QAHxpw4dpJzauxvtaw5SH8SqwCfWtu9mCzmw+JZQNkirQtXh/qIGV540nt6vfDtCZSDMGM8KzwkikTxZr41yiKRB5ad+iWieqrLrSLTaHtmp+Z9XaxQ2UzuEQbI2LeVThPKat3ery1GlFN/kqOGnOMM4m23/auOz0rGHVjhdspfNipny9iHm7+BSo8GANe+U3oFOQsQ/pj9XfK+d66/KsvgwUzmmqITd0AaVdP264NfX4+GVqdEOtYedEyELnwlrrnQs7T26vSspY5nzdcSKmBP3nCCOqoSR+VGCW1McVs/l1GcZqkbgv5qunG2q3iBNhtYgTHp67AmNTR1jLf1EOs8I6gTZTYIdPxFzDMa2eKa7BspQaM66i6Z2bfSc9mnMn+N6dNt+t7PQLlElupxg3YKEpXxaXOW9lx+mePK8IZ7yJqmM5vpv1A2eO8zhH2aX4zdMvcAPeSdzS4joDm50WBsF+L3XeH2a7BB3OfQFaEYFF8maRjQzEWpkEYrFp5X6QNAeaCA7QKo4L9qHk656c733hQYuQe5V9lf3QRw9pk/WruhkkILrNDi0OPHFpWdZJpzDV8abCqZ1gxkneLdLQvsUOUkchVkiC3l7WVIv96oA7e2Y4VY4q0o5T/SyQSlmFp80+Z85HEuRJx2SAQUHjtI4prLvRPzdNdzPdAN3y3SRu/u5KXA1ON9FUcLlTNbfXe1S3Ek6Qo2/jldtdK0DdUBONVGfJuNFObF6h1oU9OK9oOnU9NzR8kCOGsfW441PrW/VzoHE78pot/r6l9uMOpQJSKkLKl3uqXiVA5CuIQMkEEU5A1WwVljR6AvF859/L9SWu+tXV6QD5o+mKfQpQS84UgGbDIcYUQoTncWLDHJuKNrp2IsM2mrB/5ohc7nMez32axkCG47MkHrFL6dAN7OqWZletm30lGe6dt1mj7l1twKI5NNDjXyaQB4DGLasT6L27vNicjiqr+JtGDkttZLxViW5PXRZDJE71Tm4FlUx6p/LE/ZnGXaNu+I0uczXKliJjCIh98bGkHf6+GQfuCDHu3j18WYm6WrlJa8wec2BPs7qixg90AgjRFKN6iC4j5gYTR67yGFeYKOA1zaBJsCP1/JVAv9Jwwq2PlD1OCurzuKSoygOuCmZoLtYUqEViCt/y9cStdiFmoXbVRa1cHnM5cImsZBd4gijrCfqPna6TU3Swa810okwjl4qrZa4QQ2t+ZzJgDU1uxSk99+dVmvHMIbOdnic250nyBfahnNabfCWM0vEMoOPcEJjjSYZ5Y8CqyA1MuLltvUVPz7pAjJUA+4WlJG7clEh35oV08+jDmMBqiEof/bHB+XRdOpBKZBXt95Tot5PoTg2aiajaLuGTQ1C9VPjOr8lAldnR9VKuFlAw68XWcmvCz34q/ULWTvJ5zlb6tssS8K5YAZIky7B71mFu59DxbqgHaxfIS+BME3oBVMmjZwWMVBus7LiBxLVAZrEwqynuyYozoQ5lU2qXYDOtTtjcjvA6Jay9CtDwzDQ6XdnKbR5J/bwaSjBqTyt2TgJPz2rxVuyImd4eaf+xZQEgeOy5zmC1QdwI3LE/QT5NdgGp8E9Pspw+iWDVU+qyU8+NxR09udzT05y/elJz3pPIsAn5CxnZmBXfBKMkik8WJ29sxKlslmClVUKKbG4pq1j0bGTpti7JerNo2XszxXbj8Jxm1eky0wUyhiNd2HvTKfmmnTkAztB0V84ZfWjLd3d/gXsaKCySsIJdYSmbGSZ+RI07wwrddNs1VCs+l+7FhxK4Xf9CYhfQ7ny305LLffdAneuWBhAt4pDhIZy7EbUBib+u/FLMaRKLQN0X2rwG43o3tb5IvIpuzy6JHoz4h9os2PzuOyV7cPjdBzVklETK1LfunI7GK/PkNd1deuXtpjmxqCX3QVUZxADjug2HtCIdOHGDQvh1OBGPXUQQiLlzeFTDS8BK1VQTVIJ3vjLSRzg8FUXPMuvQBGFX0KOqoLYckoJ67F5zIvyuw9lYmEVDa1Xx1popmIg8r7z1+h93lZqw2VzbhZXMBrOWpHDwq4Po1axbr9O65a8qplOb5WUK4dHtzbrOIHhZml5vA6mc6d6fmN21IMguLfIaCzBmMlmIN3PKQjyCQtNLaMMfmGZCid06+gEiqy3MBGreJNxqm9ahBwtYItRRr1arOsXxSrIYO514WDbsrDzUyc+HM6XHVH9ypjGHnJ2keOdZV9P7KSedsR9gtPlkNJyHifYjeCFBDIswzPLsrZXgUiW8/20luFh/ntpN55V6IfIbvUtZZY+36uypL8pWFoZsMJIkVDsJnxqo8zdcv2fch4whMdVrLD/NzpCkgxDDHeFtlfv2FB/P9jOkJCur6c3L5OXIvGqmRU95lDVdBd41bfQoiOC8xR2hFfXbiposBDdaBFZNRFXzDdlaYphoMb3tsy0fBN4nvO5NUl8ir4YDurbpeScKm+dgRAF3LLNTGkMMWQQ+IX6X8PTGawsOq42gbu1QcYppmeFq7bbESvZSCqFcTq5/qyKpc2xVBTbEowthzA9Px0a2FeIpNKcGQ0UcmMWym1QfP6y8IUCdhyhsRGBun9EGnDgEvp3l8wUR47v9wslAjCobhFnZNF8QTztvmrhL1SME7wWPeuyinyIsxTrZsQE92ujW1IIirgsD1NSFUuqwfM7IVp87CBzeUJ/MuZzqAcIZFcVygGPdjJD6JNZGrFHKCsQjS04J4pbPbCtiiBA6ok03OIR77MsavHZLbI16kRFrMbZVebPJ4kOU4/6pL+TtYo6vmrj36vzyILLB+x1xCnt19ZCra2Vhfw+IynmrwVcouZEfFi8jlZ3IfhIt3k/L/95Z/vPpSuIY02DMrQN5CWCE/oXvfnZfm8/EmXOzFZnm0S0f7EhJBDMDydOvSsxaT8m4qPpuxaLGvW7JtW1GPaXBPraTBwFIDnuKmeAZ/XSvY2Xg31kXzZBNhRD721ahFP88ARBmy6dqZgogAvqiyYQAvFfLVI8wLW1aUs7YDMmTcnUupOVlLt3y7/hQ3HgVZjs9qpnJUFUlHLcVIHy0lcRhqGzkzeEQr0zVy9ln/i0/jEyFbfXbL6syuJiGs4v2+hhPUcgNp1HqhtR+FnbNYaQ85xfOypS7hV0/lJ9C+Hn55JWX0ZNfzJQya5YUGVW5/TDV2m8tyd1QBY5EW6fNt/J8t8mqSaLVfetgWxjn/cH0olAnwMJd1iOttkKnLWROU1V/MT47UHlgGGTCdjDLlg6Ti1C1CirDcyzP7j4dvs1q5gZUqrgiHx5dHTMsACa8yKrDlJ06OXFXDnO2Qwvek961cp1SZYGXMcI0CrAbCls2jsrZmCxo8DXU/Xk7p0k494MyiKKD+AKR9d+Www3N8i0x9MXNcG5NqrRyvLctrcFUtpt2rKob0KaTKYC3sfVCbtWWVJ456WB5pgbJw9u+4Xk0uzGP9kxlBtcNnhZu0ywpmeHXT/ic6qYtzLFE47fxlo9UvgblbGkdHNSbkalBqgxy+m6g/xKMpkxIELMMW0wIZTWMYnlOaYm9LSXaTIk2dqLQq1dJpliWdEqYSkLNywQfxDppsylt5qYVFolPAtyUyvK8jL+2pM0gDE9M9LppJvyaTV1CmTooUxulZrpsbNbo4NFrRQlSebPdrQRRKHNzqqPuyzVsoOjmwtNcHEOmLvpHWEPhGt16NmyjF5yppySBBF2cigiA9GSNm8mZdjTNl5pahOpAhL3NSWjdQejNXZT9irLHKHvG6KDpj3ZAekQoC9AGFSvr1duBaLD3DVFrtGLTgreVvUvtTFYOAPjiC9EmSxGf1Idxy3gnkAXME4BTHL5oXUYr0QsoF9MGUnjZ6u2IqUThulXL53zTT6sz7Wum5Qebv4Wlz+rk+gJTGZl95o00dy1+Hxg9yzNBEb6jOBsC+xKO7qPnyW3BpvxSOsWjsJ7299E/lFnMrmdaEwZx3tKsyLqUsUPAo2psbVFg5zGsKrcTBiBnfBkwLxSANHkPDe7z+wI8gZ9iKVoWaCK7zb7L8eDudJxOiDvMGH275qt+GJMXV5zoZWnayeNZlyMBoVea7KulnW49tZy8+/c2ZOoM1XTSB3c3N4um9XI5khfY5ejLWc8PSq4QE0rgZeGCBm4owAHFtLKzkAYqvmnVFh5H450ON/t5QQSVBPyUk4+hpV7VU3+XYlP2twXCmAEJhLo1Od0JBIsgBJghTAMOS8GD4r4QIMcdOOw4TczfQ0PcUG4ecD2Z8L7KsnZiujZ4Oodb7vPEV1lvjmpiraIX7F340A3nDdi6pwPNDdGLOuhiT9LFdX8oe54v3mgbTbv2FyK9bk7EXhK38wImO3rF9lOU8FgTHzGHo7oMeuGpJ8cN6YupCTuemTWJp70GVd4WJz6Y1IjQosQyPA5RXJKXj3kI336V0dLUZtFrxs8EwZB3jbzn2YHv2/OLk5282Oc7L/DMDvX9uU6KjjhZYuRK4hym0lsFX224SxFhdUI7WQ0i3YdwjBvaOg3Qv/+iKHrJ+RWc0f3wIifGVoA0rx0y1lCUMPlVfeKZEW6iqMdQiW22WjY5drNmJ168VZqJAbZItAIVlOqEvO2iLsMnRPIAaKPOj1haJBSvBlBf4CkmB902iWK4fidQ1hT95guc30ZySbzUaYbVZkz2VON/ICVa0i+UDuA4hYop8iG5vmX+TTt9eTMsZES/+dr2dzLSsMGY14+K65FF+H6rMTedipgNkbxH+vvnZ0+CeoWXX2v18mutXn59FCWVDQEsfQfXB/VYDsFzOg7gB3wcxGjZBcziIkw1jsumJe7bIfbv3qe9W8RmithMEZtrYjNDbK6IzTSxuSE2M8RmhthME2vIoy0Udto8hfGrQ+N9lIeHU7S8PZziMSKtaLxJs2L5aaEVnclR9BRQl07ut1PBHTSVh+hRKsMKeVLVYgPpCrLBpKpsKFVpNpCuPocGVZF2mK5SjzKqXLtMbp8IPPGLo89N9JlEn2n0mUWfefS5jT6L6LOMPnfR5z76rKLPQ/RZR59N9NlGn5/RZxd99tHnEH2O0ecx+jxFn1/R5zn6/J5GimTka4GMDpvokESHlFWQ5NFhy7pHyuiwczWQNKyE5DM6dEoVyWGMDsfocGKtJefo8E1jzS3FfhPtk2gvL27zaL+lGVw9vd3vo30V7Q/Rvo72NLO30f4z2nfRvo/2Q7Qfo/0x2p+i/Ve0P0f7b4iHoG+yCpdbM/XroqleokZGoUZGqUdGYUZGqUZGoUdGaUZGYUZGYUZGYUaGzD/zSSfDOM55HPP4i/DIkweeDDo14GS00QQxjeN5KewiYuOWdjFYnF7txKz9xBut8MezE+Lu1jTE5Jd4JaGC2TaAbyl2ntbPJxwn6SZlUAvZXgAIYvAzX4yu1PMbtUeTvSrzdapKTeiKMUUbQTgFV5JEgn1EHnrexfnYRbmLj5xDw7gFiyBQG0mVHfnCVH9cpNpF4iCWvBy8Fr0fl+h1MAROClR21k41RDny9omfKlBVpg+g6bWwL1RAsKV1lsEKnTL0R9C8Ep0YqYhAca0KdUur9DcuFpbjL5bVbpVQt1so6ZTxckHtdg2dcbybUi20nNXKF0o7EWXtMmajxTnVs7BfKNJUNRcbN1Q0d4hcK/PUQMEST9FOE8xK+/HXpZ0aN1jWKdoZr8srxo9K6/bvhTL7QIFBMSu/OzSkoWb14A0QJJnBBIbJHMipwIsd+PKI9brdhW5xeWx7Y8EtWGgI+xWkYIIdxa2Rhe7iAwWmhHnXSbUW2OCqvhQ7T+uv5+E4FWqhSk3kGnewovDUbk0kiDb6caSJEMhoLbm4i7qHyVKy6yCyVP76eMyiukTQxxJBuoizZX+BoI8Fgjw83tK0RFZ+jayL6/sCifkVEueLjtcAVicPNIN9qRFsDLvjuRU5R/xxEbFXqTbiUCXM0ec/Qn9lyMVd4vfYlqttazd2LTGJkTeUyy8lAt5YN1pRJzLvjX0jFlWiWDVhiGRso0QjxM2yGqULkUKn6A9EERhWQei6M2uvjUvI59Qu+MSF6Fs8FrqSM7xboXtSbqTC/8EhGHah4n1wNB7pQAvPg60DyU2kMJlQRz+SJoO395okkbmeQ/0JIvwTyPqPRdqfEO1/UGK3jM9OBdxqFZJWVcmoxuGeUYurfCmrXRO31PGsRhXCeThvv+J6sLvVWprwebp1jRJpzOkydfIKsOq1hd1Z3STR/1CTtPykfnQ/w+mcy7sCGtGrXCTwTRXUKfEddx+9KQFPHPqr1HyqoXHY4h3WOM6hTPp1UkDMXshbNDIEeUgVuNdQcdaFtDv8JH4TGK0qpRnWPs7bEL2qzE6YuobS0oQayAoQCFOcGWgoRtJogf4Gtgc0uBcokMFrF5UgHDdPJ+W6lNqHCF7B+QgWo4Opw0RcAQpiYgckLYIoTKykXbqgkrRLsaG04QJchplUmC/TsBQbShum4TJMCI9XhQuRqhaUElldYOV9Wy3MAQY+L/siO0PoWss6C4ZJzYUoKFdeWwjLnSJYEUAPVHecTyiFUhDMEzkeor06UzuHKMEYK8RZKRGiJhQzWys4FAuPMqzpyAO59fI3NPpkmAi+HOozrcL+ya0bizIN6AJYhQkDhGhlkTTca/ELLq+sTuStPdcupL+A26Y/QLEOUl3Tysp0W9Flbt/nTyuBgfHSqP6ljQLYi9APuoeVg1k85t3He6RiAQQkG6fr75LFHqDIGkfcD6GZ23q3tRztl2M3Kwf0am+nbjAnKtAxtNycG1i4rR9tbKbDhD7Yo/C/GfdtqNUf/Fa38PtdQTNwzpLuBbqQARYgGBXstJq3GNUjvC4+96yCY6TpcDxsuqyCmpe+bk6HWPSbZxP/BUls3V7sZl605vcFQ8Hitv3A982UAV7aJlnNqozrhtnTzAvgV561krZpWi2Jq/Mzj0yMyM8UsKGiwlp78xX9o0R++Ar6A3fvcTWUqAJdIF3Wsl6lXdP2EEOBpXfq/fE06/fE5JVKRlGX2A4iHu3QCQ+tH81obbt51XRy7NINZnRPy9qkkrykOvrSHcQLtZa6WQLaRP0IBwsOzRD3e+xrWIMpeM0N1SBaPR5F6FYU38dp2bBJiczovG+K+BtiBUrXfZyOScaKcep9gee8xBanzZc24JEU5QrS53fwQiiAKgV1nkXPu6wbqVWyg3pAK6Rwd4BynLjry0n2F/r/CyjqhWGpA8sRsJEdFku4bTM8INLAZ2rSM9uooS4OrpQlLrAdhWWKCpqrX3P0hVfVP6PXUwneAKL70SvLL0B65ZUF3tAEWcYPLNMi7g5xdI8W4edAqE6osoEtMX6NJT7DrNthqj+5g0xshujN3kH05MWzINh1GfEIJ89oOOu2UORZIbuxLZkH6mMWx7kdaUJC49RZO4w1P7UaWfNJV/Kr9njsRlZ3cyCOCK1ZJyIM3OCZVrfFI9Jy02H00yaqhSL3u3hbDtReotQ9bmGhBVnFIJkD27LnN/NqZS8yannY6IpeP0dcvb52EDp5pdWlaNrodV+LrZA2PplR/neJHvoWUi39WBpBQBl1HPKgX29LvMqgGjdOAhuFgCyjUAWbUGDm6CFLvu1508xNVzeQBVIbavHgiROUr0xhvRFKMAG3h7GH5ZZK2594qNGa2jTGQw+NivpBHD+WO9NMnugRxwrd3KCxLjE3yZbunHCn1IPFD+GxAiH/m7tVi65YJn20u7fcvyz3b8v9x3I/WO7HyZ1tsxpqqvCAn3759bna+F0lESof4tZ6XKH0mFXnmzDAHRsfgYimCpYaw2BOxDideZKQ8Ri9uYue76PnX9Hz7+j5T/T84LL+05tZOYDYKHNGpgw2mN5mOcAmsJcnGWZu4tnqvWRNAyZQvSWSyBc8T4OHgBIOMNFlremkLrPVxIjbmivbkhVd1EmBN5jcM6DmHIaSep6B8xxzXEwTMDHEMtSJCUSHxCS9gdIrMRaF+SLurDRQ0cBwLP+uajWvsrG7SbObCiLAzTiAh0xXNqcgp18Ih6ok7Ae2aHepsa2ITp/ijqdZZRaGolbHphrirau5npZba2p8suZE3hXiOGuCQXVYECbMRvHH0igqIbFJ5sNOUtscNktpS+gvQChuzdkMPTpbL2UXwIG40+KXU1c+Qm2I8Y/1ASA8NLqhlmfL1kOnPEfvyWlpwPzCS0adjbyEJHgdhFFGvFKPpaXGmgDNk7yqdxNLhjWKWrEqB1aV9yUKTg6ldtKMWNbJWIPpyPC+UzhlmhDvmiTBISfrKIQWaXFpFS/8ZlYNmi4eqVf0K3Cga14Y9EY/EKNYVa7nBo+PyB/d0dK7yYoSbIbwtmBEzGKtuVvFEwiMHMYD7E7eIs+5wscAV+icOeB9r+a/edjxhipmdist+5h7b4Lx0LRFOSaFrKEYrQneIVWlWDTEozFt4E71AsVjKSEjD/ldgbfseKi3wlO18/QcLcNR780pVqfzcAwdjWUMccVln5qFeMV0L8ZbDC7IoG1It3WOfJzgtGPWsjLW8+TS4PIxl7zXgWW8VJdM9xjD5efUkVioXW95y9oZOvC7B8iq4DAwwYZNWNFZpu62OBtaH/J71gAJKeSD/XYH87XmtaQI9mKgRjo/EFFrhjaxw88r5ORUTgSLmI+sZdaiRQnmcQ0In3hdhDDCu1aYmkaEA8eL1jKroP2KhsKAxyAdvyKiftclBU0p/YBKLkrs2mB4rgTnghnfDKdi3ETPK9DBy8Mhbu164P2faD6406z0tOsiAswLEh17R2sVGqRoKtaBwC0al9WmiQeowRPB+7EzB/l3+xJTFCTJ+72Y2aPgSVs3JpGBtxG7uMVgyERWeXp/GadUPOqHVEPH7Mz7Gb1ujcTst+MBOq2gOcTvJ9NSO7soUC/a9Ma4K9tpLxDnGTSoJmXfN12vzwgoElynCVXAxi/7dR9KTULa/6B6nPUYd1LFQCtfPO3o7ogTWvGgo35cdrB7xI9Wj5k816epDqMqh9LXx0IsR5TQ7nBeie/UlTwaxWcfJ1CHS2CGQP/aRyM6TAivS21RR5w24fOiuFrMVl8aZh6utv8GYvIb7kPMAal5U6CcIFFSLy97HahAhBK6FQ8u2Kgy9ALhxJncndADZuPeYBMdUrTHjI9lqqxiDjTocDZx07cN2BdjK/QPF62pZxGKWk69CCNDiXYv8yjFOwJAztNT54AnEEH7pg66E6K7AQbCVkFGT69Qdphdo/ZRkpqtJMJJoDHb0Kp1QlFtWcvOXRHqtpCdfCq/TdQUKqLsfmU96IqwMn33My2/VgEwhVHHsHVQFCDuAoX7GaySkg9lpqXeddxUsMUO5lTEMpSSEF6M5+JnA+4HNUn8OFNNoU0HcfJpx6L9fryqAY3Ia+0JTnczm3i39ux69ck2TWfRT0xhzgdGt4M+M82bqmTTrFOcmbSOMONuRajBoSGMd3FoCrUzymDLqoJpPL/qfw4vy78yTu4OBX3obqTWNTdlp3HuETgvbzyp5dGe9i/B2fh+gGoBRHqAY6p5RTxCLPrJBXYh9sE3/2wldK4QlTVlQWYWl1lqoyjAe6aNDqd2d26gJ4jHDyyVmJE2E8daQ1xz3ROVb5ejH/R7zv8OXMKgM22XIbXxzMtQUBpw5OGY8VNhbfAdprUnoIWKnqiSE7oLANZB3mQFTzEH1hmfMUBundhP8MFzfOs9qqPgweT9OFf+MMXhbI/4U727CALFlxBcUArlk3AV7HYS1LpsKd6q2B/Ylbd7z0+offghtZYUWvgtuI/yKpjTmK4eCL85F2JvsUPfxMNq4eEPbqcaPCdq+TlRw8+JWnDhDZ4TtfycqJHnRA0/Jyqt50RPGpllG3HC+wm8HeP9ZLzM3X8Cb8d4PwXvJ+Pd23hn1AYz+EYG/8EZfHMG/4EMvpHBf3AG35LBN2cw2O+g1G6+TDNtmGKmFethsr/wYJlmeJh0Bsuh98wQ3ByTGDuxzcelXZxPwiHzzBWBovOMdhNtiMJbffKwWIZb81LqCpyyWvNThD8GtwSO5mZWblgtxQ2Pm0BqVkL4JNoVLgMtZCNx9qyqZndLR1gdoDoxSspCsXyko+RUFisoaeokhv4hh+udQ8vUwkKQmoOYA/EsdQUGr5Spo1TMS7osyRw4J25w+DG0moUntujmWpIHi0G6CnzLqqSy9K9yMKqBm3ZC8Fe5GuVW1rneHIrDb3JYxWC9YAs93IKYzQcfszQf8/nA6qSXcOVz3X1zXIbphnG4S7OCYc6LuN4HAU9QcHADK44X8FwBYuVdZmcUsswpfJnVoMpIu9bkONmO0bpUlAiPJTFn30FMB7LUH1rIcLAkldo7KrXRj0pttJKcRiVgkoUe1TRj8xyW4qqF2Kabrt5KIjXNjLSFsZkuWoqZRMn4th+VnnwrSoCt+xqjaC2gKvaA/gG+kmVhy94+Tsb+hb2ySHnA/uHzdD5tqxv/aDr/psBSLJeKTFWsQ9lnad9FJSMPbcXQ2VAp+5G2aJaRSJrFieIsXPqsoAbISINbISwCbweItJZWn/8wqdS/0+Lfjn28STf9mqH+GPXud42+8JP0fyxF/Vqlo6W8Rx+bK9lMZdQI1k3sFuzGqRfrJaJnOC3luZ/k0pSlPNy3fNqm80p+EOAJ41lxGx/Y7QNyM2KLsWlVReotVzhOic/balzfbM2KLqB5dxKAD8dZZC1oUnLIW4JROof1LsbW9vSmdRCHIo11vOlh98ya3izKNfO0jZlNWzIzGoyeWWFzrFXIWPYVuP6ZzaF/ZsaMnwPmIf8s2ZP8s2Q38jloaPfPsnXePwumNINpwxAfvp1Hatqygjo+NFvHlx71Hg+nhh665O6j7O6eVcrd0f89fvH5Tb/0f49ffH7Bgc89u/j7hxz0f49ffH7Bgc89u/j7Gy587tnF31/s5O+9uOXngVz0f49ffH7Bgc89u/j7Gy587tnF31/s5O+9uOXnD5z43LOLv7/Yyd97ccvPb3bz917c8vNLPPJzr3zq95Gc9H+PX3x+wYHPPbv4+xsufO7Zxd9f7OTvvbjl5w+c+Nyzi7+/2Mnfe3HLz2928/de3PLzSzzyc6986vcBbnzu2cXfX+zk77245ec3u/l7L275+SUe+blXPvX7hz38vRe3/PwSj/zcK5/6/S0++blXPvX7S3nV7732a8cTuen/Hr/4/IIDn3t28fc3XPjcs4u/v9jJ33txy88fOPG5Zxd/f7GTv/filp/f7Obvvbjl55d45Ode+dTvA9z43LOLv7/Yyd97ccvPb3bz917c8vNLPPJzr3zq9w97+Hsvbvn5JR75uVc+9ftbfPJzr3zq95fyqt977deOR3jwuWcXf3+xk7/34paf3+zm77245eeXeOTnXvnU7x/28Pde3PLzSzzyc6986ve3+OTnXvnU7y/lVb/32q8dD+zj77245eeXeOTnXvnU72/xyc+98qnfX8qrfu+1Xzv+iFd+7pVP/f5SXvV7r/3a8Vv51e+99mvHLx2gHfcmRLs8O/aOhdGwQdXPSxZRl2w3XzK2+gPohbX1Ou5ZkSZL99dW2durq2zYNnJgrxGwsjyHenLNOU+4l8w826/tF41d27Ezk9ILSeexr1M1ziNfHPu3w6BO/v1ia+PMfqUtWnMWBbDEt4SbuV3ohy/hbgxE0RhG9R/XuzRj4v35nFIVHO5Q8zSB2JCFa/edW9DWtQviI9H99CfYLsDaRqbrwHGKGDqfoiw15Q+WaWrV65u9TuCFzg1WWymCeObmr0HE7CjHzi5YgHnOVwszZWQrZfdOESaJvfmJwUyAzcDOjiJm1BnQ+amVHzLBzku9TMIc72LJ5miXSZhVmF2jFzKHwmYFNWmzZT3zlVZQcOtF25NZAWmBsTvaxyknMwlFa2uitUHNaIqOEzZz1lymGat0mHamzjGzjnb3tvposWmXI5Ue5KuJvQhtRoHNJQYSSrzeD1t38zBIoR9J+pk9GBt00zvKEE2eoWYR3VzawQejZ/MRHwSJJuvZ1n020dnAgZuGYLhKNMMdXoX4FmsDnfoLNuxtgPlUXXTNuC0gXTCzGq/jlIkq8072EvviwjJKnFKvjDEz9omqobhr8cboH8uYmYbVcTiJ4zBL4xH71btOgXqadCZZwAbHEhU/yWcRlU+0UySDziPModpqLRWkhUiFtgDzcRFON8wcyGh98Jica5CXCJSD15+Q6EAuE6mVVlyl0QG8UodBjvkK5LV6DPHY12Gv1uUPSfVgr9Tnz2j1QK/UqT87hWm8Stom46XoSm1fbzgh52qd/aAGFEVXW/WHNXSF8KgSnUs/Jf9n9XCZsuhg5Xm9BX/WEfg6CuqzpUC80lihPyXcJDiE0fysO/2g8X7aD37WMwObfq38R8QTxNatSJjNGltzTmzNS9vxXQQLMxdu4kWGxQPbxtWh6cM2W8P8x30e5Bwsm7aODbKlQigD4z8to2FC/MvVBSZJqTTq1a5a26WcAjDXTz6ZTid/yNq2dSFsGeTs22agDT2MUokhuFvrhsuzLmJfbHlRViLnuspO4kRYJHBasdCr8b1IOi9QunUpyg48UD84aAbKtbgaNvfkwSyiwZUl3tywbZZL9qMcaG22xTYa9Rfw1zOwyZnfhVq31oFLUf9OG7sgywSy2w0Q6Zo/1vFqKjEoglCPE5ZAFtLS8qBswV6NavaLMOqsLM9qPCo0o0GZ0xPjTwfaCI8QF5Cq0GIB8njWrqRjDHkNVUlaftqkDljvY+kD4++16MVdAtMUSvKjb4usUxINs+wLWHBW4scK3ijJUH4rA6tfO0B+bLOpys8x8zKkrHJZLr0KEVO+kEiBIRqlaaSs/eMCRzHn/xb6/5enjvF/ayWM/6uzFLpG/8uovIOnczS5WpGKf9Blyw4t3oOxmVbtdO0Or+1dnBJ8WNs7QxWkOuoU4miYcq0KRg+pK3H+pNW3RU+eSA1FOWI9DwvCFhulusMY0rXAnKwepR9h5ShhYJFAoJvEPTG40VLXrvynsbdrViJXm5YWQNNqqfTvtCw+OUZdH1SntmvYMcv7GjZn7dnu1WI9/umXGDJ5mh2gqXDzKuPJ2ag/q0GJrMUglxqnfXTna1tSTf0+jYuep08jk+UqYGKZ3h6msbWVOVcHkLWO+w9tDYhiyNxHDM4SrSBm6oWa01D+WKOVKEuTNGInqg8nfZkrkVK6Pybz0ErKfwqQhR6SD2c9r6o13gmzpWtC0MGosoblUDbUU9Z5WbNRZZScDa1NQdol0uJZGrC0pRahm4xZWCMt5SgHg1hewzOdEvtjCqiX91RjMb9JHPMcIh1dk47J4DHBNRtBZrFZMwe0ejEGk6omE7HvwzagmnCqW2rlMin4cRUelUEdRJOe6/iAB+HhV9zhJq3mTeo+xTGGZc0BZEhJ3wwsoKDDjs3op4McZ+c/MHpz3v6+eboE3XuQN+c11ZunUG+k1iQWNj5naXTnCS9OuwYd4hqg94Udl24RN+Uk4/jbn841XyNHvIrDVue9zvsMJb192dJ4GIiiqH8f+FvfxN15egdBU5Yp5jsfhk5eGeTG/zDWbFhcb8QMP7JjcrVQnm2Xb0r85iaW2dQSu5xiXgn1BCbkepTcUj8eq0YMKI4H2xwoEzVZh5+E1ozx0gkLD3feQAxWEgNoW89TTfkcixoyNXtPdrGUETZjCNc/W1dIJYoNuVkhamNsWQpr46FQNt+JF4Iqa+cwfxYd1yyDm1Qj81FYCjl8KoyCjtWTi6kSIM6fddw4gSpyKyN4gs5XeqqvMFPw7lhmfOeGj971qLGWRltm1V3TJgLsPWUCMc6VZQY62rRlCyUcSdfstCVI83AlwEso1owr8kBz8BfMnkFyV0XYM+w6Zb1zuBlQ4cqDzXZC43RgG3BrraBCL6vTaxm9HuDJneD8mHB+GC4Eeoc+NKvCSoimIpS1NRnrKcyajfU8dsygDQC2c+VxqFlbvOf4E1kTs1JazAr1MmUJWmFQBztqv8hXQNHdATIEF7MI0b0N0K3noUUyZ021mJ9jMMq2VucwrE7VBhvNDr8LZzWl465eUrWb2uBCQg3Dah5ndeYukxkDd7JWh76Nqbtu9bNJNGdjUjsTqyVDXhu/9VDrxaxS82Q6amOLvdt4dDgmfeFAXWOrDkoBkFGukEgQ70B+lnoCdfAoxhWVqRhvtemc41kAdXNWV5hWSYUBjx7nlaRi9PIcWNz01LaIVtgyd7DYS543Dp/sBxWKy9OHHlZDrfXqOdGCnb0FUTLLUjWtKB3C9IrlXKkG0U3L3aCK29ZP/mRoU4pTWCjIUOcEGlDb+gJvpppuIcIqOZdN98bYTEOxNvwwzUs8iR+z2amDVZwQzu0EaY29tDlAvShWaK1QiA2odjHeLvjBDntu2kddGU9cuN9yipPzduRBi7yKudj7x6sq/M49//YySp2Voy8PJTgEPROwj5W3brsxq4cZmapwHDxpJfCOv5em4ruW+vVXCa2BtN0SaKJwOjWfH+9Pz0qtqViiLOBQSv8k37xor6hJGVyGBZWVBsXID2gtLFC8hXdVi9HzdnaVQrl6oqT9f5XHuDLVympYbC1S0xGk/VZGv5VyDjBDAF5yV2GCymKOJAg2oYKhZLVTnNrJwRKEuIhg/g7sGsJ5ih9mECr2TxL8DXp9jPSXmajDXSeneBohc3xOpHXBxBp0+WUx7xTA2y801WVQFyXilskJQviXXur0g7OSbCTcOcMLXXQtJbSux/y89Eym55Mg3jnQEpofEuqCXyDvJ4UM5nC1TgNlcPrdYv4OWLh0AUQXMwMb4fV5aJIz1ZI6FZp6E5Y1vNP5PGUP/nn/8HMqnJxeL5PVuu1s9ZIJ5sWBeQpXhr0kvQcq1Fmy1IJU0/TLGkR0Tk7C6N2rpIlDcacHmzkzqN4UmxvsmIoN3ZzlFMhDOItdTPiD7vSjFMy0QeWE0Ak+VHvsKJdjsMCWWQnZk46H9mz0NfJj4qw3w3iaE5026kfiXLL0KtwFfO4cewGhC+hhvETVJUou5n4xx5lIg5d4Fh/I+RqOIIw+4FTookedyIg7mM3svRJfmAKm+IldFN7LgZ1FTulCxwUBDBfAGBfedneL/IVGdQVKY5q3s4UgEOmm8zjhWVI/3k3tt88s+QzATe90slliJ1bpCJWX7LjrhY1tQ5e6q59H6A21kmp5VroKnoUOa1J41rl3Tpe0RGi0QIwhVAcz5vvNPMiDM3nLxKugPqxzho0ohFEbfyWIE9AIMEmu37blkBR506nn7kOGW05cytMOtFf61t2TCwCztuG6qY17krKevfd/0DoAXCUQikjvflDtO9X9oNEJcOvvUwEruU0wriyQJaJxBc8CqBFpE4lLjj5krLkISjhdRLoGTLHd460HR1GBWWffbanzqcY0lVPIo67DR6UoGH1bGeDQ4gLO9YAFkDY0b8Irt+76hF+lEgVPmGXkBsGy11tnAb0KO3Xa4BVUwahIfe+3dA317m+gQ9Jcm7LGfYs+nYzSBWSPsu2exvIVrsfh8DSf4OyUzABO/W3SNLQVxfq+zSdWXSWEyjU7Npjf8XlW9pglk9unQMzd9NhFYu2HMXaI/QroCqT1xMAO/y03LkpNp4Bq6UsncBLddIKtdzl2uBDgQFqkXoG0SPXoUvL8duDC+8CytabE3aQvJXTH5AKXBti+dzeCLkqCQd1ZzI1yLRvderWMPwWNcjn33f4t+dvslvzNo+ltTtOdenfpKM6UfuxqtnbDjLHIc9D2ZCBCmYpk9eONMU1h/A9F9iURWgOj8toHmG6MTau6dXlQKvs8K39+qGMJyxMV8ENDxgBfvTQS6yWxCM+qqmz7bBJEmcd41je9FPNwS7prds1oLGi4Xbmfp3L0ndy56k48TSB30xvgH732XnpluzdPGbL5i+B/Fl4EZ8uveZuFfP658Jp3CKP6XkI1e4118WWhHMPND5DnT8aUKEZQwPyHj9c0jtmuZ/ExmbMulobDtPDPNO1YuPy4u0tlmAmQ34Wl3xcL8V+pGR9ZHq7uRZH8JXDnfb2jgFEJ4DrPBzWvIaugWtCgLlBHyKJnK7wzJvosvedqLrWN6lkhYcOy3lS7GK00DDrzaHPUV0rsUudkjnVE97LgNXq1zGwESj0Ja5jHFwvV4ECK4P8FfGYqFcgrOF3oOxa98Iax+6p34l50i27+LpGjO8HpLh4vtRDtqlcIQSx3yDm3tEiD2neEo60H2GEIeSq/kNpi6xZSX8B8of6UGtQr1ehCXahNF3C5Ul24ScTKhxNt885rZVcm6wcJrnSe2cPNy1DXulLggedluGv9QgNe6B4G17VeYnBdz+5qtdm34Be0rvxbia9W8pX01+r+SnJnituIqSzDz5iQaxXEksnXZ57LFTVlwkcnVyapq/XGNF2dTa9Vn0PUlal3ObM2LjsN1y/Xgwd2oYge5HIpPMCJRFuuOHU39u5uPQhikXYByt/hB4EuT3KyDI1apaukqdW+1A/mhcsPxJ7WCyNOGmd4wnk/qtvzOjvxaQ8HPqlAy1yUqkMphGiWtwgPVIlezlx7mKuYNmXE+HdNDVOWQd3aUysRN1pWYL9ZJNao2RbeTIPr9loAXtDavQDNQtwafGrAMLRlpu0S2MNlCh+uUvVwlZAfTYN8WouzmUnnyv+wda78YCIPoPiXjeJHS4lBYg6GfrYKzNP9XXbWkf5fZmilvKCb3d9p7WcbujdbWbsPXs7BLZB66ugq0gafx7pJPWVgs8R+PFXQZtPo933M7PLEIOp6UQ7xfyi/TD2tPlSDy6gLmVTp2poUrElw0ooVemt3P/VzfnGoJe9xlN7AKpl19W6/OumjDUpmPz3po1fXa9k6Vy3OlH5N8shfUOpfpWwYzUqq1UtPNo11gH6q6R/gzQ7mmmSwD+a0V5/JjW3guY/O5G3hOZCJd9+izOO93e0MQJu6xrx9YMH5W/dw1Jydzc5IJ4U58lrdNnamB0/fToZhroAFTKa56RcBVEtpYW1YbMd1MQ4lRhjohjZ2vBjlGyBYU2yVkSa27j2V/JWNdryw0Y7XUoRF47pXNsDbrumzjnpfLDYt44wcxXlb4rctmkoMh/f9aEwOsqXXnpZBpHFfZjXGsN3QjZmqG4aPOzYZO7Zl2sAiMa7mb7/ZZvwehjRhOLhtKjzev0sP2YCA41glYk0TD0UpoX7Yb7WWHIn4Z+Ha5tmgB6V/ev7P/I1ZdeXIc3olqcdzf0ED03KSq5o0g6msFfLniSBfKx0BJlz+4XHQZynarRv7voRkEbYSWq5ZMTvHcouBRYOgqpsj/8J4r4RsSh3W68mhwpjLEr5SnQnOmHeO6uJwxCuoydBmn+Em0Q7RppwnC99io9rYAVfXmtZjdTaLW/UJ9fQSl7dtPPaT+eNtRVRWNIiSVRK35cB62aHfehV/j9FuM+7P0Y6WwyzaKdBolzabrol2Z9p9Esh3QeNmoPj0mwpB/uxQ7eJoV34XMKZTwgL5SjwEs8u6I6HYx3sCrXZjWu4o6eHcVzCiuqvjvqDopibEbbNvduTpyqGnn75qjpRmOHYYJbtxTyA5xdFPkXX0beBsCUlf0HDacSIqdYn8iEcGwQR2KKN9PCCIRlvGVjsphlLKKeKZRlRvnY/vzpRXqaajCWSHh4Ts0HEmIC8HKT2RHQsxbZkQPbQrHQeYeV9RMBu6hJE8U/QkHlMEKJJf1E3K1BgFN0bBjVHoxiikMQppjEI3RiGNUajGKLj+S7sxkFQao+DGKHRjFJqiQhqjQGMUqjEKaYxCGqNQjVGgMQppjIIbo0BjFNQYBTdGwYlUyQo0RsGNsS+jEo1RWI1RUGMUU01/Wo1RUGMU88YodN0XfmMU3BiFboxCN0bhNEYxa4zCawxtydQdIe67RLFOZzdaID6MQb3j4OP1KGttk8iRNkTBFeDijx1A/UBsekov4X6eSjyG1pgEb6d9oufRXvr95fT7a+m/L6f/vpY+rlrqJdnBevKYaRUa0YEjXYxHJfIhixrrQvVQOnpSnbR2TKIQQTHOvFaxWBZ+XUpgMrDhALwFpPGUqEsDNhZEcUK63cpJo7coJ6KalXHInYNCqy44FQEKAUVPryEdKnb8SLfMSz404iCd9rjQs9UM2J9irXAo+54F3SZNG1o3qjyOHt2OykEe3LFMfTgJ8uC28eHgA6owDzKNqxlKFeZBZmXmwXGIXwvN6EFxiN+f48HPVIJmPWTwM5UgD24oMvrzIHWgB1timvJAVZg/auPWB5Qgf0aKx8oHVGEeJC2kLhgCPJjah6nnMPveB+IQD6rxYJoZROujaedYOh9NN8fTl7PuJkF+O8V+7+AQD2r0cY1zTLlPeR6opWJWS8Ucqp3VZRuqy1m/bgL9mtYRHObdtDR8s9wfVl6kn0MFc6o8O8B6vZeZF+mlTbpzOzTbjoY4QcxHaiB+kfJAr/cjF9PO+q4bdZHqWdp59HKNBZrHi/R7bHyYdX4VNqOykf1Ckc0ptKOWqQskncUup876YjkxR/qryb44lKiz/TxfL26xJXE8s9iWErlMcSDxLPZC6vhC2sDsqw/zZ+mcmAv5XWqcK21Dq9ElYodLabe01SwvlFXHL2NIdxeSc+SlPjmfs+fRgfT1uME+fym9G72cnsq2nJojL6Q9X0p7vpj2FI/LaRH5JGcW+7iM3g8lVrv3Vn56WqxoxEfv9MsBtJxIBAobXvHcSSw4h8wBLuIIdpswSNIcNmJhsS6VLHZMu0bsOaHLqaWdwq7K6hK6250cN00RE1hwBvHirNpje349ngJslBYO5zFvxNooQ+EiKSWy5l30mHexUr9TZ7wfiJ4M5sdD0+EUUR0w6TS326zpttzxnNmujvINPlt8cN6XZ/R/pCU0/4ZrQDh8eziquI/yA1w1bTxzgLdwfBf4djEU2cScirwjYjliz98tBOLyTzipP5AzwZcz3hHnnyf02TLkF4cxeEE4t/RHK3J+yuDvom1DjjNFxjB2PNAmpI5ZFysX6RxHm01Eu6DNlr5F9LHJOhxRxUmcZoczxe+iD3w2KaCSNEqLKM7OURzn0WYffQw4BaatfrwH3J5QbEJYCguyACQAKe+9HbHnmE8rhNw0/uL4m2LiIt5uY5D8bSf65kRVtDlEm9oK39YR3oVQXBvROIypKpKOimmnhSc+czVsGU0fJT3XxsBfdg3Uo6LNKdqco803JY5PWYUHLQMyR6Lvb6qRKG6iZ3+TV8XUk6vyezI4Hj2rE8WmU348wW9qKL3kJzTU+WifUTYthu+5Igys8YKq6oBPh09Pn6SAa4PPgE+CT42IM1zbqhkwAuH+xidFFD6bHafh5IKkxZfTb7cn2teXUZZRn6F8+jhKxygtozQmFwVmUdpQsiQc/v29BI/jgpExU4Rgzyji8xxOsF8I/1oI34bDb6cZKzl3ZVWViZl2MpypRrttgWPTDGeoWbTPcCwa7bIq2h+ifR3tGjnOpFbZ99EOZ4QFn2visLDI5FCzQunUmWPW3wAIp4+ZOmqNdoemxlzaFqtxH+3OtIzj4LRsMBb5yGRXlcNAzTw71hQAHeJoSsVJw0Azr+lZROOrllIOxCk1uHaMp+Y1HKfuGed4vdSXQO7iEnwtP+Jqmyq26XpUCYORWrms3AjpmyanRG6UR1Q4UpGj3wKIQKKENYey7wOIFqOztKShXLLiIghd9PL0iJsbd0R4nqbUEJowc0UQiizOLU0iMa1O8liMy9/gcqKP7qfrcMottkxTKb8C964f5Q7iXnTBKMW0lE2RsdogyGPp+u8aWt62KEJ1QBlrmgBvBdScbGadKJcWSWR1rodctGoJqk0cm6FUbdHFva+fbzHWwji9El1b9kpWc5PIkNcwqrsXo3G5al2xqQx/25dsmgh14TqHfgxBy6AinuEUn/vVOBtSgRhba2dAjXcoxuhZYakzsDGonxba9Ub12EsHMoSBd0C0HlitmMWNzcujYJBLWtNHXd7Kkt7jk/JbbnruadHtqeloVE3Lmxyps1oudULK2t8okYwmxDyqIAXAiv1ERXpKq31mX49uifxU62IVj04msNGdvkPXuqv48vnu1NxkB9G3xFpvjO+2HzI1NdPKMPGbUyn78kvpElJaVJ3HibTAgNEdK2hd1FKQamCZClQFNLqrTjc66uaZalerYeLqvTNPZ5XEB8pHxZJHeiOx2GwEXbWFGbsYUPv4eKa1K5Hk4psMUZv4fyxdaea5JnqmJvRepnGtj9O8iuEKvoX0RHYUNW0olZm6aAcgJeA+1UMK7RgPOvQWQm7QnO+y5neinS8ehrN9QcDnIKz6SmyBay9NEJhiY/UeXW9rMKgMXdlXUmmFccJfeR14URu8IzJ7EWIRhase8wImD9DIfjBme+g/Cw5nNrBFQmYJXgMJ/Dk/2e1pQUvFZHzWZsSQvCZVmefRKw0ckZPAZdapIWYfwhmveJVDY/IVEkGvA1jS6HVfl3nGkBsW40Cj1jKZEBpiyN946zQBULsIfAzvhjHHIvbR1zHVwyukFeMU3mYcrJRFBqWkxv8GvWyv1OuI7AIV+NrT7ukVchxEBhWngAcafgmAqKpKKEk5xYNMngppjrchr2184rAPDqM9d1sJ08XVO+Dh2tCN9Z4wwYBk2myj112MJya0q+cX7Qlx2pRhdgYdvBuequ91E9PunxFXQHFjZSBBdTZM+cdcJx9SJwecxb3SDj5rUdgDZUFbulfaIBPabqTBNJXlgDZ8azrsJF9pPNKoMpGJNOFQbrk+QC0ktVhw3bSGRxoS2HVBo5dagb8uYJtlxCLsIN5ANdo0gweQUMM5qE4xSo2vnTk0Tr/Z6bZcTBYQXKARcVEJ1dRo7FF1WqmODofar5tqzLxEtD+vWQI25t5RkiOPylMJNYF5daYqjmfN4WLgwcJCoW44VU7PnYISv26Jk/NrAoZDonJT0qpV4mWSWysF8G7PVI3oZW7CjvucQ8Qx81tCghyooeGOmQTCHLi0YykZF1AH0gI0YLS7mFVgEgi83RMH+VWaCQYVsubFEipko7U88v/geSZa863umjXH0oITrXFasq6ybR+tMzCk0QcLQK7lHTXNPusEHE60LhMoqOWZaK11ZkRrnpOidYuHy9H6hCli3bMFtbWrXoNyLlk5cFZDvcbYARvV4NqaxdY8i61lZly3XXlEZ1vHW/Su9QEvREClTv9BXZ0CepqSoGVwvaUOtOqpPalfrdE8OI1Y016OCGu4nElBPBRR1jSEvwSvLdYUqAZoqkRRO7yupRJ0lBlnWQ+cOdHCBaT9AxW/zvqsIhTUAjidWqcd5SjPw9SMulYbA1UWHlfQ6ZhmXPkraGjtOQ2aaMN6fWvOc9OVPZp1TawSVSbPxFTUapN1jLYhMgpWxKm2C2updL4ER3XikTlV2hdQyIZrXXM/oCn7Iz6jVKhrzLQod7JHVsSDrWUiX5+yuAVA2qw4HfTDMpacJklqHBSYaKP5cc0zPEVgYkcMlSKXgb5WCy7a3ZvXqUNyX8qx8Vljkl9jkqf2bnJMK9Gap/v1IauYzpIr45QR10FdFr1tRBvREEBbuovCui+TPYQTTQMMUBS5ZjlFit2X3ON69KMzN3SGniMywqgGzES8pKCCuG62PLetk/jIbSI1L4sM9QoUhNcVIpoQ1SBSVpB1rua8NWbWNadrWYEzZ8kLCgpJ09BHSawa16R0KyIHYpnUULy+rIms7cjDDmKPKHM8SKOx9uk1+PeOKUXBZd2h7g2eHPqhmyZFU9ECYI09vSytsSwh4wxzQ1dznWCJWR+hzuOM7SBavMUw2sQp42aDNFT8LI0+qFetc9WL0zMqqoO7HLhAB7ChoJGXoTWvO+uTTE5UZooauTWIZ6jibYZBjNritWbNaw0PwpSnMWiwlkEWlxUf02BISPvw2kMTECfM44QtoKgG8BYhisjQDQUvr0hrXpHWOc8cqFxecNY589roQLLarHm1IXwoPU7R0Q15uuxjGn95mZT8bhZASTxWaYceLIvTmtejtdDM6xENOJ5TCpXjgTqNWpDWh5ItlYh2b6LpsOkalhYDURgt2CagXdOOtkJUBwNGOUjkdWkty85aLSprtVRQAcdBjDeYTRiEjjB1gGFPihhH91oHxdAoVZSdUuzUKJnNTkerHedkDGeCtKJUItnujR2rgo867RJpedk4/U8B/Z8si/8/RV+GZVuHIoyGjKgTQflyhsoBVWRZ0updlldKr1HXqc0gGEn0mVfZZb1aO9OUenKjtjK7uI0x90P0esR0zhJnVMS4m+RR7cqFYTJrawRmkLXliq8eWbPQd9Y1IbNWQWtW7nFGED4cJzs7efrkJfBDbVtpwQThOMu8VcVqiVnlU9C0VSie5jY0j9T0Nhtie/942V7WUqxVkGWKluOt5JfzvwxjoXG3pm5yP46VTCgrjZ6+J2KNaGfnHWXcXoys+NnLBQCr+lc8f94Sl7H9LppxRf2U32cFt5Kbkm8ly69ow1NPnPGIi2sxPWMNhorioYqhzlT/V6qjrZAUZ1mDF8h8qRvGtI2V0nfIp2hT5KNRpWWHoj7Pqj7NmRKxzrHakQtUJppBGlrYWYEAzSkSzvUiExLfaC4AOiAcINMQB5hHOE5Xt6toyKpMLi747WKeZfb5np5hZg0DRnpzono6U9OU3WA/+r0wHd0e4n7UzY8NP61KWVfbEHZqNhXnvTx5Ze4uLzFdttJrSlpzUK2O4GZMrGf0Ie6SGB7tHomB0G5a3TPtbqIP+ttTmi397wl+S/97gt3S/57giFn42BMMcf0fPcF8Az/BfAM3wXwDL8F8AyfBfDe4SYw+UvofCCY1NAwjLigpBL8wkoHdaANjGdFHHUdxybeZfN/4UVDqDf239F8Qhk0JfpHclHZD/y39FxmuY8nN7Aq56b+l/4OHSwlzx7jRND5KfzY1ciYo/HfBlCdKdZIYCSb+/mjSUt1BGdF0IbePhxj9/ca00LybVzgOvpmH3/4k8WYpsUnj9b9nBesHp6WMgTMEjQJZuwe/T/9/T/t/oad9HC2AZ+sq4mlquBYvi+qt2z2e/rZb7Bu8U9s0bXOgHaO5X6aiU8mjj5zqk6qViayo1ajxqHaij1308Rl9fFH7kIc2OB84FenISz7ycLdp0DEgLkEl+cjon2rioxmhcJP82D9DwCGjT9xx36Kokv6PlBtFbAmipNQzzasfdW3WLC3KWp4zWC7qewrWHvm96UtIKdVlRpur5Cah3yRKC/opoEZxn42DSqc9HcVVBKrwpAfyH6K0pZ82ShldOgABbQrSFo62MBgF+F2ABa9y84+ihr9rRIofxG2jdyFOUil3ArxUwRCvysY9aFZZv+us31XWMe1Xond0SvrJaEdNHvr5iN6b6P0kwQ0gyDtSCMetSwogX0b/Z3KX0SMWIFxt65kA1Ej1SS3eqIpSVUFcvBSC6+3GrvVUQ1plzxR4SmDEiNjVduNUscG7j1uCHWu7ak3j2LTowFIHqsY2NaYxST653Tp2+kR1FoUmEZBEtYihi5OrljtnvbhyKeV2Rr1pLU6mim3Xwbq5obajVZ+Gy3q8QdMlcL/H/Gw08RhA2oYb68hlvTcboa3WtSU+w7JtcVLGroIV2kkg36aq+EY9cd2q+UY86r5GgZddr5i7rbpsUYlpWkotnHiTxB4oxMrUpLPF8ZuOOMSaLZpNPqMsB7tSlg1wxzTkP5pGfssOUwcc+IzsOmDO2GKqIW+MsJiCmkPEcwwF1tEzRMcmsfaIdr35PsqL6Fm/CaHJpqL/77MHu51ATjQB0n+DA9NC7qKUvtghejlto5cv+t/g05+il+L7O3rbRq9t9PqNyJ6/xfcQvX1TWEs+iiDPd/RSUwRBRC8tfek/BWD0yqmi1xP9D+xrU0oTvQw1IhADjF+M6fsb8fT/iSBO2f7kfKIfN4OSMpw4BJcRoCU8p2WamiOH+rd6hHRetOUQiOxR2GGEVKATdjtd5H3zpRTP2WqUZTLKMjXKMpl2MxnlmYy5TKYMGVqZDMBczYiZnhEzPb4zPcYyGVGZ5ERcjOQFh+QGF+cHB+cIB+cJB3LFL+cLB+dMDpU3glTujFPyZxRCAZxMw5SY5td902WxXfHNLqMqb1fEhrybZuKdYYGdYck7w4J3hiV2hgV2hiXvDAvZGRa8MyywZyn4KLrg8+NCDpNLnFYWB9r+VxGffReEguq8HJoE80DMOBsikHY5RY1j+6JvMxy8AVEd1+Jkk0PxoAwj4rnjhrYrRF3bZXinjOeOFcH1w5ieodIVz0KJiyt4t0lbZLgJlApC01gBY3kxzLkWOS63j8gCVpoIAY5sceifFNMGb6oZfRkebWi+S7NuS0XCbg23FrSX2zAz86ROgigGL+Yd66IfvK+bB/M+bxa8zptQ8EeZh4CpbULAaK0QOLffPJz3jjVN4EXZKu0Duh50uXQZMhqL1Eu23Ety7iVb9JIcvWTLvSSXXpJzL5FSRtmFpE/uEF3LEF2rIbqWIbqWIbqWIboWXkaG6FqG6Icaoms9RNd6iK71EF2rRc8M0bUeomszRNd6iK71EF3rIbpWQ3Sth+haD9EPM0TX0xBdT0N0PQ3RtR6iT7ORSa4DbVPK3ZiNpakWyWykSVLgZ8eV8y7rXWRvuK4T1PUGzZRwM22kmTbcTBvu0jyYNzyYNzKYEwzmjQzmjQzmTc9sCgbzhgfzRg/mDQ/mjR7Mm2kwb7zBvJHBTPvNpMuIBpruQWYmv/1YyjXlJvtKIDhMg31DAxo/8YD7IMZRQrHshscw4W/PUdpBtB0HKFsIIrPiENgoPFGJJ00xGwi+JFzoLqvKLeOSSSQxk8jGmkQ2ZhLZmEmEag24zLCXsbwwBmRIR3LdnqFdcm6XjNsFUmSY/b8oEZJmkjST4YNhv3TCZCmy2sU1jeRz9Jlnm05cxOfQaPiMqRAVfBS0GwllX5ErHrcj1dtnn7UDa8ePPhtqU3bUtN+RoDRLxKU1lxTb6JFmwOgJT3DLQynaUuJNWZVGb4nujmZNdzekFEZNFxG/Rfte2u7GvecfPH/t+QvPf/D8EM8f2dV5MSfxs0eXiDaoK3TbVZeVFP8Yt3GM+bwbi5HGaN0SF/wUdyMsPOKuK3oeaLcyUp95zPpxP46083/K9jElbep+jJ4aYkke93ifET1Tjydc/xC7TWlo3aBUzzXR+1RuY3IhdH8eJbbsRghiP+7LroletmMXE6KXQ5YNDeX+cmJUjyr8bQAB+7EbvzPA/9Ogaz1lGVPQjVRnz8TgRo99XAKKMhvKkhI+lR2X4gmDKHohCMoUiagDcsrokVHTwKVyNZxnEUNDwiNVDJZdygy+TUy1B/C2pPRM4zPn9A+l2JSIoQrs4pTq57ksgWcz9j3rT6CYDiaTMigz4LptaYShQvA4FJoYOL8M9fmcEVf+uKFqoLphoUlgouyYMpDa0oaA3aDhHwo4cJmJTtBE/Aa1AzQ9PNf9meCfOLKGmBgxzZz9U0bN8YJyP0ttP57jOBUETyNR+tjhCgnoqEs9jS012PO4GTnpgSu32dLIfZRGuj5aYbdeLo2OaLcjpoQTTwlHnhJOmBKOmBJOPCUcZUo48pRwHDikkhhamCsCPmECyhDAGyG4TjR1cAh4BA5griAz+NgFlOKSJT761w1I+k+Q9D+YpP9kkswMgNeneKkdcyegHXtzpDZIKPAQPSuGIo3+ScYN/TyWIyYMNcSIfexxJEPtMOJoYIhLOKOPQ1ailSG80Sgb19TdVvGh7dEVqUlHLJgYHfSzIT/9bzd4plVRGH/bnEBzBs2jf2iKoqlqT/+0n3nc43PAZ4vPwN5xVUVPlDAFCvrPD4TgwBGH6IkcCf3vEXAwxaKwyW0593bwYaUKnxiXceytIJY7Ji5mSoq63eNzwGeLD42g6B8NGlugqJmeqe2jJ3K01Az1kQOOmJ8f9/AcVwd07sf2RLEnjj1FT+TYw3NSsftVUxyYJPzQJvZx80nkJ9FTGj1J5lSVT5gtUPFnzAnRU4s5kRLvqba0ZGn0NESPFdUfDbSGknyhrWQ7RyOP/hs0VYH6fWrpn/pP3zG5J8J8lLxAg3ZdH0xpLHzpiC575C47cpc9YhSNGEVHHiujjKKRR9E4cIiMolGNoqMeRaMZRUc1ikY9io5mFI1mFI1mFI1qFP0Hj6J/gaT/ZJL+xST9J0j6F0j6T874X0LSv2RgC6ssSfV4", + "28JKDVtMoIlfdFYW2SqBCnhIn8tJBy11tFK3YpKUmbS3tMxz3IbSshwPnGaTbcuaRTnezhDEykfUX0XcwNuJZniOIDYtr0riod6QIu4OFFk0ldiEpzmOpS/e1FF4fOA0A8Sl2EVrJbFGb8ygwhxPFb3lLA2BfUX0xnrrcXPWZ/wiJHo7NClxb5QH9utUw3F/oCRQGXZihBDWwmYFxBAvEp+hKI4NTGKvBmqJeWkVT/m2KeXeUdTkIz8hp8VTIX5ugW1O9Ca6RqM3qo2GmETACGm6RCynpi7He0M3bTwb7P+Y/5P62ZxRFSthlWNWQop8mIEm9Hk1Cvp0VLMa8u5Y8FRXBqTu3qhA5O8prxTvdPiyp8m52JVoM4QzJ/LQWixEJNa+34lx7UY5RHlLiZs9KvrW6CE9U6FdxMbGe1M5SXOQRl2BxSB6WLLGbed2xDPKrdLjyBl3uulAEB71oUjHphoHE2rEZmhtbUa5Hy7YeBLxflnGWhG5d6yMcB6RTgta08LilSAh5rU7y/EiLCRTq28IxVT1pxgIgZIW3oE12tdpFO8a6tr9qoJoNA0BvK8VcplZVW1A7Q6WvcPWUPVlr3HjnLdjDfWtTPUt4tWhY3EKuj2X02PDksj+it6oyqgvD9H7V/QevbfRazyFv46NDm2s0AyO19MYvVL3NQnfITn0Fa1p40jUTOFvQCKhjRWamWgLRQfIt7Mf8to6+fw8k5/g3qAQmvA17Jx9RR+41nmPp/B34JfQxgrNTLSFogPk+3kKea3dLEL4bawXkUnIa3G4ijJMcgC5i/nwg7q2WnrWppcr/TW30DtYmx812uvxJ13OJ+qHXSH9YTf7YUd+Hf6LVRnGmqb/ZtMv99bXeo5zsXteQFPUPx9LGqeH8bUOV9q/O5u8FtXfVNffjWxV7Opn0+BfN3Wgi27/a1ldmhtf9//mLHsZ63Zr6n+h8q1u4vSzS7PW62FbzrvpX/f74utnHXaJRDPDK2oWU4aTFahx9v1dV8Erp2CrzAC//902/ZtOmfxfYgO+v3/SWoExfG0A198/nCMYuUZ9HW//f6H23/q/Yi5CgyFA+Xfxg3H1lzxLUvz9uL+Gs+tiaYpmPsr+kry6C/eiv0TT/x+oue6/eSDtlgbs4szzE6yf/0ew7nZLg/7HDK7Nil/B5qK60i5v53+btNev5cqasZjzSjn/n6jqX/ox3yclfKnK6AUcwUt9LtvoJTlD3qKnwO22wSaQvIcS8hOAqc5d9LLZUCYvB4p9OTfRSwtf8TWSk7axlC6OXr5HRkW+NB2RBJ/tFjD1GQmHMXrB726H1N8gpAV4cSAQlPrliCR9cSYXaPgmrDskZ9S7HYVvkWoH1SwvJ4pJR8AjVYWg5Ix9LZUApSq+kBkPWaKNESMASl9eaLXJUPwNUvGD8LIfjexNjEfF0VtBv2mM19LipkK+7pV7R/+JhvkGUB9H7/DhtUcd4600zRcxz7a0LICNiCHcTL0Dv3DkMRZ7nlWo1ZEBHASdURNQq1IxaHNOJULIW0FuPAJmYaZzvBrKiCUgceVE3oQQZJsmgsr8bJeN0R9LN4R66x/b+hFi67wAb7VqyoJ+3054v1zj9AyHNAh6h+uwwXfPoYcte+Sb43PEZwAs40gLfv0FZ4VPx4H41PztDeS3cSX47BiGv2fOj/3bLWfHWXMAEnF8Gb2D7pLJP8lPW4JuFuMjqksQXTLNJUimT07/R/qnGnwnOKK2xDU4TmVg9wEnNSC0xPIrEN/qN6H/HSLxOQN1yeQBM/KAr2QZQmpxUFZD2xc6CdMnP+haGwp6j0FfDPpirnEiMQaJ9KGu8Xak/0E6FZGIm3pyUK966xAQg0T6qG739q1+0Sl3iMTnDOySK1EJ5MgTsTELSb7hzSEIpN+3U9NIw8OzQdA7XPwwkWhk95Y98s3xOeIzAJZxpPiu2Vnh03EgPjV/ewP5bVwJPjuG4e+Z82M/TUfIjrPmACTi+FEafpSKlZ92BN0jBDuJ6hFEj0zzCJLpk9P/EbeVBENwRC0lhKOi/w4BIwilT68gvtVvQv87ROJzBuqRyQNm5AHfyEKkb41q+IbrVeiTn1bqFaKoqFWuVKlTrlKu/JzrFFWK2uEKRX2iOlGbqEyuS1SlQHyr34RrkSsRdYgqlBpEBaL+UH0s+EqziZCY8ZgXEuWnlTFPQ55HPA943TdlxAuVPOQx4jF4ebxjuGO0Y7BjrPNQx0gXiG/1m/Ag5zGOIY4RLgM8wkDZChUHHuMY4tH7FkjrLcxgZl30Wyay39NE9ttVDvLbzGlUSRUOqaMEOlXQ8R7kjiaDtDVN+vzD9wwvuPp+Yb1JL3mMu1d8Uvhfm4ahRwZmd9rcNFiXyP07LWkHLFen/xgDGC98w/IP37C84IblH9ywvPANyz9yw/IP37D4xB5Yv1t0azSd+Uqys0NFo/bZVZOtAn3FrWy6wAVVYb46Z/MWjBrJTeBG+Wqzm8GnRYJ8SliFmkeJhPnKsG0ta24CN8pLB5V60OyFy0M3mRPjq9XOxgFvnc7Ur9xUToyXChIDIowPy7CBxCGAec2JwgUokpvVoBW11FI0zyw0FGKWcouX8prXDZ6VsiyNUWrnJg3E+21SwfBAGkjrxCzReo2AS4B+i9V+C9XLNQu9gAtVy1Ez5fZ4OusnMaEh6KwKQSM0CH0IQh+CY0demzaBoWNi/FYql1I5Mf6IludSy1mGADQ1Y0WztQ69m2t3PH4fiDVPILmKN+s0s4utnyjBrR20n3nBQ9GMPV6Fu+Gw8XyEDUUYIIKZov0lZZLjHq/+oZgKWh/LaEc83A5GcViyEfjE8M2O618CZFpJtNquFmpIm310p1GriGcdMavGk99xOGQ2kc/BvgNw38UMToL8oY0NkDeaOWiW7/c838AyMGSO+RVWB+MmC0L4WGbEDwHah34O1gfh+jlcYPgO87oYQnUxr9pQzfZzsD4Ep0bHwqCZDzetVN5PMIXPTZPoPjj133LquRfGQZZbWkthvC4+jAejPJl3E2+K/TUbuyHOwPa+Qc/2Wyl7FGxyIEi4VntAtXcTcNm70BZkF9NM9nYAv6246L4oeedGzOL4hRdZX5TZmTehA3hsympN6fBLTO4nEjBH/snbqRpbaWIpkarlL+8l37Ezpe0Bdrf4tGbf2inmX+3cqDzINWa+lFnk/Qk6l9c0ztfYbIHRbjlz2ku8Nwfe1GE3xXtH7DMrELVnDj9jAQvmZ2smb1A7RuLF3zeohQGFwvbvbeDsBlRDHx9kCxgfmJDmSKHQ+XGIHqaG46fg++azhg7rbBj3EPQp++ihRqUSNQ8Tj/wg+hifwDo/TPoZHzy9erNOVJSsm4KPHM5lvWLlMHUMdZHsKqHVPdZhykmBn6OE4Je8nfJ2eMf0RZzVDSSitbpZxg7JvY9wKM0a80BRPuAFCu5QVG6jZsuPtCQcFrIOxVtEhKKtPEPRM8ICQELiIm1LRC1Rc5mMUCzeltraV6NU9HylnrXRD0sNirF8zOppP5RSUDxOYP1HW9b5pdwztY5bo/xyFsVFuBDdDxD8YVUwXDusZmlfscV2CKsFzTFlW2jE13ri2eKKa2gqBHAZR1lfRoF4fynBttMzcMVB/tL07UEhwIeBHt+KtnQepAn2F5IxHrpAAit8KYUy2tXIFBJM7IAEjWzlUME9s0TmI0SAD+NTHM9JjUcfZpzDHH2YYwAmaGTXTxcG8nGd/XTnGcykZXbS6/oQ3oHYEGF7ctpaXciY3IIlu/2CwbugPborVvGcnMRs8k/QXoKfb/VpZV75Rvym4LBtQJ4lgiSEAHxbIZata0WqaIryW/cS4BJOLM9hJLxw+zanfOD5OHAMH2rp00VDgVehw9jzqhk7qB8LYptiF2j7HMuug+qeuTnGMIiH5/Ovyvj5l2X8/MmI+PzZiIBxtAGiov6YnsL9FMRvL6SxY3w7gD+h+fgzmo9+vz7O+++xpJ1EM0AK3l+o3KiZXT7iGC7MVYH4axiutv+PUvjlo2C/XBzkMwT+ZJ3N52Zw5e7h1XwVTBqflUDIjCWHPm9hbtyt43iIEqgwTw741PhAjV94GeYYt4aQAKE+5XXPBzV+VVjhCynyhRT5YoqtMUA6hfhU+tF+1xCAKpyuWsy6WyC2W0zRL6ToF1MMCymGeSODj8WrxfGQV9nXKk7wdDT6kE3bh2iFtYxgL1kfjashwOtNweHKK8LrIx4KNEwOjm+0EsZh6mFlPZlgCvAn9WV7tfU1e7WJPlL3U1oRuzammqA0YmhWqeF3AmfsxMXlbHNlOcsvTGT5xUns2FRxO1I9zqZoK2IhTbOUpllOMy6lGedptkK5VjkfLN0CTJgdvIhp/yNM9Q8w1T/C1P0AU/cjTP0PMPU/wlTYVpgNt8+KrvEUW6wR0/yoxiIPvMyd08uFuf5zaZzvIyDZqU2bnCTeiJHipCijbIMXrt5w4CCfJeVDcI8rlTDfiOuF0TJeHC3aEpafjxW+kKJcSFEuphgXUsw3k7Bz1zYVbGLM2HInyt8U1tuK5sk6Xp383aEdE54Andks6+2O8x2CSFXF8qJxcfNyEXLBsvV1rP1fYO3iQy+GCnTBLrOz/c/YWXVDuMRVzKITdRDPbGO0O53r+SmOusroE5jo8ZkBP3JmGnl7aMp0lswKn5mTPmxmuwEdGIR1rZ0sGS5PoiKPis8FBsJMREGr7LPYrC0nvayqQMp0UrlMQuFQqvT/VTAKMXYZVjRF2yWj7YdQ5pOFruizjQpzmHiISt6gx1EBhRQxpThEt/2Zhnm5quNtV063HSICtq1XKe1pjtDf8Kbnqyhl83QSXcR9XA9T7L6JsqKJ0q38ClBcjy6OREHt1C/e6udwQEcBOwYVk6rfmv5b5d6o3wP9d/Rf4ReOHiZfWIrolFViZofKWkbFGBVZxBJXbUPc3JnPUm/uovI+Kn9F5W9Np1LZmpli3dYNVJaxjtaVY4oTb4JZx5Kopx1YqZoK7KMMIOqd8lBEJYu+FBrMRPTRq0qi1PO2VZxkeOZrQrqx1draAFsPUO+h1MwW8ba/aePJHjur5GDdm2jlj0QF7BBw5mf+EgBtmrXow4y1bswD4qEBhAG+RUvlB0Q4Y6PnUim9pJb8qBCoIgvREyoqHDPW/PhJ/i/6z0EPaMlwPzhu2EpkqimmHHYQ4NHr86CzZwJB4dQkyJiVWVY4/0bWYsz4g624xujgeRzIg4h9abMuL7+csGczGuu0i2GNFYIlogIZCuu1nkylHnUK4dsnyj6N3rUhJHhu+3js4r4YunjldvoPGkFxBzFhM7oSVn+SsEaUZIw2x4Y2D9TDumgPK7TRHip+IlZzU0JFCo2XTUxwuGuH0pWt+kUrbxLl2elAqF1BVUJycoOqZAeqczMomFTDwoCmcm/UL7S4AAV0tlArb46w2VlAkEwIB0xFES+T7U81FUCDx4s9+OIoL6ERLh9ZddxUzKaL6ipqqihnk685FTNvWI1cDLFmJD5Sox64E08NBME0iCUrndTimeTQ4n9DqfZ0rZhmR+I/tjFNg5Zs257vV4CzYpx7xonn3dEeOEVtwV5w7hlnZtq5GqOK2qyiaq6omiuq0upYQsUQaucITQIFrKtNOXMMtD/zDbVVdLseTN2oDhiKssNA/YGpr0ymH3hS3pZE3cs2bldK6edLEkML1Av6u1qYpDVoQaNedIhedjEtSc1h6sxnt8nPUCF4jqF0267GtRh7OEEZLxtL4Wr8YNMcqMYPMbUg1bjmanxemtZ6FfBtTWsfxeDNaQc1z23UhHVWkxarOynUrHWUWZLV1WY8g9Ei8SzlgQ0MGEjhi/w1BfOFYVs1LQRtqSdDXaf2P4tRt1MJA9hnWAnMdrj4ncrwvoVcND6QbE7hiaFNFPfh0TtRSyghFkDhlP4dws1E9nsl4spQ4Aoh53dckL+zRPOacKzPO5amfrSawOhZkrmDJ45sxNB99EZsvY22UY4LWEIg/eZRGx90VMMnBTGKONoX3Ww3ogFO6U4VHbZKYe2HrQVWqVjVHqVGLre17eaCKp+rZM19ba3IJVc6ILViuQ9RHDvLAbAfk9bZG61/ziTMRf/cR6+V8Crlsx+s4+1GNN05QJzzjdIsqfF9KG1yKpyVzxWiAlZS2Rpeb3c0+lisgGu/jamhuSXfkyyJ92jrc9xRU1MsxZgBgKWVehD1LdbfhUWWFv2Etst7HhHUyWDfBFar+lMMDdmZKF0WXdybVU/czB4HpF0q42izUm7NJpgAxSpMXuoIRdx20P2lBhvWEDsUK4wTUJvkg4U5ZbcNxWPVxG8s92FiNDareAsJZDN2e409Nbg2PJjVEERVQj3NqMcxBw+0NkGHKOvMjtLTSPHF6pBV5Z74Riilgo8my4F4zxjqQ4j3LGnVRmbE77ZZmw22uWvGus8wWxZtRp2cFWXG+46l3sjfcAPCOC8BoZlrbQ/RCmhj2rBgGWsxBaQY6NWIRz3vJ5713xkVnsmBJJoT1iO6Kw35NNuibvDz3pY99YCCZijZFTBWEwgUHdBkLev9/q9MyYx5KLshxsF5NmRQXt1n9Q0+tNWhbksTxyQCFtcrvOxJwViksD6dgg1JwUM8yboCkD4+RU/+NoljuiwdWxwMsKKPJ80nxrRTibFCokeWxPZBixvQlzv1i065hwP5PU0JrPIXf69odU4AGKEyVZlu5PcW2iOnrRSeMo141vQay6Om/fSoin/ZINV7zC9J5SHVTscUEoNlwbzFSnUk5LngT9WjLf1wa6N+DwoAnB0/surU26wjXl718jaLAP+4LButglpj+8jLYsyzCbS3E8I/3hCA7XLCmxLelIbnH30GzAqU98SqgkudpZJoRDjwYrt+UxNTygbriXmrYMh9If2Bqjv6YzXpC5r0RaxuoklfxBglmvQFTfrKTfoiTfrCTeq8FeOdRBXFwllubDYzNrZk4fN7OnW1A22iqUVzmk3R5fOd+kUXzTFp4uFbjsaCQ6Lov49FlTL81JFnw0BhDg8EFUkbrZyYIahffm62DeunUlENMWTFJ3Xj4kAjTlR1xSVxMrZoEW9XRR2mxiwwnR6mbdzQCkTTlkgZvU0DAP6b+6j6Y5JC8JOP4qAsFV26wu7hFkmOZTbYVz2wBMHiB3BwQGFCChNkhenArQ7aqoDahNQ6KNEhiQ4wiBKNp9chvcZzNnjOjZZuM0JyEjDogEEHGMSDRlwbNCpgowM2KqDVAa0OMFhajSXXIbkKOOiAgwow5GpqOx3QqYBKB1Qq4KgDjirA5Kuz1X7YnojBetBAVYtpDJ27tAplsB0gbDGDQOWDAimxSmXMVK9jAJ7ZfMRBMdAAJ8ZlQ9MXod2gxjY9FuVn1T2xcn5ILC32B1jjIMpgR6ShjBqcqGW08pSE6ZztzeUzzqRkncGISzHiMLBSjLjcrDx8boCpz2aYcUJEDEBMs1w5RmWMV28079MQgror8MBUwDElWt75+aN5uwRrR0M58ctvbER8Fmrlpc8C3oXdvgUn2bS0JzY4h4G2EzT5ZlTVEBrOaXRiGx8ITb5HHNRBnhhvS7kKNknCE82IrTdedEHYd4vd9QbrQDpPEbpV38QdnhvEVYuNf2yOFG/6pKBZPmGd1VPNCzROLLxrw6TK6rJf5VGir3ICty6JutyZLILH3+dVH+30Wwo5VBab7Tvlg4I0YmlD6OpQIHWnULBdkCZyRIKihK+hGjfMENnASrLwW03mwNgG8lTQnq+0bpqoc7H1xEt1Y4vr9rC8gm1ZvMq2wds6mJuGFdMqMwf4XZR0oeLq6FCcaqEu2utMUcObmNhI2M+CQedktO80Jqoy6i/hGOpsupbG0qRnvliuqnHjlmu5r5NKyVm3Yqk860rqPl9BkIp32LlkdeKreQ/iS6gSJOcwjdMJ/Qb93OuMHGb2YlL9LLaaL3Tbg9Nf81mRQ+ON9mdFzA/fEusJguqA5Bgbq+fJqLzdEoezD98OyC1kUFzme6VN/wSEG6it+ovxqTRl57xqkYLO7jm0mSZOcaKVhW0PwgTnh7I0CDcxy3ghhFNx5z4QJ4M5nwpiKjtGOXgr4pxzmJYocVQIMxNHYZ68oGoedHCDmPUqaubBihnw5xjzhQGtCw1fHhyZT9vOALG0YJ1BOw/0T709H+g/1RDbChDVDB22cn4OpznVOEgKLXZ7NAXWRmK7S1gogo0dLHG81aLBnA74EA9F0z0xRCOM4OB7AjhOHSJaT9CcNS8HLY72UuotWDm3QL7jkA7gWDV2QJfis2U8KX83DETE4FqpH4Uc4yaqjBuXFMpZT04icgomKo3HILGXTmL/+TYL35i/54x/YP8Kv/LFys2OemQ9qryQZ3ieMh5WJVUi9JaOtXJam4fEGL5PefOQ8OYhxeYhweYh5c1DIpuHRE6P1fnYDrtyPiBrxHBPc0MbpnNzg8WaEja0e5KIkiPGm5iX3jgjF8eLt7w5x7RIqDSZ4EmItaNlOymhxjPO4hvuJ0+NzlKMMsmJ1Vbbi4rtQ7ZKHW7F6vhOfAUfU5mzukKO1kqFoNBHXLGc6NkneepXHXpJVurcTx2vqURyOidgcqynjUf9f+y92XLrvI8ves+n8AukypmzshI71GCJ1uRosGN379117vf7Xx/8AFKiZNlZw9fd/31OVyWWxJkgCAIgCRTOEUTSu04yvabMFew0gNI3LaWJT4rEc0slDRBFovY8Sd34ikk9qt42t2+EzeypH7WvPbSZpKS0BzHirP5yrKwMeq2ihVhmiwhY02h9Q1llZmLL2/RKStt9m84OlxlXoR3cbAu2NpOoKZ1m1uuP51VMO60lN8O4esfrhduI3myYDucknhJpylUsZ7wXOIfTqqWui5gvj06yUSjJPgeVw/81MRBE6fbxgYNSxH3FKawp0+p66C8nV5E7kV6bT2tjnuYWzYWbhoCBMyXwm0mrwHNfz5HWIEQgM/53uiWK/mJXEeeDk1Z1fTQl1GpRLPdbwkhDa4o7j2Gm6Rtu6yOa9aJaiHGOlHmeVu/Vyi9pl3f2+OEKVnkdU0FvOP5n7DONdEL5mSnpI1v7XKEJ7tAKGpx+QhZvCDaEeJ9qFZCgLEc8uBS1SkzhDkG5IO7AOCh1902llL27rOHiT4DCOKidltEPgwuwuhy9GQefBTAAx0EExnEAEeVxAK1icZbOVbiLx6HT77bRtFCMgj6rSZMwgpP60jMATIG0H6645JD5+rGoNTElQ7/l0zWLv14cWvL4CkbRFNHBcDpDRl43uV6YhirgjeuqLpSRbvM71Rmnk/jQiydmkATM/gt+VPqsu7OcgZczGOUMRjmDOD3LG3l5o1HeaJSX+naeOfYyx6PMsZ95/ef1rts/htP+j+G0+ws4Rcc/bnD551lxtfsPWxyeZdx4GTejjJtxV7FDk19BifVMvN+qdZdfGaF1dJbZB8dqe3V8V3V9FZqr7C8GOSES8Ueote7+HDuS6o8nUVVhn6YryylN2o4gViLdn0EEsGQyCRxmP66Tgj59ACXV2dAmXnwyqijxKwoiOCTQDfEY0xpKr4RyVEI5aipayPqv+AqBNrJA6OKkZ7tz8tI+W8Xm4MI2CGL4wlrBJ2eEo5ISnEjwmg+JeeFGwg0zRLyLVR1KOAJwCf7dlsfuPL2MqQ23ah//jvNi2gQXmR9t5tqmYD3KynmaSCdFy0omYc5lLLVwDA3tQUOPQK9HoO8m+T589KviK6Wujt21WKuEuTxeq/3V0jNTE5t+WlTXcGJz1obRkh5f6dzHCCgfY6CQwNnhCMlJE6PkWsJsRKGzpqtp0vq5/x8/d8+QHN0E9GHAAVzSuGn/4TXt36bt/l9e5OmgD5Po/+1HTwHy735kdbXkM2COYuMrBf/7GJgOfhZw3wCiB+mo+P8zRHgV/Z8LI2Clj42uG7M4X7RTr4h0lDH9zaHbxsRfTwhPqqf1nYqZZFc6ezpv8kfg2jBTpTmvEnsnZ2EzzTBXmmFmmtH+SzRDp1easZ0pf3ul/O1MN7lYO+TpL5T/gWQX4TKXIbuWY/uLtTZxXP5WIdmvFax1dKn3s52JXPp/Fis+Wp3+VjtOLv1cpDbl7w1Rkl7Lks1l2fxrzNJPJyH/5xTfC+AzK5f5i56TuP6f0FqU+i8wJkVPUv7Zufq7pI1liH+Bdlwj4f8EvI//IgsmJGxRUMKjrt3jnZk4H7Vr8HcJRy34pRy4IOEuZkW6KHSrp3JknummngvfaOrCNJALmS1hGvhd0y7zVoCHz3GeQI39AB4dP4BR2w8YQWrE247LHrirSaVmWqmZVmqmlZpLlZpppe1/Q6UD5zSpdDutdDutdDutdHup0u20p/2y+Muw+RwtMb+SY7wo+SmxAFyF5i/X0S8lf17EsAxM23kGcI9U/1cO1i+QFz/58b8Bi80FQcwX5UQOG4Vk50HFTL54kmgqe/lx5qxIc16LKWbyndXS/lfUMsz/89RTqceP284kn0gw37TlTOL5rvipcDNKf97A7FfaPBZsfh+gU0nnnxikiZQzipoINKO4iXDyXS1n0owfm81k2Pzz+DgRTL7FGJf6T1vAAsV3tUzkg/+k2T1l//8JbD7j5f+JQrfnbU/j35no5pzlG5V2/K+gc9vpAsGZfO0e03k/YCDzZ2nNWdr219NOSK4ftT0rdyB63yemgi8mzs5K7icT8H3U4LPMEz5nFDWg3C/05vgbEPVlFJE5/GgrcYyCRN4YD4tOv1Ulz0lpPWn8zXweUb2SM5vJOQz078nN3qD/Zo3pH8JmO+ZYf13Cz36lxrmMjVtkf7Ol0R/ma9JretQZxUA2FzajLMjOt7h1X9VMnGt/faVvM3HzWH9NCpnH2ms5LmG6lyab5rmA41eEj0vYfa2W9Ld7fwGjrwlF2be1nGWZx+Jr7Yp+O8cUc304ocX+91nAVB7LJhLcGFX9CB8XZztQf9POMfN5tsRnM0EzzHxf5pyYczFumC7fCx3j5U2Plyzhpy6syNvzFXmSODsLmbRsFHW6HDUcZeR1Ezo8D/bNmFgsK7HmwpcBdrhR2KYxpVHPcifAD+oPzrmN0FqnptBpRwiaa52qIDL2lYLKVO20VruuUDU9P9l8TINolyLXx9QsDvpG69ykaDgH6OaGkmmN40veR6K1H9W/tx1O77nwj88O509h86Wm5g01+hVyfXGMqjm6sHWPaiDoBzjgnWmka5FJ8xV46XPhOj0R1C9gkhlLu96AHEbp6pmsA7EpLjDcF2ZSczZtmvOZ9DFpdi+PeW38uiDpDxkmlKi5RLK8GXVN/r+iemgvUtxfbH57Xl87pX3Hy2qCuQr2l8ZkWq5PiEZAvFh3tr0E42yoZkrLT6MiujPN+AUlxvdLZ3ax1V/XiOoczMZ435yjdnORS9lehO8V0I8beBlBPc7mcmHdpG3dxeJ6tckvg65XilwEXXOmGu4ltIuV1JMW1xfHeHuFonz9CTKYX8SBj3G6S0Tte0y5Sj5mVBzXVJFz6bfjiXdBO3KVMl/V3lyh9xfxdnt5Uhx/m35O4Hkxy0Si/xXsDs7nw8WNsO1vLy/mYqmXs/zBIja3ZE5x8HsJofhW7vBWy+8ljvNV6rI0dRH20XeFTPSjc0kuQ9Tf3p0v3vxJqcX3wzFHVadJZibgL5RyTgEuEOML6vrL7cl+p8lXSN7HhFH41WG9poK/PN8vlvQr7Z6fZBcbPabb3+DG5TSb+Dt+diBbF9tyCTTXdmkuip1uFl4rS8/Qhl/Bj3PFBOSdzgpIJQk5Ya4XHQzW6maRVbWG50p4b7PmOaaHy34nNYtiUz1XhvPv0/NRVQoVb3SuDDw/FkZCWVOd3U0Rme7slDcJiyzzzRR8dgUsRmsrKzlCXnTi4hZP+tF51eHq9bLGsIgLhKmUHJgG7kBxUr++IfGx0KV9oyGheruABM8SAupBL3o5U59OEDwXqEktcc3SmkSK8zhsq/rmVoV3KrxX4YMKH1X4pMJnFb6o8IcKb5cqulXRnYruVfSgokcVPanlro4bkuWlGHQPP8MdBPGWVZkorpz9Ygn6t8F7XyWOH6rBcV915hGtGrvyq1izcEgNKxlKqottWwe1DrO4VZWoGebisxDxnu0OGg2zY0XEYCS0h7LYc4Dt31CK5PdXZ0AbJhG8NImfptBhXZVerPZjw6qEAVtxdIiE6vW8Unt7w6vahrxOarbBH+cJp62w4fo85VmLbMRP50CzNW1eef0xXn++QwN7/4Ryazi/qIhqRPC9tyvlWbENI1y2rw56f1wMn2cqpOpchSSJwq7Oj1MUmASKdYqqbisDA40pDf40x6VYzsqGZK5g3OV4zm7xhr0JTrPOx3G22fRzCa23wikMJqHe3JnPMBu3bGLc4uWLzUtJ4Yd8gwBi5QVmsM86MgldAiFgbgdG9MV4L5Vbi3maIZDRZPi00BuH3kpJPTL5JQ2BY4RbWhsr4uXvnG75Xkc9T6OzDkefzsjYs8X7pzO0fjpH66cZtH6aQ+una2j9dBWtn8quCMQ2PzVfF9hU12Wknp1L6afhHvxTetylcXlTmLLj1jUwuQqjAByb1DGtcbUf5DvxebLWpRa0FpoIBURVzi6FOJYqxujYL8CaArD86bZf/HrN83g9fSasO8Tu3nyfyN5Wu3AU9RnmkGDsPSngfOj5wsnU57mTqe++Zvx57pjqOMXcmdVxCrsvPbmtNron1GVdebUM52uFDyVMShq09wVXNHc5rvUvLF2+Q+cnW+Fi2Dd37ho//dAOycBLzLUKZk/uXq6gmepDvBt2MweDw/Fl/D+9KQ7VAk3voGuv3awN/uyucPrHd4Vntpl/Nev5zvOvwmJm0/pXKz2/6T26yt2m12+C19dvgvNJ0SvZWSnyRw1fp+dZf/VO9pko8qtwjv44Z/vHY3v645znsP/VnKI4/7Pr6Js/ntGff3q1n+2G/FnOc+nxV3MWfz7RZy77/zKN+GPonl8nDs4WiQtHjqZrwx81oL9z2yuVfmV99K9LN5eXIz/ZcW59+4+RhYKLxguWMFdGbYpamJe9CYi7ythnBPGo4EEl5ozDfP3sqtb/9hm8V5/leh2xXK8D7/dzV8FyJfF6JJRO+dTXcz71VTtm8XVgFl+FXX4d8YyvA/P86tjAV8842weMs33AOJtm42wfbJxNwzjbB4yzaTbO9iHG2T7YONurcN6vAy/+OmFMX30u9PWcS30dM+2vY97zddZ1lFZVoKpQVRHJsqraqCpRFYmxRlVbVUE/oapCQZNRKWg4PuELpSJJlaSeTlV7EnNV9aWqo6pO6ueMbPQ65ZZ/zslKr+deNF97SYa6qmERy4Wfm4nUqghUEaoiUkWsio0qElWkqjCq2KoiU0WuikIVpSoqVexU8amKWhWNKlpVdKrYq+Kgii9VHFVhezGWS14H8Y8bNCe7iCrDIpqIlTPodh6xhN5B5oAvpHkINicRv85KxK/nYt5rRsJABk911vwlhNzQOTSq1Na5StoZtevULla7Su2OWn126pPe2k4FN6kh8QJl7Gr2SEDTHFYMrY+hYBiGrVHbTm1jtaWSM60yo7JOwaIsapp8t5PvcvKdTr6LyTc1Eh/0Vk9i4KipVCH7Xxo1NcTsujkPf7WWEa1fGe0MV1pbg741wdRaE2RjdKmY9CtuxFKd9ZyRWvN5qW/VMBWzgL33j1IM4Vn7eGJir3S27Upn6s+VKIlTZwpxMJSXerYDxUSicdb8VCqWCq2pxNQzqZc6w4upM4HYG1BMXdWprVorEys4iaFhTeNKGViyJCCzLdCDBFdIIaZBDxwHI9VH+DGj/6OB5VCP1nvEesdjIO9l5UKdJtE6i4fL2Ndj7MjcobJv3tTBStNA3UmTwk1WmTnW8ExdQzfY7UafPIlGIZ6pGgkQRZiQK6paFEpErHJavUzZioJGwyNk6ZYrXYYpUcmkiWme6xavlI4WDn5fVsE2DuFWg72nQWiH2Xk4ayPMW14ItrUEg+HtYLl8gee7+xeYtL57WRgVPd0uKhXdLuH1bnm7gNeRh8cFHOAtnxewnHr7ALPw0SPFdSp+XmyR4mlBQxjd04Oinh4XNIOj52c4AYoeHhY0paIn+qLcz0tYvo9ebhc01eIlTR0q8X5BJDd6pgfKf4Sp9+iOvtCEpwVMvN49LEpUsFyUlOTxDkbm48dFiRT3CxiCfb5b7JDix2KHQm5hZD56XC6IIEW3T4tPJHlZfKKft4tPSnJ/t/hEY5ew+R/dPS/g9OTxflFT3PIOxuSju6dFTdnvbxdEd6Llj0VDSR7oCzXcwYJ+9PiyaKgjPxbwPrZ8WLRow/OiRSGPMJcfPVEcFfL4AN9v0fPj4oBClsTNqPgO5DO6fV6cEPVACz9VulycuHP6jtLdL/Q9gYu+AFGCOXL/WNKTMj68LEoUeked7ij1E8EADXimdiP3PfUG2Z9eqDt3Kn6iVlLwC7WPi7llP1k/2VRTsLzlrY3g7k4F9w8qeHjmz8cnFTzxHkjwTJ8vsiPyhLgfdqkoFsHtEkNZSo/4hbAkJqyjfhDLYSK1ARtLIN4UtCTRcsFOGJ42i/jAYVQKIdMGGrmbpNJwk7Rwr/ELhdNEoqCgonkc/9jQyiTfRBAYZIc0RspbTPQ8PqIhFbssi+/h44IYRWpJeCS2jviHH0VVuobfAUvhZ/EFVv81IaffLUK4Cl5yb2m44DDibpSX4EtdIuyjsolNMqOsNMREe0oaUsqdVHmE3JTwUBFDFD8BOREjLlAp5p5gNir98QmmpGnc/FIfn6mlwLcwr4jSEvpSIehtwmZJW/SX3sAqUnHxI2qKbR7MPkmNVFQT/DM+MFqAwRySvQzJXCk/gHXc3jgvYET0joC+qaqW+Av055EA36ZtF/AkbXYxxunWUkCpsIGrAKlQJkAaxzmtoSBRpuLB61/v3Cu0kgWPIie3PfLAdPcAsgS098B09yAdeRx6QZSsbqcACfbEHsc54PqotnfLpcpvVX6n8nuVP8DDR/6k8meVv6j8h8pur0ffSZwfREO8vV8+qqWOk5h4bHaW0NN04QQ34KaewzSmNUL04lZKAf8PY2ViHU1Mnak1cHoF/n/N/P9K+P8V8/+rFu6LDoQGR8pkanpQLjzWZoMPuOE8Sk58ct6jZMYTzipSWkzrOBIzae5D7LP1UWx0rY+Dgdg+imoYYlDPEBXLFpn7RKXDF6qGwW4Wurju/ksqHyK59iEW1Q+RqH+I4wYMkdKC4Zub4NXqJxYw+q0APEfNGH0zhMcNGUULzKeNOU5a4wc8H6S98Eew6EiAh5nYuiEGpwvks4nDCqyP+yb+q/Y+ASi+TC7fzxHcwMa6YRvHo5Ke4bHcRJdiXfCkvvW4PmueH3zXLq1wRkG3xESNfMdmvEOaRcSTpDBQvwE6M276WJT3MBgDlYdaY0exAT9UDh8bSeg+PUT20+xnQn3Em6Q9C85p5WJnt1x5/yGV959+5V6a/UzoqPJR4eehmxEsxqmLUjc4fFZrYvEX4rQRnndpjdWQEXcwV82uQlNwkVXZf8c7E2kaW/pmVUOfmr/CIwmZ8JrMe9YyaM00kxfR1lV8EuPYPLI5CFLleRl2p+T6RiABEXiiwsPn0Ab4GRU6FvglA18+r5UqSYaC5Hvr07dtO6Jpfp/8sTrrUx8RDIX7yUNdH5v2PLzUX+eB/tgMaL4dYZ/SUZyLPI9gGeqmpRWk75kEPnH3cIqBJZtwCqAnoaoGkgmneB55cLa7jce434YUtLcfdpDtVwWW0aaiUvE5KtQLeGJ67adAN/wExE/UcKxnP7MjwaVqhO5JUG6ck2Gquisz4z6+4mbISP3Qgc3yUnV9DvAEfcvb+hiA+fSLZ+2iLX0gVjakgbaOXbXzJzvGlnNCLD+WVWEaV/qyBvNLdPKr1aVrVleGfXubuPA+X77aLndRkSlMhJjYD20MSHOfhmZjbfo9aKLZo+8G0CDBtQ+Iuh0R7OFbuxeIz51/oqrhRrHVVkfIrQ3XVneLmuR0ON82xO3BXUoTWoeecURVUjmlivIOttDhRhcG5FtiC/vPUO9gRl5FqSE2OBQJIXScZKK7smXD9ITRNZwvMdMYBvhpUhMjT5gTaxlSPk1ic6NiKj+ELkZTmpzEC0pdEQsOPx9UXb3D4YYjUUFdsoug3HQFRVQFFdKwr0v6oBZTM2B3XDxepGanQubHI2IlKYaEi4b95VCR1DzIKGGsE/E6tGdvSGV55CJUyHUJJx3uwY2FO707QtyA0yEog9DSnJJXX4R8aP0m7xCawJd3DddItaaMtYpEn/ZFcXwgIwAZCIcjWVUApIidT6VlfgxBC3oV2opYwYA4FrVK1Io4C6NWB7U6gUFQq61aZWr1qVa5WmHTg37xoCecb1IkxdbEW1BqWuHVSoPJpH/K+qWWIY7J+VXt7rgKKqzrOs5Jw7UiMRNVBFxFRSnuUNyqSdXHnVqrVXhD0iYqRL1f3Iq2veP6m4YbHHOBHRq7pggwSPhK+KtpUc4KVnqNQWn3P1AAZ7mDoWt4DUaSj3v18YAmUShJAoi/V7fVDnwJseHhwA021nOZaOB/3zHKu+XasWbFwoLHsnRFwoLHvAZFwoLHlgWPLAseWRY88peoyGfB49FyFY1Y8NhfVCKfBY9HLHg0ZsGjEQu+JBF1Ab2+Z7gfZptVQCgW0HzAKyw5k0RLax/82MXw6Q4X7QFJZiFNjhKziF0w72K4UEdm+GIGclOGWPw0Z/S+4zj8wDEF8TFByMXBlTPSEBb8JIjSjM5lMJifCAHdUFZz5477SNlKgjAt/8QxNKi36oavZUJysteltGH/06bOgNgJPJiuIp002JdN9zRbV58UScwBPNZ1W3ZPmuTMW0O1SWw7Jcm6pmBP1QkyEFUq2bk1JWhw1IDQr8PEX+36opyIRTM8Yl/XnUGhsTk07PkWFW2oBYTiJkkQmB4oM00ebPVPpCUeqh3YnaFfJY0VXL8n8IEdVYaH6wQvgkEkj5OGc+LoZPDAuIF2BHlssCFYVgCjPPYVku9ixNT4aTAsrRY32/BedcTgIlUU8iM4UlAY1x3GPqx4UOHxNmgb0wFrqGFHaIOMAiUNDNVyZAfdgdH+YdPZjuXoTs7Nz6WJOVq07OA/vvX9TOzgVTlu2eVzAffJcIj7QfwT+0uv1Adc/55i+cJvS8vOx7GK+HA5bk2bko/Xs0tmnB2OAP2PsqPgU8feGTN2DlvCnTwfI4/Vx2e143urcLUI+4N8EZc36+mzYifrSNt06gdrAIiQGBz9dOPYGLv/tmB317qDIyAAWyfy+NJgLJXe8sjxOHbw2crj2IGP1HCeozRhs95oxS6iKbzoUxwpcC+5a4kj8Gj4lT/hibGyTuY1ccGU8QSPidnNHfsU1l+UQoMvg78sqjg9UjKa6ltKQJVyM7sC/g/fRj1883QZQk9pAkdCHsMenYmJgFvp6cYiu92hkafx1tiLyytsviXizM7wNp1WZYrAksL1kQSqg0oOHVwsxSqBB6aYbczHEJPoBx4gE0Jg+t3iJ0MezkgIm+wRRGITJeYkxGckJ3mhsJOE1SrNVVqotFQmoQoNhR3Uy2gv0TYce1jwyYydrKxSsWs4dpgIlVMEUp9iqj+GlowaHqPhcapiNDxGw2M0PGbXldzwGA2P0fAYDY+p4TEaHqPhMTc8BoN0khcKO0lYzR6NCrUpqctUoaGwg1rSwO69FZ3q3dGyX9HanxniUdZwpglBn6C5hstY+AZf09DVIQWQsEBsBjaI1oEhjiMCu7dONH3vYdafmnNU61NVqbXVIaj1tosSehxoGq9TfUPYtc6rPKcUhkZ0bTZqHVMD1zga+hGx026kJr50TXQdHjTUuoYaeI1ZuYbad61RIpS8645aX+lMfVS0TH0QjV3rQwxTnxRMWUBS13GNt7rWUIWhIPCv1BeCRkXjCGfwnuca6ho1kabcmgZzTTNxjRlBXaU1b01zad2Amhia6+sIEaE+loABgY7+PzXRlXXGv7lGPQUnLTs0/qDh+4CSHeE5lt3LGniYXXf0iW80u1Iv3rGA1e+rBe8IPOeb9vBtVaoNIUhAvYjhR5Y4YTzg/oqYGLxRu+CCNeM4/GYIoekY09QjYQQ+WTnxjlPsxNUsPBSCyFIIfttGXht+RxwAFRO2H1Ai3uEMOj5JzqfJvnxEDSCikRKfDekALQyloRFOPCl+o2aFBm6tEIdfNDSkhpLMQHyJxqrEiXecAr/Y00FZLYfgFy0MpaEhNzTkBB3YcCoR72hoeJKcyzgnIdLnhtcBJkeMK6rAEBpm/ET4gnNxzCZCjRg3r3BSjkcbr0QR1kTmPuh/jUmAkx9aUtE4Ey+1/qT/2iJyYyto7ZOQBR7sSVxYY7bZ0IR+NARfICzOe+su1LzSaGp26XPxeau2tGyqbWIKtY1oRm3jADYv65zeCJ23J7hY3La6UVuAe3usDhFCsV1fU1IAa0sCEH3CF/H2i3PB7yJloCm23abVF7bz6TU/mhamq470+0lzcKtpZlKx1VHlRByPCCr0JyJrmNU8hFTSiYOpmozKwgzbElnYthy60Wj1Ca/UOCqVpD/qC9XQYF+fApr4SPn28fFEecyhRklU3dYc0L4jzcKMy6TiqFs7TpEZEi1D458fWu5Nm2bdpzmfTSk4ZWxy0+gb+LmM7JPG3aiUxj1NxA+6of/U4BqmSvFPyJoSnhq4zKSxT2nsOa5SKQ18+knBNOhpY8tr7RMeNOnxhV1zldKg/5h6E0WLCNc2IZbCmF128pNalKgNnI0mnid2gyVRbfAPn6NwKApPntSiTRlLHE11atHmE37X6dnY8lr7hNNSelCLNke1oRYt24rEJ+NNjwasN2Qz+gk1k74V2GE4mF9hShHdgnhIlHMFl9ElfpItvwkrzlQY8iEeGfPgIKxgwsGBI7pkiZNmOHHyYLiZShPHzdV90DxftbbqDp7PSP5EVvx8pfyGX2LVt0ec8pSUABFJnZhLKB+kYLWDJFFV/ca6tixcsFzeqgC7qCp4UMGjCp5U8KyCFxX8UPp2qYJbjuNQfcff4QbyE2WyL/f8+zBkXS/vXmiBDZZ3VMa9lPHgFfvQB03qe+zrO497krg+lIKely6tn/BFEt4Nade3y+XN7ZKE+eCWRHl0Y317t0QTb3kHmVp5C7fZFHx/GyL46YGKv5XCKMePW7W+J0hp4iApNUU+UosoCaWgWMieJGyoDwKYtqlc2FliEvWHVHPR99ejH65HP16Pfroe/czR6wcC2B6621t53MnjXh4P8niUx5M8nuXxIo8f/CB4/FUx68cZmEtDb/1+cIQD6zcwvQbQx1+BI4B43p7n63B9uR79Y9I2mkNPy0mW+a5/j10jMDzYD+70LGAffx151s/LW0iBd4uAQhYRhS1oHX9cbCjbIqWMiy1lXWSUeZGr4OZukeNIxiLHGY1F/qDCp0X+hB4tDlTy4gtlHVGWuMim8jTNIioRv8+LiGTfu6dFfDweqS93OMezflleAMcFj9duNSSWVXumSFkxnPDVPzmNmvPuxFmwFnUnlipbUECrl3NIWWW0dPU+vJ3D+omX7j0OUtJqd0r7hIkkZE/vBSf6XMhmHgVs7JFS+BzfhHmFtz6IfZDHWCLheMwWh3MIjZzW6JtJy2jiN7MP9wOdjwHR1fZp4PQW5fu9rFoc111s/RzcZonPm6Fzp2k/g5i4uL703A/M50DG5XI8oKa2s2DdWF/mR1X6BVbzXSKJLhFQCqptPvsCaufMnt3XJ+rfufppbbU/ZBvTpGOwkgTbhmNn7TLszTfYwV5pJ/Ca1m0doNp7vKN6aWJQv1q88q17v/MfPdZcThIQbxdgryXMIVJ/RDFftrZfOPJeD58638cVzw35HtrJAbON/5Bp2HgwWYbHHZ+f6Q/70dyMWbtUsYIJqqRK9Eyixq2cVmj0XUy+y8n3bvJdT76byXc7+T5431Bz0Qc0UvS1NDiEzyfPoY8auZPF0dIACo+UnQTD83DOn+CMIVSn7PYX3wht+fdI3CjYbWRmP7U4ExsX7Dad+Gv2yqtSyQfOu9EQ3NLPChnYMXLK+kESFYmyNrG3C6g9NVcK2dywbG5IDjGi7Ep9xf5wviEdnTlZ7nReYMs9HvdVc1+19FXbvmrId+irlr5q7qvmvmruq+a+attXjb5aF3/oseYf220tRVC3tXRbc7c1d1tztzW6/bZpb3qfjISAHZ+x5UkzE+5BRQMqAUNFs8YigMZCQ58fCISWpQ6ojniQS6WtFgT2IWECj1moSII0vg4fSSVQkl/n8nnXw01CHPTcc3CW/RcAlUwC1gG4V+H1GtZdaPgyuU0mwe5jCk7tI9ySxOLaF/gByxXDT9xsW9fa6U1tnWrzxST2no2tP07IkFsxtFYMoZWFCXxes59r59tarTjbDiop7vyKO8+eqCF9HcZn3Ljt/tm10UG05S6t4tKMdjjzDXamWux2FDk2p2hV4j2pA5G24ISdihTRUO8HUO8HUO8HUOxjs4NEK7Q2aOIiUwHU9LJfBWV+8FltcNoE+1jc3qClMn967Q14E0paGvgtDTBmIY/Zz/FJP2zRRuN908BtzlLX9yzRHnljtt+VrWQblvdhIalueEe1kX1OtymbH2ULNVTPHlslyooiriveHkmJYauS/Ljz98FYfW74NsuRPg64/6JVdXOnCqLpUBsVpXzD8gSCaxsNZTwE4ALajKLpE2FnpCCRu2hH+UqqgcT7jT1OsDfRVn1S+A9apxpsXA46lBiKESg+qEW4FpBSi6Cqw1GxtJRLBLWoS1K0IEULsKGX6jpMsUTgvbFKFWhOWs5kKqwQNJFwFB5EO87lZOAhzjfYs9u6ozM0z6tEDpHWRau2prhI3FOefwa4m0LxaljxmoriNWXFK6i7WwCMbAanshlseAszlc1gYzeDR2tE6m/+mtHmbzra/DX+5m/qb/6a0eZvOt78TUc7iunoAFI6On9pxucv0/H5SzM6q5SOzl+a8fnLdHL+Mh2fvxyvhWZy/tJMzl+mk/OXZnxUMJ2cvzTT85fp9PxlOj1/mY5OEY5gcxY6GqAprM5Tj04ijmB3ntYfxDNYnof7w+qdIetRnwda8F5teZzdJMhknPs5IePcx/I495E8zn3cZDbZce6/ZZz7z9ZPvKSJDGrbpp6i8Oe+onhr3ko0i1XIJxNIBmBNJI6mJXxFlUjdT05ozZ7AebOzAURTt9mDJ/3Ym0bXJJO4UwPYIsCmZ2KfoX2CLYYGO2hbUfIHUWRfsKsbtDZdZJ8I29n3wD7BM6MI8MLgp7HvyrsJ2FfQWJ9kczzLuB5s3sZIRk/pCYx1icWOj1B32IuGvSBrgmhvwA6rn8NBlTNe4ad3FmVuodr0ePFzhBdMAX/uujJsO1F742x6YoV8ubGU2Cc4Yr6EhZtVSUFLD1gkCIBt16gk0tDppjIk8pFAT9rIpjcf0ViwKZNhVST6byxLYZjlMFiqDfMOBuyI4QXZMI9imHsxLQfrVhlmSQzWdZNJbuE9MuZIDKENe7tSW2JNDA0o4owwP8Yyj4S2YFwMczqGeR+klDhmfEi+wmYBAgJvWTByJCUmeSVc8AlBXvUf+FzKeTdT7idbrBaji9RJ4k+kj3FDiyP1kbuIGvFDgbfo4kZ8eIkVTu4hx92jf6nrIGAUISbhoqlz3DMEtzoVP2Hck5zt2+M15uBJp4A+W8ucFzA6l/rcuTCRAQ9DyAAPBJphyo/AAtXyZQeL213Uz0Hhy0MRuWjm+V9SIA9EwJAPeHyDL/6l3uNhkSWgMZKX1r14PJ5wpIGULoWD2dsIw5cyx8cl8+9nyg9GMeH/QscFUg90QDF7M2wJ2Wla2Lnpc4nM1V7kFUezrGkxh5zYlFhChjkPgd7INDSjr61KnB97mVju3ulS7+Om9VlN7CRW9Ev/JUii+sC5b2w2f/D+IkWuDQ6prDucU+HNyK8YlkSJbNr9ysRuKmKLfettPUZuK5ICeJ8SG5yBDSwpl6ZS9J6r4gJLu8OJra718Sht2MvmJrZAsbmJLcw1Do+tTym/IRl/0//L2RioJUmdR2dWrWGTV0zOAEAPzM6c1S8kJCY6iX8h4ZML5BR9+lEShGJN8orhJeqsHA7tC5Iso1aZUhSr9EHSI4kWhA3T+VjyfCxlJpZ2CpYEtxJTsJQpV/LsKnl2lTy7Sp5dpZ1QJaZPielT2ulTSj4a4VImTcmTpuR5UvIMKTFDEm8GlFiWKl6WSl6WSr4NIJOh9CdD3a9HH8Tb7824SwV3qZAuFbZLBbWBhJbDDRomUmshnSu4cwV3ruDOFdy5wnauoM7dcOsL9LCwPSyob4XtG7pToDsbrzsFulNydwruToHulNKdwu/Op6fQafgQPg3WTMcS7lgiHUtsx7CVmow7lkjHEu5Ywl1KuEuJ7VLSdylBlxLbpYS6lFgtFrqUoEsfTnHFU+fD6mfHgcz5MSaLQpH4s0ZVIDsfHkBAgKhgACRhgOAqCi5vAyBJNT2vSDVlg/xZ1VmKe844F1iaJjb0iuOINtwM4XyOyoVX/OGiqiFCB15JwRAc++GxF5F44YmX3g+PvYjIC4+89FiAT0Mc3l3c0cty9LL44bEfkfkR2dBpP6LyImgBHzLkXkG0sEMlsoWHT1rDoRUaCi77hLgvOrQcH31E6EeEXsTRj8DhjTLxYkfQ82N2JITTvwmpZX7ZQ9H608v7OWCCF2yG4MoLroZgXXuF1B5EcOSDAAHJJfWS8Gll20Q/IvYitAck3Xpl+uHxEIG1OkDJDzgZJ+flz86LlFDABKrQsDpCUCgJyGXYEMmmsFJskPC+1IJemIISUYeNlJJtkpQ4/rglsk2p6b/DC4064kG58SKnIovSZFXeBF2dYLoUdRcZ3BPW/FWBmNHYlAX9w5wJn1AkYBUEqepEFJsKo38Q7DCFoZOyGxXZjYrEV7ynVQbmXSjjDUk9u9jenClwIHpyRiXHpA9UBihkBIWcoJATFPKIwggKOCnpoJBRW0k8yRPYWMHhScPHhQgKeUap6R9QyLBGUHxBZeFFjlhmYyhkIyhkgEJGUMgJCnmtsh4KGUGhOCmaSTlBISco5ASFrFN5NyqyGxWJL4JCfoJ5mHwChQxQ8IhozGxizLcGrBDhU04zLCUpceAbs6grIuWJd0SRlhH6JxmUyDsrvHBSJgnlWE8CNVmy0VheWAeWQH9G/7SmYG3gE0m0mOAULB/4SXArk5CTliAKNyTzwmwB1ee+8IZjOdDRJXtI1iyq8wkiCOosnX8wb9zoDEcDKRPmBTsnggRA8n6gU5xdJWkEG05cX9MQD+qdc9wAOhssMQkvMRtZYgCtDdRtCavbNqJu27C6bUmTTR8XXiFvKOQNhbxzIW9cyDsKeUMh71zImxTyxoU8eaoH7fbLkNVXODw1sECpns6mdRzao5E4K0njEm/lRCSfdMSxyQSnH+n/i/6P9pQkjl9C5xBv7JlKHKOEUgDLJhVkKMxvVgyboGVDXCCJ30nMVkH6xfvFHaUHWyrSSdCLE/L94vKWsLZNcp9npVVMVMFAadTtcsixQ9xk8oahPV0JXQp0H1ur4jjYk5fQrUBPQn0Nj/agJU5woq/hxh7LtMqT0PYVuOCbWWVbWe5yXVeYxaD2+IlxfRN1O4/rG8b1J8b1jcf1p4zrTx7XR08n8i48yruoZN9EJfvOs+9NVLLvViX7Zu/nvNn7G2/+5HzzVbTvIxXt20hF++6raN98Fe37SEX7NlbRvo1UtI/nqprAXasO+FqnuzePG55qeYxPJuo5zjg3G+z48K4M5KgVru+sSNpahQZmGw2M/RuYskvtkTjoDVYn/NT2FBzRDD531+AEMzjKNbFCsL7IR+pWJLatcO5z9ZXyA6f4QCGmF1FhUZCNA6LUDU76bXgvSa0K4zaSusLuQJFYvYoPOPp3xOZTS18wl9DfGBHjc4ygWuzViREFQWTf3LA7nO/s3A0TAuVaVtezIcZRva15yQyznHJGwcl6zlIQzHixEmDVO2a6kqZ3ZXA5jddHtsjHlpwJCM92GlYHa05CZy3OWuimVhuGgFOxJdGZeBj6e6qh6G68LdXQaXBiF5zyHcQDzjyLeoaTsQwSsgwSWhkkhMwYYuzCYUvUAmswfY6THaEVT0QZE/W4IRXscMWOZRZbjpXJZkuCeCSCkpWeRFkTQtCx2fE624zzqylnV/3a4bJKJLQiHM3/8xn51huu91u1nB2LNYN8LSDn0+B8HUAAvWZArxnQawb02gJ6DUDL3QcLyLXkwMQWYK17uEB7gl9AYb3hInPwti+mjOJdXEZ8wRtJXgZ0G5TNQY+e9ttbVPoo+x12NSzs8Udqk8tBIw5KbBAfAeJwG4C2und75Em+XrwBWmMoPqxlE38MXnw9GprUD3Kg60Z1/VRvVCSa6z5E7ldKYOOn41Nq08Q8p7pjknb1nAZUdJ83orbEOAYyjoGbRlNFZn5RU7kbNJOeGpIVkAEP3s/xUAl8jQAtngxLaTWTPphYY490DKJMdIi9zK+WuAOtm+IMYQNr5++s2+e6XmADbPv4kPgdGAx62ikIxjvx/YZ7IIdKLqlbl3F+PD9DNJ6Btg8XZmL7N/ORdTM8K/0J+cPRCq7ohsteBvBfYoTRC4nxx/JTRp166/ey3txe1tvWpHtddDku5b11O6oLanr6eB6O3PNp+bXBEYI1zrv3+2gJXwjD1dYYd1/5wIHu+FC9HHm3Tz6D7w7rb13gEcfo+R4lOIXIvvA92HY42C9pNZ/G5/fAPnFa/yin83GCn4/hY4sMl6nWctB/lSOCNUe6MLTg4TutIb+UqOfZZ9Sx+5bC3AysS3b8bXAhKOhwfScYep3hAorKcj51puUYGvX6RTbVnmWn6sXftnqe7ofFjp3GfX4sHqG/FRbKBti/hhGnYDAm5ElF72jUOxq14ka9c6NWaNQ7GrXiRr1Lo965Uc8M5mEw7Cakw7MhwsrOUD34A3SegNpxnhtD7CAHByzYz8g0dj1+aUJcRvt/BsWxDcxf9T+N7FNk9pF3hKgyEBb8xMKA93sebYmIjZVYLs97Ib7t4+eRvvfZbjiNAl9mZoLXyGFG+QU7prmpYHylKnYxn/eVo+I6pRUXPwF+QvxE+EnwU+Cn5NecX/Gzx88OP0f8wNtwhH3PKMPPltNxDP7jmH4M/Xf0XyGAi42dSQdG/fD3DTvQcqgza+DllxFQ7igJ4mWa8YDxzb2VeCWUc9/bIeaoBe8Y1QTz3GtZclyfNhpyacY79xn0bwV+jigTF0pX8BO9gvcrEq74UhSj3wT/rqBfUBn1XFm00Z19cdSAKuOq/prYjLFzBhPHZqp70e6sKzhQbPr4PX0vCdP0lpZJb4NU7ufHvE2ayS34j8Q+Q/vc2ifIwgfIQsCmBSL7wuqt1qaJXFr639n3wD4LthSAY9/qY8/+upmkfGBh+8GNlkn943xS/xjB5UcvajRpbfgid62jGTx97/H03eHpi785PNr8HeZ1WoM5SHO+lazlWrLG9rA0GDec+QniuQ7tx9YF4kJza+GxjixA1oDS2pLUdeTS0v/Ovgf2Wdg70bXc7gO01ntQzNSCTEjry3isCWkjA6SlXodDT6DTzVVO8iLNcupJSHQAa75PSt/1Xic1Gvnuc1XvPlf1UhXqRRDwh4+NL+dD9TIc/fxBaWj9kjEbxtc2vb9QI0Q3/mJDV7xG2gQc3nQIl3evz7va4OQUjN5TdGy7ZEoIQbCs6WHBX94hf4kzXdjyGxPhxIV6gXUne8mBxEcc/u7GMBjQ9YYtcd6aEhrfhTuuOSjzfk/T++Ep8+yGYyqsUiKsUsqsUiKsUmpZpcSySolllUZ7lNmgac/Sapv511Z9an6BjbjISmx/g1uOLnERVzkJj12+xEbM8RD+6uVzE2/if2me7k6ONf8CHzHHnAgWsQrdkeZP5onEPsY8n7GkKdmO6PaaqRbI05Qm+eRoO0+O/pYkCTmScVmDeCPRCOWBSF2kDzry2hzwnkLARl5w/wV39GWPwVl9gbmVRE4m8jswCsZf+GNrjyhyBEyxtPZAIg8ZtO2wa4EvTlFquXGTSoclm5iK4fdATi3yO/WPrcQgey7WYsQujADqdYw0r2NMo0V2Y2DSYdMpWBuhPsWwbNLZfIJaa4tpf+nmYkmEuoQnMlnqBjWpbZzT6v79GpjkYoODl79/wfXPs5zE/bSaszGABPbDAvfLi2YYu/VyZsHkxZA4QH9bTBLs8q4dwLuPI1iCdeCPe9eO7mSuqxHQzkeNc43htdvrquudh0XpN4fzg36wjd1QM3ujDIF92XZ5d9MaHF/1bRVsJkg9QAYb5bkqc0J0h+mC6tj0Y9Mn1q5CDNTAjiB/bF0gb/u1sj8bAzX4BaiB3UBOE7m0shnI74F9FnbnsLY7invsMMKCQyONRhqsBXHNKViLImPtEGA1RgBj4HPDdHC7YYZu0oB85qrGURIcnaUU1E2DdW8y6iuP48S4lroBkMN+iEM35WLGnDCvKuyHW0RaWWersJpWxzteUCd7misPr1ayEq39ZUniq2Kx65p0x5WDJzbD90rQsMWKj0bBBpqhBkZMQJdlfPA21N9pETTq3ag3Ihwk5w0wgW1GGvdcvcUk/lGCih6Ugmp4p4a/JfbJXABeQhuwdRFHG4Fq+QUIwC9AgLfWpotcevvc2Wdgn4V9QvFX2/fcPg+yhpN4JV2h18fxiBOp0yzzUNs/ht4Ztm1lchaFkACnRjv16E/7V5+nfPWWAzvEr0JtXntke7U7Ti7lI9GNR+YgjXqU4Xvyx/JRfM48JnrnjrQ+nrMQj97c//n7m8G2RlsVe8tIqzxybPijKRtsI/S1NR4P/zhP2ARKvuzw6ssOy9bUKXwi6pIm2/9t8tc/JHs53Z8TwuTbX1y+kVvXIqudrWjJHsfQ5uQwFtn+SvJZWnFn8f+nMZuTlH9rbHoZcU5eHjwgQIseQG3+QqQ/bo0vL6Z3Kr0nwbOMFtWGRL2v1nEZHpNtd9FrwzuZMCrQufNWVV3qgu2276kaloetop7NQh0bTn4WdbIcihdCxe9GIbF316i3OUAlqtjuF05K2J6VsP3sdFR3k0ACTDsNcxuUbDABdeyxdReXOBfXUTK15607L8BRF7ZwfmM3MoczGAZmMOeCO0LY4bsbY4sXXnZiCOSfXjFnV8vfWCnnVkm3QmJ1fNufr4xv4I/+geXxfCV8k/VS1zQPZOrMr3czi5sck+v2+m/XubsyqXLs4waGmiR46qaFeq3hbYpwnyPht4qbNZvU4u9snBdoi7hQxSRjcZa6V1xJi9ILhTYHU+c2TTwpNDtL7U64D5nmi122OvMFgJUGQq8MEHpFaB0TytBHRQ/6ygQX3y2j9w78fQ/tx9YFQoPYWg3Pu9PuvAN/3y1Wv0cuLf3v7Htgn6CnKAJkFtzdHqibStMQDw7/aYx+Px36PY1x+rLS4cln734K+X5yULB6OpwifTpH1Ke/O2q5LI66JCK+2OnKF+aC2b39kO9ToaiQiwqkqMCqJ9nvJgkJRBszuEb0C9yhwB0K/OQCd1zgJwrcocBPLnAnBe6kbTqt+iU/84jUu9Cet4EgtmPKw1RnC2rGfH7q0Z/G0TQEerQrGZWHr4QLY1qYjiID5pDdAU4eOuvNFWep4cSQtwUgJtcTwqampA1k7CBkjIILS3cyy3T/HeWZOW4pxVtTNbKEUx55vtZdTo14cjYCei47vLwCgHIvI1zW/79j0jaTiXtlgg6Lzraena7n8/19NH/P5+ryoOEdYRESjzW9jsC7kXC1eYD9zQ7H8nFo3sAfpnOImYHDzqiiDB+4+kEpt5QgxFdJSSIo0VtKXMIgcBahyBYn8TPqUrbr4MrliOP4sONcE5upcda+oRpy1LRH5NvojDG3y9AftctQu2iItpUyBtqKzhp2gNELRSivDLXLoF0G7TIdbppQuwzaZdAuw+2C+XWj5W4MtctQuwy3a4t2ZdSuLbXLcLu2qEna9Xfk6c2bDZMDhbJfEfF+RSj7FZHdrwjtfkXYHz4uCOGpHmIGs67uPBO5E14+Zs49swZuE/sEuuPQNn9s3UFs1iADzWNOU8pBbU4TuYxyTpvfA/ss5FA3G96t7YHvPSteKLCRJiEdZikM5r6N0T1hh55JB0OmSaxgtT7B8I+QW/siB98VKFtvv2JXxxvzRWs7n2MXNH+z1BBU1jm9Bvm1wXj1lKJvkc+KvXk6h7czseMvUWBJBDsypU5GWsbo14Wwb4dTAt2Q8mj+8bB+P6R1fX1Mh57sam+EEzD/k1F2JCzkYdW9WK+dEPnmbTS+Xdn+XJ40jEid4MFInEP3gNYjixI5biqxYfmKX6htBZGh3pYbNdXXcOqBD2DrvYl98j2Y0H5sEQDDNYA+Vu0U0OcXQJ9N0aRyCUcyi20bfg/sE3ZuYH1asp/sC8wsExVMb+TWTW8CZw9jN4hrJB5piaBqZ19q4BOkFz6jt/Gn1ueEic4n35t+rDZurHSYd+C4btwksyCiNMYazrLuObTaU+CeGrzHlpJLjyG17YLgykf5hyAW7dsmjRO1wX4kjCPK3iJ/8CFiie4LlAQ3OJIXzZV+Kb7pAnfUrKmOFTEgA9a8jLAmJKyJLHGNZG6O52yWq9VoP2TAm/8a9U/buOwwXAy8geLn5nvF0Jrx5uVMhzk+/3B5zCsqt0KZ1KqXKfZxqQk7UacFGA7WS3a2XrAL9RzXDhUcYLsGzOzVnd1yGkbtxcOVd0aPdx9X3u12VD/igttFxV6W4b1QnlbC3eBUr/qSR6NerNfl3CmlNnewpF5qPs4vthVN2NAK1LYmN9kilbuZcveSr3nmfDxnZ1QFQURVDKOw2cVsWR87R7D71xFjhqtx/aK+sxernAn7SJZRJsiltVrDN6wyZ1kmsFeyWp+8p5aWb5zlfM0ILKtKJ+uPdncldsREEa+kDPFGJTQd5qCg4TLEexCpxSziHRRMP5VAnmG1uG/58jyhmPFTqTzm8tgUoV92Mpe3MNENLHflXDqt134he75p205T+eVktpy8Otxs4IN41KF8XOCFZLaowhY1048l8W/aLvQDnYmspddhJbO2fmBfxqkxxJonsRy4mRHZuNKPO8Qi5+LaKNEyXJbgRGz3yQ8YDJOexRRM9JeE+R0JBf3VJpIXQGkakIg4g1GQAs4x6hhHaNuWMHudEX4wodG7XQrPBGaH4/O4vqKLpgJRo+kC+oTD9dCsb3E+c51XGsi3rqQYWPSArQ8aspBpE1x44DCcxjH8isljC/+/VEPKnj4S/LLfDeSt4YEkzvWO74W0HcyNoLwsr6jddhd6/9d+M5YEL5M1XXbl/MZIUiNAXDnQMXuY48JBjl8+vXH15EYznN64clxjurM9d37D5xbWPX1e99wA8xTrYdNPGOqfPnf9Ojk79Dpw23I47C9PhfyCtVE+CcA5teTUnNM3mxmIWKZFLAvEj6iIZYEVy7QVy7QVy17tEbKGnfQ644tQneFqZ08AZJ3iNWmGLzjjCSw/MCz800V/ZsE/XFn0m3RY7PWwfkaejgvMJkvSaIsJbcAWAVSSsWwtC9A4QLGz32BeC8Q3mp1FGbTFUFsM+wehJ3LX4uLCNDZMeNrzDanQia9TXsBHwbsGGLdI4Nzy8pGNER7/ix3OYH4r3kp99a+eyTDuJIYcxBhDqD9mEYpwG9pdh9AJzit34kKOWaz1TYZ8K2/ewf8g34sTf4PiZ5D9C7JfQfEnaP0Iiv9AtUy6cotDnd+NxuSwzNGCxwddNvgO4mfujZcPdjds/UgxTN0gDsOWeEOU2mFprgN7etjlAox7WFbFXwOwoGWiGRbizKcIO3+ye4Qg9KnE3LFEHEsuYdlhKsO46bXTTWOKgDfOrbLDaWWXmT7M3LjxjnsIBvV7XY9/uBP437ILOHM+5o0n4mQbcFC6X94TdFuBcTfRng+HmmY3/UbW37ztbEqvh3qnMST3HvBsdjrsDb5pvonW30nTVpDhd2urUXPSyJlwpPyEvPkgGtvvv1X5e4q1ZW6aXpQ54qSiXPAamyHl/Wm7et4QYG5aLMKGL3JTglEU1mCJ4TrllRfm", + "G/FzL6pUCW95Fb8Rf/XgJWGboc/XEBHwMjZyo9irG7ExfaXEmBR3fA+8rzh1xfXpbXGcwZYFSy6UwZlnAAXeyIkGm9k53Qa7eygboBNECwJORQTA0MppFf0lTZifIbHmxOX+1JpWVJ1l9NrRG78UXbfvP6AVJvHz5w4eIW105gIzrWn2U1wJlRo2XzCXNRwaUSAWVBRwIgb9JwlPRj0d4JKxy1uzH+351ceZ0JxlafFCTQhM4mvZO9wmYdnarAtpNI31KB74F9Kewq6uB2fjKKyK+gJ3Q0xbtU7V+0QC865qmpjoWN8OmFIUI/R1VTh/49gk62DvEpwI9TrT9IKrUE/+PPQ0viTjd2Us1tbt5tnHojUFNO+wtxPBXk55B31+J3Z2aObAfg7JKQtaDymwgHvMpNEJuyEOlHb5G5xribryXhKmCc28rSuLdXhUlsSZAu4GUGoATR+7IOgWbB3FPVTAKfWdCmwFAa3FvCPiyqRQSQxj1ET47sHKZQ/qA15P+3bFtSnv2MNBqyV5AneeH/nQcvhZMDQfUo4RdaOO7rF+onXUNti21+CudynbAFKhzYvoD4oQ+4ZwVmsnEWJVwPVBZF5Uu53QJF0u+lCVizo3glxDBe3gWLWGZ3FbfAbhICMofRDy3SkYMl2ciFEVAIQU416l/iZdtF1yZ60t4m3yuSPZMndpVSsm8LhZlLUvo08Az1gYJCzV1Cyd3IMrr6klObWEkwV4pYGBVTIaLawnPUalEG+HYccqYzN1MGa3xc34vgXspaNLVOSS4AOl3jF3AGN2REFoaX905QsgCzT0E4OyExT5NGpHsK39aKNqavVnFyms77QsuOi8UzsY2drRCvrZ+ZnuVF2oHTbYCWgSDOjtGiqe8WzX3TmEQtnAkULAAJdFDIkAQYGHK9QZIAnxQk1G871jwMDxPHuj8CAUuRkQ8PwwCQpzJcVoHYoimFCXCC1QKNVqp548ggeFoYI9VJsP7ddcfAwzJlIT+wC+G0ZN+pTaZ+RGscBkgGVdcdL3AaeTH9RzzCSeAZId01PldtIXsTe+bJ/PzQJ8ONz/qCG4YpZ+oF8fJ9xU7XEos+NEVbc2EO9ZqbagV9uB4jTygOyW29ce9bYCcLVbuFqz7h6eHRUMpw6lYmeY8PJOZezvlbo1JUM9XBycLEYRndwGQpkkpgWGl2yXL3eIAvih1ZnFM2LdtjTF8/4LQijx7Fnh4cy2C2D2cIAEis08eFtyOLzCGAAV8uAKxgkK24QG28La4b6lnwA7TrMOFRj7alD7HVHCHpBEHqTjNjPQ1rCZOgbw1kRDOfTZ3dtkpYjJHs2GbCLGdHo8hOxtgGXoAXXdltQSjDIqeNsVlsZDqIkcRCJH/xLNXpsJe3qsS7SQLkutEh0tsJbZj1oIGULnowNM6YKn1x2QEtCNbCwhbOTVQ5/IcM86KuhwGuLKSrXxSLlHHHkSDZODsEc/9I00DzC+0EfRPKb1iSezneE810f4yPg3YMCWv90A88eO/WJTd9MRfEB6IrfCRvCFSuCNY0euh4SjWYABdxNnWNZ5CLFlbUctoQbL/Imm8wfgMPixI9dFhI6YH/gb00xA9ZkIHZusZkWPXfQsi5CPFh1Kkt1h5zHCqo71PMErLPZZh0iWgFFOGVPJV4Jw5D2h2ObIuwV1pYUXx6LBKwWgewVl4kYbel9AG1z2pCxhLSoR9ECFtbGdA4CIhFu04rfOIhyVLxDy+JFhFLGeFn04j8yAMtSOgZ7io+clQJnBSICe8hntYUXGJHIDcA+uyYJqi4UTml6i8sIxSVwC97cDG0cp7JwDv+WIC/QMhJs9aSDZWRVjDMN8rZ+ZF8AuTAr8QTYamZxVFFgrtv103iVYZGNOYtklAtJJnMhiEHfUzrpjHyloNXRvMdMeqDposTRdSuOSwv44jbW5Q8dN0RX9QqgYNU5GkLpvbMYUhPDVc3NqR5tYwkdixnrU7NGeScgwg0KvMODyHS/EjFTxgnlem7iTckdBamPrYvbg29QfTLo99Ge079BbsGtlP+MDYpuoeimcmSiP10iNx8MTYsyEWoeJgduNEoN38PbI9JPBUPJMHThdZl6blBbTj0N3f/vCehzm+aMeH/Oz1bQG2a2xduQ5bJ3mhFUDy5uhgzCPGuGQFS0iOLlV0ApKE8ky1kRKWF1bUHbXBUz8rB+wvFBFX18Dm6e07hdUFU0J3ICzcaZfPEVSYYpAqSlJBjO2/UKWQz7ICDUzoi1umaU6RhKHTc1z69+4LwVBpnKzid5zypO1GhvKtHLbgrQrz0kNbKbVtazuxSXHYoD+5RGgRtK7JQhh3UO8YZNzfRNjodsDaomUJ2SXKOUIufMxac48xqVjHEQ0OtVzsgNO+gyU5YEM425xxryYHvE4FfZsM8zH/N6BHOWDecj18J1hhEYSYRkzMWiMlyizUMIBOV6eIhae+hmbU+vDHoH5ywExcmz4PXA4d2KKLFqbIQs+455nT/v1zKamIR5zGNCAjim84ziRmWeQCu/Yt0HDUC69mVt0IhfZCdgQp6jrxA7BwENvMVZbeHe3uWBVfrweE2INzAwnCO9n5ilmnrFoA30tmgnNfG+bwfEShDuOW3KwYYmXcFHD01trcppKAdgqdG0QGWn29iLPiF9CVQP2+cyuY677ZbOMKHE8rOw4iFF58wMkIne4MuTLYQ2/Y5IT9+mRf0+Zvrz8nTfZChbdoA6him9vRbyTqeRaWquKpdAKxLjuud1RKkRVDHZPnmerk/2o4KuymYYJS4zRiQZKQ/Zw5BpzoQqMqiISoSv0tuqJX8WqDT7XAkdmDc0i+iSUiUfCNeVuiaxAT29Xkt35aoNNMuIfZAFnJ2f45vV24FNoqaY1I+mRCQthBhp9giVghxwkklMaaPuh7WCNNNT9OvFxxWNjsBTIZhtYCQhRBpPLFGZgQ4mjw7IPQcxQB7cBDsduaxbJBMAYt3BYxP3FVVa9kkWKmjcnfabbCp/M22xBaZiCbyGoENHJHH2GT3H8Q2NCsjAJTa7iNL4ideTUZKu00cFEIEl+qADCM3Htd7ApRauwifyGgRUsxi0FwKFN2UJo36IYlg8KJxt30vq8I5AVSMdcQ0kDEtRjqYeZV2J5nY6mZs9RODNgWWJ30wVrB7RHgRN7BMoJmCHLUDUmeZCVT2fQKBEeDpStEaEBVBBsBPUJMwgA+MEbRjQvcWDENMSQSU/hYo9G35LPQHkQLO0KVxpWtVgNC8auJ+9MRnvUN5gzBmQgcyuFgSiQPTAyxK4/MhdiwR/mfjxCLiPdmppJ/qWxRpcTgMBpj5y2Dn6E5B1b4FQXcza6o1kpOhxa+20Ceo7KTBs3Qg244M5zAS0Z3bfV4X5QuQuLBYHHSELnM9XLHqwEOlZO+Uu2JgzyxBar5nXkNpLDnfegE9h/o+QDtjrhC8cByh7ItS+HAuX65fVMLQNVTMkyC9MGpgTQ5gz0+jNgURti2r0gbj9RhHAaXNskAlPymYEMqiZPrdJJwSxRF0xJTGZ62uM0GNDaEHYDdaj+gS8leWdbw/EZ/KxFAxsPVetA3DKuShQdwRdPo674gk8TqurjdO9J4Qwu3MQ9DVKxRWlfhUygQgGxpd6CVYZ5mYC1kU6PjJSnO0bKR69JOpBJCAuhi5iIjoFfpJ5WsoPYfv1hDXlfewLtbTLW3Lr1k1dFGoaPnj9uWDL3pf91fIJbPVlKAUIOTIbqLDtLy4CjultepuI79JaqZ/U9tbzPgBKoxnur8MfMTsfSTorxZA+d1KCc5Eic/YYu1V8hEqxSdwuLjL4EOGhpB02YQdfWRcy8MVVu05943xva4hKkjfDibtjvIE4FddzeLtx9Q+vLMYqTOo4b2GJFJT0p/IAmmtbNZCqjrltak9e9/FtAJ9zx0SJ27cZ7Qbh+q3kDBDsYeBPjuRwGS+8cBCvvHMIW3jlIrLvzK1t25zfZB2Eia23wGleOBKIgCeOSJFCKkncuyyugk9ydZO1svs5l6myOTuxfJcyssDlgeZVu2WAu0IajUBuMgm0oF26DpQL7wZXYd1dRN1TUeRV1XkXdUJFN3fBOiqSW93osXktmmwyZ5ZVbaUO5lTZYWmk/uJX2vbKvXr2dV293ud5uqBdgR3E9V9uLBDRA/w7Sx/UQobDV8JvUwq+fc5VIItRhM3J6PyGm0e2T+l93tzbLKDI3JHGq//2g/jfN+/8IBDajFISMPyycRuGg1vd9NoHdKEHXEA/yv+8tKMd5pdr/uFf/8aD+A1undu64zU47gew+qptFNtZOJRtp55P9YhBClWztWJcOQSRQYIbX3RiaAsKZCGp9YiKN8WHawzVAPr2XKuyrHFswdWQn3OBwwc1AxgPz1aYuZMgyhvco8zSKa+fjBiKQ2/MCQlFyEmOa5siOhRhnUZ36cqcN0rI/X0BErYaSJ9/wW2KXpEXfJlV5LiMqOfS4E9t5QktmwDcJEyozSSckZ5LQ0p8zwJdnZb6Ozsc4A8J9p/kkaWT2JoKTnt7ie1jlVQnBWydy2oC/25Yot7zB5oK8Wmtm3sJskU70cJG/gbimtcp+M1csDIA3x6Efz0ujclqkPrp+59YWrXlf1md4+2VH9jqKYRECEwTGtRdSacn96JLRiswbZQvdLvJ40xIDBlEFTJhVRyeyMUaN4wUtw8KdctiwOWUc/9ixt6NBv2bDSdbNbpZ3S5UV/e4Fq0a61DsaYJgtYZ9aECZhTss4ns6upvGdlzvFtuoHWrn44i3MgVmN3YbmhEtABTUJLHXf9JoE8jZXNa3MbaNqIj1OkdL53E4g2++88yDCW3e21jeutzE2VpmJrXv1TQ0NutsAZF4TcJpC6Qw8UJ4DNFByWhXbnfpMGC7Q0J3MibfeLjEqdjds4HgZ4Swb1aST/SiwVVMle+SpUj2cW6fCuTp5bADwuRbbYwKDTnypC1qSiDbi7E4W2U846X6zXN6TrH2r4kcV3S9V9LhU8a2Knkj8fv7hNDGUjD64EdELEngRL5T6x50Kb5H7gV7ubinFDyp0iULjFyqX/p/o9UmF9w/3Kn7m0Bd6e6C8SxU+PNwiy6bnhFXBInx/NgHK6/3oq3DjijuQaPQzNXjJpaJIGkCi/FR/+EiR4dOSKrx97mtg3Ra42aLfYZfuFRmryTU8SdaKVWZ3cO9WsmAT3T9RH1/6YqIuUAV09GjtzpZQ+g0ft5nniUVHXF505YbPdwSJhx+MG9yYoZnhQMSA2zmEsJ1TWY6KF5lqXVid8Ek/MzO+6NWiPXejWuiV1oTGA0feT7qcsbQgySCnSZxnPM1zHmsCZc70Ix+dGsG2gZOgC+4Qc+leR3CHyRJnPs4UD6RQTjWl+smS6NhtJMYqtHvxRKnTEntNKTbftBv5qKcOIGPxIDMNM0Uggl+3eQdVZnF+vMBj6NckCw0a37An6dp1JtI1jmMBIk9PLzgFAAn1uV9FTt2wU6idVDhUIDXeHnd1dUOcS2XP3C3CYrnkq2qbB7V5VJsntSGEJWT7QRNuqTYclwRqc8/RzxxBMxff5zloNs5HPEhRDy6Ugh5d6aMckvxpEucX9XyWD83rs77MFtvn/tFHn8VFt8vzvCNgcC4iWHK3L06OuxY8RkrLQpXkxx1xYIBmQhAjBvBBJY8KB/6eFF/cVcmzSl5UQiSHCku8dEj0iHSUAu+S6G6cqE9ho+9dNHLMpiCgI85LhF+vWUPSx+t1PV2PBgkM5nveJ4pCm0BgkYYXyrr1Gj2fYgKXKJrW3KdGQefQ/qa8mZEQUON7bsQGaJ8Xg3R+Ux6XQ//TiDX8G5UmJJHwffjxeM5U8nS5rbOFRvE3wMGFk9vLLR9h45Vxsd27P8drlyLaoCU+DGdGvs/cI+rMSF0r4/5yCumKbej5YPUTddTrR1eeRVnOECUzQO1zYqL7HbrW3EtA7dFmBqjzw/MwB7xvZnmUXuwHBsx8M6Mt6kgHJr2Msot4F+UDIZivuLCYAkhewYbbMXmbxf9vhvdu+c2cG+F130fbtusU18K4vAiIb0iTrWSWQE0H9v5s9KUffboZRIl5HMRyYkoZHtkwBMGIUlPtPygZ9WacQqKRTlKA2+6mxUzLQPJb/p1LhHApSeoy2FKfIRX+QuqP8xQf7ES9DHOg7fm8m8BrSHo/Tuqjot+Yb9aB0Ry0I0sizG7U0YtojqSf83gU1aPZdBEzb3+F0lznOKLmm4k7z9mgPb/I3EzZpPtvEX8W2FE7wGoCU38RGJa+cxL9G2CZMmJ+jVE3T2GvMYPX2JNZDLFY+j0zKCmi/UBe57mQuVLmF7Z+VbTRVxa5S7WlW5VmsJZ5pZPDeN2frTezAzzQ4uhwERdmVrErHLldCe7mOPfoazTMPtL7DGB0vMYCRacpgwyy4k3pWRI1gz3XhvbpMqeo9TwhN3Ik5fqSMKwH16LvXTTh4O1tpGKnjrX3H6O0qs2pKlsvSOxrQ3KH2Qy+s6XKoGpb3NmSL0TEUJfYYLxH1gfuojBRlMckn8SJwQXKhM0URbjB1X8MddjUKNIV57L2VnMls/cp8QfNFycnyc5DC1PXVb0YupofiTnu8nwR5LrMrE9R+06Z7HU2Cfa+W3Ht238fTBT73727oEgXOqE2jED4NQLhl304SP7bOF6s3ti4r1FQn5Cj+vI52o+xsPyaxqqvPqNmqPZp++9WLXWpW7FOO5W1v2c8fg9ZkeccX2cLMCAnyxneRvgoO2/6wh6vz42nC62hMkzopXu+XszL9egfV1k64cU20IP4TBt+OfnQnEfXPY9EINyHPaKvM5jnIzBNcf9tiofrHf4TqP9nA1uiaSnxeF4A6wKXDTy7vQCHEbrefcuvX0fo/yRYDtX/FTgBhglEUfJZIuIRvi3nr5YxFOAA2SP+9Un7V4BFfU9XO25lqOflNUFrgLBLsaj1glai2nDILAX0AC6bzHOI/HAd4ATthSyReZXABm8hVm6M5nvU48B/grv4U+S+tF4MCPzfQi5IZLy+zv0dzJYJLv0niyyNC888cpSJIZQosU8Y3IhC+7G1T/y31gRLFFm7K9EeoTZF5LJr+GeV98A+CzEKC8szUS6GQ9/HhjVw/tnw+Wc+Dm2IYdX0XcGuTQpLp74Nxfd5a9dUQ0MtEjseE0NBsxlql7BNqzytYKX5L/3CBhoXpZy5vlQ38Y1elEnWxYtiU5UqTgITxwt+3cGKB70tdman44JjVBuwORttkzdpF5f4aRU8Ybjg8jQkwC4bTrHChwyXKe+jUvcBG9OJi0C+4xZuWulTDOKUSSfR+7j7UknZdDpWG/rQiC2olrgrj3ghfvlzR72Os7ijvxaGS+IyozZQ5TCPHHNny1OMGzK53ulPtYnbRda1yKx31GwtbaHsO1jioeGiBiUpaqvxutOFhBXUmTJJEIHcpw4Dh4K6xbH7XJRDPvm1NZRwhhs3sICK/muYWaL2b6uijOKO2lNVxY6ecaY3bAuIxgs1H9CVyP/aoV7AJeM+l/AaFe/Q7Jaqo0cuD0KtLaDTUuvi7oC0lKs8GsCp5VL10JGsqz7RuUo6Q6MLUMHtEPVgY4hKE/ZRULZDuoYTYz+UBo6Tm9p1FV8VAYKKaAkkGJ8jrI1VNAio7BO905I8sy9dmZXVAb2hBklDG6pROgDTP2h1eWSEYwRAE1ouCOVT9cAfAEXZHtIQIxymmxCVAwngnBPhVOCnCoNFj8OCdxYLG/wCPdqOIUBDx3hDuZAsR5qM0lDQMe64+RQl/YDrURogwAN2ozadN245rskwUBzWGj6vFwPym6ij+QEUAdYI5qAoI80rG2laSs2iZJ9EkwiQaCDP1VbgugkAZ2qLjO/RuKYDq4FbtmyZKUdMK2qVLgW/a6Tcc3oaKUyeRbEnEQsoQqVSXQdBlUZngtgtQ78A+mLg0I9skes6AUg25ghYNx3DhwBlCMe5zyVbL4sZs3YdTKdLKS3PK9Sw4aZRnUCzDQPcAqQAGWEMwEX7T4CV+5pwKZtGkAcDxG0ijA1DR+qEtGxwS4XR8gCzU1yFYN0m4tmO0U8Yf5JU2+GNqQGohyauYKKpFzT/KPoTs5/yAocCjBb6yiNX265GFQMP47IIdRCQNHzT1rZTDY/0juvaCQFDzUcqrasYQpZqURn4aCz2S11HBr20QzEJaxhyNHYRGyezdKzcdph2TKuPKKex1IsGjYqzCLmXvLpsCCV4fi8Y7Jj7TL42GOOSKSi3QHq4YWoGKBKylQmot5CcL6mASt5w2yNQFtiXo75S8gBG7mOm5zvpklDauuOJHzOpLrjVAiJaASrgCA3qZhvHAkHbC0cyNoHgCea7kHeQkA3yEPruJDGGctOgmJbnQkfif0+KqBaggrbIJhMPvsJBMHey+PHywSsdQYEAL4hlyRRG1eIvPzJHPWhBNCG3+NgdGO22ko4JDs8oohsY0BhXyQ7KbHRrEoZdwgNMcTkSwKzMBk1vqbQwwuysgM/oHxZcux5vue05/6Iu9Dpl9MZswWrK434QlMJk4LWbk9MM2Nlp1zKG86BytCxqWwZG5wYBE5rxlaCJtZlRZMNZMPDopgYtNEoCG7sUHLnqrZ3eVF8FEiZVYL0A8oHOJSkPQZId0TwqY+NW4IhJfxJUG16y7HyiaVfyYm2AoNyBXYeKLZnfbCpgCa8e9L2TEaIWHKTU87XGDpoMZ83NbQULh4Wt2FjoNLIuWnbC7LjXHMPzzydaIJVSSnLg2o4MQRwywiv3RTOuomLmgmIeKV68iTPKLPOERspQZUyR+T5wywFY+Leuzh1DqbA0G1QzBWoIjXBMS0Ywh3OaKo9ASAhgjLFA8Jp4YiyDDHd+bCybVXSMwkYlgvk8ViUHdkwfYl4dwbQIl4BBAdiwztBa+yl1Fl2YYt4jS+dIZ8OMbcyUBqQujBcyIdtKJqJj7mAnlnkXZmeZKFY8YsIRAKKbSPBBFjFZ8DD2O272AZOpsUNisUwYjRYmIbNOGjswHkRedj33AVygQcGaDlIBcBVMFO1s3zHn0Ag2J5Z/4AQA/VePTSBy9JsbZrS4PzJ+AvEIdKBl4m0Rg5vJwxoBXNWmLeOmYaKtYdoztmT+yOiCykphGXkd4cW4QoDMYglpBP8tfyHEmgDkOAegacfrjKyWWlYsAlrtEYtP7iBWioCBegItywA/CmX+BjO/EyqyE8aFJCu9j2u0tpVp9cnLmmbqFzPlYHzNLeXgJSYJHAS7naVLtkVE3QvDvQZ7oRmzmFXrZBkt+sEmomgW1K4Dr20n1LsTDGO4bbidzDIV3cDrI2KBodobRqxPaUVhVyFqcuu442M8LL4sayx2cbXLpYhQ5zlNtYLRBXZIgXSfbBoWk467z2d9YQYRgFfJpx3x4riAY/h+FTlaWMgI80DSHIZ7saJgW+l8nZEWnk8SrnjEGTs50xZWCHcVpuEOgD10sWXEem4a4KyReiMQ5k4lbEWWhONP7k1N9CE6WgO0xs7wrALZACvObSfcArvGtBpfJcaH0QnM2wZGRjmFNczKjJOlpEbsrtZMcHpixFBhkMgMUjzfiI5sQJk2vAA54rThgQCEEhBAhhTLN6m1+yoihIUK0y8GBRMxZlQcFLBo85gzDU8cICyR4RFlIcAIIWUgYE7wkW6wrLQebXgFannh2LEBWJaF90D0ZVH37h5auE9KjPp5rNTPwhTqJyX7CTPW9LeDWcQMeoqfqa4QTG9hCpuLsaa2/KxyygS4wBgmDCpSUKXe1E8Y04Tg8rNNCe9+4v+AJ+WkmFyX6h1lUoIaieJMPXiKiVcoJl6hmPjJiolXVkz8hGLiFYqJn0y/X0Ux8Sp2OMXEqG9vdNkSU970iqDqpNahWn+q9Zdaaf9j73/E/ofxP7pRAYeT+gjVx6f6QJTxv8SvAE2LFdvO72IKE6+vHZUe6QNyxJT8ZHOsDZWtQ0W4qimu8CvKxHz1CuZ32cMyTPnCoTLBcwU3XOxdmT1IwxkXrPOWYix2BSfY8MCyEg/SagW7xyV75cIPfIDBfPUKthxX7MFlBc9tqy/63yALp8IPyTnP3vi8Y3zeMT4rHp93Hp8Vxucd47Pi8XmX8Xl3iqOGxmKvUzcecUkID1vxuoGxVph0D+iFlhRYjUiVjjDHNGEvvW9hE/2AN+q2PtFXApOAEb2ElL470EdbsX0vvaf3Y4zLw7BPcGDb8rBsCw9GuA6r4bsId3xfB+/qKTVV/CtEeXWwb4WJhrCb4QuJb/pkr7zjyc4TltRWfUgXKRQUC9H/kbAXqM1ewepTTA/dyWcnn7ENNRJaVfLUB5tK23BJZuynls+DzSyhng5wr3HhkQa3g31OttaJAH6t+TXD7ycHHzkBxxX4CSWxPNISv7tcwlo8+BX/X5waPubYynuISz3oXUPkJ4sb1Lqnrw4cZ8oiEq5zv1s39zjTXRV8cTBYhIBSgBLCFExNIPHc3w0HfBGNhf7ky+xVWmNdaCt62wBynJq4rL0KiG5vFw3AxoFl3WkVmGABdiWgBjdSS9tU+0VdJX+rD30ffJw1lMvaxFdRG7POtYPjjwaYlOem8pIshhAkDdwXLUD2bQBTTjCl7lcw7k80P+CLazdNS8L/ggNOhy1VprcUXyJt+QnjDF8AXkC8CYXTOATtVwrYhAOY2oah3uKie14RZAoHHqLMqJfg11YJ/6hNSOMIjzNVtaWR/DrsFRWW0mOz64KFYGxZ46g+FfUe5u5cPpzUxFtCszhOCBtNAwSib/SIHhn1ixDlsIX1WN3glicFpw01PiGqRr8Z/8IlVrKnTiYb/Bzx0zYHxB8QQwUsM1PrdlFra8Z7cNlAE5V4ht5zw+vgIetvfFX8sZsKGzfrogKG4+NZdxTW+Pqa+P1WrY8d9WjO5cTPv3IosSQui5gmE9WmnHpMLFTWqGyvsgOcHJpOZSeVZTuFv1Zlico2bCQzY7eKW/ahGKgshJ0MeFiEuYRPlaWUHJ4Uv2BHM6vgOxEmDdjdIlwxTvwhFopQhiY93PJwrbTWGqqSBGF47SHmc4OdFTjxgeMGdhfAm5ZISrXCo8+nMlSrgZ/EL7b2VsXs7KcWrwKGnf38c94OwzgXUkGcf76Pxe0hZACmKPwG34ccYq1oW/+HcU9g+I0vyuHNNg5XWAdL6XxrNODbxeOwUO4YjwPfQmjg1duwXL014nmUEILC4y+as4XcPq1SdWt05bllYievJM3gFeZwYWCeDc07b7lctLibft9Yd7GR5MHM+bDm7NmUPSzWc2aolUuvkNKauGdb97n1KZoKw/PW5mz0nn/p/SgfeGTWnSwVh9dP8XbKhvVXfhvZ0j4Cvqy3WY5t4ZXiLTqdrNl9G8iVnWwr+XMtn3UMeMKGBqdxVvXfTql1evrWSoEuq3WCe7LW90/CxPWt4opPJ9TcHK2pfuJ03lK250/8MY2TQXn4bcFiEbYRFlnb857DO3dOCkZKnHcCdhNpTjyuzm03m763LmhdZ/aVCSHKhV7smSddnYo14QQOdImh+gBpYZM3NjA+shERDTNEYcIegWKwWmC7SjGD1ceBEzMSfGQ/A7CCRJQprmv1UVcde4Pij3gUYJ0PGHZE/lF1bA0GZVcoqYOPciod6fYHNvLxEcOVQcX1G/XIXq1qkR1wWsu+6qCCfBGQZHnooYe0N87AoX5U+ontGr74WIAkt2p7p7YPavuotk9q+yLCR9cuDJXiuXBblrhSexaKi95hSpO9idnllXW+OU2WwU557004rM2udQ4RlnsTt/Bc2PgTv451xDbbmD/Tqibu/9i3jQgCnESX7Q3On4V3sOoWPqjwUYVPKnxW4YsKf6jgdqnCK9F316Pvr0c/XI9+vB79dD36+Xr0y/XoH1ejNc6Whf8Dtt8F293/gO1PwHb/P2D7E7A9/A/Y/gRsj/8Dtj8B29P/gO1PwPb8/0mwLUlGhp+hXgFdGBJtSsdS5vcqf1D5o8qfVf6iEsunDwzl/k7t79X+Qe0f1f5Z7V+I37USA4npOCSVeIW7qGOsbrE5ZEaRVBwMgt6rCC4izfD5oILO/4oeiQW/8b6iJxKG+xRBpsVtZczGR2I2SiL2SOLezEKcwdfupXRhNxsTxufBYTWEZQaePS8WOlPdhYqQelqXX5GXNGhHFV7o06SetprtSw+k2bpqCEXXQHsJniQFevXPVpxV53UG6S+M4/f9vdDRC+CkwoNivt5fAm1fGzxDz1QRHM8KP1bTMuby1X8wzIJi8bdlH6ZtOiv++0KAiuVN0d0UlQiatxcm/6E7pzo9YTB85hhJprRD5EnCk80Bu58qqc6LmUmzKdUy6nb/L3Nvut26jqQL/sdT8AW8lix5rONtbw6gSIkkKA6SpXTWyaHydvXt+/6/O74IgAQpymdndVatXssWgcAUCAQCgSlQmDNJNRstw3bWz1r97NTPFC9t4QEgtiH784gHMPDuRB1UMDbWUgy4aLJLYHg7St0WMOiSkAv/+72D7NTPjLIqCNjgmS1+xIKAlKxELhVy2eGnRdxSno/Ge4A/K8+9G927NsirFlfNcD1LZv+UeAwPZCmA8mqRSYvULaJImQItBV5KyM7GGnPBWoeEdQpvJ0Y1f352BIy41ie25Q5YSxWJSlCEA7byaYO9JAkdLYCUCbHwEho2M4wHGXNgz5uMOS9z/MR6r8TXIJrBe/YhXsN0UArn/UmC0Kjxs+cHHX9+nmCIp7JhvZcSxleHFsLKi8F2HL8NeeLtNazzYEUH+PFwxk9W8DY54VrrpsqxKK+ycsABW/c4S1CN70uW6jVM0/yT7Rt5lwvxMCSeOv/ARtwCmJdxlgKwUzeYy/MzuQLyLuAVFCv/cQaz1QLIgNhdZ+6kRAfFogruYO7yQmWyjKOy3H5toPiknDDuO7yaKvZRxbNtwiNvN8LYmbjBRIl9wzIpsNKcnDjA4SkVlAxiP7dYcoi93GJ+NtPmFnNuMecWD7nFYdNQA76KAUJhZDbApl67LI/3g0DQhcbDjeo1kd0HXqJ69W0YYkULi1neBilzaIYOh9UzNmIlm/N8x7VWYYxzvVWPRasBhtciKb0mZ1+LY9XXd7XJK371cGvwpm+nVtwgC3BusAHcdqhGmm9xiXWeZhqIkm+F8bOkPr81fcF0kau4kvHITbNQSS1xZkHETfz28srPG8f98UzmEGvM+CqIO45Y38QTttxKK7kPfAUWDObQKcGS3CTXlLLQqiaVtgkrQUKt6qqe+Bsd65o6UKEnFYrDOoxzjjGashxhhdmSKNhiDZO8vxHDqN8G8/F5Vfddq4jvOnKo36I+TfEmrDDrNJpaReYzSJrwRDjjzbKZkAAr9nXt2kI1XsNQd7KXeSUGG1yLvTu9EpfBP2wvGOxwepmSRu9HbaV9HEyKWtk34gnvqDDEZjDbSWTsaMTHC0X39L+hD/2v8cXPA33pf40vfjZw4GfNLvyuRszxdmuRojdL93+KiVkavRj2w+I9S7EMtZy1WAYDnV3WaTZzqM1msQzbXf4HSnr67yTVqqU25iX+gf+wfK+ehy7A3hVkpLHmXCF6s7CLMxs2GnqdhdzjRH8wzelpXhJhoON9Ie8o42HiEtonzV+ly6dhzK9t4pXsSg8S9QqcFmcWiGEfE12520U6LEmloT5pnSsazXEA11QtS/iaPLvw1Kp3GBAgPmfPU3voaSjmULw4DEHRqjcbZYQ8xU0YseyvUbJ0moT701NbwyYuCNJjyNmqH22NnQ9qaVs40vn1HIRYY3CKHi9XzMaUScBM8k3CpkPEJAjSQ2wdeLRtDAkQ9UrD3ylskhl0Qm6Bray8uZHR22JGb0sZTWseUqYkYiNTRtOaTwJmNZ+ETWs+CYK1zMYQ1tSOfXJF9DxFZ5iQW0BzQgt0RmIBil3lJjxDjQcFcAqiY8cqKsLY3h6yXQ+LLzDz6QsJ9/B7LjLyCjwVHgNYRNEc/FTpnoa9As9Z62lvaqtwT32eGFJ6CvN6SchmTINfiDVpze8iMqV+Id536Nmu94cITuN9i+I06ndITmNO2UZXutmeA9ZXJ8wzCZix0CRsykiTIHkXwz4KL+9oo/uygNlabcD2RPHtOOgeD88TwlNMOxjs3hKXvvhojtAZjmPAFMEBPqpIRZjA/LevSTnQKYOR81HPCDgfChFhMHhXODDSsDZEEnpb6WRqwcWRgk2hx6ap+CmkostJ0aQJhB1+yCm9zCHZqueQulHHujHrYDQaSRRKU+JJelFMR33Ks/cuOg+U/1AOZEpKu9PNCM1znYaNFIJldeYlrgCr7JiatFOi3Y7l940UBm2nvC2geaQ/6LPLUVKa3fBoFsEo/VxISkqajs0kpQefi0svaCYzvRB/VuGBx/nECHy9MYPqYNFnXroAF4fXyJiWWW95IB2C54lxsoGYgl8wWa7xQhRZNsBoOdFS3FRnKcRTkp3azXLcazJ9hhIyDAnfxLmVjRVtf5CRH2vldeYhalvmBbMUxpl5PtPAacLJADVPOA38lhLCvH9AChtpllFDTHkT92noYpt0OFeXtzzezlJ7QYtk+8WkS6WSWkOMiiv1YNJ56mnoYtn/VAZLGMSZbmHynFTbeWovaLHsX0x6u9RDj/OHy2kl7JtyfyHx7ZIbrJUtp+Wgb8r9w6S3S41IVJv6RmIb+E3Jv5T8mzauWLm40VQS+F07/0ry26XX4elWa3HQNyX/YdKlUlsaM/h82g285+HLAvGfzYREE4Z/UtrC7vqQc6iqSFUxP1qgVZUq6h5VpqpcVTtFI1xVqKpUVaUqo6paVQdV4Y1vVXWq6lV1VNVJVZ+qOqvqol69M8UfOFP8gTPFP/lM8QefKf6JM8UfOFP8k48Mf8iZ4g97aYbVIhN3WAjaqB9r+sfSz48H+j6o9zV9N3DjB+s9Px7JQ/9rfOnnfQPPhn34fYALP2t28e+Gnfy7Frd8nshF/2t88bOBAz9rduH3/QHeB/bid8NO/l2LWz6PcOJnzS7+3bCTf9fils8Du/l3LW75bMQjn7X1PZPzGVHoZwMHftbs4t8HuPCzZhf/btjJv2tx8+f9EYBH9uN3w/6NAPjzwG78EuE5ikDks5bPEyD4WbOLfzfs5N+1uOXzwG7+XYtbPhvxyGdtffb7yB7+XYtbPhvxyGdtffb7ID75rK3PfjfWa79r57eO9xeCvcBPPxs48LNmF/8+wIWfNbv4d8NO/l2LWz6PcOJnzS7+3bCTf9fils8Du/l3LW75bMQjn7X1yff9CaAnBuB3w/6NAPjzwG78UgtyFIHIZy2fRwbx71rc8tmIRz5r67PfB/HJZ2199ruxXvtdO791vD8D+MwQ/G7Yyb9rccvngd38uxa3fDbikc/a+uz3kT38uxa3fDbikc/a+uz3QXzyWVuf/W6s137Xzu8cT+zj37W45bMRj3zW1me/D+KTz9r67Hdjvfa7dn7reH8U8KOFyndjoRsHto4H65fv+9p+Nw8uvjjGZbth5KCRq4V26C/FXQUOyaZrb32FCbRbaZ1k8W3EX8hu/avZrW+tRX6D3Hfx/jiz9S9m5mM2X8nkeNN8FqMMeH2u1edGfT6oVWkMzJ5UvDAyFlCEMj3iBdEhWbW+WsvMm5pS66s10wEuiw+TZdMhzIemuGM4y11g+rOmqR62SR0eeG53M5mm8h7TMJ2VBZ7pjsgQTdSrhXhjOeGw8eW0MY6e6fB4toncaoqX+VLwNex66eaom/NsjUYSeBuX0Gu2hZ03eusSuL+ycstvNr/ZHi5nPC6QpeCEYrbZN9+S87THzrjNJLu1M9uOK/19s4W4/pbhat5EuijyutWTppyFjEmwgMh391qfBJO0t6IsrmcNS1l+Icsx+ZaYv/TllfmLKX4xmsdPCwt11/E99vyl+L8UaWEjeEjnzEJLi9aTld56WAh2cPasZH+hO9caputi7e0S49SVKmTxVG1pWlHCJIDachhN97s4U6GNWKqQt/L4ZWnBXcjVdrrEiYcJKfRnYNKA4AtcrUJrZYCTDKWG/lY0EAuds5yGWcQqQRtLavYY1RAsWGqv9Enew5a4EK5XO99rsRPQiJ3XK6db7YKr7XNU6b2Le02MRSKd/MSfuFi6v3jnWVCTsAlzLLfNCx2r7lrMxvePbcyODkjKGWGGak1aaZo77MN3aj8WspCHK3nOStJUhbCb5SuXkRQheQgvjbQ53qDlyW52cGVKmz31n9h2KhpACWwLQqZ3NFNMeb6IZ8ZoBgqPSvnwAd4eo8nqFt7rAw6t/uzkfANsut6LXdd7+l/juxYjrzTJzdb44mcDB37W7OLfR3LQ/xpf/GzgwM+aXfz7ABd+1uzi3w07+Xctbvk8KTwonK3xxc8GDvys2cW/D3DhZ80u/t2wk3/X4pbPI5z4WbOLfzfs5N+1uOXzwG7+XYtbPhvxyGdtffL1l1Xcq7iamN7uqExPLixFsMcXFtN+E+SfxFjM9o/KTW5n/g1KC+dA/gdLf/qfJrM/IEvNjffMsU0uA50FtjfjuVNhvxT58dsi70fJMVT4D5Bajma599ciP31XoKfrjHuLszrNirkVbzgS90uxn74t01dkxmb+nla34lne/8XYT9+W6ettl3x7CbesOanVXp8zA4UaN5JlZstvSsvuhAwCMISI84Z5FdQ0oNMQSkU0OY7q8FEIe/zCktGq6Nibw8mhC+4oV9U5GG3v8OXkrWnCS2KCKr/sTdAG++Z8yWiYxDwO4192M6Brwy4cvdOMZskHb9vopNKjn6YThmpzPONt1QF6BSCv8bOZJCPcMrPPYOb3KoelMJvZUtA31BBdKrsdMtDD+q8IMslh9I8ksYA5TSz4GjJSZSnltH6zTBYDFwkzqd1Q7+uyHLzFIdSKpm5e+KRcG/Eg8fxSl7N28Rw9Jb7KLrqgX+L7rAmPiNDl+ww2X7LINBd29AmxeIjS+dQ2nFQrfPZ9XSFKHsb85PRFH3FcvN2bKESGl1ZzNKA0sEfcca9scKZcek/ZUHoqu2uPuiN0OhqMrDPmCJcw0c2Fi0h0qdvuyJ3QA5uu1YIDYRlnIcxRKtvjxyPxXWP2REYOp7ggT8EVyAx6fQaCtKYxcXYOg8pI1p2RjJOj0XBTxrEcqkf3HzI3JSzQiqmCvjmSosgQqTyOsZ/EIMNQddiVpoxwBr0mcVaF+9EEBgywFHdrVW/ULskbOaUVpDT9VjvJcIdlmNdK96VGk/ekFQRourP6gKK6L/JOfSTHMDhiH6vAy+774gxzoh+XEFXTe/WBU+05LHxsiXFQTVNSct1QM+LZgSyodG0o0pl4B2QaEghh56T6QEnnvgWLEBYFPpewPhPPI/HWFH1EVNsHYK2zygXfXJqfHNzmgNvmp7ocqSpZTkXUNC3gbDKJzk6OxS6XhD1SUX0M/XTdmK4bonZ+ug+74uKhTJTAmZ0k8GtGTBcx1T6op5Q5cemH46gPj/s+2j0NFmdQayw6H0rL/aJ3ttN9+Ozt2mvMx6/YkLaeNVLNwa4b52Bb5oAJNY5D8uMs+dErBNdoLhm1E3WaoLWEMdRCl5B4roMZolHgfAhjfoAxP9K8A31MdC7ABII/+CfsYEzSzywbJJYDBfkoxdwIkY8JUikd+Bk/oxTb47BvTV21L6m2EnIu80nWYxOB2U2x74v8Up4dcnOep4G/8AiXWmHl6JsKgkytlHLrSeKaRNjTOdJZlqkl8Ri1nMew2QekuAjAb0ZljFdqPWZjkMRvP2OGwAk83TamZKh05JyVnJHxd166GzGqWTzVuWtjs06093DtgzH+R6khDIgZBHYe6HKkxiwd0CcNNxK3R9ecw9Zsi7DlvIox24JjSAmGxriQBOPA7NrvdJrlppn2pnSpix2u5SBjMWagaq9mhz+gbv+H1O2rWTz1+w3qHj3q/sXHgSkEkbTv07yF5TWMcTTCfSQ0oKuPSpcipmnoWEVnGhQ6rD6WfStjpRjXqtu8yEmIhK2GfTIaG/K2poGtIqD51Hg6aJ9Co873pEPQ8FUj+pE6zSyotkH7sMvytiNXe8YVqnxPTjdisedcE3fnbd7S+O0SNboMOVFY69ZMMs715wyAE1FAdo+HJUrYuaNkBoN/alrVukzbc6WPJQQx7BJRdYp8i30GvnGKfEhVmgJADHxjEfsVKtphBMvbSTxb8AipO8+Tt+GnRYvqTZkxrAuPJGICQjTRn8CeqZt7yYSoPoQjN35BRYfHgwgD6hj4NlLDOofXS0lNHW4Rggf9gANzSE6NjO/uzKFj/ANpMmEgOPaE2pk0mHyWoxRc6NKAX84GAxzVY6fbFhfEqQ3DsTW4EandKk3x0o7mc35eeWlhyMOUaFWfupTHERJAQsCUVFvSrNSuJe2JXQjopO5EX6aCl0MT1lJf5ruw0JOqVMKIPj7kSGBwr4KRRCqvE+q6QoKwKIyPK3uhcm+3KAh1JpFQdZnzMcNw5S3Xwb3j/sRQLgL8vje291qQGQFCUOPHEDpIFgP3wxuQykciyrmoj0m/HvsFJ2py6vdVQvSwAHTGpjH5UJr4udsVYdqMvYGiUOUJEKBugwiQ2gj7cR1dE9naY5ICTiZcCWHDLHTeeq1jGwOxK9tSnFLThJ4fUxpakHA8F5LSZTcAhqaRtHvI75oZpbW8joB9M2EYiVvrrW7GziHQzxyFu15mc69H9nPOoS42ivPXE7xd7AnQprD4jZEGAIsn8lHP4zLDqdcSaAYduy7Xg3ttl3N7U59Ux08iMwmhwvQkTEi3g7ypDUVrXcdj5PCoBElc5HhONVEC5osrZi0ryZwMEn5jkev3YREGI6RBlzkwToNU4ybh0UcENm8k5iRRqGPJsEDzjwrmNUnelyVesaNqxBkBSUrVJIOsBwK4kSu94j2QUAobD1AT87baS+2E/9B3qG1IMc9xR5WpmuPIdqj+3UrrxCZQh2A5ppDo/0Zef7FpCCebiNtOBF/i3IMj3JottFYm4DYnJY/gHd4PoT/MMSFmDy25kVuuWgk0nEJAROqmO1M86LHEQgGYnMZXElT5DJSQpq6bWZQ5kIock/QYekMaWDWelB3Afyqo43gZz7x1EW7zwUsCMdwTejR0m56BEF0IGCRUvhCYhhXQoklIB6ZwiJTUhM5NE2pxjTQg0XQe8UDtfUhrEeum1UFTdZkVIq6HHMGZcFCHCJvPXDqMHc+OYCMMZcxhJYBoztlo52jbczlg25zqVkHm1aG68IhTV+GAhxee5KpuqYOAkQXKDj/KXqvLxVA2ufDfn5mXSeiGe8v91G0GEv3uEW6XdUDT5W+jUven/raTKszCIJjSHNNREQQA0xzsTPJHGchxKIhtDf1voEIekPiw7UfUpgGmYX0J5MRCLTQikuWME4sajkvc52JSN7mCHaZ5QVYEEAYJyRXIMCIA1RNPXZbczqygeKHUl22Y/vTA6K4Wbvadl53D67+/oK22DY/yVC3lsqjAWJMLBhiGc/WptyHJyEZkZwMJrsHGLfWDiilmIWfKjoDEepeusa4/oTeJs8GVX4r2OUQ7D9EuY7Tc1iUMtjCk3JntFuj3GA9y0TSbPfRzcPUBXeOwJQdx64F49HCB8M/nSkuJIan2nBbOrFyPzp2MNOz2BTcDVrMZjZ1rRWHDewZu0Wfwy/MHg9euAAUzME6zYC/Y+eVwwODl/RxSMXRoXwG39j180E9xJ6ZrkR8sdmyp3+BptJpmaeL7iE3C61CISwWK+Ya7e2XWymwIW4yUePfTmnv5iBqKaN/h/IhD3fawIB41uJXCT27hIPcdHzShkTpN+Uy37+fj3ZMIOOk9iZEfpxHa/NP3xySw5aSY7iKDK62SxTV4i9dtUqUD07FOHxZUlZLfWiDkJfAj/S5S0vQlh4uhgY+yLzo+blTqEM+8w75ENzRym4VNrdK0gAly/AZ9DRslJ2ogmgjhKRlAtgLh2PBr8btNKLbAK1kVkhVsU+PxwbyEJZpOHB8+vqnF99Dzsq9uWftBSGFDGHOL7gm7WNYtO2HsdAiIz949FM+49yp+mMToznetjk2VeHHOd2zD20VDTZxN/+5E6c93k2w/g4q0CVxwVR81W9QfvPZmsh/DHqZzADk1pnhpnZhx2EsbwvvaRukkyoG7jYCOFiT9RmAnC2OLKtNovT38ZMEXWyafpJzhU87wuWPbzGMsL/cvGxUqHVRoyM2xukeTJ553yEAS/YTZGI9cRD02aD1FprYlRJAzruERxza8OF3Di8+2kHjGhhf/tOHHOEPDC+h2w0v4uL/JZ292daPjbKvb0EGwfF2aAia9Dmt12LDgpJkS8htCat7B8DILezbyIgZ2YM0npw60lVOs1UZVD6p6JGLwI9Www0CVpVqIS6BYi2YgOwTWFn0jQHEJtM4avM3CcOf2MIlx6IGnK3HMA0enq74zAyRvMbKx2sjh9d0YVRJ7AFICG8qeRIKmKX/IRyzVTsTGWGZiYPK/gel/3sqheZfGsbmIUKQRVGQUSRc8dJjbY5PWS+NHlWJDjiZe1KB9ROqU+rgQa+ZQtj5KDT2P5GzDrUe9N9YcNdGeZ4thgFuYKEUjmNpVxrqoOxDLNoTvYIGmYy9+bZyEKvVhGt4D7+xu2jAUmQdlHpV5UuZZmRdlXpW5X6n6Hozc1x2pASWEYqWpts6DpjE4jC7eRG9xOsAi5NONemREo1tO3Zy/maiHMZGw4rd3LxfeS8PuFYZSHv40xZZxkLuSF/KBhzzwuAm3Uy7tJPepmYmrMC94UC5h7wwPkX2UvGgHa1Uww8/9lVQvGqXLXNy2Q++c5CHU8fyqlQYcUWCziGnfOlBiQVwGzi+kOGMsophmuFOARcHJ9hEPAdiyxtAJgHpwTdLc5oghlP5pKlRwz9RD2er3sVj1+4BAgtx6RKXmT4co3+TzVy+f/2ea/v94vvXEB9HRmPwTjKtJr4MZN6sV5FYrcGNOhOdR8DgKduBoJG8hcXNpohhXHWILKkN20eQm7gu4sKAF3FtFrV/oz95PMkBcfNCvr2GNA6zWBtQT2WYYCtrn+jhimFrm5sO1pHPIq1oQrqQAxTlk4NGaHUs9sZ+OYj/1xT5LXe4J6rPHI5qjtPaC8LArqzdW62yJaNiGw8xzhc61D9hQHdKJEBatmJqh8I26Plm7rsWrKqgXl/eqXKtyo8oHVT6q8kmVz6p8USUFr6fBxePU/5RTbyclTfNpneti27VqH1T7qNpn1b6o9v5edWvVbVT3oLpn1b2o7pUiif9RdU8MJdBmxRGfvFgPK5f20YMSQp2X6WqUK0IQNz/AtEaXeNsesxq4shpYs3M1jSsLTrAzSRO0Y74PKqohtEe+KxnirmSIu5IR35UM+a5khLuSIe5KRnxXMpS7kiHflQw7hsjDK6F9eCVyD6+Ew8MrkX14JXQPr0TDwyvh8PBKODy8sipDmLecYPcO7N6B3Qdj987YfQC7d2D3wTi8C3bvjN17xxDB7t1i9+Gwex+w+7DYvTvsPgbs3gfs3gfs7u3sGBdjAhoJ2bxKPkBwT0NXxdkGvfUlbC6y+zf+UJDEoZGJwtRPteJ1oCEHOddICEIXs1dK3suclBQ8N9c0uW7U+17reriUod5xFYQmvcQFZ/UetqwlvJu6Nm3O58PeaS5VydkP01NQoiHViHp4YzQw2LOC6TiOC6I2NGknAfB+hk0BQoSfIn3PKxqWoZK8E48BZ8mbYHEmOIQxZU5yIRHbVTQuvJ9CbNxsQfCCJnvsDBOSOci/oeZBhj9huk5AUsDOnCVHzK1RCB4KDo/85l1Cgla3/EwejXuoTExze6kL1RTH6EjgmaKXlDWhwaUWpGEBwPYeJDIFsN2o9y3NP3XD0bDMXm2pvd7rvslBULSExIfhv0RIU4QnEK40iS44oDYVMN8atsyB2T9NXAnvmDR1nBtEzjB4+r7FbFfyI07BjQa2IUiI4jY0CIonsynTtBB2PoZt5xrqhC0WoIk3aEAyws9OGyk7pGeUe/nwuJS3mRQwsfTzviVBneD8GSHy4aof5BUeNITRMbRTTENjX9h2xouXRTHkBtWvQ/viYDp1nkqonPMVMmoUmn90VsHca4gu4ix5uvRdf5J61UqueBi44aan8aquQ7QoaUqC1zuOQRZa+JKw51qmpOiwI9zCxKbFjmPmwkOY1mZ87Yn5I6eBLMZMFVxThBFxkeVIzG7YGAM3ktxToykeES8YXn9SGcROzmInY7GTQ+xkEDs5C5dMu+N9/EYjqYr/5dQrYi+IlzrL44CNA8lpM+S0RU4Z57TlnDLktJrF+i1laBnabRJIfu4T7tJ9SFqc2sWk6asdaXSp2m3VjrTqXO12ardXu0LtaPJUqZ2hKZTaHdSuUTssoKpdr3ZHtTup3afandXuoiK5FYaTdyqLVZYoHPlLVbYlTAlBle1UtldZAQu0GVWWalDjfdmM0Cftherdq+yospPKPlV2VtlF/QCaVP0R4SJSRayKRJEoLFJVbFWRqSJXxU4Ve0UCsChVUanCqKJWxUEVjSJVuOhU0aviqIqTKj5VcVbFRSUO4QUi/Jco8IOJe4XyIVKHmGb96qDVIVWHrTpk6pCrw04dsGigDqU6VOpg1KFWh4M6NOrQqkOnDr06HNXhpA6f6nBWhwtmXIKyiZSJlUmU0cqkymyVyZTJldkps1emUKZUWK82ytTKHJRpFJaxO2V6ZY6K5iDmU5FgNYS1fcrIo7EQeOuI6pPz12mZ3mClX6PiFVL/f6di2pAuBZtdA8ZlpMpEkfJVpqrcqnKnyr0qC1WWqqwUzc1pdlYeVNmqElceVXlU5UmVn6o8K+1QtE/4JfycX8rP/GX8zN+OX/or1L7kF/wMvwN44Kf8Wn4QsHePBdrLV85IKtYxe5j7GhBtI9UmikasNlXtVrW5aneq3au2UG2pWqNI/NKsq+1Ve1TtSbWfqqUcHYr/wpaRtr8mZROpJlZNokjWN6lqtqrJsH3Y7BTNP5pCNaWi4ZK0w6ZWzUE1jWqwz6eaXjVH1ZxU86mas2ouxHYW7TpSdazqRNVa1amqt6rOVJ2reqfqvaoLVZeqrlSNzVNVH1TdqLpVdafqXtVHVZ9U/anqs6rRhcKqvWtpAEk9pP+FBWQO6X+hdZRsNhT0kepj1Seq16pPVb9Vfab6XPU71e9VX6i+VH2leqNoktYfFI06NIskFbLvVX9U/Un1n6o/q/5CLG3RBWfFU+bKrvirYharVXtQbbPMay2heyVXT5E6xeqUqJNWp1SdtuqUqVOuTjt12qtToU6lwpzSqFOtTgd1atSpVaeOZpnqdFSnkzp9qtNZnS7Uqy3C/0IiZMujwVekvmL1lagvrb5S9bVVX5n6ytXXTn3t1Vehvkr1Vakvo75q9XVQX436atVXp7569XVUXyf19am+zurrojqH9SVSl1hdEnXR6pKqy1ZdMnXJ1WWnLnt1KdSlVJdKYSe1VpeDujTq0qpLpy69uhzV5aQun+pyVhdiZWz5tTXW2Uac/4VycutwhnSMpwIyU2V+W0w2y5KyHLUEyToxXQENmaXDjymTF3ipexfpjn632O6jkUpjF2On7eG43YUD+QeHTnC22eB3H5JGiq26MqEPIbGjLrX7pPHNsA0xjGzkwdvIktCuEeDIEDYQd3jod9e7YvC4+y7GD0GQh97yKyRREQ6aFGObMbaZYJsJtpnDNmNsGc1MsM0Y20ywzQTbjLDNCNuMsM0cthlhKy85y9KOYJnZD5DNHLIZkM2AbAZkM4sstPqcUkKp1thgIA/N5yWRq300oUXEeA0+yndwEyojfABfKYBMk4JpUghNCqFJ4WhSME0K/hGaFEyTQmhSCE0KogluFRREk8LRpCCaFKBJMcG6EKIUIErhiFKAKAWIUoAohRAlkRZM/Bb87+c3vwX/CXZLFlswmbVgMqFFMmnBxGvBxGvBxGvBRTHIhDkwYQ5CmIMQ5uAIc2DCHPhHCHNgwhyEMAchzIEIcyDCHIgwB0eYAxHmAMIcJqgfhDIHUObgKHMAZQ6gzAGUOQhlcmnG3G9Gw9gawdYItsZhaxhbwz+CrWFsjWBrBFtD2BrC1hC2xmFrCFsDbI3fjMZ+gKxxyBogiys8Cof1kAUju9iM+awZ8wkt8kkz5l4z5l4z5l4zeirOgkztmTi9EKcX4vSOOD0Tp+cfIU7PxOmFOL0Qpyfi9EScnojTO+Lgme0exOkn6PdCnR7U6R11elAHNsgVIMgD1CmlKUu/KVvGthVsW8G2ddi2jG3LP4Jty9i2gm0r2LaEbUvYtp84sWaxbQnbFti2flO29gNkW4dsC2RbINsC2dYiu9iU5awpywktyklTll5Tll5TlmNTloud8Ytp8iU0+RKafDmafDFNvvhHaPLFNPkSmnwJTb6IJl9Eky+iyZejyRfR5As0+Zpg/SVE+QJRvhxRvkCULxDlC0T5EqJ00oKd34IXxvYi2F4E24vD9sLYyo9ge2FsL4LtRbC9ELYXwvZC2F4cthfC9gJsL34LXuwHyF4cshcgewGyFyB7scgutmA3a8FuQotu0oKd14Kd14LdXKa69ktyIYNVGwavZ/0w+y8sXk1ni15mB2R2QGYNZ3bgzBpkdkBmDWd2kMwOkpknPbycKuRUISfDOVWck0FOFXIynFMlOVWck2jVXh4t8miRB9/Npq6HPLCgjY73SaRHHq3k0Qo2o47rZVQioxIZVZxRyRlVyKhERhVnVEpGpSzRYZfq1PCqdoB3de5wxBk3I/WnCu0JE/FFfe3g5kiNZt1Yh3dRQjleYj1jTkGERdZJdhbEcbqsL6MAz3M3fmAqbmtiZV/1eHiCFBbciU9UwQXTfBpmBmZ5c9AEAbH4MIvmgFfxpPx2WjLN6myRBba1JaKDyNdBaWZVOJNPpoJ9Forz5dftz35Bf7ZV+rPNrYMBFvouYSu2ZBDIWHvZ8HtHlvbpWJSAbVWL4RUfovhy/jbomia4TWEtG6C5hERcggBcOMacMYIljDyo4WLmib4moh/495FsV6SdZDJCJyVYO28OFUvfC1c3UWe8osV+Jnfq8O1OWlfLlXYUnbeqj8z/5TX2fwoH+zQNpFSbP7aJxTUJ/IaBFshkGWUCmmHmKGF5bAadImijLCNoA0cEZ2mFtmPiv1pmnmTC8iHBtp2X0TmvPF/jcromhS1pRhB1HnNVv8/Q8gocMPsP14Uuv9IUtpAIW/ps618OqOBunM/hpAl5Pb2tcfs7jLGv5ifyOER62HKgFY4iWm+mZ4xwhMEF2ldr0kzrYjlkASj5C7veSujHWQr+g9S3E065MSQeW8T7k43CDwRZyEjCeVxayuAmsVzz/sXvQ3+tjBWDGseHrFyow6IMxHBkK5V1koMTSfV9gCcGi6HDMWcEPruJILMb5Y0P/LNNTCk6HryInZSelDFgms5ICSaGGQRSk3sNi2ugLVMpUe65pDEf7bs5cCTB6PJSuXL01BtLeVJQriLZ8Od2+WXEuY05g/1cWqnUnhHYziuw9d3TCmxH1xgp6OxbT3bALF0rD297VVurziyNhRK8NHxKiKcULeR4O4Vr6eUShR0+PRlwo5wrMSP5ygmlA0Wpa39sO4u5DNVg4g8hY8fJEpLRV85sNn091N2DcOfz/FJVD+BjMlPqSq5ZyY2iW9tclWgiPmUm2okFeX1pFnkSMkHH73++G0PIPxayn9d3ovtOYdflLDXn0KUXWMiFLTSuDdreZKbbDMSD3rflTmNwDo07/OmwGQDBfMQctGnBaow4GY8llbwH6hVB7LGfscR+hirHczDmtQnEK/W6Bha1g9cvmrlyv5e22jtGQpU48bVCPCllQkk/JLLC9zooMJUtYCGIOPAzxxFDNj7MYnuhVJ83FuhwI9/ppMFv18lUaNS8wuH1swHix5j34qlyHnpsMaHihCMs4qX7LhHXF21z6l6HgbxxvZRoUtklui1lRoQjRVGdv8FGBHMEbW8hcGS6vy0QZjEml/p3KvVvNIaOLW2VFZ8XJ/T2ovrwxejW6WyF0gRhQPPPXJ2TN109RYafaBzBMsVu7NBscx9GlL9w1IZfK24GLaQ/jmJAMGMFeTrLaK4iXaHvR5Ju0lpFY+wtwm/1RHGcSHrAWz6wphpl3yefdp9xSGipJRp/sYJUE1YAC6bkQMPDSMPDVO8rlmaXqvNVgM7nx0IGXDy15uYbBU/kJxAbiS36DdOSySRFEjFoLvCg23Il3njYtdfyVOQucKnI4qzetk3Y1t9FwMWyvXYx4iFGPMSImr79toymj1zwzyH451hC3/ATUbJ+2KrEhfzAO0AXbV9rtDnY3Svnk7AhVxs6+LWmPGSZ8y0t8uHpR4ftJLNollk0yyz2MmstbpJpWOBEY8gnHt9KahgcPbwT1iS+5cFSGLIVbqzaMa+9PGLtAVwSL1ub/HdJvreKrnT3Ns7b1hBL6BMFsql5yyWBO+yq08KYZjloTGSvbw7LQVLY76VO8r5UvwsK/9F26nhqeIpb0LBq3P0/JyH8wKNPmb8GfjLRFIy9ijOU6aj3q9lEfDWJEe0sop0gatwLhRx4tIFHCTw29rS8qjPtngxUvY3U2xxgF1xCWhti5YqxpjEX8yYBFO7b5SzfOry2XtyNRHeI3M3bQf1FKKv+4tf+6LWkjfdXG++vfryyzUI+6VqGTeker7QJPm2CTyG+x7KDfenwFJ6Xq/5J7V91BrKvXa7/nxDDSUUvoz/ZaH+SaH8BI00z+ncb498lxt/bKecu8+dfbKK/SKJ/UKKTxyH1nD/9wJNPsr/5jFULf9Y3+fNWNmOMv/vZ8T20esKSJ4v4SRA/gBFhSP5zmZ/rCc/NEtc+z83aw/GcR8mB6a656W+WOf7mk+Z0xZyLTFc5phs5akwoY/vwOi5j+meL6Z8F079R2/W4pHNnFTKJ9Vcb668S638hFg+Nd9P3u230/22jGxrP6xuygap9I6hzJ3W4egZvwFrUHSMt4XRxfLIUaJxaQ/1hYMMusdMySfJlk7zdlgfG4eRIrhfp7NrAlpqR2mHfFqm6ANEsYZYCmCxLAUyGhYDb6C5mY0m4FOR3oaWCbnKUi4z1hW5WNwubVMvCJjUS2C9Uxiae1cNCl6pgc17AnhEYBC5sd1hW+Jtlhb8J9/gScFZjLY/WSLL/ZSXBlAB+FMfU/xBFx/mGF1PqMcz66inlJplZrvzHRKP6xzcF1VOST5D/hxVVtwXTPOEg2K/gi81gA8eGuElVDrBo/ccSTb0Irmp/n1T0774wcKT8398Q1s/REvLvE7L+/ZvSpmT1sf/7rxOVQ65IaqGLXZODviHnTdXgKJcEaSZVewK69iSy1IgfAKcMWIv6w5o43CfYLuNnBSTbNysKmiZ5KjCUJX8wcblfpB6Dd9IeLtB6/Q7r5ecod+Js/cz/c5r5f06a/j8nRf3ntKj/nHCCVw9RPWzJIkZn47uP5ST2FE9J9L+vS3DTCE7Uuoj/vpD7LOZS/v/HJntLzlVY5jHRrTEntuVgJ0zCAEkaEgclLQ4GJLjBRCBYC/0kbkraHFM1KtH0pLhNJmWJ5keneBVcLIgkNPNNcH3tjW1I/KSZeqnCpeF0GLC7vOjUzmckF7SbjUmTWALJ3R3Jt1TOdjjD0+7yY1AZmMKxqy4oC4ifsbfTyILe3wfomz7riAjUjnppX6vKPtWsKo7+RpQJy3MwxHUvOXNowTNMlwJb9oPbxaMs3wgfManhQvU4b2zyao/NBGDT2uUYOy/Gjh/f4lMfQUSCd+8aOh1m0x+tPH4g6U6YyNoVHUBtaoZXE636IzhRfuoDhgx0y1u8XKE0LfrO3pP72IYXvdSGR9dVJop/stSmJxf1cxJ11tLJJLEDeZHQ6NxkpAho0tDrPk0pSuzoGbd9jBMLb8zNgY2VEQow+shrSTm4/U2HNMN/YyZxaUPXFqFti1ZF+XaL71uY84sOJ3eX9ifKsTcnfyLAiiAnUVuJcQV9s0aP8oraBWsgn/x949uZ7k1yh1DuFsVyh1mEd8e12gYDt2TcyhG/6b0A5x0+21W2LrvtEGvLG477MVlxxhvC2+HFOOr4Q9iBw6J9ThO54YVAL7NIJMh2CMpcY+AttqButJzBMFsNwUGsZ989wcobv9+hftr3PQDhwIEyPNOjBnFN43rA3ok6sT4CAx3SMDjJkIaNigsLABKKhEQ9bFQzZOttcPL6j1yUjX1f4IRijH7TBuE2hK0AYS8V2zdp/KLVbpLbD01VVuHY7SJcVhV7KfsRqhmj3IsW4TE7hi7pvDtsc3sdBv63CvPet4w4lrj8M6YMOKu3NjN9gWXQLMchIBxqy520pOz9GY8XEaVisc8b7q9CB5AVqBghSxqQcqjqnWlasyA84NC4RFzYNwh4Sh95JXWnXG49vwlXRCY5T4sACvyoVwse4yMv0IVkJYr6FS5022ev5JUreXfqmSrEgyilMvHVFAWnBacLJQxJAntoUpMUpdbUia7xsfKciK65rmjFMrKXgQkxWNwKqURc7IflVKKXpjHZ4GDpm/14VpuAG5ZJ7fsKd2u126jdg9o9qt3TqLL5EQZzRNWTqp5V9aKqV1Xdr5S5snizkqe4RSzZh7hTjR3InO8f29fHGkJBxcOTAvaG5hYPM3XDcsNwKhV2dygWBU/yHZLvb6QrpLRIkyIwTVroi0WFeKQxWPPhvVPqv1LW2Us64kkVGWI07oU/dH295bfhZpkl7j1Ms18Kfhrq4cAsSxbxmqKv22xiAx2PzR25CGzxDChaM/QMc4UNJo22BYyyCct48X7YboOHHjzw+1KDzNGy9E7zNhNiJiDzpOVJ3Q+Rg4R7DcTYT0PBNguJpvSfhjVTDBYy7UC7b1AaGGMKvq7JnHHsi49iCmqpuWNzg+OuMJrHiJfBrdc+seU10kHuRIzY92Z9Oi8HVt8FNt8Ftt8Fdt8E+oZninBrYNk6dlwUXnpVRP3+rAoS21oVNgp0YNKMSYXQbUdRLjBUACN2uix2uJl1yTQOU/ORefFQkp1ujjkubO0pZbHrk3yH06rntoCZqaLC6xeqwE2aojZ7s8OtLRKr9KFZyxHXt45NntC331OUFEY0VEHaBf22Gd8La/nuVpOjmBY3ys4INbmCnQRcMSykk5xpmlOcjVwhQw/0wKQHisOFDQB+PWTlvYbDNIrPkKDDPUW+UaQwVppthpVH+s+x7UGeWvP1Srzxo/meMF+tJKDmO8KwroSrlTpVBjeTuhYLoMgEdTFSF/Kd6ZNcLoDH2QkFnnVhmr5t87C663FopIJRKtzkxFYMzQixe67MOOWhYsNCXhBajRXoIyv9J6IEV54Jd6pRjRrVVKM6x6I6eQ6arz5TNjVqhDvPqGbLl52pHrjUUaMeNepRox41bH+IIaiaq4Rc3bOabNytvlmfOqFaN5n+w1bQtj8kYmSO6MvkszIOL6mdARsJ4ksMv0/M8rWl3URwVZ3zcA9pWfdhnJGSmpUyKnE6Ug4qvDhTkYqv+D+Dh/4/8SUyVnGIGbuqEOsCYMycQC6EJoDgBZWGHEfOCCn5J6V/gA/0f0YQHDXyZh9cScGuggvOVFXCxd4tEiM1nmvhq+c9rpsTg1bgT1wx38LC6F3Epjh2bCmiZWsSNC9Aa7JpI/tuOylLvJ7oVC5VhzDzRhxix7wIj5aq4vMUfJ5Udi6KMOK3J6HFaX7f9//bFQ4aUbdixIlIsVNbd36aiLnqDN6llgYhorxF9E9N8Ua0fSMavxEp3qDFESl+wE20pyko/RAZSXVWbyTh3uAncr0R7d5yN9U7Ewe85b3nJTf96RFCTm08L7npL/RiwB2qRyYpTBqzrSHcSjnBwNOAeRiqD5iLUu9Up3fC/Z1wfScU39Hn3gmv9woe+sebR4ARg7y31k11eCf2eqf6vBMfvVPF3416D3v1TtUiFYNAiId/rd5zyg35U3BRAMbvJiGmYTNCIZYOxDjQFjAYPmIwpQNOPbznPFPPbKa2g8lGYrK3PclDOJ695v5h2MgONfc7N/cPbu53NPcPNPc7N/cPae4f3NzPNLuqRKasqnAblD31lCZ3tDIqqVVSqOSsEqiNoUp2KokUHvJJMP9TSauSJFFJx/5eJbGCF4+aKswHqkolW5WU5KJIFAv7KtxEZmcSFZZ9ZhqF", + "p5zwyfc5nnruuz4jthprFqFmEWoWc80irlmMmkWoWcw1i6RmkdxFMkUgL1K7qvws1U+qxM+GptDkO6uPUP1M1M9I/czUz0L9PKmPXP3s1M+afjsOq9RHr37uyU2eHfnPlF59wCwXp4oJVKmfW/XCdaKB8gfX4UdmksTQXO3Fq8V/wVLbSxixGUhrZY/biWbJuakhWV33zzI8f9QrnStN7K0p71RRD4m2fRNuEU7cGtFvbsNcQEmQPUHyg3UUKo8cbD/CtqMzdcG1daxKjBPBPif1pM9HpMrV6p6garcOqI/sNgHpHvnTY8CJX/FV+fNTsCdJmT+8BHir7/75lWKFKlutHmhcoekcTZBpRhecen4AOTgh7f0LfWm2F5woabZ6oEhI+0qAPqe8NhScU8DTfXA6AvBK3xBPFsOhkfszqXSV2r0EMDO3ewXbq/yRvjhoThmVuOV//0iOniLkL4iBC4Gr+xVpNWp3T0MhKhYBr0eC4Q7h6vWZHARYbWgaTrXavNAXiTYk3gjfEBVCiqdNgIqsViTVQBImwXOAJM+B5vyB3iN+QSrg8PwSCAavxAYqX68CEiQUseUM10HLpHmiL+VCH6YN0bNl2hAgB13XjwGe3HgKSMztnoOCmuTlgboI2mITYOGPKl0g7f0j+QkjqrGdHqLwJzxIQAlxB/8lSHqmTYLa37+saCZngFKCotfrgDRHanZc3n8gwUU1uQ86lPT4SF/QicCM5tNrAKu765cA9pFeA5Kx+WYV7Ji6z8GOq7ahL1GLwJKG/Mwyj4IfPKvNfXBmjjszx52RweqVVBYgTwieUewDRQLF1/gi0QPNtUDtlHkt7ZnYKaUBDCk2GxqjEfWF4EzPZ4pGSBKHpyFahdqtEo6qhKOqHhx0T2CwFFWQH1chfofViBWhAFMW9y/k7+Ff4fAcUYj89HlYY4oBVAnO5W4QnqMTvCAIaah9SFcAdivctUSsZ9iAJvpScvDK/StFASevHlAOuOh1FVTbrfQSclAVXtZwgFD3j3ABDYoOF+XEDiYWJzTcS5CQUq6fOSXYiurBjcCpiOSjF2lfNqOXWx8I3N8HKP7pJdj2jBeX/PREXs0stpWu90DJmPEfURz3y2e4eq4yJSc1On99hUKSU0+swZL3pE4Be3yBzjqohWeeyMGPmgekpgKwJgcaYg0HtwSJhkj4+cW6Vs8IBIgd4PEHfKkgRO4h1u6lhoiWrx6dh/v1evARU5MshJ2R1SschPHzA30pgwd8udjVC1xEH8RABo8AoAUegi0jTY2yZaRJam4ZaWrnrSBNkm0bMc5EXkZ1hS9wvw/wANea2j3hTgaVmBi8SqRnVgn3MsCR/olonEhVYWqa+iHxCfrlK749S9WKOyZ1n2rHzbwOjtyPjiHT/tizUDlK5yMwd76H4Cii6ZkcEF2U/JxzA79A5+QGJmY7owOtXgHjHgQQ1KPRfGCCkVTzSJrwSKoxkiYYSTWPpImMpInYPB2nJlVP7dRAFlWtOtC/sabTMZPMTA9L0q2SO0HOZwbr6iOoxAQH68KrkOYH5bhkZxXNIqdROAnxbocuwrBUusxz+qXG06SeUrXzM3V3Tc2tIzgajN1KkxzCSE6VS0hKaI5zwio2hIreh5SrHe93nB/u3GvEPIQIo26lK34ckWJgnqSPeBwRDvCGvmBLDSylMaucrn4xzrHgHDPOMeMcE86xh3Nc4zguHIQznqIgnEkbjElBA84xxwHOMXCOgXNMKJGCGDPOMXDG3CBmnGPCOQbOMeEcA+eYcI6BcwycY+AcA+eYcQaa/qTn6WhOuphAtkTsyq4CwyjzUxaWpLc/wTgo6YVVNywOD3H5yPxVYNXvaQh7Dlsq9OJn6Gl2b+DHN/DjD+bHN+bHHzkv/BM//mB+fBN+fGN+fMrtKo/+JEKXXsbvh163o3fFL0zQ+H0OD451UVyM4hIuLubiEhQXo7iEi4uluJiLi2HyN+GXASgR3hRAKnyonvDwowKSEl5Oe5bE+HoPDHDJg4cxGIP4cPgQhiuSQxCVMIagnDFI1tYGLwodfTzvsb1Oyh58UvgYyKWPofnRD0T5YxgjMAZqexnd+RkFr1Q/spDRxwL0nKAx8TOFp4hMgoXmc2TOM2wmgCLcZ2pLwvINLmGUN8sc+7ChuRRUgrhudJp/Yg2LWKAAw5TMMAUzTAmGKcAwJTNMIQxTMMO81UUYaxgsxhZQ2oRydACNYU9Awmx/keLSJhrBAlucvaeRbIrScHowGFckfIq+jRHG+qxM1xnYiL5ifY0MUq6J5pqwYVeNmqRcE203obgmGqyfCuunwvpaWD9l1tfC+qllfW1ZX1vW1z7ra5/10wnr6wnrpz7ra5/10wnr6ynr6wnr6wnr6wnrp1PW11PWTyesryesn05ZX89YX09ZX09YP52xfjpjfT1j/XTK+nrG+umc9fWc9fWc9d+JN5qwwwLJyDRuRCe2qJktDLNFDbYwYIua2cIIWxhmCwO2MJNGM347mQm5fW2AJu5+d+BesEfNMtIEmjAiaT2xMRzi/YAk0plKSGMqVZLArBhGx+QSkuqTYEkx6fBzRiSMllAoVFJy9AoPdCYt7qckHD9FrDYk0XFA1Ia9GYd3mndbkYvkmqGsBHEv8G8zzsEZBQRSBedfINOC83MjEwcyxgVyLCl9AQQLIAi7capgBG0GjGCB7CUvIMgZFoJbAdzKjDMAbgWwKixCXZhjmZFL49A9StqjkD1nv+fs94i8R8575LyXnPeSAvntJb+9qyCnbbla46YgKlZxURXQMVjRBfkrlFmhdhVXrOLUFZdcIdsKFatQfIUsKym+QsVMxml5dRiIVCB3JdhUPrmP3Ho4ekiYMGvsAd5L1cEae2S1B3/smT+kdt2UKIzgNWmQuUefhr1CJGDJDWnJxawhRAOu+4E1fDtHQK1h1Bqg1gCrhrFqkEkDrBpg1QCrhrFqGKuGsWo4KrBqgFUDrJqGvYxVA6xaYNXsJUNg1QCrBlg1FiuiFvV6WJWnEuyWdOh24vHAgi6ItxwEqK6IX3eYeXXEWYEOW2zmUef90fJpFXGf9ACu8CCkdUPRTxock1Y/8FJENfj4ZZfBh+5v0oAUWQgEjH5Yfp2BeDF2Ho3lziweZPYsGgTSLBZL71k0EeEzIMvxGcwiHIWYnI7YOv+A6hDB4TnEsEgOESyGQ7hDb4gw4DZAHGIDwJFRTmuONLT+kYAuwkA9F8ORzkVwdHPhA9FchJFiDjKQywHqoi8Jt4amKsQSgqz6EWfNmQYBiHcEt7UYzO/LkjSiH2Hf9SXYJMfDBurHzuzx4fceVgnNGGE+AvyYmSa/GH5EhQPTu9WK/tT+Xu3Xar9R+we1f1T7J5oO34Cvb8A3N+APN+CPN+BPy/A37EOJ7XwgnljEc36wL9+o/IFm/zRhV+n9Dfj6BnxzA/5wA/54A/60DF+RRnvmrUnsozLyP3AuFi9W1WHiMZ71Dnzngh3buXDLdS7YMp0LdTznggeWcwDHcUPp0/g77LZ6/n01zwAHXydJ5GTd6LfVy/C8ylg96x2q54Jd9Vy4rZ4LttVzoa56LniongO46g2lT+O76jn/WD0HGao3RLHVc36IadvDbE2TPCwNFmdcXQfAUNsxiqvvGMfWeIxi6zzGcLUeowz1HkGu5h4281Su9iNkrP8IGyjgRbM0GCH8ytiMDnHRR54gZd8oRiVwEKIS6kSoBDoBKmGD+JTAUXiKfxCdttRJZFdT6x2raQFDHV0EW0HrlQHX1i41sPaI96fqu3sVr1W8UfGDih9V/KTiZxW/qPhVxfcrldyrZK2SjUoeVPKokieVPKvkRSUUvObg1bh+E4znDn+Tk4hPGJKsE0QU5zNT0IKZfBYO2lkwCGehTDULFpJZD9NL3OtqG4XdYPBs2S7kS6W38r7Y9/FWLpgrJQcz+PG9F7y6HBcm3p/yVstNB/WSGFLiG95VlMg4UkwKvAhHSbkaT11eKGM5GTlf6PxX2rVf4bElAyxJK6RWwVO3e93dKrsdK23NuC5Gi1XXqJc4US+ni7o39ZnPcVnzoSt5dO5m7f6FptlfsqN6IdgL0eq1VS91Te5TrFZXLXwDl2OkjrE6JopmtsdUHbfqSFOKXB136rhXR9x+UsdKHY061up4UMdGHVt17NSxV8ejOp7U8VMdz+pIlLY2HMpYNpZf7OGil8ZuNA9nP2L1epNBXjJ+x0seMvbq8Qc0/VfWw1rgC36t7HoByTxWYR2qsKX/MFIhWsS+RJjs1BORoFCvkD0vKVYXXkghpD55Uq9b9WL21Jqkxb709gjq1YLuC2H+IqtklM4+5drGmFcQnKQLRWFpQl+REwAAvxrntnnJ66VlaeIB7DOvSC9QrH68yAJLTWhdvQgL6MLJZkIpowZOGvWa3zWkNbwURE5MVyk3sGufUZSjSTCjavfByTT7oec0/HCY2G/lFzsb9y730NL/wudQXJtkOc2/wiokLXofonnwnPoegL3ZG27Gl3i3x2tVaY7mdS9H3T2tHyJVPUaPz8psiK9fhpSJvpXmQb/ElOb1PlTVy6vewL1+VdWDDh9U9fREw0n1fL++J/fjK8Ef1w+JMiklMvcvCaDRCtB7cj8nD2tlHu9TyioOEfklXSnzsCHnU3r/oMz69ZFQe3xE/qTGHijgdfVART8m+gnANWXzuEkJjafNCgfZk2fK/mn9SJDn15d7ZcJnRH9YvRBYv1D2z6tXdSDf8+MG2K+fgUNEub3eE6q3Je4NGj6vY/U7Yfeq/kqV/P0xenlVvz+vIvplNH5/fqLB9vfHdZIQ5JFoPcpol0vAD911eNMsjmNdd8RLeLcZY5swEE7Fpb0iNQCbPoZ+P3O4+rDawhWHOY5g0qiG0z6p2W7P5JfLQX0ZNVSVkLq6vCItZxRxnWnV9hVehrSWbPG4Ge6pKEayO7ckLWiA7IKkp5ELkVttrd5Gfc6v97UsOSs8XLuKmjzZcnwuCGfNwPW4TKpWR1PEeM13VebF/kxAQpAfOsS59UgHum9Mre/CtKGuo95CmkGSg5Wv8A6vwDU0oFEdJLacRKYopPlhz5HkT8DvYbu+eAo/eXYj7wN308A0b9pusISwlG6bR5Hp21mynq9ZTGJXN2MX4e0yqtu4TaBexeQYPK6VLKHvhV6X6ycdquABqV1979beWgOLUGBmTDd6cQ+rNCVeEKQGZ2U7oYYjAUf1Yu2UcnMjpL28UZg+Uf8W6SzHfQb2pfYAPJazVgzyAL+1FbHTb/yqIT8I+FuHh5kTw5xN5SAfd7dOcM4MMSnCujCmaFHfNHhEesW3/6uekGu1Tvgi4Ap3P2Qdq8P4tcK7kEmP9hM/WyMVZxzy47mcfa35wtmq6/G8NXJumjPQaFtTosO2wCOP8haP8IKoqVxIWw1xiN+hzJchqY/qmfgbKXQToV49DiGHfPHyiERlWPNZ1jClUFyTrqyHY413LWmwkXW6Vdm3WWNQDnaKUPuwj6iqfAAQcoaGs1WpcX1IeqZ1494esgLvaBz2WkU0BlTU13DlK4RBS4xtSWCdQjvrqfHI9ybOLEHwdOIKffUUgTxUvbCkxsDNqVVLCqmWV4MvFxyB1yFG74DPM65q0xcdEbTQ1EQgDfUPiN5GPUa4gLyKxXYwU+2+B+35SgYTse10WLIZT3Mq1H0dbjMacXOIJFwuXpGiUsXE34JfY6iLQLaeNImzGgf0iVgJkYE+JsHTsm2PWwQrJKB4WZOTMnuftxnpT3srfdpT3hQ4Gs7qYWtIhRas8aD7fRYeWZXCU40DdJWYfpsxO6I2OVUkMzEelJYbP/dUI6JZQVORvDZgsh69LgEDVvoMVLlDNh3QoNqRnDBU50+Qj6eRNCdMbOZg9RTqCchEE80Ub0BqtuMG/HHbEVbp0YgtKhUZNpQnd45q7mUalzlazCposoRNCefvGpy5xFVmXK4EIpA1PR7ILOSBz8CBWrBTdLbZz1GyN3NAAYonGAjI1LWYW8XmJ/lwnxOMQZIW/EvsjC0DXBHFXcVVlNNQkoTnQCiDefaduSvCip9KXeE6R9uRymY7dsoPmQYDmBq30VDmSM/DglGzL7jnEuexGMbDDWdGCmDSWVPwVyCcSR0opHlr6ISG1cDTIkTt0YmITQh/OcROuNVhRWgHmHKCuGFT891GjHlWusUZ7sivWFIfc30SExoNuicxSBuTUKY5Op5U1QV37qQXHZtGbMgUQtduB+R1YJ85xSwPRO4PvRZmYfnU8pBMkwLqUaXmzYIGR0BwPdOR2z0NvdfnyGDBkPMGkbm790luAn4ko+bHJFZ4TJnwK/LEkosYhlJXJgI7oKIkTfhOBV8tt7njvW/SPexti+sQGvhgJ7qh5HzMqMzbFnXGLVrdCSVJjGtc8WogjVNIJDxejw0R6vYkRbFKgd7fIDc2ME6tatkeABBjqMe9IdoTSfHANDSiSuNdbFzftPXEcx402tKIAQUfgremTtWJiocBhXlT8EPfCO21VO7TeDPeNCy2eAVvdYRCGGxDtLzYJ4CtBghO6txliDvH6CU4aAWbXdTuFDVIcu46JxncpE0Df3W3HduPn15fiwGAOXHb8NM137bPebCfNzs6fl/WqMsxN0XucUZL/I1hoq9Yt2mxFW7lJK+cECUqagoS6cx9ILd0nnafsw/fyEDARTSx0l3E16AogFhdhltK2NhuRclIRWCc0JIolUeYvqEmJ/lPErJ1zAxZlWEkAk8AAaaT1S9x38R0gknTb0lOjX4S8KX0SHvbDQ+Ak3dripRL5axImyLtBKo3DekxqBY33N4BlrLGeh7BfWdx0xyiQMUo2lkugXsRMVxcBdU99kw6PktuSVmHbODSoySRBP2/lrebWZVHnyhrrnGE57ftDSk3I7i3Wjyf9cIep0gobO1rX8UfJgPQlihpDtacRGLuboUXRhh1Zd106inI2wJnBVZyCI3NLUGu0+jG1mlmJaonRnOL5iV0DN5l9osaJGhtWkiylMdZmUGE1RSamZZXPFir2UMnYu0ICwGa5cHQsUjJg5iA/hVYN5HlqKscL3ljRRQcLrIXVcOYgIvyLoQ0UXIQp+UXmkWfw2AYfQZ8aULDg+CAqgOI6lxTy4Y8mrFiPXhpBsUGWzgS8/+zxJC+ANWTxY8AB28RRprrTZKSFIVq0vto7ojRFiM7ybkTw2QplPoGyQFIPBpudvlw+o/kY3epww7sHXRnmqzd361VvVH1g6ofVf2ELtFh0OohfKGVyAQw6lPSYKGNI/cuZ22w0KZmkdKEsFkARqUfu5eMMTSmYoU0IesoFekfarPXticjYYnOGLJOpHWNkivqNiCIERFPLUsdqYLitcVIjG5g0Ed1oeuMaWuo0WpW2K2JRkz7MYOAkEAEVr1woJjomZyh14gew4PFoAiJF5MSG9A3HC3DGC12yHJ0YdaFrJvNAt3JuweBH0DKDI8PFQliQn5vQszea9LtkCXNtyDamjOPTNzAMTUKcxP7Sa+oMxbO3KtkhkS0ty5uAOsW4rsooXNJM7jpIanmYjBIWkIEqYQJxV0q46ZjRGk34WwGIE0F2m4o+URS1DojzItsQmLDUNz3lAesrZBWfAqwscwjfJbXZY9+DJs3akOB1JocbSWGM1bWSIbtUqTt8oKgkBiHaCtrUlk9sQWem6G8KH4ztOEh4VYwuAMihkEyQbB92IOYve9j48ctP7cD/7MYpZWlZ+gNLnHrUuMQlg+I2aAL0bUMq1a0EKIRK+yaV0hIhYeq0N3x4ExSSfPSSQIrK8RkOR6+Au+R+p4P+dB0FPsd1DI9dzqUGEHo1DCCgmkqRaIpCZShLiM1CKdz2QsTOnfQvHgGZfSQJU6NkTx+xmgPpY4+rnmjnu1RU40KGhFYij20M8C9oR6+pbkXF25zhfQlLfbMMJZlDA5wZHOgHNX9ZHCtaQZ+oLhXQKqgna9iHGlsOfbqL+kb54ANAvGil52zHDVJqJVcXrURC6xus2WV1ZB624c0BaZxx6hXEhMRsOeTpXwB68nWB/KAB6BhXObFZmACasXcaMPAYmhSrl63JmKlbEuDXmdlDSb3hJX+7HBZtqHGhqzAObwcgpE/uOIlAhPzXFLJelZEKqinMq2ggXzvruWSegitkrGkSTMTBwZnOpZdENNQqVkKsqktml61WNpcgQ5xz4g1OKEIxZtKOzds8JyEBkqFsSB75JVHYlk6x8wPI/9WlxhuMVyzVSE3nQGl+tpNHnn+A70tSZzqI7bzGH6P29mVi8RnWGULfSUTvzEmTaxkkcl6vXmVHSqjApezXWQ9ZnumUYQkrvVR5wFy19m4CVajST88DkW1LpI/b7Sb3DCfV9uKhnjQ2Flzx6CGgSAOeOWMuLSIMIZB2rvVxciUESYUNFyymu4WHbHiwHOpYRewxoYWxzlhncbB3WLffQib4xZY4xAPFnYMlugK/cn2DmJdQ7zkl8vZy1brOAuGeTXWIRhXB3A6jqycuT0blrPtkEvJqyEshuK+wdrOGRtNWch8RJQ7ngNvP5cXVRMa5mJWOKAHYs4jJDxrK2bf/RTv0NCss8ZSvM1ISuaEJ6saZ0Nj9rXYUqapPJQp+h8yX7UaAll6EPW+2JR1L2uoTa5TUgMxgJHgTfI25llcXVMdciy7m1pOGElQckx4IgxTdXwcXUaCCaTGddbRlMijVTGwqhPDyFHCK7nEYHck3YIRFA/vDWABa7Fa6jcMTD4AvZmP1fEMN6/d7LZvsxrCiHcygsFbE/PCJFst64TMqU3Pqy2sxGxhatJBaIjYQxYENPNpoTMmrDui9RCkXpx9BuklfPCAV0/t1gdHEgKJU/qouLnv2hgNWMfB6RcDJibXpDtvWenH4gGWLEsDykF7xJ4izdFxz8qSHGsK4ec4oWhDTDHAz5gIVLyi2kfYlqepG0bdAAvfLSxHi7KqZUUXb4XamTipNLBHTYTCvKIa3TUpHCxU9V0Jieu6Bo0MhpcUNM1cCpgFWTmXMzDkmo9FWBBGsDLiCIa8UIi1hHQaZ9yJ3SCXKQeTdBLZD44mKVeYj2GR8oGN7zSyq9EyI6BHRWBdqe+bk4rEFRMkO7t6dcyjZrBmpaepMVSDNwIf2LIWD+I7qx0NLxTxks6T3faQwx2y/OJWe9DIR5aJ0JKT3NgIMfQpnl7xalTdmJ3GvA/VbGSCjqFUGxpnwjNmPzoU1UNUwnndWqa9PYviB1KnQZ3F51nlc8n+YXu43UxkAvCJhLP6N6+RKRvXgRcyWU3Pwvx6OgxuEaNbgZEd+0HpW4JbJrcoQ2koCnuNX4ylPKtne6oC5tNYZPC+4Q85KjBCeD0ZKsHZG/DqAtM1kOtuUMnLcFvl6dmaJIKuwGh9FwF0ECxgMRPmEF2/GEN4gsk/gNmeIM4IM8eH23W8t9IM6lLlHRsAd9Fo3XWy9+JKGlt/0lMxtnwX7nTP+cmLMZGw2TRVO+wJXnc+iTFYFXNsMQmlboeWk2dTeL0MgtZVkegVhzVWriChaOTz97WXDqa0auufy2hVKLdayOGeKQklnYuAXVFfB8KiXIaNAuz88OST1/Kq3i7KmYLn9nFmoL+QTlnYpd82ZqmJ/m+dcXNu5WwyL7Pln6KPYF7ThaM9LXn4qfO0cq+Skd7mskjZYcJQdYEuSVaUbtHGHuZwXGC3UqdAsTUMuWrtcz7xEOY8dhCzaqINdL6VkPP7OH099g4+KsMDMq85kGC4FeanstZLv0m7FEPWrIUrSbulBBQsJLCVW4lBx2+jDCe02Kp/bajBNZT9weNuSozPG1CPhWlX1ij4MoychIO1RYkgeyhyWgmz1ReLwe0YK6/R0e1a6EY1q3qCrmV3ft3C6qoTEIkNTKKtz5Sj6m3kUCqJUiyV7MMwYkNiMPmLYqtwa3jlgyaz1M52rZePV9KgWcU8jcdGAZ8aPm9zjfMULPx5xUWGEPar3/iwrLjf5KisDZCDsjaEj8naAD4ka+FyRNYG2AOy1ifHY10pfrRikqo76cLLHUajOrmvCNycm3EbAoDbEEK4DQGE2wBHKUMA4zb4gNtYih+tmKQS3Jx3ZXnC6nE/FsexeGkco2k260NWjZ0EQhOUfVRejhQje3a/toRKU9S5xs6yHXtEimDmLlu4YJ9IFCCSzVjbjHkTxKbHokrUt7mM0n0OBeuYd2JkGRNEXAvCAbb6jFk+Trn11bCY1Na8swcbNDSd3JmznfwjYywJcCZiHRDILCnM1zBnpRFarZD0ZmLpSWyHVyxBuTiOEItBY05sS7fmsxikRpa8xFbKga+JPiqjMUUbtWkS+WXNlkOX9evx1ArN4s5TTRyqAp+eus4EGgEmum521A6bAG7iJEJSViVpTMsL9RsGJDnuCF0F7M+bPuKrydXx22Dqt5hUURpB7pHYf5Ke16n5UbzJWqTV5RlizW+6l31JvdQJZWTtp/5hzNfZuubPcV3z9Zjzholg8jrmYcdSa7Zef3awqUSFzsvCBkwwe11WzoTgXJB9ps3yynStd2RNu16LBZRTeG7tkDJd+5U4H7MlX4G+Siv9eoLVUoJ/cnV5hq2/xm2LnlZ3guovxl5dx/7n1s/tYhdWDtHXxhWP4RABItvNIpGOFW51N+gHLnYrq51Id294VzUOi7gvQp5xCYpiCZI772TdRIhzK5QP7CzAOyyuxYQ6H2bEcQzoKuMOOMSHKGQD7iczhdxzZaYgnGUS/dEUSbCwDsR4WtTkNLSreQBj7rK0IC5/QciCEhP3vBcp6gj1GRXJxnEO87pavTvHis9P2A5kYb/hFl6rfiPpPTS8W0uarjJZz7hQREhgWkwN9chLUHwYiV1xiEdGsAtR1t1Zjh78m4j3H4ms4dBkif3PiYvl6qGeOODf2rFqssaiHtClcYJDjgkM+3a8oleHCTbhZT2LfQP/4VgNVmyxyFbi/N19+CmOlUyb66uJ+DAH9/U9OwG+9+d3n7zu0uiQH5Dgpz4uetTb9M0gND8WgniVAYxhty8L0mPv+EmIYZ3EW9Ozei63Mo1H0N/s+lsSbiEy7WkvGUZYL7Ery8lsL8X2uwayRCZyv4lK/Bsvt/zWyDleoYFduu2jqNCe0uMD0RUmoNZ2hhlQchwWfydZzqEcVVaxpxGnsNKYZEzjBuHAB7/bA11dMKxaiV89W4u1n9iVskED6LVIPI9LaHyoFAjr/tQWMsW/KgkJOAK2kpoCa228ZU1jdpD2uxwz7P3ZkGLCS9+kInQ96/tFThNf0jPvh3YDlCeZSH/G0W88W10Nx2F/uOO38sITb5XKXowVDyGN0MgDW2ku1hgui3u8myrK5CSjQ8xVx66AOnSod3G+s8skHCHKsNmP83otn2bbj8d0r8tawLENj6TH8yPXOGmS42SunGvEyRONc5W3cuMx5443SBwyntq6aTxU3CMr4tOfrh+yaQIB9lVY9u1Q3FiMRwHodC2mQW6XvUrHJA/2EL+EYcNqLJ9zo+4nG0xhINtZfpwFAkU+nT2E2q7Hece+c09E7GQP1BKfoiuz1FQrGkLC2q1muI35hk+9io86WeP29905AFvV5jx6MKBBJ5zVzy4jG9ahaUTtyzqbFUrDZDBrV36a5CZLAqU+b7MxOjV62ruWpFYZEOZ9rvNw7KEZklB3KWVPxJ6ZN31SnINJlZYLz3q/5IUoMvsaGeSx5bO/9qQ2cKUaYAtzUoXCz3bYnrPHKngHbVYi2lpQgqHOhPUB3EjyRIE7zrHU0aZhywJhGscjQnrdzWYZnppzIA/PDBw9jTBhQsdX4/kT2xAjQFp19LeFcHMw4RX16osELBpBU75jPXXeYhhkB3r8G02RtxgptrBETxrRvxHLOrfb0Y+kqybUODho0Gp9V5k7mjVj0igHj0CYKyAPwNdRQ+icNmtMo/imL1vQqZKhTBfAj4TLaQ+sFNFE1u6DqGdHAfVsD057nfSNFbbEHWmwVj1g5sObCuFSgTUDshAiadhiyGKapRA7qbxZ3PPN4p5vFvd8u7ilco5YZrpdNy94qcSr1DeDZQHvewyevsfg6XsMnv4Ag6Wyoz5ZrjcHLJXnpVgIuF1LBD/dKunpVklPt0q6N3xs4tDnReeWv3H3hycABS9aecvlwLjIkxvR99fRxy2TxsiZbLeZ4fze7ocDjZtiDmL1PpJBISREgOP0rlRLq2+jDFAWqgupb0d4wsJRgyNUXqL2hNMYCyH34814dyqCn5exHZRv3RP1hheCsM43JM6+Dw7RUDa/72PaSvFktjFRCEE34j6iuBzB0vOPovH7gjYumKKn+ax95mcArFj/Hk/gu/Ap+N62cgbt08jSPV8wwjafKQ3OGfAaWXHi+yaNPeuGOQ52NXDs+qc7KEYzuU6OMa4kZFXi0Rc3Y0AuouvzFLDDmdYHyTMCwsZt57Ova+QQeS9H5cRIA89oGYSrVgXmpbIZhseNcrlaxSfZONchQx/Y0VTYCxIvH5TmxVAvyAc2PK+157mPOst5FwY6O7cFm8ySKxK8YMO7qHwnrGtC2THHiUOmwNouXFqi8v0rVqyNB3Nn2rGyUGgGhZrPsoFskizDuZKGrwZ0ctooEadnYohi40yfrNQy48hyygw+OXon66IjzdpgPLFl43unV3DsIZCnJVl+GD6zEuDRt7M7D1TyFa1hJYCC5yBskxa5feMpyLs2YCuU3n4QFj1clCGVkUMIcvR6zB5bcEshUS53F4CBdbcOiufYRrJ7MNL75BxhJbsLg1eO6BZJo+1+Fi+EUw8djwLwYcvWuzSP3XHcWuTjig7cmVzulDKyrC7K3Te5URmSGvrQ9RHWRdoWJy8Ce8tILs2Zks8JbLdYNYmLMC/tQkLRM8w1VzFogzJTc68GrurG4C4nb/JO7D/4pyJpFGv4ALM5jxXC0dTWW+HpY5kTFCGfrXS6fRhDaJpEev59Zu+7RXxnDJs+BJHNn3XC1prk7iTNzoTJTdzZl6stQ7kcrJBQ911fh7xuRIVARFVJT5p+iWub9ziFiU0tWUfFGifbOGCrUFs5scW3t7CKKpenRAiZs9tKlwmm3V0nlHSBxdEcVwJxoYNvxXCfdIISvX5vAwLplP7O8XAHLczlET1+QtO67KNIzr+a+1nPgDYx5jcGOlcgVzag0r+GDZ534q0ud0jLk3IT6ZnkGlfKfNkPntNyrpLboo2N6eQwExt9cF5ceJf5XDLsBrVhzydm232IQ2w8DkGq4ibrnqZUJxxHiPd97QSovbbG8XFelwarUq5cjRvNpADRoAikiB1THDdO+ThEyjfsVcq9iAJIDYJN0rxVuwDWKkJV363VHht/mp0pFMstjQmlvBKYtn2RwqZsTb3atKbOeHPHAq1yZX3EFHEPAYczbrhio06UySdlQjNt3JCkOG1YdCqt8g7IUbFNTp0EZaXQrQIONvBuaeJC0fMC+31UF5gXpTQVwnA5pOf5KuCUVJPY9QGxkUdBUQggdz5gQI/tKsmNTi9LCzlSQVtJhSNSNFLlqBFXYIw2Cdv6GU/jUV11gxfhiPIp9voZkwILsuyy2ZwXMHRBamtzHAFL5Q2hriWnQI9UA/BMVS1dg1cPhE2xh8nzArQmTS4O29xW/Y66PmobUyRSnKo8RpZh4TgmDXtSe/Mtq2RplLelbCNTaurbuFPImRK7YgsMV1zTiDSAT7UncLFB0SQ8UhIjVFydN3nH5JJdinSLsBPFTmtzSrjZwoJ8Xd/BZHEc1rwoQl0cEVsY0tCNLGtQr6XwhLpejxaQIzgUp5NXzQZAYTCSYes3bU1Yq7Tni/Gp3HlJepIYKb97DBy6wDoj9F2HFda0xB+WoAxQwdl7vC/e17z5yz71J7CYbUOMAWlNGlWOU1CgdoKnTEn656S8Hi3j14RNelYZ9Z5UbO6Cc/s4x+o2YgwPdxIhdRmheTBUitEBUr2qY1jTmNWi1WDoBBVD1xV7HWkSnu+sk5qZV3rwFnQCrXRPg4IsldmL5kRmPqEax3j0W/TXoq+I4zRvYPOB/77UOKMS7nXJ97JpxNriX61IFPFNLNOwuYRxV3QU4VT1Fksdrd2OGQ4MPfkDx+1Ys/N+tyNOTyjdjjesOlnDFvbgkX0Snlf4p0eSFkAyRZnCvLnLNAC3NnSpi+VQ38fqTyhPOlixPMFRxvQOJ8iG+4VU27ObGs/rNsyYxWSMdxxtqO8U6FXVgXycHeyqqi5guaoudHIe7qqqnOkE78riOKwTSMqF+g9H4bxMBpjLZQJ1JwrsdYzvsHFJjM1oyMIlXkCoMBfoFhOEBtgEIQd1B8vEe4sThth4VS/AQfi9O2QmjTwB2YImMG7iCYRRvAI/SgtOYs6bdxLIGGEEy0eWG7yuys4vO2/O51YHrNdfBXCwedGzgti2GE0h9myTAEZVsIpuS10OZBSWg6SI5TAPueUIc0yXY1n65J83sV4ME7othViyLAX59FwKv6LtUiRBWNsN42WUb4Qy0jfCpMQbgR7iN2IUdrcZ29PDZpT0FzF+IIjdjvBPJqXJGc+lbBzLfDhN+U0WN8P/qYSzot2y1wIKy0gO1vdmZXlc+g0q/oHp69S3Qn34DKsJy9zO+Xb4FXP8aiaL5LEnVW/ncTuC/n/Lu7blVnEs+q6v8A+4KnYc55yctDvYyFgOBsIliTOPXT1V8/8/MFp7SyBAyKSra6q65sEY0NZlC12Q2HutQYKtaUdrGj2CwuyCWvhTM8eNcVE5YIVvBTZzM5Fy8cme3JiEWyty47hoL9lhyl4ZP8bW/ByfntqrssuS7crthcnBXpoc7CXnYK9MDm06lEP/hULqq9R6PQ+dIBzcsXaHh0JOBATV9124ITzyhLghP3StuiHuLbodOuaVPSDtL3wggrf0AXlv8blJzSz9tLC/8NPy3rJPiwcajcS3JOyWwEV6RruZkA81nYkogdYzEcOrxnwFvlX07xR6QtZ82ppf6O3sQm+/U+jtNwq9DbTy+YUOyofa+ncUCMVwmortD0sEyNhNIePz6hQdnS+jsyM4isyO4zoTz4wySxX76jFblX6Eear048xSpR9llir83j5bEVd8nhpujFlKuBFmqWDe9Gbr0JOfp0QvyiwtejFmqeEuhmbrMo40T6FxvFlajaN1qrFLxJLgsQx+hVXAE+QU0xPaFcYT2GVpMcUH2Q1uO1kNQrpsBgFdFtaGepzLOMTJaBzY5TUO67Ljup3OdCrcyXpKpCvAlMSwGN68pzKcyGX8zDpTi+FjG4W4T24U6Dy8UZhjSzQK3JJd0DiOYzQ0juNP6s7xd/bpxX5B45AP2A2a3tXVjMFVicq9kXu2NTMOcWpmHNjVzDjMqZlR4J6UH8dxamYcx5/Uc6eWT6EJVfxKTBR/VPCJIo8K6y+m3Wb3lNYT5BTaE9qV3RPoqDAOZU08sRyFPLEmUnse9mifduOQUd/26zYOc1QbBbJm4ziOYuM4/qQctZwJyafbRLCj4IREp+WEgKOqX4L1nYjtKD0RO5Cy53XCtxa7sfINL3TD61re5uneC1QWLMlMcadwM2N05Z0Zwbvest75NVnLeRZYfQH/iqov411C9UWc6ZHfpbRQzJ7d4sR8qArouqeW9zSlO64Se6Lthal83G6+jadOllr4pJyWlBeLG+lMiTgzGD6w3kiFP5uG05mWcee9qczcqefwuqxVSnZWfVgHTzXdFHbedQlbc27KM6Td9htqDXcs0n5Nbjv7SWaOBbXxDnbCDk1J5oSdMfXkPhh5gp8IEsCZhGlbmcWACk/AmCMSoH73ElGvM4lomKGIBh1FrLphlfPSdUdTmnltG9x0X9qG8r5ERgMAhQwLMa4Yv1gfEgSGexYFhL56EGDHGQ+PzuIWsyC1zJdD4aOD9JHYeEegvrx0z2Jh8NboCb3YQYWvcLRAXHU/sLsNzHi6PXBiNy7VvCluoQUh2vnzfynYGy3ZFanFaJXX3h3H88el88hkaV2QMD6/+nyhMEov90DwJJiGXA9dFt61SRLH0w88anD6OhG9JxmGYivzYh1cDHKABVjgmzRimNo7qrYH9G+RM8sJ5iQbC9YER2TyJneRA6qFQeIXd2pBWJLXvHFhDlyHvo99fjXQ7WnnLpRFDYD7Ws8s6zRkEPWPaU74RU1yYrjrMs8d96N06E0GZhEgGUv55fUz0/OIvEo8XgOsMHDs7Kh72G3pgBi870dm/4Ac4Q3jay9hg6RA2HjkV2VArdg/WN8jF8suA0ZY6uTZ7WsVdN5krHZ2futF83vJvecXZbBGCOw8dpKVn0Wax9ZlGba4MgEQ9sJCo5Zk6nmUkuE9Ua2EMFHniUSLhlLpEWC3DJXaIp7UzaeMcz2GDdgfdCFKIIgZr6s4N9j5tbF+Peu2bfD1JQOeAjekJKSNGri3zEkhAeZdwjm8ZnjT3ALmwvE/JotT46X3wXONBbqE0azp//qM0FQqh0yjBV6pG6BGlRawrCoINDPJ4QDP7ivHtGUIYqNhA4NvmNZ692jK6t/a58x/lBKq1wXW+7STXFdEfqVHUMLcTJkRiMkeIu5nIyR7QCwYwHvuCoxgqaVVVRG2dvSeH4jX59AcCN+LEFeIcMOwshwwkhNkbMKuz4bRxXw1jFJc6NGAPikWUdaSoKzq5nhkCMLaxJEJEGRRc2QQp9JX4q/Jmpo8bz/UsWwU4QxkYBGBe2xzKVLLpAJ7t4XhbbmrtQB8MAnv4HDKC/vMCGCJewc/HEu4QnZ/mD+1fg2P4oeDHi4whAMgQtZfBDnfkH3dhZyL4c3zoYhdJ8rgscN+0HD8YhOajJp2giZN5B/EChMR4m91u7vyZGYRZ6+R40npiV6T72p3zZwoGNwZaYIvdbGfdEUByqnN5wMv0mY0wOBwcsdUkAg6w6EuwjkiH2F4+fZdbS1CM00a5LQqHgyBjH7AnXdrpd9jCP4eZB9A5s1190XASTE3DfFMoGUYZOpDGe3xOb/DPD/kZcEuOU1J/pq69cM5wPqLRwxt1jCmO7kmkNs/+Id0Y/m00OZE03SEv2gsmTyiVMTFlqov9kHSU0euh5ScRyEiGnprVEyOBJFuwialL3h82qkWOKinnKzXwSSANlEvS6C2GPIJwINlSVQCkDcFDCC1dAL715VQFDn61wWGl4XpYCUcEsiGM99XxphdvzWCRWsFWLw9tSzGX60+CHoAxsB4pHGOLgyWEjxfgmte4ZN/U0OseiW8dl3bsK0Hw9KV09frbxh3rxSBSut5NiXmkVgyk1eh8+RhGIMMUxFgR1SPOVlNAHKEq/2C0ehqzvVoE4sXC/yiCEGW+WgSBhqHYwkVk0xxT+CJfXjHA1GZHrWPUrfgd3rzlhbYD72D/QliY99P3K80MRwoj5UeQfQY6d6RwCImI/1ID5i/KHvAu+pB8gPPTqyagjsr2W3T2wzViK6QKDEoKvrxpeoAtwTF+C+pLiDRxx1pkOe2hecAa0QmYiL3pIaeFWFeoJcYvzFyM2NaHQvk/arfRFL3RgxuMXvR9XT4aZEVaRQ3gE0kFx8LWm7uAcQfCz0b24VBxzRe6ZH8KB5h6AdfuuuCnH4e9RR32ZP3MrAc87oBWF+l2Jz4Qi+Z8GfQ/ecdRCZsEFjaTPQsD0zwDCPyV64TguLsZmeMTuwrs0ppHRCRtwZKckdTHHFbUffNafRGs0qUXgN0yFxwpLBUZHdnlVSgI2i+vgASBgQ24IrpybamWi9kXSrMc+gWINJk/0i4En4y3AvN25EewZrKuul94kWIIA1Kap8pPX42Ikcd0MxuHZf0u4siZ3Sm08Ikk/KLNk9yxJujr68RgHYrbtMEIKaHXOKvIOdCqv2VgdBB8yBkQYaa2bPXABnAIwOyGiXwNTBTZpEeuBZ68CAYcIOiAXDBakGkYzvisBa7Euud3V7BMUnsmOla7Iroo4W3NJGYlbLEhE8znJ5GlmRTFktMca1x+GzxrF+o2xF6xSGASyMMQECgEhnBZ6bnngqFxpOBXBGTwYNSDoNRbVOB/er55xU/G7WhKdFdUIFdSIFdWIFdWIFdUIFAa+4RDxNc5PymfTNusJ3fjO2W2viDU/89cP89UP89mP57MP33wP3XLfV34/ZL7caWHFtSbGliSxNb3hw5iMmhR/I8v65vxg3W9c3YkwOMG5NIrae7a1C01/SDkoN+EJQNqDmS7fWQkOT0cPX/WBmBwS8Ubze/Onazq2P3jerYfaM6dvOrI9S9ebFqYh5BxiezeZ07HDPctcNx3fLC9O5kGELd0rj3+3m5If6UZs35M8Sn8v3GnLb0je2eavfLfeJT35uidZt+YYd9oni+YB9ZL1zEc8vH9szkbs8ANFR6vfZblGX6Tf+5wtJf19MPztAmsWuT2LVJ7DiJnU3id05iZ5OgV2TJS3+C2JBLhlIG4WNFO0BEylIZrl1yUMrJdZuIq4zZ/4D65+psyL/ac7Dl4FV6n9K+TRTresLE0G6g67WQTtvgzH8uidrjUDY1tnyu+fKaY2OqJpdzvQQ5NUyTm4OigoAVokQdFh+MGKWyqAbJu16N0GYbs8teEBFbnKCMJp/MsiDF3q1bv6QtQFpk8PL1roy+AAsQfZL7OzEZArtAl/qcO2yxelVzQSzsHJQxO4CinhgB4JDTmrosDOwFPNuBhfahl6oE4pxGMYGJ8oesiyrL3NDf4tNNkTYZbzYw+20G/m7giWW0HdjwLgcz3OmmXZiVPQMeE0er2Z7E9ibvtNDuB+djuTbh9auOeqVuyHPp6y2oLSzFBEjrIkZBbenbjtjWQE0BQFUnSbC3Ee1yEnzehQiRaXmGHZcyj/A4C+yMcFUD14IaxFFGvF9NK1+Io1FbxFTaiMDRbIsngIY4XfEtBFsYZ5mmV2Yb/DCA29GR4AuZhzjJCXYm0s0iZ8QA0ypRs9j5kTmRUvF3G+xA8i479th/mhX2ylnFG4I5/phA2LSEulkRxD+DmqFP7A0N+ArQupY0PU8JOMHZjK3hHU180FncMDU10VsXBvsxVbwLtmeWujNWrQl/xyhpI6eQ0YJ2vnC5eJeJJHgTpq4yOyOA0u92NKPUxS8cfJbof8MglG7esXwqpGxRFJ9iZVA3zHZmzE81hY+N2fJjeG0wHK0s3Ck2eHw5A+3DcmbQzmUHbs0ftcyXG96sbS777pOWawLUfjtzr4nGnszb6PqhKUwAp9wBZdT0LQss07K0vGMGMK5LEzDk3VdGJ/N+wJ7YBCr5WeuWtFyJ3VrsVvp3r//0b41/HDb6X//W+MfhHic4rOmMjg/6RP/W+MfhHhf3dIXjBmc4rOmMjvd0Ssc1n/PfVp/p3xr/ONzjBIc1ndFxgzN9+H2Ns3u6pOOaz/nvAac4rOmMjvd0Ssc1n/Pfhs7puOZz/rvnC/5b05+L7s512DY0DjFfNhk3Nzc3DxhapfiTYXrPzJExQ7LwBhrU8UH23kT5pon3b0701VtQn+SbN/DNG9PcNBFZtCt5P7Sv1VRMX7rz8nQ4SAw9qLeuglkVgayKoHpFQL1RTHPb2xZ6MXvEKt9uefbR3255//Y+I9vypisz1Jxsu7/d8P70Vr4JLG43vL/lyfz11tBreIFe+nc08r/esdyW93a75W2ZqqHFWScJB0SNV16wWwIPACvcooFb+S6NmzEbA9hjIN3/Sp5dEvPyfHAEsB9ngvslCsuMMvLIjNTwyLQod2RkgkRPHLRci/O9OG/E+UGct+L82MPK80in9yLdiPRBpFuRPo6eyDCG+Mlqju7fdc9+QuJpIkX3UU5IhFTQM/UPm8a4prb8JDmGfZBb2s4b3PM+8m3Fn757okbV/1FmnQ1b520WO5w6owCuCk+AMTQcB6iMEQQm0+HhqXtCdNMb65fv7jDmSLPJSI6SJlIP3BM8qWlXfl8Ym/06DYhvs3L98aw08Ag63AzLbRAJcoh3pBmp5R1VXCm3AJ1Ery63owR8zzMstA3mAPsg4EER+a1xKpmchJw5QPzBg34aekeoBnVobqeBdEfCf0ykEYjjJMmF/NdEhkaFUHEcI0R/Qf7oRr2QGv+ZLiNX5yxF0sA70VA48DS+U/+phTg6OD3IeibyDGTYMO9aq3+LJM8YFeWge1oy8Lbvlw1bRJItoNPfe/dtEl47/1oVnSX02OS4P9VPTTFjnsxZ0Ub8u22/981zcyW72rEUPU7F2FvvuYKFRg96ySRYtBAcMVsgt5bjbe/mCPtgm9kPMLJ6gEsTSKuGCgaWiBzJT5tl8r0taFlkbsmNbOPfGuycGvRqbM3CmvGoEmAPPlvW90tlTXN/S2WUWTIxIbnH/WZsOAlM1bJzddByukG/A6FyywbpnJGxhLZ8p8cWyXxPVictOhgL+JIzddg6IdjXT+K/o4owzSQ0evsfLCmXuovEwUhU2mEgOPK4a4PUN5WaBlT6lxOlv7mNpL0l8q+jyqE2/pxTZzq/KdtXbEKWyvg1HLeDRfPWYr9gwzH6drl8D5pIfs9NhT1x2XsD6yMPclxHsB1+hviH5NjUCTqviH1JSqGTc0YvHw+s0XNyLTQd7tboOPhx6kV9umLMB7CbFdOXC1VMX3K6YvpyKOAo966JdOp4ijHIw+3t3niPw4ycBubPCKUb5OK+jPojVZKAZDElqUTViy+Ya77go86LHutEhCWReIFzjojweeGlUp8iwpJIvND0KF4yxRbq+l0WdpU16Oj1YVEVxM805MgWmz6Hgdgw7TQ7jGzwSS2yFyDqlETohquWfEE8AAmhBFKy2DDLox7Lsxpf/iqxMXORe6uFpNsUgObl9IhRQWxOV51OtryorNGSR7C7Euj/xlIabJyqeULVPKFqflHVPFHV/ELVPKFqflHVPHHVPFHV6Hzgu7Ahgjs+xRekZX2KDOj9xoXb2iRA/JelG96fNqngumbIa6DWqXnIvReRUHuhDkLFQkmhjkIlQp2EUkKdhXoVKhXqIlQmVC5UIdSbUKXQVaVqoRqh3oX6EFofdRXqSzx4ZszNkPnhgREABlJoaM3lmMJ76ICHqcurX7RSqpmkjPTLQXuf9HA5ybUWyV4kB5HEIpEiOYokEclJJEokZ5G8iiQVyUXoKkpykRQieRNJKZJKJLVIGpG8i+RDJJ8iuYrEaMGmzG3x2jdmLhA3nYFMrVIsy5huntv3e6QXb4xPT2zoeblcPYr4h4h/isP6TsQrEa9FfC/ijYgfRLwVcRt8Hw7ehIMfwsHbcPBjOPhHOPhnOHh1dyfkSsi1kPdCboR8EHIr5KOQP4T8qaOGg9fh4Ptw8CYc/BAO3oaDH8PBP8LBP4PBurn8s6rtvxuemM8=", +) +_D_NAME_CPS = ( + "eNrtXT+P1EYUl9/M2N717bGJ+KMIcuhAAgmaSyIkUkSIhihIFDTJJwjU1FQIIV2HRIfSRqKgokKiQymoUlyTVCnyEfINgte7t2N7/vuN7d19v5Pudj0zb57fe/PmvfF47jCJiisJgbB9YIvfovoCoKgBJKTxADyU6mkGgXqe6Isqq9ojrSGNJtYHg2d65I+5y4ZJhalNxOkuWhTTyH9ZDlwWeFV5IqpSZnULwkJ88VPpaFGV5+XVvFm9kJQMOoVLNGu8VQ3YvMFw3iLH7My2ZJGXjGuEUSxb8ooEL+dJXn7jTWe3rMEy5ShKG8yAm4tgjSb5Qgysxmquo2TtA9RdZNWNyNVmbqQttgpywOHgOpQdcZt3hSVBLuqBTSb3OAsec8JUeG3ZnU4+AAZvCNBUUHn5sMfZR+CRAsPXa9vhfFOWEAab95g0olhAw2DqgMB197RND64tySKmkTQWCKMFj0VYHXtNNbVV19uR1SyqKJjCG2Q9ewyt4BJr6ByMwj1ckaMgwf0k67PiIVzEzpG0HSNqZInVmCwMfDuW9ZX+MMHzY91sIw0yo0nfA5ewXfAJF+t1AQAiuDtTprqkCMquoFfHA273CV4OYt65Qo8QNHgIo8SF9cfzJA0CgUAgEJzCctpmFBFeWXj4M61cu3tkWlOy95+BcLV/a51tpf1djJgH9+ei+h+Mcc0/DvXpKLggjAUfv+tI4NnvJEQCgTAKBD5wm5LkouHchvI92SotsPXO1vMYwysbVKoylWwAae7FcEL2EFx41A13f6zvnOsrQ1khMcJkZhHWIMTAI3KF978g8ffiXvV3Zs5kqw3wsHrXYih8QXPjJs8nIcgPnasGuHVQXxJd/QSm2DZ7QYW3vDE7ne5ActjMaU5S6gtMdnZ1uFtPPf1xrB3N9e1DR15tn+NyPO84t05tAvfQTdegqM7vzQ3xvZn3nXWLNEKi9z29KkAx6HVVQsbTdj6viY6pIRJfRevu89hpzXv+M+BntTPUTEdv0d+o+rD6IINVpncR0xL/cGvNPNhfElh3mbc+BOLQ/2bDVuF4YJiq122+dh0PscbUbf8m+wHxdeAqStZd0pPkBG1xonyFvkwPbwfdjA0XtCXXDa3OhcQwMVYkMHosmN2CgtbVIFQvsVfgwRKZBM0qd5atIDG9pNBhgTKtEfE7QkM+pICVx16kNZfI6xIAx3kZGi3ksyomyUFsDV7GnvaTNzHXP1Dy1T21JZ0NJmh+r/Rr55vWeKsPXW72V3zDWWUBjOkWGVqWxpSe6cegYEyqfQndetGwj0VoPYG8t1c+07ZE8PYJrQwlaHWDOXRw381+Gh1L1ZsRlyOlVTVJtuAcAjrzapTQz/PhTIpAIGDicb/dgTra3jz8eTZ+H+Q2CQQCLt5eJhkQuuPDreCmn+hxHKHjmoIlSUff0QeNhN28elCg9Fk0e1dm8IrHV+/C92t+iqi9R3ikBJoF3a1SkpdHNLoIO4z/fkrU+3AIaswPPnv7ct36dY8vttScPW87tZXj/+dgZ/WSkWluHB541dZEN0O8u/fDTqqr6KSnDQLOEXFPFddmjtcQoB0Xx1G6AywyrNreItMDrANn5AP+HWiebnABjnqThK1yFyQjAsGQMilc50nuEs7/pZtcWC1j7XaO+ZUnPrW5ZmCK5KNldvgyPP07cXcAf3vQFf8yeaKDKDP6uDznDUTaQvr0CuMs/QddGv9h0RnU9vguNA6ZWJzYvihaHN4OrB4ZQVL7l2igWJhQ/zu1W8lLCBJlPMyMlhFi/MVGDYXvTYX7IcpaHSn5G81xBML2QRijHz4SpnAhLySLOUK/vq/Z2fb3sxpPd8hKI0cKTG3zoQFfrtVmpqkyBvSTDBwfH8Xep/Zs14z5f8Fjsug=", +) +_NAME_RANGES = [ + ('CJK UNIFIED IDEOGRAPH-', 0x3400, 0x4DBF), + ('CJK UNIFIED IDEOGRAPH-', 0x4E00, 0x9FFF), + ('CJK COMPATIBILITY IDEOGRAPH-', 0xF900, 0xFA6D), + ('CJK COMPATIBILITY IDEOGRAPH-', 0xFA70, 0xFAD9), + ('EGYPTIAN HIEROGLYPH-', 0x13460, 0x143FA), + ('KHITAN SMALL SCRIPT CHARACTER-', 0x18B00, 0x18CD5), + ('KHITAN SMALL SCRIPT CHARACTER-', 0x18CFF, 0x18CFF), + ('NUSHU CHARACTER-', 0x1B170, 0x1B2FB), + ('CJK UNIFIED IDEOGRAPH-', 0x20000, 0x2A6DF), + ('CJK UNIFIED IDEOGRAPH-', 0x2A700, 0x2B739), + ('CJK UNIFIED IDEOGRAPH-', 0x2B740, 0x2B81D), + ('CJK UNIFIED IDEOGRAPH-', 0x2B820, 0x2CEA1), + ('CJK UNIFIED IDEOGRAPH-', 0x2CEB0, 0x2EBE0), + ('CJK UNIFIED IDEOGRAPH-', 0x2EBF0, 0x2EE5D), + ('CJK COMPATIBILITY IDEOGRAPH-', 0x2F800, 0x2FA1D), + ('CJK UNIFIED IDEOGRAPH-', 0x30000, 0x3134A), + ('CJK UNIFIED IDEOGRAPH-', 0x31350, 0x323AF), +] +_D_DECOMP = ( + "eNrtfduSxbht4Ht/xXyCeCerXFslktJ/TNtO1dQ6djJ2Nr+/FKALAIE9E683sZN+OYcAKBAAQfAqal1++M0f/1R//v2P//t//bAsdvnIP/zmt3/653/58S8I/7C4JX/YH37z53/7l9//fOCi+QjvPP7DkTzOfhgKugOUjxiGdLUdLEQmmzgjw8C4H5L9088//vYvP/3pj5jhB7t4f6T8kXVCsy+aI8/Z8efNIeIy8l1pQ9KWpB1JZ5JekY+7tBjpQHgGwjMQnoHwKSR/IfkLyV+uGhrpjcizk2d38uxOnt1l/jyqYFkCkTMQOQORMxA5wymbA+94no3EbpHYLRK7RWK3SOwWid0ikScSeSKRJxJ5IrFbJHaLxG6R2C0Su0Vit0jsFond4i7zo90SkTMRORORMxE50ymbvdPUfzyxiSf4SPDxwVtiwzMNvnfJT9KItwRvCT4RfCL4RvCYPtrLjT/T7vZhT+rFE9+OBB8JntY1aS+XXiSN+RvJf8qTiF4kjfhI8JHgE8GnB28J/mq/mfA/0+5ug474lSNt0xO8J/hI8PHBW+LDlsaBdMS6JzweyMWvPLAeTy1xxadWIi1J+0q0O9MQPRrxFpIG/JWfpDF/I/kbF+bIsNQkJDyR7o5XZ4kkDfirRJLG/I3k5yXa2oCCzHdifJJGfCT4SPCV4CsGQ0saMkkD/hQskTTmbyQ/pgNpgImkA2mAiaQDCYCJpANpgImkgyf5STqQRppII8UA7khQciSwe4L3BB8JPhL8SvArwVeCrw/+dOxE0oE02ETSgQTtVCT+fHYltiVpxCeCTwTfCF64bnIf9nYKQ5xipLdLCUOUO9KeOf8wtUldtAhAbqJFaEhoO7J1AzKuSoOSyKOlvB/ftMc3EjEMaV8kjfGnkXjVSJNppMk0UvWNVD2me3vcaSfpTqLNTtKdRJi9ST4LwS8QwZp/eG5P2tpI0unJ0yLJH69R7NUvNNIvtCdyXvgq7HDF7SdttvXmb7b6pOvD0xYSIqLmijAoDauCTOvbkRB5qWCICoaE3IWEUEw3MlzZSBpNZIiJzqrJpMqyHB7vxIX2B2/IUNDQoe9OuvL9wRsyzDN06LsTV9wfvCHDPEOHuztx0f3BGzK0MySqn3kSSQPekF7A0CHxTlx9f/CGDP8MifY2kqgeSfSOJHpHrK9M3ONMp9vOidiZDpnIUOpMd+LqO0l3EuH3IHvJROyWsPlspCmRXjWQ4U0606nTqVqmMzcbI5/IrQxMbPpoU+FgZWDmc8LEZ4zj2TGRfM09ozYhTRpyVZDQvl851UlupfNiGx1Xu3FZOTVxk5XwEZ7Ad84bnHEInW3QLccwqHzElyQ+fMD0tiq0s/GuT0N2hczdYAw3UIGQE0k/0xhX9ie9kvzrMw1z7eqh1/vhjJmeuZGrT/muEkaVFFwp00qYVsK0UaY7eYAwbbcGdD3CivUJXulDWni2P2PCMy3ytSjg5RCSMl5FBrEw0iwXrIgC6lGzVDB3hAhvntnomYbZrjfn4HN4g18i4sOBfwZO3uTnWeuwwdQbH48mNWaFJ2CO0hwpzZHSHCktkNIcKc2R0vxZ2lGSx/EqRFR/RddjWuNNvAeg3p3p7cAvBE/SZrmd4MTDjP20SyRSQ9j12L1h/v4401luJuWe+ETwifDPd1g8tfTEvpngTz4bwW8Pn43k2Yg8tj9pT9JYZ55Y1BN8JniavxI8pi3RyxO9bCX4M5034oTh6HxCth9lUOPBJgaIVGcaxIlH73alER8QvyJ+9EIPS8yRPHN+ZCGRTc25IhKeOPq9owR75DanFMf/0YSBcDhrsSNvce0D/hZMu+PPYdoOBy2HEx2AOdKRpBNJtyd9zCzutCXpStI7po/RfTnUKXUDAqT7CMiHNOuBqfjEajF9/K07po9Rxers8QNyr4evHemjvtdD1hXLWw9Z73R7HjhkOtLHULYeHlADtBBMO5DpxKNM9dCuIqd6aHekjyZRj5FuHZIf7aYe48qKKtVDpTsdMVMaMjQ/gDbKS0PqdsTu1sMR2tqR60ibOx0PvTHdLOLXM/94rh+cOkrbD2nv9IEfkg/fXfrR0HuD5cczDZGnH9ONA28ufN8/Al0C346mtzn7kelIY2sHdvQitlDsOiy6lcJ8E5Hr6IB2uhy/H6OHIe3uh0j76IXXI90wPZxuD4akI0lXTPcj/3KkAzybjvzp6E6uNLS9vR6IvDCZTqTBDE7L4DBDvrgdGY6HChG3EHFXIu5KxF2JuOUUN/YfzGLD8bN9jNHrNQ4yoyo+1mX9wdRlUKsLQ5uRTiRdSLqSdMe0H3+jrSMe8q5PJtcw7Y6/DdOQd3/yeHviRyh+hmuej0MbH+F6yzZRvOfUQEGTN07lQ1qfOVg4yIfSvnKQjzh95+DGhdzZANTyTZ2wcFBQuYIhcJBrFJnpLOdsA6WavvCCogB5uTFwVnwmEfhMInDjxMT3vbglIzOdEXaO3HTMGqabyEExZeGGTVyjFPiznc+rdp6ZF2SZNc4R7gM6DrJyHfdn106ZP3HZmQDX5O2TSvtJpfmkhX/Soj+f8e8F0GdGodsjg3f96MiIlYUrOF4H3AX35cu6j5zKq1P4q3AyOdXlPsemuqaLyWwR1dlZ5swLKlyqxKXibmTlnJobhzuZTbwgMRPNnFVmrMwqpudc/czVN41TxbNifrxy9bmChatfhHPnD//slQWyV4Zpb8mCB0kD3roHf6YB78yDP9ONLLxtJI17ZYnslaUHf/EnacBf/Enak6X9SNKI7wQPaWPsPbcyOPNbCN4QPFmQu/iQNOAd2YPFtLX5nkFZS/eyItE3ir21a1uGpHGhK5GFLrLndtmHpH0m+70kjfkJH7p3ZzeC356FQ0f2is90I3u/G90/r2RhtQr8JSdJA96R/I7uqjmyq3akzebuxbmRpvZphE+TfDrhc9ZXJ3KSNOITwacHf8lD0rhgTPbiFrIXd+XfRH5H9vQc3dPrJH8nC5CGLEAags8Ej2vq/lkCM6jLQvCG4M8FV7K+lRaJTwRPt+/Ith7Fnzom+9RXWJ/6CpUsiJKYkEg6kH31RNK4MOzIwjCkDdnCMsgf03Eh6XsB2GxP7Bppyp/EnOQF/iqXpAOJOYmkA4kziaRxW49sG1qybejImQhHzpVcfJ60ic8apCFnNwzujaAPxEq2/iLZxiRpwFuCv/RK5IwGSQcSqxNJh0TOa5B0IOcFEkkD/iqXpAOJaYmkA4ldKcszNYksqNOtS0u2Lu2Dv8olacA7sjV6tc0s6pfpuJJy5S7TEelxtm7SuTMQ7o6VHOqx9GBUITsVmG5kL30j6fZ0WCd+IfhC8JSPI3hsmOtyGWekn8NHYz75ONXiSJp0lAvpKJenrBNfCN4RPC03knLJIZfLPiSNO2CF7IAVgif5z3Qj+9sbSSN+IfiF4AvBF4J3BI/y1/zYrb4OmhWy81bIoRVy+MWSA2WWHJKi+IsPSXdPOgKSRvxC8AvBF4KnfBzBo16tPXq1/vjD+nQKZjUkvTw+sBqSXh4fWA1JL48/rIaklyeYr6RdBOIDKQj8qUsKhP8zCDGVyvwcWDvxC8EXgqd8HMG7B28J/pKHHKZLJB1IXaci8xeSvxA8yb/ANgVu9Jy7WJiGznRfbl1G2pD0rfuFNw/e2wcP6XMj6+RfKP9MeBaSzoRnIelM+JeHP2xOXfKHh78h8hsivyHyG3PvzOPu2iUn5UPkNEROQ+Q0zwFM3CC75EkPH0vksUQeS+SxxJ6W2NNSexL+hfIncloipyVyWmJPS+xpqT0Lkb88/B2R3xH5HZHfEfkdkd9R+Qn/QvkT+R2R3xH5HZHfEfkdlX8n8u8Pf0/k90R+T+T31B8In0L5EDk9kdMTOT3xh0b8qhG/CkSeQOQJRJ5A7BmIPcNpz3uX1xw7KQNfrsM4V9o86dM+jdi/EftHIk8k8kQiTyTyRCJPJPW7Ev4r5U/sFondIrFbJPUbSf1GWr9PX+DWRvanT1Qn29QnaiO71SdqJ/vRiGqNbEufqE52p0/UcbjxCnaBBLszbUnakbQn6UDSkaQTSWeSLiS9knQl6UbSnaQ3kt6ftCXyWyK/JfJbIr8l8lsivyXyWyK/JfJbIr8l8lsivyXyWyK/JfJbIn8k8kcifyTyRyJ/JPJHIn8k8kcifyTyRyJ/JPJHIn8k8kcifyTyx1v+y4kjSWMjSYvIc6bXk7+98dgwanzyFMKzPKfWzzS6byZk3PMQJ1HuwD+jvY612OfoyilU8kSJRJTYiBLpyd+oEqT55UyOupyo8qBOsz5t+EqbJ037tMvcz0kpR8bsrizYfdNQuYpu67IuYVFIcMgrRNt9eyTat0ciSF+sn4MPZ9qTYzTIrp4hhwyg2j2AOh+72FUSgAnrlbBeqWkxJK4Pu/Pw0Uk+12cXCHapPfXTCkmT+mzlqc+d1ieJsLmRo0gnan9Q+MRSveZ6R/9mF5gyjL+XI/4tYP4a1n+UQSIM7JiRKqe8nPvoDCnOHB/BboZESpFSknNHdswA4Ic+fyORYhklwI/IHgiFv2Zm4Ie/BIGD1/BBd9gXt8MP1wOQ1gjlDObcZhKj2Fnanr2SxnfrYuEvwvHNO8f3oBzfI3biZTe+z+v4Pq+lWyXWGvHGHd/YtZyV5aziRjbpLn0+6ft2n/Slvs/nlb4L8BSgW34uUoDuGV7afVLdPqlmn1SvT6rVJ9Xp89TIPtuRVOpIxbm2Rz/p+cpPujP8SQ+rftJ93096YvOTbgF/voyYqBETNVXyH426U7CYI2S5yLYcA45zE1OjINt/+tMf8US4yHdM4Q8kay7HkORkK5rHQ0m8WzZl4TyQcaRlx8Qkyb8WihQylnMpX0CNcWnwEuhF27SXHvajUV5Z8HjBDRkG2S8h2rSDuw9QkOr059KdPGmBhE5FDStOoMobicc2jmP5TG8rapw8F3lODkVmoc6sxx0h9EXARsBWwMwLYxEvqcVzBXgJtK7hDOwDVcrDFQatJOeIBvDu8a2JZ2VzKAi5KLQe3eXk1eD0xWvD5QuauWPnJIN70ewXtOe58MVz4Yv3mN80/wXtKS++aOEL2vNc/kKW/AXPNy19QcPyRBsvEp4jZ5Qg3gh4w8qTJ/IXKNMixVsEb1hjnKc85YtDTr4zJOAu3x3V3iXVkTNKElZ7w8qTJ/IXKNMihdXesMY4T3k22THKl6wE3D9W4aILbdbDX02B0fch10jbM+0OwJ/APoBOcnVP0ucTR5OxsKjjjiP0I51PwpGu5wN5APbMZI90wDSZDgxkhR829L6QSLGMssGPyL5RyhDUuvbI4x1Jh0ccf8p8nDcew7mHAKsoI32U7/ul/cjTSHq7rWKjJ+nwFJbsg09ECNgDvvAJ0+lIrwRfn/yZ8MmETyZ88snHHoSVPLBmki4kfRUApTVScn/SxZC0fSStpIDqSJpYol6WaD+MKe6BG3/Dw91R/T/9/Ns//P4Z1RPYCtgJ2As4CDgKOAk4C7gI+Ok7JdJoSKshnYb0GjJoyKghk4bMGlJqZB+NnpljvrLbolHslOKmFD+lhCklTilpSslTSplSsFa/JpuvyfZrsvua7L8mh6/J8Wty+pqcvyaXL71AtRraSkxv0EIS6TSk15BBQ0YNmTRk1pBFQz7OoFLMlGKnFDel+CklTClxSklTSp5SyqyuVBtAzcdpW4jTZhCnLSBOnT9O/T5OXT5OvT1OHT1OffzYxZhQ6pTSppQ+pWxTyj6jpGnAStP6SdP6SdP6SdP6SdP6SdP6SdP6SdP6SdP6SaR+7i7Ni67Yi17Yiw7Yi77Xi27Xix7Xi87Wi37WS3lWAVcBNwF3AW8C3jkcxHgkCP2D0D8I/YPQPwj9g9A/CP2D0D8I/YPQPwr5opAvCvmikC8K+aKQLwr5opAvCvmilE/UTxT1E0X9RFE/UdRPEvWThP5J6J+E/knon4T+SeifhP5J6J+E/knoP0aDwdrZhAtnXZEtAh+vSJ8/Yqp+TJxmSKSMUG7Xfs0q1uVZpuavhw0v3J+XnGw/vMiRtxhjbf14jfRGlL3sdBvJbwsb5vqNX47gNxcFvHM4FA7nIODG4VWUx1+fD4bzDyYGAVcOZ8vhEjm8ivzbwuGd87fcHsEW/rzdmb7BmSBgro9zmcPecDg0DkfBX+jnKtfPNcF/YyseIXZ2LUZIhts3b1y/slgBc32K0LdYzr8kXn4N3J41C3jn8reFy9csl6cJe7a4cThx+/bO9esbl7/vIv/O+W3JCngVMJd3272AOb994fLs/FhE2IW99sjl24V998bgaPn9FdHy9hutZ+XH4dAcdp7DOXG4CHgV+fnZjxh4exsws3+MO6cnIX/i8ShWvnkea7QcTrz8Wrl9auP61+4FzOnCH2MzPH/j9koLj0/J2pXDvD4GLPLz+JesTxzm8TadL8E+8MriSXLZC5g/7zvP7zcu3wiwAubyBSvofNkkhczlC4XVV4p8jXnAncPrxuHKy48bpydefyltvLy0M39IxfH6KfyemIQXNzzwyu+lSCv3p7Ty/iE13l5T4/FuiMP134PhcOby7ZXZJy/8Ht4BNw4by2F+mW9eePzKC/ePbHh/MuCVw7ug77x8K+SxpgqYl295PM+Wx99s+QZBjnwfJEfe/nL2i4C5PJnvEOTCr/LLhftvLnwHNa98vJCbSxz2kcMhcFjo0wrXp/Mdi9wTL6/z+JY3Pt7JW+P1tfPxTN7rImAmX1kK869i+L5VMfx+pAE3DvMd6BJS4jAfD5Ro+PORj3cGzMuPG7NfSbz9DHjjMO8vBsz5Jd6ehzt0DnN/L5m3v5JXLk/m8WjAzN9L4ePVAXN5Co/nZRX81y5hzr/aIGBB5ye+Ct79QmB+d2FpvP8uW5Iw57+tgl65PTY+fhkwt/cm/Gfj8XXAPP++8PoW46uy8/FD2Xn/W3Z+7WbZA7fPnkV5hdtrH/ObMR/8zb//9Lvfn+fNHNm8c0c8tl/NB/g+b4BzjXY85+v4KccBDXe87fuk9ycdDEk7kg4knUi6kDThHwj/QPjHk//BOnqCjySdMX0UE89nzZ1eIU+yDx7TJz4QfCD4TPCZ4CvBV8Sbo2AfLyH4acMz9wuJ7Eq/M/yf3//8l59+++MfjhrLR4mjGz6oK7HSSqy0EitVUguV1EIltVBJLVRSC5Xwr4R/JfwbqYVGaqGRWmikFhqphUZqoZNa6KQWOqmFTmqhk1ropBY6qYVOa2GNj6AbEWJfSNqQ9CnQodOu1wXYc0x5HWlDxvA+eMCGw+sq6FbQm4C7yO8E7AUcOFyFPFXIU0X5VfCvgn8V/I3UJwo4CThz2Ap5liJgyb8KWNhrkfbaBLwL+YV9jJDHCPtEQY+SLuwXhf2isF8U9orCXlHYKwr7RGGfKOwThX2isE8U9onCPknYJwn9k9A/Cf2T0D9J/aX9RX4j8jdhnybs04S+TejXhXxd8OvCvkbw68J+XfqToBtRvhX6WmE/K+SzQj4r5LOivq2Q1wp5rJRHyO+EPE74pxfyeyGfF+Xvwl92wT+I54OozyD0zcI/svCPLJ4vovwiyi+CXxH2WY8LR69V7WuJ+gbZtUKDSk/Dh9grp64MtJ1TaeYU2HdvrqXtGzQcXOiFRaGwQ/khOS5zXT+i3Kk7+i19D8/A9QQTiptSwpQSp5Q0pZQppU4pbUrZppR9RjFT6xgzpczttkBH8oXBvyS7r8nha3L8mpy+JpevyfVrcvuavH1N3r8km6+NelzT+BXZ/grJt6/1LnfGowrW+su5sdTtfuuEZTyCjc7iiDszyqytHNFo9kyZnCAIZnYiYpTjps9MywkTbsfMU6cca/A6JU1PeBzr4DNudsLtWBuayJbMJCoc+wcTSrbrVJ9J/aTiJu4V/DKxW7Kzkxe5rWZWzrQW4PynXnPbrLZ9mnhiqLMzQCnOuHl4A13Xp6WZ7wQ/03Tqvfssamf40oZO2d3rLEsI/KxH2BI7i3BvWZ1wqnk/3jD887/+248/n2dDnld9tIOfRkNaDek0pNeQakFRQyYNmTWkPLXqtHO4TtPIqceGNY2cppF7aXTPwR/YCtgJWD4fBZwEXARcBdwEvAl457AR8hojYCn/8kxEiZIa0mnIoCGjhkwasmjIqiGbhtw05K4gjabm2Y9LA80LOtYs0m20okm4XQrwkzyXVnCV8YW8T6nccG4c5t5xzQIeemGFBMOPKx09q6CL5wPLf6/aXiHn2rW+Qo44LnXvEt/5Lct/75Jc/K9TGndI21hrOfo6UT7T/+jXGD+/MPmT5cedjp6LPy/0tdVzeuf6Bh617lMgl37ieFkwXP7x+MLttXH7ZB4tjr6E8yuMf6z8uNw1DXxgK+uf1VfoW+Ty7dw/nOP5a+H6V3787uh9ufyL4fZv/HnHjx+GYpoWgqOGTBoya0jZf3it//Ba/+G1/sOr755o/YfXekSvaeQ1jbymkdc0Csp7HM68TplAh6ognYb0GjJoyKghk4bMGrJoyPMg/oxippRHwWcg5PN9MvRBwgFzOBOtUvDgK+HR7sEUq2a3rFbAkh4FnAW8CrgKuAt453A1AnYCDgJOAi4CFuVXUX4V5TdRfhP6N6F/E/o3oX8T5bcmYCFP2wQs5OuifrqwRxfydFF+F/y74L8tAhb22ET5m7DPJuyzCXk2UT+bsNcm5N2EvTZhr03Ivwv5dyE/rqpeLWHM1/zoaM/FyRN5NILDMrC71e46FuStXjtt2A0L8n7sefX1blGS3G5dCcWDw1xP44aUIAOlyRKPPbu1AFlQ8rVXCZudqE5R8gAFNkp3aYz1FqholHZ7DaHUS16sX0HZDoGa00wL5A4ParK0i/xStN1G3wRlA7KCbKq6UHiYSrBddd+W6dNdRUKVXtq/LHbn2YjfaU7yZNxnVpwXQylXCS9T7peKtd3V2LU8/ZZUkOutg/QZ2AtG+60KBZ7pklu4xDhFU8hnu5g5JGzdb+usadU6a1qEIox81r+iY0t3x0SQRRFdtX9b736AILdZZcPpAAwdnlOeCDbXgkQ5+fSt36YFq+6vWAbhRfXVPq0zoFSheHdaTgyxPGoULY+bxeserwfBDdY0K2bTQiicmgAl6j6L3BDoa1eQEGO6VVhiI/DKM2qw7XewrVK9clN2Qem825APtlsMSamaIfrNqGjZVcPclBe3jTfqPiO/WD4tYVcooM+qUfbbA7akCbTzuKaRZW92InlrEfJCPJf9z4mchYBf6AM2P+vLH8rrmfgMTQRlfUKL9uB6D9sIsl6NWPaA213j0Oxe3LTovLXHRY86UqUUvR2ZKi0/pKW+39xWkFZDOg3pNWTQkFFDJg2ZNWTRhZ+rNdPNTBU0Uy3NVFUz1ddMlTZTzc1UfTO1gZ3awH5RvzMb2KkNLLcBmTnna9shGkHxChKv3Aoip73eMk9WUHZlXg5vQkenldZV5HE5nJ1SBCO8AYlJGLbkfojWsAYZo+2vWdHx0ti9RvfkXLYfYquskcOmXjjuHva7We91TaGllzbd3khXm5aza8iqIH29X5omyK4hk4KEN/2jea4g5KXNyem5r08qGDUFNeRrHadryKogfX6+2yXso1HQHiolzSi4dKRQDtmtMe4lu4L0GrJqyKg1gO2NPC3XNct1rW67Zk79ca2luSlFRdYvs6tNlhThtCLctAilCqwJz9WYKkWRTQ+AdUYBb9IpaUZJd5CMfk6Zya/nUTSBVvnSfnsj0Y2SZvBX4YsSxYFn0Br1K2fXkFVbse2z7iIkrfSkla6FlKCFFIn0s5zHTZqvnC8kHhfa7otDRH/g7X2XgPR8tTkIJ/HuqnY9HLr78pFN6SnVniBpQ4GXQ+fni6xPzvLcSyv6oaohtQiUhIJRjWpNKQiRu9ZTtOf2XRF31GBUtF6v39ybEiR8VrxzXut4oGNRjIAU2XqdMoiC+2CTaBXH58BeWoV4O0l/jdsYhW86iVefcU/mjXQa0mvIoCGjhkwaMmvIoiGvTacJxUwpdkpxU4qfUsKUEqeUNKXkKaXodTWzgf2ifmc2sFMb2KkN7NQGdmoDO7WBndrATm3gpjZw3AakoScysk22dPIBYP6ta+/bR39uaF5T3D8y+56141+75revB3pmfDGWUU1wHy5S5pZe1r5Wfne7ZR+LXusIICv9rm3/8L2k4+XeI07FCHc+nK/a5gaLChFfXPQbbJMHB3Y53xY8/0KBd1XPwx8Bj62FgjzNfiiQIhycSDucuM8RLgfICe5MyRleJS8LfAUhrnDgKnZ4vzot8EpFcrCDkT1cNlPwvZVSdpQso2Twckis8E5Twtezc4TzEWWDFylCh54p7rAAkwOs0OcCfWe0sGyUDWwW5gznVgJaIib4MnbsUGyysLxTcDna7/AtkWBgbTtYkDN6WMOMK7wvknAqmeJ2ZDlfdM8RzonlCNem5A57diWBkUuF92hK36G8DJPOVOCF1NTh3pnsQNyCH7U4X1bNawdZ8NXcMdsESzR4SSYv8D54stAJpHxVMZQX94TPHbqHBlniClOO2DuYYF+wdHjjI23gZsNyFZW2UAK8YR4MXMQQ8F2atMKBj9Th9oHsoMZKhKrKeIXKsDyp97zCPSPD3Q79QgWbRXz5PznwrBTgkE1wUCsp7xXqoaLSMM7yG5wTig2EiAE6+SE8Ogq8qRsyvFCdElaHh9fB8wp79bGiY+I75bHBayHRgmTZQguIeCN4CvBKlt/gdoeAR8SG7sdfHF4EFYD1jt9EH3UEJjegdLBwa0/wMOI6TxuFbUOp4db1uEOxqcBJoxLgsEBZsQVscFynbOCK5xU/McJ+fKzwgnreoTbDBgOoaAqaHI6hRV+wbuG1oYRvxCcPFyekAh6SOoYEvPYq7xCNsoe7KsoCzxUH4S9Ygy1gBR08rPwnXJgcHmwf645WBVbadzQkfHo8VrBgarAwkrAxH1vRR864E2cIHSpn+AR4Fn7APfkzvoBGGWNqsXBgZ7g3QAkCUslwEchotxBfChRb8E3FEmEfIeIO/wgs0JwWaAGjdDByg9AVAxzUOp024YtiKUI1Zn8GiIQxEl60jhGcqESLVQVGjgl1x3fxY4e1mrhBUE0ejsKlAC/vpAyRPHUIJQV99zz9F/FO5NGqoPnidytCh7d8Yt/Qk8F7AiodDZxwiRkbELaqElFbC4eUg4f2PmIB1FHEWJDgsrqIVwNEfIN+yAkBPsApiLTDNGFUOPhL3rBjgGZY4obtDy2IF2YFD++8JQMX/idfwF8CRL4SwZdKC+jl8J35mAoGYzhFkg0cpjhvL0l4qU5q8J5WsnC9f8K3b3OFl8P81jB+OtTWoe/CId2wwUme0WdAe2gYTSt0WaM/At0jOErGt+3PSzgK3t1xXrERNng84MtuIbTj60Ej2hzvGMdhwgMyHb0caiVFbGrFYZzHuFTA8qlk7BhgmpsahFG4O8WOvgNewR8R87gSuuBJsrLso1MfHoIdSkZXLHBMs3T0cjwOMJw9QUPA0LVg4zKgSsDeMFhsfy5gxw5XegTsuUKEl0sD3ksS0CeGv3j8A2MtBYNOxJEAfG0p4kt8EQ+/R3SbMTowGDHR1hC64mbO8IRtLGIHBu6dPCIzPHcup6aCEQxHHsOQC/5F/Otoz/MPHlhB+LRioK7oLxjyEh7FTRs0yuHX2MfB+c3hdVDhePr0+vPgpkMicDC8DyNX7F4qdGe5gWvkDufXRvcCcemsODxaOXp5rDhwsIjXAVpvN+x7zFHVfrPnmCNgFDgD2oIViEiEbMOgDO3pqsAA690BQ1jAGgAHPf5gkWwM3jwO7OBvxT6kghcN/8YepWMUxy5vh34p4lmrEWCwqhdW8TAQueofY3N0OFLyEMyjD+gbUGXQWJ7RVzIYK8PZu5Wno74jJ5zsihsEg8tvFmi4l/ukFWKehVObycKm6NUOPay3pHAGNKiBFDE+RRgQXk0Vj2UnHC+nBB3g+FtwaIUDn0p9qiUM36ESD9vBay+fcqB7dhsOjdGnCig2IkskPrVWHEnAsDlj6LscDYdPeUUHPd2uwt1Lt9udgSLhQAS8oFhYMRh9SKO+GLDjBG1vz4QjxqeDlgojs3MiYG0GUxz/h4bWOTiL5yo4nl+w68XjrTZYj/8NYr9NGDjL7vFveI1l917gmrf4lEPUPuWAyKYh59mVZ+DL4ksS31rAZRfPvmIWjot0g/jOBCL5S/sXsgrkNn28f8TjAzdl/NTj+29L2I+fSr9ThI34hvrCIMcgz6DKoMagzkrIDFrpl2wgJg/kISOcFrrSh1R79Tf+SsMn+sLxqQnU40pnkm6YNiRtSdqRtCfpQNIR08djPRN8IemVpCtJN/Ls9qQ3IttmCJ7Is3mCjwSfSJrIsxF5tlXqUogddiLnTsp6fT3prsyf/vynP/z4l9//bqAjrif/009/PO4guUCWofIMAP70x5/+8hNF/PPvf8dgxmHjHDbJYRMcNskB79G6OSBIOCDi4XBmoDKsXIZVyrAKGdYXh51z2CWHXXDYXxwK51AkhyI4FMkBT5nfHBAkHBDxcDgzUA6Rc4iSQxQc4qsuuAxZypCFDPklQ3acg5McnODgXhy4FllqkYUW+a1F4hyS5JAEh/Ti0DmH/srQeIZX08u8XeS322eeIcsMhWco7wy8dZdX6165T67SJ1fhk+vbJ3m7WGW7WEW7WF/tonJ/qNIfqvCH+vKHytVEkHIwgsPLDpXHh/pq/pWHwSrDYBVhsL7CYONBrL1iVONaNKlFE1q0txbco6qMtFVE2vpyOTyCeXNAkGXglTXA4+Zw5hC8YSBIHaILh3i1nMYbZ3u1vcbbf3s178YbRns1jPTmySu4vesv8AzhlYG3pfZqKp17QJfdWBfd2CuDF63Rv4o4vjoeLbcfwb2y9vDO2oOa1ed3Vp/VrE0RoOkCiKokuHdWRYCmCyAsTXDEmhT7UrYoyhaNwbsOGg/8CNJ23EQ7bnotTtBdFzh8occb/Ypvx0UWWpFZLxLQm4pWJMm6JFmXZNUlWXVJVl2SVZdk1SVZdUmqLknVeVedd9V5N12dpvPuuiRdz73puTe9yE1lcmx7KkwQ3XX0pqIV3kFnEvTcemtwemtA9KaiFd5JZ5L03Lp/H59U0gQsem7dv53uscdxWSU3oruO3lT0hPfbYxH98tjj+JFWpNV5W5231Xk7tYvyug963Qe97oOA9l5HBx1ddPRbbq8L6HUBvS6g1yXxuiRelyTokugtDdGbilYkCbokQZdEb65eb65eb65eb65e79O83qf5pEuiN25EFx395q23Yq/3Ul7vpfykzeu9lNd7qeOzbTG9hjHHcR8Ffay1vdHHVcGDdnQ+wei0/gVt+4K2z2lh+YL2iM9HYc4oOKuM1pSRrY+zUZ3A8dkgDFRkuVkpNyvlZqXcrJSblXJXpdxVKXdVyl2Vclel3FUptyrlVqXcqpRblXKrUm59l0v6I4ET+aySzyr53HsyRHoDgQsKrig4UYZXnvXKs155NijyBYWf4vde8XsfJ8+K+vCK33vF70mseHCKT3rFJ73ik17xSa/4JA10YrZlm4rtKnZT52tBxcoFQDofktiuYjcN+y4tq6WtammrWtqqlraqpa1qaVXN29TSmpq3q/J2Ne+m5t20vHTSIbFdxW4a9s03qByCyiGoHFTvc6r3OdX7nOp9dAJCsKrv0HmGwL7zqh7lVC+hcwyJ7Sp207BvvlblYNW8as17tea9WvN0nC+xr9K8WppXS/NqaX7K99Xe6NhcYruK3TTsuzTVJ73qk171SR+nfN9aJLW0pHJIzyiTYFWf9GqU82qU87r/PlHuWVUjwV4iZc6s5cxazlXLqZZetZxVyUkClkTKnF7L6ZWcpClIpHjcazx9nCJlQZpB1OrwYqIgKfuMok8SzhWaoqNXfSmm6OhVX4opOnrV17iKjn7n1mf1Tp/VY49adLS+pqjkbnruTc+96XLrawBOXwNw+jzdxblNlBUxfRXF6asoTl9FAbQzau0o6KCjlQE4cUCB44No4noCJ/IpA2GnTM6cMjFxysTEKZMQp0xCiIsJnMjXlHxNybcp+TZFvqDIF5R8ymTFxYm+tim4ruA2xS7hjZN17hRcUHCPv9DBlzrocOqgw6mDDueng+ZXd+3UoQhZ2Ba9jW0asmvITemCXo977XGvPa6KpC2lQMbXvuyNdtqUarIyMpnA/BqSPsnS5zPngGHKUB8DEtKmtLfwxTzt7e+nzLOGH7SNzbPu53OxprQrNwkS5wBnOoX7RVKbsJs0BGUB5Zz+zeeAXdEnzJj5qSdIkgxOsygdvmjs02g1FUAVOk5C/TlXnU95N4VZmlfbryFN2Wldp9aEzynvdI6sllK4u4tOVntincm1Tlidk+P5HFsx5jkdfjvgQ9CWFzUvI4R1Rij6TPjdzn6BsM2n1dtsRTRMp9dfzYX7F5NnpaQgxsevafi8JHWp62yBcyFOdd2srE2fMX8xmZ7P9ftkgVdr2efqwBcLBzNmbbY8rLQFQtAWccN8vh4mmyXaYJF05lOCsq8xZ7XNdkLC5AlNxafP1cbK6sC6zYKQm0jlwqRNu1ljJ6F+nbRofQ9DIawzVrP68DMj+jAj2K88a9KS7dfhRO2Cy6wcJ/aytXYiY3MQM2UtoKo7StN4/mVrlGO6Npuk9Vm9hBnBzHw4z83vvu5+9aAzH1C5SVMl0Wj9sEVbefDqIVX0D52G0wUvFmtfGRzf91XOVNypXV8U8V8cATL3aDWrh1PwOc8X05gM+ebg50esJkdIKO3ab3+Z5SK8RLl39n9JBKw5f5fQbl9Pc+uDaVp7cn0YTz+TO5g1+eFc/OAEw1iOWRZ4qZdjqsRY88qzS84mvjCJY+xyvIqZBCrITPhdUoZxsviw/zIGv7bCMEVi0kvV1F9q+BcmvDDLC/M2/frC1BcmvzCvryEv72p+yYzfQWKY/RiIMYu9dA/s/iK7uO3/Bb7q5JfgP//zj38g/nuCl/M+VPg40A2ikz7gykHBmbK6POyhZg4WBiZeEPrHLSRjdXnGw8pxMHKQy2x5QbZzjRoHNw52ZpzAM1uhLxfSLx9BO59Utd2IOjkf9WHVo1E6elN3QCanpNQ9kcmpKXWXZHKKSss7OXFltbzv/vPVH1pxKuj9CH9nxL7e37H8PI599YdWzBOUw+7iFNfrkIfcCHx3+2Kx8X1cXYyPXic75A7ii4OYDCjn0MXE47UwKLce36fNxSmr19EPuSX57rXFUPO10Cg4KKfSxZj0dUxEcFCOpIvtg9fhEcHhff6fv5WmjNH4sSannJ/kGd6bQtztnX3vMYlh7mu5Ui6uvzevxJTvtdwn19ffQz0xm3wNygUH5fS9mF2+VgkFh/jekxXLfa+FQbkh8D53zznk13EZuXvwHlCLyeBr3iI4KLu/Yg3wdbRGcHgfGRan5sxriVAE4PfMQ5yxs695seDwnhk5MSd9Te3koYH3+XMxeX3Nf+UJg/f8SUxNX8tqgoNyDFzME1/zdnl24X2qm3N4H3YRHJQZGOeQ3yetxWHK93lusXTyWiaT5yr0Fwqssppg9axOyer0rNoahf6OgjzBeuLGaOvff/rd75+B6Q1ZBjkGeQYFBkUGJQZlBhUGrQyqDGoM6gzaGLRTCPuLG2L6OaafY/o5pp9j+jmmn2P6OaafY/o5pp9j+jmmn2P6OaafY/p5pp9n+nmmn2f6eaafZ/p5pp9n+nmmn2f6eaafZ/p5pp9n+nmmn2f6BaZfYPoFpl9g+gWmX2D6BaZfYPoFpl9g+gWmX2D6BaZfYPoFpl9g+kWmX2T6RaZfZPpFpl9k+kWmX2T6RaZfZPpFpl9k+kWmX2T6RaZfZPolpl9i+iWmX2L6JaZfYvolpl9i+iWmX2L6JaZfYvolpl9i+iWiny05MAhk+eOPP//8p39/FrQI3ATcBWw4DBdiUljwW0V+uGWPwkHAScCFw5t4fhPPb+L5JvLvQr9VyusFLOyF39sk8CpgYY9V2A9vqXjgKuxThbxV6FeFflXYp4ryqyi/ivKbKL8J/ZvQvwn9m9C/ifKbsHcT8uB31ggs5OuifrqwRxfydFF+F/y74I+fQiKwsMcmyt+EfTZhn03Is0n/FfbahLybsNcm7LUJ+XfhL0WUV3h5JnL5jTMCtgJ2ApbPBwFHAScBZwEXAQt5XRVwE3AX8CZgbi+8KJPCQn8v9PdCfy/090J/L/T3Qn8v9PdCfy/090J/L/T3Qv8xNvEMFvoHoX8Q+gehfxD6h+NOUQoL/YPQPwj9g9A/CP3HmIXzF/oHoX8Q+gdR/0HoHxfOPwr9o9B/jGL807OubASwshHAynrklY0qVjYCWGmPfPRw9inRBt4jW7xFmcJGwDI/qzEbVv58GBH6uNTN4BV37riNFqH1hOh18xavMXlAw+6P39iF8RaDzw0O3yFX0eNlzc/98JE/i0Z5QM9Z8cyB3jxvejGcmjm4cc5cyMgLOr9bcYNc/VLZBfmWX4BfGn+WUzMvaF05WPmzjSmI16s/F/FnrlLcRG5uyyzJ/CMAOzdX4qZOTIvrMzE3dRWsBa/OQS525sZd+bNr5O7CrbkK49JnbRtSUs/LO3+W67DyKi9MDNMWDhoOWqG/sIfZPvK2/GDM6JiP33rczHxA9YT2438NJ5TdSIw++fgF5zoge0LWtJFyPh2/0M/d0GgPDhL5yHzc1w//2R+/Y0hYAKpAsx9HIa4sZ07nEX0S7QPBDZkPrXzsx5O+FvhdgXhBCzx4Qf1jP2QNNR+/EAsPqJyQS32kigvwu3z4tA1SNGbD3yP7BcGSy0PbEbKFQmfO5aQZltMyyJw5mx/6xx4T/gK1R8egckJhj+25f/Rcbb0gyyDHIM+gwKDIoMSgzKDCIHYXqq8MagzqDNoYtFMoLAxi+gWmX2D6BaZfYPoFpl9g+gWmX2D6BaafY5I5JpljkjkmmWOSOSaZY5I5Jpljko2xqY/DR/sYxRy/sGpxQJlBO0Abg3YKwZrCAxkG2Q9kfjSOh2ldGVRpEbUxqNICT9r+YYd/f7vsf4HLRiZLZLJEJktkskQmS2SyRCZLZLJEJkvksjBbR2bryGwdma0js3Vitk5Mv8T0S0y/xPRLTL/E9EtMv8T0S0y/xH3p26//0f3afnvytyd/R+j/xn5tv/Bkx7zVfeGR7q/0OvsP4meWeZb9/+5L9jsqfkfF76j4d+LX9q/0ZPef7K3//6Op/fbIf2iPtH+TaGqZR/pvr/ue9Xz379/9+7dff/v1t19/+/W3X3/79bdff/v1t19/+/W3X3/79bdff/v1fwO/NuyAk3V0fdcVSnPFMsgxyDMoMCgyKDEoM6gwaGVQZVBjUGfQxiBaD25dGMT025kOK9Nv5TSm38r0W5l+K9NvJfpZu7CclclSma0rk6UyWSqTpTJZKi+ByVKZrSuzdWW2rszWldm6MltXZuvGbN2Yfo3p15h+jenXmH6N6deYfo3p17itWXk749m5FzCpO8u5s5yd+/V3W/luK99t5butfLeV77by3Va+28p3W/luK99t5but/J22lc6s1Ds91/Vf/gqU+ZblW5b/gCzZkRdkvWOvz3pnOGg56DjoORg4GDmYOJg5uHKwcrBxcOMge3vYe66R5xp5rpHnGnmukecaea6R5xp5rpHnKvjOQarCGjN75913DvKX6z1/fd5vPPPKrdFO8JNW9iet6k9a0Z+0mj9pJX/SKv6kFfxJq/eTVu4nrdpPWrGftB4/aS1+0kr7pHX0SWvok9bPJ62dT1o3n7RmEKDieCpOoYUGyi3QcgI3MLsYYD3v2L2po+fv5ektrivzLigzqDFoJ6ceI9vviCxOXNeuXjRWAtsLiWzvJbK9l8j2XiLbe4ksEkUWzyLb64mOc2FyOp6TlW6ZnLYyaGPPLQzicnIrMZ5sxyGyMVFkY8UYmeVfdURrhe4AHPVg/44sb/9KW1tmXcvsmZglwhe6W6at/dX62V+tkfvVUltW7/ZvUtO/vsXZf5Ca/vXtyLKWY//K6GaYdc3fJNbZ/1HRLf4n9yT/s6xrfaAfc3DLfTOsRDaBNBrSakinIb2GDBoyasikIbOGLIiMFHl8+mbx5r5LV1LslOKmFD+lhCklTilpSslTSplS1imlTiltSulTyjal7DNKWKaUaf2Eaf2Eaf2Eaf2Eaf2Eaf2Eaf2Eaf2Eaf2Ed/0cHyVBfa7vkfz2p59/+wdyJ/ED49EcSr/PHJFMCQ/VHDdS/eu//fgzufmYwFbATsBewEHAUcBJwFnARcCrgKuAm4C7gDcB7xzGA04EFvoHoX8Q+gehfxD6B6F/EPoHoX8Q+gepf1aYQvt7leSU6gHkS4fl/nlJe1Z5JVetQWl8AeHE+Tdu2M967jBYq2l5sG5Jdfzwuj3unL0vniXI8LE9cLT8oVC5gYNrjT/fGN1vmdFDMczguWyO023hz6/MwjFa5lDJWOZQMRT2fLDcYcMu5DG58+frwp83jJ46b7ApGObwua28/Lxzft4xetwN188W5uBj8BK4PZZFwIxfEQ069C3y/Jbbw+2Ol7ew+ss9LVw+7typZGb/tCZevl9YA4xb5vwSl3/AmdvXcf+widk/hMr0K8fFqEEE9Zhse4I6pRzmm1Hy5JlQ8+SZtNQJ5TDb5JnY06Qc2/uEWwjnM/npb8KOu2Q37Lb9o5T972iFeG9LGoaFq3vHX4Y/6BDtYuAjDn6Hizf9vm7wB5tKAS8rD3hoMuBVxwFv/A54cbTzsIFnz0llwOtxg4HeI+Dlx8HA8Uw7uqAGj8Bu1iACH4wDgwjxLpiCWIg+foMgNyD8g+0zWwzcKT0CwAEGuzjgikgLC5Ij+kT4A6cNeKemCwYfgEg5/kAMCxdMB7uD/A5u8hx/8LiDLwIGB313cNCFjj/MCWdVx1/Hv/31Z5cVRugJD8COiI0PdiTWiAzgQuqA21Wj1ULBaNWA664B1zuDj/gH12eGUWPHX4Av+YUA0SEE5Bng6tP7D+stwMLmaLeYBTb1QoKvIIaIxSbUF9c8Q0xoGQhMIW8gUmr4B/uvIcNt9SFlYJ3BmccfPJ6h0qzxaOC8I3EHbgULxE5p9D1AK3DY2ZoIG7Hjf0MqXNEdVgOFrBYZwD3kYYVzzi6CcC7CZfOjJwFaheXo88+a0hAL+5eh4vMVnblCMLamGsTuUI0NhdzRtg2EdAnibmjQXsYflNEaQujLpqPK3bsTBD4d83Y4VB06fFBgdBMG/4B5hmWU0Hcw6waLAAHbbdjgoLbLaCRrMrh9RjYb9J7jz+EfFLiBw9kVDwOEbQdDWAf1c/1nC18YCDvWAf65DG3EOgv70DaaDlWxR8wEKrgMQ4gR/5AGN82HvYNF9/2QNi5gLVcgOrgCASAucADB2tg9gFBWxJu6I164HQ2Mb28IIlA0GZGw4R4xRoy/Hf460nakQeuIFlrH+KvwB3dXRwu799Fi6Q4GytZW+BBDdA7z7AhBk4sObB3dhnJXaKvRg6kibnpHPC/gVlhRiB4qK/qEEJx5GBCEoRXO0ccAI/YYALLn5zZjAJvGCHcER/zWkKsGuEXY0HDo3m5FJ8PrqMcfSJFglDJyHkwzfgzBO9h+iti6xx8YI8H4LSa4rHn8gas63N131eMTEBRjgi9axAxThpgBss7DCwADBAYZhmNDQg/Po8IFxmyxwPGMWKA5xxVbt4uIXeEDAq5By4sVpLIuw8mMWKEfcQ2doUI0jxVOicQKS/7jr8IT69X2lhNG2fFR6xocjIgNTj3EBr4aG3RBsUMQjB0CxRgWIBL6x+NSWkSCeP3UvRvMCj103KDVxg3at+vQiccNPsww/rAhbR3ZYbPYI0q1h/MfjbjDiYmEG8xpgULGHxioF6TBMDPhB0gSvviQsJ5HHwqfWUp4R771FnqDZMAZrHfQASQLUSVZGE8ki+7v44JYGCUmHAxbnxz+Z6jW5KAZJgfh3m0Q4BMesBndWH7+Eu7XJQ+3xycP73wkD9ZLHsLS6PBAnAAfirK+wYhm+OGGILh1Cglbp4E6T9GgtDts8Ix/DE8BZ2huh1br8au0KUIfNYgY3AN+KsUGA61p/ENFpYRmTuDA9x+Y2Z81gf2bxzm/X6AmbPAwQ0kZPCxlmN+k3FCEDcvEz1OmEvCRCKFy/EPMGGN4KKzAEMAbcKO0wn73+FvxD0YLoUCct2GFhnH9pxU6Po9HZmyoWMUV/ajCCGeEKXykYd02+MKHtytC8P2M8Qe26BA+7JisAYMODuQd9BCpgyunDcpKGziZd9AEbESvGv9Q8d7BdH+AEHrSDo4z/BFqN+3gXmmHJpoXGHPZ6DtmCvAhsYxfPhogxIuMg6gRoWC71uNhn7xAV5ANjAG9h7af8ZsUY7yDfBOaLCaEHZ6GO/7b0/+Nv0ORvMPIy3vo4bItSMsnBD2chU42YzeSb6jDH3T1NlaHvOFrOWNABEQH5sxuRQjVxDNa2cFAJHuY5WcXkAYtJeNUP+OpJRuxpYzeE2QcMJjCB1gozx46p/EHHAKENptOTiFibe0wMPUBOkQf4JWzgQWNbMJvwAw0MMQv0o4/ECJCyBx/Bf5W/IPb4HOCrzjnCGOZnODFq5ws0pBZAsfyAQYJOcHgJ2eoAR8gNuYM9T7+oJbSWWDu5x9UD24t5AwONCYUYIiUYfJiU4FB4ahCzAtum1fw95EFzF0z2KPBJN+mhj7WoPmMJgxidQhQGfsDm3aL4/aMjtIbUqFfyR1WGwYR5MtbR2eC8bvNAQw6/qHwguOfskBNFQNf3rbDUBuCB99i4dFiQe3xhxAEgeLAUMXDdGb4JlihBAxSBdpWCXCc0J7Sj/nEYZIScfDbodWUBB44fBz7i2JhNO5X6Jz8Cq/YlQQf7LHFL0iERwcIQbBkaHH3H6whjc6jIhEcwVeIswUXmEqB1lgKzD/GNBnKqjCrsKXCVLlUA8QGkbA0GA37Bnl8QxvipfEjiJ1YGC/Z1WAsWS244viHBjwCLNimQxguG9oPx8MFP94w/nb4gwZTdphG2jUuy/8FuNDlaA==", +) +_D_NUMERIC = ( + "eNrtG1mS6yjsv68yNVMg9vw5Xm4y97/CBCyx2Dhxuh1ex5N2VaMQRxLakFgEu4TnH/bFL+EJEPgnQMI/AZL+CZDyT4C0fwJk/BMg658AOf/cIOMuER+i0xekJS6XG3VQ/qsbQK1RX6qDBrxZ04BI34IId0MLXbYYigo2wHQ0C54gawiEzFg8wD1ifRohNCGy7X78gQ701MKmvVpZBDLIg0Y2YMHNcpjpYouhDHHX+7VtwJxG7jI1sQSJpMaoOmqjE33ZP65H/n0jHFsImZ/F26VppGtSIscWsBXYSmwVthpbg63F9u+AiA1nkQ0M7BJRL3OiG0B4I9qINSKNOGuuBQQIAiQBigBNgCHAEuDqLuphYcB/MtRtCfA8TE2yyB2BWNJgaaw0VBopDdS3TZwBWtiu5W38ekbc6Sbafj2Na5Nc1pylimkyQ928EonIb4XD+HN+dKDt5wDEJVhlsv+Ujyz+FgmXWPxht178xaxsbiW9hq0lrBu/syURucqaUkqYciqqqPiRwbVI+CJmWE5GaaJRtazwN7HC8u9X02PGhMrfK15Mya5PBcxLU4H1SHksV0h8nOTHifeNCT7PLT48N+BZTlkce0e5zMyDeamRvx1mpTusjgTrKJ/tDgp0051KQNkHROz18HA7HVSZ+MIDImvEGxBzQNwBsQfEHxCDQByCW7IhCLOIoybMgjALjxkOn5DAK0XQq4LeFfSycEtRSaIviQEZOSAWJPEgCbMkzJIwS1fIXmpk3Yw4NtEZ7BIgaBxwFSgC6pLZFAgkjivhcDhgmLDHIk4giXm6/N+/+C1/EXGSzCfNZEeh0yENUIhJizhz+12GWS8DAtO4wCkhdXgsAl8E1BCQ5gYZdVRO/aUZG9KNUZkt1FrBDY4Z5kGjNHyrLFmWlZmJBFLDhs0BybhnqAoYiWU54nCk1filkj1Fm9GS7hwj/YQ+zH9MIB1yGmVz+bGw3uhwGKLTme6tJYYUtoaUIIeRyLhrLL1tEmvQpZ73hJAJ6LEr2KPvmaBrURAOB7r47FnfX9u8SavBgtR5tr9OU8xz16TSHgxFbBvTkxj9yX4nNHSKjNDFd28Ru4EsxvEVZeDx66TAEsqEc11RapbQJrwJcaXcBJbjzpBX6lHNcvwZgYzCsnYlGjmRnEqtnNWsJJRTyknRHLYKgXyhOrUWlaqTVktl7q3g1QE4+IY8+HLFYmsxZatV612yx4Bga+ltArxioepp6L48FVtsAKV2Y8XKT4SQrezPhqL0/8/rQx7E7xvoSGy4+DNrKqJaD3nmuW+RU4huurdXvsHalqM9Ux2XuMHu+Ol9FIm9kEDznS/zXCf3Bpxz1c3m73jVT9SX+B0uIT7T3r5pb7XqC2xJrSBX0CsIFhQLkgXNbHXZ1ncbtrYN0vZA/Xey/KFZhnhb3XW4E/HrmxVy58Lb3hgSvKaIqmk9oYrpKScPZ28eOeQeTg/CA91P8Mjr49mnRlXwk+w8cm7e7GjG0bE3OfSjeLDybDd9e5YuRMILZuC6Yxo1/Admb80bHscJ4EkOlYgWx2NcE3G9R8WCBjT1LUKqOs05ad6Eij7LMR7eZAGz9cHl2Rs79Wfo/iwKqBYnpcGdZxH+94fzUZ7myHjXKLrOlyVE2mkrbk5k3VzVb1Tw6u0Kqe36qkWOOdvkW2/21a42bd2JWO8fzjzJsGX6U0P97u+edoijHGsnHtjYmT+K3iZdni1MSQGPDzZuYRIPli+X7XIkZmNkyxFutXs19exyq9p5o+rZA7QbB2GfQ5J8NDnroxW0lcc+Q3I9GzxjoaLvW9yYdfA5Nv9UUrR9961cJl58Wn+u9cxLf6zJZUx2+BWclx6krXGoRtXiIJHq30dUw9twqodfnZTvXf7MPkulT1KNf2g8MYNKfpqiik8tqEwtLqlDf1R8abN0zu3naNypzwjwWs5XvHjoRTnYPKoM1SNGFUbl8DHJNzdJOFJzsiJJqI8pGdy6xha9yK7Dveh+Ly9OIbKvrs36KqP7GOEqi6RLD+GOxYQyt4zOiChHbuCiG7AIhZsfgaYg7fUEWGNQszqQDJ3c0otgFN3KcTpcjLlx9x/6oFX8", +) +_COMPOSITION_EXCLUSIONS = [ + 0x344, 0x958, 0x959, 0x95A, 0x95B, 0x95C, 0x95D, 0x95E, + 0x95F, 0x9DC, 0x9DD, 0x9DF, 0xA33, 0xA36, 0xA59, 0xA5A, + 0xA5B, 0xA5E, 0xB5C, 0xB5D, 0xF43, 0xF4D, 0xF52, 0xF57, + 0xF5C, 0xF69, 0xF73, 0xF75, 0xF76, 0xF78, 0xF81, 0xF93, + 0xF9D, 0xFA2, 0xFA7, 0xFAC, 0xFB9, 0x2ADC, 0xFB1D, 0xFB1F, + 0xFB2A, 0xFB2B, 0xFB2C, 0xFB2D, 0xFB2E, 0xFB2F, 0xFB30, 0xFB31, + 0xFB32, 0xFB33, 0xFB34, 0xFB35, 0xFB36, 0xFB38, 0xFB39, 0xFB3A, + 0xFB3B, 0xFB3C, 0xFB3E, 0xFB40, 0xFB41, 0xFB43, 0xFB44, 0xFB46, + 0xFB47, 0xFB48, 0xFB49, 0xFB4A, 0xFB4B, 0xFB4C, 0xFB4D, 0xFB4E, + 0x1D15E, 0x1D15F, 0x1D160, 0x1D161, 0x1D162, 0x1D163, 0x1D164, 0x1D1BB, + 0x1D1BC, 0x1D1BD, 0x1D1BE, 0x1D1BF, 0x1D1C0, +] +# --- END GENERATED DATA --- diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/urllib/parse.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/urllib/parse.py index 2f7a44baddd..7397687f5ec 100644 --- a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/urllib/parse.py +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/urllib/parse.py @@ -3,7 +3,7 @@ # exception, as the rest of the Codename One Python runtime. """Parse URLs into components, and quote and unquote their parts.""" -from collections import namedtuple +import _cn1url __all__ = ["urlparse", "urlunparse", "urljoin", "urldefrag", "urlsplit", "urlunsplit", "urlencode", "parse_qs", "parse_qsl", "quote", "quote_plus", "quote_from_bytes", "unquote", "unquote_plus", @@ -111,9 +111,173 @@ def _hostinfo(self): return hostname, port -_DefragResultBase = namedtuple("DefragResult", "url fragment", module="urllib.parse") -_SplitResultBase = namedtuple("SplitResult", "scheme netloc path query fragment", module="urllib.parse") -_ParseResultBase = namedtuple("ParseResult", "scheme netloc path params query fragment", module="urllib.parse") +# The result bases are written out as namedtuple writes them, so each is a +# class statement the compiler gives a layout. +class _DefragResultBase(tuple): + "DefragResult(url, fragment)" + + __slots__ = () + _fields = ('url', 'fragment',) + _field_defaults = {} + __match_args__ = _fields + + def __new__(_cls, url, fragment): + return tuple.__new__(_cls, (url, fragment,)) + + @classmethod + def _make(cls, iterable): + result = tuple.__new__(cls, iterable) + if len(result) != 2: + raise TypeError("Expected 2 arguments, got %d" % len(result)) + return result + + def _replace(self, /, **kwds): + result = self._make([kwds.pop(name) if name in kwds else v for name, v in zip(self._fields, self)]) + if kwds: + raise TypeError("Got unexpected field names: %r" % list(kwds)) + return result + + def __repr__(self): + return self.__class__.__name__ + "(url=%r, fragment=%r)" % tuple(self) + + def _asdict(self): + return dict(zip(self._fields, self)) + + def __getnewargs__(self): + return tuple(self) + + @property + def url(self): + "Alias for field number 0" + return self[0] + + @property + def fragment(self): + "Alias for field number 1" + return self[1] + + +class _SplitResultBase(tuple): + "SplitResult(scheme, netloc, path, query, fragment)" + + __slots__ = () + _fields = ('scheme', 'netloc', 'path', 'query', 'fragment',) + _field_defaults = {} + __match_args__ = _fields + + def __new__(_cls, scheme, netloc, path, query, fragment): + return tuple.__new__(_cls, (scheme, netloc, path, query, fragment,)) + + @classmethod + def _make(cls, iterable): + result = tuple.__new__(cls, iterable) + if len(result) != 5: + raise TypeError("Expected 5 arguments, got %d" % len(result)) + return result + + def _replace(self, /, **kwds): + result = self._make([kwds.pop(name) if name in kwds else v for name, v in zip(self._fields, self)]) + if kwds: + raise TypeError("Got unexpected field names: %r" % list(kwds)) + return result + + def __repr__(self): + return self.__class__.__name__ + "(scheme=%r, netloc=%r, path=%r, query=%r, fragment=%r)" % tuple(self) + + def _asdict(self): + return dict(zip(self._fields, self)) + + def __getnewargs__(self): + return tuple(self) + + @property + def scheme(self): + "Alias for field number 0" + return self[0] + + @property + def netloc(self): + "Alias for field number 1" + return self[1] + + @property + def path(self): + "Alias for field number 2" + return self[2] + + @property + def query(self): + "Alias for field number 3" + return self[3] + + @property + def fragment(self): + "Alias for field number 4" + return self[4] + + +class _ParseResultBase(tuple): + "ParseResult(scheme, netloc, path, params, query, fragment)" + + __slots__ = () + _fields = ('scheme', 'netloc', 'path', 'params', 'query', 'fragment',) + _field_defaults = {} + __match_args__ = _fields + + def __new__(_cls, scheme, netloc, path, params, query, fragment): + return tuple.__new__(_cls, (scheme, netloc, path, params, query, fragment,)) + + @classmethod + def _make(cls, iterable): + result = tuple.__new__(cls, iterable) + if len(result) != 6: + raise TypeError("Expected 6 arguments, got %d" % len(result)) + return result + + def _replace(self, /, **kwds): + result = self._make([kwds.pop(name) if name in kwds else v for name, v in zip(self._fields, self)]) + if kwds: + raise TypeError("Got unexpected field names: %r" % list(kwds)) + return result + + def __repr__(self): + return self.__class__.__name__ + "(scheme=%r, netloc=%r, path=%r, params=%r, query=%r, fragment=%r)" % tuple(self) + + def _asdict(self): + return dict(zip(self._fields, self)) + + def __getnewargs__(self): + return tuple(self) + + @property + def scheme(self): + "Alias for field number 0" + return self[0] + + @property + def netloc(self): + "Alias for field number 1" + return self[1] + + @property + def path(self): + "Alias for field number 2" + return self[2] + + @property + def params(self): + "Alias for field number 3" + return self[3] + + @property + def query(self): + "Alias for field number 4" + return self[4] + + @property + def fragment(self): + "Alias for field number 5" + return self[5] class DefragResult(_DefragResultBase): @@ -469,6 +633,10 @@ def unquote_plus(string, encoding="utf-8", errors="replace"): def quote(string, safe="/", encoding=None, errors=None): + if encoding is None and errors is None and type(string) is str: + r = _cn1url.quote(string, safe) + if r is not None: + return r if isinstance(string, str): if not string: return string @@ -501,6 +669,9 @@ def quote_from_bytes(bs, safe="/"): raise TypeError("quote_from_bytes() expected bytes") if not bs: return "" + r = _cn1url.quote(bs, safe) + if r is not None: + return r if isinstance(safe, str): safe = safe.encode("ascii", "ignore") else: diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/uuid.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/uuid.py index 782ae2de24a..936e66b8c8e 100644 --- a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/uuid.py +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/uuid.py @@ -37,7 +37,7 @@ class SafeUUID: class UUID: - __slots__ = ("int", "is_safe", "__weakref__") + __slots__ = ("_int", "_is_safe", "__weakref__") def __init__(self, hex=None, bytes=None, bytes_le=None, fields=None, int=None, version=None, *, is_safe=SafeUUID.unknown): @@ -83,57 +83,73 @@ def __init__(self, hex=None, bytes=None, bytes_le=None, fields=None, int=None, v int &= _RFC_4122_CLEARFLAGS_MASK int |= 0x8000 << 48 int |= version << 76 - object.__setattr__(self, "int", int) - object.__setattr__(self, "is_safe", is_safe) + self._int = int + self._is_safe = is_safe @classmethod def _from_int(cls, value): self = object.__new__(cls) - object.__setattr__(self, "int", value) - object.__setattr__(self, "is_safe", SafeUUID.unknown) + self._int = value + self._is_safe = SafeUUID.unknown return self def __getstate__(self): - d = {"int": self.int} - if self.is_safe != SafeUUID.unknown: - d["is_safe"] = self.is_safe + d = {"int": self._int} + if self._is_safe != SafeUUID.unknown: + d["is_safe"] = self._is_safe return d def __eq__(self, other): if isinstance(other, UUID): - return self.int == other.int + return self._int == other.int return NotImplemented def __lt__(self, other): if isinstance(other, UUID): - return self.int < other.int + return self._int < other.int return NotImplemented def __gt__(self, other): if isinstance(other, UUID): - return self.int > other.int + return self._int > other.int return NotImplemented def __le__(self, other): if isinstance(other, UUID): - return self.int <= other.int + return self._int <= other.int return NotImplemented def __ge__(self, other): if isinstance(other, UUID): - return self.int >= other.int + return self._int >= other.int return NotImplemented def __hash__(self): - return hash(self.int) + return hash(self._int) def __int__(self): - return self.int + return self._int def __repr__(self): return "%s(%r)" % (self.__class__.__name__, str(self)) - def __setattr__(self, name, value): + # Immutable: the two values are read-only properties over private slots, + # rather than a refusing __setattr__, which would leave UUID without a + # layout. Only __init__ and _from_int store the slots. + @property + def int(self): + return self._int + + @int.setter + def int(self, value): + raise TypeError("UUID objects are immutable") + + @property + def is_safe(self): + return self._is_safe + + @is_safe.setter + def is_safe(self, value): raise TypeError("UUID objects are immutable") def __str__(self): @@ -142,7 +158,7 @@ def __str__(self): @property def bytes(self): - return self.int.to_bytes(16, "big") + return self._int.to_bytes(16, "big") @property def bytes_le(self): @@ -156,35 +172,35 @@ def fields(self): @property def time_low(self): - return self.int >> 96 + return self._int >> 96 @property def time_mid(self): - return (self.int >> 80) & 0xffff + return (self._int >> 80) & 0xffff @property def time_hi_version(self): - return (self.int >> 64) & 0xffff + return (self._int >> 64) & 0xffff @property def clock_seq_hi_variant(self): - return (self.int >> 56) & 0xff + return (self._int >> 56) & 0xff @property def clock_seq_low(self): - return (self.int >> 48) & 0xff + return (self._int >> 48) & 0xff @property def time(self): if self.version == 6: - time_hi = self.int >> 96 - time_lo = (self.int >> 64) & 0x0fff + time_hi = self._int >> 96 + time_lo = (self._int >> 64) & 0x0fff return time_hi << 28 | (self.time_mid << 12) | time_lo elif self.version == 7: - return self.int >> 80 + return self._int >> 80 else: time_hi = self.time_hi_version & 0x0fff - time_lo = self.int >> 96 + time_lo = self._int >> 96 return time_hi << 48 | (self.time_mid << 32) | time_lo @property @@ -193,11 +209,11 @@ def clock_seq(self): @property def node(self): - return self.int & 0xffffffffffff + return self._int & 0xffffffffffff @property def hex(self): - return "%032x" % self.int + return "%032x" % self._int @property def urn(self): @@ -205,11 +221,11 @@ def urn(self): @property def variant(self): - if not self.int & (0x8000 << 48): + if not self._int & (0x8000 << 48): return RESERVED_NCS - elif not self.int & (0x4000 << 48): + elif not self._int & (0x4000 << 48): return RFC_4122 - elif not self.int & (0x2000 << 48): + elif not self._int & (0x2000 << 48): return RESERVED_MICROSOFT else: return RESERVED_FUTURE @@ -217,7 +233,7 @@ def variant(self): @property def version(self): if self.variant == RFC_4122: - return int((self.int >> 76) & 0xf) + return int((self._int >> 76) & 0xf) _int = int diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/warnings.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/warnings.py index a7b7d9cb01a..99000ff26b7 100644 --- a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/warnings.py +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/warnings.py @@ -196,7 +196,11 @@ class catch_warnings: def __init__(self, *, record=False, module=None, action=None, category=Warning, lineno=0, append=False): self._record = record self._entered = False - self._module = sys.modules["warnings"] if module is None else module + # Kept as given: this class saves and restores this module's own + # globals and never reads it. Naming sys.modules["warnings"] here + # made the module a value read by computed names, which left every + # class of it untyped. + self._module = module if action is None: self._filter = None else: diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/weakref.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/weakref.py index 61486897575..f752f539620 100644 --- a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/weakref.py +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/weakref.py @@ -138,6 +138,7 @@ def __hash__(self): class WeakValueDictionary: + __class_getitem__ = classmethod(type(list[int])) def __init__(self, other=(), /, **kw): self.data = {} self.update(other, **kw) @@ -263,6 +264,7 @@ def __ior__(self, other): class WeakKeyDictionary: + __class_getitem__ = classmethod(type(list[int])) def __init__(self, dict=None): self.data = {} if dict is not None: @@ -354,6 +356,7 @@ def update(self, dict=None, /, **kwargs): class WeakSet: + __class_getitem__ = classmethod(type(list[int])) def __init__(self, data=None): self.data = set() if data is not None: diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/xml/__init__.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/xml/__init__.py new file mode 100644 index 00000000000..296561f1f21 --- /dev/null +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/xml/__init__.py @@ -0,0 +1,5 @@ +# Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. +# Licensed under the GNU General Public License version 2 with the Classpath +# exception, as the rest of the Codename One Python runtime. +"""xml: the XML packages -- etree, dom, sax and parsers.expat, all over one +pure-Python parser (xml.parsers.expat) that follows expat's behaviour.""" diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/xml/dom/NodeFilter.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/xml/dom/NodeFilter.py new file mode 100644 index 00000000000..0457972cbb8 --- /dev/null +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/xml/dom/NodeFilter.py @@ -0,0 +1,31 @@ +# Copyright (c) 2001 Python Software Foundation; All Rights Reserved +# Licensed under the Python Software Foundation License Version 2; the full +# text is in maven/python-transpiler/third-party/cpython/LICENSE.txt. +# +# Derived from CPython's Lib/xml/dom/NodeFilter.py. Changes: rewritten for the Codename One +# Python runtime, trimmed to what the transpiler supports and reorganised; +# the C accelerators and platform-specific branches are left out. +"""xml.dom.NodeFilter: the DOM Level 2 NodeFilter constants.""" + + +class NodeFilter: + FILTER_ACCEPT = 1 + FILTER_REJECT = 2 + FILTER_SKIP = 3 + + SHOW_ALL = 0xFFFFFFFF + SHOW_ELEMENT = 0x00000001 + SHOW_ATTRIBUTE = 0x00000002 + SHOW_TEXT = 0x00000004 + SHOW_CDATA_SECTION = 0x00000008 + SHOW_ENTITY_REFERENCE = 0x00000010 + SHOW_ENTITY = 0x00000020 + SHOW_PROCESSING_INSTRUCTION = 0x00000040 + SHOW_COMMENT = 0x00000080 + SHOW_DOCUMENT = 0x00000100 + SHOW_DOCUMENT_TYPE = 0x00000200 + SHOW_DOCUMENT_FRAGMENT = 0x00000400 + SHOW_NOTATION = 0x00000800 + + def acceptNode(self, node): + raise NotImplementedError diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/xml/dom/__init__.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/xml/dom/__init__.py new file mode 100644 index 00000000000..309567d28b4 --- /dev/null +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/xml/dom/__init__.py @@ -0,0 +1,133 @@ +# Copyright (c) 2001 Python Software Foundation; All Rights Reserved +# Licensed under the Python Software Foundation License Version 2; the full +# text is in maven/python-transpiler/third-party/cpython/LICENSE.txt. +# +# Derived from CPython's Lib/xml/dom/__init__.py. Changes: rewritten for the Codename One +# Python runtime, trimmed to what the transpiler supports and reorganised; +# the C accelerators and platform-specific branches are left out. +"""xml.dom: the DOM node type constants, the DOM exceptions and the +implementation registry.""" + + +class Node: + __slots__ = () + ELEMENT_NODE = 1 + ATTRIBUTE_NODE = 2 + TEXT_NODE = 3 + CDATA_SECTION_NODE = 4 + ENTITY_REFERENCE_NODE = 5 + ENTITY_NODE = 6 + PROCESSING_INSTRUCTION_NODE = 7 + COMMENT_NODE = 8 + DOCUMENT_NODE = 9 + DOCUMENT_TYPE_NODE = 10 + DOCUMENT_FRAGMENT_NODE = 11 + NOTATION_NODE = 12 + + +INDEX_SIZE_ERR = 1 +DOMSTRING_SIZE_ERR = 2 +HIERARCHY_REQUEST_ERR = 3 +WRONG_DOCUMENT_ERR = 4 +INVALID_CHARACTER_ERR = 5 +NO_DATA_ALLOWED_ERR = 6 +NO_MODIFICATION_ALLOWED_ERR = 7 +NOT_FOUND_ERR = 8 +NOT_SUPPORTED_ERR = 9 +INUSE_ATTRIBUTE_ERR = 10 +INVALID_STATE_ERR = 11 +SYNTAX_ERR = 12 +INVALID_MODIFICATION_ERR = 13 +NAMESPACE_ERR = 14 +INVALID_ACCESS_ERR = 15 +VALIDATION_ERR = 16 + + +class DOMException(Exception): + def __init__(self, *args, **kw): + if self.__class__ is DOMException: + raise RuntimeError("DOMException should not be instantiated directly") + Exception.__init__(self, *args, **kw) + + def _get_code(self): + return self.code + + +class IndexSizeErr(DOMException): + code = INDEX_SIZE_ERR + + +class DomstringSizeErr(DOMException): + code = DOMSTRING_SIZE_ERR + + +class HierarchyRequestErr(DOMException): + code = HIERARCHY_REQUEST_ERR + + +class WrongDocumentErr(DOMException): + code = WRONG_DOCUMENT_ERR + + +class InvalidCharacterErr(DOMException): + code = INVALID_CHARACTER_ERR + + +class NoDataAllowedErr(DOMException): + code = NO_DATA_ALLOWED_ERR + + +class NoModificationAllowedErr(DOMException): + code = NO_MODIFICATION_ALLOWED_ERR + + +class NotFoundErr(DOMException): + code = NOT_FOUND_ERR + + +class NotSupportedErr(DOMException): + code = NOT_SUPPORTED_ERR + + +class InuseAttributeErr(DOMException): + code = INUSE_ATTRIBUTE_ERR + + +class InvalidStateErr(DOMException): + code = INVALID_STATE_ERR + + +class SyntaxErr(DOMException): + code = SYNTAX_ERR + + +class InvalidModificationErr(DOMException): + code = INVALID_MODIFICATION_ERR + + +class NamespaceErr(DOMException): + code = NAMESPACE_ERR + + +class InvalidAccessErr(DOMException): + code = INVALID_ACCESS_ERR + + +class ValidationErr(DOMException): + code = VALIDATION_ERR + + +class UserDataHandler: + NODE_CLONED = 1 + NODE_IMPORTED = 2 + NODE_DELETED = 3 + NODE_RENAMED = 4 + + +XML_NAMESPACE = "http://www.w3.org/XML/1998/namespace" +XMLNS_NAMESPACE = "http://www.w3.org/2000/xmlns/" +XHTML_NAMESPACE = "http://www.w3.org/1999/xhtml" +EMPTY_NAMESPACE = None +EMPTY_PREFIX = None + +from .domreg import getDOMImplementation, registerDOMImplementation diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/xml/dom/domreg.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/xml/dom/domreg.py new file mode 100644 index 00000000000..f4129a8c826 --- /dev/null +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/xml/dom/domreg.py @@ -0,0 +1,68 @@ +# Copyright (c) 2001 Python Software Foundation; All Rights Reserved +# Licensed under the Python Software Foundation License Version 2; the full +# text is in maven/python-transpiler/third-party/cpython/LICENSE.txt. +# +# Derived from CPython's Lib/xml/dom/domreg.py. Changes: rewritten for the Codename One +# Python runtime, trimmed to what the transpiler supports and reorganised; +# the C accelerators and platform-specific branches are left out. +"""xml.dom.domreg: the DOM implementation registry. minidom is the only +implementation; one registered by name is called, never imported.""" + +well_known_implementations = {"minidom": "xml.dom.minidom"} + +registered = {} + + +def registerDOMImplementation(name, factory): + registered[name] = factory + + +def _good_enough(dom, features): + for f, v in features: + if not dom.hasFeature(f, v): + return 0 + return 1 + + +def _minidom(): + from xml.dom import minidom + return minidom.getDOMImplementation() + + +def getDOMImplementation(name=None, features=()): + if name: + if name in registered: + return registered[name]() + if name == "minidom": + return _minidom() + raise ImportError("no registered DOM implementation named " + name) + if isinstance(features, str): + features = _parse_feature_string(features) + for creator in registered.values(): + dom = creator() + if _good_enough(dom, features): + return dom + dom = _minidom() + if _good_enough(dom, features): + return dom + raise ImportError("no suitable DOM implementation found") + + +def _parse_feature_string(s): + features = [] + parts = s.split() + i = 0 + length = len(parts) + while i < length: + feature = parts[i] + if feature[0] in "0123456789": + raise ValueError("bad feature name: %r" % (feature,)) + i = i + 1 + version = None + if i < length: + v = parts[i] + if v[0] in "0123456789": + i = i + 1 + version = v + features.append((feature, version)) + return tuple(features) diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/xml/dom/expatbuilder.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/xml/dom/expatbuilder.py new file mode 100644 index 00000000000..97ae88889a2 --- /dev/null +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/xml/dom/expatbuilder.py @@ -0,0 +1,789 @@ +# Copyright (c) 2001 Python Software Foundation; All Rights Reserved +# Licensed under the Python Software Foundation License Version 2; the full +# text is in maven/python-transpiler/third-party/cpython/LICENSE.txt. +# +# Derived from CPython's Lib/xml/dom/expatbuilder.py. Changes: rewritten for the Codename One +# Python runtime, trimmed to what the transpiler supports and reorganised; +# the C accelerators and platform-specific branches are left out. +"""xml.dom.expatbuilder: builds a minidom Document from expat events. + +ExpatBuilder and the Namespaces mixin keep the method names subclasses +override (defusedxml's builders replace install() and reset()).""" + +from xml.dom import xmlbuilder, minidom, Node +from xml.dom import EMPTY_NAMESPACE, EMPTY_PREFIX, XMLNS_NAMESPACE +from xml.parsers import expat +from xml.dom.minidom import _append_child, _set_attribute_node +from xml.dom.NodeFilter import NodeFilter + +TEXT_NODE = Node.TEXT_NODE +CDATA_SECTION_NODE = Node.CDATA_SECTION_NODE +DOCUMENT_NODE = Node.DOCUMENT_NODE + +FILTER_ACCEPT = 1 +FILTER_REJECT = 2 +FILTER_SKIP = 3 +FILTER_INTERRUPT = 4 + +theDOMImplementation = minidom.getDOMImplementation() + + +class ElementInfo: + __slots__ = ("_attr_info", "_model", "tagName") + + def __init__(self, tagName, model=None): + self.tagName = tagName + self._attr_info = [] + self._model = model + + def getAttributeType(self, aname): + return minidom._no_type + + def getAttributeTypeNS(self, namespaceURI, localName): + return minidom._no_type + + def isElementContent(self): + if self._model: + type = self._model[0] + return type not in (expat.model.XML_CTYPE_ANY, expat.model.XML_CTYPE_MIXED) + return False + + def isEmpty(self): + if self._model: + return self._model[0] == expat.model.XML_CTYPE_EMPTY + return False + + def isId(self, aname): + for info in self._attr_info: + if info[1] == aname: + return info[-2] == "ID" + return False + + def isIdNS(self, euri, ename, auri, aname): + return self.isId((auri, aname)) + + +def _intern(builder, s): + return builder._intern_setdefault(s, s) + + +def _parse_ns_name(builder, name): + parts = name.split(" ") + intern = builder._intern_setdefault + if len(parts) == 3: + uri, localname, prefix = parts + prefix = intern(prefix, prefix) + qname = "%s:%s" % (prefix, localname) + qname = intern(qname, qname) + localname = intern(localname, localname) + elif len(parts) == 2: + uri, localname = parts + prefix = EMPTY_PREFIX + qname = localname = intern(localname, localname) + else: + raise ValueError("Unsupported syntax: spaces in URIs not supported: %r" % name) + return intern(uri, uri), localname, prefix, qname + + +class ExpatBuilder: + """Document builder that uses Expat to build a ParsedXML.DOM document + instance.""" + + def __init__(self, options=None): + if options is None: + options = xmlbuilder.Options() + self._options = options + if self._options.filter is not None: + self._filter = FilterVisibilityController(self._options.filter) + else: + self._filter = None + self._finish_start_element = id + self._parser = None + self.reset() + + def createParser(self): + return expat.ParserCreate() + + def getParser(self): + if not self._parser: + self._parser = self.createParser() + self._intern_setdefault = self._parser.intern.setdefault + self._parser.buffer_text = True + self._parser.ordered_attributes = True + self._parser.specified_attributes = True + self.install(self._parser) + return self._parser + + def reset(self): + self.document = theDOMImplementation.createDocument(EMPTY_NAMESPACE, None, None) + self.curNode = self.document + self._elem_info = self.document._elem_info + self._cdata = False + + def install(self, parser): + parser.StartDoctypeDeclHandler = self.start_doctype_decl_handler + parser.StartElementHandler = self.first_element_handler + parser.EndElementHandler = self.end_element_handler + parser.ProcessingInstructionHandler = self.pi_handler + if self._options.entities: + parser.EntityDeclHandler = self.entity_decl_handler + parser.NotationDeclHandler = self.notation_decl_handler + if self._options.comments: + parser.CommentHandler = self.comment_handler + if self._options.cdata_sections: + parser.StartCdataSectionHandler = self.start_cdata_section_handler + parser.EndCdataSectionHandler = self.end_cdata_section_handler + parser.CharacterDataHandler = self.character_data_handler_cdata + else: + parser.CharacterDataHandler = self.character_data_handler + parser.ExternalEntityRefHandler = self.external_entity_ref_handler + parser.XmlDeclHandler = self.xml_decl_handler + parser.ElementDeclHandler = self.element_decl_handler + parser.AttlistDeclHandler = self.attlist_decl_handler + + def parseFile(self, file): + parser = self.getParser() + first_buffer = True + try: + while buffer := file.read(16 * 1024): + parser.Parse(buffer, False) + if first_buffer and self.document.documentElement: + self._setup_subset(buffer) + first_buffer = False + parser.Parse(b"", True) + except ParseEscape: + pass + doc = self.document + self.reset() + self._parser = None + return doc + + def parseString(self, string): + parser = self.getParser() + try: + parser.Parse(string, True) + self._setup_subset(string) + except ParseEscape: + pass + doc = self.document + self.reset() + self._parser = None + return doc + + def _setup_subset(self, buffer): + if self.document.doctype: + extractor = InternalSubsetExtractor() + extractor.parseString(buffer) + subset = extractor.getSubset() + self.document.doctype.internalSubset = subset + + def start_doctype_decl_handler(self, doctypeName, systemId, publicId, has_internal_subset): + doctype = self.document.implementation.createDocumentType(doctypeName, publicId, systemId) + doctype.ownerDocument = self.document + _append_child(self.document, doctype) + self.document.doctype = doctype + if self._filter and self._filter.acceptNode(doctype) == FILTER_REJECT: + self.document.doctype = None + del self.document.childNodes[-1] + doctype = None + self._parser.EntityDeclHandler = None + self._parser.NotationDeclHandler = None + if has_internal_subset: + if doctype is not None: + doctype.entities._seq = [] + doctype.notations._seq = [] + self._parser.CommentHandler = None + self._parser.ProcessingInstructionHandler = None + self._parser.EndDoctypeDeclHandler = self.end_doctype_decl_handler + + def end_doctype_decl_handler(self): + if self._options.comments: + self._parser.CommentHandler = self.comment_handler + self._parser.ProcessingInstructionHandler = self.pi_handler + if not (self._elem_info or self._filter): + self._finish_end_element = id + + def pi_handler(self, target, data): + node = self.document.createProcessingInstruction(target, data) + _append_child(self.curNode, node) + if self._filter and self._filter.acceptNode(node) == FILTER_REJECT: + self.curNode.removeChild(node) + + def character_data_handler_cdata(self, data): + childNodes = self.curNode.childNodes + if self._cdata: + if (self._cdata_continue and childNodes[-1].nodeType == CDATA_SECTION_NODE): + childNodes[-1].appendData(data) + return + node = self.document.createCDATASection(data) + self._cdata_continue = True + elif childNodes and childNodes[-1].nodeType == TEXT_NODE: + node = childNodes[-1] + node.data = node.data + data + return + else: + node = minidom.Text() + node.data = data + node.ownerDocument = self.document + _append_child(self.curNode, node) + + def character_data_handler(self, data): + childNodes = self.curNode.childNodes + if childNodes and childNodes[-1].nodeType == TEXT_NODE: + node = childNodes[-1] + node.data = node.data + data + return + node = minidom.Text() + node.data = node.data + data + node.ownerDocument = self.document + _append_child(self.curNode, node) + + def entity_decl_handler(self, entityName, is_parameter_entity, value, base, systemId, publicId, notationName): + if is_parameter_entity: + return + if not self._options.entities: + return + node = self.document._create_entity(entityName, publicId, systemId, notationName) + if value is not None: + child = self.document.createTextNode(value) + node.childNodes.append(child) + self.document.doctype.entities._seq.append(node) + if self._filter and self._filter.acceptNode(node) == FILTER_REJECT: + del self.document.doctype.entities._seq[-1] + + def notation_decl_handler(self, notationName, base, systemId, publicId): + node = self.document._create_notation(notationName, publicId, systemId) + self.document.doctype.notations._seq.append(node) + if self._filter and self._filter.acceptNode(node) == FILTER_ACCEPT: + del self.document.doctype.notations._seq[-1] + + def comment_handler(self, data): + node = self.document.createComment(data) + _append_child(self.curNode, node) + if self._filter and self._filter.acceptNode(node) == FILTER_REJECT: + self.curNode.removeChild(node) + + def start_cdata_section_handler(self): + self._cdata = True + self._cdata_continue = False + + def end_cdata_section_handler(self): + self._cdata = False + self._cdata_continue = False + + def external_entity_ref_handler(self, context, base, systemId, publicId): + return 1 + + def first_element_handler(self, name, attributes): + if self._filter is None and not self._elem_info: + self._finish_end_element = id + self.getParser().StartElementHandler = self.start_element_handler + self.start_element_handler(name, attributes) + + def start_element_handler(self, name, attributes): + node = self.document.createElement(name) + _append_child(self.curNode, node) + self.curNode = node + if attributes: + for i in range(0, len(attributes), 2): + a = minidom.Attr(attributes[i], EMPTY_NAMESPACE, None, EMPTY_PREFIX) + value = attributes[i + 1] + a.value = value + a.ownerDocument = self.document + _set_attribute_node(node, a) + if node is not self.document.documentElement: + self._finish_start_element(node) + + def _finish_start_element(self, node): + if self._filter: + if node is self.document.documentElement: + return + filt = self._filter.startContainer(node) + if filt == FILTER_REJECT: + Rejecter(self) + elif filt == FILTER_SKIP: + Skipper(self) + else: + return + self.curNode = node.parentNode + node.parentNode.removeChild(node) + node.unlink() + + def end_element_handler(self, name): + curNode = self.curNode + self.curNode = curNode.parentNode + self._finish_end_element(curNode) + + def _finish_end_element(self, curNode): + info = self._elem_info.get(curNode.tagName) + if info: + self._handle_white_text_nodes(curNode, info) + if self._filter: + if curNode is self.document.documentElement: + return + if self._filter.acceptNode(curNode) == FILTER_REJECT: + self.curNode.removeChild(curNode) + curNode.unlink() + + def _handle_white_text_nodes(self, node, info): + if (self._options.whitespace_in_element_content or not info.isElementContent()): + return + L = [] + for child in node.childNodes: + if child.nodeType == TEXT_NODE and not child.data.strip(): + L.append(child) + for child in L: + node.removeChild(child) + + def element_decl_handler(self, name, model): + info = self._elem_info.get(name) + if info is None: + self._elem_info[name] = ElementInfo(name, model) + else: + assert info._model is None + info._model = model + + def attlist_decl_handler(self, elem, name, type, default, required): + info = self._elem_info.get(elem) + if info is None: + info = ElementInfo(elem) + self._elem_info[elem] = info + info._attr_info.append([None, name, None, None, default, 0, type, required]) + + def xml_decl_handler(self, version, encoding, standalone): + self.document.version = version + self.document.encoding = encoding + if standalone >= 0: + if standalone: + self.document.standalone = True + else: + self.document.standalone = False + + +_ALLOWED_FILTER_RETURNS = (FILTER_ACCEPT, FILTER_REJECT, FILTER_SKIP) + + +class FilterVisibilityController: + __slots__ = ("filter",) + + def __init__(self, filter): + self.filter = filter + + def startContainer(self, node): + mask = self._nodetype_mask[node.nodeType] + if self.filter.whatToShow & mask: + val = self.filter.startContainer(node) + if val == FILTER_INTERRUPT: + raise ParseEscape + if val not in _ALLOWED_FILTER_RETURNS: + raise ValueError("startContainer() returned illegal value: " + repr(val)) + return val + return FILTER_ACCEPT + + def acceptNode(self, node): + mask = self._nodetype_mask[node.nodeType] + if self.filter.whatToShow & mask: + val = self.filter.acceptNode(node) + if val == FILTER_INTERRUPT: + raise ParseEscape + if val == FILTER_SKIP: + parent = node.parentNode + for child in node.childNodes[:]: + parent.appendChild(child) + return FILTER_REJECT + if val not in _ALLOWED_FILTER_RETURNS: + raise ValueError("acceptNode() returned illegal value: " + repr(val)) + return val + return FILTER_ACCEPT + + _nodetype_mask = { + Node.ELEMENT_NODE: NodeFilter.SHOW_ELEMENT, + Node.ATTRIBUTE_NODE: NodeFilter.SHOW_ATTRIBUTE, + Node.TEXT_NODE: NodeFilter.SHOW_TEXT, + Node.CDATA_SECTION_NODE: NodeFilter.SHOW_CDATA_SECTION, + Node.ENTITY_REFERENCE_NODE: NodeFilter.SHOW_ENTITY_REFERENCE, + Node.ENTITY_NODE: NodeFilter.SHOW_ENTITY, + Node.PROCESSING_INSTRUCTION_NODE: NodeFilter.SHOW_PROCESSING_INSTRUCTION, + Node.COMMENT_NODE: NodeFilter.SHOW_COMMENT, + Node.DOCUMENT_NODE: NodeFilter.SHOW_DOCUMENT, + Node.DOCUMENT_TYPE_NODE: NodeFilter.SHOW_DOCUMENT_TYPE, + Node.DOCUMENT_FRAGMENT_NODE: NodeFilter.SHOW_DOCUMENT_FRAGMENT, + Node.NOTATION_NODE: NodeFilter.SHOW_NOTATION, + } + + +class FilterCrutch: + __slots__ = ("_builder", "_level", "_old_start", "_old_end") + + def __init__(self, builder): + self._level = 0 + self._builder = builder + parser = builder._parser + self._old_start = parser.StartElementHandler + self._old_end = parser.EndElementHandler + parser.StartElementHandler = self.start_element_handler + parser.EndElementHandler = self.end_element_handler + + +class Rejecter(FilterCrutch): + __slots__ = () + + def __init__(self, builder): + FilterCrutch.__init__(self, builder) + parser = builder._parser + # Each handler by name: a computed setattr is reflection. + parser.ProcessingInstructionHandler = None + parser.CommentHandler = None + parser.CharacterDataHandler = None + parser.StartCdataSectionHandler = None + parser.EndCdataSectionHandler = None + parser.ExternalEntityRefHandler = None + + def start_element_handler(self, *args): + self._level = self._level + 1 + + def end_element_handler(self, *args): + if self._level == 0: + parser = self._builder._parser + self._builder.install(parser) + parser.StartElementHandler = self._old_start + parser.EndElementHandler = self._old_end + else: + self._level = self._level - 1 + + +class Skipper(FilterCrutch): + __slots__ = () + + def start_element_handler(self, *args): + node = self._builder.curNode + self._old_start(*args) + if self._builder.curNode is not node: + self._level = self._level + 1 + + def end_element_handler(self, *args): + if self._level == 0: + self._builder._parser.StartElementHandler = self._old_start + self._builder._parser.EndElementHandler = self._old_end + self._builder = None + else: + self._level = self._level - 1 + self._old_end(*args) + + +class Namespaces: + """Mix-in class for builders; adds support for namespaces.""" + + def _initNamespaces(self): + self._ns_ordered_prefixes = [] + + def createParser(self): + parser = expat.ParserCreate(namespace_separator=" ") + parser.namespace_prefixes = True + return parser + + def install(self, parser): + ExpatBuilder.install(self, parser) + if self._options.namespace_declarations: + parser.StartNamespaceDeclHandler = self.start_namespace_decl_handler + + def start_namespace_decl_handler(self, prefix, uri): + self._ns_ordered_prefixes.append((prefix, uri)) + + def start_element_handler(self, name, attributes): + if " " in name: + uri, localname, prefix, qname = _parse_ns_name(self, name) + else: + uri = EMPTY_NAMESPACE + qname = name + localname = None + prefix = EMPTY_PREFIX + node = minidom.Element(qname, uri, prefix, localname) + node.ownerDocument = self.document + _append_child(self.curNode, node) + self.curNode = node + if self._ns_ordered_prefixes: + for prefix, uri in self._ns_ordered_prefixes: + if prefix: + a = minidom.Attr(_intern(self, "xmlns:" + prefix), XMLNS_NAMESPACE, prefix, "xmlns") + else: + a = minidom.Attr("xmlns", XMLNS_NAMESPACE, "xmlns", EMPTY_PREFIX) + a.value = uri + a.ownerDocument = self.document + _set_attribute_node(node, a) + del self._ns_ordered_prefixes[:] + if attributes: + node._ensure_attributes() + _attrs = node._attrs + _attrsNS = node._attrsNS + for i in range(0, len(attributes), 2): + aname = attributes[i] + value = attributes[i + 1] + if " " in aname: + uri, localname, prefix, qname = _parse_ns_name(self, aname) + a = minidom.Attr(qname, uri, localname, prefix) + _attrs[qname] = a + _attrsNS[(uri, localname)] = a + else: + a = minidom.Attr(aname, EMPTY_NAMESPACE, aname, EMPTY_PREFIX) + _attrs[aname] = a + _attrsNS[(EMPTY_NAMESPACE, aname)] = a + a.ownerDocument = self.document + a.value = value + a.ownerElement = node + + def end_element_handler(self, name): + curNode = self.curNode + self.curNode = curNode.parentNode + self._finish_end_element(curNode) + + +class ExpatBuilderNS(Namespaces, ExpatBuilder): + """Document builder that supports namespaces.""" + + def reset(self): + ExpatBuilder.reset(self) + self._initNamespaces() + + +class FragmentBuilder(ExpatBuilder): + """Builds a document fragment in the context of an existing node.""" + + def __init__(self, context, options=None): + if context.nodeType == DOCUMENT_NODE: + self.originalDocument = context + self.context = context + else: + self.originalDocument = context.ownerDocument + self.context = context + ExpatBuilder.__init__(self, options) + + def reset(self): + ExpatBuilder.reset(self) + self.fragment = None + + def parseFile(self, file): + return self.parseString(file.read()) + + def parseString(self, string): + self._source = string + parser = self.getParser() + doctype = self.originalDocument.doctype + ident = "" + if doctype: + subset = doctype.internalSubset or self._getDeclarations() + if doctype.publicId: + ident = 'PUBLIC "%s" "%s"' % (doctype.publicId, doctype.systemId) + elif doctype.systemId: + ident = 'SYSTEM "%s"' % doctype.systemId + else: + subset = "" + nsattrs = self._getNSattrs() + document = _FRAGMENT_BUILDER_TEMPLATE % (ident, subset, nsattrs) + try: + parser.Parse(document, True) + except: + self.reset() + raise + fragment = self.fragment + self.reset() + return fragment + + def _getDeclarations(self): + doctype = self.context.ownerDocument.doctype + s = "" + if doctype: + for i in range(doctype.notations.length): + notation = doctype.notations.item(i) + if s: + s = s + "\n " + s = "%s' % (s, notation.publicId, notation.systemId) + else: + s = '%s SYSTEM "%s">' % (s, notation.systemId) + for i in range(doctype.entities.length): + entity = doctype.entities.item(i) + if s: + s = s + "\n " + s = "%s" + return s + + def _getNSattrs(self): + return "" + + def external_entity_ref_handler(self, context, base, systemId, publicId): + if systemId == _FRAGMENT_BUILDER_INTERNAL_SYSTEM_ID: + old_document = self.document + old_cur_node = self.curNode + parser = self._parser.ExternalEntityParserCreate(context) + self.document = self.originalDocument + self.fragment = self.document.createDocumentFragment() + self.curNode = self.fragment + try: + parser.Parse(self._source, True) + finally: + self.curNode = old_cur_node + self.document = old_document + self._source = None + return -1 + return ExpatBuilder.external_entity_ref_handler(self, context, base, systemId, publicId) + + +_FRAGMENT_BUILDER_INTERNAL_SYSTEM_ID = "http://xml.python.org/entities/fragment-builder/internal" + +_FRAGMENT_BUILDER_TEMPLATE = ('\n%%s\n]>\n' + '&fragment-builder-internal;' + % _FRAGMENT_BUILDER_INTERNAL_SYSTEM_ID) + + +class FragmentBuilderNS(Namespaces, FragmentBuilder): + def reset(self): + FragmentBuilder.reset(self) + self._initNamespaces() + + def _getNSattrs(self): + attrs = "" + context = self.context + L = [] + while context: + if hasattr(context, "_ns_prefix_uri"): + for prefix, uri in context._ns_prefix_uri.items(): + if prefix in L: + continue + L.append(prefix) + if prefix: + declname = "xmlns:" + prefix + else: + declname = "xmlns" + if attrs: + attrs = "%s\n %s='%s'" % (attrs, declname, uri) + else: + attrs = " %s='%s'" % (declname, uri) + context = context.parentNode + return attrs + + +class ParseEscape(Exception): + """Exception raised to short-circuit parsing in InternalSubsetExtractor.""" + pass + + +class InternalSubsetExtractor(ExpatBuilder): + """Rips out the internal document type subset. This expat never calls a + DefaultHandler, so the subset is cut from the source text: everything + between the DOCTYPE's '[' and its matching ']', skipping quoted + literals, comments and processing instructions.""" + + subset = None + + def getSubset(self): + return self.subset + + def parseFile(self, file): + self.parseString(file.read()) + + def parseString(self, string): + if isinstance(string, (bytes, bytearray)): + enc = "utf-8" + head = bytes(string[:200]) + if head.startswith(b"\xff\xfe") or head.startswith(b"\xfe\xff"): + enc = "utf-16" + string = bytes(string).decode(enc, "replace") + i = string.find("": + return + elif c == "[": + break + i += 1 + if i >= n: + return + start = i + 1 + i = start + while i < n: + if string.startswith("", i + 4) + i = n if j < 0 else j + 3 + continue + if string.startswith("", i + 2) + i = n if j < 0 else j + 2 + continue + c = string[i] + if c in "\"'": + j = string.find(c, i + 1) + i = n if j < 0 else j + 1 + continue + if c == "]": + self.subset = string[start:i].replace("\r\n", "\n").replace("\r", "\n") + return + i += 1 + + +def parse(file, namespaces=True): + if namespaces: + builder = ExpatBuilderNS() + else: + builder = ExpatBuilder() + if isinstance(file, str): + with open(file, "rb") as fp: + result = builder.parseFile(fp) + else: + result = builder.parseFile(file) + return result + + +def parseString(string, namespaces=True): + if namespaces: + builder = ExpatBuilderNS() + else: + builder = ExpatBuilder() + return builder.parseString(string) + + +def parseFragment(file, context, namespaces=True): + if namespaces: + builder = FragmentBuilderNS(context) + else: + builder = FragmentBuilder(context) + if isinstance(file, str): + with open(file, "rb") as fp: + result = builder.parseFile(fp) + else: + result = builder.parseFile(file) + return result + + +def parseFragmentString(string, context, namespaces=True): + if namespaces: + builder = FragmentBuilderNS(context) + else: + builder = FragmentBuilder(context) + return builder.parseString(string) + + +def makeBuilder(options): + if options.namespaces: + return ExpatBuilderNS(options) + return ExpatBuilder(options) diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/xml/dom/minicompat.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/xml/dom/minicompat.py new file mode 100644 index 00000000000..490a8e797ef --- /dev/null +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/xml/dom/minicompat.py @@ -0,0 +1,61 @@ +# Copyright (c) 2001 Python Software Foundation; All Rights Reserved +# Licensed under the Python Software Foundation License Version 2; the full +# text is in maven/python-transpiler/third-party/cpython/LICENSE.txt. +# +# Derived from CPython's Lib/xml/dom/minicompat.py. Changes: rewritten for the Codename One +# Python runtime, trimmed to what the transpiler supports and reorganised; +# the C accelerators and platform-specific branches are left out. +"""xml.dom.minicompat: NodeList and EmptyNodeList. CPython's defproperty is +left out: it binds a property under a computed name, which is reflection, +and minidom declares its read-only properties directly.""" + +__all__ = ["NodeList", "EmptyNodeList", "StringTypes"] + +StringTypes = (str,) + + +class NodeList(list): + __slots__ = () + + def item(self, index): + if 0 <= index < len(self): + return self[index] + return None + + def _get_length(self): + return len(self) + + def _set_length(self, value): + raise AttributeError("attempt to modify read-only attribute 'length'") + + length = property(_get_length, _set_length, doc="The number of nodes in the NodeList.") + + def __setstate__(self, state): + if state is None: + state = [] + self[:] = state + + +class EmptyNodeList(tuple): + __slots__ = () + + def __add__(self, other): + NL = NodeList() + NL.extend(other) + return NL + + def __radd__(self, other): + NL = NodeList() + NL.extend(other) + return NL + + def item(self, index): + return None + + def _get_length(self): + return 0 + + def _set_length(self, value): + raise AttributeError("attempt to modify read-only attribute 'length'") + + length = property(_get_length, _set_length, doc="The number of nodes in the NodeList.") diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/xml/dom/minidom.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/xml/dom/minidom.py new file mode 100644 index 00000000000..cdcbdfb4ba9 --- /dev/null +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/xml/dom/minidom.py @@ -0,0 +1,1757 @@ +# Copyright (c) 2001 Python Software Foundation; All Rights Reserved +# Licensed under the Python Software Foundation License Version 2; the full +# text is in maven/python-transpiler/third-party/cpython/LICENSE.txt. +# +# Derived from CPython's Lib/xml/dom/minidom.py. Changes: rewritten for the Codename One +# Python runtime, trimmed to what the transpiler supports and reorganised; +# the C accelerators and platform-specific branches are left out. +"""xml.dom.minidom: a lightweight DOM over the expat parser.""" + +import io +import xml.dom +from xml.dom import (EMPTY_NAMESPACE, EMPTY_PREFIX, XMLNS_NAMESPACE, XML_NAMESPACE, Node) +from xml.dom.minicompat import NodeList, EmptyNodeList, StringTypes +from xml.dom.xmlbuilder import DOMImplementationLS, DocumentLS + +_nodeTypes_with_children = (Node.ELEMENT_NODE, Node.ENTITY_REFERENCE_NODE) + + +def _write_data(writer, text, attr): + if text: + text = text.replace("&", "&").replace("<", "<").replace(">", ">") + if attr: + text = text.replace('"', """).replace("\r", " ").replace("\n", " ").replace("\t", " ") + writer.write(text) + + +class _TextWriter: + def __init__(self): + self._parts = [] + + def write(self, s): + self._parts.append(s) + + def getvalue(self): + return "".join(self._parts) + + +# The DOM base by an imported name, which the layout resolves across +# modules (a dotted xml.dom.Node it does not). +from xml.dom import Node as _DomNode + + +class Node(_DomNode): + namespaceURI = None + parentNode = None + ownerDocument = None + nextSibling = None + previousSibling = None + prefix = EMPTY_PREFIX + + def __bool__(self): + return True + + def toxml(self, encoding=None, standalone=None): + return self.toprettyxml("", "", encoding, standalone) + + def toprettyxml(self, indent="\t", newl="\n", encoding=None, standalone=None): + writer = _TextWriter() + if self.nodeType == Node.DOCUMENT_NODE: + self.writexml(writer, "", indent, newl, encoding, standalone) + else: + self.writexml(writer, "", indent, newl) + if encoding is None: + return writer.getvalue() + return writer.getvalue().encode(encoding, "xmlcharrefreplace") + + def hasChildNodes(self): + return bool(self.childNodes) + + def _get_childNodes(self): + return self.childNodes + + @property + def firstChild(self): + cn = self.childNodes + if cn: + return cn[0] + return None + + @property + def lastChild(self): + cn = self.childNodes + if cn: + return cn[-1] + return None + + def _get_firstChild(self): + return self.firstChild + + def _get_lastChild(self): + return self.lastChild + + def localName(self): + return None + + def insertBefore(self, newChild, refChild): + if newChild.nodeType == self.DOCUMENT_FRAGMENT_NODE: + for c in tuple(newChild.childNodes): + self.insertBefore(c, refChild) + return newChild + if newChild.nodeType not in self._child_node_types: + raise xml.dom.HierarchyRequestErr("%s cannot be child of %s" % (repr(newChild), repr(self))) + if newChild.parentNode is not None: + newChild.parentNode.removeChild(newChild) + if refChild is None: + self.appendChild(newChild) + else: + try: + index = _index(self.childNodes, refChild) + except ValueError: + raise xml.dom.NotFoundErr() + if newChild.nodeType in _nodeTypes_with_children: + _clear_id_cache(self) + self.childNodes.insert(index, newChild) + newChild.nextSibling = refChild + refChild.previousSibling = newChild + if index: + node = self.childNodes[index - 1] + node.nextSibling = newChild + newChild.previousSibling = node + else: + newChild.previousSibling = None + newChild.parentNode = self + return newChild + + def appendChild(self, node): + if node.nodeType == self.DOCUMENT_FRAGMENT_NODE: + for c in tuple(node.childNodes): + self.appendChild(c) + return node + if node.nodeType not in self._child_node_types: + raise xml.dom.HierarchyRequestErr("%s cannot be child of %s" % (repr(node), repr(self))) + elif node.nodeType in _nodeTypes_with_children: + _clear_id_cache(self) + if node.parentNode is not None: + node.parentNode.removeChild(node) + _append_child(self, node) + node.nextSibling = None + return node + + def replaceChild(self, newChild, oldChild): + if newChild.nodeType == self.DOCUMENT_FRAGMENT_NODE: + refChild = oldChild.nextSibling + self.removeChild(oldChild) + return self.insertBefore(newChild, refChild) + if newChild.nodeType not in self._child_node_types: + raise xml.dom.HierarchyRequestErr("%s cannot be child of %s" % (repr(newChild), repr(self))) + if newChild is oldChild: + return None + if newChild.parentNode is not None: + newChild.parentNode.removeChild(newChild) + try: + index = _index(self.childNodes, oldChild) + except ValueError: + raise xml.dom.NotFoundErr() + self.childNodes[index] = newChild + newChild.parentNode = self + oldChild.parentNode = None + if newChild.nodeType in _nodeTypes_with_children or oldChild.nodeType in _nodeTypes_with_children: + _clear_id_cache(self) + newChild.nextSibling = oldChild.nextSibling + newChild.previousSibling = oldChild.previousSibling + oldChild.nextSibling = None + oldChild.previousSibling = None + if newChild.previousSibling: + newChild.previousSibling.nextSibling = newChild + if newChild.nextSibling: + newChild.nextSibling.previousSibling = newChild + return oldChild + + def removeChild(self, oldChild): + try: + index = _index(self.childNodes, oldChild) + except ValueError: + raise xml.dom.NotFoundErr() + del self.childNodes[index] + if oldChild.nextSibling is not None: + oldChild.nextSibling.previousSibling = oldChild.previousSibling + if oldChild.previousSibling is not None: + oldChild.previousSibling.nextSibling = oldChild.nextSibling + oldChild.nextSibling = oldChild.previousSibling = None + if oldChild.nodeType in _nodeTypes_with_children: + _clear_id_cache(self) + oldChild.parentNode = None + return oldChild + + def normalize(self): + L = [] + for child in self.childNodes: + if child.nodeType == Node.TEXT_NODE: + if not child.data: + if L: + L[-1].nextSibling = child.nextSibling + if child.nextSibling: + child.nextSibling.previousSibling = child.previousSibling + child.unlink() + elif L and L[-1].nodeType == child.nodeType: + node = L[-1] + node.data = node.data + child.data + node.nextSibling = child.nextSibling + if child.nextSibling: + child.nextSibling.previousSibling = node + child.unlink() + else: + L.append(child) + else: + L.append(child) + if child.nodeType == Node.ELEMENT_NODE: + child.normalize() + self.childNodes[:] = L + + def cloneNode(self, deep): + return _clone_node(self, deep, self.ownerDocument or self) + + def isSupported(self, feature, version): + return self.ownerDocument.implementation.hasFeature(feature, version) + + def _get_localName(self): + return None + + def isSameNode(self, other): + return self is other + + def getInterface(self, feature): + if self.isSupported(feature, None): + return self + return None + + def getUserData(self, key): + try: + return self._user_data[key][0] + except (AttributeError, KeyError): + return None + + def setUserData(self, key, data, handler): + old = None + try: + d = self._user_data + except AttributeError: + d = {} + self._user_data = d + if key in d: + old = d[key][0] + if data is None: + handler = None + if old is not None: + del d[key] + else: + d[key] = (data, handler) + return old + + def _call_user_data_handler(self, operation, src, dst): + if hasattr(self, "_user_data"): + for key, (data, handler) in list(self._user_data.items()): + if handler is not None: + handler.handle(operation, key, data, src, dst) + + def unlink(self): + self.parentNode = self.ownerDocument = None + if self.childNodes: + for child in self.childNodes: + child.unlink() + self.childNodes = NodeList() + self.previousSibling = None + self.nextSibling = None + + def __enter__(self): + return self + + def __exit__(self, et, ev, tb): + self.unlink() + + +def _index(nodes, node): + i = 0 + for n in nodes: + if n is node: + return i + i += 1 + raise ValueError("not in list") + + +def _append_child(self, node): + childNodes = self.childNodes + if childNodes: + last = childNodes[-1] + node.previousSibling = last + last.nextSibling = node + childNodes.append(node) + node.parentNode = self + + +def _in_document(node): + while node is not None: + if node.nodeType == Node.DOCUMENT_NODE: + return True + node = node.parentNode + return False + + +def _get_elements_by_tagName_helper(parent, name, rc): + for node in parent.childNodes: + if node.nodeType == Node.ELEMENT_NODE and (name == "*" or node.tagName == name): + rc.append(node) + _get_elements_by_tagName_helper(node, name, rc) + return rc + + +def _get_elements_by_tagName_ns_helper(parent, nsURI, localName, rc): + for node in parent.childNodes: + if node.nodeType == Node.ELEMENT_NODE: + if ((localName == "*" or node.localName == localName) and + (nsURI == "*" or node.namespaceURI == nsURI)): + rc.append(node) + _get_elements_by_tagName_ns_helper(node, nsURI, localName, rc) + return rc + + +class DocumentFragment(Node): + nodeType = Node.DOCUMENT_FRAGMENT_NODE + nodeName = "#document-fragment" + nodeValue = None + attributes = None + parentNode = None + _child_node_types = (Node.ELEMENT_NODE, Node.TEXT_NODE, Node.CDATA_SECTION_NODE, Node.ENTITY_REFERENCE_NODE, + Node.PROCESSING_INSTRUCTION_NODE, Node.COMMENT_NODE, Node.NOTATION_NODE) + + def __init__(self): + self.childNodes = NodeList() + + +class Attr(Node): + nodeType = Node.ATTRIBUTE_NODE + attributes = None + specified = False + _is_id = False + _child_node_types = (Node.TEXT_NODE, Node.ENTITY_REFERENCE_NODE) + + def __init__(self, qName, namespaceURI=EMPTY_NAMESPACE, localName=None, prefix=None): + self.ownerElement = None + self._name = qName + self.namespaceURI = namespaceURI + self._prefix = prefix + if localName is not None: + self._localName = localName + self.childNodes = NodeList() + self.childNodes.append(Text()) + self._value = "" + + @property + def localName(self): + try: + return self._localName + except AttributeError: + return self.nodeName.split(":", 1)[-1] + + def _get_localName(self): + return self.localName + + @property + def name(self): + return self._name + + @name.setter + def name(self, value): + self._name = value + if self.ownerElement is not None: + _clear_id_cache(self.ownerElement) + + @property + def nodeName(self): + return self._name + + @nodeName.setter + def nodeName(self, value): + self.name = value + + @property + def value(self): + return self._value + + @value.setter + def value(self, value): + self._value = value + self.childNodes[0].data = value + if self.ownerElement is not None: + _clear_id_cache(self.ownerElement) + self.childNodes[0].data = value + + @property + def nodeValue(self): + return self._value + + @nodeValue.setter + def nodeValue(self, value): + self.value = value + + @property + def prefix(self): + return self._prefix + + @prefix.setter + def prefix(self, prefix): + nsuri = self.namespaceURI + if prefix == "xmlns": + if nsuri and nsuri != XMLNS_NAMESPACE: + raise xml.dom.NamespaceErr("illegal use of 'xmlns' prefix for the wrong namespace") + self._prefix = prefix + if prefix is None: + newName = self.localName + else: + newName = "%s:%s" % (prefix, self.localName) + if self.ownerElement: + _clear_id_cache(self.ownerElement) + self.name = newName + + def unlink(self): + elem = self.ownerElement + if elem is not None: + del elem._attrs[self.nodeName] + del elem._attrsNS[(self.namespaceURI, self.localName)] + if self._is_id: + self._is_id = False + elem._magic_id_nodes -= 1 + self.ownerDocument._magic_id_count -= 1 + for child in self.childNodes: + child.unlink() + del self.childNodes[:] + + @property + def isId(self): + if self._is_id: + return True + doc = self.ownerDocument + elem = self.ownerElement + if doc is None or elem is None: + return False + info = doc._get_elem_info(elem) + if info is None: + return False + if self.namespaceURI: + return info.isIdNS(self.namespaceURI, self.localName) + return info.isId(self.nodeName) + + @property + def schemaType(self): + doc = self.ownerDocument + elem = self.ownerElement + if doc is None or elem is None: + return _no_type + info = doc._get_elem_info(elem) + if info is None: + return _no_type + if self.namespaceURI: + return info.getAttributeTypeNS(self.namespaceURI, self.localName) + return info.getAttributeType(self.nodeName) + + def __repr__(self): + return "" % (self._name, id(self)) + + +class NamedNodeMap: + def __init__(self, attrs, attrsNS, ownerElement): + self._attrs = attrs + self._attrsNS = attrsNS + self._ownerElement = ownerElement + + @property + def length(self): + return len(self._attrs) + + def _get_length(self): + return len(self._attrs) + + def item(self, index): + try: + return self[list(self._attrs.keys())[index]] + except IndexError: + return None + + def items(self): + L = [] + for node in self._attrs.values(): + L.append((node.nodeName, node.value)) + return L + + def itemsNS(self): + L = [] + for node in self._attrs.values(): + L.append(((node.namespaceURI, node.localName), node.value)) + return L + + def __contains__(self, key): + if isinstance(key, str): + return key in self._attrs + return key in self._attrsNS + + def keys(self): + return self._attrs.keys() + + def keysNS(self): + return self._attrsNS.keys() + + def values(self): + return self._attrs.values() + + def get(self, name, value=None): + return self._attrs.get(name, value) + + def __len__(self): + return self.length + + def _cmp(self, other): + if self._attrs is getattr(other, "_attrs", None): + return 0 + return (id(self) > id(other)) - (id(self) < id(other)) + + def __eq__(self, other): + return self._cmp(other) == 0 + + def __ne__(self, other): + return self._cmp(other) != 0 + + __hash__ = None + + def __getitem__(self, attname_or_tuple): + if isinstance(attname_or_tuple, tuple): + return self._attrsNS[attname_or_tuple] + return self._attrs[attname_or_tuple] + + def __setitem__(self, attname, value): + if isinstance(value, str): + try: + node = self._attrs[attname] + except KeyError: + node = Attr(attname) + node.ownerDocument = self._ownerElement.ownerDocument + self.setNamedItem(node) + node.value = value + else: + if not isinstance(value, Attr): + raise TypeError("value must be a string or Attr object") + node = value + self.setNamedItem(node) + + def getNamedItem(self, name): + try: + return self._attrs[name] + except KeyError: + return None + + def getNamedItemNS(self, namespaceURI, localName): + try: + return self._attrsNS[(namespaceURI, localName)] + except KeyError: + return None + + def removeNamedItem(self, name): + n = self.getNamedItem(name) + if n is not None: + _clear_id_cache(self._ownerElement) + del self._attrs[n.nodeName] + del self._attrsNS[(n.namespaceURI, n.localName)] + if hasattr(n, "ownerElement"): + n.ownerElement = None + return n + raise xml.dom.NotFoundErr() + + def removeNamedItemNS(self, namespaceURI, localName): + n = self.getNamedItemNS(namespaceURI, localName) + if n is not None: + _clear_id_cache(self._ownerElement) + del self._attrsNS[(n.namespaceURI, n.localName)] + del self._attrs[n.nodeName] + if hasattr(n, "ownerElement"): + n.ownerElement = None + return n + raise xml.dom.NotFoundErr() + + def setNamedItem(self, node): + if not isinstance(node, Attr): + raise xml.dom.HierarchyRequestErr("%s cannot be child of %s" % (repr(node), repr(self))) + old = self._attrs.get(node.name) + if old: + old.unlink() + self._attrs[node.name] = node + self._attrsNS[(node.namespaceURI, node.localName)] = node + node.ownerElement = self._ownerElement + _clear_id_cache(node.ownerElement) + return old + + def setNamedItemNS(self, node): + return self.setNamedItem(node) + + def __delitem__(self, attname_or_tuple): + node = self[attname_or_tuple] + _clear_id_cache(node.ownerElement) + node.unlink() + + +AttributeList = NamedNodeMap + + +class TypeInfo: + __slots__ = ("namespace", "name") + + def __init__(self, namespace, name): + self.namespace = namespace + self.name = name + + def __repr__(self): + if self.namespace: + return "<%s %r (from %r)>" % (self.__class__.__name__, self.name, self.namespace) + return "<%s %r>" % (self.__class__.__name__, self.name) + + +_no_type = TypeInfo(None, None) + + +class Element(Node): + nodeType = Node.ELEMENT_NODE + nodeValue = None + schemaType = _no_type + _magic_id_nodes = 0 + _child_node_types = (Node.ELEMENT_NODE, Node.PROCESSING_INSTRUCTION_NODE, Node.COMMENT_NODE, Node.TEXT_NODE, + Node.CDATA_SECTION_NODE, Node.ENTITY_REFERENCE_NODE) + + def __init__(self, tagName, namespaceURI=EMPTY_NAMESPACE, prefix=None, localName=None): + self.parentNode = None + self.tagName = self.nodeName = tagName + self.prefix = prefix + self.namespaceURI = namespaceURI + self.childNodes = NodeList() + self.nextSibling = self.previousSibling = None + self._attrs = None + self._attrsNS = None + if localName is not None: + self._localName = localName + + def _ensure_attributes(self): + if self._attrs is None: + self._attrs = {} + self._attrsNS = {} + + @property + def localName(self): + try: + return self._localName + except AttributeError: + return self.tagName.split(":", 1)[-1] + + def _get_localName(self): + return self.localName + + def _get_tagName(self): + return self.tagName + + def unlink(self): + if self._attrs is not None: + for attr in list(self._attrs.values()): + attr.unlink() + self._attrs = None + self._attrsNS = None + Node.unlink(self) + + def getAttribute(self, attname): + if self._attrs is None: + return "" + try: + return self._attrs[attname].value + except KeyError: + return "" + + def getAttributeNS(self, namespaceURI, localName): + if self._attrsNS is None: + return "" + try: + return self._attrsNS[(namespaceURI, localName)].value + except KeyError: + return "" + + def setAttribute(self, attname, value): + attr = self.getAttributeNode(attname) + if attr is None: + attr = Attr(attname) + attr.value = value + attr.ownerDocument = self.ownerDocument + self.setAttributeNode(attr) + elif value != attr.value: + attr.value = value + if attr.isId: + _clear_id_cache(self) + + def setAttributeNS(self, namespaceURI, qualifiedName, value): + prefix, localname = _nssplit(qualifiedName) + attr = self.getAttributeNodeNS(namespaceURI, localname) + if attr is None: + attr = Attr(qualifiedName, namespaceURI, localname, prefix) + attr.value = value + attr.ownerDocument = self.ownerDocument + self.setAttributeNode(attr) + else: + if value != attr.value: + attr.value = value + if attr.isId: + _clear_id_cache(self) + if attr.prefix != prefix: + attr.prefix = prefix + attr.nodeName = qualifiedName + + def getAttributeNode(self, attrname): + if self._attrs is None: + return None + return self._attrs.get(attrname) + + def getAttributeNodeNS(self, namespaceURI, localName): + if self._attrsNS is None: + return None + return self._attrsNS.get((namespaceURI, localName)) + + def setAttributeNode(self, attr): + if attr.ownerElement not in (None, self): + raise xml.dom.InuseAttributeErr("attribute node already owned") + self._ensure_attributes() + old1 = self._attrs.get(attr.name, None) + if old1 is not None: + self.removeAttributeNode(old1) + old2 = self._attrsNS.get((attr.namespaceURI, attr.localName), None) + if old2 is not None and old2 is not old1: + self.removeAttributeNode(old2) + _set_attribute_node(self, attr) + if old1 is not attr: + return old1 + if old2 is not attr: + return old2 + return None + + setAttributeNodeNS = setAttributeNode + + def removeAttribute(self, name): + if self._attrsNS is None: + raise xml.dom.NotFoundErr() + try: + attr = self._attrs[name] + except KeyError: + raise xml.dom.NotFoundErr() + self.removeAttributeNode(attr) + + def removeAttributeNS(self, namespaceURI, localName): + if self._attrsNS is None: + raise xml.dom.NotFoundErr() + try: + attr = self._attrsNS[(namespaceURI, localName)] + except KeyError: + raise xml.dom.NotFoundErr() + self.removeAttributeNode(attr) + + def removeAttributeNode(self, node): + if node is None: + raise xml.dom.NotFoundErr() + try: + self._attrs[node.name] + except KeyError: + raise xml.dom.NotFoundErr() + _clear_id_cache(self) + node.unlink() + node.ownerDocument = self.ownerDocument + return node + + removeAttributeNodeNS = removeAttributeNode + + def hasAttribute(self, name): + if self._attrs is None: + return False + return name in self._attrs + + def hasAttributeNS(self, namespaceURI, localName): + if self._attrsNS is None: + return False + return (namespaceURI, localName) in self._attrsNS + + def getElementsByTagName(self, name): + return _get_elements_by_tagName_helper(self, name, NodeList()) + + def getElementsByTagNameNS(self, namespaceURI, localName): + return _get_elements_by_tagName_ns_helper(self, namespaceURI, localName, NodeList()) + + def __repr__(self): + return "" % (self.tagName, id(self)) + + def writexml(self, writer, indent="", addindent="", newl=""): + writer.write(indent + "<" + self.tagName) + attrs = self._get_attributes() + for a_name in attrs.keys(): + writer.write(' %s="' % a_name) + _write_data(writer, attrs[a_name].value, True) + writer.write('"') + if self.childNodes: + writer.write(">") + if (len(self.childNodes) == 1 and + self.childNodes[0].nodeType in (Node.TEXT_NODE, Node.CDATA_SECTION_NODE)): + self.childNodes[0].writexml(writer, "", "", "") + else: + writer.write(newl) + for node in self.childNodes: + node.writexml(writer, indent + addindent, addindent, newl) + writer.write(indent) + writer.write("%s" % (self.tagName, newl)) + else: + writer.write("/>%s" % newl) + + def _get_attributes(self): + self._ensure_attributes() + return NamedNodeMap(self._attrs, self._attrsNS, self) + + @property + def attributes(self): + return self._get_attributes() + + def hasAttributes(self): + if self._attrs: + return True + return False + + def setIdAttribute(self, name): + idAttr = self.getAttributeNode(name) + self.setIdAttributeNode(idAttr) + + def setIdAttributeNS(self, namespaceURI, localName): + idAttr = self.getAttributeNodeNS(namespaceURI, localName) + self.setIdAttributeNode(idAttr) + + def setIdAttributeNode(self, idAttr): + if idAttr is None or not self.isSameNode(idAttr.ownerElement): + raise xml.dom.NotFoundErr() + if _get_containing_entref(self) is not None: + raise xml.dom.NoModificationAllowedErr() + if not idAttr._is_id: + idAttr._is_id = True + self._magic_id_nodes += 1 + self.ownerDocument._magic_id_count += 1 + _clear_id_cache(self) + + +def _set_attribute_node(element, attr): + _clear_id_cache(element) + element._ensure_attributes() + element._attrs[attr.name] = attr + element._attrsNS[(attr.namespaceURI, attr.localName)] = attr + attr.ownerElement = element + + +class Childless: + attributes = None + childNodes = EmptyNodeList() + firstChild = None + lastChild = None + + def _get_firstChild(self): + return None + + def _get_lastChild(self): + return None + + def appendChild(self, node): + raise xml.dom.HierarchyRequestErr(self.nodeName + " nodes cannot have children") + + def hasChildNodes(self): + return False + + def insertBefore(self, newChild, refChild): + raise xml.dom.HierarchyRequestErr(self.nodeName + " nodes do not have children") + + def removeChild(self, oldChild): + raise xml.dom.NotFoundErr(self.nodeName + " nodes do not have children") + + def normalize(self): + pass + + def replaceChild(self, newChild, oldChild): + raise xml.dom.HierarchyRequestErr(self.nodeName + " nodes do not have children") + + +class ProcessingInstruction(Childless, Node): + nodeType = Node.PROCESSING_INSTRUCTION_NODE + + def __init__(self, target, data): + self.target = target + self.data = data + + @property + def nodeValue(self): + return self.data + + @nodeValue.setter + def nodeValue(self, value): + self.data = value + + @property + def nodeName(self): + return self.target + + @nodeName.setter + def nodeName(self, value): + self.target = value + + def writexml(self, writer, indent="", addindent="", newl=""): + writer.write("%s%s" % (indent, self.target, self.data, newl)) + + +class CharacterData(Childless, Node): + def __init__(self): + self.ownerDocument = self.parentNode = None + self.previousSibling = self.nextSibling = None + self._data = "" + + @property + def length(self): + return len(self.data) + + def _get_length(self): + return len(self.data) + + @property + def data(self): + return self._data + + @data.setter + def data(self, data): + self._data = data + + @property + def nodeValue(self): + return self._data + + @nodeValue.setter + def nodeValue(self, data): + self._data = data + + def __repr__(self): + data = self.data + if len(data) > 10: + dotdotdot = "..." + else: + dotdotdot = "" + return '' % (self.__class__.__name__, data[0:10], dotdotdot) + + def substringData(self, offset, count): + if offset < 0: + raise xml.dom.IndexSizeErr("offset cannot be negative") + if offset >= len(self.data): + raise xml.dom.IndexSizeErr("offset cannot be beyond end of data") + if count < 0: + raise xml.dom.IndexSizeErr("count cannot be negative") + return self.data[offset:offset + count] + + def appendData(self, arg): + self.data = self.data + arg + + def insertData(self, offset, arg): + if offset < 0: + raise xml.dom.IndexSizeErr("offset cannot be negative") + if offset >= len(self.data): + raise xml.dom.IndexSizeErr("offset cannot be beyond end of data") + if arg: + self.data = "%s%s%s" % (self.data[:offset], arg, self.data[offset:]) + + def deleteData(self, offset, count): + if offset < 0: + raise xml.dom.IndexSizeErr("offset cannot be negative") + if offset >= len(self.data): + raise xml.dom.IndexSizeErr("offset cannot be beyond end of data") + if count < 0: + raise xml.dom.IndexSizeErr("count cannot be negative") + if count: + self.data = self.data[:offset] + self.data[offset + count:] + + def replaceData(self, offset, count, arg): + if offset < 0: + raise xml.dom.IndexSizeErr("offset cannot be negative") + if offset >= len(self.data): + raise xml.dom.IndexSizeErr("offset cannot be beyond end of data") + if count < 0: + raise xml.dom.IndexSizeErr("count cannot be negative") + if count: + self.data = "%s%s%s" % (self.data[:offset], arg, self.data[offset + count:]) + + +class Text(CharacterData): + nodeType = Node.TEXT_NODE + nodeName = "#text" + attributes = None + + def splitText(self, offset): + if offset < 0 or offset > len(self.data): + raise xml.dom.IndexSizeErr("illegal offset value") + newText = self.__class__() + newText.data = self.data[offset:] + newText.ownerDocument = self.ownerDocument + next = self.nextSibling + if self.parentNode and self in self.parentNode.childNodes: + if next is None: + self.parentNode.appendChild(newText) + else: + self.parentNode.insertBefore(newText, next) + self.data = self.data[:offset] + return newText + + def writexml(self, writer, indent="", addindent="", newl=""): + _write_data(writer, "%s%s%s" % (indent, self.data, newl), False) + + @property + def wholeText(self): + L = [self.data] + n = self.previousSibling + while n is not None: + if n.nodeType in (Node.TEXT_NODE, Node.CDATA_SECTION_NODE): + L.insert(0, n.data) + n = n.previousSibling + else: + break + n = self.nextSibling + while n is not None: + if n.nodeType in (Node.TEXT_NODE, Node.CDATA_SECTION_NODE): + L.append(n.data) + n = n.nextSibling + else: + break + return "".join(L) + + def replaceWholeText(self, content): + parent = self.parentNode + n = self.previousSibling + while n is not None: + if n.nodeType in (Node.TEXT_NODE, Node.CDATA_SECTION_NODE): + next = n.previousSibling + parent.removeChild(n) + n = next + else: + break + n = self.nextSibling + if not content: + parent.removeChild(self) + while n is not None: + if n.nodeType in (Node.TEXT_NODE, Node.CDATA_SECTION_NODE): + next = n.nextSibling + parent.removeChild(n) + n = next + else: + break + if content: + self.data = content + return self + return None + + @property + def isWhitespaceInElementContent(self): + if self.data.strip(): + return False + elem = _get_containing_element(self) + if elem is None: + return False + info = self.ownerDocument._get_elem_info(elem) + if info is None: + return False + return info.isElementContent() + + +def _get_containing_element(node): + c = node.parentNode + while c is not None: + if c.nodeType == Node.ELEMENT_NODE: + return c + c = c.parentNode + return None + + +def _get_containing_entref(node): + c = node.parentNode + while c is not None: + if c.nodeType == Node.ENTITY_REFERENCE_NODE: + return c + c = c.parentNode + return None + + +class Comment(CharacterData): + nodeType = Node.COMMENT_NODE + nodeName = "#comment" + + def __init__(self, data): + CharacterData.__init__(self) + self._data = data + + def writexml(self, writer, indent="", addindent="", newl=""): + if "--" in self.data: + raise ValueError("'--' is not allowed in a comment node") + writer.write("%s%s" % (indent, self.data, newl)) + + +class CDATASection(Text): + nodeType = Node.CDATA_SECTION_NODE + nodeName = "#cdata-section" + + def writexml(self, writer, indent="", addindent="", newl=""): + if self.data.find("]]>") >= 0: + raise ValueError("']]>' not allowed in a CDATA section") + writer.write("" % self.data) + + +class ReadOnlySequentialNamedNodeMap: + def __init__(self, seq=()): + self._seq = seq + + def __len__(self): + return len(self._seq) + + @property + def length(self): + return len(self._seq) + + def _get_length(self): + return len(self._seq) + + def getNamedItem(self, name): + for n in self._seq: + if n.nodeName == name: + return n + return None + + def getNamedItemNS(self, namespaceURI, localName): + for n in self._seq: + if n.namespaceURI == namespaceURI and n.localName == localName: + return n + return None + + def __getitem__(self, name_or_tuple): + if isinstance(name_or_tuple, tuple): + node = self.getNamedItemNS(*name_or_tuple) + else: + node = self.getNamedItem(name_or_tuple) + if node is None: + raise KeyError(name_or_tuple) + return node + + def item(self, index): + if index < 0: + return None + try: + return self._seq[index] + except IndexError: + return None + + def removeNamedItem(self, name): + raise xml.dom.NoModificationAllowedErr("NamedNodeMap instance is read-only") + + def removeNamedItemNS(self, namespaceURI, localName): + raise xml.dom.NoModificationAllowedErr("NamedNodeMap instance is read-only") + + def setNamedItem(self, node): + raise xml.dom.NoModificationAllowedErr("NamedNodeMap instance is read-only") + + def setNamedItemNS(self, node): + raise xml.dom.NoModificationAllowedErr("NamedNodeMap instance is read-only") + + +class Identified: + def _identified_mixin_init(self, publicId, systemId): + self.publicId = publicId + self.systemId = systemId + + def _get_publicId(self): + return self.publicId + + def _get_systemId(self): + return self.systemId + + +class DocumentType(Identified, Childless, Node): + nodeType = Node.DOCUMENT_TYPE_NODE + nodeValue = None + name = None + publicId = None + systemId = None + internalSubset = None + + def __init__(self, qualifiedName): + self.entities = ReadOnlySequentialNamedNodeMap() + self.notations = ReadOnlySequentialNamedNodeMap() + if qualifiedName: + prefix, localname = _nssplit(qualifiedName) + self.name = localname + self.nodeName = self.name + + def _get_internalSubset(self): + return self.internalSubset + + def cloneNode(self, deep): + if self.ownerDocument is None: + clone = DocumentType(None) + clone.name = self.name + clone.nodeName = self.name + operation = xml.dom.UserDataHandler.NODE_CLONED + if deep: + clone.entities._seq = [] + clone.notations._seq = [] + for n in self.notations._seq: + notation = Notation(n.nodeName, n.publicId, n.systemId) + clone.notations._seq.append(notation) + n._call_user_data_handler(operation, n, notation) + for e in self.entities._seq: + entity = Entity(e.nodeName, e.publicId, e.systemId, e.notationName) + entity.actualEncoding = e.actualEncoding + entity.encoding = e.encoding + entity.version = e.version + clone.entities._seq.append(entity) + e._call_user_data_handler(operation, e, entity) + self._call_user_data_handler(operation, self, clone) + return clone + return None + + def writexml(self, writer, indent="", addindent="", newl=""): + writer.write("" + newl) + + +class Entity(Identified, Node): + attributes = None + nodeType = Node.ENTITY_NODE + nodeValue = None + actualEncoding = None + encoding = None + version = None + _child_node_types = (Node.ELEMENT_NODE, Node.PROCESSING_INSTRUCTION_NODE, Node.COMMENT_NODE, Node.TEXT_NODE, + Node.CDATA_SECTION_NODE, Node.ENTITY_REFERENCE_NODE) + + def __init__(self, name, publicId, systemId, notation): + self.nodeName = name + self.notationName = notation + self.childNodes = NodeList() + self._identified_mixin_init(publicId, systemId) + + def _get_actualEncoding(self): + return self.actualEncoding + + def _get_encoding(self): + return self.encoding + + def _get_version(self): + return self.version + + def appendChild(self, newChild): + raise xml.dom.HierarchyRequestErr("cannot append children to an entity node") + + def insertBefore(self, newChild, refChild): + raise xml.dom.HierarchyRequestErr("cannot insert children below an entity node") + + def removeChild(self, oldChild): + raise xml.dom.HierarchyRequestErr("cannot remove children from an entity node") + + def replaceChild(self, newChild, oldChild): + raise xml.dom.HierarchyRequestErr("cannot replace children of an entity node") + + +class Notation(Identified, Childless, Node): + nodeType = Node.NOTATION_NODE + nodeValue = None + + def __init__(self, name, publicId, systemId): + self.nodeName = name + self._identified_mixin_init(publicId, systemId) + + +class DOMImplementation(DOMImplementationLS): + _features = [("core", "1.0"), ("core", "2.0"), ("core", None), ("xml", "1.0"), ("xml", "2.0"), ("xml", None), + ("ls-load", "3.0"), ("ls-load", None)] + + def hasFeature(self, feature, version): + if version == "": + version = None + return (feature.lower(), version) in self._features + + def createDocument(self, namespaceURI, qualifiedName, doctype): + if doctype and doctype.parentNode is not None: + raise xml.dom.WrongDocumentErr("doctype object owned by another DOM tree") + doc = self._create_document() + add_root_element = not (namespaceURI is None and qualifiedName is None and doctype is None) + if not qualifiedName and add_root_element: + raise xml.dom.InvalidCharacterErr("Element with no name") + if add_root_element: + prefix, localname = _nssplit(qualifiedName) + if prefix == "xml" and namespaceURI != "http://www.w3.org/XML/1998/namespace": + raise xml.dom.NamespaceErr("illegal use of 'xml' prefix") + if prefix and not namespaceURI: + raise xml.dom.NamespaceErr("illegal use of prefix without namespaces") + element = doc.createElementNS(namespaceURI, qualifiedName) + if doctype: + doc.appendChild(doctype) + doc.appendChild(element) + if doctype: + doctype.parentNode = doctype.ownerDocument = doc + doc.doctype = doctype + doc.implementation = self + return doc + + def createDocumentType(self, qualifiedName, publicId, systemId): + doctype = DocumentType(qualifiedName) + doctype.publicId = publicId + doctype.systemId = systemId + return doctype + + def getInterface(self, feature): + if self.hasFeature(feature, None): + return self + return None + + def _create_document(self): + return Document() + + +class ElementInfo: + __slots__ = ("tagName",) + + def __init__(self, name): + self.tagName = name + + def getAttributeType(self, aname): + return _no_type + + def getAttributeTypeNS(self, namespaceURI, localName): + return _no_type + + def isElementContent(self): + return False + + def isEmpty(self): + return False + + def isId(self, aname): + return False + + def isIdNS(self, namespaceURI, localName): + return False + + +def _clear_id_cache(node): + if node.nodeType == Node.DOCUMENT_NODE: + node._id_cache.clear() + node._id_search_stack = None + elif _in_document(node): + node.ownerDocument._id_cache.clear() + node.ownerDocument._id_search_stack = None + + +class Document(Node, DocumentLS): + _child_node_types = (Node.ELEMENT_NODE, Node.PROCESSING_INSTRUCTION_NODE, Node.COMMENT_NODE, + Node.DOCUMENT_TYPE_NODE) + implementation = DOMImplementation() + nodeType = Node.DOCUMENT_NODE + nodeName = "#document" + nodeValue = None + attributes = None + parentNode = None + previousSibling = nextSibling = None + actualEncoding = None + encoding = None + standalone = None + version = None + strictErrorChecking = False + errorHandler = None + documentURI = None + _magic_id_count = 0 + + def __init__(self): + self.doctype = None + self.childNodes = NodeList() + self._elem_info = {} + self._id_cache = {} + self._id_search_stack = None + + def _get_elem_info(self, element): + if element.namespaceURI: + key = element.namespaceURI, element.localName + else: + key = element.tagName + return self._elem_info.get(key) + + @property + def documentElement(self): + for node in self.childNodes: + if node.nodeType == Node.ELEMENT_NODE: + return node + return None + + def _get_documentElement(self): + return self.documentElement + + def _get_actualEncoding(self): + return self.actualEncoding + + def _get_doctype(self): + return self.doctype + + def _get_documentURI(self): + return self.documentURI + + def _get_encoding(self): + return self.encoding + + def _get_errorHandler(self): + return self.errorHandler + + def _get_standalone(self): + return self.standalone + + def _get_strictErrorChecking(self): + return self.strictErrorChecking + + def _get_version(self): + return self.version + + def appendChild(self, node): + if node.nodeType not in self._child_node_types: + raise xml.dom.HierarchyRequestErr("%s cannot be child of %s" % (repr(node), repr(self))) + if node.parentNode is not None: + node.parentNode.removeChild(node) + if node.nodeType == Node.ELEMENT_NODE and self._get_documentElement(): + raise xml.dom.HierarchyRequestErr("two document elements disallowed") + return Node.appendChild(self, node) + + def removeChild(self, oldChild): + try: + _index(self.childNodes, oldChild) + except ValueError: + raise xml.dom.NotFoundErr() + Node.removeChild(self, oldChild) + oldChild.nextSibling = oldChild.previousSibling = None + oldChild.parentNode = None + return oldChild + + def unlink(self): + if self.doctype is not None: + self.doctype.unlink() + self.doctype = None + Node.unlink(self) + + def cloneNode(self, deep): + if not deep: + return None + clone = self.implementation.createDocument(None, None, None) + clone.encoding = self.encoding + clone.standalone = self.standalone + clone.version = self.version + for n in self.childNodes: + childclone = _clone_node(n, deep, clone) + assert childclone.ownerDocument.isSameNode(clone) + clone.childNodes.append(childclone) + if childclone.nodeType == Node.DOCUMENT_NODE: + assert clone.documentElement is None + elif childclone.nodeType == Node.DOCUMENT_TYPE_NODE: + assert clone.doctype is None + clone.doctype = childclone + childclone.parentNode = clone + self._call_user_data_handler(xml.dom.UserDataHandler.NODE_CLONED, self, clone) + return clone + + def createDocumentFragment(self): + d = DocumentFragment() + d.ownerDocument = self + return d + + def createElement(self, tagName): + e = Element(tagName) + e.ownerDocument = self + return e + + def createTextNode(self, data): + if not isinstance(data, str): + raise TypeError("node contents must be a string") + t = Text() + t.data = data + t.ownerDocument = self + return t + + def createCDATASection(self, data): + if not isinstance(data, str): + raise TypeError("node contents must be a string") + c = CDATASection() + c.data = data + c.ownerDocument = self + return c + + def createComment(self, data): + c = Comment(data) + c.ownerDocument = self + return c + + def createProcessingInstruction(self, target, data): + p = ProcessingInstruction(target, data) + p.ownerDocument = self + return p + + def createAttribute(self, qName): + a = Attr(qName) + a.ownerDocument = self + a.value = "" + return a + + def createElementNS(self, namespaceURI, qualifiedName): + prefix, localName = _nssplit(qualifiedName) + e = Element(qualifiedName, namespaceURI, prefix) + e.ownerDocument = self + return e + + def createAttributeNS(self, namespaceURI, qualifiedName): + prefix, localName = _nssplit(qualifiedName) + a = Attr(qualifiedName, namespaceURI, localName, prefix) + a.ownerDocument = self + a.value = "" + return a + + def _create_entity(self, name, publicId, systemId, notationName): + e = Entity(name, publicId, systemId, notationName) + e.ownerDocument = self + return e + + def _create_notation(self, name, publicId, systemId): + n = Notation(name, publicId, systemId) + n.ownerDocument = self + return n + + def getElementById(self, id): + if id in self._id_cache: + return self._id_cache[id] + if not (self._elem_info or self._magic_id_count): + return None + stack = self._id_search_stack + if stack is None: + stack = [self.documentElement] + self._id_search_stack = stack + elif not stack: + return None + result = None + while stack: + node = stack.pop() + stack.extend([child for child in node.childNodes if child.nodeType in _nodeTypes_with_children]) + info = self._get_elem_info(node) + if info: + for attr in node.attributes.values(): + if attr.namespaceURI: + if info.isIdNS(attr.namespaceURI, attr.localName): + self._id_cache[attr.value] = node + if attr.value == id: + result = node + elif not node._magic_id_nodes: + break + elif info.isId(attr.name): + self._id_cache[attr.value] = node + if attr.value == id: + result = node + elif not node._magic_id_nodes: + break + elif attr._is_id: + self._id_cache[attr.value] = node + if attr.value == id: + result = node + elif node._magic_id_nodes == 1: + break + elif node._magic_id_nodes: + for attr in node.attributes.values(): + if attr._is_id: + self._id_cache[attr.value] = node + if attr.value == id: + result = node + if result is not None: + break + return result + + def getElementsByTagName(self, name): + return _get_elements_by_tagName_helper(self, name, NodeList()) + + def getElementsByTagNameNS(self, namespaceURI, localName): + return _get_elements_by_tagName_ns_helper(self, namespaceURI, localName, NodeList()) + + def isSupported(self, feature, version): + return self.implementation.hasFeature(feature, version) + + def importNode(self, node, deep): + if node.nodeType == Node.DOCUMENT_NODE: + raise xml.dom.NotSupportedErr("cannot import document nodes") + elif node.nodeType == Node.DOCUMENT_TYPE_NODE: + raise xml.dom.NotSupportedErr("cannot import document type nodes") + return _clone_node(node, deep, self) + + def writexml(self, writer, indent="", addindent="", newl="", encoding=None, standalone=None): + declarations = [] + if encoding: + declarations.append('encoding="%s"' % encoding) + if standalone is not None: + declarations.append('standalone="%s"' % ("yes" if standalone else "no")) + writer.write('%s' % (" ".join(declarations), newl)) + for node in self.childNodes: + node.writexml(writer, indent, addindent, newl) + + def renameNode(self, n, namespaceURI, name): + if n.ownerDocument is not self: + raise xml.dom.WrongDocumentErr("cannot rename nodes from other documents;\nexpected %s,\nfound %s" + % (self, n.ownerDocument)) + if n.nodeType not in (Node.ELEMENT_NODE, Node.ATTRIBUTE_NODE): + raise xml.dom.NotSupportedErr("renameNode() only applies to element and attribute nodes") + if namespaceURI != EMPTY_NAMESPACE: + if ":" in name: + prefix, localName = name.split(":", 1) + if prefix == "xmlns" and namespaceURI != xml.dom.XMLNS_NAMESPACE: + raise xml.dom.NamespaceErr("illegal use of 'xmlns' prefix") + else: + if name == "xmlns" and namespaceURI != xml.dom.XMLNS_NAMESPACE and n.nodeType == Node.ATTRIBUTE_NODE: + raise xml.dom.NamespaceErr("illegal use of the 'xmlns' attribute") + prefix = None + localName = name + else: + prefix = None + localName = None + if n.nodeType == Node.ATTRIBUTE_NODE: + element = n.ownerElement + if element is not None: + is_id = n._is_id + element.removeAttributeNode(n) + else: + element = None + n.prefix = prefix + n._localName = localName + n.namespaceURI = namespaceURI + n.nodeName = name + if n.nodeType == Node.ELEMENT_NODE: + n.tagName = name + else: + n.name = name + if element is not None: + element.setAttributeNode(n) + if is_id: + element.setIdAttributeNode(n) + return n + + +def _clone_node(node, deep, newOwnerDocument): + if node.ownerDocument.isSameNode(newOwnerDocument): + operation = xml.dom.UserDataHandler.NODE_CLONED + else: + operation = xml.dom.UserDataHandler.NODE_IMPORTED + if node.nodeType == Node.ELEMENT_NODE: + clone = newOwnerDocument.createElementNS(node.namespaceURI, node.nodeName) + for attr in node.attributes.values(): + clone.setAttributeNS(attr.namespaceURI, attr.nodeName, attr.value) + a = clone.getAttributeNodeNS(attr.namespaceURI, attr.localName) + a.specified = attr.specified + if deep: + for child in node.childNodes: + c = _clone_node(child, deep, newOwnerDocument) + clone.appendChild(c) + elif node.nodeType == Node.DOCUMENT_FRAGMENT_NODE: + clone = newOwnerDocument.createDocumentFragment() + if deep: + for child in node.childNodes: + c = _clone_node(child, deep, newOwnerDocument) + clone.appendChild(c) + elif node.nodeType == Node.TEXT_NODE: + clone = newOwnerDocument.createTextNode(node.data) + elif node.nodeType == Node.CDATA_SECTION_NODE: + clone = newOwnerDocument.createCDATASection(node.data) + elif node.nodeType == Node.PROCESSING_INSTRUCTION_NODE: + clone = newOwnerDocument.createProcessingInstruction(node.target, node.data) + elif node.nodeType == Node.COMMENT_NODE: + clone = newOwnerDocument.createComment(node.data) + elif node.nodeType == Node.ATTRIBUTE_NODE: + clone = newOwnerDocument.createAttributeNS(node.namespaceURI, node.nodeName) + clone.specified = True + clone.value = node.value + elif node.nodeType == Node.DOCUMENT_TYPE_NODE: + assert node.ownerDocument is not newOwnerDocument + operation = xml.dom.UserDataHandler.NODE_IMPORTED + clone = newOwnerDocument.implementation.createDocumentType(node.name, node.publicId, node.systemId) + clone.ownerDocument = newOwnerDocument + if deep: + clone.entities._seq = [] + clone.notations._seq = [] + for n in node.notations._seq: + notation = Notation(n.nodeName, n.publicId, n.systemId) + notation.ownerDocument = newOwnerDocument + clone.notations._seq.append(notation) + if hasattr(n, "_call_user_data_handler"): + n._call_user_data_handler(operation, n, notation) + for e in node.entities._seq: + entity = Entity(e.nodeName, e.publicId, e.systemId, e.notationName) + entity.actualEncoding = e.actualEncoding + entity.encoding = e.encoding + entity.version = e.version + entity.ownerDocument = newOwnerDocument + clone.entities._seq.append(entity) + if hasattr(e, "_call_user_data_handler"): + e._call_user_data_handler(operation, e, entity) + else: + raise xml.dom.NotSupportedErr("Cannot clone node %s" % repr(node)) + if hasattr(node, "_call_user_data_handler"): + node._call_user_data_handler(operation, node, clone) + return clone + + +def _nssplit(qualifiedName): + fields = qualifiedName.split(":", 1) + if len(fields) == 2: + return fields + return (None, fields[0]) + + +def _do_pulldom_parse(func, args, kwargs): + events = func(*args, **kwargs) + toktype, rootNode = events.getEvent() + events.expandNode(rootNode) + events.clear() + return rootNode + + +def parse(file, parser=None, bufsize=None): + if parser is None and not bufsize: + from xml.dom import expatbuilder + return expatbuilder.parse(file) + from xml.dom import pulldom + return _do_pulldom_parse(pulldom.parse, (file,), {"parser": parser, "bufsize": bufsize}) + + +def parseString(string, parser=None): + if parser is None: + from xml.dom import expatbuilder + return expatbuilder.parseString(string) + from xml.dom import pulldom + return _do_pulldom_parse(pulldom.parseString, (string,), {"parser": parser}) + + +def getDOMImplementation(features=None): + if features: + if isinstance(features, str): + from xml.dom import domreg + features = domreg._parse_feature_string(features) + for f, v in features: + if not Document.implementation.hasFeature(f, v): + return None + return Document.implementation diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/xml/dom/pulldom.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/xml/dom/pulldom.py new file mode 100644 index 00000000000..ec5f9c10a62 --- /dev/null +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/xml/dom/pulldom.py @@ -0,0 +1,333 @@ +# Copyright (c) 2001 Python Software Foundation; All Rights Reserved +# Licensed under the Python Software Foundation License Version 2; the full +# text is in maven/python-transpiler/third-party/cpython/LICENSE.txt. +# +# Derived from CPython's Lib/xml/dom/pulldom.py. Changes: rewritten for the Codename One +# Python runtime, trimmed to what the transpiler supports and reorganised; +# the C accelerators and platform-specific branches are left out. +"""xml.dom.pulldom: a stream of DOM events built from SAX, with +expandNode() to turn the rest of an element into a subtree.""" + +import xml.sax +import xml.sax.handler + +START_ELEMENT = "START_ELEMENT" +END_ELEMENT = "END_ELEMENT" +COMMENT = "COMMENT" +START_DOCUMENT = "START_DOCUMENT" +END_DOCUMENT = "END_DOCUMENT" +PROCESSING_INSTRUCTION = "PROCESSING_INSTRUCTION" +IGNORABLE_WHITESPACE = "IGNORABLE_WHITESPACE" +CHARACTERS = "CHARACTERS" + + +class PullDOM(xml.sax.ContentHandler): + _locator = None + document = None + + def __init__(self, documentFactory=None): + from xml.dom import XML_NAMESPACE + self.documentFactory = documentFactory + self.firstEvent = [None, None] + self.lastEvent = self.firstEvent + self.elementStack = [] + self.push = self.elementStack.append + self._ns_contexts = [{XML_NAMESPACE: "xml"}] + self._current_context = self._ns_contexts[-1] + self.pending_events = [] + + def pop(self): + result = self.elementStack[-1] + del self.elementStack[-1] + return result + + def setDocumentLocator(self, locator): + self._locator = locator + + def startPrefixMapping(self, prefix, uri): + if not hasattr(self, "_xmlns_attrs"): + self._xmlns_attrs = [] + self._xmlns_attrs.append((prefix or "xmlns", uri)) + self._ns_contexts.append(self._current_context.copy()) + self._current_context[uri] = prefix or None + + def endPrefixMapping(self, prefix): + self._current_context = self._ns_contexts.pop() + + def startElementNS(self, name, tagName, attrs): + xmlns_uri = "http://www.w3.org/2000/xmlns/" + xmlns_attrs = getattr(self, "_xmlns_attrs", None) + if xmlns_attrs is not None: + for aname, value in xmlns_attrs: + attrs._attrs[(xmlns_uri, aname)] = value + self._xmlns_attrs = [] + uri, localname = name + if uri: + if tagName is None: + prefix = self._current_context[uri] + if prefix: + tagName = prefix + ":" + localname + else: + tagName = localname + if self.document: + node = self.document.createElementNS(uri, tagName) + else: + node = self.buildDocument(uri, tagName) + else: + if self.document: + node = self.document.createElement(localname) + else: + node = self.buildDocument(None, localname) + for aname, value in attrs.items(): + a_uri, a_localname = aname + if a_uri == xmlns_uri: + if a_localname == "xmlns": + qname = a_localname + else: + qname = "xmlns:" + a_localname + attr = self.document.createAttributeNS(a_uri, qname) + node.setAttributeNodeNS(attr) + elif a_uri: + prefix = self._current_context[a_uri] + if prefix: + qname = prefix + ":" + a_localname + else: + qname = a_localname + attr = self.document.createAttributeNS(a_uri, qname) + node.setAttributeNodeNS(attr) + else: + attr = self.document.createAttribute(a_localname) + node.setAttributeNode(attr) + attr.value = value + self.lastEvent[1] = [(START_ELEMENT, node), None] + self.lastEvent = self.lastEvent[1] + self.push(node) + + def endElementNS(self, name, tagName): + self.lastEvent[1] = [(END_ELEMENT, self.pop()), None] + self.lastEvent = self.lastEvent[1] + + def startElement(self, name, attrs): + if self.document: + node = self.document.createElement(name) + else: + node = self.buildDocument(None, name) + for aname, value in attrs.items(): + attr = self.document.createAttribute(aname) + attr.value = value + node.setAttributeNode(attr) + self.lastEvent[1] = [(START_ELEMENT, node), None] + self.lastEvent = self.lastEvent[1] + self.push(node) + + def endElement(self, name): + self.lastEvent[1] = [(END_ELEMENT, self.pop()), None] + self.lastEvent = self.lastEvent[1] + + def comment(self, s): + if self.document: + node = self.document.createComment(s) + self.lastEvent[1] = [(COMMENT, node), None] + self.lastEvent = self.lastEvent[1] + else: + event = [(COMMENT, s), None] + self.pending_events.append(event) + + def processingInstruction(self, target, data): + if self.document: + node = self.document.createProcessingInstruction(target, data) + self.lastEvent[1] = [(PROCESSING_INSTRUCTION, node), None] + self.lastEvent = self.lastEvent[1] + else: + event = [(PROCESSING_INSTRUCTION, target, data), None] + self.pending_events.append(event) + + def ignorableWhitespace(self, chars): + node = self.document.createTextNode(chars) + self.lastEvent[1] = [(IGNORABLE_WHITESPACE, node), None] + self.lastEvent = self.lastEvent[1] + + def characters(self, chars): + node = self.document.createTextNode(chars) + self.lastEvent[1] = [(CHARACTERS, node), None] + self.lastEvent = self.lastEvent[1] + + def startDocument(self): + if self.documentFactory is None: + import xml.dom.minidom + self.documentFactory = xml.dom.minidom.Document.implementation + + def buildDocument(self, uri, tagname): + node = self.documentFactory.createDocument(uri, tagname, None) + self.document = node + self.lastEvent[1] = [(START_DOCUMENT, node), None] + self.lastEvent = self.lastEvent[1] + self.push(node) + for e in self.pending_events: + if e[0][0] == PROCESSING_INSTRUCTION: + _, target, data = e[0] + n = self.document.createProcessingInstruction(target, data) + e[0] = (PROCESSING_INSTRUCTION, n) + elif e[0][0] == COMMENT: + n = self.document.createComment(e[0][1]) + e[0] = (COMMENT, n) + else: + raise AssertionError("Unknown pending event ", e[0][0]) + self.lastEvent[1] = e + self.lastEvent = e + self.pending_events = None + return node.firstChild + + def endDocument(self): + self.lastEvent[1] = [(END_DOCUMENT, self.document), None] + self.pop() + + def clear(self): + self.document = None + + +class ErrorHandler: + def warning(self, exception): + print(exception) + + def error(self, exception): + raise exception + + def fatalError(self, exception): + raise exception + + +class DOMEventStream: + def __init__(self, stream, parser, bufsize): + self.stream = stream + self.parser = parser + self.bufsize = bufsize + if not hasattr(self.parser, "feed"): + self.getEvent = self._slurp + self.reset() + + def reset(self): + self.pulldom = PullDOM() + self.parser.setFeature(xml.sax.handler.feature_namespaces, 1) + self.parser.setContentHandler(self.pulldom) + + def __next__(self): + rc = self.getEvent() + if rc: + return rc + raise StopIteration + + def __iter__(self): + return self + + def __enter__(self): + return self + + def __exit__(self, *args): + self.close() + + def expandNode(self, node): + event = self.getEvent() + parents = [node] + while event: + token, cur_node = event + if cur_node is node: + return + if token != END_ELEMENT: + parents[-1].appendChild(cur_node) + if token == START_ELEMENT: + parents.append(cur_node) + elif token == END_ELEMENT: + del parents[-1] + event = self.getEvent() + + def getEvent(self): + if not self.pulldom.firstEvent[1]: + self.pulldom.lastEvent = self.pulldom.firstEvent + while not self.pulldom.firstEvent[1]: + buf = self.stream.read(self.bufsize) + if not buf: + self.parser.close() + return None + self.parser.feed(buf) + rc = self.pulldom.firstEvent[1][0] + self.pulldom.firstEvent[1] = self.pulldom.firstEvent[1][1] + return rc + + def _slurp(self): + self.parser.parse(self.stream) + self.getEvent = self._emit + return self._emit() + + def _emit(self): + rc = self.pulldom.firstEvent[1][0] + self.pulldom.firstEvent[1] = self.pulldom.firstEvent[1][1] + return rc + + def clear(self): + self.pulldom.clear() + del self.pulldom + self.parser = None + self.stream = None + + def close(self): + stream = self.stream + self.clear() + if stream is not None and hasattr(stream, "close"): + stream.close() + + +class SAX2DOM(PullDOM): + def startElementNS(self, name, tagName, attrs): + PullDOM.startElementNS(self, name, tagName, attrs) + curNode = self.elementStack[-1] + parentNode = self.elementStack[-2] + parentNode.appendChild(curNode) + + def startElement(self, name, attrs): + PullDOM.startElement(self, name, attrs) + curNode = self.elementStack[-1] + parentNode = self.elementStack[-2] + parentNode.appendChild(curNode) + + def processingInstruction(self, target, data): + PullDOM.processingInstruction(self, target, data) + node = self.lastEvent[0][1] + parentNode = self.elementStack[-1] + parentNode.appendChild(node) + + def ignorableWhitespace(self, chars): + PullDOM.ignorableWhitespace(self, chars) + node = self.lastEvent[0][1] + parentNode = self.elementStack[-1] + parentNode.appendChild(node) + + def characters(self, chars): + PullDOM.characters(self, chars) + node = self.lastEvent[0][1] + parentNode = self.elementStack[-1] + parentNode.appendChild(node) + + +default_bufsize = (2 ** 14) - 20 + + +def parse(stream_or_string, parser=None, bufsize=None): + if bufsize is None: + bufsize = default_bufsize + if isinstance(stream_or_string, str): + stream = open(stream_or_string, "rb") + else: + stream = stream_or_string + if not parser: + parser = xml.sax.make_parser() + return DOMEventStream(stream, parser, bufsize) + + +def parseString(string, parser=None): + from io import StringIO + bufsize = len(string) + buf = StringIO(string) + if not parser: + parser = xml.sax.make_parser() + return DOMEventStream(buf, parser, bufsize) diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/xml/dom/xmlbuilder.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/xml/dom/xmlbuilder.py new file mode 100644 index 00000000000..62a03b0129e --- /dev/null +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/xml/dom/xmlbuilder.py @@ -0,0 +1,137 @@ +# Copyright (c) 2001 Python Software Foundation; All Rights Reserved +# Licensed under the Python Software Foundation License Version 2; the full +# text is in maven/python-transpiler/third-party/cpython/LICENSE.txt. +# +# Derived from CPython's Lib/xml/dom/xmlbuilder.py. Changes: rewritten for the Codename One +# Python runtime, trimmed to what the transpiler supports and reorganised; +# the C accelerators and platform-specific branches are left out. +"""xml.dom.xmlbuilder: the DOM Level 3 load options and the DocumentLS +mixin minidom's Document carries.""" + +import xml.dom + +__all__ = ["DOMBuilder", "DOMEntityResolver", "DOMInputSource"] + + +class Options: + namespaces = 1 + namespace_declarations = True + validation = False + external_parameter_entities = True + external_general_entities = True + external_dtd_subset = True + validate_if_schema = False + validate = False + datatype_normalization = False + create_entity_ref_nodes = True + entities = True + whitespace_in_element_content = True + cdata_sections = True + comments = True + charset_overrides_xml_encoding = True + infoset = False + supported_mediatypes_only = False + errorHandler = None + filter = None + + +class DOMInputSource: + __slots__ = ("byteStream", "characterStream", "stringData", "encoding", "publicId", "systemId", "baseURI") + + def __init__(self): + self.byteStream = None + self.characterStream = None + self.stringData = None + self.encoding = None + self.publicId = None + self.systemId = None + self.baseURI = None + + +class DOMEntityResolver: + __slots__ = () + + def resolveEntity(self, publicId, systemId): + source = DOMInputSource() + source.publicId = publicId + source.systemId = systemId + # Entities are resolved from local files only; nothing is fetched. + source.byteStream = open(systemId, "rb") + return source + + +class DOMBuilder: + entityResolver = None + errorHandler = None + filter = None + + ACTION_REPLACE = 1 + ACTION_APPEND_AS_CHILDREN = 2 + ACTION_INSERT_AFTER = 3 + ACTION_INSERT_BEFORE = 4 + + def __init__(self): + self._options = Options() + + def parse(self, input): + options = self._options + options.filter = self.filter + options.errorHandler = self.errorHandler + fp = input.byteStream + if fp is None and input.systemId: + fp = open(input.systemId, "rb") + from xml.dom import expatbuilder + builder = expatbuilder.makeBuilder(options) + return builder.parseFile(fp) + + def parseURI(self, uri): + source = DOMInputSource() + source.systemId = uri + return self.parse(source) + + +class DocumentLS: + async_ = False + + def _get_async(self): + return False + + def _set_async(self, flag): + if flag: + raise xml.dom.NotSupportedErr("asynchronous document loading is not supported") + + def abort(self): + raise xml.dom.InvalidStateErr("haven't decided what this should do") + + def load(self, uri): + raise NotImplementedError("haven't written this yet") + + def loadXML(self, source): + raise NotImplementedError("haven't written this yet") + + def saveXML(self, snode): + if snode is None: + snode = self + elif snode.ownerDocument is not self: + raise xml.dom.WrongDocumentErr() + return snode.toxml() + + +class DOMImplementationLS: + MODE_SYNCHRONOUS = 1 + MODE_ASYNCHRONOUS = 2 + + def createDOMBuilder(self, mode, schemaType): + if schemaType is not None: + raise xml.dom.NotSupportedErr("schemaType not yet supported") + if mode == self.MODE_SYNCHRONOUS: + return DOMBuilder() + if mode == self.MODE_ASYNCHRONOUS: + raise xml.dom.NotSupportedErr("asynchronous builders are not supported") + raise ValueError("unknown value for mode") + + def createDOMWriter(self): + raise NotImplementedError("the writer interface hasn't been written yet!") + + def createDOMInputSource(self): + return DOMInputSource() diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/xml/etree/ElementPath.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/xml/etree/ElementPath.py new file mode 100644 index 00000000000..c45c7d57fea --- /dev/null +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/xml/etree/ElementPath.py @@ -0,0 +1,361 @@ +# Copyright (c) 2001 Python Software Foundation; All Rights Reserved +# Licensed under the Python Software Foundation License Version 2; the full +# text is in maven/python-transpiler/third-party/cpython/LICENSE.txt. +# +# Derived from CPython's Lib/xml/etree/ElementPath.py. Changes: rewritten for the Codename One +# Python runtime, trimmed to what the transpiler supports and reorganised; +# the C accelerators and platform-specific branches are left out. +# +# +# ElementTree +# $Id: ElementPath.py 3375 2008-02-13 08:05:08Z fredrik $ +# +# limited xpath support for element trees +# +# history: +# 2003-05-23 fl created +# 2003-05-28 fl added support for // etc +# 2003-08-27 fl fixed parsing of periods in element names +# 2007-09-10 fl new selection engine +# 2007-09-12 fl fixed parent selector +# 2007-09-13 fl added iterfind; changed findall to return a list +# 2007-11-30 fl added namespaces support +# 2009-10-30 fl added child element value filter +# +# Copyright (c) 2003-2009 by Fredrik Lundh. All rights reserved. +# +# fredrik@pythonware.com +# http://www.pythonware.com +# +# -------------------------------------------------------------------- +# The ElementTree toolkit is +# +# Copyright (c) 1999-2009 by Fredrik Lundh +# +# By obtaining, using, and/or copying this software and/or its +# associated documentation, you agree that you have read, understood, +# and will comply with the following terms and conditions: +# +# Permission to use, copy, modify, and distribute this software and +# its associated documentation for any purpose and without fee is +# hereby granted, provided that the above copyright notice appears in +# all copies, and that both that copyright notice and this permission +# notice appear in supporting documentation, and that the name of +# Secret Labs AB or the author not be used in advertising or publicity +# pertaining to distribution of the software without specific, written +# prior permission. +# +# SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD +# TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT- +# ABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR +# BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY +# DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + +"""xml.etree.ElementPath: the XPath subset of Element.find and friends. + +Steps are tags (with {uri}, {*}, {} and prefix:tag forms), *, ., .., //, +and the predicates [@a], [@a='v'], [@a!='v'], [tag], [tag='text'], +[tag!='text'], [.='text'], [.!='text'], [n], [last()] and [last()-n]. +""" + +import re as _re + +_TOKENS = _re.compile(r"('[^']*'|\"[^\"]*\"|::|//?|\.\.|\(\)|!=|[/.*:\[\]\(\)@=])|" + r"((?:\{[^}]+\})?[^/\[\]\(\)@!=\s]+)|\s+") + + +def xpath_tokenizer(pattern, namespaces=None): + default = namespaces.get("") if namespaces else None + in_attribute = False + for m in _TOKENS.finditer(pattern): + op = m.group(1) or "" + tag = m.group(2) or "" + if tag and tag[0] != "{": + if ":" in tag: + prefix, local = tag.split(":", 1) + try: + if not namespaces: + raise KeyError(prefix) + yield op, "{%s}%s" % (namespaces[prefix], local) + except KeyError: + raise SyntaxError("prefix %r not found in prefix map" % prefix) from None + elif default and not in_attribute: + yield op, "{%s}%s" % (default, tag) + else: + yield op, tag + in_attribute = False + else: + yield op, tag + in_attribute = op == "@" + + +def _matcher(tag): + """A test for one element's tag: exact, or one of the {*}/{}/{uri}* + wildcards.""" + if tag == "{*}*": + return lambda t: isinstance(t, str) + if tag == "{}*": + return lambda t: isinstance(t, str) and t[:1] != "{" + if tag[:3] == "{*}": + local = tag[3:] + suffix = "}" + local + return lambda t: isinstance(t, str) and (t == local or t.endswith(suffix)) + if tag[-2:] == "}*": + ns = tag[:-1] + return lambda t: isinstance(t, str) and t.startswith(ns) + if tag[:2] == "{}": + local = tag[2:] + return lambda t: t == local + return None + + +def _parent_map(context): + pm = context.parent_map + if pm is None: + pm = {} + for p in context.root.iter(): + for c in p: + pm[c] = p + context.parent_map = pm + return pm + + +def _child(nxt, token): + tag = token[1] + test = _matcher(tag) + if test is not None: + def select(context, result): + for elem in result: + for e in elem: + if test(e.tag): + yield e + return select + + def select(context, result): + for elem in result: + for e in elem: + if e.tag == tag: + yield e + return select + + +def _star(nxt, token): + def select(context, result): + for elem in result: + yield from elem + return select + + +def _self(nxt, token): + def select(context, result): + yield from result + return select + + +def _descendant(nxt, token): + try: + token = nxt() + except StopIteration: + return None + if token[0] == "*": + tag = "*" + elif not token[0]: + tag = token[1] + else: + raise SyntaxError("invalid descendant") + test = _matcher(tag) + if test is not None: + def select(context, result): + for elem in result: + for e in elem.iter(): + if e is not elem and test(e.tag): + yield e + return select + + def select(context, result): + for elem in result: + for e in elem.iter(tag): + if e is not elem: + yield e + return select + + +def _parent(nxt, token): + def select(context, result): + pm = _parent_map(context) + seen = set() + for elem in result: + p = pm.get(elem) + if p is not None and id(p) not in seen: + seen.add(id(p)) + yield p + return select + + +def _predicate(nxt, token): + signature = [] + values = [] + while True: + try: + token = nxt() + except StopIteration: + return None + if token[0] == "]": + break + if token == ("", ""): + continue + if token[0] and token[0][:1] in "'\"": + token = ("'", token[0][1:-1]) + signature.append(token[0] or "-") + values.append(token[1]) + sig = "".join(signature) + if sig == "@-": + key = values[1] + + def select(context, result): + for elem in result: + if elem.get(key) is not None: + yield elem + return select + if sig == "@-='" or sig == "@-!='": + key = values[1] + value = values[-1] + equal = sig == "@-='" + + def select(context, result): + for elem in result: + if (elem.get(key) == value) == equal: + yield elem + return select + if sig == "-" and not _re.match(r"\-?\d+$", values[0]): + tag = values[0] + + def select(context, result): + for elem in result: + if elem.find(tag) is not None: + yield elem + return select + if sig in ("-='", "-!='", ".='", ".!='"): + tag = values[0] + value = values[-1] + equal = "!" not in sig + if sig[0] == ".": + def select(context, result): + for elem in result: + if ("".join(elem.itertext()) == value) == equal: + yield elem + return select + + def select(context, result): + for elem in result: + for e in elem.findall(tag): + if ("".join(e.itertext()) == value) == equal: + yield elem + break + return select + if sig in ("-", "-()", "-()-"): + if sig == "-": + index = int(values[0]) - 1 + if index < 0: + raise SyntaxError("XPath position >= 1 expected") + else: + if values[0] != "last": + raise SyntaxError("unsupported function") + if sig == "-()-": + try: + index = int(values[2]) - 1 + except ValueError: + raise SyntaxError("unsupported expression") + if index > -2: + raise SyntaxError("XPath offset from last() must be negative") + else: + index = -1 + + def select(context, result): + pm = _parent_map(context) + for elem in result: + p = pm.get(elem) + if p is None: + continue + elems = list(p.findall(elem.tag)) + try: + if elems[index] is elem: + yield elem + except IndexError: + pass + return select + raise SyntaxError("invalid predicate") + + +_OPS = {"": _child, "*": _star, ".": _self, "..": _parent, "//": _descendant, "[": _predicate} + +_cache = {} + + +class _SelectorContext: + def __init__(self, root): + self.root = root + self.parent_map = None + + +def _compile(path, namespaces): + key = (path, None if namespaces is None else tuple(sorted(namespaces.items()))) + sel = _cache.get(key) + if sel is not None: + return sel + if len(_cache) > 100: + _cache.clear() + if path[:1] == "/": + raise SyntaxError("cannot use absolute path on element") + it = iter(xpath_tokenizer(path, namespaces)) + + def nxt(): + return next(it) + + sel = [] + try: + token = nxt() + except StopIteration: + raise SyntaxError("invalid path") + while True: + op = _OPS.get(token[0]) + if op is None: + raise SyntaxError("invalid path") + s = op(nxt, token) + if s is None: + raise SyntaxError("invalid path") + sel.append(s) + try: + token = nxt() + if token[0] == "/": + token = nxt() + except StopIteration: + break + _cache[key] = sel + return sel + + +def iterfind(elem, path, namespaces=None): + if path[-1:] == "/": + path = path + "*" + selector = _compile(path, namespaces) + result = iter([elem]) + context = _SelectorContext(elem) + for s in selector: + result = s(context, result) + return result + + +def find(elem, path, namespaces=None): + return next(iterfind(elem, path, namespaces), None) + + +def findall(elem, path, namespaces=None): + return list(iterfind(elem, path, namespaces)) + + +def findtext(elem, path, default=None, namespaces=None): + e = find(elem, path, namespaces) + if e is None: + return default + return e.text or "" diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/xml/etree/ElementTree.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/xml/etree/ElementTree.py new file mode 100644 index 00000000000..0a1374a4d2a --- /dev/null +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/xml/etree/ElementTree.py @@ -0,0 +1,1073 @@ +# Copyright (c) 2001 Python Software Foundation; All Rights Reserved +# Licensed under the Python Software Foundation License Version 2; the full +# text is in maven/python-transpiler/third-party/cpython/LICENSE.txt. +# +# Derived from CPython's Lib/xml/etree/ElementTree.py. Changes: rewritten for the Codename One +# Python runtime, trimmed to what the transpiler supports and reorganised; +# the C accelerators and platform-specific branches are left out. +# +#--------------------------------------------------------------------- +# Licensed to PSF under a Contributor Agreement. +# See https://www.python.org/psf/license for licensing details. +# +# ElementTree +# Copyright (c) 1999-2008 by Fredrik Lundh. All rights reserved. +# +# fredrik@pythonware.com +# http://www.pythonware.com +# -------------------------------------------------------------------- +# The ElementTree toolkit is +# +# Copyright (c) 1999-2008 by Fredrik Lundh +# +# By obtaining, using, and/or copying this software and/or its +# associated documentation, you agree that you have read, understood, +# and will comply with the following terms and conditions: +# +# Permission to use, copy, modify, and distribute this software and +# its associated documentation for any purpose and without fee is +# hereby granted, provided that the above copyright notice appears in +# all copies, and that both that copyright notice and this permission +# notice appear in supporting documentation, and that the name of +# Secret Labs AB or the author not be used in advertising or publicity +# pertaining to distribution of the software without specific, written +# prior permission. +# +# SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD +# TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT- +# ABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR +# BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY + +"""xml.etree.ElementTree: the element tree, its parser and serializer. + +The tree, TreeBuilder, XMLParser (over xml.parsers.expat), XMLPullParser, +iterparse and the "xml", "html" and "text" serializers, with CPython's +output byte for byte: namespace prefixes, attribute order and escaping. +canonicalize() and C14NWriterTarget (C14N 2.0) are not provided. +""" + +import collections as _collections +import io as _io +import re as _re +import sys as _sys +import warnings as _warnings + +from xml.etree import ElementPath +from xml.parsers import expat as _expat + +import _cn1xml + +_NOT_UTF8_STARTS = (b"\xff\xfe", b"\xfe\xff", b"<\x00", b"\x00<") + +__all__ = [ + "Comment", "dump", "Element", "ElementTree", "fromstring", "fromstringlist", "indent", "iselement", + "iterparse", "parse", "ParseError", "PI", "ProcessingInstruction", "QName", "SubElement", "tostring", + "tostringlist", "TreeBuilder", "VERSION", "XML", "XMLID", "XMLParser", "XMLPullParser", + "register_namespace", +] + +VERSION = "1.3.0" + + +class ParseError(SyntaxError): + pass + + +def iselement(element): + return hasattr(element, "tag") + + +class Element: + tag = None + attrib = None + text = None + tail = None + + def __init__(self, tag, attrib={}, **extra): + if not isinstance(attrib, dict): + raise TypeError("Element() argument 2 must be dict, not %s" % (attrib.__class__.__name__,)) + self.tag = tag + self.attrib = dict(attrib) + if extra: + self.attrib.update(extra) + self._children = [] + + def __repr__(self): + return "<%s %r at %#x>" % (self.__class__.__name__, self.tag, id(self)) + + def makeelement(self, tag, attrib): + return self.__class__(tag, attrib) + + def __copy__(self): + elem = self.makeelement(self.tag, self.attrib) + elem.text = self.text + elem.tail = self.tail + elem[:] = self + return elem + + def copy(self): + _warnings.warn("elem.copy() is deprecated. Use copy.copy(elem) instead.", DeprecationWarning, stacklevel=2) + return self.__copy__() + + def __deepcopy__(self, memo): + import copy as _copy + elem = self.makeelement(self.tag, _copy.deepcopy(self.attrib, memo)) + elem.text = self.text + elem.tail = self.tail + for child in self._children: + elem._children.append(_copy.deepcopy(child, memo)) + return elem + + def __len__(self): + return len(self._children) + + def __bool__(self): + _warnings.warn("Testing an element's truth value will always return True in future versions. " + "Use specific 'len(elem)' or 'elem is not None' test instead.", + DeprecationWarning, stacklevel=2) + return len(self._children) != 0 + + def __getitem__(self, index): + return self._children[index] + + def __setitem__(self, index, element): + if isinstance(index, slice): + for elt in element: + self._assert_is_element(elt) + else: + self._assert_is_element(element) + self._children[index] = element + + def __delitem__(self, index): + del self._children[index] + + def __iter__(self): + return iter(self._children) + + def append(self, subelement): + if not isinstance(subelement, Element): + raise TypeError("append() argument 1 must be xml.etree.ElementTree.Element, not %s" + % type(subelement).__name__) + self._children.append(subelement) + + def extend(self, elements): + for element in elements: + self._assert_is_element(element) + self._children.append(element) + + def insert(self, index, subelement): + if not isinstance(subelement, Element): + raise TypeError("insert() argument 2 must be xml.etree.ElementTree.Element, not %s" + % type(subelement).__name__) + self._children.insert(index, subelement) + + def _assert_is_element(self, e): + if not isinstance(e, Element): + raise TypeError('expected an Element, not "%s"' % type(e).__name__) + + def remove(self, subelement): + for i, c in enumerate(self._children): + if c is subelement: + del self._children[i] + return + raise ValueError("Element.remove(x): element not found") + + # A path that is one tag, as most are, matches children directly, in + # Java, as the C accelerator does in C; _cn1xml answers NotImplemented + # for anything else, which goes to ElementPath. + def find(self, path, namespaces=None): + if namespaces is None: + r = _cn1xml.find(self, path) + if r is not NotImplemented: + return r + return ElementPath.find(self, path, namespaces) + + def findtext(self, path, default=None, namespaces=None): + if namespaces is None: + r = _cn1xml.find(self, path) + if r is not NotImplemented: + return default if r is None else r.text or "" + return ElementPath.findtext(self, path, default, namespaces) + + def findall(self, path, namespaces=None): + if namespaces is None: + r = _cn1xml.findall(self, path) + if r is not NotImplemented: + return r + return ElementPath.findall(self, path, namespaces) + + def iterfind(self, path, namespaces=None): + return ElementPath.iterfind(self, path, namespaces) + + def clear(self): + self.attrib.clear() + self._children = [] + self.text = self.tail = None + + def get(self, key, default=None): + return self.attrib.get(key, default) + + def set(self, key, value): + self.attrib[key] = value + + def keys(self): + return list(self.attrib.keys()) + + def items(self): + return list(self.attrib.items()) + + # A walk over a stack of (children, next index) in Java, as CPython's C + # accelerator walks in C (_cn1xml.ElementIter). + def iter(self, tag=None): + if tag == "*": + tag = None + return _cn1xml.iter(self, tag) + + def itertext(self): + tag = self.tag + if not isinstance(tag, str) and tag is not None: + return + t = self.text + if t: + yield t + for e in self: + yield from e.itertext() + t = e.tail + if t: + yield t + + +# Element's own __init__: the fast build below makes the elements of a class +# that still has it as that method would, without calling it. +_ELEMENT_INIT = Element.__init__ + + +def SubElement(parent, tag, attrib={}, **extra): + if not isinstance(parent, Element): + raise TypeError("SubElement() argument 1 must be xml.etree.ElementTree.Element, not %s" + % type(parent).__name__) + attrib = {**attrib, **extra} + element = parent.makeelement(tag, attrib) + parent.append(element) + return element + + +def Comment(text=None): + element = Element(Comment) + element.text = text + return element + + +def ProcessingInstruction(target, text=None): + element = Element(ProcessingInstruction) + element.text = target + if text: + element.text = element.text + " " + text + return element + + +PI = ProcessingInstruction + + +class QName: + def __init__(self, text_or_uri, tag=None): + if tag: + text_or_uri = "{%s}%s" % (text_or_uri, tag) + self.text = text_or_uri + + def __str__(self): + return self.text + + def __repr__(self): + return "<%s %r>" % (self.__class__.__name__, self.text) + + def __hash__(self): + return hash(self.text) + + def _key(self, other): + return other.text if isinstance(other, QName) else other + + def __le__(self, other): + return self.text <= self._key(other) + + def __lt__(self, other): + return self.text < self._key(other) + + def __ge__(self, other): + return self.text >= self._key(other) + + def __gt__(self, other): + return self.text > self._key(other) + + def __eq__(self, other): + return self.text == self._key(other) + + +class ElementTree: + def __init__(self, element=None, file=None): + if element is not None and not iselement(element): + raise TypeError("expected an Element, not %s" % type(element).__name__) + self._root = element + if file: + self.parse(file) + + def getroot(self): + return self._root + + def _setroot(self, element): + if not iselement(element): + raise TypeError("expected an Element, not %s" % type(element).__name__) + self._root = element + + def parse(self, source, parser=None): + close_source = False + if not hasattr(source, "read"): + source = open(source, "rb") + close_source = True + try: + if parser is None: + parser = XMLParser() + while True: + data = source.read(65536) + if not data: + break + parser.feed(data) + self._root = parser.close() + return self._root + finally: + if close_source: + source.close() + + def iter(self, tag=None): + return self._root.iter(tag) + + def _rel(self, path): + if path[:1] == "/": + path = "." + path + _warnings.warn("This search is broken in 1.3 and earlier, and will be fixed in a future version. " + "If you rely on the current behaviour, change it to %r" % path, + FutureWarning, stacklevel=3) + return path + + def find(self, path, namespaces=None): + return self._root.find(self._rel(path), namespaces) + + def findtext(self, path, default=None, namespaces=None): + return self._root.findtext(self._rel(path), default, namespaces) + + def findall(self, path, namespaces=None): + return self._root.findall(self._rel(path), namespaces) + + def iterfind(self, path, namespaces=None): + return self._root.iterfind(self._rel(path), namespaces) + + def write(self, file_or_filename, encoding=None, xml_declaration=None, default_namespace=None, method=None, *, + short_empty_elements=True): + if not method: + method = "xml" + elif method not in _SERIALIZERS: + raise ValueError("unknown method %r" % method) + if not encoding: + encoding = "utf-8" if method == "c14n" else "us-ascii" + parts = [] + write = parts.append + enc_lower = encoding.lower() + if method == "xml" and (xml_declaration or (xml_declaration is None and encoding.lower() != "unicode" + and enc_lower not in ("utf-8", "us-ascii"))): + declared = encoding + if enc_lower == "unicode": + declared = "UTF-8" + write("\n" % (declared,)) + if method == "text": + _serialize_text(write, self._root) + else: + qnames, namespaces = _namespaces(self._root, default_namespace) + _SERIALIZERS[method](write, self._root, qnames, namespaces, short_empty_elements=short_empty_elements) + text = "".join(parts) + if enc_lower == "unicode": + data = text + else: + data = _encode(text, encoding) + if hasattr(file_or_filename, "write"): + file_or_filename.write(data) + else: + mode = "w" if enc_lower == "unicode" else "wb" + with open(file_or_filename, mode) as f: + f.write(data) + + def write_c14n(self, file): + raise NotImplementedError("C14N serialization is not supported") + + +def _charrefs(text, limit): + out = [] + start = 0 + for i, ch in enumerate(text): + if ord(ch) > limit: + out.append(text[start:i]) + out.append("&#%d;" % ord(ch)) + start = i + 1 + if not out: + return text + out.append(text[start:]) + return "".join(out) + + +def _encode(text, encoding): + e = encoding.lower().replace("_", "-") + if e in ("us-ascii", "ascii"): + return _charrefs(text, 0x7F).encode("ascii") + if e in ("iso-8859-1", "latin-1", "latin1", "iso8859-1"): + return _charrefs(text, 0xFF).encode("latin-1") + return text.encode(encoding) + + +_namespace_map = { + "http://www.w3.org/XML/1998/namespace": "xml", + "http://www.w3.org/1999/xhtml": "html", + "http://www.w3.org/1999/02/22-rdf-syntax-ns#": "rdf", + "http://schemas.xmlsoap.org/wsdl/": "wsdl", + "http://www.w3.org/2001/XMLSchema": "xs", + "http://www.w3.org/2001/XMLSchema-instance": "xsi", + "http://purl.org/dc/elements/1.1/": "dc", +} + + +def register_namespace(prefix, uri): + if _re.match(r"ns\d+$", prefix): + raise ValueError("Prefix format reserved for internal use") + for k, v in list(_namespace_map.items()): + if k == uri or v == prefix: + del _namespace_map[k] + _namespace_map[uri] = prefix + + +def _raise_serialization_error(text): + raise TypeError("cannot serialize %r (type %s)" % (text, type(text).__name__)) + + +def _namespaces(elem, default_namespace=None): + qnames = {None: None} + namespaces = {} + if default_namespace: + namespaces[default_namespace] = "" + + def add_qname(qname): + try: + if qname[:1] == "{": + uri, tag = qname[1:].rsplit("}", 1) + prefix = namespaces.get(uri) + if prefix is None: + prefix = _namespace_map.get(uri) + if prefix is None: + prefix = "ns%d" % len(namespaces) + if prefix != "xml": + namespaces[uri] = prefix + if prefix: + qnames[qname] = "%s:%s" % (prefix, tag) + else: + qnames[qname] = tag + else: + if default_namespace: + raise ValueError("cannot use non-qualified names with default_namespace option") + qnames[qname] = qname + except TypeError: + _raise_serialization_error(qname) + + for e in elem.iter(): + tag = e.tag + if isinstance(tag, QName): + if tag.text not in qnames: + add_qname(tag.text) + elif isinstance(tag, str): + if tag not in qnames: + add_qname(tag) + elif tag is not None and tag is not Comment and tag is not PI: + _raise_serialization_error(tag) + for key, value in e.items(): + if isinstance(key, QName): + key = key.text + if key not in qnames: + add_qname(key) + if isinstance(value, QName) and value.text not in qnames: + add_qname(value.text) + text = e.text + if isinstance(text, QName) and text.text not in qnames: + add_qname(text.text) + return qnames, namespaces + + +def _serialize_xml(write, elem, qnames, namespaces, short_empty_elements, **kwargs): + tag = elem.tag + text = elem.text + if tag is Comment: + write("" % text) + elif tag is ProcessingInstruction: + write("" % text) + else: + tag = qnames[tag.text if isinstance(tag, QName) else tag] + if tag is None: + if text: + write(_escape_cdata(text)) + for e in elem: + _serialize_xml(write, e, qnames, None, short_empty_elements=short_empty_elements) + else: + write("<" + tag) + items = list(elem.items()) + if items or namespaces: + if namespaces: + for v, k in sorted(namespaces.items(), key=lambda x: x[1]): + if k: + k = ":" + k + write(' xmlns%s="%s"' % (k, _escape_attrib(v))) + for k, v in items: + if isinstance(k, QName): + k = k.text + if isinstance(v, QName): + v = qnames[v.text] + else: + v = _escape_attrib(v) + write(' %s="%s"' % (qnames[k], v)) + if text or len(elem) or not short_empty_elements: + write(">") + if text: + write(_escape_cdata(text)) + for e in elem: + _serialize_xml(write, e, qnames, None, short_empty_elements=short_empty_elements) + write("") + else: + write(" />") + if elem.tail: + write(_escape_cdata(elem.tail)) + + +HTML_EMPTY = {"area", "base", "basefont", "br", "col", "embed", "frame", "hr", "img", "input", "isindex", "link", + "meta", "param", "source", "track", "wbr"} + + +def _serialize_html(write, elem, qnames, namespaces, **kwargs): + tag = elem.tag + text = elem.text + if tag is Comment: + write("" % _escape_cdata(text)) + elif tag is ProcessingInstruction: + write("" % _escape_cdata(text)) + else: + tag = qnames[tag.text if isinstance(tag, QName) else tag] + if tag is None: + if text: + write(_escape_cdata(text)) + for e in elem: + _serialize_html(write, e, qnames, None) + else: + write("<" + tag) + items = list(elem.items()) + if items or namespaces: + if namespaces: + for v, k in sorted(namespaces.items(), key=lambda x: x[1]): + if k: + k = ":" + k + write(' xmlns%s="%s"' % (k, _escape_attrib_html(v))) + for k, v in items: + if isinstance(k, QName): + k = k.text + if isinstance(v, QName): + v = qnames[v.text] + else: + v = _escape_attrib_html(v) + write(' %s="%s"' % (qnames[k], v)) + write(">") + ltag = tag.lower() + if text: + if ltag == "script" or ltag == "style": + write(text) + else: + write(_escape_cdata(text)) + for e in elem: + _serialize_html(write, e, qnames, None) + if ltag not in HTML_EMPTY: + write("") + if elem.tail: + write(_escape_cdata(elem.tail)) + + +def _serialize_text(write, elem): + for part in elem.itertext(): + write(part) + if elem.tail: + write(elem.tail) + + +_SERIALIZERS = {"xml": _serialize_xml, "html": _serialize_html, "text": _serialize_text} + + +def _escape_cdata(text): + try: + if "&" in text: + text = text.replace("&", "&") + if "<" in text: + text = text.replace("<", "<") + if ">" in text: + text = text.replace(">", ">") + return text + except (TypeError, AttributeError): + _raise_serialization_error(text) + + +def _escape_attrib(text): + try: + if "&" in text: + text = text.replace("&", "&") + if "<" in text: + text = text.replace("<", "<") + if ">" in text: + text = text.replace(">", ">") + if '"' in text: + text = text.replace('"', """) + if "\r" in text: + text = text.replace("\r", " ") + if "\n" in text: + text = text.replace("\n", " ") + if "\t" in text: + text = text.replace("\t", " ") + return text + except (TypeError, AttributeError): + _raise_serialization_error(text) + + +def _escape_attrib_html(text): + try: + if "&" in text: + text = text.replace("&", "&") + if ">" in text: + text = text.replace(">", ">") + if '"' in text: + text = text.replace('"', """) + return text + except (TypeError, AttributeError): + _raise_serialization_error(text) + + +def tostring(element, encoding=None, method=None, *, xml_declaration=None, default_namespace=None, + short_empty_elements=True): + stream = _io.StringIO() if encoding == "unicode" else _io.BytesIO() + ElementTree(element).write(stream, encoding, xml_declaration=xml_declaration, + default_namespace=default_namespace, method=method, + short_empty_elements=short_empty_elements) + return stream.getvalue() + + +def tostringlist(element, encoding=None, method=None, *, xml_declaration=None, default_namespace=None, + short_empty_elements=True): + return [tostring(element, encoding, method, xml_declaration=xml_declaration, + default_namespace=default_namespace, short_empty_elements=short_empty_elements)] + + +def dump(elem): + if not isinstance(elem, ElementTree): + elem = ElementTree(elem) + elem.write(_sys.stdout, encoding="unicode") + tail = elem.getroot().tail + if not tail or tail[-1] != "\n": + _sys.stdout.write("\n") + + +def indent(tree, space=" ", level=0): + if isinstance(tree, ElementTree): + tree = tree.getroot() + if level < 0: + raise ValueError(f"Initial indentation level must be >= 0, got {level}") + if not len(tree): + return + indentations = ["\n" + level * space] + + def _indent_children(elem, level): + child_level = level + 1 + if child_level < len(indentations): + child_indentation = indentations[child_level] + else: + child_indentation = indentations[level] + space + indentations.append(child_indentation) + if not elem.text or not elem.text.strip(): + elem.text = child_indentation + child = None + for child in elem: + if len(child): + _indent_children(child, child_level) + if not child.tail or not child.tail.strip(): + child.tail = child_indentation + if not child.tail.strip(): + child.tail = indentations[level] + + _indent_children(tree, 0) + + +def parse(source, parser=None): + tree = ElementTree() + tree.parse(source, parser) + return tree + + +class _IterParseIterator: + def __init__(self, source, pullparser, close_source): + self._source = source + self._pull = pullparser + self._close_source = close_source + self._done = False + self.root = None + + def __iter__(self): + return self + + def __next__(self): + while True: + q = self._pull._events_queue + if q: + ev = q.popleft() + if isinstance(ev, Exception): + self.close() + raise ev + return ev + if self._done: + raise StopIteration + try: + data = self._source.read(16 * 1024) + if data: + self._pull.feed(data) + else: + self.root = self._pull._close_and_return_root() + self._done = True + self.close() + except BaseException: + self.close() + raise + + def close(self): + if self._close_source: + self._close_source = False + self._source.close() + + +def iterparse(source, events=None, parser=None): + pullparser = XMLPullParser(events=events, _parser=parser) + close_source = False + if not hasattr(source, "read"): + source = open(source, "rb") + close_source = True + return _IterParseIterator(source, pullparser, close_source) + + +class XMLPullParser: + def __init__(self, events=None, *, _parser=None): + self._events_queue = _collections.deque() + self._parser = _parser or XMLParser(target=TreeBuilder()) + if events is None: + events = ("end",) + self._parser._setevents(self._events_queue, events) + + def feed(self, data): + if self._parser is None: + raise ValueError("feed() called after end of stream") + if data: + try: + self._parser.feed(data) + except SyntaxError as exc: + self._events_queue.append(exc) + + def _close_and_return_root(self): + root = self._parser.close() + self._parser = None + return root + + def close(self): + self._close_and_return_root() + + def read_events(self): + events = self._events_queue + while events: + event = events.popleft() + if isinstance(event, Exception): + raise event + yield event + + def flush(self): + if self._parser is None: + raise ValueError("flush() called after end of stream") + self._parser.flush() + + +def XML(text, parser=None): + if not parser: + # The default parser and builder in one Java pass, as CPython's C + # accelerator does; None for any document it does not take, which + # the parser below then handles (and reports) as before. + src = None + if isinstance(text, str): + src = text + elif isinstance(text, (bytes, bytearray)) and not text.startswith(_NOT_UTF8_STARTS): + try: + src = bytes(text).decode("utf-8") + except UnicodeDecodeError: + src = None + if src is not None: + root = _cn1xml.build(src, Element, not isinstance(text, str), _ELEMENT_INIT) + if root is not None: + return root + parser = XMLParser(target=TreeBuilder()) + parser.feed(text) + return parser.close() + + +fromstring = XML + + +def XMLID(text, parser=None): + if not parser: + parser = XMLParser(target=TreeBuilder()) + parser.feed(text) + tree = parser.close() + ids = {} + for elem in tree.iter(): + i = elem.get("id") + if i: + ids[i] = elem + return tree, ids + + +def fromstringlist(sequence, parser=None): + if not parser: + parser = XMLParser(target=TreeBuilder()) + for text in sequence: + parser.feed(text) + return parser.close() + + +class TreeBuilder: + def __init__(self, element_factory=None, *, comment_factory=None, pi_factory=None, insert_comments=False, + insert_pis=False): + self._data = [] + self._elem = [] + self._last = None + self._root = None + self._tail = None + if comment_factory is None: + comment_factory = Comment + self._comment_factory = comment_factory + self.insert_comments = insert_comments + if pi_factory is None: + pi_factory = ProcessingInstruction + self._pi_factory = pi_factory + self.insert_pis = insert_pis + if element_factory is None: + element_factory = Element + self._factory = element_factory + + def close(self): + assert len(self._elem) == 0, "missing end tags" + assert self._root is not None, "missing toplevel element" + return self._root + + def _flush(self): + if self._data: + if self._last is not None: + text = "".join(self._data) + if self._tail: + assert self._last.tail is None, "internal error (tail)" + self._last.tail = text + else: + assert self._last.text is None, "internal error (text)" + self._last.text = text + self._data = [] + + def data(self, data): + self._data.append(data) + + def start(self, tag, attrs): + self._flush() + self._last = elem = self._factory(tag, attrs) + if self._elem: + self._elem[-1].append(elem) + elif self._root is None: + self._root = elem + self._elem.append(elem) + self._tail = 0 + return elem + + def end(self, tag): + self._flush() + self._last = self._elem.pop() + assert self._last.tag == tag, "end tag mismatch (expected %s, got %s)" % (self._last.tag, tag) + self._tail = 1 + return self._last + + def comment(self, text): + return self._handle_single(self._comment_factory, self.insert_comments, text) + + def pi(self, target, text=None): + return self._handle_single(self._pi_factory, self.insert_pis, target, text) + + def _handle_single(self, factory, insert, *args): + elem = factory(*args) + if insert: + self._flush() + self._last = elem + if self._elem: + self._elem[-1].append(elem) + self._tail = 1 + return elem + + +class XMLParser: + def __init__(self, *, target=None, encoding=None): + parser = _expat.ParserCreate(encoding, "}") + if target is None: + target = TreeBuilder() + self.parser = self._parser = parser + self.target = self._target = target + self._error = _expat.error + self._names = {} + parser.DefaultHandlerExpand = self._default + if hasattr(target, "start"): + parser.StartElementHandler = self._start + if hasattr(target, "end"): + parser.EndElementHandler = self._end + if hasattr(target, "start_ns"): + parser.StartNamespaceDeclHandler = self._start_ns + if hasattr(target, "end_ns"): + parser.EndNamespaceDeclHandler = self._end_ns + if hasattr(target, "data"): + parser.CharacterDataHandler = target.data + if hasattr(target, "comment"): + parser.CommentHandler = target.comment + if hasattr(target, "pi"): + parser.ProcessingInstructionHandler = target.pi + parser.SkippedEntityHandler = self._skipped + parser.buffer_text = 1 + parser.ordered_attributes = 1 + self._doctype = None + self.entity = {} + self.version = "Expat %d.%d.%d" % _expat.version_info + + def _setevents(self, events_queue, events_to_report): + parser = self._parser + append = events_queue.append + for event_name in events_to_report: + if event_name == "start": + parser.ordered_attributes = 1 + + def handler(tag, attrib_in, event=event_name, append=append, start=self._start): + append((event, start(tag, attrib_in))) + parser.StartElementHandler = handler + elif event_name == "end": + def handler(tag, event=event_name, append=append, end=self._end): + append((event, end(tag))) + parser.EndElementHandler = handler + elif event_name == "start-ns": + if hasattr(self.target, "start_ns"): + def handler(prefix, uri, event=event_name, append=append, start_ns=self._start_ns): + append((event, start_ns(prefix, uri))) + else: + def handler(prefix, uri, event=event_name, append=append): + append((event, (prefix or "", uri or ""))) + parser.StartNamespaceDeclHandler = handler + elif event_name == "end-ns": + if hasattr(self.target, "end_ns"): + def handler(prefix, event=event_name, append=append, end_ns=self._end_ns): + append((event, end_ns(prefix))) + else: + def handler(prefix, event=event_name, append=append): + append((event, None)) + parser.EndNamespaceDeclHandler = handler + elif event_name == "comment": + def handler(text, event=event_name, append=append, self=self): + append((event, self.target.comment(text))) + parser.CommentHandler = handler + elif event_name == "pi": + def handler(pi_target, data, event=event_name, append=append, self=self): + append((event, self.target.pi(pi_target, data))) + parser.ProcessingInstructionHandler = handler + else: + raise ValueError("unknown event %r" % event_name) + + def _raiseerror(self, value): + err = ParseError(value) + err.code = value.code + err.position = value.lineno, value.offset + raise err + + def _fixname(self, key): + try: + name = self._names[key] + except KeyError: + name = key + if "}" in name: + name = "{" + name + self._names[key] = name + return name + + def _start_ns(self, prefix, uri): + return self.target.start_ns(prefix or "", uri or "") + + def _end_ns(self, prefix): + return self.target.end_ns(prefix or "") + + def _start(self, tag, attr_list): + fixname = self._fixname + tag = fixname(tag) + attrib = {} + if attr_list: + for i in range(0, len(attr_list), 2): + attrib[fixname(attr_list[i])] = attr_list[i + 1] + return self.target.start(tag, attrib) + + def _end(self, tag): + return self.target.end(self._fixname(tag)) + + def _default(self, text): + pass + + def _skipped(self, name, is_parameter_entity): + # An entity the document's DTD may declare but this parser cannot + # read: answered from self.entity, as ElementTree's default handler + # does. + value = self.entity.get(name) + if value is not None: + if hasattr(self.target, "data"): + self.target.data(value) + return + p = self.parser + err = _expat.error("undefined entity &%s;: line %d, column %d" + % (name, p.CurrentLineNumber, p.CurrentColumnNumber)) + err.code = 11 + err.lineno = p.CurrentLineNumber + err.offset = p.CurrentColumnNumber + raise err + + def feed(self, data): + try: + self.parser.Parse(data, False) + except self._error as v: + self._raiseerror(v) + + def close(self): + try: + self.parser.Parse(b"", True) + except self._error as v: + self._raiseerror(v) + try: + close_handler = self.target.close + except AttributeError: + pass + else: + return close_handler() + finally: + # None rather than del: a closed layout keeps the module typed, + # and a parser used after close still raises AttributeError. + self.parser = self._parser = None + self.target = self._target = None + + def flush(self): + try: + self.parser.Parse(b"", False) + except self._error as v: + self._raiseerror(v) diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/xml/etree/__init__.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/xml/etree/__init__.py new file mode 100644 index 00000000000..56bbcce6101 --- /dev/null +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/xml/etree/__init__.py @@ -0,0 +1,4 @@ +# Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. +# Licensed under the GNU General Public License version 2 with the Classpath +# exception, as the rest of the Codename One Python runtime. +"""xml.etree: the ElementTree API.""" diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/xml/parsers/__init__.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/xml/parsers/__init__.py new file mode 100644 index 00000000000..2e5971ea42e --- /dev/null +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/xml/parsers/__init__.py @@ -0,0 +1,4 @@ +# Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. +# Licensed under the GNU General Public License version 2 with the Classpath +# exception, as the rest of the Codename One Python runtime. +"""xml.parsers: the expat-compatible parser.""" diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/xml/parsers/expat/__init__.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/xml/parsers/expat/__init__.py new file mode 100644 index 00000000000..3c0240df498 --- /dev/null +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/xml/parsers/expat/__init__.py @@ -0,0 +1,1176 @@ +# Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. +# Licensed under the GNU General Public License version 2 with the Classpath +# exception, as the rest of the Codename One Python runtime. +"""xml.parsers.expat: a non-validating XML parser with expat's interface. + +Written in Python over the regular expression engine, so it runs wherever a +translated program runs. It follows expat where programs can see it: the +handlers and the order they are called in, namespace processing with a +separator, buffered character data, the internal DTD subset (general +entities, attribute defaults, notations), incremental Parse() calls, and +the error codes, messages and positions ElementTree and minidom report. + +What it does not do: + +- It never reads an external DTD or external entity on its own; an + ExternalEntityRefHandler decides, as with expat's default settings. +- DefaultHandler and DefaultHandlerExpand are accepted and never called. +- Input encodings are what the codecs module decodes (UTF-8, UTF-16, + ASCII and Latin-1). Any other declared encoding is "unknown encoding". +- Positions count characters, so CurrentByteIndex and ErrorByteIndex equal + the character offset rather than the UTF-8 byte offset. +- Names are checked loosely: anything but markup delimiters and whitespace + is accepted as a name character. +""" + +import codecs as _codecs +import re as _re + +import _cn1xml + +from xml.parsers.expat import errors +from xml.parsers.expat import model + +__all__ = ["ParserCreate", "ExpatError", "error", "ErrorString", "XMLParserType", "EXPAT_VERSION", + "version_info", "native_encoding", "features", "errors", "model"] + +EXPAT_VERSION = "expat_2.7.4" +version_info = (2, 7, 4) +native_encoding = "UTF-8" +features = [("sizeof(XML_Char)", 1), ("sizeof(XML_LChar)", 1), ("XML_DTD", 0), ("XML_CONTEXT_BYTES", 1024), + ("XML_NS", 0)] + +XML_PARAM_ENTITY_PARSING_NEVER = 0 +XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE = 1 +XML_PARAM_ENTITY_PARSING_ALWAYS = 2 + +_XML_NS = "http://www.w3.org/XML/1998/namespace" +_XMLNS_NS = "http://www.w3.org/2000/xmlns/" + +_NAME = r"[^\s<>/=\"'!?&;%()\[\],|]+" +_Q = r"(?:\"[^\"]*\"|'[^']*')" +_START = _re.compile(r"<(" + _NAME + r")((?:\s+" + _NAME + r"\s*=\s*" + _Q + r")*)\s*(/?)>") +_ATTR = _re.compile(r"(" + _NAME + r")\s*=\s*(?:\"([^\"]*)\"|'([^']*)')") +_END = _re.compile(r"") +_REF = _re.compile(r"&(?:#([0-9]+)|#x([0-9a-fA-F]+)|(" + _NAME + r"));") +_WS_CHARS = _re.compile(r"[\t\n\r]") +_DOCTYPE = _re.compile(r"$") +_NOTATION = _re.compile(r"$") +_ATTDEF = _re.compile(r"\s+(" + _NAME + r")\s+(\([^)]*\)|NOTATION\s*\([^)]*\)|" + _NAME + + r")\s+(#REQUIRED|#IMPLIED|(?:#FIXED\s+)?" + _Q + r")") +_XMLDECL = _re.compile(r"<\?xml\s+version\s*=\s*(" + _Q + r")(?:\s+encoding\s*=\s*(" + _Q + + r"))?(?:\s+standalone\s*=\s*(" + _Q + r"))?\s*\?>") +_ENC_SNIFF = _re.compile(rb"^<\?xml[^>]*?encoding\s*=\s*[\"']([A-Za-z0-9._:-]+)[\"']") + +_PREDEFINED = {"amp": "&", "lt": "<", "gt": ">", "quot": '"', "apos": "'"} + +_HANDLER_NAMES = ( + "StartElementHandler", "EndElementHandler", "ProcessingInstructionHandler", "CharacterDataHandler", + "UnparsedEntityDeclHandler", "NotationDeclHandler", "StartNamespaceDeclHandler", + "EndNamespaceDeclHandler", "CommentHandler", "StartCdataSectionHandler", "EndCdataSectionHandler", + "DefaultHandler", "DefaultHandlerExpand", "NotStandaloneHandler", "ExternalEntityRefHandler", + "StartDoctypeDeclHandler", "EndDoctypeDeclHandler", "EntityDeclHandler", "XmlDeclHandler", + "ElementDeclHandler", "AttlistDeclHandler", "SkippedEntityHandler", +) + + +class ExpatError(Exception): + pass + + +error = ExpatError + + +def ErrorString(code): + return errors.messages.get(code) + + +def _unquote(q): + return None if q is None else q[1:-1] + + +class _Entity: + def __init__(self, value, sysid, pubid, notation, base): + self.value = value + self.sysid = sysid + self.pubid = pubid + self.notation = notation + self.base = base + + +class XMLParserType: + """One parse: create with ParserCreate, set handlers, then Parse().""" + + def __init__(self, encoding=None, namespace_separator=None, intern=None): + self.StartElementHandler = None + self.EndElementHandler = None + self.ProcessingInstructionHandler = None + self.CharacterDataHandler = None + self.UnparsedEntityDeclHandler = None + self.NotationDeclHandler = None + self.StartNamespaceDeclHandler = None + self.EndNamespaceDeclHandler = None + self.CommentHandler = None + self.StartCdataSectionHandler = None + self.EndCdataSectionHandler = None + self.DefaultHandler = None + self.DefaultHandlerExpand = None + self.NotStandaloneHandler = None + self.ExternalEntityRefHandler = None + self.StartDoctypeDeclHandler = None + self.EndDoctypeDeclHandler = None + self.EntityDeclHandler = None + self.XmlDeclHandler = None + self.ElementDeclHandler = None + self.AttlistDeclHandler = None + self.SkippedEntityHandler = None + self.buffer_text = False + self.buffer_size = 8192 + self.ordered_attributes = False + self.specified_attributes = False + self.namespace_prefixes = False + self.intern = {} if intern is None else intern + self.ErrorCode = 0 + self.ErrorLineNumber = 1 + self.ErrorColumnNumber = 0 + self.ErrorByteIndex = -1 + self._encoding = encoding + self._sep = namespace_separator + self._raw = b"" + self._decoder = None + self._buf = "" + self._base_line = 1 + self._base_col = 0 + self._base_index = 0 + self._ev = 0 + self._started = False + self._finished = False + self._failed = False + self._state = 0 + self._stack = [] + self._ns = {"xml": _XML_NS} + self._text = [] + self._entities = {} + self._pentities = {} + self._expanding = [] + self._ref_pos = -1 + self._attdefaults = {} + self._seen_doctype = False + self._ext_subset = False + self._standalone = -1 + self._foreign_dtd = False + self._base = None + self._held_cr = False + self._outer_buf = "" + + # -- configuration ------------------------------------------------- + + def SetBase(self, base): + self._base = base + + def GetBase(self): + return self._base + + def SetParamEntityParsing(self, flag): + return 1 + + def UseForeignDTD(self, flag=True): + if self._started: + self._raise(26, 0) + self._foreign_dtd = bool(flag) + + def GetReparseDeferralEnabled(self): + return False + + def SetReparseDeferralEnabled(self, enabled): + pass + + def SetAllocTrackerActivationThreshold(self, threshold): + pass + + def SetAllocTrackerMaximumAmplification(self, factor): + pass + + def GetInputContext(self): + if not self._started: + return None + i = max(self._ev, 0) + return self._buf[i:i + 1024].encode("utf-8") + + def ExternalEntityParserCreate(self, context, encoding=None): + p = XMLParserType(encoding, self._sep, self.intern) + # Spelled out rather than setattr over _HANDLER_NAMES: a computed + # attribute name keeps the whole module from being typed. + p.StartElementHandler = self.StartElementHandler + p.EndElementHandler = self.EndElementHandler + p.ProcessingInstructionHandler = self.ProcessingInstructionHandler + p.CharacterDataHandler = self.CharacterDataHandler + p.UnparsedEntityDeclHandler = self.UnparsedEntityDeclHandler + p.NotationDeclHandler = self.NotationDeclHandler + p.StartNamespaceDeclHandler = self.StartNamespaceDeclHandler + p.EndNamespaceDeclHandler = self.EndNamespaceDeclHandler + p.CommentHandler = self.CommentHandler + p.StartCdataSectionHandler = self.StartCdataSectionHandler + p.EndCdataSectionHandler = self.EndCdataSectionHandler + p.DefaultHandler = self.DefaultHandler + p.DefaultHandlerExpand = self.DefaultHandlerExpand + p.NotStandaloneHandler = self.NotStandaloneHandler + p.ExternalEntityRefHandler = self.ExternalEntityRefHandler + p.StartDoctypeDeclHandler = self.StartDoctypeDeclHandler + p.EndDoctypeDeclHandler = self.EndDoctypeDeclHandler + p.EntityDeclHandler = self.EntityDeclHandler + p.XmlDeclHandler = self.XmlDeclHandler + p.ElementDeclHandler = self.ElementDeclHandler + p.AttlistDeclHandler = self.AttlistDeclHandler + p.SkippedEntityHandler = self.SkippedEntityHandler + p.buffer_text = self.buffer_text + p.ordered_attributes = self.ordered_attributes + p.namespace_prefixes = self.namespace_prefixes + p._entities = self._entities + p._attdefaults = self._attdefaults + p._ns = dict(self._ns) + p._base = self._base + # An external entity is content, not a document: it may hold text + # and several elements at its top level. + p._state = 1 + p._fragment = True + return p + + # -- positions ----------------------------------------------------- + + def _position(self, i, buf=None): + if buf is None: + buf = self._buf + if i > len(buf): + i = len(buf) + nl = buf.count("\n", 0, i) + if nl == 0: + return self._base_line, self._base_col + i, self._base_index + i + return self._base_line + nl, i - buf.rfind("\n", 0, i) - 1, self._base_index + i + + @property + def CurrentLineNumber(self): + return self._position(self._ev)[0] + + @property + def CurrentColumnNumber(self): + return self._position(self._ev)[1] + + @property + def CurrentByteIndex(self): + if not self._started: + return -1 + return self._position(self._ev)[2] + + @property + def buffer_used(self): + return sum(len(t) for t in self._text) + + def _raise(self, code, i): + buf = None + if self._ref_pos >= 0: + i = self._ref_pos + buf = self._outer_buf + line, col, index = self._position(i, buf) + self.ErrorCode = code + self.ErrorLineNumber = line + self.ErrorColumnNumber = col + self.ErrorByteIndex = index + self._failed = True + e = ExpatError("%s: line %d, column %d" % (errors.messages[code], line, col)) + e.code = code + e.lineno = line + e.offset = col + raise e + + # -- input --------------------------------------------------------- + + def Parse(self, data, isfinal=False): + if self._finished: + self._raise(36, len(self._buf)) + if self._failed: + self._raise(self.ErrorCode, len(self._buf)) + self._started = True + if isinstance(data, str): + text = data + else: + text = self._decode(bytes(data), isfinal) + if text is None: + return 1 + if text: + if self._held_cr: + text = "\r" + text + self._held_cr = False + if not isfinal and text.endswith("\r"): + text = text[:-1] + self._held_cr = True + if "\r" in text: + text = text.replace("\r\n", "\n").replace("\r", "\n") + if not self._buf and self._base_index == 0 and text.startswith(""): + text = text[1:] + self._buf = self._buf + text + elif isfinal and self._held_cr: + self._buf = self._buf + "\n" + self._held_cr = False + pos = self._run(self._buf, 0, bool(isfinal)) + self._flush() + if isfinal: + self._finish(pos) + else: + self._compact(pos) + return 1 + + def ParseFile(self, file): + read = file.read + while True: + chunk = read(self.buffer_size if self.buffer_size > 0 else 8192) + if not chunk: + break + self.Parse(chunk, False) + return self.Parse(b"", True) + + def _decode(self, data, final): + if self._decoder is None: + raw = self._raw + data + if not final and len(raw) < 4: + self._raw = raw + return None + if not final and raw.startswith(b"" not in raw[:1024] and len(raw) < 1024: + self._raw = raw + return None + self._raw = b"" + enc = self._encoding + if raw.startswith(b"\xef\xbb\xbf"): + raw = raw[3:] + enc = enc or "utf-8" + elif raw.startswith(b"\xff\xfe") or raw.startswith(b"\xfe\xff"): + enc = enc or "utf-16" + elif raw.startswith(b"<\x00?\x00"): + enc = enc or "utf-16-le" + elif raw.startswith(b"\x00<\x00?"): + enc = enc or "utf-16-be" + if enc is None: + m = _ENC_SNIFF.match(raw) + enc = m.group(1).decode("ascii") if m else "utf-8" + try: + self._decoder = _codecs.getincrementaldecoder(enc)() + except LookupError: + self._started = True + self._buf = "" + self._raise(18, 0) + data = raw + try: + return self._decoder.decode(data, final) + except UnicodeDecodeError: + self._raise(4, len(self._buf)) + + def _compact(self, pos): + if pos <= 0: + return + line, col, index = self._position(pos) + self._base_line = line + self._base_col = col + self._base_index = index + self._buf = self._buf[pos:] + self._ev -= pos + + def _finish(self, pos): + if pos < len(self._buf): + self._raise(5, pos) + if getattr(self, "_fragment", False): + if len(self._stack) > 0: + self._raise(3, len(self._buf)) + elif self._state == 0 or self._stack: + self._raise(3, len(self._buf)) + self._finished = True + + # -- events -------------------------------------------------------- + + def _flush(self): + if self._text: + data = "".join(self._text) + self._text = [] + h = self.CharacterDataHandler + if h is not None: + h(data) + + def _chars(self, s): + if not s: + return + if self.buffer_text: + self._text.append(s) + return + h = self.CharacterDataHandler + if h is None: + return + # Unbuffered, expat reports each line ending as a call of its own. + start = 0 + while True: + nl = s.find("\n", start) + if nl < 0: + if start < len(s): + h(s[start:]) + return + if nl > start: + h(s[start:nl]) + h("\n") + start = nl + 1 + + # -- the tokenizer ------------------------------------------------- + + def _run(self, buf, pos, final): + # The common tokens run in Java (_cn1xml.run); it stops before any + # other, which _step handles exactly as the full tokenizer would. + n = len(buf) + while pos < n: + pos = _cn1xml.run(self, buf, pos) + if pos >= n: + break + q = self._step(buf, pos, final) + if q == pos: + return pos + pos = q + return pos + + # One token at pos; returns pos unchanged to wait for more input. + def _step(self, buf, pos, final): + n = len(buf) + lt = buf.find("<", pos) + if lt != pos: + end = n if lt < 0 else lt + if lt < 0 and not final: + amp = buf.rfind("&", pos, end) + if amp >= 0 and buf.find(";", amp, end) < 0: + end = amp + if end == pos: + return pos + self._ev = pos + self._text_run(buf, pos, end) + pos = end + return pos + self._ev = pos + c = buf[pos + 1] if pos + 1 < n else "" + if c == "/": + f = _cn1xml.scan_end(buf, pos) + if f is not None: + self._end_tag(f[1], pos) + pos = f[0] + return pos + m = _END.match(buf, pos) + if m is None: + if not final and buf.find(">", pos) < 0: + return pos + self._raise(4, pos + 2) + self._end_tag(m.group(1), pos) + pos = m.end() + return pos + if c == "?": + e = buf.find("?>", pos + 2) + if e < 0: + if not final: + return pos + self._raise(5, pos) + self._pi(buf, pos, e) + pos = e + 2 + return pos + if c == "!": + if buf.startswith("", pos + 4) + if e < 0: + if not final: + return pos + self._raise(5, pos) + body = buf[pos + 4:e] + bad = body.find("--") + if bad >= 0 or body.endswith("-"): + self._raise(4, pos + 4 + (bad + 2 if bad >= 0 else len(body) + 1)) + self._flush() + h = self.CommentHandler + if h is not None: + h(body) + pos = e + 3 + return pos + if buf.startswith("", pos + 9) + if e < 0: + if not final: + return pos + self._raise(20, pos) + if self._state != 1: + self._raise(4, pos) + self._cdata(buf[pos + 9:e]) + pos = e + 3 + return pos + if buf.startswith("", pos) < 0: + self._raise(5, pos) + self._raise(4, pos + 1) + self._start_tag(m, pos) + return m.end() + + def _text_run(self, buf, s, e): + if self._state != 1: + i = s + while i < e and buf[i] in " \t\n": + i += 1 + if i < e: + self._raise(2 if self._state == 0 else 9, i) + return + if "]]>" in buf[s:e]: + self._raise(4, buf.find("]]>", s, e) + 2) + amp = buf.find("&", s, e) + if amp < 0: + self._chars(buf[s:e]) + return + p = s + while amp >= 0: + if amp > p: + self._chars(buf[p:amp]) + m = _REF.match(buf, amp, e) + if m is None: + self._raise(4, amp + 1) + self._content_ref(m, amp) + p = m.end() + amp = buf.find("&", p, e) + if p < e: + self._chars(buf[p:e]) + + def _char_ref(self, m, at): + if m.group(1) is not None: + cp = int(m.group(1)) + else: + cp = int(m.group(2), 16) + if cp == 0 or cp > 0x10FFFF or 0xD800 <= cp <= 0xDFFF or cp in (0xFFFE, 0xFFFF) or ( + cp < 0x20 and cp not in (9, 10, 13)): + self._raise(14, at) + return chr(cp) + + def _content_ref(self, m, at): + name = m.group(3) + if name is None: + self._chars(self._char_ref(m, at)) + return + v = _PREDEFINED.get(name) + if v is not None: + self._chars(v) + return + ent = self._entities.get(name) + if ent is None: + if self._ext_subset or self._foreign_dtd: + self._flush() + h = self.SkippedEntityHandler + if h is not None: + h(name, 0) + return + self._raise(11, at) + if ent.notation is not None: + self._raise(15, at + 1) + if ent.value is None: + h = self.ExternalEntityRefHandler + self._flush() + if h is not None: + if not h(name, ent.base, ent.sysid, ent.pubid): + self._raise(21, at) + else: + h = self.SkippedEntityHandler + if h is not None: + h(name, 0) + return + if name in self._expanding: + self._raise(12, at + 1) + value = ent.value + if "<" not in value and "&" not in value: + self._chars(value) + return + self._expand(name, value, at) + + def _expand(self, name, value, at): + # The replacement text is parsed as content where the reference + # stood; errors inside it are reported at the reference. + saved_buf = self._buf + saved_ref = self._ref_pos + saved_ev = self._ev + depth = len(self._stack) + self._expanding.append(name) + if self._ref_pos < 0: + self._ref_pos = at + self._outer_buf = saved_buf + try: + r = _EntityRun(self) + r.run(value) + finally: + self._expanding.pop() + self._ref_pos = saved_ref + self._buf = saved_buf + self._ev = saved_ev + if len(self._stack) != depth: + self._raise(13, at) + + def _attr_value(self, raw, at): + lt = raw.find("<") + if lt >= 0: + self._raise(4, at + lt) + if "&" not in raw: + if "\t" in raw or "\n" in raw: + return _WS_CHARS.sub(" ", raw) + return raw + out = [] + p = 0 + for m in _REF.finditer(raw): + seg = raw[p:m.start()] + if "&" in seg: + self._raise(4, at) + out.append(_WS_CHARS.sub(" ", seg)) + name = m.group(3) + if name is None: + out.append(self._char_ref(m, at)) + elif name in _PREDEFINED: + out.append(_PREDEFINED[name]) + else: + ent = self._entities.get(name) + if ent is None: + if self._ext_subset or self._foreign_dtd: + p = m.end() + continue + self._raise(11, at) + if ent.value is None: + self._raise(16 if ent.notation is None else 15, at) + if name in self._expanding: + self._raise(12, at) + self._expanding.append(name) + try: + out.append(self._attr_value(ent.value, at)) + finally: + self._expanding.pop() + p = m.end() + seg = raw[p:] + if "&" in seg: + self._raise(4, at) + out.append(_WS_CHARS.sub(" ", seg)) + return "".join(out) + + def _start_tag(self, m, pos): + if self._state == 2: + self._raise(9, pos) + qname = m.group(1) + raw_attrs = m.group(2) + names = [] + values = [] + if raw_attrs: + for a in _ATTR.finditer(raw_attrs): + an = a.group(1) + if an in names: + self._raise(8, pos + 1 + len(qname) + a.start()) + names.append(an) + v = a.group(2) + g = 2 if v is not None else 3 + values.append(self._attr_value(a.group(g), m.start(2) + a.start(g))) + self._start_tail(qname, names, values, pos, m.group(3)) + + # The fast scan (_cn1xml.scan_start) joins here with names and values + # already checked and normalised. + def _start_tail(self, qname, names, values, pos, self_closing): + if self._state == 2: + self._raise(9, pos) + # specified_attributes leaves out the values only a DTD default gave. + defaults = None if self.specified_attributes else self._attdefaults.get(qname) + if defaults: + for an, dv in defaults: + if an not in names: + names.append(an) + values.append(dv) + parent_ns = self._ns + declared = [] + if self._sep is not None: + ns = None + keep_n = [] + keep_v = [] + for an, av in zip(names, values): + if an == "xmlns" or an.startswith("xmlns:"): + prefix = an[6:] if len(an) > 5 else None + if prefix == "xmlns": + self._raise(39, pos) + if prefix == "xml" and av != _XML_NS: + self._raise(38, pos) + if prefix != "xml" and av in (_XML_NS, _XMLNS_NS): + self._raise(40, pos) + if prefix is not None and av == "": + self._raise(28, pos) + if ns is None: + ns = dict(parent_ns) + ns[prefix or ""] = av + declared.append((prefix, av if av != "" else None)) + else: + keep_n.append(an) + keep_v.append(av) + if ns is not None: + self._ns = ns + names = keep_n + values = keep_v + name = self._expand_name(qname, True, pos) + expanded = [] + for i in range(len(names)): + en = self._expand_name(names[i], False, pos) + if en in expanded: + self._raise(8, pos) + expanded.append(en) + names = expanded + else: + name = qname + self._flush() + h = self.StartNamespaceDeclHandler + if h is not None: + for prefix, uri in declared: + h(prefix, uri) + if self._state == 0: + self._state = 1 + h = self.StartElementHandler + if h is not None: + if self.ordered_attributes: + attrs = [] + for i in range(len(names)): + attrs.append(names[i]) + attrs.append(values[i]) + else: + attrs = {} + for i in range(len(names)): + attrs[names[i]] = values[i] + h(name, attrs) + self._stack.append((qname, name, declared, parent_ns)) + if self_closing: + self._ev = pos + self._close_top() + + def _expand_name(self, qname, element, pos): + colon = qname.find(":") + if colon < 0: + if not element: + return qname + uri = self._ns.get("") + if not uri: + return qname + return uri + self._sep + qname + prefix = qname[:colon] + local = qname[colon + 1:] + uri = self._ns.get(prefix) + if uri is None: + self._raise(27, pos) + if self.namespace_prefixes: + return uri + self._sep + local + self._sep + prefix + return uri + self._sep + local + + def _end_tag(self, qname, pos): + if not self._stack: + self._raise(9 if self._state == 2 else 2, pos) + if self._stack[-1][0] != qname: + self._raise(7, pos + 2) + self._close_top() + + def _close_top(self): + qname, name, declared, parent_ns = self._stack.pop() + self._flush() + h = self.EndElementHandler + if h is not None: + h(name) + h = self.EndNamespaceDeclHandler + if h is not None: + for prefix, uri in reversed(declared): + h(prefix) + self._ns = parent_ns + if not self._stack and not self._expanding and not getattr(self, "_fragment", False): + self._state = 2 + + def _cdata(self, body): + hs = self.StartCdataSectionHandler + he = self.EndCdataSectionHandler + if hs is not None or he is not None: + self._flush() + if hs is not None: + hs() + self._chars(body) + self._flush() + if he is not None: + he() + else: + self._chars(body) + + def _pi(self, buf, pos, e): + body = buf[pos + 2:e] + i = 0 + while i < len(body) and body[i] not in " \t\n": + i += 1 + target = body[:i] + if not target: + self._raise(4, pos + 2) + if target.lower() == "xml": + if target == "xml" and pos == 0 and self._base_index == 0 and not self._expanding: + self._xml_decl(buf, pos, e) + return + self._raise(17, pos) + data = body[i:].lstrip(" \t\n") + self._flush() + h = self.ProcessingInstructionHandler + if h is not None: + h(target, data) + + def _xml_decl(self, buf, pos, e): + m = _XMLDECL.match(buf, pos) + if m is None or m.end() != e + 2: + self._raise(30, pos) + version = _unquote(m.group(1)) + encoding = _unquote(m.group(2)) + sa = _unquote(m.group(3)) + if sa is None: + standalone = -1 + elif sa == "yes": + standalone = 1 + elif sa == "no": + standalone = 0 + else: + self._raise(30, pos) + self._standalone = standalone + h = self.XmlDeclHandler + if h is not None: + h(version, encoding, standalone) + + # -- the DTD ------------------------------------------------------- + + def _doctype(self, buf, pos, final): + if self._state != 0 or self._seen_doctype: + self._raise(2, pos) + if not final and buf.find(">", pos) < 0: + return -1 + m = _DOCTYPE.match(buf, pos) + if m is None: + if not final: + return -1 + self._raise(2, pos) + n = len(buf) + p = m.end() + subset = None + if p < n and buf[p] == "[": + e = _subset_end(buf, p + 1) + if e < 0: + if not final: + return -1 + self._raise(5, pos) + subset = buf[p + 1:e] + p = e + 1 + while p < n and buf[p] in " \t\n": + p += 1 + if p >= n: + if not final: + return -1 + self._raise(5, pos) + if buf[p] != ">": + self._raise(2, p) + self._seen_doctype = True + name = m.group(1) + sysid = _unquote(m.group(2) if m.group(2) is not None else m.group(4)) + pubid = _unquote(m.group(3)) + if sysid is not None: + self._ext_subset = True + self._flush() + h = self.StartDoctypeDeclHandler + if h is not None: + h(name, sysid, pubid, 1 if subset is not None else 0) + if subset is not None: + self._subset(subset, pos) + h = self.EndDoctypeDeclHandler + if h is not None: + h() + if self._ext_subset and self._standalone != 1: + h = self.NotStandaloneHandler + if h is not None and not h(): + self._raise(22, pos) + return p + 1 + + def _subset(self, s, at): + n = len(s) + i = 0 + while i < n: + c = s[i] + if c in " \t\n": + i += 1 + continue + if c == "%": + e = s.find(";", i) + if e < 0: + self._raise(2, at) + # A parameter entity can bring in declarations this parser + # never reads, so undeclared entities stop being errors. + self._ext_subset = True + i = e + 1 + continue + if s.startswith("", i + 4) + if e < 0: + self._raise(5, at) + h = self.CommentHandler + if h is not None: + h(s[i + 4:e]) + i = e + 3 + continue + if s.startswith("", i + 2) + if e < 0: + self._raise(5, at) + body = s[i + 2:e] + parts = body.split(None, 1) + h = self.ProcessingInstructionHandler + if h is not None and parts: + h(parts[0], parts[1] if len(parts) > 1 else "") + i = e + 2 + continue + if s.startswith("$", d, _re.S) + if m is None: + self._raise(2, at) + h = self.ElementDeclHandler + if h is not None: + h(m.group(1), _content_model(m.group(2))) + return + if d.startswith("", i + 4) + if e < 0: + return -1 + i = e + 3 + continue + if buf.startswith("", i + 2) + if e < 0: + return -1 + i = e + 2 + continue + i += 1 + return -1 + + +def _decl_end(s, i): + n = len(s) + while i < n: + c = s[i] + if c == ">": + return i + if c == '"' or c == "'": + e = s.find(c, i + 1) + if e < 0: + return -1 + i = e + 1 + continue + i += 1 + return -1 + + +def _content_model(spec): + spec = spec.strip() + if spec == "EMPTY": + return (model.XML_CTYPE_EMPTY, model.XML_CQUANT_NONE, None, ()) + if spec == "ANY": + return (model.XML_CTYPE_ANY, model.XML_CQUANT_NONE, None, ()) + toks = _re.findall(r"#PCDATA|[(),|?*+]|[^\s(),|?*+]+", spec) + pos = [0] + + def quant(): + if pos[0] < len(toks) and toks[pos[0]] in ("?", "*", "+"): + t = toks[pos[0]] + pos[0] += 1 + return {"?": model.XML_CQUANT_OPT, "*": model.XML_CQUANT_REP, "+": model.XML_CQUANT_PLUS}[t] + return model.XML_CQUANT_NONE + + def particle(): + t = toks[pos[0]] + pos[0] += 1 + if t == "(": + return group() + return (model.XML_CTYPE_NAME, quant(), t, ()) + + def group(): + items = [] + kind = model.XML_CTYPE_SEQ + mixed = False + while pos[0] < len(toks): + t = toks[pos[0]] + if t == "#PCDATA": + mixed = True + pos[0] += 1 + continue + if t == ")": + pos[0] += 1 + break + if t == "|": + kind = model.XML_CTYPE_CHOICE + pos[0] += 1 + continue + if t == ",": + pos[0] += 1 + continue + items.append(particle()) + q = quant() + if mixed: + return (model.XML_CTYPE_MIXED, q, None, tuple(items)) + return (kind, q, None, tuple(items)) + + if toks and toks[0] == "(": + pos[0] = 1 + return group() + return (model.XML_CTYPE_ANY, model.XML_CQUANT_NONE, None, ()) + + +def ParserCreate(encoding=None, namespace_separator=None, intern=None): + if namespace_separator is not None: + if not isinstance(namespace_separator, str): + raise TypeError("ParserCreate() argument 'namespace_separator' must be str or None, not " + + type(namespace_separator).__name__) + if len(namespace_separator) > 1: + raise ValueError("namespace_separator must be at most one character, omitted, or None") + if encoding is not None and not isinstance(encoding, str): + raise TypeError("ParserCreate() argument 'encoding' must be str or None, not " + type(encoding).__name__) + return XMLParserType(encoding, namespace_separator, intern) diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/xml/parsers/expat/errors.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/xml/parsers/expat/errors.py new file mode 100644 index 00000000000..369500f310e --- /dev/null +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/xml/parsers/expat/errors.py @@ -0,0 +1,79 @@ +# Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. +# Licensed under the GNU General Public License version 2 with the Classpath +# exception, as the rest of the Codename One Python runtime. +"""xml.parsers.expat.errors: expat's error codes and messages.""" + +__all__ = ["codes", "messages"] + +_TABLE = ( + "out of memory", "syntax error", "no element found", "not well-formed (invalid token)", + "unclosed token", "partial character", "mismatched tag", "duplicate attribute", + "junk after document element", "illegal parameter entity reference", "undefined entity", + "recursive entity reference", "asynchronous entity", "reference to invalid character number", + "reference to binary entity", "reference to external entity in attribute", + "XML or text declaration not at start of entity", "unknown encoding", + "encoding specified in XML declaration is incorrect", "unclosed CDATA section", + "error in processing external entity reference", "document is not standalone", + "unexpected parser state - please send a bug report", "entity declared in parameter entity", + "requested feature requires XML_DTD support in Expat", "cannot change setting once parsing has begun", + "unbound prefix", "must not undeclare prefix", "incomplete markup in parameter entity", + "XML declaration not well-formed", "text declaration not well-formed", "illegal character(s) in public id", + "parser suspended", "parser not suspended", "parsing aborted", "parsing finished", + "cannot suspend in external parameter entity", + "reserved prefix (xml) must not be undeclared or bound to another namespace name", + "reserved prefix (xmlns) must not be declared or undeclared", + "prefix must not be bound to one of the reserved namespace names", "invalid argument", + "a successful prior call to function XML_GetBuffer is required", + "limit on input amplification factor (from DTD and entities) breached", "parser not started", +) + +XML_ERROR_NO_MEMORY = _TABLE[0] +XML_ERROR_SYNTAX = _TABLE[1] +XML_ERROR_NO_ELEMENTS = _TABLE[2] +XML_ERROR_INVALID_TOKEN = _TABLE[3] +XML_ERROR_UNCLOSED_TOKEN = _TABLE[4] +XML_ERROR_PARTIAL_CHAR = _TABLE[5] +XML_ERROR_TAG_MISMATCH = _TABLE[6] +XML_ERROR_DUPLICATE_ATTRIBUTE = _TABLE[7] +XML_ERROR_JUNK_AFTER_DOC_ELEMENT = _TABLE[8] +XML_ERROR_PARAM_ENTITY_REF = _TABLE[9] +XML_ERROR_UNDEFINED_ENTITY = _TABLE[10] +XML_ERROR_RECURSIVE_ENTITY_REF = _TABLE[11] +XML_ERROR_ASYNC_ENTITY = _TABLE[12] +XML_ERROR_BAD_CHAR_REF = _TABLE[13] +XML_ERROR_BINARY_ENTITY_REF = _TABLE[14] +XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF = _TABLE[15] +XML_ERROR_MISPLACED_XML_PI = _TABLE[16] +XML_ERROR_UNKNOWN_ENCODING = _TABLE[17] +XML_ERROR_INCORRECT_ENCODING = _TABLE[18] +XML_ERROR_UNCLOSED_CDATA_SECTION = _TABLE[19] +XML_ERROR_EXTERNAL_ENTITY_HANDLING = _TABLE[20] +XML_ERROR_NOT_STANDALONE = _TABLE[21] +XML_ERROR_UNEXPECTED_STATE = _TABLE[22] +XML_ERROR_ENTITY_DECLARED_IN_PE = _TABLE[23] +XML_ERROR_FEATURE_REQUIRES_XML_DTD = _TABLE[24] +XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING = _TABLE[25] +XML_ERROR_UNBOUND_PREFIX = _TABLE[26] +XML_ERROR_UNDECLARING_PREFIX = _TABLE[27] +XML_ERROR_INCOMPLETE_PE = _TABLE[28] +XML_ERROR_XML_DECL = _TABLE[29] +XML_ERROR_TEXT_DECL = _TABLE[30] +XML_ERROR_PUBLICID = _TABLE[31] +XML_ERROR_SUSPENDED = _TABLE[32] +XML_ERROR_NOT_SUSPENDED = _TABLE[33] +XML_ERROR_ABORTED = _TABLE[34] +XML_ERROR_FINISHED = _TABLE[35] +XML_ERROR_SUSPEND_PE = _TABLE[36] +XML_ERROR_RESERVED_PREFIX_XML = _TABLE[37] +XML_ERROR_RESERVED_PREFIX_XMLNS = _TABLE[38] +XML_ERROR_RESERVED_NAMESPACE_URI = _TABLE[39] +XML_ERROR_INVALID_ARGUMENT = _TABLE[40] +XML_ERROR_NO_BUFFER = _TABLE[41] +XML_ERROR_AMPLIFICATION_LIMIT_BREACH = _TABLE[42] +XML_ERROR_NOT_STARTED = _TABLE[43] + +codes = {} +messages = {} +for _i, _m in enumerate(_TABLE): + codes[_m] = _i + 1 + messages[_i + 1] = _m diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/xml/parsers/expat/model.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/xml/parsers/expat/model.py new file mode 100644 index 00000000000..a768fa519ee --- /dev/null +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/xml/parsers/expat/model.py @@ -0,0 +1,16 @@ +# Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. +# Licensed under the GNU General Public License version 2 with the Classpath +# exception, as the rest of the Codename One Python runtime. +"""xml.parsers.expat.model: the content-model constants.""" + +XML_CTYPE_EMPTY = 1 +XML_CTYPE_ANY = 2 +XML_CTYPE_MIXED = 3 +XML_CTYPE_NAME = 4 +XML_CTYPE_CHOICE = 5 +XML_CTYPE_SEQ = 6 + +XML_CQUANT_NONE = 0 +XML_CQUANT_OPT = 1 +XML_CQUANT_REP = 2 +XML_CQUANT_PLUS = 3 diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/xml/sax/__init__.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/xml/sax/__init__.py new file mode 100644 index 00000000000..c0d18555ff2 --- /dev/null +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/xml/sax/__init__.py @@ -0,0 +1,52 @@ +# Copyright (c) 2001 Python Software Foundation; All Rights Reserved +# Licensed under the Python Software Foundation License Version 2; the full +# text is in maven/python-transpiler/third-party/cpython/LICENSE.txt. +# +# Derived from CPython's Lib/xml/sax/__init__.py. Changes: rewritten for the Codename One +# Python runtime, trimmed to what the transpiler supports and reorganised; +# the C accelerators and platform-specific branches are left out. +"""xml.sax: the SAX2 interface over the pure-Python expat parser.""" + +from xml.sax.xmlreader import InputSource +from xml.sax.handler import ContentHandler, ErrorHandler +from xml.sax._exceptions import (SAXException, SAXNotRecognizedException, SAXParseException, + SAXNotSupportedException, SAXReaderNotAvailable) + +default_parser_list = ["xml.sax.expatreader"] + + +def parse(source, handler, errorHandler=ErrorHandler()): + parser = make_parser() + parser.setContentHandler(handler) + parser.setErrorHandler(errorHandler) + parser.parse(source) + + +def parseString(string, handler, errorHandler=ErrorHandler()): + import io + if errorHandler is None: + errorHandler = ErrorHandler() + parser = make_parser() + parser.setContentHandler(handler) + parser.setErrorHandler(errorHandler) + inpsrc = InputSource() + if isinstance(string, str): + inpsrc.setCharacterStream(io.StringIO(string)) + else: + inpsrc.setByteStream(io.BytesIO(string)) + parser.parse(inpsrc) + + +def make_parser(parser_list=()): + # Only the built-in reader exists; a module name is never imported + # dynamically, so any other entry in parser_list is skipped. + for name in list(parser_list) + default_parser_list: + if name == "xml.sax.expatreader": + from xml.sax import expatreader + return expatreader.create_parser() + raise SAXReaderNotAvailable("No parsers found", None) + + +__all__ = ["ContentHandler", "ErrorHandler", "InputSource", "SAXException", "SAXNotRecognizedException", + "SAXNotSupportedException", "SAXParseException", "SAXReaderNotAvailable", "default_parser_list", + "make_parser", "parse", "parseString"] diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/xml/sax/_exceptions.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/xml/sax/_exceptions.py new file mode 100644 index 00000000000..1033194aedd --- /dev/null +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/xml/sax/_exceptions.py @@ -0,0 +1,72 @@ +# Copyright (c) 2001 Python Software Foundation; All Rights Reserved +# Licensed under the Python Software Foundation License Version 2; the full +# text is in maven/python-transpiler/third-party/cpython/LICENSE.txt. +# +# Derived from CPython's Lib/xml/sax/_exceptions.py. Changes: rewritten for the Codename One +# Python runtime, trimmed to what the transpiler supports and reorganised; +# the C accelerators and platform-specific branches are left out. +"""xml.sax._exceptions: the SAX exception classes.""" + + +class SAXException(Exception): + def __init__(self, msg, exception=None): + self._msg = msg + self._exception = exception + Exception.__init__(self, msg) + + def getMessage(self): + return self._msg + + def getException(self): + return self._exception + + def __str__(self): + return self._msg + + def __getitem__(self, ix): + raise AttributeError("__getitem__") + + +class SAXParseException(SAXException): + def __init__(self, msg, exception, locator): + SAXException.__init__(self, msg, exception) + self._locator = locator + self._systemId = self._locator.getSystemId() + self._colnum = self._locator.getColumnNumber() + self._linenum = self._locator.getLineNumber() + + def getColumnNumber(self): + return self._colnum + + def getLineNumber(self): + return self._linenum + + def getPublicId(self): + return self._locator.getPublicId() + + def getSystemId(self): + return self._systemId + + def __str__(self): + sysid = self.getSystemId() + if sysid is None: + sysid = "" + linenum = self.getLineNumber() + if linenum is None: + linenum = "?" + colnum = self.getColumnNumber() + if colnum is None: + colnum = "?" + return "%s:%s:%s: %s" % (sysid, linenum, colnum, self._msg) + + +class SAXNotRecognizedException(SAXException): + pass + + +class SAXNotSupportedException(SAXException): + pass + + +class SAXReaderNotAvailable(SAXNotSupportedException): + pass diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/xml/sax/expatreader.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/xml/sax/expatreader.py new file mode 100644 index 00000000000..f71ebfa0fd7 --- /dev/null +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/xml/sax/expatreader.py @@ -0,0 +1,350 @@ +# Copyright (c) 2001 Python Software Foundation; All Rights Reserved +# Licensed under the Python Software Foundation License Version 2; the full +# text is in maven/python-transpiler/third-party/cpython/LICENSE.txt. +# +# Derived from CPython's Lib/xml/sax/expatreader.py. Changes: rewritten for the Codename One +# Python runtime, trimmed to what the transpiler supports and reorganised; +# the C accelerators and platform-specific branches are left out. +"""xml.sax.expatreader: the SAX driver over xml.parsers.expat.""" + +from xml.sax._exceptions import SAXException, SAXParseException, SAXNotRecognizedException, SAXNotSupportedException +from xml.sax.handler import (feature_namespaces, feature_namespace_prefixes, feature_validation, + feature_external_ges, feature_external_pes, feature_string_interning, + property_lexical_handler, property_xml_string, property_interning_dict) +from xml.sax import xmlreader, saxutils, handler +from xml.parsers import expat + +AttributesImpl = xmlreader.AttributesImpl +AttributesNSImpl = xmlreader.AttributesNSImpl + + +class ExpatLocator(xmlreader.Locator): + def __init__(self, parser): + self._ref = parser + + def getColumnNumber(self): + p = self._ref + if p._parser is None: + return None + return p._parser.ErrorColumnNumber + + def getLineNumber(self): + p = self._ref + if p._parser is None: + return 1 + return p._parser.ErrorLineNumber + + def getPublicId(self): + p = self._ref + if p is None: + return None + return p._source.getPublicId() + + def getSystemId(self): + p = self._ref + if p is None: + return None + return p._source.getSystemId() + + +class ExpatParser(xmlreader.IncrementalParser, xmlreader.Locator): + def __init__(self, namespaceHandling=0, bufsize=2 ** 16 - 20): + xmlreader.IncrementalParser.__init__(self, bufsize) + self._source = xmlreader.InputSource() + self._parser = None + self._namespaces = namespaceHandling + self._lex_handler_prop = None + self._parsing = False + self._entity_stack = [] + self._external_ges = 0 + self._interning = None + self._namespace_prefixes = 0 + + def parse(self, source): + source = saxutils.prepare_input_source(source) + self._source = source + try: + self.reset() + self._cont_handler.setDocumentLocator(ExpatLocator(self)) + xmlreader.IncrementalParser.parse(self, source) + except: + self._close_source() + raise + + def prepareParser(self, source): + if source.getSystemId() is not None: + self._parser.SetBase(source.getSystemId()) + + def setContentHandler(self, handler): + xmlreader.IncrementalParser.setContentHandler(self, handler) + if self._parsing: + self._reset_cont_handler() + + def getFeature(self, name): + if name == feature_namespaces: + return self._namespaces + if name == feature_string_interning: + return self._interning is not None + if name in (feature_validation, feature_external_pes): + return 0 + if name == feature_external_ges: + return self._external_ges + if name == feature_namespace_prefixes: + return self._namespace_prefixes + raise SAXNotRecognizedException("Feature '%s' not recognized" % name) + + def setFeature(self, name, state): + if self._parsing: + raise SAXNotSupportedException("Cannot set features while parsing") + if name == feature_namespaces: + self._namespaces = state + elif name == feature_external_ges: + self._external_ges = state + elif name == feature_string_interning: + if state: + if self._interning is None: + self._interning = {} + else: + self._interning = None + elif name == feature_validation: + if state: + raise SAXNotSupportedException("expat does not support validation") + elif name == feature_external_pes: + if state: + raise SAXNotSupportedException("expat does not read external parameter entities") + elif name == feature_namespace_prefixes: + self._namespace_prefixes = state + else: + raise SAXNotRecognizedException("Feature '%s' not recognized" % name) + + def getProperty(self, name): + if name == handler.property_lexical_handler: + return self._lex_handler_prop + if name == property_interning_dict: + return self._interning + if name == property_xml_string: + if self._parser: + return self._parser.GetInputContext() + raise SAXNotRecognizedException("This property is only available during a parse") + raise SAXNotRecognizedException("Property '%s' not recognized" % name) + + def setProperty(self, name, value): + if name == handler.property_lexical_handler: + self._lex_handler_prop = value + if self._parsing: + self._reset_lex_handler_prop() + elif name == property_interning_dict: + self._interning = value + elif name == property_xml_string: + raise SAXNotSupportedException("Property '%s' cannot be set" % name) + else: + raise SAXNotRecognizedException("Property '%s' not recognized" % name) + + def feed(self, data, isFinal=False): + if not self._parsing: + self.reset() + self._parsing = True + self._cont_handler.startDocument() + try: + self._parser.Parse(data, isFinal) + except expat.error as e: + exc = SAXParseException(expat.ErrorString(e.code), e, self) + self._err_handler.fatalError(exc) + + def flush(self): + if self._parser is None: + return + was = self._parser.GetReparseDeferralEnabled() + try: + self._parser.SetReparseDeferralEnabled(False) + self._parser.Parse(b"", False) + except expat.error as e: + exc = SAXParseException(expat.ErrorString(e.code), e, self) + self._err_handler.fatalError(exc) + finally: + self._parser.SetReparseDeferralEnabled(was) + + def _close_source(self): + source = self._source + try: + file = source.getCharacterStream() + if file is not None: + file.close() + finally: + file = source.getByteStream() + if file is not None: + file.close() + + def close(self): + if self._entity_stack or self._parser is None or isinstance(self._parser, _ClosedParser): + return + try: + self.feed(b"", isFinal=True) + self._cont_handler.endDocument() + self._parsing = False + self._parser = None + finally: + self._parsing = False + if self._parser is not None: + parser = _ClosedParser() + parser.ErrorColumnNumber = self._parser.ErrorColumnNumber + parser.ErrorLineNumber = self._parser.ErrorLineNumber + self._parser = parser + self._close_source() + + def _reset_cont_handler(self): + self._parser.ProcessingInstructionHandler = self._cont_handler.processingInstruction + self._parser.CharacterDataHandler = self._cont_handler.characters + + def _reset_lex_handler_prop(self): + lex = self._lex_handler_prop + parser = self._parser + if lex is None: + parser.CommentHandler = None + parser.StartCdataSectionHandler = None + parser.EndCdataSectionHandler = None + parser.StartDoctypeDeclHandler = None + parser.EndDoctypeDeclHandler = None + else: + parser.CommentHandler = lex.comment + parser.StartCdataSectionHandler = lex.startCDATA + parser.EndCdataSectionHandler = lex.endCDATA + parser.StartDoctypeDeclHandler = self.start_doctype_decl + parser.EndDoctypeDeclHandler = lex.endDTD + + def reset(self): + if self._namespaces: + self._parser = expat.ParserCreate(self._source.getEncoding(), " ", intern=self._interning) + self._parser.namespace_prefixes = 1 + self._parser.StartElementHandler = self.start_element_ns + self._parser.EndElementHandler = self.end_element_ns + else: + self._parser = expat.ParserCreate(self._source.getEncoding(), intern=self._interning) + self._parser.StartElementHandler = self.start_element + self._parser.EndElementHandler = self.end_element + self._reset_cont_handler() + self._parser.UnparsedEntityDeclHandler = self.unparsed_entity_decl + self._parser.NotationDeclHandler = self.notation_decl + self._parser.StartNamespaceDeclHandler = self.start_namespace_decl + self._parser.EndNamespaceDeclHandler = self.end_namespace_decl + self._decl_handler_prop = None + if self._lex_handler_prop: + self._reset_lex_handler_prop() + self._parser.ExternalEntityRefHandler = self.external_entity_ref + try: + self._parser.SkippedEntityHandler = self.skipped_entity_handler + except AttributeError: + pass + self._parser.SetParamEntityParsing(expat.XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE) + self._parsing = False + self._entity_stack = [] + + def getColumnNumber(self): + if self._parser is None: + return None + return self._parser.ErrorColumnNumber + + def getLineNumber(self): + if self._parser is None: + return 1 + return self._parser.ErrorLineNumber + + def getPublicId(self): + return self._source.getPublicId() + + def getSystemId(self): + return self._source.getSystemId() + + def start_element(self, name, attrs): + self._cont_handler.startElement(name, AttributesImpl(attrs)) + + def end_element(self, name): + self._cont_handler.endElement(name) + + def start_element_ns(self, name, attrs): + pair = name.split() + if len(pair) == 1: + pair = (None, name) + elif len(pair) == 3: + pair = pair[0], pair[1] + else: + pair = tuple(pair) + newattrs = {} + qnames = {} + for (aname, value) in attrs.items(): + parts = aname.split() + length = len(parts) + if length == 1: + qname = aname + apair = (None, aname) + elif length == 3: + qname = "%s:%s" % (parts[2], parts[1]) + apair = parts[0], parts[1] + else: + qname = parts[1] + apair = tuple(parts) + newattrs[apair] = value + qnames[apair] = qname + self._cont_handler.startElementNS(pair, None, AttributesNSImpl(newattrs, qnames)) + + def end_element_ns(self, name): + pair = name.split() + if len(pair) == 1: + pair = (None, name) + elif len(pair) == 3: + pair = pair[0], pair[1] + else: + pair = tuple(pair) + self._cont_handler.endElementNS(pair, None) + + def processing_instruction(self, target, data): + self._cont_handler.processingInstruction(target, data) + + def character_data(self, data): + self._cont_handler.characters(data) + + def start_namespace_decl(self, prefix, uri): + self._cont_handler.startPrefixMapping(prefix, uri) + + def end_namespace_decl(self, prefix): + self._cont_handler.endPrefixMapping(prefix) + + def start_doctype_decl(self, name, sysid, pubid, has_internal_subset): + self._lex_handler_prop.startDTD(name, pubid, sysid) + + def unparsed_entity_decl(self, name, base, sysid, pubid, notation_name): + self._dtd_handler.unparsedEntityDecl(name, pubid, sysid, notation_name) + + def notation_decl(self, name, base, sysid, pubid): + self._dtd_handler.notationDecl(name, pubid, sysid) + + def external_entity_ref(self, context, base, sysid, pubid): + # External general entities are never fetched; the reference is + # reported as skipped, as expat does with the feature off. + if not self._external_ges: + return 1 + source = self._ent_handler.resolveEntity(pubid, sysid) + source = saxutils.prepare_input_source(source, self._source.getSystemId() or "") + self._entity_stack.append((self._parser, self._source)) + self._parser = self._parser.ExternalEntityParserCreate(context) + self._source = source + try: + xmlreader.IncrementalParser.parse(self, source) + except: + return 0 + (self._parser, self._source) = self._entity_stack[-1] + del self._entity_stack[-1] + return 1 + + def skipped_entity_handler(self, name, is_pe): + if is_pe: + name = "%" + name + self._cont_handler.skippedEntity(name) + + +class _ClosedParser: + pass + + +def create_parser(*args, **kwargs): + return ExpatParser(*args, **kwargs) diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/xml/sax/handler.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/xml/sax/handler.py new file mode 100644 index 00000000000..54def0e3c9d --- /dev/null +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/xml/sax/handler.py @@ -0,0 +1,112 @@ +# Copyright (c) 2001 Python Software Foundation; All Rights Reserved +# Licensed under the Python Software Foundation License Version 2; the full +# text is in maven/python-transpiler/third-party/cpython/LICENSE.txt. +# +# Derived from CPython's Lib/xml/sax/handler.py. Changes: rewritten for the Codename One +# Python runtime, trimmed to what the transpiler supports and reorganised; +# the C accelerators and platform-specific branches are left out. +"""xml.sax.handler: the handler base classes and the feature and property names.""" + + +class ErrorHandler: + def error(self, exception): + raise exception + + def fatalError(self, exception): + raise exception + + def warning(self, exception): + print(exception) + + +class ContentHandler: + def __init__(self): + self._locator = None + + def setDocumentLocator(self, locator): + self._locator = locator + + def startDocument(self): + pass + + def endDocument(self): + pass + + def startPrefixMapping(self, prefix, uri): + pass + + def endPrefixMapping(self, prefix): + pass + + def startElement(self, name, attrs): + pass + + def endElement(self, name): + pass + + def startElementNS(self, name, qname, attrs): + pass + + def endElementNS(self, name, qname): + pass + + def characters(self, content): + pass + + def ignorableWhitespace(self, whitespace): + pass + + def processingInstruction(self, target, data): + pass + + def skippedEntity(self, name): + pass + + +class DTDHandler: + def notationDecl(self, name, publicId, systemId): + pass + + def unparsedEntityDecl(self, name, publicId, systemId, ndata): + pass + + +class EntityResolver: + def resolveEntity(self, publicId, systemId): + return systemId + + +class LexicalHandler: + def comment(self, content): + pass + + def startDTD(self, name, public_id, system_id): + pass + + def endDTD(self): + pass + + def startCDATA(self): + pass + + def endCDATA(self): + pass + + +feature_namespaces = "http://xml.org/sax/features/namespaces" +feature_namespace_prefixes = "http://xml.org/sax/features/namespace-prefixes" +feature_string_interning = "http://xml.org/sax/features/string-interning" +feature_validation = "http://xml.org/sax/features/validation" +feature_external_ges = "http://xml.org/sax/features/external-general-entities" +feature_external_pes = "http://xml.org/sax/features/external-parameter-entities" +all_features = [feature_namespaces, feature_namespace_prefixes, feature_string_interning, feature_validation, + feature_external_ges, feature_external_pes] + +property_lexical_handler = "http://xml.org/sax/properties/lexical-handler" +property_declaration_handler = "http://xml.org/sax/properties/declaration-handler" +property_dom_node = "http://xml.org/sax/properties/dom-node" +property_xml_string = "http://xml.org/sax/properties/xml-string" +property_encoding = "http://www.python.org/sax/properties/encoding" +property_interning_dict = "http://www.python.org/sax/properties/interning-dict" +all_properties = [property_lexical_handler, property_dom_node, property_declaration_handler, property_xml_string, + property_encoding, property_interning_dict] diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/xml/sax/saxutils.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/xml/sax/saxutils.py new file mode 100644 index 00000000000..b8c839e57cd --- /dev/null +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/xml/sax/saxutils.py @@ -0,0 +1,302 @@ +# Copyright (c) 2001 Python Software Foundation; All Rights Reserved +# Licensed under the Python Software Foundation License Version 2; the full +# text is in maven/python-transpiler/third-party/cpython/LICENSE.txt. +# +# Derived from CPython's Lib/xml/sax/saxutils.py. Changes: rewritten for the Codename One +# Python runtime, trimmed to what the transpiler supports and reorganised; +# the C accelerators and platform-specific branches are left out. +"""xml.sax.saxutils: escaping, XMLGenerator, XMLFilterBase and +prepare_input_source.""" + +import io as _io +import os as _os +import sys as _sys + +from xml.sax import handler +from xml.sax import xmlreader + + +def __dict_replace(s, d): + for key, value in d.items(): + s = s.replace(key, value) + return s + + +def escape(data, entities={}): + data = data.replace("&", "&") + data = data.replace(">", ">") + data = data.replace("<", "<") + if entities: + data = __dict_replace(data, entities) + return data + + +def unescape(data, entities={}): + data = data.replace("<", "<") + data = data.replace(">", ">") + if entities: + data = __dict_replace(data, entities) + return data.replace("&", "&") + + +def quoteattr(data, entities={}): + entities = {**entities, "\n": " ", "\r": " ", "\t": " "} + data = escape(data, entities) + if '"' in data: + if "'" in data: + data = '"%s"' % data.replace('"', """) + else: + data = "'%s'" % data + else: + data = '"%s"' % data + return data + + +class _Writer: + """Writes text to a text stream as it is, or encoded (characters the + encoding lacks as character references) to a binary one.""" + + def __init__(self, out, encoding): + self._out = out + self._encoding = encoding + self._text = None + + def write(self, s): + if self._text is None: + try: + self._out.write("") + self._text = True + except TypeError: + self._text = False + if self._text: + self._out.write(s) + else: + self._out.write(s.encode(self._encoding, "xmlcharrefreplace")) + + def flush(self): + f = getattr(self._out, "flush", None) + if f is not None: + f() + + +class XMLGenerator(handler.ContentHandler): + def __init__(self, out=None, encoding="iso-8859-1", short_empty_elements=False): + handler.ContentHandler.__init__(self) + if out is None: + out = _sys.stdout + w = _Writer(out, encoding) + self._write = w.write + self._flush = w.flush + self._ns_contexts = [{}] + self._current_context = self._ns_contexts[-1] + self._undeclared_ns_maps = [] + self._encoding = encoding + self._short_empty_elements = short_empty_elements + self._pending_start_element = False + + def _qname(self, name): + if name[0]: + if "http://www.w3.org/XML/1998/namespace" == name[0]: + return "xml:" + name[1] + prefix = self._current_context[name[0]] + if prefix: + return prefix + ":" + name[1] + return name[1] + + def _finish_pending_start_element(self, endElement=False): + if self._pending_start_element: + self._write(">") + self._pending_start_element = False + + def startDocument(self): + self._write('\n' % self._encoding) + + def endDocument(self): + self._flush() + + def startPrefixMapping(self, prefix, uri): + self._ns_contexts.append(self._current_context.copy()) + self._current_context[uri] = prefix + self._undeclared_ns_maps.append((prefix, uri)) + + def endPrefixMapping(self, prefix): + self._current_context = self._ns_contexts[-1] + del self._ns_contexts[-1] + + def startElement(self, name, attrs): + self._finish_pending_start_element() + self._write("<" + name) + for (name, value) in attrs.items(): + self._write(" %s=%s" % (name, quoteattr(value))) + if self._short_empty_elements: + self._pending_start_element = True + else: + self._write(">") + + def endElement(self, name): + if self._pending_start_element: + self._write("/>") + self._pending_start_element = False + else: + self._write("" % name) + + def startElementNS(self, name, qname, attrs): + self._finish_pending_start_element() + self._write("<" + self._qname(name)) + for prefix, uri in self._undeclared_ns_maps: + if prefix: + self._write(' xmlns:%s="%s"' % (prefix, uri)) + else: + self._write(' xmlns="%s"' % uri) + self._undeclared_ns_maps = [] + for (name, value) in attrs.items(): + self._write(" %s=%s" % (self._qname(name), quoteattr(value))) + if self._short_empty_elements: + self._pending_start_element = True + else: + self._write(">") + + def endElementNS(self, name, qname): + if self._pending_start_element: + self._write("/>") + self._pending_start_element = False + else: + self._write("" % self._qname(name)) + + def characters(self, content): + if content: + self._finish_pending_start_element() + if not isinstance(content, str): + content = str(content, self._encoding) + self._write(escape(content)) + + def ignorableWhitespace(self, content): + if content: + self._finish_pending_start_element() + if not isinstance(content, str): + content = str(content, self._encoding) + self._write(content) + + def processingInstruction(self, target, data): + self._finish_pending_start_element() + self._write("" % (target, data)) + + +class XMLFilterBase(xmlreader.XMLReader): + def __init__(self, parent=None): + xmlreader.XMLReader.__init__(self) + self._parent = parent + + def error(self, exception): + self._err_handler.error(exception) + + def fatalError(self, exception): + self._err_handler.fatalError(exception) + + def warning(self, exception): + self._err_handler.warning(exception) + + def setDocumentLocator(self, locator): + self._cont_handler.setDocumentLocator(locator) + + def startDocument(self): + self._cont_handler.startDocument() + + def endDocument(self): + self._cont_handler.endDocument() + + def startPrefixMapping(self, prefix, uri): + self._cont_handler.startPrefixMapping(prefix, uri) + + def endPrefixMapping(self, prefix): + self._cont_handler.endPrefixMapping(prefix) + + def startElement(self, name, attrs): + self._cont_handler.startElement(name, attrs) + + def endElement(self, name): + self._cont_handler.endElement(name) + + def startElementNS(self, name, qname, attrs): + self._cont_handler.startElementNS(name, qname, attrs) + + def endElementNS(self, name, qname): + self._cont_handler.endElementNS(name, qname) + + def characters(self, content): + self._cont_handler.characters(content) + + def ignorableWhitespace(self, chars): + self._cont_handler.ignorableWhitespace(chars) + + def processingInstruction(self, target, data): + self._cont_handler.processingInstruction(target, data) + + def skippedEntity(self, name): + self._cont_handler.skippedEntity(name) + + def notationDecl(self, name, publicId, systemId): + self._dtd_handler.notationDecl(name, publicId, systemId) + + def unparsedEntityDecl(self, name, publicId, systemId, ndata): + self._dtd_handler.unparsedEntityDecl(name, publicId, systemId, ndata) + + def resolveEntity(self, publicId, systemId): + return self._ent_handler.resolveEntity(publicId, systemId) + + def parse(self, source): + self._parent.setContentHandler(self) + self._parent.setErrorHandler(self) + self._parent.setEntityResolver(self) + self._parent.setDTDHandler(self) + self._parent.parse(source) + + def setLocale(self, locale): + self._parent.setLocale(locale) + + def getFeature(self, name): + return self._parent.getFeature(name) + + def setFeature(self, name, state): + self._parent.setFeature(name, state) + + def getProperty(self, name): + return self._parent.getProperty(name) + + def setProperty(self, name, value): + self._parent.setProperty(name, value) + + def getParent(self): + return self._parent + + def setParent(self, parent): + self._parent = parent + + +def prepare_input_source(source, base=""): + """An InputSource for a system id, a path or a file object. A system id + names a local file; URLs are not fetched.""" + if isinstance(source, _os.PathLike): + source = _os.fspath(source) + if isinstance(source, str): + source = xmlreader.InputSource(source) + elif hasattr(source, "read"): + f = source + source = xmlreader.InputSource() + if isinstance(f.read(0), str): + source.setCharacterStream(f) + else: + source.setByteStream(f) + if hasattr(f, "name") and isinstance(f.name, str): + source.setSystemId(f.name) + if source.getCharacterStream() is None and source.getByteStream() is None: + sysid = source.getSystemId() + basehead = _os.path.dirname(_os.path.normpath(base)) + sysidfilename = _os.path.join(basehead, sysid) + if _os.path.isfile(sysidfilename): + source.setSystemId(sysidfilename) + f = open(sysidfilename, "rb") + else: + f = open(sysid, "rb") + source.setByteStream(f) + return source diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/xml/sax/xmlreader.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/xml/sax/xmlreader.py new file mode 100644 index 00000000000..c645352a723 --- /dev/null +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/xml/sax/xmlreader.py @@ -0,0 +1,230 @@ +# Copyright (c) 2001 Python Software Foundation; All Rights Reserved +# Licensed under the Python Software Foundation License Version 2; the full +# text is in maven/python-transpiler/third-party/cpython/LICENSE.txt. +# +# Derived from CPython's Lib/xml/sax/xmlreader.py. Changes: rewritten for the Codename One +# Python runtime, trimmed to what the transpiler supports and reorganised; +# the C accelerators and platform-specific branches are left out. +"""xml.sax.xmlreader: XMLReader, IncrementalParser, InputSource and the +attribute collections.""" + +from xml.sax import handler +from xml.sax._exceptions import SAXNotRecognizedException, SAXNotSupportedException + + +class XMLReader: + def __init__(self): + self._cont_handler = handler.ContentHandler() + self._dtd_handler = handler.DTDHandler() + self._ent_handler = handler.EntityResolver() + self._err_handler = handler.ErrorHandler() + + def parse(self, source): + raise NotImplementedError("This method must be implemented!") + + def getContentHandler(self): + return self._cont_handler + + def setContentHandler(self, handler): + self._cont_handler = handler + + def getDTDHandler(self): + return self._dtd_handler + + def setDTDHandler(self, handler): + self._dtd_handler = handler + + def getEntityResolver(self): + return self._ent_handler + + def setEntityResolver(self, resolver): + self._ent_handler = resolver + + def getErrorHandler(self): + return self._err_handler + + def setErrorHandler(self, handler): + self._err_handler = handler + + def setLocale(self, locale): + raise SAXNotSupportedException("Locale support not implemented") + + def getFeature(self, name): + raise SAXNotRecognizedException("Feature '%s' not recognized" % name) + + def setFeature(self, name, state): + raise SAXNotRecognizedException("Feature '%s' not recognized" % name) + + def getProperty(self, name): + raise SAXNotRecognizedException("Property '%s' not recognized" % name) + + def setProperty(self, name, value): + raise SAXNotRecognizedException("Property '%s' not recognized" % name) + + +class IncrementalParser(XMLReader): + def __init__(self, bufsize=2 ** 16): + self._bufsize = bufsize + XMLReader.__init__(self) + + def parse(self, source): + from xml.sax import saxutils + source = saxutils.prepare_input_source(source) + self.prepareParser(source) + file = source.getCharacterStream() + if file is None: + file = source.getByteStream() + buffer = file.read(self._bufsize) + while buffer: + self.feed(buffer) + buffer = file.read(self._bufsize) + self.close() + + def feed(self, data): + raise NotImplementedError("This method must be implemented!") + + def prepareParser(self, source): + raise NotImplementedError("prepareParser must be overridden!") + + def close(self): + raise NotImplementedError("This method must be implemented!") + + def reset(self): + raise NotImplementedError("This method must be implemented!") + + +class Locator: + def getColumnNumber(self): + return -1 + + def getLineNumber(self): + return -1 + + def getPublicId(self): + return None + + def getSystemId(self): + return None + + +class InputSource: + def __init__(self, system_id=None): + self.__system_id = system_id + self.__public_id = None + self.__encoding = None + self.__bytefile = None + self.__charfile = None + + def setPublicId(self, public_id): + self.__public_id = public_id + + def getPublicId(self): + return self.__public_id + + def setSystemId(self, system_id): + self.__system_id = system_id + + def getSystemId(self): + return self.__system_id + + def setEncoding(self, encoding): + self.__encoding = encoding + + def getEncoding(self): + return self.__encoding + + def setByteStream(self, bytefile): + self.__bytefile = bytefile + + def getByteStream(self): + return self.__bytefile + + def setCharacterStream(self, charfile): + self.__charfile = charfile + + def getCharacterStream(self): + return self.__charfile + + +class AttributesImpl: + def __init__(self, attrs): + self._attrs = attrs + + def getLength(self): + return len(self._attrs) + + def getType(self, name): + return "CDATA" + + def getValue(self, name): + return self._attrs[name] + + def getValueByQName(self, name): + return self._attrs[name] + + def getNameByQName(self, name): + if name not in self._attrs: + raise KeyError(name) + return name + + def getQNameByName(self, name): + if name not in self._attrs: + raise KeyError(name) + return name + + def getNames(self): + return list(self._attrs.keys()) + + def getQNames(self): + return list(self._attrs.keys()) + + def __len__(self): + return len(self._attrs) + + def __getitem__(self, name): + return self._attrs[name] + + def keys(self): + return list(self._attrs.keys()) + + def __contains__(self, name): + return name in self._attrs + + def get(self, name, alternative=None): + return self._attrs.get(name, alternative) + + def copy(self): + return self.__class__(self._attrs) + + def items(self): + return list(self._attrs.items()) + + def values(self): + return list(self._attrs.values()) + + +class AttributesNSImpl(AttributesImpl): + def __init__(self, attrs, qnames): + self._attrs = attrs + self._qnames = qnames + + def getValueByQName(self, name): + for nsname, qname in self._qnames.items(): + if qname == name: + return self._attrs[nsname] + raise KeyError(name) + + def getNameByQName(self, name): + for nsname, qname in self._qnames.items(): + if qname == name: + return nsname + raise KeyError(name) + + def getQNameByName(self, name): + return self._qnames[name] + + def getQNames(self): + return list(self._qnames.values()) + + def copy(self): + return self.__class__(self._attrs, self._qnames) diff --git a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/zipfile.py b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/zipfile.py index c2c4cd6e21c..f02caa67383 100644 --- a/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/zipfile.py +++ b/maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/zipfile.py @@ -388,7 +388,18 @@ def _read_entry(self, zinfo): off = zinfo.header_offset if data[off:off + 4] != _LOCAL: raise BadZipFile("Bad magic number for file header") + lflags = struct.unpack(" members(Node.Module m, String cls) { + List out = new ArrayList(); + for (Node.Stmt s : m.body) { + if (s instanceof Node.ClassDef && cls.equals(((Node.ClassDef) s).name)) { + for (Node.Stmt b : ((Node.ClassDef) s).body) { + out.add(b.getClass().getSimpleName() + + (b instanceof Node.FunctionDef ? ":" + ((Node.FunctionDef) b).name : "")); + } + } + } + return out; + } + + private static Map program(String user) { + Map t = new LinkedHashMap(); + t.put("openpyxl/descriptors/base.py", Parser.parse(BASE, "openpyxl/descriptors/base.py")); + t.put("openpyxl/x.py", Parser.parse(user, "openpyxl/x.py")); + return t; + } + + @Test + void literalAliasesBecomePropertiesAndMethodsGo() { + Map t = program("from openpyxl.descriptors import Alias\n" + + "class C:\n u = Alias('underline')\n"); + AliasLowering.rewrite(t); + assertEquals("[FunctionDef:u, FunctionDef:u]", members(t.get("openpyxl/x.py"), "C").toString()); + assertEquals("[FunctionDef:__init__]", members(t.get("openpyxl/descriptors/base.py"), "Alias").toString()); + } + + @Test + void computedAliasKeepsMethods() { + Map t = program("from openpyxl.descriptors import Alias\n" + + "N = 'underline'\nclass C:\n u = Alias(N)\n"); + AliasLowering.rewrite(t); + assertEquals("[Assign]", members(t.get("openpyxl/x.py"), "C").toString()); + assertEquals(3, members(t.get("openpyxl/descriptors/base.py"), "Alias").size()); + } +} diff --git a/maven/python-transpiler/src/test/java/com/codename1/python/transpiler/ArgArrayFreeCallsTest.java b/maven/python-transpiler/src/test/java/com/codename1/python/transpiler/ArgArrayFreeCallsTest.java new file mode 100644 index 00000000000..1aa14e11d73 --- /dev/null +++ b/maven/python-transpiler/src/test/java/com/codename1/python/transpiler/ArgArrayFreeCallsTest.java @@ -0,0 +1,121 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.python.transpiler; + +import com.codename1.python.runtime.Builtins; +import com.codename1.python.runtime.Py; +import com.codename1.python.runtime.PyFunction; +import com.codename1.python.runtime.PyInt; +import com.codename1.python.runtime.PyBuiltin; +import com.codename1.python.runtime.PyModule; +import org.junit.jupiter.api.Test; + +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/// The calls a measured application makes hundreds of thousands of times must +/// not allocate an argument array. A builtin whose fixed-arity slot is empty +/// falls back to `call(Object[])`, which builds one per call: nothing fails, the +/// program is simply slower and the garbage collector busier. This holds every +/// call shape the llm hero app was measured making to a builtin to a fixed +/// slot, so a refactor that drops one fails here instead of in a benchmark. +class ArgArrayFreeCallsTest { + private static final String[] FIELDS = {"one", "two", "three", "four", "five", "six", "seven"}; + + /// module, name, arity: the shapes counted on the llm benchmark. + private static final Object[][] HOT = { + {"_cn1sql", "plain", 1}, {"_cn1sql", "run", 4}, {"_cn1sql", "plan", 7}, + {"_cn1sql", "begin", 1}, {"_cn1sql", "commit", 1}, + {"_cn1hash", "new", 5}, + {"_cn1json", "encode", 2}, + {"builtins", "zip", 2}, {"builtins", "iter", 1}, {"builtins", "any", 1}, + {"builtins", "all", 1}, {"builtins", "sorted", 1}, {"builtins", "enumerate", 1}, + {"builtins", "enumerate", 2}, + }; + + @Test + void hotBuiltinsHaveFixedArityPaths() throws ReflectiveOperationException { + List missing = new ArrayList<>(); + for (Object[] h : HOT) { + String module = (String) h[0]; + String name = (String) h[1]; + int arity = (Integer) h[2]; + Object f = "builtins".equals(module) ? Builtins.lookup(name) : PyModule.load(module).getAttrOrNull(name); + if (!(f instanceof PyBuiltin)) { + missing.add(module + "." + name + " is not a builtin"); + continue; + } + Field slot = PyBuiltin.class.getDeclaredField(FIELDS[arity - 1]); + slot.setAccessible(true); + if (slot.get(f) == null) { + missing.add(module + "." + name + "/" + arity); + } + } + assertTrue(missing.isEmpty(), "calls that would allocate an argument array: " + missing); + } + + /// A Python function called positionally binds into its reused slot array + /// for every shape that needs no keyword matching. Each case is checked by + /// what its body received, and the whole set by the runtime's count of + /// calls that had to build an argument array instead. + @Test + void positionalCallsOfEveryParameterShapeBuildNoArray() { + Object one = PyInt.of(1); + Object two = PyInt.of(2); + Object dflt = PyInt.of(9); + long before = Py.argArrayFallbacks(); + // def f(a, b, c=9, d=9, e=9, f=9, g=9, h=9): eight parameters, past the + // fixed-arity bodies. + Object[] eight = {dflt, dflt, dflt, dflt, dflt, dflt}; + PyFunction many = fn(new String[] {"a", "b", "c", "d", "e", "f", "g", "h"}, 8, false, 0, false, eight, null); + assertEquals("[1, 2, 9, 9, 9, 9, 9, 9]", Py.toRepr(many.call2(one, two))); + // def f(self, x, *, strict=9) + PyFunction kwOnly = fn(new String[] {"self", "x", "strict"}, 2, false, 1, false, new Object[0], + new Object[] {dflt}); + assertEquals("[1, 2, 9]", Py.toRepr(kwOnly.call2(one, two))); + // def f(a, *args, strict=9): no extra positional + PyFunction star = fn(new String[] {"a", "args", "strict"}, 1, true, 1, false, new Object[0], + new Object[] {dflt}); + assertEquals("[1, (), 9]", Py.toRepr(star.call1(one))); + // def f(self, name, **kwargs) + PyFunction kw = fn(new String[] {"self", "name", "kwargs"}, 2, false, 0, true, new Object[0], null); + assertEquals("[1, 2, {}]", Py.toRepr(kw.call2(one, two))); + // def f(a, b=9, *args, c=9, **kw) + PyFunction all = fn(new String[] {"a", "b", "args", "c", "kw"}, 2, true, 1, true, new Object[] {dflt}, + new Object[] {dflt}); + assertEquals("[1, 9, (), 9, {}]", Py.toRepr(all.call1(one))); + assertEquals(before, Py.argArrayFallbacks(), "a positional call built an argument array"); + } + + /// A function whose body answers the slots it was given, as a list. + private static PyFunction fn(String[] params, int positional, boolean varArgs, int kwOnly, boolean varKw, + Object[] defaults, Object[] kwDefaults) { + return new PyFunction("f", params, positional, varArgs, kwOnly, varKw, defaults, kwDefaults, + (Object[] a) -> Py.list(a.clone())); + } +} diff --git a/maven/python-transpiler/src/test/java/com/codename1/python/transpiler/ConformanceTest.java b/maven/python-transpiler/src/test/java/com/codename1/python/transpiler/ConformanceTest.java index 3460606fda2..9eb44c8f65d 100644 --- a/maven/python-transpiler/src/test/java/com/codename1/python/transpiler/ConformanceTest.java +++ b/maven/python-transpiler/src/test/java/com/codename1/python/transpiler/ConformanceTest.java @@ -106,8 +106,16 @@ private static void run(Path program) throws Exception { } if (Files.isDirectory(program)) { try (Stream s = Files.walk(program)) { - for (Path p : s.filter(x -> x.toString().endsWith(".py")).collect(Collectors.toList())) { + for (Path p : s.filter(x -> x.toString().endsWith(".py") + || com.codename1.python.transpiler.codegen.Jinja2Lowering.isTemplateFile( + program.relativize(x).toString().replace(File.separatorChar, '/'))) + .collect(Collectors.toList())) { String rel = program.relativize(p).toString().replace(File.separatorChar, '/'); + if (!rel.endsWith(".py")) { + // A template jinja2's loaders read, as the build passes it. + sources.put(rel, read(p)); + continue; + } if (natives.containsKey(rel.substring(0, rel.length() - 3).replace('/', '.'))) { continue; } @@ -155,10 +163,52 @@ private static void run(String stem, Map sources, boolean http, boolean client = stem.startsWith("pilclient_"); List classPath = new ArrayList(); classPath.add(new File(core)); + // The runtime too, as an application has it: the build then leaves + // out what the program does not reach, and every program here runs + // without it. + classPath.add(new File(runtime)); if (backend != null) { classPath.add(new File(backend)); } - for (Map.Entry e : PythonTranspiler.transpile(sources, "main", classPath, natives).entrySet()) { + // A program written to exercise runtime reflection cannot compile in + // strict mode. Its `.strict` file lists the refusals, one per line + // (`module:line` and what was refused), and the build must fail with + // exactly those: one accepted silently, or refused differently, fails + // here. The `.out` beside it stays CPython's output, for the day the + // construct gets a compliant lowering. + Path strict = ROOT.resolve(stem + ".strict"); + if (Files.isRegularFile(strict)) { + IllegalStateException e = org.junit.jupiter.api.Assertions.assertThrows(IllegalStateException.class, + () -> PythonTranspiler.transpile(sources, "main", classPath, natives), + "strict mode accepted a program it must refuse"); + String[] lines = String.valueOf(e.getMessage()).split("\n"); + assertTrue(lines[0].startsWith("cn1.python.strict: "), e.getMessage()); + List actual = new ArrayList(); + for (int i = 1; i < lines.length; i++) { + actual.add(lines[i].trim()); + } + java.util.Collections.sort(actual); + List expected = new ArrayList(); + for (String l : Files.readAllLines(strict, StandardCharsets.UTF_8)) { + if (!l.trim().isEmpty()) { + expected.add(l.trim()); + } + } + java.util.Collections.sort(expected); + assertEquals(String.join("\n", expected), String.join("\n", actual), "strict refusals differ"); + return; + } + Map generated = PythonTranspiler.transpile(sources, "main", classPath, natives); + if ("liveness_".equals(stem)) { + // What nothing live imports is left out: neither emitted nor + // registered. + for (String k : generated.keySet()) { + if (k.contains("unused")) { + throw new AssertionError("a module nothing imports was emitted: " + k); + } + } + } + for (Map.Entry e : generated.entrySet()) { Path f = gen.resolve(e.getKey()); Files.createDirectories(f.getParent()); Files.write(f, e.getValue().getBytes(StandardCharsets.US_ASCII)); @@ -234,6 +284,10 @@ private static void run(String stem, Map sources, boolean http, } } catch (InvocationTargetException e) { failure = String.valueOf(e.getCause()); + if (System.getProperty("conformance.only") != null) { + // One program asked for by name: the whole trace. + e.getCause().printStackTrace(savedErr); + } if (!failure.startsWith("com.codename1.python.runtime.PyException")) { // A Java failure: name the frames that recur, which is // where a runaway recursion is. diff --git a/maven/python-transpiler/src/test/java/com/codename1/python/transpiler/DirectivesTest.java b/maven/python-transpiler/src/test/java/com/codename1/python/transpiler/DirectivesTest.java new file mode 100644 index 00000000000..d3d491b75b3 --- /dev/null +++ b/maven/python-transpiler/src/test/java/com/codename1/python/transpiler/DirectivesTest.java @@ -0,0 +1,197 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.python.transpiler; + +import com.codename1.python.transpiler.api.PythonSyntaxError; +import com.codename1.python.transpiler.api.PythonTranspiler; +import org.junit.jupiter.api.Test; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/// What a build leaves out, and how `cn1-python.properties` overrides it: +/// code the program does not reach is not compiled, code it reaches that +/// cannot be translated is a build error naming every place at once, and +/// `remove=` / `replace=` take a function out by name, however deep the +/// package it is in. +class DirectivesTest { + // No function here has a name the runtime's own classes hold as a + // string: one that did would be kept, as something Java may look up. + private static final String TOOLS = "def run_code(text, env=None):\n return eval(text, env)\n\n" + + "def drop_everything(x):\n exec(x)\n\n" + + "class Box:\n def load_text(self, text):\n return eval(text)\n\n" + + "def spread(text, *rest, flag=False, **more):\n return text\n\n" + + "def fine(a):\n return a + 1\n"; + + private static Map program(String main, String directives) { + Map sources = new TreeMap(); + sources.put("pkg/__init__.py", ""); + sources.put("pkg/tools.py", TOOLS); + sources.put("main.py", main); + if (directives != null) { + sources.put("cn1-python.properties", directives); + } + return sources; + } + + /// The runtime, as an application's class path has it: what the + /// runtime may look up by name is what keeps a function nothing calls, + /// and without the runtime to read nothing is left out at all. + private static List classPath() { + List cp = new ArrayList(); + try { + cp.add(new File(com.codename1.python.runtime.Py.class.getProtectionDomain().getCodeSource() + .getLocation().toURI())); + } catch (java.net.URISyntaxException e) { + throw new IllegalStateException(e); + } + return cp; + } + + private static final String CALLS_ALL = "from pkg import tools\nprint(tools.fine(1))\n" + + "print(tools.run_code('1'))\nprint(tools.Box().load_text('x'))\ntools.drop_everything('pass')\n"; + + @Test + void everyReachedUseIsNamedInOneError() { + PythonSyntaxError e = assertThrows(PythonSyntaxError.class, + () -> PythonTranspiler.transpile(program(CALLS_ALL, null), "main", classPath())); + assertEquals("pkg/tools.py", e.file); + assertEquals(2, e.line); + assertTrue(e.reason.contains("pkg/tools.py:2:"), e.reason); + assertTrue(e.reason.contains("pkg/tools.py:5:"), e.reason); + assertTrue(e.reason.contains("pkg/tools.py:9:"), e.reason); + assertTrue(e.reason.contains("remove=pkg.tools.Box.load_text,pkg.tools.drop_everything,pkg.tools.run_code"), e.reason); + assertTrue(e.reason.contains("replace="), e.reason); + } + + @Test + void codeNothingReachesIsLeftOut() { + Map out = PythonTranspiler.transpile( + program("from pkg import tools\nprint(tools.fine(1))\n", null), "main", classPath()); + String java = module(out, "pkg.tools"); + // A top-level function nothing reaches is not compiled at all + // (Liveness); keep= is what brings it back. + assertFalse(java.contains("run_code"), "the unreached functions are left out"); + assertTrue(java.contains("fine"), "the reached one is not"); + } + + @Test + void keepCompilesWhatNothingReaches() { + PythonSyntaxError e = assertThrows(PythonSyntaxError.class, () -> PythonTranspiler.transpile( + program("from pkg import tools\nprint(tools.fine(1))\n", "keep=pkg.tools.drop_everything\n"), "main", + classPath())); + assertTrue(e.reason.contains("exec() in pkg.tools.drop_everything"), e.reason); + assertFalse(e.reason.contains("run_code"), e.reason); + } + + @Test + void removeLeavesAFunctionOutByName() { + Map out = PythonTranspiler.transpile(program(CALLS_ALL, + "# everything that runs text\nremove=pkg.tools.drop_everything, pkg.tools.run_code\nremove=pkg.tools.Box.load_text\n"), + "main", classPath()); + String java = module(out, "pkg.tools"); + assertTrue(java.contains("pkg.tools.drop_everything was left out of this build (remove= in cn1-python.properties)")); + assertTrue(java.contains("pkg.tools.Box.load_text was left out of this build")); + for (String k : out.keySet()) { + assertFalse(k.contains("/ext/"), "a removal needs no Java: " + k); + } + } + + @Test + void removeTakesAClass() { + String java = module(PythonTranspiler.transpile(program(CALLS_ALL, + "remove=pkg.tools.Box,pkg.tools.drop_everything,pkg.tools.run_code\n"), "main", classPath()), "pkg.tools"); + assertTrue(java.contains("pkg.tools.Box.load_text was left out of this build (remove=pkg.tools.Box in"), java); + } + + @Test + void removeTakesAModuleAndAPackage() { + String java = module(PythonTranspiler.transpile(program(CALLS_ALL, "remove=pkg.tools\n"), "main", + classPath()), "pkg.tools"); + assertTrue(java.contains("pkg.tools was left out of this build (remove=pkg.tools in"), java); + assertFalse(java.contains("load_text"), "nothing of the module is compiled"); + java = module(PythonTranspiler.transpile(program(CALLS_ALL, "remove=pkg\n"), "main", classPath()), + "pkg.tools"); + assertTrue(java.contains("pkg.tools was left out of this build (remove=pkg in"), java); + } + + @Test + void aNameThatIsNothingIsAnError() { + PythonSyntaxError e = assertThrows(PythonSyntaxError.class, () -> PythonTranspiler.transpile( + program(CALLS_ALL, "remove=pkg.tools.Missing\n"), "main", classPath())); + assertTrue(e.reason.contains("is not a function, a class, a module or a package"), e.reason); + } + + @Test + void replaceGeneratesTheJavaToFillIn() { + Map out = PythonTranspiler.transpile(program(CALLS_ALL, + "remove=pkg.tools.drop_everything\nreplace=pkg.tools.run_code,pkg.tools.Box.load_text\nreplace=pkg.tools.spread\n"), "main", classPath()); + String shim = out.get("com/codename1/python/ext/PkgToolsShims.java"); + assertNotNull(shim, out.keySet().toString()); + assertTrue(shim.contains("NativeModule.replace(\"pkg.tools.run_code\""), shim); + assertTrue(shim.contains("NativeModule.replace(\"pkg.tools.Box.load_text\""), shim); + assertTrue(shim.contains("// args: text, env"), shim); + assertTrue(shim.contains("// args: self, text"), shim); + assertTrue(shim.contains("// args: text, rest (a tuple), flag, more (a dict)"), shim); + assertTrue(shim.contains("NativeModule.notReplaced(\"pkg.tools.run_code\")"), shim); + boolean installed = false; + for (Map.Entry e : out.entrySet()) { + installed |= e.getKey().endsWith("/PythonModules.java") + && e.getValue().contains("com.codename1.python.ext.PkgToolsShims.install()"); + } + assertTrue(installed, "the program installs the replacements before any module runs"); + assertTrue(module(out, "pkg.tools").contains("dyn(\"__cn1_replaced__\")), \"pkg.tools.run_code\"")); + } + + @Test + void aNameThatIsNoFunctionIsAnError() { + PythonSyntaxError e = assertThrows(PythonSyntaxError.class, () -> PythonTranspiler.transpile( + program(CALLS_ALL, "remove=pkg.tools.no_such\n"), "main", classPath())); + assertTrue(e.getMessage().contains("pkg.tools.no_such"), e.getMessage()); + e = assertThrows(PythonSyntaxError.class, () -> PythonTranspiler.transpile( + program(CALLS_ALL, "omit=pkg.tools.drop_everything\n"), "main", classPath())); + assertEquals("cn1-python.properties", e.file); + assertEquals(1, e.line); + } + + /// The Java of the module `name`. + private static String module(Map out, String name) { + String file = "/py_" + name.replace(".", "$2e") + ".java"; + for (Map.Entry e : out.entrySet()) { + if (e.getKey().endsWith(file)) { + return e.getValue(); + } + } + throw new AssertionError("no " + file + " among " + out.keySet()); + } +} diff --git a/maven/python-transpiler/src/test/java/com/codename1/python/transpiler/JvmSql.java b/maven/python-transpiler/src/test/java/com/codename1/python/transpiler/JvmSql.java index 2bd58e485a8..d5f77cba643 100644 --- a/maven/python-transpiler/src/test/java/com/codename1/python/transpiler/JvmSql.java +++ b/maven/python-transpiler/src/test/java/com/codename1/python/transpiler/JvmSql.java @@ -47,7 +47,12 @@ public JvmSql(String root) { @Override public PySql.Connection open(String name) throws IOException { String url = ":memory:".equals(name) || name.isEmpty() ? "jdbc:sqlite::memory:" - : "jdbc:sqlite:" + (new File(name).isAbsolute() ? name : new File(root, name).getPath()); + : "jdbc:sqlite:" + (new File(name).isAbsolute() + // An absolute path is one of the program's own, which + // JvmFileSystem roots at the parent of the home directory: + // the database has to be where os.mkdir put its directory. + ? new File(new File(root).getParentFile(), name).getPath() + : new File(root, name).getPath()); try { return new Conn(new org.sqlite.JDBC().connect(url, new Properties())); } catch (SQLException e) { @@ -80,8 +85,14 @@ public Result run(String sql, Object[] params, boolean query) throws IOException st.setString(i + 1, p.toString()); } } + // A query word may still return nothing (PRAGMA x=on), which + // executeQuery refuses; execute() answers whether rows came. + if (query && !st.execute()) { + r.changes = st.getUpdateCount(); + return r; + } if (query) { - try (ResultSet rs = st.executeQuery()) { + try (ResultSet rs = st.getResultSet()) { ResultSetMetaData md = rs.getMetaData(); int n = md.getColumnCount(); r.columns = new String[n]; @@ -143,5 +154,47 @@ public void close() throws IOException { throw new IOException(e.getMessage(), e); } } + + @Override + public boolean createFunction(String name, int nargs, java.util.function.Function body) throws IOException { + try { + org.sqlite.Function.create(c, name, new org.sqlite.Function() { + @Override + protected void xFunc() throws SQLException { + Object[] args = new Object[args()]; + for (int i = 0; i < args.length; i++) { + args[i] = value_type(i) == org.sqlite.core.Codes.SQLITE_NULL ? null + : value_type(i) == org.sqlite.core.Codes.SQLITE_INTEGER ? Long.valueOf(value_long(i)) + : value_type(i) == org.sqlite.core.Codes.SQLITE_FLOAT ? Double.valueOf(value_double(i)) + : value_type(i) == org.sqlite.core.Codes.SQLITE_BLOB ? value_blob(i) : value_text(i); + } + Object v; + try { + v = body.apply(args); + } catch (RuntimeException e) { + // SQLite reports a failed function as the statement's error, + // in CPython's words. error() sets that message; a thrown + // SQLException would reach SQLite as its toString(). + error("user-defined function raised exception"); + return; + } + if (v == null) { + result(); + } else if (v instanceof Long) { + result(((Long) v).longValue()); + } else if (v instanceof Double) { + result(((Double) v).doubleValue()); + } else if (v instanceof byte[]) { + result((byte[]) v); + } else { + result(String.valueOf(v)); + } + } + }, nargs, 0); + return true; + } catch (SQLException e) { + throw new IOException(e.getMessage(), e); + } + } } } diff --git a/maven/python-transpiler/src/test/java/com/codename1/python/transpiler/RuntimeNamesTest.java b/maven/python-transpiler/src/test/java/com/codename1/python/transpiler/RuntimeNamesTest.java new file mode 100644 index 00000000000..11c27252df5 --- /dev/null +++ b/maven/python-transpiler/src/test/java/com/codename1/python/transpiler/RuntimeNamesTest.java @@ -0,0 +1,94 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.python.transpiler; + +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.TreeSet; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/// `runtime-names.txt` must name every identifier a string literal of the +/// Java runtime spells. Infer types a method call on a value of no one type +/// by the program's methods of that name only when no runtime object can +/// answer it, and a runtime object can answer only a name its source spells; +/// a name missing from the list would type such a call too narrowly. +class RuntimeNamesTest { + @Test + void listCoversTheRuntime() throws IOException { + Path src = Paths.get("..", "python-runtime", "src", "main", "java"); + assertTrue(Files.isDirectory(src), "runtime sources not found at " + src.toAbsolutePath()); + Pattern lit = Pattern.compile("\"([A-Za-z_][A-Za-z0-9_]*)\""); + Set spelled = new TreeSet(); + List files; + try (Stream s = Files.walk(src)) { + files = s.filter(p -> p.toString().endsWith(".java")).collect(Collectors.toList()); + } + for (Path f : files) { + Matcher m = lit.matcher(new String(Files.readAllBytes(f), StandardCharsets.UTF_8)); + while (m.find()) { + spelled.add(m.group(1)); + } + } + Set listed = new HashSet(); + try (InputStream in = RuntimeNamesTest.class.getResourceAsStream( + "/com/codename1/python/transpiler/runtime-names.txt")) { + assertNotNull(in, "runtime-names.txt is missing"); + for (String l : new String(readAll(in), StandardCharsets.UTF_8).split("\n")) { + listed.add(l.trim()); + } + } + List missing = new ArrayList(); + for (String n : spelled) { + if (!listed.contains(n)) { + missing.add(n); + } + } + assertTrue(missing.isEmpty(), "add to runtime-names.txt (sorted, one per line): " + missing); + } + + private static byte[] readAll(InputStream in) throws IOException { + java.io.ByteArrayOutputStream o = new java.io.ByteArrayOutputStream(); + byte[] b = new byte[8192]; + for (int n = in.read(b); n > 0; n = in.read(b)) { + o.write(b, 0, n); + } + return o.toByteArray(); + } +} diff --git a/maven/python-transpiler/src/test/java/com/codename1/python/transpiler/TypedShapeTest.java b/maven/python-transpiler/src/test/java/com/codename1/python/transpiler/TypedShapeTest.java new file mode 100644 index 00000000000..5c38f5e18d8 --- /dev/null +++ b/maven/python-transpiler/src/test/java/com/codename1/python/transpiler/TypedShapeTest.java @@ -0,0 +1,135 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.python.transpiler; + +import com.codename1.python.transpiler.api.PythonTranspiler; +import org.junit.jupiter.api.Test; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; +import java.util.regex.Pattern; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/// The shape of the typed code for patterns the hero apps were measured on. +/// Each of these is an optimization whose loss changes no output: the +/// program still runs, through the generic path, only slower. The +/// conformance programs check what the code answers; this checks that the +/// fast form is still the one emitted. +class TypedShapeTest { + + private static String main(String program) throws Exception { + Map sources = new TreeMap(); + sources.put("main.py", program); + List classPath = new ArrayList(); + classPath.add(new File(location(com.codename1.io.Util.class))); + classPath.add(new File(location(com.codename1.python.runtime.Py.class))); + Map out = PythonTranspiler.transpile(sources, "main", classPath, + new TreeMap()); + for (Map.Entry e : out.entrySet()) { + if (e.getKey().endsWith("/py_main.java")) { + return e.getValue(); + } + } + throw new AssertionError("no py_main.java among " + out.keySet()); + } + + /// The typed method whose name ends with `tail`, through the next + /// method of the class. + private static String typedBody(String j, String tail) { + int at = j.indexOf("static "); + while (at >= 0) { + int eol = j.indexOf('\n', at); + String head = j.substring(at, eol); + if (head.contains(" TM_") && head.contains(tail)) { + int end = j.indexOf("\n static ", eol); + return j.substring(at, end < 0 ? j.length() : end); + } + at = j.indexOf("static ", eol); + } + throw new AssertionError("no typed method ending " + tail); + } + + private static String location(Class c) throws Exception { + return new File(c.getProtectionDomain().getCodeSource().getLocation().toURI()).getPath(); + } + + @Test + void constantBoolIsMarked() throws Exception { + String j = main("class T:\n def __bool__(self):\n \"\"\"Always.\"\"\"\n return True\n\n" + + "print(bool(T()))\n"); + assertTrue(j.contains(".constant(Py.TRUE)"), "a __bool__ that only returns True is marked constant"); + } + + @Test + void nextUnderStopIterationIsDirect() throws Exception { + String j = main("def first(it):\n try:\n v = next(it)\n except StopIteration:\n" + + " return None\n return v\n\nprint(first(iter([1])))\n"); + assertTrue(j.contains("Builtins.nextOrStop("), "next() in try/except StopIteration calls the runtime"); + assertFalse(j.contains("\"__cn1_next_or_stop__\""), "the desugared helper is not looked up by name"); + } + + @Test + void generatorPropertyLoopIsTyped() throws Exception { + String j = main("class Node:\n def __init__(self, name, kids):\n self.name = name\n" + + " self.kids = kids\n\n @property\n def children(self):\n" + + " return (k for k in self.kids)\n\n" + + "def names(n):\n out = []\n for c in n.children:\n out.append(c.name)\n" + + " return out\n\nprint(names(Node('r', [Node('a', []), Node('b', [])])))\n"); + assertTrue(Pattern.compile("L\\d+_Node v_c = null;").matcher(j).find(), + "the loop variable over a generator property is held typed"); + } + + @Test + void sharedKeywordCallIsVirtual() throws Exception { + String j = main("class F:\n def match(self, e, _known=False):\n return _known or e == 1\n\n" + + " def run(self, xs):\n return [x for x in xs if self.match(x, _known=False)]\n\n" + + "class G(F):\n def match(self, e, _known=False):\n return e == 2\n\n" + + "print(F().run([1, 2]), G().run([1, 2]))\n"); + String run = typedBody(j, "_F_run("); + assertTrue(run.contains(".tv_match_2("), "a keyword call every override binds alike is a typed virtual call"); + assertFalse(run.contains("callKw"), "the typed body makes no keyword call at run time"); + } + + @Test + void localNamedGlobalsKeepsModuleTyped() throws Exception { + // bs4 keeps a frame's globals in a local named `globals`; only the + // builtin itself hands the namespace out. + String src = "class Node:\n def __init__(self, name, kids):\n self.name = name\n" + + " self.kids = kids\n\n @property\n def children(self):\n" + + " return (k for k in self.kids)\n\n" + + "def names(n):\n out = []\n for c in n.children:\n out.append(c.name)\n" + + " return out\n\n" + + "def frame(d):\n globals = d\n return globals\n\n" + + "print(names(Node('r', [Node('a', []), Node('b', [])])), frame({}))\n"; + Pattern typed = Pattern.compile("L\\d+_Node v_c = null;"); + assertTrue(typed.matcher(main(src)).find(), "a local named globals leaves the module's globals stable"); + assertFalse(typed.matcher(main(src.replace("globals = d\n return globals", "return globals()"))).find(), + "the builtin itself still does not"); + } +} diff --git a/maven/python-transpiler/src/test/java/com/codename1/python/transpiler/UnsupportedTest.java b/maven/python-transpiler/src/test/java/com/codename1/python/transpiler/UnsupportedTest.java index ce92a074552..5123decec5d 100644 --- a/maven/python-transpiler/src/test/java/com/codename1/python/transpiler/UnsupportedTest.java +++ b/maven/python-transpiler/src/test/java/com/codename1/python/transpiler/UnsupportedTest.java @@ -49,13 +49,23 @@ class UnsupportedTest { {"m = __import__('os')\n", "1", "__import__()"}, {"run = eval\n", "1", "eval()"}, {"import sys\n\ndef t(*a):\n pass\n\nsys.settrace(t)\n", "6", "sys.settrace"}, - {"import sys\nprint(sys._getframe().f_lineno)\n", "2", "sys._getframe"}, {"def f():\n x = 1\n return locals()\n", "3", "locals()"}, {"x = 1\nfrom java.java.util import NoSuchList\n", "2", "no Java class java.util.NoSuchList"}, {"import java.java.util\n", "1", "import the Java classes by name"}, {"from java.java.util import *\n", "1", "imported by name"}, {"from java.java.util import ArrayList\n\nclass L(ArrayList):\n pass\n", "3", "cannot extend the Java class ArrayList"}, + // ImmutableSlots: a store outside the generated constructor. + {"class Immutable:\n __slots__ = ('_hash',)\n def __init__(self, **kw):\n pass\n" + + " def __setattr__(self, n, v):\n raise AttributeError(n)\n def __eq__(self, o):\n return True\n" + + " def __repr__(self):\n return ''\n\nclass T(Immutable):\n __slots__ = ('tag', '_hash')\n" + + " def __init__(self, tag):\n super().__init__(tag=tag)\n" + + " def retag(self, t):\n self.tag = t\n", "17", "on an immutable instance"}, + {"class Immutable:\n __slots__ = ('_hash',)\n def __init__(self, **kw):\n pass\n" + + " def __setattr__(self, n, v):\n raise AttributeError(n)\n def __eq__(self, o):\n return True\n" + + " def __repr__(self):\n return ''\n\nclass T(Immutable):\n __slots__ = ('tag', '_hash')\n" + + " def __init__(self, tag):\n super().__init__(tag=tag)\n" + + "\nt = T(1)\nt.tag = 2\n", "18", "a field of an immutable class"}, }; @TestFactory diff --git a/maven/python-transpiler/src/test/resources/conformance/accumulators.out b/maven/python-transpiler/src/test/resources/conformance/accumulators.out new file mode 100644 index 00000000000..4602c3edc05 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/accumulators.out @@ -0,0 +1,5 @@ +(9.223372036854776e+18, [1.5, 4.611686018427388e+18]) +13835058055282163715 +('abcdef', 6) +(2.5, 'TypeError') +(True, [0, 1, 2]) diff --git a/maven/python-transpiler/src/test/resources/conformance/accumulators.py b/maven/python-transpiler/src/test/resources/conformance/accumulators.py new file mode 100644 index 00000000000..0c8f9405b6e --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/accumulators.py @@ -0,0 +1,62 @@ +# Untyped locals accumulated with += / -=: a long while they hold ints, +# Python's in-place operators on whatever else they come to hold. + + +def source(i): + return [1, 2.5, "x", 2 ** 62, None][i % 5] + + +def mixed(n): + acc = 0 + seen = [] + for i in range(n): + v = source(i) + if v is None: + continue + if isinstance(v, str): + seen.append(acc) + continue + acc += v + acc -= 1 + return acc, seen + + +def overflow(): + t = 0 + for i in range(6): + t += 2 ** 62 if i % 2 == 0 else -1 + t += source(0) + return t + + +def lists(): + acc = [] + alias = acc + for i in range(3): + acc += [i] + return acc is alias, acc + + +def strings(words): + out = "" + n = 0 + for w in words: + out += w + n += len(w) + return out, n + + +def raises(): + t = 0 + t += source(1) + try: + t += "s" + except TypeError as e: + return t, "TypeError" + + +print(mixed(12)) +print(overflow()) +print(strings(["ab", "c", "def"])) +print(raises()) +print(lists()) diff --git a/maven/python-transpiler/src/test/resources/conformance/annotation_tables.out b/maven/python-transpiler/src/test/resources/conformance/annotation_tables.out new file mode 100644 index 00000000000..d9bc39af9f8 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/annotation_tables.out @@ -0,0 +1,36 @@ +Point 10 + x = int + y = str Point + tags = alias True 1 + table = alias True 2 + maybe = alias True 2 + either = alias True 2 + fn = alias True 2 + seq = alias True 1 + lit = alias True 2 + flag = alias True 2 +plain 6 + a = int + b = str + rest = bytes + key = float + more = bool + return = None +shaped 6 + a = alias True 1 + b = alias True 2 + c = alias True 3 + d = alias False 0 + e = str Point + return = alias True 2 +called 3 + a = alias True 2 + b = alias True 2 + return = alias True 2 +none 0 +True +True True +True ([, ], ) +True True +('a', 'b') (, 'x') +(, tuple[int, ...]) True diff --git a/maven/python-transpiler/src/test/resources/conformance/annotation_tables.py b/maven/python-transpiler/src/test/resources/conformance/annotation_tables.py new file mode 100644 index 00000000000..14b3cb5f398 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/annotation_tables.py @@ -0,0 +1,60 @@ +# Annotations of functions and of class bodies, read back: names, attributes, +# subscripts, unions, tuples and lists of them, constants, and a call. +import collections.abc +import typing +from typing import Callable, Optional + + +class Point: + x: int + y: "Point" + tags: list[str] + table: dict[str, tuple[int, ...]] + maybe: Optional[int] = None + either: int | None = None + fn: Callable[[int, str], bool] = None + seq: collections.abc.Sequence[int] = () + lit: typing.Literal["a", "b"] = "a" + flag: typing.Annotated[int, str("meta")] = 0 + + +def plain(a: int, b: str = "", *rest: bytes, key: float = 0.0, **more: bool) -> None: + return None + + +def shaped(a: list[int], b: dict[str, Point], c: int | str | None, d: typing.Any, e: "Point") -> tuple[int, str]: + return (1, "") + + +def called(a: typing.Annotated[int, str("x")], b: Callable[..., int] = None) -> Optional[Point]: + return None + + +def none(): + pass + + +PLAIN = (int, str, bytes, float, bool, Point) + + +def show(d): + for k, v in d.items(): + if isinstance(v, str): + print(" ", k, "= str", v) + elif v is None: + print(" ", k, "= None") + elif any(v is p for p in PLAIN): + print(" ", k, "=", v.__name__) + else: + print(" ", k, "= alias", typing.get_origin(v) is not None, len(typing.get_args(v))) + + +for owner in (Point, plain, shaped, called, none): + print(owner.__name__, len(owner.__annotations__)) + show(owner.__annotations__) +print(plain.__annotations__ is plain.__annotations__) +print(shaped.__annotations__["b"] == dict[str, Point], shaped.__annotations__["c"] == (int | str | None)) +print(Point.__annotations__["tags"] == list[str], typing.get_args(Point.__annotations__["fn"])) +print(Point.__annotations__["maybe"] == Optional[int], Point.__annotations__["either"] == (int | None)) +print(typing.get_args(Point.__annotations__["lit"]), typing.get_args(called.__annotations__["a"])) +print(typing.get_args(Point.__annotations__["table"]), shaped.__annotations__["d"] is typing.Any) diff --git a/maven/python-transpiler/src/test/resources/conformance/argparse_computed_dest.out b/maven/python-transpiler/src/test/resources/conformance/argparse_computed_dest.out new file mode 100644 index 00000000000..87aadac939d --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/argparse_computed_dest.out @@ -0,0 +1,11 @@ +usage: h [-h] [--alpha ALPHA] [--beta BETA] + +options: + -h, --help show this help message and exit + +g: + --alpha ALPHA + --beta BETA + +Namespace(fixed=None, alpha=None, beta=None, late=None) +ArgumentParser(prog='e', usage=None, description=None, formatter_class=, conflict_handler='error', add_help=True) diff --git a/maven/python-transpiler/src/test/resources/conformance/argparse_computed_dest.py b/maven/python-transpiler/src/test/resources/conformance/argparse_computed_dest.py new file mode 100644 index 00000000000..3a6f687d260 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/argparse_computed_dest.py @@ -0,0 +1,33 @@ +import argparse + +NAMES = ["alpha", "beta"] + + +def help_only(): + # Only formats help: a computed option is never stored, so it builds. + p = argparse.ArgumentParser(prog="h") + g = p.add_argument_group("g") + for n in NAMES: + g.add_argument("--" + n) + return p.format_help() + + +def parsed(argv): + p = argparse.ArgumentParser(prog="x") + p.add_argument("--fixed") + for n in NAMES: + p.add_argument("--" + n) + opts = {"dest": "late"} + p.add_argument("--late", **opts) + return p.parse_args(argv) + + +def escapes(): + p = argparse.ArgumentParser(prog="e") + p.add_argument(NAMES[0]) + return p + + +print(help_only()) +print(parsed([])) +print(escapes()) diff --git a/maven/python-transpiler/src/test/resources/conformance/argparse_computed_dest.strict b/maven/python-transpiler/src/test/resources/conformance/argparse_computed_dest.strict new file mode 100644 index 00000000000..b8553d80f16 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/argparse_computed_dest.strict @@ -0,0 +1,3 @@ +main:19 add_argument(...) whose destination the build cannot read (a computed option string or dest, *args or **kwargs) on a parser that reaches parse_args or parse_known_args; write the option strings and dest= as literals +main:21 add_argument(...) whose destination the build cannot read (a computed option string or dest, *args or **kwargs) on a parser that reaches parse_args or parse_known_args; write the option strings and dest= as literals +main:27 add_argument(...) whose destination the build cannot read (a computed option string or dest, *args or **kwargs) on a parser that reaches parse_args or parse_known_args; write the option strings and dest= as literals diff --git a/maven/python-transpiler/src/test/resources/conformance/attrs_pkg.strict b/maven/python-transpiler/src/test/resources/conformance/attrs_pkg.strict new file mode 100644 index 00000000000..fde356796b4 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/attrs_pkg.strict @@ -0,0 +1,3 @@ +main:233 attrs define(...) applied to a class built at run time cannot be lowered; decorate a class statement instead +main:348 attrs make_class builds a class at run time, which a closed-world build cannot compile; declare the class with a class statement and @define +main:350 attrs make_class builds a class at run time, which a closed-world build cannot compile; declare the class with a class statement and @define diff --git a/maven/python-transpiler/src/test/resources/conformance/attrs_static.out b/maven/python-transpiler/src/test/resources/conformance/attrs_static.out new file mode 100644 index 00000000000..cbe1c367bb6 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/attrs_static.out @@ -0,0 +1,91 @@ +Point(x=1, y=2) Point(x=3, y=0) Point(x=4, y=5) +True True False +True +lt raised TypeError '<' not supported between instances of 'Point' and 'Point' +missing raised TypeError Point.__init__() missing 1 required positional argument: 'x' +extra raised TypeError Point.__init__() takes from 2 to 3 positional arguments but 4 were given +badkw raised TypeError Point.__init__() got an unexpected keyword argument 'z' +True False +['x', 'y'] x 0 +{'x': 1, 'y': 2} (1, 2) +Point(x=10, y=2) +('x', 'y') +True True [Ver(major=1, minor=0), Ver(major=1, minor=5), Ver(major=2, minor=0)] +True False +Frozen(name='a', tags=(1, 2)) True True +frozen set raised FrozenInstanceError can't set attribute +FrozenInstanceError caught True +attr.exceptions caught +Frozen(name='z', tags=(1, 2)) Frozen(name='a', tags=(1, 2)) +WithFactory(items=[1], d={}, n=3, twice=6) WithFactory(items=[], d={}, n=5, twice=10) [] +Factory(factory=, takes_self=False) +SelfFactory(a=1, b=2) SelfFactory(a=1, b=7) +Validated(x=1, name='n', opt=None, kind='a', pos=1) +v type raised TypeError 'x' must be (got 's' that is a ). +v name raised ValueError 'name' must match regex '^[a-z]+$' ('Bad1' doesn't) +v opt ok -> Validated(x=1, name='n', opt=3, kind='a', pos=1) +v opt bad raised TypeError 'opt' must be (got 'x' that is a ). +v in raised ValueError 'kind' must be in ['a', 'b'] (got 'c') +v pos raised ValueError 'pos' must be >= 0: -1 +v pos2 raised ValueError 'pos' must be < 100: 100 +v dec raised ValueError unlucky x +set invalid raised TypeError 'x' must be (got 'q' that is a ). +set invalid2 raised ValueError unlucky x +4 +validate() raised TypeError 'x' must be (got 'zz' that is a ). +Lists(xs=[1, 2], m={}, s='ab', c=) +deep it raised TypeError 'xs' must be (got 'a' that is a ). +deep it2 raised TypeError 'xs' must be (got (1, 2) that is a ). +deep map raised TypeError 'm' must be (got 'b' that is a ). +min raised ValueError Length of 's' must be >= 1: 0 +max raised ValueError Length of 's' must be <= 3: 4 +callable raised NotCallableError 'c' must be callable (got 5 that is a ). +Converted(n=5, s=None, z=7, b=True, p=3) +Converted(n=1, s='2', z=7, b=False, p=9) +8 int +conv bad raised ValueError invalid literal for int() with base 10: 'x' +to_bool bad raised ValueError Cannot convert value to bool: 'maybe' +Kw(a=1, b=2, c=3) +kw missing raised TypeError Kw.__init__() missing 1 required keyword-only argument: 'c' +kw positional raised TypeError Kw.__init__() takes 2 positional arguments but 4 were given +AllKw(a=1, b=5) +allkw raised TypeError AllKw.__init__() takes 1 positional argument but 2 were given +Post(a=4, b=40) 40 +Priv(_hidden=1, shown=2) Priv(_hidden=5, shown=2) hidden +Opts(a=1, ignored=0, shout=X) True False +Child(a=1, c=3, b=20) ['a', 'c', 'b'] [True, False, False] +False True +{'inner': {'v': 1}, 'items': [{'v': 2}, 3], 'mapping': {'k': {'v': 4}}, 'tup': ({'v': 5}, 6)} +{'inner': Inner(v=1), 'items': [Inner(v=2), 3], 'mapping': {'k': Inner(v=4)}, 'tup': (Inner(v=5), 6)} +{'inner': {'v': 1}, 'items': [{'v': 2}, 3], 'mapping': {'k': {'v': 4}}, 'tup': ({'v': 5}, 6)} +((1,), [(2,), 3], {'k': (4,)}, ((5,), 6)) +{'inner': {'v': 1}, 'items': [{'v': 2}, 3], 'mapping': {'k': {'v': 4}}} +{'inner': {'v': 1}, 'mapping': {'k': {'v': 4}}} +{'v': 4} +(1,) (Inner(v=5), 6) +Priv(_hidden=9, shown=2) +evolve bad raised TypeError Point.__init__() got an unexpected keyword argument 'q' +fields bad raised NotAnAttrsClassError is not an attrs-decorated class. +fields inst -> (Attribute(name='x', default=NOTHING, validator=None, repr=True, eq=True, eq_key=None, order=True, order_key=None, hash=None, init=True, metadata=mappingproxy({}), type=, converter=None, kw_only=False, inherited=False, on_setattr=None, alias='x'), Attribute(name='y', default=0, validator=None, repr=True, eq=True, eq_key=None, order=True, order_key=None, hash=None, init=True, metadata=mappingproxy({}), type=, converter=None, kw_only=False, inherited=False, on_setattr=None, alias='y')) +Old(x=1, y=5, z=[]) True True True +['x', 'y', 'z', 'w'] 5 +old validator raised TypeError 'y' must be (got 'no' that is a ). +changes freely unhashable +OldFrozen(a=1, b='b') True +old frozen raised FrozenInstanceError can't set attribute +OldFrozen(a=1, b='c') +{'a': 1, 'b': 'b'} +False True +no order raised TypeError '<' not supported between instances of 'NoOrder' and 'NoOrder' +OrderBy(b=1, a=2) ['b', 'a'] +Decorated(n=2, m=3) +decorated raised ValueError neg +Auto(a=1, b=[], c=3) True +custom! True +False +_Nothing.NOTHING NOTHING False +Validated(x='not an int', name='n', opt=None, kind='a', pos=1) +False +5 6 +> +> or None> diff --git a/maven/python-transpiler/src/test/resources/conformance/attrs_static.py b/maven/python-transpiler/src/test/resources/conformance/attrs_static.py new file mode 100644 index 00000000000..eb4b08a9fd8 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/attrs_static.py @@ -0,0 +1,386 @@ +import attr +import attrs +from attrs import define, frozen, field, mutable, asdict, astuple, evolve, fields, has, validators, converters +from attrs import Factory, NOTHING +from attrs.exceptions import FrozenInstanceError + + +def show(label, fn): + try: + print(label, "->", fn()) + except Exception as e: + print(label, "raised", type(e).__name__, e.args[0] if e.args else "") + + +@define +class Point: + x: int + y: int = 0 + + +p = Point(1, 2) +print(p, Point(3), Point(y=5, x=4)) +print(p == Point(1, 2), p != Point(1, 3), p == 5) +print(Point.__hash__ is None) +show("lt", lambda: p < Point(2, 2)) +show("missing", lambda: Point()) +show("extra", lambda: Point(1, 2, 3)) +show("badkw", lambda: Point(1, z=3)) +print(has(Point), has(int)) +print([f.name for f in fields(Point)], fields(Point).x.name, fields(Point).y.default) +print(asdict(p), astuple(p)) +p.x = 10 +print(p) +print(Point.__match_args__) + + +@define(order=True) +class Ver: + major: int + minor: int = 0 + + +print(Ver(1, 2) < Ver(1, 3), Ver(2) > Ver(1, 9), sorted([Ver(2), Ver(1, 5), Ver(1)])) +print(Ver(1) <= Ver(1), Ver(1) >= Ver(2)) + + +@frozen +class Frozen: + name: str + tags: tuple = () + + +f = Frozen("a", (1, 2)) +print(f, hash(f) == hash(Frozen("a", (1, 2))), f == Frozen("a", (1, 2))) +show("frozen set", lambda: setattr(f, "name", "b")) +try: + f.name = "c" +except FrozenInstanceError as e: + print("FrozenInstanceError caught", isinstance(e, AttributeError)) +try: + f.name = "c" +except attr.exceptions.FrozenInstanceError: + print("attr.exceptions caught") +print(evolve(f, name="z"), f) + + +@define +class WithFactory: + items: list = Factory(list) + d: dict = field(factory=dict) + n: int = field(default=3) + twice: int = field(init=False) + + @twice.default + def _twice(self): + return self.n * 2 + + +a = WithFactory() +b = WithFactory(n=5) +a.items.append(1) +print(a, b, b.items) +print(Factory(list)) + + +@define +class SelfFactory: + a: int + b: int = Factory(lambda self: self.a + 1, takes_self=True) + + +print(SelfFactory(1), SelfFactory(1, 7)) + + +@define +class Validated: + x: int = field(validator=validators.instance_of(int)) + name: str = field(default="n", validator=[validators.instance_of(str), validators.matches_re("^[a-z]+$")]) + opt: object = field(default=None, validator=validators.optional(validators.instance_of(int))) + kind: str = field(default="a", validator=validators.in_(["a", "b"])) + pos: int = field(default=1, validator=[validators.ge(0), validators.lt(100)]) + + @x.validator + def _check_x(self, attribute, value): + if value == 13: + raise ValueError("unlucky " + attribute.name) + + +print(Validated(1)) +show("v type", lambda: Validated("s")) +show("v name", lambda: Validated(1, name="Bad1")) +show("v opt ok", lambda: Validated(1, opt=3)) +show("v opt bad", lambda: Validated(1, opt="x")) +show("v in", lambda: Validated(1, kind="c")) +show("v pos", lambda: Validated(1, pos=-1)) +show("v pos2", lambda: Validated(1, pos=100)) +show("v dec", lambda: Validated(13)) +v = Validated(2) +show("set invalid", lambda: setattr(v, "x", "q")) +show("set invalid2", lambda: setattr(v, "x", 13)) +v.x = 4 +print(v.x) +vv = Validated(1) +attrs.validate(vv) +object.__setattr__(vv, "x", "zz") +show("validate()", lambda: attrs.validate(vv)) + + +@define +class Lists: + xs: list = field(validator=validators.deep_iterable(validators.instance_of(int), validators.instance_of(list))) + m: dict = field(default=Factory(dict), + validator=validators.deep_mapping(validators.instance_of(str), validators.instance_of(int))) + s: str = field(default="ab", validator=[validators.min_len(1), validators.max_len(3)]) + c: object = field(default=len, validator=validators.is_callable()) + + +print(Lists([1, 2])) +show("deep it", lambda: Lists([1, "a"])) +show("deep it2", lambda: Lists((1, 2))) +show("deep map", lambda: Lists([1], {"a": "b"})) +show("min", lambda: Lists([1], s="")) +show("max", lambda: Lists([1], s="abcd")) +show("callable", lambda: Lists([1], c=5)) + + +@define +class Converted: + n: int = field(converter=int) + s: str = field(default=None, converter=converters.optional(str)) + z: int = field(default=None, converter=converters.default_if_none(7)) + b: bool = field(default="yes", converter=converters.to_bool) + p: int = field(default="3", converter=converters.pipe(str.strip, int)) + + +c = Converted("5") +print(c) +print(Converted(1, 2, None, "off", " 9 ")) +c.n = "8" +print(c.n, type(c.n).__name__) +show("conv bad", lambda: Converted("x")) +show("to_bool bad", lambda: converters.to_bool("maybe")) + + +@define +class Kw: + a: int + b: int = field(kw_only=True, default=2) + c: int = field(kw_only=True) + + +print(Kw(1, c=3)) +show("kw missing", lambda: Kw(1)) +show("kw positional", lambda: Kw(1, 2, 3)) + + +@define(kw_only=True) +class AllKw: + a: int + b: int = 5 + + +print(AllKw(a=1)) +show("allkw", lambda: AllKw(1)) + + +@define +class Post: + a: int + b: int = field(init=False) + + def __attrs_post_init__(self): + self.b = self.a * 10 + + +print(Post(4), Post(4).b) + + +@define +class Priv: + _hidden: int = 1 + shown: int = 2 + + +print(Priv(), Priv(hidden=5), fields(Priv)._hidden.alias) + + +@define +class Opts: + a: int + secret: str = field(default="s", repr=False) + ignored: int = field(default=0, eq=False) + shout: str = field(default="x", repr=lambda v: v.upper()) + + +print(Opts(1), Opts(1, ignored=3) == Opts(1, ignored=4), Opts(1, secret="q") == Opts(1)) + + +@define +class Base: + a: int + b: int = 2 + + +@define +class Child(Base): + c: int = 3 + b: int = 20 + + +print(Child(1), [f.name for f in fields(Child)], [f.inherited for f in fields(Child)]) +print(Child(1) == Base(1), Child(1) == Child(1)) + + +@define +class Inner: + v: int + + +@define +class Outer: + inner: Inner + items: list + mapping: dict + tup: tuple = () + + +o = Outer(Inner(1), [Inner(2), 3], {"k": Inner(4)}, (Inner(5), 6)) +print(asdict(o)) +print(asdict(o, recurse=False)) +print(attr.asdict(o, retain_collection_types=True)) +print(astuple(o)) +print(asdict(o, filter=lambda a, v: a.name != "tup")) +print(asdict(o, filter=attrs.filters.exclude(attrs.fields(Outer).tup, "items"))) +print(asdict(Inner(3), value_serializer=lambda inst, a, v: v + 1)) +print(evolve(o, tup=(1,)).tup, o.tup) +print(evolve(Priv(), hidden=9)) +show("evolve bad", lambda: evolve(Point(1), q=2)) +show("fields bad", lambda: fields(int)) +show("fields inst", lambda: fields(Point(1))) + + +# attr.s / attr.ib style +@attr.s +class Old(object): + x = attr.ib() + y = attr.ib(default=5, validator=attr.validators.instance_of(int)) + z = attr.ib(factory=list) + w = attr.ib(default="w", repr=False) + + +o1 = Old(1) +print(o1, o1 == Old(1), o1 < Old(2), Old(1, 2) > Old(1, 1)) +print([a.name for a in attr.fields(Old)], attr.fields(Old).y.default) +show("old validator", lambda: Old(1, "no")) +o1.x = "changes freely" +print(o1.x, hash(o1) if False else "unhashable" if Old.__hash__ is None else "hashable") + + +@attr.s(frozen=True, auto_attribs=True) +class OldFrozen: + a: int + b: str = "b" + + +of = OldFrozen(1) +print(of, hash(of) == hash(OldFrozen(1))) +show("old frozen", lambda: setattr(of, "a", 2)) +print(attr.evolve(of, b="c")) +print(attr.asdict(of)) + + +@attr.s(eq=False) +class NoEq: + a = attr.ib() + + +print(NoEq(1) == NoEq(1), hash(NoEq(1)) is not None) + + +@attr.s(order=False) +class NoOrder: + a = attr.ib() + + +show("no order", lambda: NoOrder(1) < NoOrder(2)) + + +@attr.s +class OrderBy: + b = attr.ib(default=1) + a = attr.ib(default=2) + + +print(OrderBy(), [f.name for f in attr.fields(OrderBy)]) + + +@attr.s +class Decorated: + n = attr.ib() + m = attr.ib() + + @n.validator + def _vn(self, attribute, value): + if value < 0: + raise ValueError("neg") + + @m.default + def _dm(self): + return self.n + 1 + + +print(Decorated(2)) +show("decorated", lambda: Decorated(-1)) + + +@attr.s(auto_attribs=True) +class Auto: + a: int + b: list = attr.Factory(list) + c: int = attr.ib(default=3) + + +print(Auto(1), Auto(1) == Auto(1, [], 3)) + + + +@define +class Custom: + a: int + + def __repr__(self): + return "custom!" + + def __eq__(self, other): + return True + + +print(Custom(1), Custom(1) == Custom(2)) + + +@define(repr=False, eq=False) +class Plain: + a: int + + +print(Plain(1) == Plain(1)) +print(attr.NOTHING, repr(attr.NOTHING), bool(attr.NOTHING)) + +with validators.disabled(): + print(Validated("not an int")) +print(validators.get_disabled()) + + +@define +class SetHooks: + a: int = field(default=1, on_setattr=attrs.setters.NO_OP, converter=int) + b: int = field(default=1, converter=int) + + +sh = SetHooks() +sh.a = "5" +sh.b = "6" +print(sh.a, sh.b) +print(validators.instance_of(int)) +print(repr(validators.optional(validators.instance_of(int)))) diff --git a/maven/python-transpiler/src/test/resources/conformance/attrs_value_deco.out b/maven/python-transpiler/src/test/resources/conformance/attrs_value_deco.out new file mode 100644 index 00000000000..9766475a418 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/attrs_value_deco.out @@ -0,0 +1 @@ +ok diff --git a/maven/python-transpiler/src/test/resources/conformance/attrs_value_deco.py b/maven/python-transpiler/src/test/resources/conformance/attrs_value_deco.py new file mode 100644 index 00000000000..28ed4b546f6 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/attrs_value_deco.py @@ -0,0 +1,4 @@ +import attr + +deco = attr.s +print("ok") diff --git a/maven/python-transpiler/src/test/resources/conformance/attrs_value_deco.strict b/maven/python-transpiler/src/test/resources/conformance/attrs_value_deco.strict new file mode 100644 index 00000000000..2e585e728f7 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/attrs_value_deco.strict @@ -0,0 +1 @@ +main:3 attrs s used as a value, not as a class decorator, cannot be lowered at build time; decorate each class statement with it directly diff --git a/maven/python-transpiler/src/test/resources/conformance/bound_init.out b/maven/python-transpiler/src/test/resources/conformance/bound_init.out new file mode 100644 index 00000000000..50e384d4f51 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/bound_init.out @@ -0,0 +1,15 @@ +(1, 2, 3, 'x') +(1, 5, 3, 'x') +(1, 2, 3, 'y') +(7, 2, 9, 'x') +eval a +eval c +(1, 2, 4, 'x') +(1, 2) +posonly kw rejected +too many rejected +unknown kw rejected +non-None init rejected +(4, 2, 8, 'x') +('new', 4, 8) +('new', 3, 0) diff --git a/maven/python-transpiler/src/test/resources/conformance/bound_init.py b/maven/python-transpiler/src/test/resources/conformance/bound_init.py new file mode 100644 index 00000000000..de02e624c2a --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/bound_init.py @@ -0,0 +1,57 @@ +class P: + def __init__(self, a, b=2, *, c=3, d="x"): + self.v = (a, b, c, d) + + +class Q(P): + pass + + +class PosOnly: + def __init__(self, a, /, b=1): + self.v = (a, b) + + +class BadInit: + def __init__(self): + return 5 + + +def order(tag, val): + print("eval", tag) + return val + + +print(P(1).v) +print(P(1, 5).v) +print(P(1, d="y").v) +print(P(a=7, c=9).v) +print(Q(order("a", 1), c=order("c", 4)).v) +print(PosOnly(1, b=2).v) +try: + PosOnly(a=1) +except TypeError: + print("posonly kw rejected") +try: + P(1, 2, 3) +except TypeError: + print("too many rejected") +try: + P(1, e=2) +except TypeError: + print("unknown kw rejected") +try: + BadInit() +except TypeError: + print("non-None init rejected") + + +def make(): + return P(4, c=8).v + + +print(make()) +P.__init__ = lambda self, a, b=0, *, c=0, d=0: setattr(self, "v", ("new", a, c)) +print(make()) +Q2 = Q +print(Q2(3).v) diff --git a/maven/python-transpiler/src/test/resources/conformance/builtins_lowered.out b/maven/python-transpiler/src/test/resources/conformance/builtins_lowered.out new file mode 100644 index 00000000000..f6d9e6acd71 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/builtins_lowered.out @@ -0,0 +1,33 @@ +[1, 3, 5, 9, 10] [5, 3, 9, 1] +['apple', 'fig', 'pear'] ['fig', 'pear', 'apple'] ['pear', 'fig', 'apple'] +['a', 'a', 'a', 'b', 'n', 'n'] ['a', 'b'] +(18, 1, 9, 4.5) (4.25, 0.5, 2.5, 1.42) +3 7 1.5 b +4.25 28 18.5 2 +2 4 0 2.67 10 2 +[Box(1), Box(2), Box(3)] Box(1) Box(3) +[Box(3), Box(2), Box(1)] +1359 +ValueError min() iterable argument is empty +3.5 2.5 1 int +38 +1 A +2 B +3 C +a5 +b9 +c16 +4 a x +8 b y +15 c z +cba [30, 16, 8] +X +Y +3 +x 11 +y 12 +[('x', 1), ('y', 2)] [4, 9, 17] +a True None +b False z +0 h +1 i diff --git a/maven/python-transpiler/src/test/resources/conformance/builtins_lowered.py b/maven/python-transpiler/src/test/resources/conformance/builtins_lowered.py new file mode 100644 index 00000000000..559b2695c82 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/builtins_lowered.py @@ -0,0 +1,88 @@ +# sorted, min, max, sum and round over values the runtime handles as +# primitives, and the same calls over values it does not. + + +class Box: + def __init__(self, v): + self.v = v + + def __lt__(self, other): + return self.v < other.v + + def __repr__(self): + return "Box(%d)" % self.v + + +def stats(xs): + total = sum(xs) + lo = min(xs) + hi = max(xs) + return total, lo, hi, round(total / len(xs), 2) + + +def main(): + ints = [5, 3, 9, 1] + floats = [2.5, 0.5, 1.25] + words = ["pear", "apple", "fig"] + s = sorted(ints) + s.append(10) + print(s, ints) + print(sorted(words), sorted(words, key=len), sorted(words, reverse=True)) + print(sorted("banana"), sorted({"b": 1, "a": 2})) + print(stats(ints), stats(floats)) + print(min(3, 7), max(3, 7), min(2.5, 1.5), max("a", "b")) + print(sum(floats), sum(ints, 10), sum(ints, 0.5), sum([True, True, False])) + print(round(2.5), round(3.5), round(-0.5), round(2.675, 2), round(7, -1), round(1.5)) + boxes = [Box(3), Box(1), Box(2)] + print(sorted(boxes), min(boxes), max(boxes)) + print(sorted(boxes, key=lambda b: -b.v)) + n = 0 + for v in sorted(ints): + n = n * 10 + v + print(n) + try: + min([]) + except ValueError as e: + print("ValueError", e) + mixed = [1, 2.5] + print(sum(mixed), max(mixed), min(1, 2.0), type(max(1, 1.0)).__name__) + + + +def loops(): + ints = [4, 8, 15] + names = ["a", "b", "c"] + total = 0 + for i, v in enumerate(ints): + total += i * v + print(total) + for i, v in enumerate(names, 1): + print(i, v.upper()) + for n, v in zip(names, ints): + print(n + str(v + 1)) + for a, b, c in zip(ints, names, "xyz"): + print(a, b, c) + acc = "" + for v in reversed(names): + acc += v + print(acc, [v * 2 for v in reversed(ints)]) + d = {"x": 1, "y": 2} + for k in d.keys(): + print(k.upper()) + s = 0 + for v in d.values(): + s += v + print(s) + for k, v in d.items(): + print(k, v + 10) + pairs = [(k, v) for k, v in d.items()] + print(pairs, [i + v for i, v in enumerate(ints)]) + opt = {"a": None, "b": "z"} + for k, v in opt.items(): + print(k, v is None, v) + for i, ch in enumerate("hi"): + print(i, ch) + + +main() +loops() diff --git a/maven/python-transpiler/src/test/resources/conformance/bytes_kinds.out b/maven/python-transpiler/src/test/resources/conformance/bytes_kinds.out new file mode 100644 index 00000000000..125cb56fe84 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/bytes_kinds.out @@ -0,0 +1,34 @@ +2 b s +a.xml bytes True +a.xml bytes True +b.bin bytes True +b.bin bytes True +bytes True +bytes True +bytes True +bytes True +bytes True +bytes True +bytes True +bytes True +bytes True +bytes True +True +True +TypeError cannot use a string pattern on a bytes-like object +TypeError cannot use a bytes pattern on a string-like object +b'ab-7- cd|e |b"q\'"|\'\\xe9\'|Az|ff|%' +bytearray(b'[mv]') +b'key=3' +b'' +TypeError %b requires a bytes-like object, or an object that implements __bytes__, not 'str' +TypeError %b requires a bytes-like object, or an object that implements __bytes__, not 'int' +TypeError %b requires a bytes-like object, or an object that implements __bytes__, not 'float' +alpha Nav True +['alpha', 'beta'] ['alpha', 'beta'] ['alpha', 'beta'] +'X X' 'ALPHA BETA' True +True blphb betb +[b'ab', b'cd'] [b'ef', b'gh'] [b'ij', b'kl'] +b'- -' [b'x', b'y'] +TypeError expected string or bytes-like object, got 'int' +TypeError expected string or bytes-like object, got 'NoneType' diff --git a/maven/python-transpiler/src/test/resources/conformance/bytes_kinds.py b/maven/python-transpiler/src/test/resources/conformance/bytes_kinds.py new file mode 100644 index 00000000000..eee46856b74 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/bytes_kinds.py @@ -0,0 +1,81 @@ +import io +import re +import zipfile + +d = {} +d[bytes] = "b" +d[str] = "s" +print(len(d), d[bytes], d[str]) + +buf = io.BytesIO() +with zipfile.ZipFile(buf, "w") as z: + z.writestr("a.xml", "text") + z.writestr("b.bin", b"\x89PNG") +with zipfile.ZipFile(buf) as z: + for n in ("a.xml", "b.bin"): + v = z.read(n) + print(n, type(v).__name__, isinstance(v, bytes)) + with z.open(n) as f: + w = f.read() + print(n, type(w).__name__, isinstance(w, bytes)) + +for v in (io.BytesIO(b"

x

").read(), io.BytesIO(b"

x

").getvalue(), + io.BytesIO(b"

x

").read(3), memoryview(b"ab").tobytes(), bytes(bytearray(b"z")), + b"abc"[1:], b"a" + b"b", b"ab" * 2, "x".encode("utf-8"), b"%s" % b"q"): + print(type(v).__name__, isinstance(v, bytes)) + +pat = re.compile(b"<\\s*meta[^>]+charset", re.I) +print(pat.search(b"", endpos=100) is not None) +print(pat.search(bytearray(b"")) is not None) +try: + re.compile("x").search(b"x") +except TypeError as e: + print("TypeError", e) +try: + re.compile(b"x").search("x") +except TypeError as e: + print("TypeError", e) + +print(b"%s-%d-%5s|%-4b|%r|%a|%c%c|%x|%%" % (b"ab", 7, b"cd", bytearray(b"e"), b"q'", "\xe9", 65, b"z", 255)) +print(bytearray(b"[%s]") % (memoryview(b"mv"),)) +print(b"%(k)s=%(v)d" % {b"k": b"key", b"v": 3}) + + +class B: + def __bytes__(self): + return b"custom" + + +print(b"<%s>" % B()) +for bad in ("str", 1, 1.5): + try: + b"%s" % bad + except TypeError as e: + print("TypeError", e) + + +class Nav(str): + pass + + +n = Nav("alpha beta") +w = re.compile(r"\w+") +m = w.search(n) +print(m.group(), type(m.string).__name__, m.string is n) +print(w.findall(n), re.split(" ", n), [x.group() for x in w.finditer(n)]) +print(repr(w.sub("X", n)), repr(w.sub(lambda q: q.group().upper(), n)), w.fullmatch(Nav("one")) is not None) +print(re.match("a", n) is not None, re.sub("a", "b", n)) + + +class Raw(bytes): + pass + + +bw = re.compile(rb"\w+") +print(bw.findall(bytearray(b"ab cd")), bw.findall(memoryview(b"ef gh")), bw.findall(Raw(b"ij kl"))) +print(bw.sub(b"-", bytearray(b"ab cd")), re.split(rb" ", bytearray(b"x y"))) +for bad in (1, None): + try: + w.search(bad) + except TypeError as e: + print("TypeError", e) diff --git a/maven/python-transpiler/src/test/resources/conformance/bytes_typed.out b/maven/python-transpiler/src/test/resources/conformance/bytes_typed.out new file mode 100644 index 00000000000..3dda852da59 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/bytes_typed.out @@ -0,0 +1,8 @@ +True 24 33 +104 32 169 32 +b'h\xc3\xa9ll' héll 5 +98 b'bc' xyz +b'h?llo ? ' �� +ababab ab +IndexError index out of range +UnicodeDecodeError 0 diff --git a/maven/python-transpiler/src/test/resources/conformance/bytes_typed.py b/maven/python-transpiler/src/test/resources/conformance/bytes_typed.py new file mode 100644 index 00000000000..5841317f315 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/bytes_typed.py @@ -0,0 +1,25 @@ +# Typed bytes: literals, encode/decode, indexing, slicing, str repetition. + + +def run(n): + s = "héllo — " * 3 + b = s.encode("utf-8") + t = b.decode("utf-8") + print(t == s, len(t), len(b)) + print(b[0], b[-1], b[n], b[len(b) - 1]) + head = b[:n + 3] + print(head, head.decode("latin-1"), len(head.decode("latin-1"))) + print(b"abc"[1], b"abc"[1:], b"xyz".decode()) + print(s.encode("ascii", "replace")[:8], b"\xff\xfe".decode("utf-8", "replace")) + print(3 * "ab", "ab" * 0, "ab" * True) + try: + b[100] + except IndexError as e: + print("IndexError", e) + try: + b"\xff".decode("utf-8") + except UnicodeDecodeError as e: + print("UnicodeDecodeError", e.start) + + +run(2) diff --git a/maven/python-transpiler/src/test/resources/conformance/call_dunder_typed.out b/maven/python-transpiler/src/test/resources/conformance/call_dunder_typed.out new file mode 100644 index 00000000000..4ec1ec3ee6f --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/call_dunder_typed.out @@ -0,0 +1,6 @@ +('m', 8) +7 [4, 5] [1, 2, 3] +13 +101 +init Box +9 diff --git a/maven/python-transpiler/src/test/resources/conformance/call_dunder_typed.py b/maven/python-transpiler/src/test/resources/conformance/call_dunder_typed.py new file mode 100644 index 00000000000..bf363a740af --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/call_dunder_typed.py @@ -0,0 +1,58 @@ +class Deco: + def __init__(self, msg): + self.msg = msg + + def __call__(self, arg): + if isinstance(arg, type): + orig = arg.__init__ + + def init(self, *a, **k): + print("init", self.__class__.__name__) + orig(self, *a, **k) + + arg.__init__ = init + return arg + + def wrapper(*a, **k): + return (self.msg, arg(*a, **k)) + + return wrapper + + +@Deco("m") +def twice(x): + return x * 2 + + +print(twice(4)) + + +class Adder: + def __init__(self, n): + self.n = n + + def __call__(self, x): + return x + self.n + + +a = Adder(3) +print(a(4), list(map(a, [1, 2])), sorted([3, 1, 2], key=Adder(-1))) +held = [a] +print(held[0](10)) + + +class Sub(Adder): + pass + + +fs = {"s": Sub(100)} +print(fs["s"](1)) + + +@Deco("c") +class Box: + def __init__(self, v): + self.v = v + + +print(Box(9).v) diff --git a/maven/python-transpiler/src/test/resources/conformance/call_global_tuple.out b/maven/python-transpiler/src/test/resources/conformance/call_global_tuple.out new file mode 100644 index 00000000000..c3436db1ac7 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/call_global_tuple.out @@ -0,0 +1,2 @@ +wd(0, 2) wd(1, -1) wd(2, None) +wd(0, 3) diff --git a/maven/python-transpiler/src/test/resources/conformance/call_global_tuple.py b/maven/python-transpiler/src/test/resources/conformance/call_global_tuple.py new file mode 100644 index 00000000000..0740d9d265b --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/call_global_tuple.py @@ -0,0 +1,23 @@ +class weekday: + def __init__(self, wd, n=None): + self.weekday = wd + self.n = n + + def __call__(self, n): + if n == self.n: + return self + return self.__class__(self.weekday, n) + + def __repr__(self): + return "wd(%d, %r)" % (self.weekday, self.n) + + +MO, TU, WE = [weekday(i) for i in range(3)] + + +def pick(w): + return w + + +print(MO(+2), TU(-1), repr(WE)) +print(pick(MO)(3)) diff --git a/maven/python-transpiler/src/test/resources/conformance/class_arg_specialize.out b/maven/python-transpiler/src/test/resources/conformance/class_arg_specialize.out new file mode 100644 index 00000000000..b5b63002db1 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/class_arg_specialize.out @@ -0,0 +1,3 @@ +A B A index +True True ['A', 'B'] +3 1 x diff --git a/maven/python-transpiler/src/test/resources/conformance/class_arg_specialize.py b/maven/python-transpiler/src/test/resources/conformance/class_arg_specialize.py new file mode 100644 index 00000000000..56d53d575b4 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/class_arg_specialize.py @@ -0,0 +1,36 @@ +# A field every construction sets to one literal attribute name is folded +# to it, so the setattr/getattr that use it name the attribute literally. +from collections import defaultdict + + +class Bound(defaultdict): + def __init__(self, reference=None, *args, **kw): + self.reference = reference + super().__init__(*args, **kw) + + def __getitem__(self, key): + value = super().__getitem__(key) + if self.reference is not None: + setattr(value, self.reference, key) + return value + + def peek(self, key): + return getattr(super().__getitem__(key), self.reference) + + +class Dim: + def __init__(self): + self.index = None + + +class Holder(Bound): + def __init__(self, owner, reference="index", default_factory=None): + self.owner = owner + super().__init__(reference, default_factory) + + +h = Holder(owner="w", default_factory=Dim) +print(h["A"].index, h["B"].index, h.peek("A"), h.reference) +print(isinstance(h, Bound), isinstance(h, defaultdict), sorted(h.keys())) +g = Holder("x", default_factory=Dim) +print(g[3].index, len(g), g.owner) diff --git a/maven/python-transpiler/src/test/resources/conformance/class_constant_fold.out b/maven/python-transpiler/src/test/resources/conformance/class_constant_fold.out new file mode 100644 index 00000000000..e5cbebf7d33 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/class_constant_fold.out @@ -0,0 +1,8 @@ +Base 64 128 +Small 32 64 +Same 64 128 +before 5 5 +after 9 9 +mode a b +kind 1 2 +width 3 7 diff --git a/maven/python-transpiler/src/test/resources/conformance/class_constant_fold.py b/maven/python-transpiler/src/test/resources/conformance/class_constant_fold.py new file mode 100644 index 00000000000..366c0e4a7ad --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/class_constant_fold.py @@ -0,0 +1,89 @@ +# A class constant read through self is folded only while the whole program +# proves no instance holds the name and nothing wrote to the class: every +# way around that must still read what CPython reads. + + +class Base: + SIZE = 64 + + def size(self): + return self.SIZE + + def twice(self): + return self.SIZE + self.SIZE + + +class Small(Base): + SIZE = 32 + + +class Same(Base): + pass + + +for o in (Base(), Small(), Same()): + print(type(o).__name__, o.size(), o.twice()) + + +# A computed setattr on the class itself, and on a class above it. +class Tunable: + LIMIT = 5 + + def limit(self): + return self.LIMIT + + @classmethod + def configure(cls, **kw): + for k, v in kw.items(): + setattr(cls, k, v) + + +class TunableChild(Tunable): + pass + + +t = Tunable() +c = TunableChild() +print("before", t.limit(), c.limit()) +Tunable.configure(LIMIT=9) +print("after", t.limit(), c.limit()) + + +# A store by name on one instance. +class Moded: + MODE = "a" + + def mode(self): + return self.MODE + + +m1 = Moded() +m2 = Moded() +m2.MODE = "b" +print("mode", m1.mode(), m2.mode()) + + +# A computed store through the instance's dict. +class Kinded: + KIND = 1 + + def kind(self): + return self.KIND + + +k = Kinded() +name = "KI" + "ND" +k.__dict__[name] = 2 +print("kind", Kinded().kind(), k.kind()) + + +# A class built at run time below a compiled one, with its own value. +class Wide: + WIDTH = 3 + + def width(self): + return self.WIDTH + + +Wider = type("Wider", (Wide,), {"WIDTH": 7}) +print("width", Wide().width(), Wider().width()) diff --git a/maven/python-transpiler/src/test/resources/conformance/class_statics.out b/maven/python-transpiler/src/test/resources/conformance/class_statics.out new file mode 100644 index 00000000000..9de0515229b --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/class_statics.out @@ -0,0 +1,5 @@ +42 84 43 +1180591620717411303424 1180591620717411303425 +cfg-40 cfg-40 5.0 +3 +3 shade 7 diff --git a/maven/python-transpiler/src/test/resources/conformance/class_statics.py b/maven/python-transpiler/src/test/resources/conformance/class_statics.py new file mode 100644 index 00000000000..1bec07a4537 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/class_statics.py @@ -0,0 +1,48 @@ +BASE = 40 + + +def big(): + return 1 << 70 + + +class Point: + def __init__(self, x): + self.x = x + + +class Config: + LIMIT = BASE + 2 + HUGE = big() + NAME = "cfg-" + str(BASE) + RATIO = BASE / 8 + ORIGIN = Point(3) + + def limit(self): + return self.LIMIT + 1 + + def huge(self): + return self.HUGE + + @classmethod + def name(cls): + return cls.NAME + + +c = Config() +print(Config.LIMIT, Config.LIMIT * 2, c.limit()) +print(Config.HUGE, c.huge() + 1) +print(Config.NAME, Config.name(), Config.RATIO) +print(Config.ORIGIN.x) + + +class Shade: + def __init__(self, n): + self.n = n + + def bright(self): + return Shade.DARK.n + self.n + + +Shade.DARK = Shade(3) +Shade.LABEL = "shade" +print(Shade.DARK.n, Shade.LABEL, Shade(4).bright()) diff --git a/maven/python-transpiler/src/test/resources/conformance/classmethod_via_self.out b/maven/python-transpiler/src/test/resources/conformance/classmethod_via_self.out new file mode 100644 index 00000000000..e9b46218210 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/classmethod_via_self.out @@ -0,0 +1 @@ +True True False diff --git a/maven/python-transpiler/src/test/resources/conformance/classmethod_via_self.py b/maven/python-transpiler/src/test/resources/conformance/classmethod_via_self.py new file mode 100644 index 00000000000..0ad2c189db2 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/classmethod_via_self.py @@ -0,0 +1,43 @@ +# A classmethod called through self does not make the instance escape: +# its fields keep their types. +from collections import defaultdict +from typing import List, Optional, cast + + +class Rule: + def __init__(self, string=None, present=None): + self.string = string + self.present = present + + def matches(self, s): + return self.string == s + + +class Strainer: + name_rules: List[Rule] + + def __init__(self, name=None, attrs=None, string=None, **kwargs): + if name is None and not attrs and not string and not kwargs: + self.name_rules = [Rule(present=True)] + else: + self.name_rules = cast(List[Rule], list(self._make(name, Rule))) + self.attribute_rules = defaultdict(list) + + @classmethod + def _make(cls, obj, rule_class): + if obj is None: + return + if isinstance(obj, str): + yield rule_class(string=obj) + else: + for o in obj: + yield rule_class(string=o) + + def match(self, s): + for r in self.name_rules: + if r.matches(s): + return True + return False + + +print(Strainer("a").match("a"), Strainer(["b", "c"]).match("c"), Strainer().match("x")) diff --git a/maven/python-transpiler/src/test/resources/conformance/closed_name_setattr.out b/maven/python-transpiler/src/test/resources/conformance/closed_name_setattr.out new file mode 100644 index 00000000000..afc075729ba --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/closed_name_setattr.out @@ -0,0 +1,2 @@ +1 1 1.0 +7 diff --git a/maven/python-transpiler/src/test/resources/conformance/closed_name_setattr.py b/maven/python-transpiler/src/test/resources/conformance/closed_name_setattr.py new file mode 100644 index 00000000000..b1176d458d2 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/closed_name_setattr.py @@ -0,0 +1,33 @@ +# setattr(obj, prop[0], v) where prop comes from a local table of literal +# tuples: each store is one of the table's literal names. + + +class Parser: + def parse(self, items): + properties = { + "a": ("alpha", int), + "b": ("beta", str), + "c": ("gamma", float), + } + for t in items: + if t in properties: + prop = properties[t] + obj = prop[1](1) + setattr(self, prop[0], obj) + return self + + +class One: + def fill(self, keys): + table = {"k": ("only", 7)} + for k in keys: + if k not in table: + continue + row = table[k] + setattr(self, row[0], row[1]) + return self + + +p = Parser().parse(["c", "a", "b", "x"]) +print(p.alpha, p.beta, p.gamma) +print(One().fill(["z", "k"]).only) diff --git a/maven/python-transpiler/src/test/resources/conformance/closure_params.out b/maven/python-transpiler/src/test/resources/conformance/closure_params.out new file mode 100644 index 00000000000..5019f748695 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/closure_params.out @@ -0,0 +1,9 @@ +[10, 11, 12, 13] cdab 1180591620717411303425 +45 [2, 5] 12.0 +6 7 8 +720 8 [0, 3, 6, 9] +make_adder make_adder..add +5 +NameError True +2 +NameError True diff --git a/maven/python-transpiler/src/test/resources/conformance/closure_params.py b/maven/python-transpiler/src/test/resources/conformance/closure_params.py new file mode 100644 index 00000000000..e09b3f55170 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/closure_params.py @@ -0,0 +1,88 @@ +# Closures over a typed function's parameters: the cell sits beside the +# typed local; anything that rebinds a captured name keeps generic code. + +SCALE = 3 + + +def make_adder(k): + def add(x): + return x + k + return add + + +def make_scaled(k, s): + def f(x): + return (x + k) * s * SCALE + def g(): + return [k, s] + return f, g + + +def make_counter(start): + def inc(): + nonlocal start + start += 1 + return start + return inc + + +def make_rec(n): + def fact(m): + return 1 if m <= 1 else m * fact(m - 1) + return fact(n) + + +def make_late(k): + def get(): + return k + k = k * 2 + return get + + +def make_gen(k): + def gen(n): + for i in range(n): + yield i * k + return gen + + +adders = [make_adder(k) for k in range(4)] +print([a(10) for a in adders], make_adder("ab")("cd"), make_adder(2 ** 70)(1)) +f, g = make_scaled(2, 5) +print(f(1), g(), make_scaled(1.5, 2)[0](0.5)) +c = make_counter(5) +print(c(), c(), c()) +print(make_rec(6), make_late(4)(), list(make_gen(3)(4))) +print(make_adder.__name__, adders[0].__qualname__) + +def bound_param(k): + def get(): + return k + return get + +def rebound_param(k): + def get(): + return k + del k + return get + +def nonlocal_param(k): + def setk(): + nonlocal k + del k + def get(): + return k + return setk, get + +print(bound_param(5)()) +try: + rebound_param(1)() +except NameError as e: + print("NameError", "k" in str(e)) +s, g = nonlocal_param(2) +print(g()) +s() +try: + g() +except NameError as e: + print("NameError", "k" in str(e)) diff --git a/maven/python-transpiler/src/test/resources/conformance/cobble_pkg.out b/maven/python-transpiler/src/test/resources/conformance/cobble_pkg.out new file mode 100644 index 00000000000..3eeada9c4ba --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/cobble_pkg.out @@ -0,0 +1,10 @@ +Text(value='hi') +None BoldElement(tag_name='b', children=[Element(tag_name='p', children=[Text(value='hi'), Comment('c')], attributes=None)], attributes={'k': 'v'}, weight=7) +True False True False +True +**7

text:hi#c +2 +Element(tag_name='div', children=[Text(value='hi'), Comment('c')], attributes=None) False True +BoldElement(tag_name='b', children=[Element(tag_name='p', children=[Text(value='hi'), Comment('c')], attributes=None)], attributes={'k': 'v'}, weight=1) +missing argument +unexpected keyword diff --git a/maven/python-transpiler/src/test/resources/conformance/cobble_pkg.py b/maven/python-transpiler/src/test/resources/conformance/cobble_pkg.py new file mode 100644 index 00000000000..3e63710b1db --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/cobble_pkg.py @@ -0,0 +1,85 @@ +import cobble + + +class Node(object): + pass + + +@cobble.data +class Text(Node): + value = cobble.field() + + +@cobble.data +class Element(Node): + tag_name = cobble.field() + children = cobble.field() + attributes = cobble.field(default=None) + + +@cobble.data +class BoldElement(Element): + weight = cobble.field(default=None) + + +@cobble.visitable +class Comment(Node): + def __init__(self, text): + self.text = text + + def __repr__(self): + return "Comment(" + repr(self.text) + ")" + + +NodeVisitor = cobble.visitor(Node) +ArgVisitor = cobble.visitor(Node, args=1) + + +class Printer(NodeVisitor): + def visit_text(self, node): + return "text:" + node.value + + def visit_element(self, node): + return "<" + node.tag_name + ">" + "".join(self.visit(c) for c in node.children) + + def visit_bold_element(self, node): + return "**" + str(node.weight) + self.visit_element(node) + + def visit_comment(self, node): + return "#" + node.text + + +class Depth(ArgVisitor): + def visit_text(self, node, depth): + return depth + + def visit_element(self, node, depth): + return max([depth] + [self.visit(c, depth + 1) for c in node.children]) + + def visit_bold_element(self, node, depth): + return self.visit_element(node, depth) + + def visit_comment(self, node, depth): + return depth + + +t = Text("hi") +e = Element("p", [t, Comment("c")]) +b = BoldElement("b", [e], {"k": "v"}, weight=7) +print(repr(t)) +print(repr(e.attributes), repr(b)) +print(t == Text("hi"), t == Text("ho"), t != Text("ho"), t == "hi") +print(hash(t) == hash(Text("hi"))) +print(Printer().visit(b)) +print(Depth().visit(b, 0)) +c = cobble.copy(e, tag_name="div") +print(repr(c), c == e, isinstance(c, Element)) +print(repr(cobble.copy(b, weight=1))) +try: + Text() +except TypeError: + print("missing argument") +try: + cobble.copy(t, nope=1) +except TypeError: + print("unexpected keyword") diff --git a/maven/python-transpiler/src/test/resources/conformance/codec_roundtrip.out b/maven/python-transpiler/src/test/resources/conformance/codec_roundtrip.out new file mode 100644 index 00000000000..503d82a07fb --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/codec_roundtrip.out @@ -0,0 +1,5 @@ +True 140 bytes +b'n\x00a\x00\xef\x00' b'na?ve caf? ?' +b'Na\xc3\xaf' b'na\xc3\xaf' b'na\xc3\xaf' +True b'\n!' +140 False 140 diff --git a/maven/python-transpiler/src/test/resources/conformance/codec_roundtrip.py b/maven/python-transpiler/src/test/resources/conformance/codec_roundtrip.py new file mode 100644 index 00000000000..97ab2e9887b --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/codec_roundtrip.py @@ -0,0 +1,12 @@ +src = ("naïve café — résumé

x

\n" * 4).encode("utf-8") +text = src.decode("utf-8") +back = text.encode("utf-8") +print(back == src, len(back), type(back).__name__) +print(text.encode("utf-16-le")[:6], text.encode("ascii", "replace")[:12]) +ba = bytearray(back) +ba[0] = 0x4e +print(bytes(ba[:4]), back[:4], src[:4]) +other = str(src, "utf-8") +print(other.encode() == src, (text + "!").encode()[-2:]) +lat = src.decode("latin-1") +print(len(lat), lat.encode("utf-8") == src, len(lat.encode("latin-1"))) diff --git a/maven/python-transpiler/src/test/resources/conformance/comptyped_.out b/maven/python-transpiler/src/test/resources/conformance/comptyped_.out new file mode 100644 index 00000000000..9119de7ca1d --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/comptyped_.out @@ -0,0 +1,13 @@ +['bb', 'ccc'] +['A=1.5', 'BB=2.0', '*CCC=3.25'] +13.5 +['a!', 'b!', 'b!', 'c!', 'c!', 'c!'] +[['aa', 'abb', 'accc'], ['bba', 'bbbb', 'bbccc'], ['ccca', 'cccbb', 'cccccc']] +['alpha', 'beta', 'gamma'] +[True, True, False] +["'x'", "'y'", '3', 'None'] +['a:1.5', 'bb:2.0', 'ccc:3.25'] +['a', 'b', 'c'] +[('a', 1.5), ('bb', 2.0), ('ccc', 3.25)] +(['a', 'bb', 'ccc'], 42) +[0.25, 1.5625, 4.0] diff --git a/maven/python-transpiler/src/test/resources/conformance/comptyped_.py b/maven/python-transpiler/src/test/resources/conformance/comptyped_.py new file mode 100644 index 00000000000..978959356d4 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/comptyped_.py @@ -0,0 +1,97 @@ +# Comprehension targets typed by what their iterable yields. + + +class Item: + def __init__(self, name, price): + self.name = name + self.price = price + + def label(self): + return self.name.upper() + "=" + str(self.price) + + +class Special(Item): + def label(self): + return "*" + Item.label(self) + + +def items(): + out = [Item("a", 1.5), Item("bb", 2.0)] + out.append(Special("ccc", 3.25)) + return out + + +def names(xs): + return [x.name for x in xs if len(x.name) > 1] + + +def labels(xs): + return [x.label() for x in xs] + + +def total(xs): + return sum([x.price * 2 for x in xs]) + + +def nested(xs): + return [c + "!" for x in xs for c in x.name] + + +def inner(xs): + return [[x.name + y.name for y in xs] for x in xs] + + +def words(s): + return [w.strip().lower() for w in s.split(",") if w.strip()] + + +def flags(xs): + bs = [x.price > 2 for x in xs] + return [not b for b in bs] + + +def mixed(): + vals = ["x", "y"] + vals.append(3) + vals.append(None) + return [repr(v) for v in vals] + + +def pairs(xs): + return [n + ":" + str(p) for n, p in [(x.name, x.price) for x in xs]] + + +def sets(xs): + return sorted({x.name[0] for x in xs}) + + +def dicts(xs): + d = {x.name: x.price for x in xs} + return sorted(d.items()) + + +def shadow(xs): + x = 42 + r = [x.name for x in xs] + return r, x + + +def floats(): + fs = [0.5, 1.25, 2.0] + return [f * f for f in fs] + + +xs = items() +print(names(xs)) +print(labels(xs)) +print(total(xs)) +print(nested(xs)) +print(inner(xs)) +print(words(" Alpha, beta ,,GAMMA ")) +print(flags(xs)) +print(mixed()) +print(pairs(xs)) +print(sets(xs)) +print(dicts(xs)) +print(shadow(xs)) +print(floats()) diff --git a/maven/python-transpiler/src/test/resources/conformance/const_arg_specialize.out b/maven/python-transpiler/src/test/resources/conformance/const_arg_specialize.out new file mode 100644 index 00000000000..c347085bc6a --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/const_arg_specialize.out @@ -0,0 +1,3 @@ +10 4 base +set 3 set 3 +6 diff --git a/maven/python-transpiler/src/test/resources/conformance/const_arg_specialize.py b/maven/python-transpiler/src/test/resources/conformance/const_arg_specialize.py new file mode 100644 index 00000000000..5db15fd69b3 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/const_arg_specialize.py @@ -0,0 +1,47 @@ +# A method always called with literal attribute names is specialized per +# name, so its getattr/setattr/hasattr name no attribute at run time. + + +class Base: + def __init__(self): + self.width = None + self.height = 4 + self.label = "base" + + @property + def area(self): + return 6 + + +class Box(Base): + def __init__(self, parent): + super().__init__() + self.parent = parent + + def effective(self, name): + v = getattr(self, name) + if v is not None: + return v + return self._inherited(name) + + def _inherited(self, name): + p = self.parent + if p is None: + return None + return getattr(p, name) + + def store(self, name, value): + if hasattr(self, name): + setattr(self, name, value) + return getattr(self, name, "none") + + def area_of(self, name): + return getattr(super(Box, self), name) + + +root = Box(None) +root.width = 10 +b = Box(root) +print(b.effective("width"), b.effective("height"), b.effective("label")) +print(b.store("label", "set"), b.store("width", 3), b.label, b.width) +print(b.area_of("area")) diff --git a/maven/python-transpiler/src/test/resources/conformance/csv_dialect_name.out b/maven/python-transpiler/src/test/resources/conformance/csv_dialect_name.out new file mode 100644 index 00000000000..bef37230139 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/csv_dialect_name.out @@ -0,0 +1,3 @@ +[['a;b'], ['1;2']] +[['a', 'b'], ['1', '2']] +[['a', 'b']] diff --git a/maven/python-transpiler/src/test/resources/conformance/csv_dialect_name.py b/maven/python-transpiler/src/test/resources/conformance/csv_dialect_name.py new file mode 100644 index 00000000000..e02032e163b --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/csv_dialect_name.py @@ -0,0 +1,4 @@ +import csv, io +print(list(csv.reader(io.StringIO("a;b\n1;2\n")))) +print(list(csv.reader(io.StringIO("a;b\n1;2\n"), delimiter=";"))) +print(list(csv.reader(io.StringIO("a,b\n"), "excel"))) diff --git a/maven/python-transpiler/src/test/resources/conformance/dataclass_init.out b/maven/python-transpiler/src/test/resources/conformance/dataclass_init.out new file mode 100644 index 00000000000..bcba972f95c --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/dataclass_init.out @@ -0,0 +1,20 @@ +Point(x=1, y=0, tags=[3]) Point(x=2, y=5, tags=[]) [3] [] p False False +Reg(name='a', priority=2.5) 3.5 Reg(name='b', priority=0.0) True +frozen cannot assign to field 'name' +Sized(w=2.0, h=3.5, area=7.0) 7.0 +Child(v=3, k='a') hi 3 True [Child(v=1, k='a'), Child(v=5, k='a'), Child(v=5, k='b')] +Empty() True +TypeError Point.__init__() missing 1 required positional argument: 'x' +TypeError Point.__init__() got multiple values for argument 'x' +TypeError Point.__init__() got an unexpected keyword argument 'z' +TypeError Reg.__init__() takes 1 positional argument but 2 were given +TypeError Reg.__init__() missing 1 required keyword-only argument: 'name' +TypeError Sized.__init__() takes 3 positional arguments but 4 were given +TypeError Empty.__init__() takes 1 positional argument but 2 were given +['x', 'y', 'tags', 'label'] {'x': 2, 'y': 5, 'tags': [], 'label': 'p'} Point(x=2, y=9, tags=[]) +999000.0 +Key(kind='a', rank=1) 2 1 True True +frozen cannot assign to field 'rank' +frozen cannot delete field 'rank' +frozen cannot assign to field 'xy' +1 4950 diff --git a/maven/python-transpiler/src/test/resources/conformance/dataclass_init.py b/maven/python-transpiler/src/test/resources/conformance/dataclass_init.py new file mode 100644 index 00000000000..0d3cde634c0 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/dataclass_init.py @@ -0,0 +1,94 @@ +# Dataclass constructors: defaults, field(), keyword-only, frozen, +# __post_init__, and the errors a wrong call raises. +from dataclasses import dataclass, field, FrozenInstanceError +import dataclasses + + +@dataclass +class Point: + x: int + y: int = 0 + tags: list = field(init=False, default_factory=list) + label: str = field(default="p", repr=False) + + +@dataclass(kw_only=True, frozen=True) +class Reg: + name: str + priority: float = 0.0 + + +@dataclass +class Sized: + w: float + h: float + area: float = field(init=False, default=0.0) + + def __post_init__(self): + self.area = self.w * self.h + + +class Base: + def hello(self): + return "hi " + str(self.v) + + +@dataclasses.dataclass(order=True) +class Child(Base): + v: int + k: str = "a" + + +@dataclass +class Empty: + pass + + +def show(e): + print(type(e).__name__, e) + + +p = Point(1) +q = Point(2, y=5) +p.tags.append(3) +print(p, q, p.tags, q.tags, p.label, p == Point(1), p == q) +r = Reg(name="a", priority=2.5) +print(r, r.priority + 1, Reg(name="b"), hash(r) == hash(Reg(name="a", priority=2.5))) +try: + r.name = "z" +except FrozenInstanceError as e: + print("frozen", e) +s = Sized(2.0, 3.5) +print(s, s.area) +c = Child(3) +print(c, c.hello(), c < Child(4), sorted([Child(5, "b"), Child(5, "a"), Child(1)])) +print(Empty(), Empty() == Empty()) +for bad in (lambda: Point(), lambda: Point(1, 2, 3), lambda: Point(1, x=2), lambda: Point(1, z=2), + lambda: Reg("a"), lambda: Reg(), lambda: Sized(1.0, 2.0, 3.0), lambda: Empty(1)): + try: + bad() + except TypeError as e: + show(e) +print([f.name for f in dataclasses.fields(Point)], dataclasses.asdict(q), dataclasses.replace(q, y=9)) +total = 0.0 +for i in range(1000): + total += Reg(name="n", priority=float(i)).priority + Point(i, i).y +print(total) + + +@dataclass(frozen=True) +class Key: + kind: str + rank: int = 1 + + +k = Key("a") +keys = {k: 1, Key("b", 2): 2} +print(k, k.rank + 1, keys[Key("a")], Key("b", 2) in keys, k == Key("a", 1)) +n = "ra" + "nk" +for act in (lambda: setattr(k, n, 5), lambda: delattr(k, n), lambda: setattr(k, "x" + "y", 1)): + try: + act() + except FrozenInstanceError as e: + print("frozen", e) +print(k.rank, sum(Key("z", i).rank for i in range(100))) diff --git a/maven/python-transpiler/src/test/resources/conformance/dict_subclass_missing.out b/maven/python-transpiler/src/test/resources/conformance/dict_subclass_missing.out new file mode 100644 index 00000000000..ae81787fbfb --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/dict_subclass_missing.out @@ -0,0 +1,4 @@ +D ['A'] +1 zzzz 1 +KeyError 'y' +5 diff --git a/maven/python-transpiler/src/test/resources/conformance/dict_subclass_missing.py b/maven/python-transpiler/src/test/resources/conformance/dict_subclass_missing.py new file mode 100644 index 00000000000..891e66c4dee --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/dict_subclass_missing.py @@ -0,0 +1,41 @@ +# dict.__getitem__ reached through super() on a dict subclass still calls +# type(self).__missing__, as CPython's dict lookup does. +from collections import defaultdict + + +class B(defaultdict): + def __getitem__(self, key): + return super().__getitem__(key) + + +class D: + pass + + +b = B(D) +print(type(b["A"]).__name__, sorted(b.keys())) + + +class M(dict): + def __missing__(self, key): + return key * 2 + + def __getitem__(self, key): + return dict.__getitem__(self, key) + + +m = M(a=1) +print(m["a"], m["zz"], len(m)) + + +class N(dict): + def __getitem__(self, key): + return super().__getitem__(key) + + +n = N(x=1) +try: + n["y"] +except KeyError as e: + print("KeyError", e) +print(dict.__getitem__({"k": 5}, "k")) diff --git a/maven/python-transpiler/src/test/resources/conformance/dict_typed.out b/maven/python-transpiler/src/test/resources/conformance/dict_typed.out new file mode 100644 index 00000000000..8f111053c4f --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/dict_typed.out @@ -0,0 +1,4 @@ +[('a', 3), ('b', 2), ('c', 1)] 4 +(None, 5, None, 7, True, False, 2) +(1, 1) +str! 5.0 s KeyError 3 diff --git a/maven/python-transpiler/src/test/resources/conformance/dict_typed.py b/maven/python-transpiler/src/test/resources/conformance/dict_typed.py new file mode 100644 index 00000000000..b9bfa389192 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/dict_typed.py @@ -0,0 +1,73 @@ +# Dicts the transpiler follows from a display: typed reads, and every way a +# dict can leave what it follows. + + +def counts(words): + d = {} + for w in words: + if w in d: + d[w] += 1 + else: + d[w] = 1 + return d + + +def total(d, keys): + t = 0 + for k in keys: + try: + t += d[k] + except KeyError: + t -= 1 + return t + + +def poison(d): + d["x"] = "str" + + +def nones(): + d = {1: None, 2: 5} + return d[1], d[2], d.get(3), d.get(3, 7), 1 in d, 3 in d, len(d) + + +def defaults(): + d = {} + d.setdefault("a", 1) + d.setdefault("a", 2) + return d["a"], d.get("b", 0) + 1 + + +def escaped(): + d = {"a": 1} + poison(d) + return d["x"] + "!" + + +def aliased(): + d = {"k": 1} + e = d + e["k"] = 2.5 + return d["k"] * 2 + + +def in_list(): + d = {"k": 1} + box = [d] + box[0]["k"] = "s" + return d["k"] + + +def missing(): + d = {1: 2} + try: + return d[3] + except KeyError as e: + return "KeyError " + repr(e.args[0]) + + +c = counts("a b a c b a".split()) +print(sorted(c.items()), total(c, ["a", "b", "z"])) +print(nones()) +print(defaults()) +print(escaped(), aliased(), in_list(), missing()) diff --git a/maven/python-transpiler/src/test/resources/conformance/enum_.out b/maven/python-transpiler/src/test/resources/conformance/enum_.out index 030d6eba686..daa4f0ea940 100644 --- a/maven/python-transpiler/src/test/resources/conformance/enum_.out +++ b/maven/python-transpiler/src/test/resources/conformance/enum_.out @@ -15,3 +15,4 @@ Red Color.GREEN r GREEN True AttributeError cannot reassign member 'RED' True [, ] NOT_FOUND 200 200 True 200 404 +PIC (13) True True a ['AUTO (1)', 'PIC (13)'] True diff --git a/maven/python-transpiler/src/test/resources/conformance/enum_.py b/maven/python-transpiler/src/test/resources/conformance/enum_.py index 1363418830c..ffb3b8dd44f 100644 --- a/maven/python-transpiler/src/test/resources/conformance/enum_.py +++ b/maven/python-transpiler/src/test/resources/conformance/enum_.py @@ -77,3 +77,20 @@ class Status(IntEnum): print(Status.OK < Status.NOT_FOUND, sorted([Status.NOT_FOUND, Status.OK]), Status(404).name, Status.OK + 0) print(int(Status.OK), Status.OK == 200, "%d" % Status.OK, max(Status)) + +import enum +class BE(int, enum.Enum): + def __new__(cls, v, doc): + self = int.__new__(cls, v) + self._value_ = v + self.__doc__ = doc.strip() + return self + def __str__(self): return f"{self.name} ({self.value})" +class ST(BE): + AUTO = (1, ' a ') + PIC = (13, 'p') +class Shp: + def __init__(self, t): self.t = t + def kind(self) -> ST: return ST(self.t) +s = Shp(13) +print(s.kind(), s.kind() is ST.PIC, ST.PIC == 13, ST.AUTO.__doc__, [str(m) for m in ST], s.kind() == ST.PIC) diff --git a/maven/python-transpiler/src/test/resources/conformance/etree_iter.out b/maven/python-transpiler/src/test/resources/conformance/etree_iter.out new file mode 100644 index 00000000000..d3e2b2cc148 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/etree_iter.out @@ -0,0 +1,23 @@ +['a', 'b', 'c', 'd', 'c', 'c', 'e'] +['c', 'c', 'c'] +['a', 'b', 'c', 'd', 'c', 'c', 'e'] +['a'] +0 +True a b +['a', 'b', 'c', 'd', 'c', 'late', 'c', 'e'] +['solo'] [] +[('{urn:n}i', '1'), ('{urn:n}i', '2')] +True {'a': '1'} +12 +-7 +0 +7 +5 +1000 +3 +123456789012345678 +1234567890123456789012 +ValueError invalid literal for int() with base 10: '-' +ValueError invalid literal for int() with base 10: '' +ValueError invalid literal for int() with base 10: '1a' +ValueError invalid literal for int() with base 10: '--1' diff --git a/maven/python-transpiler/src/test/resources/conformance/etree_iter.py b/maven/python-transpiler/src/test/resources/conformance/etree_iter.py new file mode 100644 index 00000000000..19e86bd6ddc --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/etree_iter.py @@ -0,0 +1,33 @@ +import xml.etree.ElementTree as ET + +root = ET.fromstring('t') +print([e.tag for e in root.iter()]) +print([e.tag for e in root.iter("c")]) +print([e.tag for e in root.iter("*")]) +print([e.tag for e in root.iter("a")]) +print(len(list(root.iter("zz")))) +it = root.iter() +print(type(it) is not list, next(it).tag, next(it).tag) + +# A child added under an element before the walk reaches it is seen. +seen = [] +for e in root.iter(): + seen.append(e.tag) + if e.tag == "b": + ET.SubElement(e, "late") +print(seen) + +leaf = ET.Element("solo") +print([e.tag for e in leaf.iter()], [e.tag for e in leaf.iter("x")]) + +ns = ET.fromstring('') +print([(e.tag, e.get("a")) for e in ns.iter("{urn:n}i")]) +print(ns[0].attrib is not ns[1].attrib, ns[0].attrib) + +for s in ["12", "-7", "0", "007", " 5 ", "1_000", "+3", "123456789012345678", "1234567890123456789012"]: + print(int(s)) +for s in ["-", "", "1a", "--1"]: + try: + int(s) + except ValueError as e: + print("ValueError", e) diff --git a/maven/python-transpiler/src/test/resources/conformance/fold_pct.out b/maven/python-transpiler/src/test/resources/conformance/fold_pct.out new file mode 100644 index 00000000000..c269de82730 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/fold_pct.out @@ -0,0 +1,5 @@ +['hell0 w0rld|-2|HELL0 W0RLD|11', '[
]', '0%', 'hell0 w0rld|-1|HELL0 W0RLD|11', '[]', '3%', 'hell0 w0rld|0|HELL0 W0RLD|11', '[]', '6%'] +['ABC', 'ABCD', 'ABCDD'] +XYZ unbound +('CAFÉ', 4) +q--7-4.5 12 0 diff --git a/maven/python-transpiler/src/test/resources/conformance/fold_pct.py b/maven/python-transpiler/src/test/resources/conformance/fold_pct.py new file mode 100644 index 00000000000..247e75dc18b --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/fold_pct.py @@ -0,0 +1,51 @@ +# Pure str operations on locals stored once fold at transpile time; a +# literal %-format with typed values is one concatenation. + + +def folded(n): + line = " \tHello World\x1f " + out = [] + for i in range(n): + s = line.strip() + a = s.find(">") + 1 + b = s.rfind("<") + cell = s[a:b].replace("o", "0") + if cell.startswith("He"): + out.append("%s|%d|%s|%i" % (cell.lower(), i - 2, cell.upper(), len(cell))) + out.append("[%s]" % s[-4:]) + out.append("%d%%" % (i * 3)) + return out + + +def rebound(k): + t = "abc" + r = [] + for i in range(k): + r.append(t.upper()) + t = t + "d" + return r + + +def maybe(flag): + if flag: + v = "xyz" + try: + return v.upper() + except NameError as e: + return "unbound" + + +def nonascii(): + w = " café " + return w.strip().upper(), w.find("é") + + +def mixed(x, y): + return "%s-%d-%s" % (x, y, 4.5) + + +print(folded(3)) +print(rebound(3)) +print(maybe(True), maybe(False)) +print(nonascii()) +print(mixed("q", -7), "%s" % 12, "<%s>" % "z", "%d" % -0) diff --git a/maven/python-transpiler/src/test/resources/conformance/gen_flat.out b/maven/python-transpiler/src/test/resources/conformance/gen_flat.out new file mode 100644 index 00000000000..c0a2c0a4172 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/gen_flat.out @@ -0,0 +1,13 @@ +[0, 10, 'ValueError: boom'] +[] [] +[10, 'RuntimeError: generator raised StopIteration'] +[0, 1, 2, 'ValueError: boom'] +done +[1, 'RuntimeError: generator raised StopIteration'] +[0, 'caught boom'] +[0, 10, 'caught boomcaught boomcaught boomcaught boomcaught boomcaught boomcaught boomcaught boomcaught boomcaught boom'] +0 +raised boom +finished +['ValueError: generator already executing'] +1000 diff --git a/maven/python-transpiler/src/test/resources/conformance/gen_flat.py b/maven/python-transpiler/src/test/resources/conformance/gen_flat.py new file mode 100644 index 00000000000..dab1b627a84 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/gen_flat.py @@ -0,0 +1,71 @@ +# Exceptions passing through generators that resume one another: each one +# finishes, PEP 479 applies, and a handler around a yield from still sees it. + + +def boom(n): + for i in range(n): + yield i + raise ValueError("boom") + + +def stopper(): + yield 1 + raise StopIteration("early") + + +def relay(it): + for x in it: + yield x * 10 + + +def chain(depth, inner): + if depth == 0: + yield from inner + else: + yield from chain(depth - 1, inner) + + +def guarded(inner): + try: + yield from inner + except ValueError as e: + yield "caught " + str(e) + + +def collect(g): + out = [] + try: + for v in g: + out.append(v) + except Exception as e: + out.append(type(e).__name__ + ": " + str(e)) + return out + + +b = boom(2) +r = relay(b) +print(collect(r)) +print(list(r), list(b)) +print(collect(relay(stopper()))) +c = chain(5, boom(3)) +print(collect(c)) +print(next(c, "done")) +print(collect(chain(3, stopper()))) +print(collect(guarded(chain(2, boom(1))))) +print(collect(relay(guarded(boom(2))))) +g = relay(boom(1)) +print(next(g)) +try: + next(g) +except ValueError as e: + print("raised", e) +print(next(g, "finished")) + + +def selfish(): + yield next(me) + + +me = selfish() +print(collect(me)) +print(sum(x for x in relay(relay(range(5))))) diff --git a/maven/python-transpiler/src/test/resources/conformance/gen_inline.out b/maven/python-transpiler/src/test/resources/conformance/gen_inline.out new file mode 100644 index 00000000000..26e345e6081 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/gen_inline.out @@ -0,0 +1,9 @@ +[0, 1, 2] ['n0', 'b0', 'n1', 'b1', 'n2', 'b2'] +60 10 +(36, 6) +[0, 1, 'at 2'] +([100, 101], 1) [100, 101] +[0, 1, 2, 3] +[(0, 0), (0, 1), (1, 0), (1, 1)] +2 +(2, [(1, [(0, []), (0, [])]), (1, [(0, []), (0, [])])]) [3, 5] [3, 5] diff --git a/maven/python-transpiler/src/test/resources/conformance/gen_inline.py b/maven/python-transpiler/src/test/resources/conformance/gen_inline.py new file mode 100644 index 00000000000..1596b0cf225 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/gen_inline.py @@ -0,0 +1,114 @@ +log = [] + +def numbers(n): + i = 0 + while i < n: + log.append("n%d" % i) + yield i + i += 1 + +def evens(it): + for x in it: + if x % 2 == 0: + yield x + +def scaled(it, k): + for x in it: + yield x * k + +def interleave(): + out = [] + for v in numbers(3): + log.append("b%d" % v) + out.append(v) + return out + +print(interleave(), log) + +def pipeline(n): + total = 0 + for v in scaled(evens(numbers(n)), 3): + total += v + return total + +del log[:] +print(pipeline(10), len(log)) + +def sums(n): + a = sum(x * 3 for x in evens(numbers(n))) + c = 1 + c += sum(1 for d in numbers(n) if d > 2) + return a, c + +print(sums(8)) + +def boom(n): + for i in range(n): + if i == 2: + raise ValueError("at %d" % i) + yield i + +def catcher(): + seen = [] + try: + for v in boom(5): + seen.append(v) + except ValueError as e: + seen.append(str(e)) + return seen + +print(catcher()) + +base = 100 + +def offset(n): + for i in range(n): + yield i + base + +def clash(): + base = 1 + return [v for v in offset(2)], base + +def noclash(): + r = [] + for v in offset(2): + r.append(v) + return r + +print(clash(), noclash()) + +def early(): + r = [] + for v in numbers(100): + if v > 3: + break + r.append(v) + return r + +print(early()) + +def nested_loops(): + r = [] + for a in numbers(2): + for b in numbers(2): + r.append((a, b)) + return r + +print(nested_loops()) + +def leaked(): + for v in numbers(3): + pass + return v + +print(leaked()) + +def tree(depth, fan): + if depth == 0: + return (depth, []) + return (depth, [tree(depth - 1, fan) for _ in range(fan)]) + +def spread(depth, fan): + return [depth * i + fan for i in range(fan) if i != depth] + +print(tree(2, 2), spread(1, 3), spread(2, 3)) diff --git a/maven/python-transpiler/src/test/resources/conformance/getattribute_dunder.strict b/maven/python-transpiler/src/test/resources/conformance/getattribute_dunder.strict new file mode 100644 index 00000000000..be2bddca64c --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/getattribute_dunder.strict @@ -0,0 +1,2 @@ +main:1 class Spy has no layout: its body binds __getattribute__ +main:19 class Fake has no layout: its body binds __getattribute__ diff --git a/maven/python-transpiler/src/test/resources/conformance/guessed_overrides.out b/maven/python-transpiler/src/test/resources/conformance/guessed_overrides.out new file mode 100644 index 00000000000..661bc36fccc --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/guessed_overrides.out @@ -0,0 +1,17 @@ +['START', 'startstart', 4.0, 'yes', 3, 1, 'heavy'] +['DYN', 'dyndyn', 7.0, 'no', 3, 1, 'heavy'] +['7', 14, 9, 'no', 4, 9, 'heavy'] +["['a']", ['a', 'a'], 3, 'yes', 4, 'a'] +zero zerozero +start startstart +2 4 +6 ab [1, 2] +43 +Back 4 +aa +bbbb +cccccc +['fb', 'fb', 'fb', 'fb'] +['real', 'real', 'fb', 'real', 'fb', 'fb'] +['fb'] +['fb', 'real'] diff --git a/maven/python-transpiler/src/test/resources/conformance/guessed_overrides.py b/maven/python-transpiler/src/test/resources/conformance/guessed_overrides.py new file mode 100644 index 00000000000..1a2915098a6 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/guessed_overrides.py @@ -0,0 +1,127 @@ +# Guessed field, local and return types: a value of another type stored +# where the compiler guessed one must read back exactly, through typed +# expressions over it, truth tests, arithmetic and method calls. + + +class Box: + def __init__(self): + self.label = "start" + self.weight = 1.5 + self.flag = True + self.items = [1, 2] + self.child = None + + +class Node: + def __init__(self, name): + self.name = name + + +def fill(obj, attrs): + for k, v in attrs.items(): + setattr(obj, k, v) + + +def describe(b): + out = [] + out.append(b.label.upper() if isinstance(b.label, str) else repr(b.label)) + out.append(b.label + b.label) + out.append(b.weight * 2 + 1) + out.append("yes" if b.flag else "no") + out.append(len(b.items) + 1) + out.append(b.items[0]) + if b.weight > 1: + out.append("heavy") + return out + + +def pick(n): + if n == 0: + return "zero" + r = getattr(Box(), "label") + return r if n == 1 else n + + +def total(xs): + acc = xs[0] + for x in xs[1:]: + acc = acc + x + return acc + + +b = Box() +print(describe(b)) +fill(b, {"label": "dyn", "weight": 3.0, "flag": False}) +print(describe(b)) +fill(b, {"label": 7, "weight": 4, "flag": [], "items": (9, 8, 7)}) +print(describe(b)) +fill(b, {"label": ["a"], "weight": True, "flag": "x", "items": "abc"}) +print(describe(b)) +for i in range(3): + v = pick(i) + print(v, v * 2) +print(total([1, 2, 3]), total(["a", "b"]), total([[1], [2]])) +n = Node("n1") +setattr(n, "name", 42) +print(n.name + 1) +setattr(n, "name", "back") +print(n.name.title(), len(n.name)) +words = "a bb ccc".split() +for w in words: + w = w * 2 + print(w) + + +class Fallback: + def tag(self): + return "fb" + + +class Real: + def tag(self): + return "real" + + +class Holder: + def __init__(self): + self.first = Fallback() + self.all = [Fallback()] + + +def walk(h): + x = h.first + out = [x.tag()] + for x in getattr(h, "all"): + out.append(x.tag()) + for x in h.all: + out.append(x.tag()) + out.append(x.tag()) + return out + + +h = Holder() +print(walk(h)) +fill(h, {"first": Real(), "all": [Real(), Fallback()]}) +print(walk(h)) + + +class Doc: + def __init__(self): + self.xrefs = [] + self.xrefs.append(Fallback()) + + def names(self): + out = [] + for xref in self.xrefs: + out.append(xref.tag()) + return out + + +def add_any(d, v): + getattr(d, "xrefs").append(v) + + +d = Doc() +print(d.names()) +add_any(d, Real()) +print(d.names()) diff --git a/maven/python-transpiler/src/test/resources/conformance/hashlib_blake2_blocks.out b/maven/python-transpiler/src/test/resources/conformance/hashlib_blake2_blocks.out new file mode 100644 index 00000000000..bcf4de8c202 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/hashlib_blake2_blocks.out @@ -0,0 +1,27 @@ +0 786a02f742015903c6c6fd852552d272912f4740e15847618a86e217f71f5419d25e1031afee585313896444934eb04b903a685b1448b755d56f701afe9be2ce +0 69217a3079908094e11121d042354a7c1f55b6482ca1a51e1b250dfd1ed0eef9 +1 dc19b62fbd4e480a12134892649b0c86c21540830bf61aa81e7e13868e7d23ed78ed66b94f6ea8bb779261b98782745fc85ad1dfe9b07859ed77c28b94eaac85 +1 6b821f55cab354e67d82cd1ae7c29b69dbdfc28072eb2e0e375e9ad798fedc70 +63 96a4646a2c8d50eda88a8ce645f2e1b6b8f3ca3abdab7ef095997f8b1e6e8ae2fb8767f2f9238011a9758ab7d0fbed9c96fa34528b169fed65eb24abc0ed84bb +63 09b00532b122d13b57d7ac541ad072bdf2811eefa4b092c881f8d550ddc18d41 +64 7f7b84dae9ba53172b941f0f0d588ce38c60842ea94ae0f66f397048f3e787122e76873aa058212b97455b282e974fd7fbd85fb864e4a9fb0dad73609cbd4461 +64 0c736ac5cf5b56f4817ca60a259904ed52d12627d9a229706c54c682652ba9f1 +65 a45f100c5a3b4acaf7a6fb4b3b2dc3e456495fc8acdc6f7af0959b3b7f13c1a7895e2abe30dd00345c7ab406bad58e36f015b2ad60350aa846f85a1280d143ce +65 d6d4450df251e3801775ffeebb90f8c6b7652c3baec55a1afdfa0d7c1e017d99 +127 3dd556bc15bb8a1c16ce9bc28f245325f5bfc50e84f44c539b7172295d22d81b613a19324b278b3a06dca69a7c9f7d38b9862fa8f2230a9818fe126ef207aa17 +127 370dc4bbc49201a0dba43845aef3fb76ac8eb4f9bbf88fe3bd4c7d7d3754c09f +128 88134c9c2bda5481ec42b0d53611231ab7c21ccbbbcf5bc813acffea3eef47c1bb198748d222a9a0d0899631eb39b8c63d61ab1bc8128196e615dc9032ebf5bf +128 9d311d9173e3948ddf703fe64e1b2d365135991fff447f0b956f4c13e5eadd02 +129 458471021bb1880be73a9a9054316b4b5b83cd27e0ece6f76987d52eb53ccea9ea89e5f1d5a45343536d439e4a125e733c41f2aef79aa299d076a10fc3b283f2 +129 ebbe2e900b7750ea0ab601a5fe6d07f0b4d6c6ce223fc9cf3e3961d0bde0cfb0 +255 ea9d73087e808d78c1ca9232ed9d191d2a6f53d0c47cc4a68771f4b02ed44f48986b7b580854daefcfc1368e58620b7efa1eb22d92f9e52f55ee66ef2fbda14b +255 e016d483ce263c371dc7eac45beda8ffa3c51a563c16ea9b7293086ddb4b06e9 +256 8055742fadd993ad58a28ef85b80e63059a8944b9fc74e65ff7dbbc6a133ac5fa7ea85ff285e7e93d1cb52e1e6ec49cc6a2c56183a953b91982dfcb6aee9e0fd +256 94d45b5532b2917fe8566242e624fcd9b51037f264124e0072c23b337aa5f69c +257 63f5c18ab71397eabc3132a907d887f845c7f16c3fbb406a90a3c1e350de7a1cd2ea07077c90a309b7f2797bf0f46a97b5f9d5570fa725042ad34ea788fa4a7c +257 0a6ffc4f4594994b305f58b0e2b1cd696b8b827d77434fab381018774f94b5fd +700 57ae4fc63c4c1e44eeb8be40ed1254c1f4a83dacbb5becec7ac99300b84259cb8a8319144fce86a1abd4478c5fda3ca07c82bc19904f7f80e2a1378e713da654 +700 8edb65d190039d3a5227ea2075c5fa4faa94259188ff8f20bcaa3995afc6775c +aaf6cf461ca304db1a64ded3afa50b2f +4d953d83b923bd79540753b220607b66b841945f 8a93abe455d9de321ca51f76a7d5481ff07ac978 +50dd597a70b2b0682d3e005e65e28ac492130997e64a1ef1385475df08e1d4fa diff --git a/maven/python-transpiler/src/test/resources/conformance/hashlib_blake2_blocks.py b/maven/python-transpiler/src/test/resources/conformance/hashlib_blake2_blocks.py new file mode 100644 index 00000000000..32d56d5327d --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/hashlib_blake2_blocks.py @@ -0,0 +1,21 @@ +import hashlib + +# Lengths on both sides of the 128 byte block of BLAKE2b and the 64 byte one +# of BLAKE2s, whole and fed in pieces. +data = bytes((i * 31 + 7) % 256 for i in range(700)) +for n in (0, 1, 63, 64, 65, 127, 128, 129, 255, 256, 257, 700): + print(n, hashlib.blake2b(data[:n]).hexdigest()) + print(n, hashlib.blake2s(data[:n]).hexdigest()) + +h = hashlib.blake2b(digest_size=16, key=b"a key", salt=b"salt", person=b"me") +for start in range(0, 700, 37): + h.update(data[start:start + 37]) +print(h.hexdigest()) + +h = hashlib.blake2b(digest_size=20) +h.update(data[:128]) +c = h.copy() +h.update(data[128:300]) +c.update(b"other") +print(h.hexdigest(), c.hexdigest()) +print(hashlib.blake2b(b"x" * 100000, digest_size=32).hexdigest()) diff --git a/maven/python-transpiler/src/test/resources/conformance/hero_fastpaths.out b/maven/python-transpiler/src/test/resources/conformance/hero_fastpaths.out new file mode 100644 index 00000000000..fd7d35a9e34 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/hero_fastpaths.out @@ -0,0 +1,34 @@ +datetime True True +2:00:00 True +MyDT True +datetime.datetime(1970, 1, 1, 0, 0, tzinfo=datetime.timezone.utc) 1970-01-01T00:00:00+00:00 1970-01-01T00:00:00.000+00:00 +datetime.datetime(1970, 1, 1, 2, 0, tzinfo=datetime.timezone(datetime.timedelta(seconds=7200), 'X')) 1970-01-01T02:00:00+02:00 1970-01-01T02:00:00.000+02:00 +datetime.datetime(2023, 11, 14, 22, 13, 20, tzinfo=datetime.timezone.utc) 2023-11-14T22:13:20+00:00 2023-11-14T22:13:20.000+00:00 +datetime.datetime(2023, 11, 15, 0, 13, 20, tzinfo=datetime.timezone(datetime.timedelta(seconds=7200), 'X')) 2023-11-15T00:13:20+02:00 2023-11-15T00:13:20.000+02:00 +datetime.datetime(2023, 11, 14, 22, 13, 20, 500000, tzinfo=datetime.timezone.utc) 2023-11-14T22:13:20.500000+00:00 2023-11-14T22:13:20.500+00:00 +datetime.datetime(2023, 11, 15, 0, 13, 20, 500000, tzinfo=datetime.timezone(datetime.timedelta(seconds=7200), 'X')) 2023-11-15T00:13:20.500000+02:00 2023-11-15T00:13:20.500+02:00 +datetime.datetime(2023, 11, 14, 22, 13, 20, tzinfo=datetime.timezone.utc) 2023-11-14T22:13:20+00:00 2023-11-14T22:13:20.000+00:00 +datetime.datetime(2023, 11, 15, 0, 13, 20, tzinfo=datetime.timezone(datetime.timedelta(seconds=7200), 'X')) 2023-11-15T00:13:20+02:00 2023-11-15T00:13:20.000+02:00 +datetime.datetime(2023, 11, 14, 22, 13, 20, 1, tzinfo=datetime.timezone.utc) 2023-11-14T22:13:20.000001+00:00 2023-11-14T22:13:20.000+00:00 +datetime.datetime(2023, 11, 15, 0, 13, 20, 1, tzinfo=datetime.timezone(datetime.timedelta(seconds=7200), 'X')) 2023-11-15T00:13:20.000001+02:00 2023-11-15T00:13:20.000+02:00 +datetime.datetime(1969, 12, 31, 23, 59, 58, 750000, tzinfo=datetime.timezone.utc) 1969-12-31T23:59:58.750000+00:00 1969-12-31T23:59:58.750+00:00 +datetime.datetime(1970, 1, 1, 1, 59, 58, 750000, tzinfo=datetime.timezone(datetime.timedelta(seconds=7200), 'X')) 1970-01-01T01:59:58.750000+02:00 1970-01-01T01:59:58.750+02:00 +2024-02-29T00:00:00+02:00 True True +2024-03-01T01:01:00.999999+02:00 True True +2023-01-24T23:59:59.999999+02:00 True True +2024-01-01T00:00:00+00:00 2024-01-01T00:00:00.000005 +cf4ab791c62b8d2b2109c90275287816 True +True +fe42f4108dd98f9b4f19fb21f386dfbe True +name='a' size=2 name='b' size=0 +ValidationError True +name='d' size=1 tag='u' name='e' size=3 +[(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6)] +(0,) (1,) +[(2,), (3,)] (99,) +(0,) +(3,) None [] +(7,) +{'a': 3, 'b': None} {'x': 1, 'y': 2} +('p', 1) {'q': 2, 'r': 3} [] +{} {'k': b'v'} diff --git a/maven/python-transpiler/src/test/resources/conformance/hero_fastpaths.py b/maven/python-transpiler/src/test/resources/conformance/hero_fastpaths.py new file mode 100644 index 00000000000..7c0d1b60fbb --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/hero_fastpaths.py @@ -0,0 +1,135 @@ +# +# Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. +# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. +# +# This code is free software; you can redistribute it and/or modify it +# under the terms of the GNU General Public License version 2 only, as +# published by the Free Software Foundation. Codename One designates this +# particular file as subject to the "Classpath" exception as provided +# by Oracle in the LICENSE file that accompanied this code. +# +# This code is distributed in the hope that it will be useful, but WITHOUT +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +# version 2 for more details (a copy is included in the LICENSE file that +# accompanied this code). +# +# You should have received a copy of the GNU General Public License version +# 2 along with this work; if not, write to the Free Software Foundation, +# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. +# +# Please contact Codename One through http://www.codenameone.com/ if you +# need additional information or have any questions. + +# The fast paths the llm hero port added, each held to what the general path +# answers: datetime's fixed-offset construction, blake2b's digest that keeps +# hashing, pydantic's cached field plan, and sqlite3 cursors that keep the +# read lock while rows are pending. +import datetime +import hashlib +import sqlite3 +import time + +from pydantic import BaseModel, field_validator + +utc = datetime.timezone.utc +plus2 = datetime.timezone(datetime.timedelta(hours=2), "X") + +# now(): a fixed offset goes the fast way, a subclass the general one. +n = datetime.datetime.now(utc) +print(type(n).__name__, n.tzinfo is utc, abs(n.timestamp() - time.time()) < 5) +n2 = datetime.datetime.now(plus2) +print(n2.utcoffset(), abs((n2 - n).total_seconds()) < 5) + + +class MyDT(datetime.datetime): + pass + + +m = MyDT.now(utc) +print(type(m).__name__, m.tzinfo is utc) + +# fromtimestamp, integral and fractional, with half-even microseconds. +for ts in (0, 1700000000, 1700000000.5, 1700000000.0000005, 1700000000.0000015, -1.25): + for tz in (utc, plus2): + d = datetime.datetime.fromtimestamp(ts, tz) + print(repr(d), d.isoformat(), d.isoformat(timespec="milliseconds")) + +# Addition and isoformat against a value built field by field. +base = datetime.datetime(2024, 2, 28, 23, 59, 59, 999999, tzinfo=plus2) +for delta in (datetime.timedelta(microseconds=1), datetime.timedelta(days=1, seconds=3661), + datetime.timedelta(days=-400)): + s = base + delta + print(s.isoformat(), s == datetime.datetime(s.year, s.month, s.day, s.hour, s.minute, s.second, + s.microsecond, tzinfo=plus2), hash(s) == hash(s.replace())) +print(datetime.datetime(2024, 1, 1, tzinfo=utc).isoformat(), datetime.datetime(2024, 1, 1, 0, 0, 0, 5).isoformat()) + +# blake2b: hexdigest twice, then more data, matches a fresh hash of the whole. +h = hashlib.blake2b(b"abc", digest_size=16) +first = h.hexdigest() +print(first, first == h.hexdigest()) +h.update(b"def" * 50) +print(h.hexdigest() == hashlib.blake2b(b"abc" + b"def" * 50, digest_size=16).hexdigest()) +big = hashlib.blake2b(b"x" * 300) +print(big.hexdigest()[:32], big.digest() == big.digest()) + + +# pydantic: the plan is rebuilt when the class's fields change. +class Item(BaseModel): + name: str + size: int = 0 + + @field_validator("size") + @classmethod + def positive(cls, v): + if v < 0: + raise ValueError("negative") + return v + + +print(Item(name="a", size=2), Item(name="b")) +try: + Item(name="c", size=-1) +except Exception as e: + print(type(e).__name__, "negative" in str(e)) + + +class Extra(Item): + tag: str = "t" + + +print(Extra(name="d", size=1, tag="u"), Item(name="e", size=3)) + +# sqlite3: a cursor iterated while other queries run, one abandoned part way, +# and the statements a held read must never stand in the way of. +db = sqlite3.connect(":memory:") +db.execute("create table t (v integer)") +db.executemany("insert into t values (?)", [(i,) for i in range(6)]) +db.commit() +out = [] +for (v,) in db.execute("select v from t order by v"): + out.append((v, db.execute("select count(*) from t where v <= ?", (v,)).fetchone()[0])) +print(out) +half = db.execute("select v from t order by v") +print(half.fetchone(), half.fetchone()) +db.execute("insert into t values (99)") +db.commit() +print(half.fetchall()[:2], db.execute("select max(v) from t").fetchone()) +part = db.execute("select v from t order by v") +print(part.fetchone()) +part.close() +db.execute("create table gone (x)") +db.execute("drop table gone") +one = db.execute("select v from t where v = 3") +print(one.fetchone(), one.fetchone(), one.fetchall()) +db.execute("vacuum") +print(db.execute("select count(*) from t").fetchone()) +db.close() + +# dict(zip(keys, row)): a list or tuple of keys against a tuple, read straight +# into the dict, and a zip already part consumed. +keys = ["a", "b", "a", "c"] +print(dict(zip(keys, (1, None, 3))), dict(zip(("x", "y"), (1, 2, 3)))) +z = zip(["p", "q", "r"], (1, 2, 3)) +print(next(z), dict(z), list(z)) +print(dict(zip([], ())), dict(zip(["k"], (b"v",)))) diff --git a/maven/python-transpiler/src/test/resources/conformance/hero_ports.out b/maven/python-transpiler/src/test/resources/conformance/hero_ports.out new file mode 100644 index 00000000000..a2387e0e506 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/hero_ports.out @@ -0,0 +1,26 @@ +debug True +coroutine True True +generator True False +deleted False +AttributeError 'function' object has no attribute 'missing' +hints [('return', ), ('x', )] +object init (self, /, *args, **kwargs) +in transaction after script False +in transaction after insert True +udf [(2,), (4,), (6,)] +OperationalError user-defined function raised exception +threads saw ['unset', 'main'] main still main +cancelling 1 +uncancel 0 +cancelled True +callback saw in callback context +factory used [1] True +runner done +asyncio.run slept +signatures (a, b, /, c, *, d) (a, /) +TypeError only_positional() got some positional-only arguments passed as keyword arguments: 'a' +to kwargs (1, {'a': 2}) 2 +60 True y False +45 True b 6 +44 True True True +20 diff --git a/maven/python-transpiler/src/test/resources/conformance/hero_ports.py b/maven/python-transpiler/src/test/resources/conformance/hero_ports.py new file mode 100644 index 00000000000..c7dc19fa158 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/hero_ports.py @@ -0,0 +1,167 @@ +# Runtime behaviour the llm and MarkItDown ports depend on (anyio, click, +# sqlite-utils, the openai SDK). +import asyncio +import collections.abc +import contextvars +import functools +import inspect +import sqlite3 +import threading +import typing + +print("debug", __debug__) + + +# collections.abc recognises native coroutines and generators structurally. +async def coro(): + return 1 + + +c = coro() +print("coroutine", isinstance(c, collections.abc.Coroutine), isinstance(c, collections.abc.Awaitable)) +c.close() + + +def gen(): + yield 1 + + +print("generator", isinstance(gen(), collections.abc.Generator), isinstance([], collections.abc.Generator)) + + +# Attributes on functions can be deleted, as click does with its params. +def f(): + pass + + +f.__click_params__ = [1] +del f.__click_params__ +print("deleted", hasattr(f, "__click_params__")) +try: + del f.missing +except AttributeError as e: + print("AttributeError", e) + + +# get_type_hints follows __wrapped__ to the function's own globals. +def hinted(x: int) -> str: + return str(x) + + +@functools.wraps(hinted) +def wrapper(*a, **k): + return hinted(*a, **k) + + +print("hints", sorted(typing.get_type_hints(wrapper).items(), key=lambda kv: kv[0])) +print("object init", inspect.signature(object.__init__)) + +# executescript runs statements as written: no implicit transaction. +con = sqlite3.connect(":memory:") +con.execute("create table t (x)") +con.executescript("insert into t values (1); insert into t values (2);") +print("in transaction after script", con.in_transaction) +con.execute("insert into t values (3)") +print("in transaction after insert", con.in_transaction) +con.commit() + +# User-defined SQL functions. +con.create_function("double", 1, lambda v: v * 2) +print("udf", con.execute("select double(x) from t order by x").fetchall()) + + +def boom(v): + raise ValueError("no") + + +con.create_function("boom", 1, boom) +try: + con.execute("select boom(1)").fetchall() +except sqlite3.OperationalError as e: + print("OperationalError", e) +con.close() + +# Each thread has its own context; Thread(context=) runs in the one given. +var = contextvars.ContextVar("var", default="unset") +var.set("main") +seen = [] +t = threading.Thread(target=lambda: seen.append(var.get())) +t.start() +t.join() +ctx = contextvars.copy_context() +t = threading.Thread(target=lambda: seen.append(var.get()), context=ctx) +t.start() +t.join() +print("threads saw", seen, "main still", var.get()) + + +# asyncio: Runner, cancelling/uncancel, callbacks in their context, task factory. +async def child(): + await asyncio.sleep(10) + + +async def main(): + task = asyncio.ensure_future(child()) + await asyncio.sleep(0) + task.cancel() + print("cancelling", task.cancelling()) + print("uncancel", task.uncancel()) + try: + await task + except asyncio.CancelledError: + print("cancelled", task.cancelled()) + loop = asyncio.get_running_loop() + done = loop.create_future() + ctx = contextvars.copy_context() + ctx.run(var.set, "in callback context") + loop.call_soon(lambda: done.set_result(var.get()), context=ctx) + print("callback saw", await done) + made = [] + + def factory(loop, coro, **kwargs): + made.append(1) + return asyncio.Task(coro, loop=loop, **kwargs) + + loop.set_task_factory(factory) + await loop.create_task(asyncio.sleep(0)) + print("factory used", made, loop.get_task_factory() is factory) + return "done" + + +with asyncio.Runner() as runner: + print("runner", runner.run(main())) +print("asyncio.run", asyncio.run(asyncio.sleep(0, "slept"))) + + +def positional(a, b, /, c, *, d): + pass + + +def only_positional(a, /): + pass + + +print("signatures", inspect.signature(positional), inspect.signature(only_positional)) +try: + only_positional(a=1) +except TypeError as e: + print("TypeError", e) + + +def posonly_kwargs(a, /, **kw): + return a, kw + + +print("to kwargs", posonly_kwargs(1, a=2), positional.__code__.co_posonlyargcount) + + +# Code points of long strings: pairs are one, a lone surrogate is one too, +# and indexing a long string in a loop sees the same answer each time. +long_pairs = "x\U0001F600y" * 20 +print(len(long_pairs), long_pairs[1] == "\U0001F600", long_pairs[-1], long_pairs[30:33] == "\U0001F600yx") +lone = "a\ud800b" * 15 +print(len(lone), lone[1] == "\ud800", lone[44], len(lone[3:9])) +mixed = "\ud83d" + "\U0001F600" * 12 + "\ude00" + "z" * 30 +print(len(mixed), mixed[0] == "\ud83d", mixed[13] == "\ude00", mixed[1] == "\U0001F600") +print(sum(1 for i in range(len(long_pairs)) if long_pairs[i] == "y")) + diff --git a/maven/python-transpiler/src/test/resources/conformance/immutable_slots.out b/maven/python-transpiler/src/test/resources/conformance/immutable_slots.out new file mode 100644 index 00000000000..9a8fc58ae0c --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/immutable_slots.out @@ -0,0 +1,8 @@ +True False False True True +Tag(name='div', prefix=None) +True False 2 False +Group(tags=(Tag(name='div', prefix=None), Tag(name='div', prefix='svg')), inverse=True) +Group(tags=(Tag(name='div', prefix=None),), inverse=False) +['div', 'svg'] False +2 +False False diff --git a/maven/python-transpiler/src/test/resources/conformance/immutable_slots.py b/maven/python-transpiler/src/test/resources/conformance/immutable_slots.py new file mode 100644 index 00000000000..8eb60567112 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/immutable_slots.py @@ -0,0 +1,125 @@ +# Immutable slot classes in the soupsieve style: the compiler writes each +# constructor and slot reader (ImmutableSlots). +def _repr_value(value: object) -> object: + return value if isinstance(value, Immutable) else repr(value) + + +class Immutable: + __slots__: tuple[str, ...] = ('_hash',) + + _hash: int + + def __init__(self, **kwargs: object) -> None: + temp = [] + for k, v in kwargs.items(): + temp.append(type(v)) + temp.append(v) + super().__setattr__(k, v) + super().__setattr__('_hash', hash(tuple(temp))) + + @classmethod + def __base__(cls) -> type: + return cls + + def __eq__(self, other: object) -> bool: + stack: list[tuple[Immutable, object]] = [(self, other)] + while stack: + a, b = stack.pop() + if a is b: + continue + if not isinstance(b, a.__base__()) or a._hash != b._hash: + return False + for key in a.__slots__[:-1]: + x = getattr(a, key) + y = getattr(b, key) + if isinstance(x, Immutable): + stack.append((x, y)) + elif x.__class__ is tuple and y.__class__ is tuple: + if len(x) != len(y): + return False + for i, j in zip(x, y): + if isinstance(i, Immutable): + stack.append((i, j)) + elif i != j: + return False + elif x != y: + return False + return True + + def __ne__(self, other: object) -> bool: + return not self.__eq__(other) + + def __hash__(self) -> int: + return self._hash + + def __setattr__(self, name: str, value: object) -> None: + raise AttributeError(f"'{self.__class__.__name__}' is immutable") + + def __repr__(self) -> str: + output: list[str] = [] + stack: list[object] = [self] + while stack: + item = stack.pop() + if item.__class__ is str: + output.append(item) + elif isinstance(item, Immutable): + stack.append(')') + keys = item.__slots__[:-1] + for index in range(len(keys) - 1, -1, -1): + stack.append(_repr_value(getattr(item, keys[index]))) + stack.append(f'{keys[index]}=' if index == 0 else f', {keys[index]}=') + stack.append(f'{item.__class__.__name__}(') + else: + stack.append(',)' if len(item) == 1 else ')') + for index in range(len(item) - 1, -1, -1): + stack.append(_repr_value(item[index])) + if index: + stack.append(', ') + stack.append('(') + return ''.join(output) + + __str__ = __repr__ + + +class Tag(Immutable): + __slots__ = ("name", "prefix", "_hash") + + name: str + prefix: str | None + + def __init__(self, name: str, prefix: str | None) -> None: + super().__init__(prefix=prefix, name=name) + + +class Group(Immutable): + __slots__ = ("tags", "inverse", "_hash") + + tags: tuple[Tag, ...] + inverse: bool + + def __init__(self, tags: list[Tag], inverse: bool = False) -> None: + super().__init__(tags=tuple(tags), inverse=inverse) + + def count(self) -> int: + return len(self.tags) + + +def values(obj: Immutable) -> list[object]: + vals = [getattr(obj, s) for s in obj.__slots__[:-1]] + return vals + + +a = Tag("div", None) +b = Tag("div", None) +c = Tag("div", "svg") +print(a == b, a != b, a == c, a != c, hash(a) == hash(b)) +print(a) +g1 = Group([a, c], True) +g2 = Group([b, c], True) +g3 = Group([b, a]) +print(g1 == g2, g1 == g3, g1.count(), g3.inverse) +print(repr(g1)) +print(str(Group([a]))) +print(values(c), values(g3)[1]) +print(len({a, b, c})) +print(a == "div", Tag("p", None) == Group([])) diff --git a/maven/python-transpiler/src/test/resources/conformance/introspect.strict b/maven/python-transpiler/src/test/resources/conformance/introspect.strict new file mode 100644 index 00000000000..2339649811d --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/introspect.strict @@ -0,0 +1 @@ +main:33 class Fz has no layout: its body binds __delattr__ diff --git a/maven/python-transpiler/src/test/resources/conformance/isinstance_mixin_base.out b/maven/python-transpiler/src/test/resources/conformance/isinstance_mixin_base.out new file mode 100644 index 00000000000..888905fccc8 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/isinstance_mixin_base.out @@ -0,0 +1,2 @@ +True True True False 2 +[True, True, True, True] diff --git a/maven/python-transpiler/src/test/resources/conformance/isinstance_mixin_base.py b/maven/python-transpiler/src/test/resources/conformance/isinstance_mixin_base.py new file mode 100644 index 00000000000..b0591edf0e5 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/isinstance_mixin_base.py @@ -0,0 +1,42 @@ +# isinstance against a class an instance derives from only through a base +# other than its first: the test passes, and the instance is still read. + + +class Base: + def __init__(self, el): + self._el = el + + def __eq__(self, other): + if not isinstance(other, Base): + return False + return self._el is other._el + + def __hash__(self): + return id(self._el) + + +class Shape(Base): + pass + + +class Inherits: + def __init__(self, el): + self._el = el + + def width(self): + return len(self._el) + + +class Placeholder(Inherits, Shape): + pass + + +def same(a, b): + return a == b + + +el = ["x", "y"] +s = Shape(el) +p = Placeholder(el) +print(same(s, p), same(p, s), same(s, Shape(el)), same(s, Shape([])), p.width()) +print([same(a, b) for a in (s, p) for b in (p, s)]) diff --git a/maven/python-transpiler/src/test/resources/conformance/jinja_loader_names.strict b/maven/python-transpiler/src/test/resources/conformance/jinja_loader_names.strict new file mode 100644 index 00000000000..b1e927fa141 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/jinja_loader_names.strict @@ -0,0 +1 @@ +main:3 template missing.html is in no directory of the program's template loaders; the build compiles only the templates it can see diff --git a/maven/python-transpiler/src/test/resources/conformance/jinja_loader_names/main.py b/maven/python-transpiler/src/test/resources/conformance/jinja_loader_names/main.py new file mode 100644 index 00000000000..80eb68384a9 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/jinja_loader_names/main.py @@ -0,0 +1,5 @@ +from jinja2 import Environment, FileSystemLoader + +env = Environment(loader=FileSystemLoader("templates")) +print(env.get_template("page.html").render(user={"name": "x"})) +print(env.get_template("missing.html").render()) diff --git a/maven/python-transpiler/src/test/resources/conformance/jinja_loader_names/templates/page.html b/maven/python-transpiler/src/test/resources/conformance/jinja_loader_names/templates/page.html new file mode 100644 index 00000000000..6968bdead4b --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/jinja_loader_names/templates/page.html @@ -0,0 +1 @@ +

{{ user.name }}

diff --git a/maven/python-transpiler/src/test/resources/conformance/jinja_loader_unseen.py b/maven/python-transpiler/src/test/resources/conformance/jinja_loader_unseen.py new file mode 100644 index 00000000000..bf0771a114d --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/jinja_loader_unseen.py @@ -0,0 +1,4 @@ +from jinja2 import Environment, FileSystemLoader + +env = Environment(loader=FileSystemLoader("no_such_templates")) +print(env.get_template("page.html").render(user={"name": "x"})) diff --git a/maven/python-transpiler/src/test/resources/conformance/jinja_loader_unseen.strict b/maven/python-transpiler/src/test/resources/conformance/jinja_loader_unseen.strict new file mode 100644 index 00000000000..9ed163f372f --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/jinja_loader_unseen.strict @@ -0,0 +1 @@ +main:3 FileSystemLoader reads no_such_templates/, where the build sees no template file; templates are compiled at build time from the project's files diff --git a/maven/python-transpiler/src/test/resources/conformance/known_attr_names.out b/maven/python-transpiler/src/test/resources/conformance/known_attr_names.out new file mode 100644 index 00000000000..b4e154a7c4f --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/known_attr_names.out @@ -0,0 +1,4 @@ +2 3 p +20 30 +relabelled 6 p +LOUD eats diff --git a/maven/python-transpiler/src/test/resources/conformance/known_attr_names.py b/maven/python-transpiler/src/test/resources/conformance/known_attr_names.py new file mode 100644 index 00000000000..d8b7a45f2af --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/known_attr_names.py @@ -0,0 +1,61 @@ +# setattr/getattr with a name taken from a fixed set of strings: each name +# is a store or read of its own, and the same name in another scope is +# another variable. + + +class Point: + def __init__(self, x, y): + self.x = x + self.y = y + self.tag = "p" + + def copy(self): + c = Point(0, 0) + for attr in ("x", "y"): + setattr(c, attr, getattr(self, attr)) + return c + + def scaled(self, k): + c = Point(0, 0) + attr = "x" + setattr(c, attr, getattr(self, attr) * k) + # A comprehension's `attr` is its own variable, not the local above. + [setattr(c, attr, getattr(self, attr) * k) for attr in ["y"]] + return c + + def relabel(self): + name = "tag" + + def inner(): + nonlocal name + name = "x" + + inner() + setattr(self, name, "relabelled") + return self + + +class Animal: + def speak(self): + return "..." + + def eat(self): + return "eats" + + +def loud(self): + return "LOUD" + + +for meth in ("speak",): + setattr(Animal, meth, loud) + +p = Point(2, 3) +q = p.copy() +print(q.x, q.y, q.tag) +s = p.scaled(10) +print(s.x, s.y) +r = Point(5, 6).relabel() +print(r.x, r.y, r.tag) +a = Animal() +print(a.speak(), a.eat()) diff --git a/maven/python-transpiler/src/test/resources/conformance/known_helpers_.out b/maven/python-transpiler/src/test/resources/conformance/known_helpers_.out new file mode 100644 index 00000000000..a0451d8b1b1 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/known_helpers_.out @@ -0,0 +1,13 @@ +b b +2 1 1 +b 2 None +DeprecationWarning Write to deprecated property nextSibling. (Replaced by next_sibling) -- Deprecated since version 4.0.0. +DeprecationWarning Access to deprecated property nextSibling. (Replaced by next_sibling) -- Deprecated since version 4.0.0. +DeprecationWarning Call to deprecated method findAll. (Replaced by find_all) -- Deprecated since version 4.0.0. +DeprecationWarning Call to deprecated method findAll. (Replaced by find_all) -- Deprecated since version 4.0.0. +DeprecationWarning Call to deprecated method findAll. (Replaced by find_all) -- Deprecated since version 4.0.0. +DeprecationWarning Call to deprecated method findChild. (Replaced by find) -- Deprecated since version 4.0.0. +DeprecationWarning Call to deprecated method fetch. (Replaced by find_all) -- Deprecated since version 4.0.0. +DeprecationWarning Call to deprecated method findChild. (Replaced by find) -- Deprecated since version 4.0.0. +fetch findChild +True diff --git a/maven/python-transpiler/src/test/resources/conformance/known_helpers_/bs4/__init__.py b/maven/python-transpiler/src/test/resources/conformance/known_helpers_/bs4/__init__.py new file mode 100644 index 00000000000..f3461dbdf18 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/known_helpers_/bs4/__init__.py @@ -0,0 +1,10 @@ +from ._deprecation import ( + _deprecated, +) +from .element import Node + + +class Soup(Node): + @_deprecated("find", "4.0.0") + def findChild(self, name): + return self.find(name) diff --git a/maven/python-transpiler/src/test/resources/conformance/known_helpers_/bs4/_deprecation.py b/maven/python-transpiler/src/test/resources/conformance/known_helpers_/bs4/_deprecation.py new file mode 100644 index 00000000000..95d1e669c40 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/known_helpers_/bs4/_deprecation.py @@ -0,0 +1,38 @@ +# The shape of bs4's own helpers: Codename One compiles their uses as what +# they mean (KnownHelpers), and this program checks that matches CPython. +import functools +import warnings + + +def _deprecated_alias(old_name, new_name, version): + @property + def alias(self): + warnings.warn(f"Access to deprecated property {old_name}. (Replaced by {new_name}) -- Deprecated since version {version}.", DeprecationWarning, stacklevel=2) + return getattr(self, new_name) + + @alias.setter + def alias(self, value): + warnings.warn(f"Write to deprecated property {old_name}. (Replaced by {new_name}) -- Deprecated since version {version}.", DeprecationWarning, stacklevel=2) + return setattr(self, new_name, value) + + return alias + + +def _deprecated_function_alias(old_name, new_name, version): + def alias(self, *args, **kwargs): + warnings.warn(f"Call to deprecated method {old_name}. (Replaced by {new_name}) -- Deprecated since version {version}.", DeprecationWarning, stacklevel=2) + return getattr(self, new_name)(*args, **kwargs) + + return alias + + +def _deprecated(replaced_by, version): + def deprecate(func): + @functools.wraps(func) + def with_warning(*args, **kwargs): + warnings.warn(f"Call to deprecated method {func.__name__}. (Replaced by {replaced_by}) -- Deprecated since version {version}.", DeprecationWarning, stacklevel=2) + return func(*args, **kwargs) + + return with_warning + + return deprecate diff --git a/maven/python-transpiler/src/test/resources/conformance/known_helpers_/bs4/element.py b/maven/python-transpiler/src/test/resources/conformance/known_helpers_/bs4/element.py new file mode 100644 index 00000000000..1e7dfaf4a5e --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/known_helpers_/bs4/element.py @@ -0,0 +1,29 @@ +from bs4._deprecation import ( + _deprecated, + _deprecated_alias, + _deprecated_function_alias, +) + + +class Node: + def __init__(self, name, children=None): + self.name = name + self.next_sibling = None + self.children = children or [] + + nextSibling = _deprecated_alias("nextSibling", "next_sibling", "4.0.0") + findAll = _deprecated_function_alias( + "findAll", "find_all", "4.0.0" + ) + + def find_all(self, name, limit=None): + found = [c for c in self.children if c.name == name] + return found if limit is None else found[:limit] + + def find(self, name): + r = self.find_all(name, 1) + return r[0] if r else None + + @_deprecated("find_all", "4.0.0") + def fetch(self, name): + return self.find_all(name) diff --git a/maven/python-transpiler/src/test/resources/conformance/known_helpers_/main.py b/maven/python-transpiler/src/test/resources/conformance/known_helpers_/main.py new file mode 100644 index 00000000000..c767e3ecbcb --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/known_helpers_/main.py @@ -0,0 +1,18 @@ +import warnings + +from bs4 import Soup +from bs4.element import Node + +a = Node("a") +b = Node("b") +s = Soup("root", [a, b, Node("a")]) +with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + a.nextSibling = b + print(a.next_sibling.name, a.nextSibling.name) + print(len(s.findAll("a")), len(s.findAll("a", limit=1)), len(s.findAll(name="b"))) + print(s.findChild("b").name, len(s.fetch("a")), s.findChild("z")) +for w in caught: + print(w.category.__name__, w.message) +print(Node.fetch.__name__, Soup.findChild.__name__) +print(isinstance(Node.nextSibling, property)) diff --git a/maven/python-transpiler/src/test/resources/conformance/kwonly_logging.out b/maven/python-transpiler/src/test/resources/conformance/kwonly_logging.out new file mode 100644 index 00000000000..a8eb7363be3 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/kwonly_logging.out @@ -0,0 +1,6 @@ +True 0 True False +'INFO:hi' +'INFO:hi\n' +'INFO:hi\nINFO:hi\n' +'INFO:hi\nINFO:hi\nINFO:hi\n' +'INFO:hi\nINFO:hi\nINFO:hi\nINFO:root info\n' diff --git a/maven/python-transpiler/src/test/resources/conformance/kwonly_logging.py b/maven/python-transpiler/src/test/resources/conformance/kwonly_logging.py new file mode 100644 index 00000000000..be6ca5ac8ae --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/kwonly_logging.py @@ -0,0 +1,17 @@ +import logging +from io import StringIO + +out = StringIO() +logging.basicConfig(stream=out, level=logging.INFO, format="%(levelname)s:%(message)s") +h = logging.root.handlers[0] +print(h.stream is out, h.level, logging.root.isEnabledFor(20), logging.root.disabled) +r = logging.LogRecord("n", 20, "p", 1, "hi", None, None) +print(repr(h.format(r))) +h.emit(r) +print(repr(out.getvalue())) +h.handle(r) +print(repr(out.getvalue())) +logging.root.handle(r) +print(repr(out.getvalue())) +logging.info("root info") +print(repr(out.getvalue())) diff --git a/maven/python-transpiler/src/test/resources/conformance/kwonly_typed.out b/maven/python-transpiler/src/test/resources/conformance/kwonly_typed.out new file mode 100644 index 00000000000..53ba5503ad4 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/kwonly_typed.out @@ -0,0 +1,14 @@ +3999000 +6 12 20 2.5 1.0 +8 6 48 +748500 +TypeError Box.__init__() takes 2 positional arguments but 3 were given +TypeError Box.__init__() missing 1 required keyword-only argument: 'h' +TypeError scale() takes 1 positional argument but 2 were given +TypeError Box.area() takes 1 positional argument but 2 were given +TypeError Box.grow() takes 2 positional arguments but 3 were given +TypeError Box.__init__() got an unexpected keyword argument 'q' +TypeError scale() got an unexpected keyword argument 'zz' +15 7 +[(99.0, 'dflt', 'a'), (10.0, 'dflt', 'b'), (10.0, 'dflt', 'c'), (99.0, 't', 'd')] +1 diff --git a/maven/python-transpiler/src/test/resources/conformance/kwonly_typed.py b/maven/python-transpiler/src/test/resources/conformance/kwonly_typed.py new file mode 100644 index 00000000000..aa78c3fa73b --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/kwonly_typed.py @@ -0,0 +1,74 @@ +def scale(x, *, by=2, add=0): + return x * by + add + + +class Box: + def __init__(self, w, *, h, depth=1.0): + self.w = w + self.h = h + self.depth = depth + + def area(self, *, factor=1): + return self.w * self.h * factor + + def grow(self, n, *, step): + return Box(self.w + n * step, h=self.h + step) + + +total = 0 +for i in range(1000): + total += scale(i) + scale(i, by=3) + scale(i, add=1, by=1) + scale(x=i, add=2) +print(total) + +b = Box(2, h=3) +c = Box(w=4, depth=2.5, h=5) +print(b.area(), b.area(factor=2), c.area(), c.depth, b.depth) +g = b.grow(2, step=3) +print(g.w, g.h, g.area()) +acc = 0 +for i in range(500): + acc += Box(i, h=2).area(factor=3) +print(acc) + +for bad in (lambda: Box(1, 2), lambda: Box(1), lambda: scale(1, 2), lambda: b.area(2), lambda: b.grow(1, 2), + lambda: Box(1, h=2, q=3), lambda: scale(1, by=2, zz=3)): + try: + bad() + except TypeError as e: + print("TypeError", e) + +opts = {"by": 5} +print(scale(3, **opts), Box(1, **{"h": 7}).area()) + +GENERIC = 10.0 +SPECIFIC = 0.0 +NAME = "dflt" + + +class Registry: + SPECIFIC = 99.0 + + def __init__(self): + self.items = [] + + def add(self, item, *, priority=SPECIFIC, tag=NAME): + self.items.append((priority, tag, item)) + + def add_generic(self, item, priority=GENERIC): + self.add(item, priority=priority) + + +reg = Registry() +reg.add("a") +reg.add("b", priority=GENERIC) +reg.add_generic("c") +reg.add("d", tag="t") +print(reg.items) + + +def late(x=LATER if False else 1): + return x + + +LATER = 5 +print(late()) diff --git a/maven/python-transpiler/src/test/resources/conformance/kwshared_.out b/maven/python-transpiler/src/test/resources/conformance/kwshared_.out new file mode 100644 index 00000000000..3a6ddbae574 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/kwshared_.out @@ -0,0 +1,11 @@ +['a'] +['a', 'ab'] +[3, 6, 2, 4] +[4, 5, 6, 7] +[True, False, False, True, 'y', 'n', 'n', 'y'] +['x', 'abc'] +['x', 'abc'] +True +False f +[True, False, False, True, 'y', 'n', 'n', 'y'] +patched diff --git a/maven/python-transpiler/src/test/resources/conformance/kwshared_.py b/maven/python-transpiler/src/test/resources/conformance/kwshared_.py new file mode 100644 index 00000000000..81882dfd0b8 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/kwshared_.py @@ -0,0 +1,110 @@ +# Keyword calls every override binds alike, constant truth tests, and the +# desugared next()/StopIteration loop. + + +class Filter: + def __init__(self, tag): + self.tag = tag + + def match(self, element, _known=False): + return _known or element == self.tag + + def scale(self, x, factor=2): + return x * factor + + def run(self, items): + out = [] + for i in items: + if self.match(i, _known=False): + out.append(i) + return out + + def scaled(self, xs): + return [self.scale(x, factor=3) for x in xs] + [self.scale(x) for x in xs] + + +class Strainer(Filter): + def match(self, element, _known=False): + return element.startswith(self.tag) + + def scale(self, x, factor=5): + return x + factor + + +class Node: + def __init__(self, name): + self.name = name + + def __bool__(self): + return True + + def __len__(self): + return 0 + + +class Empty(Node): + def __bool__(self): + """Never true.""" + return False + + +class Counted(Node): + def __bool__(self): + return len(self.name) > 2 + + +class Late: + def __bool__(self): + return True + + +def truths(nodes): + return [bool(n) for n in nodes] + ["y" if n else "n" for n in nodes] + + +def drain(it): + out = [] + while True: + try: + v = next(it) + except StopIteration: + break + if v: + out.append(v.name) + return out + + +def gen(nodes): + for n in nodes: + yield n + + +print(Filter("a").run(["a", "ab", "b"])) +print(Strainer("a").run(["a", "ab", "b"])) +print(Filter("a").scaled([1, 2])) +print(Strainer("a").scaled([1, 2])) +nodes = [Node("x"), Empty("e"), Counted("ab"), Counted("abc")] +print(truths(nodes)) +print(drain(gen(nodes))) +print(drain(iter(nodes))) +late = Late() +print(bool(late)) +Late.__bool__ = lambda self: False +print(bool(late), "t" if late else "f") +Node.__bool__ = lambda self: self.name == "x" +print(truths(nodes)) + + +def next(it, *rest): + return Node("patched") + + +def once(): + try: + v = next(iter([])) + except StopIteration: + return "stopped" + return v.name + + +print(once()) diff --git a/maven/python-transpiler/src/test/resources/conformance/liveness_.out b/maven/python-transpiler/src/test/resources/conformance/liveness_.out new file mode 100644 index 00000000000..e5397aacbca --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/liveness_.out @@ -0,0 +1,6 @@ +chain leaf +fast backend +alpha +beta +starred +late diff --git a/maven/python-transpiler/src/test/resources/conformance/liveness_/lp/__init__.py b/maven/python-transpiler/src/test/resources/conformance/liveness_/lp/__init__.py new file mode 100644 index 00000000000..9a1b1e216d4 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/liveness_/lp/__init__.py @@ -0,0 +1,11 @@ +from importlib import import_module + + +def backend(name): + return import_module(f"lp.backends._{name}") + + +def __getattr__(name): + if name == "late": + return import_module(".lazyattr", __name__).LATE + raise AttributeError(name) diff --git a/maven/python-transpiler/src/test/resources/conformance/liveness_/lp/backends/__init__.py b/maven/python-transpiler/src/test/resources/conformance/liveness_/lp/backends/__init__.py new file mode 100644 index 00000000000..e69de29bb2d diff --git a/maven/python-transpiler/src/test/resources/conformance/liveness_/lp/backends/_fast.py b/maven/python-transpiler/src/test/resources/conformance/liveness_/lp/backends/_fast.py new file mode 100644 index 00000000000..db2cc1cf5e9 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/liveness_/lp/backends/_fast.py @@ -0,0 +1 @@ +name = "fast backend" diff --git a/maven/python-transpiler/src/test/resources/conformance/liveness_/lp/backends/_slow.py b/maven/python-transpiler/src/test/resources/conformance/liveness_/lp/backends/_slow.py new file mode 100644 index 00000000000..6bcb9f4995d --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/liveness_/lp/backends/_slow.py @@ -0,0 +1 @@ +name = "slow backend" diff --git a/maven/python-transpiler/src/test/resources/conformance/liveness_/lp/chain.py b/maven/python-transpiler/src/test/resources/conformance/liveness_/lp/chain.py new file mode 100644 index 00000000000..56fc1629d23 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/liveness_/lp/chain.py @@ -0,0 +1,3 @@ +from . import mid +def top(): + return "chain " + mid.middle() diff --git a/maven/python-transpiler/src/test/resources/conformance/liveness_/lp/lazyattr.py b/maven/python-transpiler/src/test/resources/conformance/liveness_/lp/lazyattr.py new file mode 100644 index 00000000000..c1440e39d0a --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/liveness_/lp/lazyattr.py @@ -0,0 +1 @@ +LATE = "late" diff --git a/maven/python-transpiler/src/test/resources/conformance/liveness_/lp/leaf.py b/maven/python-transpiler/src/test/resources/conformance/liveness_/lp/leaf.py new file mode 100644 index 00000000000..25b6cf2fd00 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/liveness_/lp/leaf.py @@ -0,0 +1 @@ +LEAF = "leaf" diff --git a/maven/python-transpiler/src/test/resources/conformance/liveness_/lp/mid.py b/maven/python-transpiler/src/test/resources/conformance/liveness_/lp/mid.py new file mode 100644 index 00000000000..2fb386e9b0f --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/liveness_/lp/mid.py @@ -0,0 +1,3 @@ +from .leaf import LEAF +def middle(): + return LEAF diff --git a/maven/python-transpiler/src/test/resources/conformance/liveness_/lp/plugins/__init__.py b/maven/python-transpiler/src/test/resources/conformance/liveness_/lp/plugins/__init__.py new file mode 100644 index 00000000000..e69de29bb2d diff --git a/maven/python-transpiler/src/test/resources/conformance/liveness_/lp/plugins/alpha.py b/maven/python-transpiler/src/test/resources/conformance/liveness_/lp/plugins/alpha.py new file mode 100644 index 00000000000..46372761122 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/liveness_/lp/plugins/alpha.py @@ -0,0 +1 @@ +ALPHA = "alpha" diff --git a/maven/python-transpiler/src/test/resources/conformance/liveness_/lp/plugins/beta.py b/maven/python-transpiler/src/test/resources/conformance/liveness_/lp/plugins/beta.py new file mode 100644 index 00000000000..abb10b33ccc --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/liveness_/lp/plugins/beta.py @@ -0,0 +1 @@ +VALUE = "beta" diff --git a/maven/python-transpiler/src/test/resources/conformance/liveness_/lp/star.py b/maven/python-transpiler/src/test/resources/conformance/liveness_/lp/star.py new file mode 100644 index 00000000000..3300a46731d --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/liveness_/lp/star.py @@ -0,0 +1,3 @@ +__all__ = ["starred"] +def starred(): + return "starred" diff --git a/maven/python-transpiler/src/test/resources/conformance/liveness_/lp/unused.py b/maven/python-transpiler/src/test/resources/conformance/liveness_/lp/unused.py new file mode 100644 index 00000000000..0c8242063cb --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/liveness_/lp/unused.py @@ -0,0 +1 @@ +raise RuntimeError("never imported") diff --git a/maven/python-transpiler/src/test/resources/conformance/liveness_/main.py b/maven/python-transpiler/src/test/resources/conformance/liveness_/main.py new file mode 100644 index 00000000000..405bb781985 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/liveness_/main.py @@ -0,0 +1,30 @@ +import importlib +import typing +from typing import TYPE_CHECKING +import lp + +if TYPE_CHECKING: + import lp.unused +if typing.TYPE_CHECKING: + from lp import unused + + +def lazy(): + # Imported only inside a function that runs. + from lp import chain + return chain.top() + + +print(lazy()) +print(lp.backend("fast").name) +print(importlib.import_module(".plugins.alpha", "lp").ALPHA) +mod, _, attr = "lp.plugins.beta:VALUE".partition(":") +print(getattr(importlib.import_module(mod), attr)) +from lp.star import * +print(starred()) +print(lp.__getattr__("late")) + + +def never(): + import lp.unused + return lp.unused diff --git a/maven/python-transpiler/src/test/resources/conformance/loop_unroll.out b/maven/python-transpiler/src/test/resources/conformance/loop_unroll.out new file mode 100644 index 00000000000..2b83ab0fe7b --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/loop_unroll.out @@ -0,0 +1,10 @@ +[('a', 1)] +[('a', 1), ('c', 3)] +[('a', 1), ('c', 3)] +[('a', 1)] +[('left', 'L'), ('right', None)] +1 3 +False +1 3 +['1', 'c', 'L', 'left'] +6 diff --git a/maven/python-transpiler/src/test/resources/conformance/loop_unroll.py b/maven/python-transpiler/src/test/resources/conformance/loop_unroll.py new file mode 100644 index 00000000000..a62773e6d4c --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/loop_unroll.py @@ -0,0 +1,108 @@ +# A loop over attribute names the program spells out is unrolled per name, +# per concrete class where the names come from a class tuple; and a method +# with an annotated name parameter is specialized like any other. + +FIELDS = ("left", "right") + + +class Model: + __attrs__ = ("a", "b") + + def __init__(self): + self.a = 1 + self.b = None + self.c = 3 + self.left = "L" + self.right = None + + def __iter__(self): + for attr in self.__attrs__: + value = getattr(self, attr) + if value is not None: + yield attr, value + + def skipping(self): + out = [] + for attr in ("a", "b", "c", "left"): + if attr == "b": + continue + value = getattr(self, attr) + for ch in str(value): + if ch == "3": + continue + out.append(ch) + if value == 1: + continue + out.append(attr) + return out + + def sides(self): + out = [] + for k in FIELDS: + v = getattr(self, k, "none") + out.append((k, v)) + return out + + def copy_into(self, other): + for k in ["a", "c"]: + if hasattr(self, k): + setattr(other, k, getattr(self, k)) + return other + + def clear(self): + for k in ("left",): + if hasattr(self, k): + delattr(self, k) + + def get(self, name: str) -> object: + return getattr(self, name) + + +class Wide(Model): + __attrs__ = Model.__attrs__ + ("c",) + + +class Wider(Wide): + pass + + +class Same(Model): + pass + + +class Target: + def __init__(self): + self.a = 0 + self.c = 0 + + +print(list(Model())) +print(list(Wide())) +print(list(Wider())) +print(list(Same())) +print(Model().sides()) +t = Model().copy_into(Target()) +print(t.a, t.c) +m = Model() +m.clear() +print(hasattr(m, "left")) +print(m.get("a"), m.get("c")) +print(Model().skipping()) + + +class Box: + def __init__(self): + self.top = 1 + self.left = 2 + self.right = 3 + + def total(self): + # A loop over a function local bound once to a literal list. + names = ['top', 'left', 'right'] + out = 0 + for name in names: + out += getattr(self, name) + return out + + +print(Box().total()) diff --git a/maven/python-transpiler/src/test/resources/conformance/loop_unroll_comp.out b/maven/python-transpiler/src/test/resources/conformance/loop_unroll_comp.out new file mode 100644 index 00000000000..55797682d17 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/loop_unroll_comp.out @@ -0,0 +1,5 @@ +False [('a', 0), ('b', '')] +True +True [('a', 0), ('b', ''), ('d', 4)] +[('bullets', '*+-'), ('keep', []), ('wrap', True)] ['bullets', 'keep', 'wrap'] +{'bullets': '*+-', 'keep': [], 'wrap': False} True diff --git a/maven/python-transpiler/src/test/resources/conformance/loop_unroll_comp.py b/maven/python-transpiler/src/test/resources/conformance/loop_unroll_comp.py new file mode 100644 index 00000000000..c1086b30b3b --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/loop_unroll_comp.py @@ -0,0 +1,63 @@ +# A list comprehension over attribute names the program spells out becomes +# a list display, per concrete class; and a dir()-based options helper over a +# nested options class becomes a dict display of the class's public names. + + +class Part: + __attrs__ = ("a", "b") + __elements__ = ("c",) + + def __init__(self): + self.a = 0 + self.b = "" + self.c = None + + def __bool__(self): + parts = [getattr(self, attr) for attr in self.__attrs__ + self.__elements__] + return any(parts) + + def names(self): + return [(n, getattr(self, n)) for n in self.__attrs__] + + +class Wide(Part): + __attrs__ = ("a", "b", "d") + + def __init__(self): + Part.__init__(self) + self.d = 4 + + +def _todict(obj): + return dict((k, getattr(obj, k)) for k in dir(obj) if not k.startswith('_')) + + +class Converter(object): + class DefaultOptions: + wrap = False + bullets = '*+-' + _hidden = 1 + keep = [] + + class Options(DefaultOptions): + pass + + def __init__(self, **options): + self.options = _todict(self.DefaultOptions) + self.options.update(_todict(self.Options)) + self.options.update(options) + + +class Custom(Converter): + pass + + +p = Part() +print(bool(p), p.names()) +p.c = 5 +print(bool(p)) +w = Wide() +print(bool(w), w.names()) +c = Converter(wrap=True) +print(sorted(c.options.items(), key=lambda kv: kv[0]), list(c.options)) +print(Custom().options, Custom().options["keep"] is Converter().options["keep"]) diff --git a/maven/python-transpiler/src/test/resources/conformance/loop_unroll_fold.out b/maven/python-transpiler/src/test/resources/conformance/loop_unroll_fold.out new file mode 100644 index 00000000000..3ee7775cf67 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/loop_unroll_fold.out @@ -0,0 +1,2 @@ +[('cropbox', 1), ('rects', ['rect']), ('lines', ['line']), ('ax', 4), ('bx', 4)] +[('cropbox', 1), ('trimbox', 2), ('rects', ['rect']), ('lines', ['line']), ('ax', 4), ('bx', 4)] diff --git a/maven/python-transpiler/src/test/resources/conformance/loop_unroll_fold.py b/maven/python-transpiler/src/test/resources/conformance/loop_unroll_fold.py new file mode 100644 index 00000000000..f0759cfceba --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/loop_unroll_fold.py @@ -0,0 +1,29 @@ +# Loops over literal names whose attribute name is a pure string +# transform of the loop variable, folded to a literal at build time. + + +class Box: + def __init__(self, attrs): + for name in ["CropBox", "TrimBox"]: + # a comment between the header and the body + if name in attrs: + setattr(self, name.lower(), attrs[name]) + for t in ("rect", "line"): + setattr(self, t + "s", [t]) + for u in ("a", "b"): + setattr(self, "pre_" + u, (u + "x", 2 * len(u + "y"))) + + def report(self): + out = [] + for cs in ["cropbox", "trimbox", "rects", "lines"]: + + # blank and comment lines before the body + if hasattr(self, cs): + out.append((cs, getattr(self, cs))) + for k in ("PRE_A", "PRE_B"): + out.append(getattr(self, k.lower())) + return out + + +print(Box({"CropBox": 1}).report()) +print(Box({"CropBox": 1, "TrimBox": 2}).report()) diff --git a/maven/python-transpiler/src/test/resources/conformance/loop_unroll_stores.out b/maven/python-transpiler/src/test/resources/conformance/loop_unroll_stores.out new file mode 100644 index 00000000000..2a218c2861c --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/loop_unroll_stores.out @@ -0,0 +1,6 @@ +[[('a', 1), ('b', 2)], [('a', 1), ('b', 2)]] +[[('c', 3)], [('c', 3)]] +[('x', 10), ('y', 20)] +sqrt 1.5811388300841898 +floor 2 +ceil 3 diff --git a/maven/python-transpiler/src/test/resources/conformance/loop_unroll_stores.py b/maven/python-transpiler/src/test/resources/conformance/loop_unroll_stores.py new file mode 100644 index 00000000000..3f54e5d05f6 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/loop_unroll_stores.py @@ -0,0 +1,51 @@ +# Attribute stores reach only the classes their receiver can be; a loop +# over a class tuple elsewhere still unrolls, and one at module level too. +import math + + +class Item: + __elements__ = ("a", "b") + + def __init__(self): + self.a = 1 + self.b = 2 + self.c = 3 + + def retag(self): + self.__elements__ = ("c",) + + def dump(self): + return [(n, self.a if n == "a" else self.b if n == "b" else self.c) for n in self.__elements__] + + +class Fill: + __elements__ = ("x", "y") + + def __init__(self): + self.x = 10 + self.y = 20 + + def dump(self): + out = [] + for name in self.__elements__: + out.append((name, getattr(self, name))) + return out + + +class Holder: + def __init__(self): + self.items = [Item(), Item()] + + def retag(self): + for s in self.items: + s.retag() + + +h = Holder() +print([i.dump() for i in h.items]) +h.retag() +print([i.dump() for i in h.items]) +print(Fill().dump()) + +for name in ["sqrt", "floor", "ceil"]: + print(name, getattr(math, name)(2.5)) diff --git a/maven/python-transpiler/src/test/resources/conformance/metaclass_layout.out b/maven/python-transpiler/src/test/resources/conformance/metaclass_layout.out new file mode 100644 index 00000000000..faba45f2193 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/metaclass_layout.out @@ -0,0 +1,7 @@ +False {'a': 1, 'b': 2} True 12 +6 6 False hello +AttributeError missing +instance does not see metaclass property +True 1 Config Singleton +SubSwap True 8 True True True +Swap 10 Swap diff --git a/maven/python-transpiler/src/test/resources/conformance/metaclass_layout.py b/maven/python-transpiler/src/test/resources/conformance/metaclass_layout.py new file mode 100644 index 00000000000..4d7dca6465a --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/metaclass_layout.py @@ -0,0 +1,95 @@ +class LazyMeta(type): + _populated = False + + @property + def table(cls): + if not cls._populated: + cls._fill() + return cls._table + + def _fill(cls): + cls._table = {"a": 1, "b": 2} + cls._populated = True + + @property + def mode(cls): + return cls._mode + + @mode.setter + def mode(cls, v): + cls._mode = v * 2 + + def __getattr__(cls, name): + if name.startswith("dyn_"): + return name[4:] + raise AttributeError(name) + + +class Lazy(metaclass=LazyMeta): + def __init__(self, v): + self.v = v + + def get(self, k): + return type(self).table[k] + self.v + + +print(Lazy._populated, Lazy.table, Lazy._populated, Lazy(10).get("b")) +Lazy.mode = 3 +print(Lazy.mode, Lazy._mode, "mode" in Lazy.__dict__, Lazy.dyn_hello) +try: + Lazy.missing +except AttributeError as e: + print("AttributeError", e) +try: + Lazy(1).table +except AttributeError: + print("instance does not see metaclass property") + + +class Singleton(type): + def __init__(cls, name, bases, ns): + super().__init__(name, bases, ns) + cls._inst = None + + def __call__(cls, *a, **k): + if cls._inst is None: + cls._inst = super().__call__(*a, **k) + return cls._inst + + +class Config(metaclass=Singleton): + def __init__(self, n): + self.n = n + + +c1 = Config(1) +c2 = Config(2) +print(c1 is c2, c1.n, type(c1).__name__, type(Config).__name__) + + +class Swap(type): + def __new__(mcs, name, bases, ns): + ns["made_by"] = mcs.__name__ + ns["double"] = lambda self: self.x * 2 + return super().__new__(mcs, name, bases, ns) + + +class SubSwap(Swap): + def __new__(mcs, name, bases, ns): + cls = super().__new__(mcs, name, bases, ns) + cls.sub = True + return cls + + +class S(metaclass=SubSwap): + def __init__(self, x): + self.x = x + + +class T(S): + pass + + +print(S.made_by, S.sub, T(4).double(), type(T) is SubSwap, isinstance(T, Swap), issubclass(SubSwap, type)) +Dyn = Swap("Dyn", (object,), {"x": 5}) +print(Dyn.made_by, Dyn().double(), type(Dyn).__name__) diff --git a/maven/python-transpiler/src/test/resources/conformance/method_patching.out b/maven/python-transpiler/src/test/resources/conformance/method_patching.out new file mode 100644 index 00000000000..93868a035b5 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/method_patching.out @@ -0,0 +1,6 @@ +3 +30 +12 shape +shadowed hello b +poked poked holder 1 +99 2 2 diff --git a/maven/python-transpiler/src/test/resources/conformance/method_patching.py b/maven/python-transpiler/src/test/resources/conformance/method_patching.py new file mode 100644 index 00000000000..85251748156 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/method_patching.py @@ -0,0 +1,104 @@ +# Methods replaced by a store: each must be looked up per call, while the +# methods no store reaches stay typed. + + +def with_init(cls): + def __init__(self, v): + self.v = v * 10 + cls.__init__ = __init__ + return cls + + +class Plain: + def __init__(self, v): + self.v = v + + def get(self): + return self.v + + +class Decorated: + def __init__(self, v): + self.v = v + + def get(self): + return self.v + + +with_init(Decorated) + + +class Shape: + def __init__(self, n): + self.n = n + + def area(self): + return self.n * self.n + + def name(self): + return "shape" + + +def triple(self): + return self.n * 3 + + +Shape.area = triple + + +class Greeter: + def __init__(self, who): + self.who = who + + def greet(self): + return "hello " + self.who + + +g = Greeter("a") +g.greet = lambda: "shadowed" + + +class Holder: + def __init__(self): + self.k = 1 + + def describe(self): + return "holder %d" % self.k + + +holders = [Holder(), Holder()] + + +def poke(objs): + for o in objs: + o.describe = lambda: "poked" + + +poke(holders) + + +class Base: + def __init__(self): + self.x = 2 + + def value(self): + return self.x + + +class Child(Base): + pass + + +def patch_base(b: Base): + b.value = lambda: 99 + + +ch = Child() +patch_base(ch) + +print(Plain(3).get()) +print(Decorated(3).get()) +print(Shape(4).area(), Shape(4).name()) +print(g.greet(), Greeter("b").greet()) +print(holders[0].describe(), holders[1].describe(), Holder().describe()) +print(ch.value(), Child().value(), Base().value()) diff --git a/maven/python-transpiler/src/test/resources/conformance/mixin_first_base.out b/maven/python-transpiler/src/test/resources/conformance/mixin_first_base.out new file mode 100644 index 00000000000..9858446a436 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/mixin_first_base.out @@ -0,0 +1,6 @@ +6 dims 6 shape-kind 7 +20 dims 20 layout shape-kind 1 4 +True True False +['Layout', 'Placeholder', 'Dims', 'Shape', 'object'] +99 99 99 +99 diff --git a/maven/python-transpiler/src/test/resources/conformance/mixin_first_base.py b/maven/python-transpiler/src/test/resources/conformance/mixin_first_base.py new file mode 100644 index 00000000000..976c98ed915 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/mixin_first_base.py @@ -0,0 +1,87 @@ +# A field-free mixin first, the field-bearing base second: the class takes +# the second base's layout, lookups follow the C3 MRO. + + +class Dims: + @property + def area(self): + return self.w * self.h + + @property + def width(self): + v = getattr(super(Dims, self), "width") + if v is not None: + return v + return self._inherited("width") + + def _inherited(self, name): + b = self._base + if b is None: + return None + return getattr(b, name) + + @property + def _base(self): + raise NotImplementedError("subclass") + + def describe(self): + return "dims %d" % self.area + + +class Shape: + def __init__(self, w, h): + self.w = w + self.h = h + + def describe(self): + return "shape" + + @property + def width(self): + return None + + def kind(self): + return "shape-kind" + + +class Placeholder(Dims, Shape): + @property + def _base(self): + return Master(1, 1) + + def __init__(self, w, h, idx): + super().__init__(w, h) + self.idx = idx + + +class Master(Shape): + @property + def width(self): + return 99 + + +class Placeholder2(Dims, Shape): + @property + def _base(self): + return Master(1, 1) + + +class Slide(Dims, Shape): + @property + def _base(self): + return Placeholder2(5, 6) + + +class Layout(Placeholder): + def kind(self): + return "layout " + super().kind() + + +p = Placeholder(2, 3, 7) +print(p.area, p.describe(), p.kind(), p.idx) +q = Layout(4, 5, 1) +print(q.area, q.describe(), q.kind(), q.idx, q.w) +print(isinstance(q, Dims), isinstance(q, Shape), isinstance(p, Layout)) +print([k.__name__ for k in Layout.__mro__]) +print(p.width, q.width, Placeholder2(1, 2).width) +print(Slide(1, 1).width) diff --git a/maven/python-transpiler/src/test/resources/conformance/mixin_layouts.out b/maven/python-transpiler/src/test/resources/conformance/mixin_layouts.out new file mode 100644 index 00000000000..fe95b4be29f --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/mixin_layouts.out @@ -0,0 +1,7 @@ +text:char-a 3 3 1 a +True True ['Char', 'Item', 'Text', 'object'] +1 2 2 item2 +line1 4 True +5 6 +7 None +CHAR-A diff --git a/maven/python-transpiler/src/test/resources/conformance/mixin_layouts.py b/maven/python-transpiler/src/test/resources/conformance/mixin_layouts.py new file mode 100644 index 00000000000..e3490c6b7bb --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/mixin_layouts.py @@ -0,0 +1,80 @@ +# Compiled classes with extra bases: typing.Generic and method-only mixins. +from typing import Generic, TypeVar + +T = TypeVar("T") + + +class Text: + """A mixin: methods only, reached after the compiled chain.""" + + def get_text(self): + return "text:" + self.label() + + def __repr__(self): + return "<%s %s>" % (type(self).__name__, self.label()) + + +class Item: + def __init__(self, x): + self.x = x + self.width = 0 + + def label(self): + return "item%d" % self.x + + def grow(self, n): + for _ in range(n): + self.width += 1 + return self.width + + +class Char(Item, Text): + def __init__(self, x, c): + Item.__init__(self, x) + self.c = c + + def label(self): + return "char-" + self.c + + +class Box(Item, Generic[T]): + def __init__(self, x): + super().__init__(x) + self.items = [] + + def add(self, v: T): + self.items.append(v) + return len(self.items) + + +class Holder(Generic[T]): + def __init__(self, v): + self.v = v + + def get(self): + return self.v + + +class Line(Box): + def label(self): + return "line%d" % len(self.items) + + +def run(): + c = Char(1, "a") + print(c.get_text(), repr(c), c.grow(3), c.width, c.x, c.c) + print(isinstance(c, Text), isinstance(c, Item), [k.__name__ for k in type(c).__mro__]) + b = Box(2) + print(b.add("p"), b.add(c), b.grow(2), b.label()) + ln = Line(3) + ln.add(1) + print(ln.label(), ln.grow(4), isinstance(ln, Box)) + h = Holder(5) + print(h.get(), Holder[int](6).get()) + c.extra = 7 + print(c.extra, getattr(c, "missing", None)) + Text.shout = lambda self: self.label().upper() + print(c.shout()) + + +run() diff --git a/maven/python-transpiler/src/test/resources/conformance/mixin_super_mro.out b/maven/python-transpiler/src/test/resources/conformance/mixin_super_mro.out new file mode 100644 index 00000000000..d5c17cd382b --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/mixin_super_mro.out @@ -0,0 +1,5 @@ +['Nested', 'Convertible', 'Typed', 'Descriptor'] 41 a +['NestedValue', 'Nested', 'Convertible', 'Typed', 'Descriptor', 'object'] +['Nested', 'Descriptor'] x +[1, 2] c ['Nested', 'Descriptor'] 3 +True True True diff --git a/maven/python-transpiler/src/test/resources/conformance/mixin_super_mro.py b/maven/python-transpiler/src/test/resources/conformance/mixin_super_mro.py new file mode 100644 index 00000000000..23b0081f5d4 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/mixin_super_mro.py @@ -0,0 +1,58 @@ +# Two compiled bases that both bind a method a super() call names, and an +# extra base that binds __init__: every super() follows the C3 MRO of the +# instance's class, and construction runs the MRO's __init__. + + +class Descriptor: + def __init__(self, name=None, **kw): + self.name = name + self.log = [] + + def put(self, value): + self.log.append("Descriptor") + self.value = value + + +class Typed(Descriptor): + def put(self, value): + self.log.append("Typed") + super().put(value) + + +class Convertible(Typed): + def put(self, value): + self.log.append("Convertible") + super().put(int(value)) + + +class Nested(Descriptor): + def put(self, value): + self.log.append("Nested") + super().put(value) + + +class NestedValue(Nested, Convertible): + pass + + +class Choice(Descriptor): + def __init__(self, name=None, values=(), **kw): + self.values = list(values) + super().__init__(name, **kw) + + +class NestedChoice(Nested, Choice): + pass + + +n = NestedValue("a") +n.put("41") +print(n.log, n.value, n.name) +print([c.__name__ for c in NestedValue.__mro__]) +p = Nested("b") +p.put("x") +print(p.log, p.value) +c = NestedChoice("c", values=(1, 2)) +c.put(3) +print(c.values, c.name, c.log, c.value) +print(isinstance(c, Choice), isinstance(n, Convertible), isinstance(n, Nested)) diff --git a/maven/python-transpiler/src/test/resources/conformance/modnames_.strict b/maven/python-transpiler/src/test/resources/conformance/modnames_.strict new file mode 100644 index 00000000000..1c8be65c58b --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/modnames_.strict @@ -0,0 +1,3 @@ +pickle:1276 setattr with a computed name is reflection; write override = pickle.Unpickler._step in cn1-python.properties and its compliant body in cn1-python-overrides/pickle.Unpickler._step.py +pickle:1338 getattr with a computed name is reflection; write override = pickle.Unpickler.find_class in cn1-python.properties and its compliant body in cn1-python-overrides/pickle.Unpickler.find_class.py +pickle:225 getattr with a computed name is reflection; write override = pickle._getattribute in cn1-python.properties and its compliant body in cn1-python-overrides/pickle._getattribute.py diff --git a/maven/python-transpiler/src/test/resources/conformance/namedtuple_classes.out b/maven/python-transpiler/src/test/resources/conformance/namedtuple_classes.out new file mode 100644 index 00000000000..ff7940d934a --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/namedtuple_classes.out @@ -0,0 +1,11 @@ +Version(major=1, minor=2, micro=3) Version(major=1, minor=2, micro=4) {'major': 1, 'minor': 2, 'micro': 3} ('major', 'minor', 'micro') True 3 2 +Version(major=4, minor=5, micro=6) (1, 2, 3) True True +replace error TypeError +make error Expected 3 arguments, got 1 +Point(x=1, y=2) 1 2 A point. ('x', 'y') True Point(x=5, y=2) +{'x': , 'y': } +3 Point Version Version(major=1, minor=2, micro=3) +1 2 ['a', 'b'] True 9 [('a', 1), ('b', 2)] True +True False collections.abc Container +SplitResult(scheme='http', netloc='u:p@h.com:80', path='/a', query='q=1', fragment='f') h.com 80 http://u:p@h.com:80/a?q=1#f http://u:p@h.com:80/b?q=1#f SplitResultBytes(scheme=b'http', netloc=b'u:p@h.com:80', path=b'/a', query=b'q=1', fragment=b'f') +{'scheme': 'https', 'netloc': 'x.org', 'path': '/p', 'params': 'r', 'query': 'q', 'fragment': 'z'} True u:p@h.com:80 SplitResult diff --git a/maven/python-transpiler/src/test/resources/conformance/namedtuple_classes.py b/maven/python-transpiler/src/test/resources/conformance/namedtuple_classes.py new file mode 100644 index 00000000000..53aeb1fdff7 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/namedtuple_classes.py @@ -0,0 +1,64 @@ +# Named tuple classes written out at build time (NamedTupleLowering) and +# classes deriving from typing's collection aliases. +from collections import namedtuple +from typing import NamedTuple, Mapping, Container +from urllib.parse import urlsplit, urlparse + + +class Version(namedtuple("Version", ["major", "minor", "micro"])): + def bump(self): + return self._replace(micro=self.micro + 1) + + +class Point(NamedTuple): + """A point.""" + + x: int + y: int + + +class Frozen(Mapping[str, int]): + def __init__(self, d): + self._d = dict(d) + + def __getitem__(self, k): + return self._d[k] + + def __iter__(self): + return iter(self._d) + + def __len__(self): + return len(self._d) + + +class Bag(Container[int]): + def __init__(self, items): + self.items = items + + def __contains__(self, x): + return x in self.items + + +v = Version(1, 2, 3) +print(v, v.bump(), v._asdict(), v._fields, isinstance(v, tuple), len(v), v[1]) +print(Version._make([4, 5, 6]), tuple(v), v == (1, 2, 3), hash(v) == hash((1, 2, 3))) +try: + v._replace(nope=1) +except (TypeError, ValueError) as e: + print("replace error", type(e).__name__) +try: + Version._make([1]) +except TypeError as e: + print("make error", e) +p = Point(1, y=2) +print(p, p.x, p.y, Point.__doc__, Point._fields, Point.__bases__ == (tuple,), p._replace(x=5)) +print(Point.__annotations__ if not isinstance(Point.__annotations__, str) else "") +x, y = p +print(x + y, Point.__name__, Version.__name__, repr(v)) +f = Frozen({"a": 1, "b": 2}) +print(f["a"], len(f), sorted(f), "a" in f, f.get("z", 9), sorted(f.items()), f == {"a": 1, "b": 2}) +b = Bag([1, 2]) +print(1 in b, 3 in b, Frozen.__bases__[0].__module__, Bag.__mro__[1].__name__) +s = urlsplit("http://u:p@h.com:80/a?q=1#f") +print(s, s.hostname, s.port, s.geturl(), s._replace(path="/b").geturl(), s.encode()) +print(urlparse("https://x.org/p;r?q#z")._asdict(), isinstance(s, tuple), s[1], type(s).__name__) diff --git a/maven/python-transpiler/src/test/resources/conformance/namedtuple_percent.out b/maven/python-transpiler/src/test/resources/conformance/namedtuple_percent.out new file mode 100644 index 00000000000..06b7def396c --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/namedtuple_percent.out @@ -0,0 +1,8 @@ +1 and 'two' +Point(x=1, y='two') +<3|4> +Q(a=3, b=4) +Pair Pair +_SplitResultBase +_SplitResultBase +5-6 diff --git a/maven/python-transpiler/src/test/resources/conformance/namedtuple_percent.py b/maven/python-transpiler/src/test/resources/conformance/namedtuple_percent.py new file mode 100644 index 00000000000..f5b8ae8fd9f --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/namedtuple_percent.py @@ -0,0 +1,19 @@ +from collections import namedtuple +from urllib.parse import urlsplit + +P = namedtuple('Point', 'x y') + +class Q(namedtuple('Pair', ['a', 'b'])): + def show(self): + return "<%s|%s>" % self + +p = P(1, 'two') +print("%s and %r" % p) +print(repr(p)) +q = Q(3, 4) +print(q.show()) +print(repr(q)) +print(Q.__bases__[0].__name__, Q.__bases__[0].__qualname__) +print(type(urlsplit('http://a/b')).__bases__[0].__name__) +print(type(urlsplit('http://a/b')).__bases__[0].__qualname__) +print("%d-%d" % (5, 6)) diff --git a/maven/python-transpiler/src/test/resources/conformance/new_copy.out b/maven/python-transpiler/src/test/resources/conformance/new_copy.out new file mode 100644 index 00000000000..52ace4b8fb7 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/new_copy.out @@ -0,0 +1,7 @@ +Col 3 2.5 ws +1 +Row2 ws2 4 3 [0] +1 +Mixed ws3 201 t +s3 Dim3 +Dim4 s4 diff --git a/maven/python-transpiler/src/test/resources/conformance/new_copy.py b/maven/python-transpiler/src/test/resources/conformance/new_copy.py new file mode 100644 index 00000000000..785e115a1fc --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/new_copy.py @@ -0,0 +1,120 @@ +from copy import copy + + +class Dim: + def __init__(self, index=0, width=1.0, worksheet=None): + self.index = index + self.width = width + self.parent = worksheet + + def __copy__(self): + cp = self.__new__(self.__class__) + attrib = dict(self.__dict__) + attrib["worksheet"] = attrib.pop("parent") + cp.__init__(**attrib) + return cp + + +class Col(Dim): + pass + + +class Other: + def __init__(self, a): + self.a = a + + +d = copy(Col(3, 2.5, "ws")) +print(type(d).__name__, d.index, d.width, d.parent) +print(Other(1).a) + + +class Styled: + def __init__(self, sheet, style=None): + self.parent = sheet + self._style = style or [0] + + +class Strictish: + pass + + +class Dim2(Strictish, Styled): + def __init__(self, worksheet, index=0, style=None): + super().__init__(worksheet, style) + self.index = index + + def __copy__(self): + cp = self.__new__(self.__class__) + attrib = {"worksheet": self.parent, "index": self.index} + cp.__init__(**attrib) + cp._style = list(self._style) + return cp + + +class Row2(Dim2): + def __init__(self, worksheet, index=0, style=None, height=3): + super().__init__(worksheet, index, style) + self.height = height + + +class Unrelated: + def __init__(self, worksheet=None, index=None): + self.w = worksheet + + +r = copy(Row2("ws2", 4)) +print(type(r).__name__, r.parent, r.index, r.height, r._style) +print(Unrelated(1).w) + + +class Tagged: + tag = "t" + + +class Mixed(Tagged, Dim2): + def __init__(self, worksheet, index=0, style=None): + super().__init__(worksheet, index + 100, style) + + +m = copy(Mixed("ws3", 1)) +print(type(m).__name__, m.parent, m.index, m.tag) + + +class Meta(type): + def __new__(cls, name, bases, ns): + ns["made"] = name + return type.__new__(cls, name, bases, ns) + + +class Base3(metaclass=Meta): + pass + + +class Swap(type): + def __new__(cls, name, bases, ns): + return type.__new__(cls, name, (Unrelated,), ns) + + +class Odd(metaclass=Swap): + pass + + +class Dim3(Base3, Styled): + def __copy__(self): + cp = self.__new__(self.__class__) + cp.__init__(sheet=self.parent) + return cp + + +class Dim4(Odd, Styled): + def __copy__(self): + cp = self.__new__(self.__class__) + cp.__init__(worksheet=self.w) + return cp + + +c3 = copy(Dim3("s3")) +print(c3.parent, c3.made) +c4 = copy(Dim4(worksheet="s4")) +print(type(c4).__name__, c4.w) diff --git a/maven/python-transpiler/src/test/resources/conformance/new_copy.strict b/maven/python-transpiler/src/test/resources/conformance/new_copy.strict new file mode 100644 index 00000000000..8cdbdaaab67 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/new_copy.strict @@ -0,0 +1,2 @@ +main:99 class Odd has no layout: its metaclass Swap is not one defined once in the module, deriving from type and binding no hook besides __call__, __getattr__, __new__ and __init__ +main:110 class Dim4 has no layout: base Odd has no layout diff --git a/maven/python-transpiler/src/test/resources/conformance/object_init_call.out b/maven/python-transpiler/src/test/resources/conformance/object_init_call.out new file mode 100644 index 00000000000..c1ec500a03c --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/object_init_call.out @@ -0,0 +1,5 @@ +3 x t +5 7 +None a-b +('x', 1) 8 +identity (True, False) (True, False) 3 diff --git a/maven/python-transpiler/src/test/resources/conformance/object_init_call.py b/maven/python-transpiler/src/test/resources/conformance/object_init_call.py new file mode 100644 index 00000000000..9c5773ca1b1 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/object_init_call.py @@ -0,0 +1,74 @@ +class Text: + def get_text(self): + return "t" + + +class Item: + def __init__(self, w): + self.w = w + + +class Char(Item, Text): + def __init__(self, w, text): + Item.__init__(self, w) + Text.__init__(self) + self.text = text + + +class Other: + def __init__(self, a=1, b=2): + self.a = a + self.b = b + + +c = Char(3, "x") +print(c.w, c.text, c.get_text()) +print(Other(5).a, Other(b=7).b) +f = object.__init__ +print(f(c), str.join("-", ["a", "b"])) + + +class Text2: + pass + + +class Text3: + pass + + +class Char2(Item, Text2): + def __init__(self, w): + Item.__init__(self, w) + Text2.__init__(self, "x", k=1) + + +class Char3(Item, Text3): + def __init__(self, w): + Item.__init__(self, w) + Text3.__init__(self, w * 2) + + +def _t2_init(self, a, k=0): + self.t2 = (a, k) + + +Text2.__init__ = _t2_init +setattr(Text3, "__init__", lambda self, v: setattr(self, "t3", v)) +print(Char2(1).t2, Char3(4).t3) + + +class Plain: + def __init__(self, v): + self.v = v + + +class Child(Plain): + pass + + +def same_init(k): + init = getattr(k, "__init__", None) + return init is Plain.__init__, init is not Plain.__init__ + + +print("identity", same_init(Plain), same_init(Child), Plain(3).v) diff --git a/maven/python-transpiler/src/test/resources/conformance/object_protocol_.strict b/maven/python-transpiler/src/test/resources/conformance/object_protocol_.strict new file mode 100644 index 00000000000..1d399822fd2 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/object_protocol_.strict @@ -0,0 +1,2 @@ +main:24 class Counting has no layout: its body binds __getattribute__ +main:6 class Fallback has no layout: its body binds __getattribute__ diff --git a/maven/python-transpiler/src/test/resources/conformance/openmix_.out b/maven/python-transpiler/src/test/resources/conformance/openmix_.out new file mode 100644 index 00000000000..7005d64f306 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/openmix_.out @@ -0,0 +1,7 @@ +3 abc True parser +2 42 Mixed detect:2 XY>Z +parser/mixed 42 7 +mixed/parser abc 5 +parser/parser ab> 5 True True +['parser', 'mixed', 'parser', 'parser'] [5, 5, 2, 7] +Mixed mixed diff --git a/maven/python-transpiler/src/test/resources/conformance/openmix_/base.py b/maven/python-transpiler/src/test/resources/conformance/openmix_/base.py new file mode 100644 index 00000000000..82bcd58b6dd --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/openmix_/base.py @@ -0,0 +1,33 @@ +class Parser: + def __init__(self): + self.raw = "" + self.count = 0 + self.last = None + self.owner = None + + def feed(self, data): + self.raw = self.raw + data + self.scan() + + def scan(self): + i = 0 + n = len(self.raw) + while i < n and self.raw[i] != ">": + i += 1 + self.count = self.count + i + self.last = self.tag() + self.owner = self + keep = [self] + return keep[0] + + def tag(self): + return self.raw[:3] + + def label(self): + return "parser" + + +def peers(a, b): + a.last = b.last + a.count = a.count + b.count + return a.label() + "/" + b.label() diff --git a/maven/python-transpiler/src/test/resources/conformance/openmix_/main.py b/maven/python-transpiler/src/test/resources/conformance/openmix_/main.py new file mode 100644 index 00000000000..04f11f78e67 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/openmix_/main.py @@ -0,0 +1,49 @@ +from base import Parser, peers + + +class Detects: + def detect(self): + return "detect:" + str(self.count) + + +class Mixed(Parser, Detects): + def __init__(self): + Parser.__init__(self) + self.extra = 1 + + def tag(self): + return 42 + + def label(self): + return "mixed" + + @property + def raw(self): + return self.__dict__.get("_raw", "") + + @raw.setter + def raw(self, v): + self.__dict__["_raw"] = v.upper() + + +class Plain(Parser): + pass + + +p = Parser() +p.feed("abc>def") +print(p.count, p.last, p.owner is p, p.label()) +m = Mixed() +m.feed("xy>z") +print(m.count, m.last, type(m.owner).__name__, m.detect(), m.raw) +q = Parser() +q.feed("hello>") +print(peers(q, m), q.last, q.count) +print(peers(m, p), m.last, m.count) +w = Plain() +w.feed("ab>") +print(peers(p, w), p.last, p.count, isinstance(m, Parser), isinstance(m, Detects)) +items = [p, m, w, q] +print([x.label() for x in items], [x.count for x in items]) +q.owner = m +print(type(q.owner).__name__, q.owner.label()) diff --git a/maven/python-transpiler/src/test/resources/conformance/oxmlreg_.out b/maven/python-transpiler/src/test/resources/conformance/oxmlreg_.out new file mode 100644 index 00000000000..b8d6c524711 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/oxmlreg_.out @@ -0,0 +1,7 @@ +CT_NvPr None +CT_Ph ph title 3 True +['CT_Ph', 'CT_Ext'] +ext 2 +None 2 +invalid required ```` child element not present +4 diff --git a/maven/python-transpiler/src/test/resources/conformance/oxmlreg_/lxml/__init__.py b/maven/python-transpiler/src/test/resources/conformance/oxmlreg_/lxml/__init__.py new file mode 100644 index 00000000000..e69de29bb2d diff --git a/maven/python-transpiler/src/test/resources/conformance/oxmlreg_/lxml/etree.py b/maven/python-transpiler/src/test/resources/conformance/oxmlreg_/lxml/etree.py new file mode 100644 index 00000000000..2a80ae89da5 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/oxmlreg_/lxml/etree.py @@ -0,0 +1,114 @@ +"""The subset of lxml.etree the test uses, for the CPython reference run.""" +import xml.etree.ElementTree as _ET + + +class _Element(object): + def _setup(self, tag, nsmap): + self.tag = tag + self.nsmap = dict(nsmap or {}) + self._kids = [] + self._attrib = {} + self._parent = None + + def get(self, key, default=None): + return self._attrib.get(key, default) + + def set(self, key, value): + self._attrib[key] = value + + def find(self, path, namespaces=None): + for k in self._kids: + if k.tag == path: + return k + return None + + def findall(self, path, namespaces=None): + return [k for k in self._kids if k.tag == path] + + def append(self, child): + if child._parent is not None: + child._parent._kids.remove(child) + child._parent = self + self._kids.append(child) + + def remove(self, child): + self._kids.remove(child) + child._parent = None + + def addprevious(self, other): + p = self._parent + if other._parent is not None: + other._parent._kids.remove(other) + p._kids.insert(p._kids.index(self), other) + other._parent = p + + def getparent(self): + return self._parent + + def iterchildren(self): + return iter(list(self._kids)) + + def __iter__(self): + return iter(list(self._kids)) + + def __len__(self): + return len(self._kids) + + +class ElementBase(_Element): + pass + + +class _Plain(_Element): + pass + + +class _Namespace(dict): + pass + + +class ElementNamespaceClassLookup(object): + def __init__(self): + self._ns = {} + + def get_namespace(self, uri): + n = self._ns.get(uri) + if n is None: + n = _Namespace() + self._ns[uri] = n + return n + + def _cls(self, tag): + uri, local = tag[1:].split("}", 1) + n = self._ns.get(uri, {}) + return n.get(local) or n.get(None) or _Plain + + +class XMLParser(object): + def __init__(self, **kw): + self._lookup = None + + def set_element_class_lookup(self, lookup): + self._lookup = lookup + + def makeelement(self, tag, attrib=None, nsmap=None): + cls = self._lookup._cls(tag) if self._lookup is not None else _Plain + el = cls.__new__(cls) + el._setup(tag, nsmap) + return el + + +def fromstring(text, parser): + def build(e): + el = parser.makeelement(e.tag) + for k, v in e.attrib.items(): + el.set(k, v) + for c in e: + el.append(build(c)) + return el + return build(_ET.fromstring(text)) + + +def tostring(el, encoding=None, pretty_print=False): + a = "".join(' %s="%s"' % (k, v) for k, v in sorted(el._attrib.items())) + return "<%s%s>%s" % (el.tag, a, "".join(tostring(k) for k in el._kids), el.tag) diff --git a/maven/python-transpiler/src/test/resources/conformance/oxmlreg_/main.py b/maven/python-transpiler/src/test/resources/conformance/oxmlreg_/main.py new file mode 100644 index 00000000000..9cc236ec97b --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/oxmlreg_/main.py @@ -0,0 +1,24 @@ +from lxml import etree + +from oxpkg import parse_xml +from oxpkg.exc import InvalidXmlError +from oxpkg.ns import nsdecls + +sp = parse_xml('' % nsdecls("a", "p")) +nv = sp.nvPr +print(type(nv).__name__, nv.ph) +ph = nv.get_or_add_ph() +ph.type = "title" +ph.idx = 3 +print(type(ph).__name__, ph.describe(), ph is nv.get_or_add_ph()) +print([type(k).__name__ for k in nv]) +e = nv._add_ext() +print(e.describe(), len(nv.ext_lst)) +nv._remove_ph() +print(nv.ph, len(nv)) +bare = parse_xml('' % nsdecls("p")) +try: + bare.nvPr +except InvalidXmlError as x: + print("invalid", x) +print(etree.tostring(sp).count("ext")) diff --git a/maven/python-transpiler/src/test/resources/conformance/oxmlreg_/oxpkg/__init__.py b/maven/python-transpiler/src/test/resources/conformance/oxmlreg_/oxpkg/__init__.py new file mode 100644 index 00000000000..4dc2486e447 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/oxmlreg_/oxpkg/__init__.py @@ -0,0 +1,27 @@ +from __future__ import annotations + +from lxml import etree + +from oxpkg.ns import NamespacePrefixedTag + +element_class_lookup = etree.ElementNamespaceClassLookup() +oxml_parser = etree.XMLParser(remove_blank_text=True, resolve_entities=False) +oxml_parser.set_element_class_lookup(element_class_lookup) + + +def parse_xml(xml): + return etree.fromstring(xml, oxml_parser) + + +def register_element_cls(nsptagname, cls): + nsptag = NamespacePrefixedTag(nsptagname) + namespace = element_class_lookup.get_namespace(nsptag.nsuri) + namespace[nsptag.local_part] = cls + + +from oxpkg.shapes import CT_Ph, CT_NvPr, CT_Sp, CT_Ext # noqa: E402 + +register_element_cls("p:ph", CT_Ph) +register_element_cls("p:nvPr", CT_NvPr) +register_element_cls("p:sp", CT_Sp) +register_element_cls("a:ext", CT_Ext) diff --git a/maven/python-transpiler/src/test/resources/conformance/oxmlreg_/oxpkg/exc.py b/maven/python-transpiler/src/test/resources/conformance/oxmlreg_/oxpkg/exc.py new file mode 100644 index 00000000000..7e48f4cb76e --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/oxmlreg_/oxpkg/exc.py @@ -0,0 +1,2 @@ +class InvalidXmlError(Exception): + pass diff --git a/maven/python-transpiler/src/test/resources/conformance/oxmlreg_/oxpkg/ns.py b/maven/python-transpiler/src/test/resources/conformance/oxmlreg_/oxpkg/ns.py new file mode 100644 index 00000000000..d900c33bfe4 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/oxmlreg_/oxpkg/ns.py @@ -0,0 +1,129 @@ +"""Namespace related objects.""" + +from __future__ import annotations + + +# -- Maps namespace prefix to namespace name for all known PowerPoint XML namespaces -- +_nsmap = { + "a": "http://schemas.openxmlformats.org/drawingml/2006/main", + "c": "http://schemas.openxmlformats.org/drawingml/2006/chart", + "cp": "http://schemas.openxmlformats.org/package/2006/metadata/core-properties", + "ct": "http://schemas.openxmlformats.org/package/2006/content-types", + "dc": "http://purl.org/dc/elements/1.1/", + "dcmitype": "http://purl.org/dc/dcmitype/", + "dcterms": "http://purl.org/dc/terms/", + "ep": "http://schemas.openxmlformats.org/officeDocument/2006/extended-properties", + "i": "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image", + "m": "http://schemas.openxmlformats.org/officeDocument/2006/math", + "mo": "http://schemas.microsoft.com/office/mac/office/2008/main", + "mv": "urn:schemas-microsoft-com:mac:vml", + "o": "urn:schemas-microsoft-com:office:office", + "p": "http://schemas.openxmlformats.org/presentationml/2006/main", + "pd": "http://schemas.openxmlformats.org/drawingml/2006/presentationDrawing", + "pic": "http://schemas.openxmlformats.org/drawingml/2006/picture", + "pr": "http://schemas.openxmlformats.org/package/2006/relationships", + "r": "http://schemas.openxmlformats.org/officeDocument/2006/relationships", + "sl": "http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideLayout", + "v": "urn:schemas-microsoft-com:vml", + "ve": "http://schemas.openxmlformats.org/markup-compatibility/2006", + "w": "http://schemas.openxmlformats.org/wordprocessingml/2006/main", + "w10": "urn:schemas-microsoft-com:office:word", + "wne": "http://schemas.microsoft.com/office/word/2006/wordml", + "wp": "http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing", + "xsi": "http://www.w3.org/2001/XMLSchema-instance", +} + +pfxmap = {value: key for key, value in _nsmap.items()} + + +class NamespacePrefixedTag(str): + """Value object that knows the semantics of an XML tag having a namespace prefix.""" + + def __new__(cls, nstag: str): + return super(NamespacePrefixedTag, cls).__new__(cls, nstag) + + def __init__(self, nstag: str): + self._pfx, self._local_part = nstag.split(":") + self._ns_uri = _nsmap[self._pfx] + + @classmethod + def from_clark_name(cls, clark_name: str) -> NamespacePrefixedTag: + nsuri, local_name = clark_name[1:].split("}") + nstag = "%s:%s" % (pfxmap[nsuri], local_name) + return cls(nstag) + + @property + def clark_name(self): + return "{%s}%s" % (self._ns_uri, self._local_part) + + @property + def local_part(self): + """ + Return the local part of the tag as a string. E.g. 'foobar' is + returned for tag 'f:foobar'. + """ + return self._local_part + + @property + def nsmap(self): + """ + Return a dict having a single member, mapping the namespace prefix of + this tag to it's namespace name (e.g. {'f': 'http://foo/bar'}). This + is handy for passing to xpath calls and other uses. + """ + return {self._pfx: self._ns_uri} + + @property + def nspfx(self): + """ + Return the string namespace prefix for the tag, e.g. 'f' is returned + for tag 'f:foobar'. + """ + return self._pfx + + @property + def nsuri(self): + """ + Return the namespace URI for the tag, e.g. 'http://foo/bar' would be + returned for tag 'f:foobar' if the 'f' prefix maps to + 'http://foo/bar' in _nsmap. + """ + return self._ns_uri + + +def namespaces(*prefixes: str): + """Return a dict containing the subset namespace prefix mappings specified by *prefixes*. + + Any number of namespace prefixes can be supplied, e.g. namespaces('a', 'r', 'p'). + """ + return {pfx: _nsmap[pfx] for pfx in prefixes} + + +nsmap = namespaces # alias for more compact use with Element() + + +def nsdecls(*prefixes: str): + return " ".join(['xmlns:%s="%s"' % (pfx, _nsmap[pfx]) for pfx in prefixes]) + + +def nsuri(nspfx: str): + """Return the namespace URI corresponding to `nspfx`. + + Example: + + >>> nsuri("p") + "http://schemas.openxmlformats.org/presentationml/2006/main" + """ + return _nsmap[nspfx] + + +def qn(namespace_prefixed_tag: str) -> str: + """Return a Clark-notation qualified tag name corresponding to `namespace_prefixed_tag`. + + `namespace_prefixed_tag` is a string like 'p:body'. 'qn' stands for `qualified name`. + + As an example, `qn("p:cSld")` returns: + `"{http://schemas.openxmlformats.org/drawingml/2006/main}cSld"`. + """ + nsptag = NamespacePrefixedTag(namespace_prefixed_tag) + return nsptag.clark_name diff --git a/maven/python-transpiler/src/test/resources/conformance/oxmlreg_/oxpkg/shapes.py b/maven/python-transpiler/src/test/resources/conformance/oxmlreg_/oxpkg/shapes.py new file mode 100644 index 00000000000..8fd190f9a4e --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/oxmlreg_/oxpkg/shapes.py @@ -0,0 +1,55 @@ +from __future__ import annotations + +from oxpkg.xmlchemy import ( + BaseOxmlElement, + OneAndOnlyOne, + OptionalAttribute, + ZeroOrMore, + ZeroOrOne, +) + + +class ST_Int(object): + @classmethod + def from_xml(cls, s): + return int(s) + + @classmethod + def to_xml(cls, v): + return str(v) + + @classmethod + def validate(cls, v): + pass + + +class ST_Str(ST_Int): + @classmethod + def from_xml(cls, s): + return s + + @classmethod + def to_xml(cls, v): + return v + + +class CT_Ph(BaseOxmlElement): + type = OptionalAttribute("type", ST_Str, default="obj") + idx = OptionalAttribute("idx", ST_Int, default=0) + + def describe(self): + return "ph %s %d" % (self.type, self.idx) + + +class CT_Ext(BaseOxmlElement): + def describe(self): + return "ext" + + +class CT_NvPr(BaseOxmlElement): + ph = ZeroOrOne("p:ph", successors=("a:ext", "p:extLst")) + ext = ZeroOrMore("a:ext", successors=("p:extLst",)) + + +class CT_Sp(BaseOxmlElement): + nvPr = OneAndOnlyOne("p:nvPr") diff --git a/maven/python-transpiler/src/test/resources/conformance/oxmlreg_/oxpkg/util.py b/maven/python-transpiler/src/test/resources/conformance/oxmlreg_/oxpkg/util.py new file mode 100644 index 00000000000..df77fdf0a3d --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/oxmlreg_/oxpkg/util.py @@ -0,0 +1,116 @@ +from __future__ import annotations + +import functools + +# Test copy: no typing import (strict refuses typing's metaclasses here). +def cast(t, v): + return v + + +class lazyproperty: + """Decorator like @property, but evaluated only on first access. + + Like @property, this can only be used to decorate methods having only a `self` parameter, and + is accessed like an attribute on an instance, i.e. trailing parentheses are not used. Unlike + @property, the decorated method is only evaluated on first access; the resulting value is + cached and that same value returned on second and later access without re-evaluation of the + method. + + Like @property, this class produces a *data descriptor* object, which is stored in the __dict__ + of the *class* under the name of the decorated method ('fget' nominally). The cached value is + stored in the __dict__ of the *instance* under that same name. + + Because it is a data descriptor (as opposed to a *non-data descriptor*), its `__get__()` method + is executed on each access of the decorated attribute; the __dict__ item of the same name is + "shadowed" by the descriptor. + + While this may represent a performance improvement over a property, its greater benefit may be + its other characteristics. One common use is to construct collaborator objects, removing that + "real work" from the constructor, while still only executing once. It also de-couples client + code from any sequencing considerations; if it's accessed from more than one location, it's + assured it will be ready whenever needed. + + Loosely based on: https://stackoverflow.com/a/6849299/1902513. + + A lazyproperty is read-only. There is no counterpart to the optional "setter" (or deleter) + behavior of an @property. This is critically important to maintaining its immutability and + idempotence guarantees. Attempting to assign to a lazyproperty raises AttributeError + unconditionally. + + The parameter names in the methods below correspond to this usage example:: + + class Obj(object) + + @lazyproperty + def fget(self): + return 'some result' + + obj = Obj() + + Not suitable for wrapping a function (as opposed to a method) because it is not callable. + """ + + def __init__(self, fget: Callable[..., _T]) -> None: + """*fget* is the decorated method (a "getter" function). + + A lazyproperty is read-only, so there is only an *fget* function (a regular + @property can also have an fset and fdel function). This name was chosen for + consistency with Python's `property` class which uses this name for the + corresponding parameter. + """ + # --- maintain a reference to the wrapped getter method + self._fget = fget + # --- and store the name of that decorated method + self._name = fget.__name__ + # --- adopt fget's __name__, __doc__, and other attributes + functools.update_wrapper(self, fget) # pyright: ignore + + def __get__(self, obj: Any, type: Any = None) -> _T: + """Called on each access of 'fget' attribute on class or instance. + + *self* is this instance of a lazyproperty descriptor "wrapping" the property + method it decorates (`fget`, nominally). + + *obj* is the "host" object instance when the attribute is accessed from an + object instance, e.g. `obj = Obj(); obj.fget`. *obj* is None when accessed on + the class, e.g. `Obj.fget`. + + *type* is the class hosting the decorated getter method (`fget`) on both class + and instance attribute access. + """ + # --- when accessed on class, e.g. Obj.fget, just return this descriptor + # --- instance (patched above to look like fget). + if obj is None: + return self # type: ignore + + # --- when accessed on instance, start by checking instance __dict__ for + # --- item with key matching the wrapped function's name + value = obj.__dict__.get(self._name) + if value is None: + # --- on first access, the __dict__ item will be absent. Evaluate fget() + # --- and store that value in the (otherwise unused) host-object + # --- __dict__ value of same name ('fget' nominally) + value = self._fget(obj) + obj.__dict__[self._name] = value + return value + + def __set__(self, obj: Any, value: Any) -> None: + """Raises unconditionally, to preserve read-only behavior. + + This decorator is intended to implement immutable (and idempotent) object + attributes. For that reason, assignment to this property must be explicitly + prevented. + + If this __set__ method was not present, this descriptor would become a + *non-data descriptor*. That would be nice because the cached value would be + accessed directly once set (__dict__ attrs have precedence over non-data + descriptors on instance attribute lookup). The problem is, there would be + nothing to stop assignment to the cached value, which would overwrite the result + of `fget()` and break both the immutability and idempotence guarantees of this + decorator. + + The performance with this __set__() method in place was roughly 0.4 usec per + access when measured on a 2.8GHz development machine; so quite snappy and + probably not a rich target for optimization efforts. + """ + raise AttributeError("can't set attribute") diff --git a/maven/python-transpiler/src/test/resources/conformance/oxmlreg_/oxpkg/xmlchemy.py b/maven/python-transpiler/src/test/resources/conformance/oxmlreg_/oxpkg/xmlchemy.py new file mode 100644 index 00000000000..4d41fdb2bce --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/oxmlreg_/oxpkg/xmlchemy.py @@ -0,0 +1,718 @@ +"""Base and meta classes enabling declarative definition of custom element classes.""" + +from __future__ import annotations + +import re + +from lxml import etree +from lxml.etree import ElementBase, _Element # pyright: ignore[reportPrivateUsage] + +from oxpkg.exc import InvalidXmlError +from oxpkg import oxml_parser +from oxpkg.ns import NamespacePrefixedTag, _nsmap, qn # pyright: ignore[reportPrivateUsage] +from oxpkg.util import cast, lazyproperty + + +# Test copy of python-pptx's xmlchemy: typing.Protocol dropped (strict refuses +# typing's own metaclasses in a conformance program). +class AttributeType: + """Interface for an object that can act as an attribute type. + + An attribute-type specifies how values are transformed to and from the XML "string" value of the + attribute. + """ + + @classmethod + def from_xml(cls, xml_value: str) -> Any: + """Transform an attribute value to a Python value.""" + ... + + @classmethod + def to_xml(cls, value: Any) -> str: + """Transform a Python value to a str value suitable to this XML attribute.""" + ... + + +def OxmlElement(nsptag_str: str, nsmap: dict[str, str] | None = None) -> BaseOxmlElement: + """Return a "loose" lxml element having the tag specified by `nsptag_str`. + + `nsptag_str` must contain the standard namespace prefix, e.g. 'a:tbl'. The resulting element is + an instance of the custom element class for this tag name if one is defined. + """ + nsptag = NamespacePrefixedTag(nsptag_str) + nsmap = nsmap if nsmap is not None else nsptag.nsmap + return oxml_parser.makeelement(nsptag.clark_name, nsmap=nsmap) + + +def serialize_for_reading(element: ElementBase): + """ + Serialize *element* to human-readable XML suitable for tests. No XML + declaration. + """ + xml = etree.tostring(element, encoding="unicode", pretty_print=True) + return XmlString(xml) + + +class XmlString(str): + """Provides string comparison override suitable for serialized XML; useful for tests.""" + + # ' text' + # | | || | + # +----------+------------------------------------------++-----------+ + # front attrs | text + # close + + _xml_elm_line_patt = re.compile(r"( *)([^<]*)?") + + def __eq__(self, other: object) -> bool: + if not isinstance(other, str): + return False + lines = self.splitlines() + lines_other = other.splitlines() + if len(lines) != len(lines_other): + return False + for line, line_other in zip(lines, lines_other): + if not self._eq_elm_strs(line, line_other): + return False + return True + + def __ne__(self, other: object) -> bool: + return not self.__eq__(other) + + def _attr_seq(self, attrs: str) -> list[str]: + """Return a sequence of attribute strings parsed from *attrs*. + + Each attribute string is stripped of whitespace on both ends. + """ + attrs = attrs.strip() + attr_lst = attrs.split() + return sorted(attr_lst) + + def _eq_elm_strs(self, line: str, line_2: str) -> bool: + """True if the element in `line_2` is XML-equivalent to the element in `line`. + + In particular, the order of attributes in XML is not significant. + """ + front, attrs, close, text = self._parse_line(line) + front_2, attrs_2, close_2, text_2 = self._parse_line(line_2) + if front != front_2: + return False + if self._attr_seq(attrs) != self._attr_seq(attrs_2): + return False + if close != close_2: + return False + if text != text_2: + return False + return True + + def _parse_line(self, line: str): + """Return front, attrs, close, text 4-tuple result of parsing XML element string `line`.""" + match = self._xml_elm_line_patt.match(line) + if match is None: + raise ValueError("`line` does not match pattern for an XML element") + front, attrs, close, text = [match.group(n) for n in range(1, 5)] + return front, attrs, close, text + + +class MetaOxmlElement(type): + """Metaclass for BaseOxmlElement.""" + + def __init__(cls, clsname: str, bases: tuple[type, ...], clsdict: dict[str, Any]): + dispatchable = ( + OneAndOnlyOne, + OneOrMore, + OptionalAttribute, + RequiredAttribute, + ZeroOrMore, + ZeroOrOne, + ZeroOrOneChoice, + ) + for key, value in clsdict.items(): + if isinstance(value, dispatchable): + value.populate_class_members(cls, key) + + +class BaseAttribute: + """Base class for OptionalAttribute and RequiredAttribute, providing common methods.""" + + def __init__(self, attr_name: str, simple_type: type[AttributeType]): + self._attr_name = attr_name + self._simple_type = simple_type + + def populate_class_members(self, element_cls: Type[BaseOxmlElement], prop_name: str): + """ + Add the appropriate methods to *element_cls*. + """ + self._element_cls = element_cls + self._prop_name = prop_name + + self._add_attr_property() + + def _add_attr_property(self): + """Add a read/write `{prop_name}` property to the element class. + + The property returns the interpreted value of this attribute on access and changes the + attribute value to its ST_* counterpart on assignment. + """ + property_ = property(self._getter, self._setter, None) + # assign unconditionally to overwrite element name definition + setattr(self._element_cls, self._prop_name, property_) + + @property + def _clark_name(self): + if ":" in self._attr_name: + return qn(self._attr_name) + return self._attr_name + + @property + def _getter(self) -> Callable[[BaseOxmlElement], Any]: + """Callable suitable for the "get" side of the attribute property descriptor.""" + raise NotImplementedError("must be implemented by each subclass") + + @property + def _setter(self) -> Callable[[BaseOxmlElement, Any], None]: + """Callable suitable for the "set" side of the attribute property descriptor.""" + raise NotImplementedError("must be implemented by each subclass") + + +class OptionalAttribute(BaseAttribute): + """Defines an optional attribute on a custom element class. + + An optional attribute returns a default value when not present for reading. When assigned + |None|, the attribute is removed. + """ + + def __init__(self, attr_name: str, simple_type: type[AttributeType], default: Any = None): + super(OptionalAttribute, self).__init__(attr_name, simple_type) + self._default = default + + @property + def _docstring(self): + """ + Return the string to use as the ``__doc__`` attribute of the property + for this attribute. + """ + return ( + "%s type-converted value of ``%s`` attribute, or |None| (or spec" + "ified default value) if not present. Assigning the default valu" + "e causes the attribute to be removed from the element." + % (self._simple_type.__name__, self._attr_name) + ) + + @property + def _getter(self) -> Callable[[BaseOxmlElement], Any]: + """Callable suitable for the "get" side of the attribute property descriptor.""" + + def get_attr_value(obj: BaseOxmlElement) -> Any: + attr_str_value = obj.get(self._clark_name) + if attr_str_value is None: + return self._default + return self._simple_type.from_xml(attr_str_value) + + get_attr_value.__doc__ = self._docstring + return get_attr_value + + @property + def _setter(self) -> Callable[[BaseOxmlElement, Any], None]: + """Callable suitable for the "set" side of the attribute property descriptor.""" + + def set_attr_value(obj: BaseOxmlElement, value: Any) -> None: + # -- when an XML attribute has a default value, setting it to that default removes the + # -- attribute from the element (when it is present) + if value == self._default: + if self._clark_name in obj.attrib: + del obj.attrib[self._clark_name] + return + str_value = self._simple_type.to_xml(value) + obj.set(self._clark_name, str_value) + + return set_attr_value + + +class RequiredAttribute(BaseAttribute): + """Defines a required attribute on a custom element class. + + A required attribute is assumed to be present for reading, so does not have a default value; + its actual value is always used. If missing on read, an |InvalidXmlError| is raised. It also + does not remove the attribute if |None| is assigned. Assigning |None| raises |TypeError| or + |ValueError|, depending on the simple type of the attribute. + """ + + @property + def _getter(self) -> Callable[[BaseOxmlElement], Any]: + """Callable suitable for the "get" side of the attribute property descriptor.""" + + def get_attr_value(obj: BaseOxmlElement) -> Any: + attr_str_value = obj.get(self._clark_name) + if attr_str_value is None: + raise InvalidXmlError( + "required '%s' attribute not present on element %s" % (self._attr_name, obj.tag) + ) + return self._simple_type.from_xml(attr_str_value) + + get_attr_value.__doc__ = self._docstring + return get_attr_value + + @property + def _docstring(self): + """ + Return the string to use as the ``__doc__`` attribute of the property + for this attribute. + """ + return "%s type-converted value of ``%s`` attribute." % ( + self._simple_type.__name__, + self._attr_name, + ) + + @property + def _setter(self) -> Callable[[BaseOxmlElement, Any], None]: + """Callable suitable for the "set" side of the attribute property descriptor.""" + + def set_attr_value(obj: BaseOxmlElement, value: Any) -> None: + str_value = self._simple_type.to_xml(value) + obj.set(self._clark_name, str_value) + + return set_attr_value + + +class _BaseChildElement: + """Base class for the child element classes corresponding to varying cardinalities. + + Subclasses include ZeroOrOne and ZeroOrMore. + """ + + def __init__(self, nsptagname: str, successors: Sequence[str] = ()): + super(_BaseChildElement, self).__init__() + self._nsptagname = nsptagname + self._successors = successors + + def populate_class_members(self, element_cls: Type[BaseOxmlElement], prop_name: str): + """Baseline behavior for adding the appropriate methods to `element_cls`.""" + self._element_cls = element_cls + self._prop_name = prop_name + + def _add_adder(self): + """Add an ``_add_x()`` method to the element class for this child element.""" + + def _add_child(obj: BaseOxmlElement, **attrs: Any): + new_method = getattr(obj, self._new_method_name) + child = new_method() + for key, value in attrs.items(): + setattr(child, key, value) + insert_method = getattr(obj, self._insert_method_name) + insert_method(child) + return child + + _add_child.__doc__ = ( + "Add a new ``<%s>`` child element unconditionally, inserted in t" + "he correct sequence." % self._nsptagname + ) + self._add_to_class(self._add_method_name, _add_child) + + def _add_creator(self): + """Add a `_new_{prop_name}()` method to the element class. + + This method creates a new, empty element of the correct type, having no attributes. + """ + creator = self._creator + creator.__doc__ = ( + 'Return a "loose", newly created ``<%s>`` element having no attri' + "butes, text, or children." % self._nsptagname + ) + self._add_to_class(self._new_method_name, creator) + + def _add_getter(self): + """Add a read-only `{prop_name}` property to the parent element class. + + The property locates and returns this child element or `None` if not present. + """ + property_ = property(self._getter, None, None) + # assign unconditionally to overwrite element name definition + setattr(self._element_cls, self._prop_name, property_) + + def _add_inserter(self): + """Add an ``_insert_x()`` method to the element class for this child element.""" + + def _insert_child(obj: BaseOxmlElement, child: BaseOxmlElement): + obj.insert_element_before(child, *self._successors) + return child + + _insert_child.__doc__ = ( + "Return the passed ``<%s>`` element after inserting it as a chil" + "d in the correct sequence." % self._nsptagname + ) + self._add_to_class(self._insert_method_name, _insert_child) + + def _add_list_getter(self): + """ + Add a read-only ``{prop_name}_lst`` property to the element class to + retrieve a list of child elements matching this type. + """ + prop_name = f"{self._prop_name}_lst" + property_ = property(self._list_getter, None, None) + setattr(self._element_cls, prop_name, property_) + + @lazyproperty + def _add_method_name(self): + return "_add_%s" % self._prop_name + + def _add_to_class(self, name: str, method: Callable[..., Any]): + """Add `method` to the target class as `name`, unless `name` is already defined there.""" + if hasattr(self._element_cls, name): + return + setattr(self._element_cls, name, method) + + @property + def _creator(self) -> Callable[[BaseOxmlElement], BaseOxmlElement]: + """Callable that creates a new, empty element of the child type, having no attributes.""" + + def new_child_element(obj: BaseOxmlElement): + return OxmlElement(self._nsptagname) + + return new_child_element + + @property + def _getter(self) -> Callable[[BaseOxmlElement], BaseOxmlElement | None]: + """Callable suitable for the "get" side of the property descriptor. + + This default getter returns the child element with matching tag name or |None| if not + present. + """ + + def get_child_element(obj: BaseOxmlElement) -> BaseOxmlElement | None: + return obj.find(qn(self._nsptagname)) + + get_child_element.__doc__ = ( + "``<%s>`` child element or |None| if not present." % self._nsptagname + ) + return get_child_element + + @lazyproperty + def _insert_method_name(self): + return "_insert_%s" % self._prop_name + + @property + def _list_getter(self) -> Callable[[BaseOxmlElement], list[BaseOxmlElement]]: + """Callable suitable for the "get" side of a list property descriptor.""" + + def get_child_element_list(obj: BaseOxmlElement) -> list[BaseOxmlElement]: + return cast("list[BaseOxmlElement]", obj.findall(qn(self._nsptagname))) + + get_child_element_list.__doc__ = ( + "A list containing each of the ``<%s>`` child elements, in the o" + "rder they appear." % self._nsptagname + ) + return get_child_element_list + + @lazyproperty + def _remove_method_name(self): + return "_remove_%s" % self._prop_name + + @lazyproperty + def _new_method_name(self): + return "_new_%s" % self._prop_name + + +class Choice(_BaseChildElement): + """Defines a child element belonging to a group, only one of which may appear as a child.""" + + @property + def nsptagname(self): + return self._nsptagname + + def populate_class_members( # pyright: ignore[reportIncompatibleMethodOverride] + self, element_cls: Type[BaseOxmlElement], group_prop_name: str, successors: Sequence[str] + ): + """Add the appropriate methods to `element_cls`.""" + self._element_cls = element_cls + self._group_prop_name = group_prop_name + self._successors = successors + + self._add_getter() + self._add_creator() + self._add_inserter() + self._add_adder() + self._add_get_or_change_to_method() + + def _add_get_or_change_to_method(self) -> None: + """Add a `get_or_change_to_x()` method to the element class for this child element.""" + + def get_or_change_to_child(obj: BaseOxmlElement): + child = getattr(obj, self._prop_name) + if child is not None: + return child + remove_group_method = getattr(obj, self._remove_group_method_name) + remove_group_method() + add_method = getattr(obj, self._add_method_name) + child = add_method() + return child + + get_or_change_to_child.__doc__ = ( + "Return the ``<%s>`` child, replacing any other group element if" " found." + ) % self._nsptagname + self._add_to_class(self._get_or_change_to_method_name, get_or_change_to_child) + + @property + def _prop_name(self): + """ + Calculate property name from tag name, e.g. a:schemeClr -> schemeClr. + """ + if ":" in self._nsptagname: + start = self._nsptagname.index(":") + 1 + else: + start = 0 + return self._nsptagname[start:] + + @lazyproperty + def _get_or_change_to_method_name(self): + return "get_or_change_to_%s" % self._prop_name + + @lazyproperty + def _remove_group_method_name(self): + return "_remove_%s" % self._group_prop_name + + +class OneAndOnlyOne(_BaseChildElement): + """Defines a required child element for MetaOxmlElement.""" + + def __init__(self, nsptagname: str): + super(OneAndOnlyOne, self).__init__(nsptagname, ()) + + def populate_class_members(self, element_cls: Type[BaseOxmlElement], prop_name: str): + """ + Add the appropriate methods to *element_cls*. + """ + super(OneAndOnlyOne, self).populate_class_members(element_cls, prop_name) + self._add_getter() + + @property + def _getter(self) -> Callable[[BaseOxmlElement], BaseOxmlElement]: + """Callable suitable for the "get" side of the property descriptor.""" + + def get_child_element(obj: BaseOxmlElement) -> BaseOxmlElement: + child = obj.find(qn(self._nsptagname)) + if child is None: + raise InvalidXmlError( + "required ``<%s>`` child element not present" % self._nsptagname + ) + return child + + get_child_element.__doc__ = "Required ``<%s>`` child element." % self._nsptagname + return get_child_element + + +class OneOrMore(_BaseChildElement): + """Defines a repeating child element for MetaOxmlElement that must appear at least once.""" + + def populate_class_members(self, element_cls: Type[BaseOxmlElement], prop_name: str): + """Add the appropriate methods to *element_cls*.""" + super(OneOrMore, self).populate_class_members(element_cls, prop_name) + self._add_list_getter() + self._add_creator() + self._add_inserter() + self._add_adder() + self._add_public_adder() + delattr(element_cls, prop_name) + + def _add_public_adder(self) -> None: + """Add a public `.add_x()` method to the parent element class.""" + + def add_child(obj: BaseOxmlElement) -> BaseOxmlElement: + private_add_method = getattr(obj, self._add_method_name) + child = private_add_method() + return child + + add_child.__doc__ = ( + "Add a new ``<%s>`` child element unconditionally, inserted in t" + "he correct sequence." % self._nsptagname + ) + self._add_to_class(self._public_add_method_name, add_child) + + @lazyproperty + def _public_add_method_name(self): + """ + add_childElement() is public API for a repeating element, allowing + new elements to be added to the sequence. May be overridden to + provide a friendlier API to clients having domain appropriate + parameter names for required attributes. + """ + return "add_%s" % self._prop_name + + +class ZeroOrMore(_BaseChildElement): + """ + Defines an optional repeating child element for MetaOxmlElement. + """ + + def populate_class_members(self, element_cls: Type[BaseOxmlElement], prop_name: str): + """ + Add the appropriate methods to *element_cls*. + """ + super(ZeroOrMore, self).populate_class_members(element_cls, prop_name) + self._add_list_getter() + self._add_creator() + self._add_inserter() + self._add_adder() + delattr(element_cls, prop_name) + + +class ZeroOrOne(_BaseChildElement): + """Defines an optional child element for MetaOxmlElement.""" + + def populate_class_members(self, element_cls: Type[BaseOxmlElement], prop_name: str): + """Add the appropriate methods to `element_cls`.""" + super(ZeroOrOne, self).populate_class_members(element_cls, prop_name) + self._add_getter() + self._add_creator() + self._add_inserter() + self._add_adder() + self._add_get_or_adder() + self._add_remover() + + def _add_get_or_adder(self): + """Add a `.get_or_add_x()` method to the element class for this child element.""" + + def get_or_add_child(obj: BaseOxmlElement) -> BaseOxmlElement: + child = getattr(obj, self._prop_name) + if child is None: + add_method = getattr(obj, self._add_method_name) + child = add_method() + return child + + get_or_add_child.__doc__ = ( + "Return the ``<%s>`` child element, newly added if not present." + ) % self._nsptagname + self._add_to_class(self._get_or_add_method_name, get_or_add_child) + + def _add_remover(self): + """Add a `._remove_x()` method to the element class for this child element.""" + + def _remove_child(obj: BaseOxmlElement) -> None: + obj.remove_all(self._nsptagname) + + _remove_child.__doc__ = f"Remove all `{self._nsptagname}` child elements." + self._add_to_class(self._remove_method_name, _remove_child) + + @lazyproperty + def _get_or_add_method_name(self): + return "get_or_add_%s" % self._prop_name + + +class ZeroOrOneChoice(_BaseChildElement): + """An `EG_*` element group where at most one of its members may appear as a child.""" + + def __init__(self, choices: Iterable[Choice], successors: Iterable[str] = ()): + self._choices = tuple(choices) + self._successors = tuple(successors) + + def populate_class_members(self, element_cls: Type[BaseOxmlElement], prop_name: str): + """Add the appropriate methods to `element_cls`.""" + super(ZeroOrOneChoice, self).populate_class_members(element_cls, prop_name) + self._add_choice_getter() + for choice in self._choices: + choice.populate_class_members(element_cls, self._prop_name, self._successors) + self._add_group_remover() + + def _add_choice_getter(self): + """Add a read-only `.{prop_name}` property to the element class. + + The property returns the present member of this group, or |None| if none are present. + """ + property_ = property(self._choice_getter, None, None) + # assign unconditionally to overwrite element name definition + setattr(self._element_cls, self._prop_name, property_) + + def _add_group_remover(self): + """Add a `._remove_eg_x()` method to the element class for this choice group.""" + + def _remove_choice_group(obj: BaseOxmlElement) -> None: + for tagname in self._member_nsptagnames: + obj.remove_all(tagname) + + _remove_choice_group.__doc__ = "Remove the current choice group child element if present." + self._add_to_class(self._remove_choice_group_method_name, _remove_choice_group) + + @property + def _choice_getter(self): + """ + Return a function object suitable for the "get" side of the property + descriptor. + """ + + def get_group_member_element(obj: BaseOxmlElement) -> BaseOxmlElement | None: + return cast( + "BaseOxmlElement | None", obj.first_child_found_in(*self._member_nsptagnames) + ) + + get_group_member_element.__doc__ = ( + "Return the child element belonging to this element group, or " + "|None| if no member child is present." + ) + return get_group_member_element + + @lazyproperty + def _member_nsptagnames(self) -> list[str]: + """Sequence of namespace-prefixed tagnames, one for each member element of choice group.""" + return [choice.nsptagname for choice in self._choices] + + @lazyproperty + def _remove_choice_group_method_name(self): + """Function-name for choice remover.""" + return f"_remove_{self._prop_name}" + + +# -- lxml typing isn't quite right here, just ignore this error on _Element -- +class BaseOxmlElement(etree.ElementBase, metaclass=MetaOxmlElement): + """Effective base class for all custom element classes. + + Adds standardized behavior to all classes in one place. + """ + + def __repr__(self): + return "<%s '<%s>' at 0x%0x>" % ( + self.__class__.__name__, + self._nsptag, + id(self), + ) + + def first_child_found_in(self, *tagnames: str) -> _Element | None: + """First child with tag in `tagnames`, or None if not found.""" + for tagname in tagnames: + child = self.find(qn(tagname)) + if child is not None: + return child + return None + + def insert_element_before(self, elm: ElementBase, *tagnames: str): + successor = self.first_child_found_in(*tagnames) + if successor is not None: + successor.addprevious(elm) + else: + self.append(elm) + return elm + + def remove_all(self, *tagnames: str) -> None: + """Remove child elements with tagname (e.g. "a:p") in `tagnames`.""" + for tagname in tagnames: + matching = self.findall(qn(tagname)) + for child in matching: + self.remove(child) + + @property + def xml(self) -> str: + """XML string for this element, suitable for testing purposes. + + Pretty printed for readability and without an XML declaration at the top. + """ + return serialize_for_reading(self) + + def xpath(self, xpath_str: str) -> Any: # pyright: ignore[reportIncompatibleMethodOverride] + """Override of `lxml` _Element.xpath() method. + + Provides standard Open XML namespace mapping (`nsmap`) in centralized location. + """ + return super().xpath(xpath_str, namespaces=_nsmap) + + @property + def _nsptag(self) -> str: + return NamespacePrefixedTag.from_clark_name(self.tag) diff --git a/maven/python-transpiler/src/test/resources/conformance/patch_init_class.out b/maven/python-transpiler/src/test/resources/conformance/patch_init_class.out new file mode 100644 index 00000000000..828b2df5c40 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/patch_init_class.out @@ -0,0 +1,2 @@ +(4, 8) +('new', 4, 8) diff --git a/maven/python-transpiler/src/test/resources/conformance/patch_init_class.py b/maven/python-transpiler/src/test/resources/conformance/patch_init_class.py new file mode 100644 index 00000000000..7dbdd574b1b --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/patch_init_class.py @@ -0,0 +1,12 @@ +class P: + def __init__(self, a, c=3): + self.v = (a, c) + + +def make(): + return P(4, 8).v + + +print(make()) +P.__init__ = lambda self, a, c=0: setattr(self, "v", ("new", a, c)) +print(make()) diff --git a/maven/python-transpiler/src/test/resources/conformance/pickle_.strict b/maven/python-transpiler/src/test/resources/conformance/pickle_.strict new file mode 100644 index 00000000000..1c8be65c58b --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/pickle_.strict @@ -0,0 +1,3 @@ +pickle:1276 setattr with a computed name is reflection; write override = pickle.Unpickler._step in cn1-python.properties and its compliant body in cn1-python-overrides/pickle.Unpickler._step.py +pickle:1338 getattr with a computed name is reflection; write override = pickle.Unpickler.find_class in cn1-python.properties and its compliant body in cn1-python-overrides/pickle.Unpickler.find_class.py +pickle:225 getattr with a computed name is reflection; write override = pickle._getattribute in cn1-python.properties and its compliant body in cn1-python-overrides/pickle._getattribute.py diff --git a/maven/python-transpiler/src/test/resources/conformance/probe_rebound.out b/maven/python-transpiler/src/test/resources/conformance/probe_rebound.out new file mode 100644 index 00000000000..ded6cf7e947 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/probe_rebound.out @@ -0,0 +1,2 @@ +(15, [(0, 1), (1, 1), (2, 1), (3, 1), (4, 1)]) +('real', 'KeyError', 0) diff --git a/maven/python-transpiler/src/test/resources/conformance/probe_rebound.py b/maven/python-transpiler/src/test/resources/conformance/probe_rebound.py new file mode 100644 index 00000000000..2be198720f7 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/probe_rebound.py @@ -0,0 +1,34 @@ +def counts(n): + d = {} + hits = 0 + for i in range(n): + key = i % 5 + try: + hits += d[key] + except KeyError: + d[key] = 1 + return hits, sorted(d.items()) + + +print(counts(20)) + + +class KeyError(Exception): + pass + + +def rebound(): + d = {} + hits = 0 + try: + for i in range(3): + try: + hits += d[i] + except KeyError: + hits += 100 + except LookupError as e: + return "real", type(e).__name__, hits + return "caught", hits + + +print(rebound()) diff --git a/maven/python-transpiler/src/test/resources/conformance/protocol_runtime_.out b/maven/python-transpiler/src/test/resources/conformance/protocol_runtime_.out new file mode 100644 index 00000000000..772e8a3bc10 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/protocol_runtime_.out @@ -0,0 +1,8 @@ +True False False +True False +True False True +True False True +True False +TypeError Instance and class checks can only be used with @runtime_checkable protocols +TypeError Protocols with non-method members don't support issubclass(). Non-method members: 'name'. +closer other closer diff --git a/maven/python-transpiler/src/test/resources/conformance/protocol_runtime_.py b/maven/python-transpiler/src/test/resources/conformance/protocol_runtime_.py new file mode 100644 index 00000000000..753fedd2747 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/protocol_runtime_.py @@ -0,0 +1,63 @@ +from typing import Protocol, runtime_checkable, SupportsInt + + +@runtime_checkable +class Closer(Protocol): + def close(self) -> None: ... + + +@runtime_checkable +class Named(Protocol): + name: str + + +class NotRt(Protocol): + def go(self) -> None: ... + + +@runtime_checkable +class Both(Closer, Protocol): + def open(self) -> None: ... + + +class File: + name = "f" + + def close(self): + pass + + def open(self): + pass + + +class Nope: + close = None + + +class Impl(Closer): + def close(self): + pass + + +print(isinstance(File(), Closer), isinstance(Nope(), Closer), isinstance(3, Closer)) +print(isinstance(File(), Named), isinstance(Nope(), Named)) +print(isinstance(File(), Both), isinstance(Impl(), Both), isinstance(Impl(), Closer)) +print(issubclass(File, Closer), issubclass(int, Closer), issubclass(File, Both)) +print(isinstance(3, SupportsInt), isinstance("x", SupportsInt)) +try: + isinstance(File(), NotRt) +except TypeError as e: + print("TypeError", e) +try: + issubclass(File, Named) +except TypeError as e: + print("TypeError", e) + + +def pick(x): + if isinstance(x, Closer): + return "closer" + return "other" + + +print(pick(File()), pick(1), pick(Impl())) diff --git a/maven/python-transpiler/src/test/resources/conformance/pytest_monkeypatch.out b/maven/python-transpiler/src/test/resources/conformance/pytest_monkeypatch.out new file mode 100644 index 00000000000..be819a35ffa --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/pytest_monkeypatch.out @@ -0,0 +1,6 @@ +set 2 +new red +dotted ! +deleted False +raising AttributeError +undone 1 False / diff --git a/maven/python-transpiler/src/test/resources/conformance/pytest_monkeypatch.py b/maven/python-transpiler/src/test/resources/conformance/pytest_monkeypatch.py new file mode 100644 index 00000000000..1340c856899 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/pytest_monkeypatch.py @@ -0,0 +1,27 @@ +import os.path +import pytest + + +class Box: + size = 1 + + +def main(): + mp = pytest.MonkeyPatch() + mp.setattr(Box, "size", 2) + print("set", Box.size) + mp.setattr(Box, "color", "red", raising=False) + print("new", Box.color) + mp.setattr("os.path.sep", "!") + print("dotted", os.path.sep) + mp.delattr(Box, "size") + print("deleted", hasattr(Box, "size")) + try: + mp.setattr(Box, "missing", 3) + except AttributeError: + print("raising", "AttributeError") + mp.undo() + print("undone", Box.size, hasattr(Box, "color"), os.path.sep) + + +main() diff --git a/maven/python-transpiler/src/test/resources/conformance/pytest_monkeypatch_receiver.out b/maven/python-transpiler/src/test/resources/conformance/pytest_monkeypatch_receiver.out new file mode 100644 index 00000000000..274a1cb7fef --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/pytest_monkeypatch_receiver.out @@ -0,0 +1,5 @@ +set 2 +attr receiver red +deleted False +other receiver [('set', 'x', 'y', 3), ('del', 'x', 'y')] +undone 1 False diff --git a/maven/python-transpiler/src/test/resources/conformance/pytest_monkeypatch_receiver.py b/maven/python-transpiler/src/test/resources/conformance/pytest_monkeypatch_receiver.py new file mode 100644 index 00000000000..6d5764c084d --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/pytest_monkeypatch_receiver.py @@ -0,0 +1,41 @@ +import pytest + + +class Box: + size = 1 + + +class Recorder: + def __init__(self): + self.calls = [] + + def setattr(self, a, b, c=None): + self.calls.append(("set", a, b, c)) + + def delattr(self, a, b): + self.calls.append(("del", a, b)) + + +class Holder: + def __init__(self, p): + self.p = p + + +def main(): + patcher = pytest.MonkeyPatch() + patcher.setattr(Box, "size", 2) + print("set", Box.size) + h = Holder(patcher) + h.p.setattr(Box, "color", "red", raising=False) + print("attr receiver", Box.color) + h.p.delattr(Box, "color") + print("deleted", hasattr(Box, "color")) + r = Recorder() + r.setattr("x", "y", 3) + r.delattr("x", "y") + print("other receiver", r.calls) + patcher.undo() + print("undone", Box.size, hasattr(Box, "color")) + + +main() diff --git a/maven/python-transpiler/src/test/resources/conformance/raise_jump.out b/maven/python-transpiler/src/test/resources/conformance/raise_jump.out new file mode 100644 index 00000000000..fb38bfe2e3b --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/raise_jump.out @@ -0,0 +1,3 @@ +123 +none outer 5 +(7, 8, 'RuntimeError') None diff --git a/maven/python-transpiler/src/test/resources/conformance/raise_jump.py b/maven/python-transpiler/src/test/resources/conformance/raise_jump.py new file mode 100644 index 00000000000..366d3451ab3 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/raise_jump.py @@ -0,0 +1,48 @@ +# A try whose body raises only by its own raise statements. +def classify(n): + out = 0 + for i in range(n): + try: + if i % 3 == 0: + raise ValueError(i) + elif i % 5 == 0: + raise KeyError(i * 2) + elif i > 1000 and i < 0: + raise IndexError() + except ValueError as e: + out += e.args[0] + except KeyError as e: + out -= e.args[0] + finally: + out += 1 + return out + + +def escapes(n): + try: + try: + if n > 2: + raise TypeError(n) + except ValueError: + return "wrong handler" + except TypeError as e: + return "outer " + str(e.args[0]) + return "none" + + +def chained(flag): + try: + if flag: + raise RuntimeError(7) + except RuntimeError as e: + try: + raise ValueError(8) + except ValueError as f: + return (e.args[0], f.args[0], type(f.__context__).__name__) + return None + + +print(classify(40)) +print(escapes(1), escapes(5)) +print(chained(True), chained(False)) + diff --git a/maven/python-transpiler/src/test/resources/conformance/random_hashlib.out b/maven/python-transpiler/src/test/resources/conformance/random_hashlib.out index e3d40d60bfb..57c508b0c96 100644 --- a/maven/python-transpiler/src/test/resources/conformance/random_hashlib.out +++ b/maven/python-transpiler/src/test/resources/conformance/random_hashlib.out @@ -53,3 +53,16 @@ ValueError empty range in randrange(5, 5) ValueError zero step for randrange() ValueError Sample larger than population or is negative TypeError Population must be a sequence. For dicts or sets, use sorted(d). +md5 d41d8cd9 93b885ad 6912ee65 51fdd1ac 48a62952 b2d3f56b 8bd70538 4fad3ab7 d1fec2ac 8402b21e 37eff018 46f98669 17b38392 e6899eaa +sha1 da39a3ee 5ba93c9d 8ae2d467 636e2ec6 6d942da0 c6138d51 69bd728a bc544e24 e4ce142d 89d7312a e6434bc4 3352e41c bf77ecf1 ac2a264c +sha224 d14a028c fff9292b 8991dfba 2b2cd637 049e8dd7 c37b88a3 114b5fd6 1aeef583 01e5abf5 554c9c3f 67d88da3 a80cb91e 0c82e586 591b5155 +sha256 e3b0c442 6e340b9c 463eb28e da2ae4d6 29af2686 fdeab9ac 4bfd2c8b 60780e94 09373f12 92ca0fa6 471fb943 5099c6a5 7728ae2f f3a25aa9 +sha384 38b060a7 bec021b4 dcedb6b5 7b9132d5 dd66b519 9f2c9eb7 14b0a9ff f5f9fe11 33ba080e d5fcfe2f ca238577 ef49ae5b 69672aca 6bee0411 +sha512 cf83e135 b8244d02 6856647f 8b12b2f6 9dc9c559 ee4320eb 02856cef a1a11144 c5fbd731 eab89674 1dffd5e3 1d9da57f f1dca2eb f1721f49 +blake2b 786a02f7 2fa3f686 659858f0 26cca012 d10bf9a1 2fc6e69f fcbe8be7 bf23c0c2 877fd652 b6292669 2319e378 f59711d4 d9cf5983 323e97a7 +blake2s 69217a30 e34d74db f4495470 e290dd27 e57cb794 56f34e8b 1b53ee94 0a4049d5 81dcc067 f18417b3 1fa877de 5bd169e6 0d273350 b928a178 +cf4ab791c62b8d2b2109c90275287816 +07221b1ffdee68746e3497ad47993c8f8011aaf770515bf8b3c70b848f6cfb00b28b479cc0e66c4b41d077264687dde7de9d877b27d1fb88f79c2099cc09dacc +9befd4490a26fb5c0b5c421777a1b38010f571bc +6b6e59aaf00eb730cf93de53560846722184bbd92f8368c21ffa95380c2f9fe6 36f45ecc9c029b7b14759ce6aefe4a162749051d8ea99bb40b842f536e65e70b 32 32 blake2b +6a7be24f5b46c5c3769d73a6689b3ad79f9f245a1cdb20e41ee9d5a31bea14445f54a362850dd4dc7d6a22b714d3d05635425c3f127951dfb8f1d9bf88f143538798e0acae2ca6a88b3f109a4e8c2cc1 diff --git a/maven/python-transpiler/src/test/resources/conformance/random_hashlib.py b/maven/python-transpiler/src/test/resources/conformance/random_hashlib.py index 334a46cb141..e1d88d5930a 100644 --- a/maven/python-transpiler/src/test/resources/conformance/random_hashlib.py +++ b/maven/python-transpiler/src/test/resources/conformance/random_hashlib.py @@ -49,3 +49,23 @@ call() except (ValueError, IndexError, TypeError) as e: print(type(e).__name__, e) + +# Every length around the block boundaries, fed whole and a byte at a time. +data = bytes(range(256)) * 3 +for name in ["md5", "sha1", "sha224", "sha256", "sha384", "sha512", "blake2b", "blake2s"]: + acc = [] + for n in (0, 1, 55, 56, 63, 64, 65, 111, 112, 127, 128, 129, 300, 768): + whole = hashlib.new(name, data[:n]).hexdigest() + h = hashlib.new(name) + for i in range(n): + h.update(data[i:i + 1]) + acc.append(whole[:8] + ("" if h.hexdigest() == whole else "!")) + print(name, " ".join(acc)) +print(hashlib.blake2b(b"abc", digest_size=16).hexdigest()) +print(hashlib.blake2b(b"abc", key=b"k" * 64, salt=b"s" * 16, person=b"p" * 16).hexdigest()) +print(hashlib.blake2s(b"abc", digest_size=20, key=b"key", salt=b"salt", person=b"me").hexdigest()) +b = hashlib.blake2b(b"a" * 200, digest_size=32) +c = b.copy() +c.update(b"tail") +print(b.hexdigest(), c.hexdigest(), b.digest_size, c.digest_size, c.name) +print(hashlib.pbkdf2_hmac("sha512", b"pw", b"salt", 3, 80).hex()) diff --git a/maven/python-transpiler/src/test/resources/conformance/re_subn.out b/maven/python-transpiler/src/test/resources/conformance/re_subn.out new file mode 100644 index 00000000000..e594b5ec3b4 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/re_subn.out @@ -0,0 +1,3 @@ +a b c ('-a-b-c-', 4) bba +1a 2b 😀3c d ('abc', 0) - +[a][] axb diff --git a/maven/python-transpiler/src/test/resources/conformance/re_subn.py b/maven/python-transpiler/src/test/resources/conformance/re_subn.py new file mode 100644 index 00000000000..a334af9c6c0 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/re_subn.py @@ -0,0 +1,4 @@ +import re +print(re.sub(r"\s+", " ", "a b\tc "), re.subn("x*", "-", "abc"), re.sub("a", "b", "aaa", count=2)) +print(re.sub(r"(\w)(\d)", r"\2\1", "a1 b2 \U0001F600c3 d"), re.subn("z", "y", "abc"), re.sub("", "-", "")) +print(re.sub("(a)|b", r"[\1]", "ab"), re.sub("\U0001F600", "x", "a\U0001F600b")) diff --git a/maven/python-transpiler/src/test/resources/conformance/rebounddeco_.out b/maven/python-transpiler/src/test/resources/conformance/rebounddeco_.out new file mode 100644 index 00000000000..3c4db8d28f3 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/rebounddeco_.out @@ -0,0 +1,2 @@ +False 1 +B 2 diff --git a/maven/python-transpiler/src/test/resources/conformance/rebounddeco_.py b/maven/python-transpiler/src/test/resources/conformance/rebounddeco_.py new file mode 100644 index 00000000000..510c0c0fb0c --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/rebounddeco_.py @@ -0,0 +1,32 @@ +# A module that rebinds `staticmethod`: a method it decorates is an ordinary +# method, so a call of it from __init__ sees the instance half built. + + +def staticmethod(f): + return f + + +class A: + def __init__(self): + self.seen = self.peek() + self.x = 1 + + @staticmethod + def peek(self): + return hasattr(self, "x") + + +class B: + def __init__(self): + self.seen = self.peek() + self.x = 2 + + @classmethod + def peek(cls): + return cls.__name__ + + +a = A() +print(a.seen, a.x) +b = B() +print(b.seen, b.x) diff --git a/maven/python-transpiler/src/test/resources/conformance/reduce_protocol.strict b/maven/python-transpiler/src/test/resources/conformance/reduce_protocol.strict new file mode 100644 index 00000000000..1c8be65c58b --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/reduce_protocol.strict @@ -0,0 +1,3 @@ +pickle:1276 setattr with a computed name is reflection; write override = pickle.Unpickler._step in cn1-python.properties and its compliant body in cn1-python-overrides/pickle.Unpickler._step.py +pickle:1338 getattr with a computed name is reflection; write override = pickle.Unpickler.find_class in cn1-python.properties and its compliant body in cn1-python-overrides/pickle.Unpickler.find_class.py +pickle:225 getattr with a computed name is reflection; write override = pickle._getattribute in cn1-python.properties and its compliant body in cn1-python-overrides/pickle._getattribute.py diff --git a/maven/python-transpiler/src/test/resources/conformance/scalar_probes.out b/maven/python-transpiler/src/test/resources/conformance/scalar_probes.out new file mode 100644 index 00000000000..403563eb647 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/scalar_probes.out @@ -0,0 +1,5 @@ +95 +missing +10115 +[None, None] +[0, 2, 4] diff --git a/maven/python-transpiler/src/test/resources/conformance/scalar_probes.py b/maven/python-transpiler/src/test/resources/conformance/scalar_probes.py new file mode 100644 index 00000000000..200a00e6b6b --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/scalar_probes.py @@ -0,0 +1,49 @@ +class Thing: + def __init__(self, i): + self.a = i + + +def probe(n): + hits = 0 + for i in range(n): + t = Thing(i) + hits += getattr(t, "b", 2) + hits += getattr(t, "a", 100) + try: + hits += t.c + except AttributeError: + hits += 3 + return hits + + +def described(): + t = Thing(5) + try: + return t.zz + except AttributeError: + return "missing" + + +print(probe(10)) +print(described()) +Thing.c = 1000 +Thing.b = 7 +print(probe(10)) + + +class Bound: + def __init__(self, v): + self.v = v + + +def method_later(n): + out = [] + for i in range(n): + b = Bound(i) + out.append(getattr(b, "twice", None)) + return out + + +print(method_later(2)) +Bound.twice = lambda self: self.v * 2 +print([f() for f in method_later(3)]) diff --git a/maven/python-transpiler/src/test/resources/conformance/setattr_before_property.strict b/maven/python-transpiler/src/test/resources/conformance/setattr_before_property.strict new file mode 100644 index 00000000000..3a04e82f2c4 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/setattr_before_property.strict @@ -0,0 +1,2 @@ +main:1 class Guarded has no layout: its body binds __setattr__ +main:40 class WithSetter has no layout: its body binds __setattr__ diff --git a/maven/python-transpiler/src/test/resources/conformance/shelve_.strict b/maven/python-transpiler/src/test/resources/conformance/shelve_.strict new file mode 100644 index 00000000000..1c8be65c58b --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/shelve_.strict @@ -0,0 +1,3 @@ +pickle:1276 setattr with a computed name is reflection; write override = pickle.Unpickler._step in cn1-python.properties and its compliant body in cn1-python-overrides/pickle.Unpickler._step.py +pickle:1338 getattr with a computed name is reflection; write override = pickle.Unpickler.find_class in cn1-python.properties and its compliant body in cn1-python-overrides/pickle.Unpickler.find_class.py +pickle:225 getattr with a computed name is reflection; write override = pickle._getattribute in cn1-python.properties and its compliant body in cn1-python-overrides/pickle._getattribute.py diff --git a/maven/python-transpiler/src/test/resources/conformance/slot_dispatch.out b/maven/python-transpiler/src/test/resources/conformance/slot_dispatch.out new file mode 100644 index 00000000000..5352a2f5207 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/slot_dispatch.out @@ -0,0 +1,10 @@ +0 9 shape:9 x:9 +1 12 circle!12 x!12 +2 p.area0 p.describe0 p.describe0 +3 16 shape:16 x:16 +side 3 +side 4 +side 4 +1 25 via:3 +2 +8 ['shape:4', 'circle!3', 'shape:1'] diff --git a/maven/python-transpiler/src/test/resources/conformance/slot_dispatch.py b/maven/python-transpiler/src/test/resources/conformance/slot_dispatch.py new file mode 100644 index 00000000000..f993ac1f5f3 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/slot_dispatch.py @@ -0,0 +1,101 @@ +# Calls on values whose class the build cannot pin to one: each is +# dispatched to the method of that name on whatever the value is, a +# method's own default where a class answers through __getattr__, a class +# attribute holding a class, descriptors on such values, and a class +# method called through the class with the instance as its argument. + + +class Shape: + def area(self): + return 0 + + def describe(self, prefix="shape"): + return prefix + ":" + str(self.area()) + + +class Square(Shape): + def __init__(self, n): + self.n = n + + def area(self): + return self.n * self.n + + @property + def side(self): + return self.n + + @classmethod + def unit(cls): + return cls(1) + + +class Circle: + def __init__(self, r): + self.r = r + + def area(self): + return 3 * self.r * self.r + + def describe(self, prefix="circle"): + return prefix + "!" + str(self.area()) + + @property + def side(self): + return self.r * 2 + + +class Proxy: + """Answers every unknown name with a callable of its own.""" + + def __init__(self, tag): + self.tag = tag + + def __getattr__(self, name): + def call(*args, **kwargs): + return self.tag + "." + name + str(len(args)) + return call + + +class Forwarder: + """Forwards unknown names to the object it wraps.""" + + def __init__(self, inner): + self.inner = inner + + def __getattr__(self, name): + return getattr(self.inner, name) + + +class Suite: + def __init__(self, items): + self.items = items + + +class Loader: + suiteClass = Suite + + def make(self, items): + return self.suiteClass(items) + + +def pick(i): + if i == 0: + return Square(3) + if i == 1: + return Circle(2) + if i == 2: + return Proxy("p") + return Forwarder(Square(4)) + + +for i in range(4): + v = pick(i) + print(i, v.area(), v.describe(), v.describe(prefix="x")) + +for i in (0, 1, 3): + print("side", pick(i).side) + +print(Square.unit().area(), Square.area(Square(5)), Shape.describe(Circle(1), "via")) +print(len(Loader().make([1, 2]).items)) +mixed = [Square(2), Circle(1), Square(1)] +print(sum(s.area() for s in mixed), [s.describe() for s in mixed]) diff --git a/maven/python-transpiler/src/test/resources/conformance/slot_dispatch.strict b/maven/python-transpiler/src/test/resources/conformance/slot_dispatch.strict new file mode 100644 index 00000000000..833c8dee5fd --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/slot_dispatch.strict @@ -0,0 +1 @@ +main:66 getattr with a computed name is reflection; write override = main.Forwarder.__getattr__ in cn1-python.properties and its compliant body in cn1-python-overrides/main.Forwarder.__getattr__.py diff --git a/maven/python-transpiler/src/test/resources/conformance/specdoor_.out b/maven/python-transpiler/src/test/resources/conformance/specdoor_.out new file mode 100644 index 00000000000..d17c344ac3f --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/specdoor_.out @@ -0,0 +1,6 @@ +AB +ABCD +TypeError abcd 4 +6 xxx [1, 1, 1] +ABCDZ 5 +Z 1 diff --git a/maven/python-transpiler/src/test/resources/conformance/specdoor_/main.py b/maven/python-transpiler/src/test/resources/conformance/specdoor_/main.py new file mode 100644 index 00000000000..471bf1ce7b0 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/specdoor_/main.py @@ -0,0 +1,37 @@ +import json + + +class Buf: + def __init__(self): + self.data = "" + self.n = 0 + + def feed(self, s): + self.data = self.data + s + self.n += len(s) + return self.data.upper() + + def scale(self, k): + return k * 3 + + +def unknown(text): + # json gives values the pass knows nothing about + return json.loads(text) + + +def main(): + b = Buf() + print(b.feed("ab")) + print(b.feed(unknown('"cd"'))) + try: + b.feed(unknown("[1, 2]")) + except TypeError as e: + print("TypeError", b.data, b.n) + print(b.scale(2), b.scale(unknown('"x"')), b.scale(unknown("[1]"))) + holder = [b, Buf()] + for h in holder: + print(h.feed(unknown('"z"')), h.n) + + +main() diff --git a/maven/python-transpiler/src/test/resources/conformance/split_loops.out b/maven/python-transpiler/src/test/resources/conformance/split_loops.out new file mode 100644 index 00000000000..891009d46ec --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/split_loops.out @@ -0,0 +1,7 @@ +['ALPHA', 'BETA', 'GAMMA', ''] +['A'] +(4, '') +(1, '') +(3, 'z') +empty separator +before two diff --git a/maven/python-transpiler/src/test/resources/conformance/split_loops.py b/maven/python-transpiler/src/test/resources/conformance/split_loops.py new file mode 100644 index 00000000000..b946c96abb6 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/split_loops.py @@ -0,0 +1,44 @@ +def words(text): + out = [] + for w in text.split(): + if w == "skip": + continue + if w == "stop": + break + out.append(w.upper()) + else: + out.append("") + return out + + +def pieces(text, sep): + n = 0 + last = None + for p in text.split(sep): + n += 1 + last = p + return n, last + + +def empty_sep(text): + try: + for p in text.split(""): + return "ran" + except ValueError as e: + return str(e) + + +def keep(text): + w = "before" + for w in text.split(): + pass + return w + + +print(words(" alpha skip\tbeta gamma\n")) +print(words("a stop b")) +print(pieces("a,,b,", ",")) +print(pieces("", ",")) +print(pieces("x--y--z", "--")) +print(empty_sep("abc")) +print(keep(" "), keep(" one two ")) diff --git a/maven/python-transpiler/src/test/resources/conformance/split_ws.out b/maven/python-transpiler/src/test/resources/conformance/split_ws.out new file mode 100644 index 00000000000..2fffaa8883c --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/split_ws.out @@ -0,0 +1,62 @@ +[] + 0 [] [] [] + 1 [] [] [] + 2 [] [] [] + -1 [] [] [] +[] + 0 [] [] [] + 1 [] [] [] + 2 [] [] [] + -1 [] [] [] +['a'] + 0 ['a'] ['a'] ['a'] + 1 ['a'] ['a'] ['a'] + 2 ['a'] ['a'] ['a'] + -1 ['a'] ['a'] ['a'] +['a'] + 0 ['a '] ['a '] [' a'] + 1 ['a'] ['a'] ['a'] + 2 ['a'] ['a'] ['a'] + -1 ['a'] ['a'] ['a'] +['a', 'b'] + 0 ['a b'] ['a b'] ['a b'] + 1 ['a', 'b'] ['a', 'b'] ['a', 'b'] + 2 ['a', 'b'] ['a', 'b'] ['a', 'b'] + -1 ['a', 'b'] ['a', 'b'] ['a', 'b'] +['a', 'b', 'c'] + 0 ['a b c '] ['a b c '] [' a b c'] + 1 ['a', 'b c '] ['a', 'b c '] [' a b', 'c'] + 2 ['a', 'b', 'c '] ['a', 'b', 'c '] [' a', 'b', 'c'] + -1 ['a', 'b', 'c'] ['a', 'b', 'c'] ['a', 'b', 'c'] +['a', 'b', 'c', 'd', 'e', 'f'] + 0 ['a\tb\nc\x0bd\x0ce\rf'] ['a\tb\nc\x0bd\x0ce\rf'] ['a\tb\nc\x0bd\x0ce\rf'] + 1 ['a', 'b\nc\x0bd\x0ce\rf'] ['a', 'b\nc\x0bd\x0ce\rf'] ['a\tb\nc\x0bd\x0ce', 'f'] + 2 ['a', 'b', 'c\x0bd\x0ce\rf'] ['a', 'b', 'c\x0bd\x0ce\rf'] ['a\tb\nc\x0bd', 'e', 'f'] + -1 ['a', 'b', 'c', 'd', 'e', 'f'] ['a', 'b', 'c', 'd', 'e', 'f'] ['a', 'b', 'c', 'd', 'e', 'f'] +['a', 'b', 'c'] + 0 ['a\x1cb\x1fc'] ['a\x1cb\x1fc'] ['a\x1cb\x1fc'] + 1 ['a', 'b\x1fc'] ['a', 'b\x1fc'] ['a\x1cb', 'c'] + 2 ['a', 'b', 'c'] ['a', 'b', 'c'] ['a', 'b', 'c'] + -1 ['a', 'b', 'c'] ['a', 'b', 'c'] ['a', 'b', 'c'] +['x', 'y', 'z'] + 0 ['x\xa0y\u2003z'] ['x\xa0y\u2003z'] ['x\xa0y\u2003z'] + 1 ['x', 'y\u2003z'] ['x', 'y\u2003z'] ['x\xa0y', 'z'] + 2 ['x', 'y', 'z'] ['x', 'y', 'z'] ['x', 'y', 'z'] + -1 ['x', 'y', 'z'] ['x', 'y', 'z'] ['x', 'y', 'z'] +['lead'] + 0 ['lead'] ['lead'] ['\u3000lead'] + 1 ['lead'] ['lead'] ['lead'] + 2 ['lead'] ['lead'] ['lead'] + -1 ['lead'] ['lead'] ['lead'] +['trail'] + 0 ['trail\x85'] ['trail\x85'] ['trail'] + 1 ['trail'] ['trail'] ['trail'] + 2 ['trail'] ['trail'] ['trail'] + -1 ['trail'] ['trail'] ['trail'] +['one', 'two', 'three', 'four'] + 0 ['one two three four'] ['one two three four'] ['one two three four'] + 1 ['one', 'two three four'] ['one', 'two three four'] ['one two three', 'four'] + 2 ['one', 'two', 'three four'] ['one', 'two', 'three four'] ['one two', 'three', 'four'] + -1 ['one', 'two', 'three', 'four'] ['one', 'two', 'three', 'four'] ['one', 'two', 'three', 'four'] +(9, 'quick') +(0, '') diff --git a/maven/python-transpiler/src/test/resources/conformance/split_ws.py b/maven/python-transpiler/src/test/resources/conformance/split_ws.py new file mode 100644 index 00000000000..41193f5672b --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/split_ws.py @@ -0,0 +1,21 @@ +# str.split with no separator: runs of whitespace, maxsplit, edge strings. +CASES = ["", " ", "a", " a ", "a b", " a b c ", "a\tb\nc\x0bd\x0ce\rf", "a\x1cb\x1fc", + "x y z", " lead", "trail\u0085", "one two three four"] +for s in CASES: + print(repr(s.split())) + for m in (0, 1, 2, -1): + print(" ", m, repr(s.split(None, m)), repr(s.split(maxsplit=m)), repr(s.rsplit(None, m))) + + +def words(text): + n = 0 + longest = "" + for w in text.split(): + n += 1 + if len(w) > len(longest): + longest = w + return n, longest + + +print(words("the quick brown\tfox jumps\nover the lazy dog")) +print(words("")) diff --git a/maven/python-transpiler/src/test/resources/conformance/sqlalchemy_model_init.out b/maven/python-transpiler/src/test/resources/conformance/sqlalchemy_model_init.out new file mode 100644 index 00000000000..ad5dc101ee5 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/sqlalchemy_model_init.out @@ -0,0 +1,7 @@ +Ann ['T1', 'T2'] True Ann HELLO +TypeError +TypeError +TypeError +1 Ann anon 2 +2 Bob bb 0 +HELLO diff --git a/maven/python-transpiler/src/test/resources/conformance/sqlalchemy_model_init.py b/maven/python-transpiler/src/test/resources/conformance/sqlalchemy_model_init.py new file mode 100644 index 00000000000..0576852e8b7 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/sqlalchemy_model_init.py @@ -0,0 +1,55 @@ +# The constructor of a mapped class: keyword-only, columns, relationships, +# an inherited user __init__, unknown keywords and positional arguments. +from typing import List, Optional +from sqlalchemy import create_engine, ForeignKey, String, select +from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, relationship, Session + + +class Base(DeclarativeBase): + pass + + +class Author(Base): + __tablename__ = "author" + id: Mapped[int] = mapped_column(primary_key=True) + name: Mapped[str] = mapped_column(String(50)) + nick: Mapped[Optional[str]] = mapped_column(default="anon") + books: Mapped[List["Book"]] = relationship(back_populates="author") + + +class Book(Base): + __tablename__ = "book" + id: Mapped[int] = mapped_column(primary_key=True) + title: Mapped[str] + author_id: Mapped[Optional[int]] = mapped_column(ForeignKey("author.id")) + author: Mapped[Optional[Author]] = relationship(back_populates="books") + + +class Note(Base): + __tablename__ = "note" + id: Mapped[int] = mapped_column(primary_key=True) + text: Mapped[str] + + def __init__(self, text, **kw): + super().__init__(text=text.upper(), **kw) + + +engine = create_engine("sqlite://") +Base.metadata.create_all(engine) +a = Author(name="Ann") +b = Book(title="T1", author=a) +c = Book(author=a, title="T2") +n = Note("hello") +print(a.name, [x.title for x in a.books], b.author is a, c.author.name, n.text) +for bad in (lambda: Author(nme="x"), lambda: Author("x"), lambda: Note("x", bogus=1)): + try: + bad() + print("no error") + except TypeError: + print("TypeError") +with Session(engine) as s: + s.add_all([a, n, Author(name="Bob", nick="bb")]) + s.commit() + for x in s.scalars(select(Author).order_by(Author.id)): + print(x.id, x.name, x.nick, len(x.books)) + print(s.scalars(select(Note)).one().text) diff --git a/maven/python-transpiler/src/test/resources/conformance/sqlite3_.out b/maven/python-transpiler/src/test/resources/conformance/sqlite3_.out index 4f669c6db77..749805fcc8c 100644 --- a/maven/python-transpiler/src/test/resources/conformance/sqlite3_.out +++ b/maven/python-transpiler/src/test/resources/conformance/sqlite3_.out @@ -49,3 +49,8 @@ isolation None in_tx False explicit True [(1,)] qmark 2.0 +(42, None, 2.5) +('1|two|3.0',) +(4,) +(9,) +error: user-defined function raised exception diff --git a/maven/python-transpiler/src/test/resources/conformance/sqlite3_.py b/maven/python-transpiler/src/test/resources/conformance/sqlite3_.py index 4b4e23f74bc..cce350389c9 100644 --- a/maven/python-transpiler/src/test/resources/conformance/sqlite3_.py +++ b/maven/python-transpiler/src/test/resources/conformance/sqlite3_.py @@ -130,3 +130,23 @@ def __init__(self, x, y): print(con4.execute("SELECT * FROM a").fetchall()) print(sqlite3.paramstyle, sqlite3.apilevel) con.close() + +# User-defined functions, as sqlite-utils and llm register them. +fconn = sqlite3.connect(":memory:") +fconn.create_function("plus_one", 1, lambda v: None if v is None else v + 1) +fconn.create_function("joined", -1, lambda *a: "|".join(str(x) for x in a)) +fconn.create_function("blob_len", 1, lambda b: len(b)) +print(fconn.execute("SELECT plus_one(41), plus_one(NULL), plus_one(1.5)").fetchone()) +print(fconn.execute("SELECT joined(1, 'two', 3.0)").fetchone()) +print(fconn.execute("SELECT blob_len(?)", (b"abcd",)).fetchone()) +fconn.execute("CREATE TABLE t (v INTEGER)") +fconn.executemany("INSERT INTO t VALUES (?)", [(1,), (2,), (3,)]) +print(fconn.execute("SELECT sum(plus_one(v)) FROM t").fetchone()) +def boom(v): + raise ValueError("no") +fconn.create_function("boom", 1, boom) +try: + fconn.execute("SELECT boom(1)").fetchone() +except sqlite3.OperationalError as e: + print("error:", e) +fconn.close() diff --git a/maven/python-transpiler/src/test/resources/conformance/sqlite_scan.out b/maven/python-transpiler/src/test/resources/conformance/sqlite_scan.out new file mode 100644 index 00000000000..1e783fbabf6 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/sqlite_scan.out @@ -0,0 +1,14 @@ +(1, 'x', 'q', 'r') +(2, 'y', 'z', '2') +('p2', 'p1', 'p2', 'p3') +("it's ? :not", 'v', None, None) +('a"b', 5, None, None) +('accent', 'été :x ?', None, None) +ProgrammingError +ProgrammingError +ProgrammingError +ProgrammingError +[(1,), (';',), (2,), (';',)] +[('a;b', 3)] +[('k:x',)] +True False diff --git a/maven/python-transpiler/src/test/resources/conformance/sqlite_scan.py b/maven/python-transpiler/src/test/resources/conformance/sqlite_scan.py new file mode 100644 index 00000000000..62e8b5616a3 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/sqlite_scan.py @@ -0,0 +1,38 @@ +# Placeholders, quoting, comments and statement ends, as sqlite3 finds them in a +# statement's text before the engine sees it. +import sqlite3 + +db = sqlite3.connect(":memory:") +db.execute("create table t (a, b, [c?d] text, \"e:f\" text)") +db.execute("insert into t values (?, ?, ?, ?)", (1, "x", "q", "r")) +db.execute("insert into t values (:a, @b, $c, :a)", {"a": 2, "b": "y", "c": "z"}) +db.execute("insert into t values (?2, ?1, ?2, ?3)", ("p1", "p2", "p3")) +db.execute("insert into t (a, b) values ('it''s ? :not', ?) -- a ? in a comment", ("v",)) +db.execute("insert into t (a, b) /* :skipped ? */ values (\"a\"\"b\", ?)", (5,)) +db.execute("insert into t (a, b) values (?, 'été :x ?')", ("accent",)) +for row in db.execute("select a, b, [c?d], \"e:f\" from t order by rowid"): + print(row) + +for sql, args in ( + ("select ?, ?", (1,)), + ("select :a, :b", {"a": 1}), + ("select 1; select 2", ()), + ("select ?1, ?3", (1, 2)), +): + try: + print(db.execute(sql, args).fetchall()) + except (sqlite3.Error, ValueError) as e: + print(type(e).__name__) + +db.executescript(""" +create table log (n); +create trigger tr after insert on t begin + insert into log values (case when new.a = 'end' then 1 else 2 end); + insert into log values (';'); +end; +insert into t (a) values ('end'); insert into t (a) values ('begin'); +""") +print(db.execute("select n from log order by rowid").fetchall()) +print(db.execute("select 'a;b', ? ; ", (3,)).fetchall()) +print(db.execute("select :x || ':x'", {"x": "k"}).fetchall()) +print(sqlite3.complete_statement("select 1;"), sqlite3.complete_statement("select ';")) diff --git a/maven/python-transpiler/src/test/resources/conformance/starred_arg_reach.out b/maven/python-transpiler/src/test/resources/conformance/starred_arg_reach.out new file mode 100644 index 00000000000..0b27e3ee516 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/starred_arg_reach.out @@ -0,0 +1,6 @@ +['id=1', 'ver=2', [('a', 1)]] +['t', '2'] +1 +['id=4', 'ver=8', [('a', 4)]] +['t', '5'] +4 diff --git a/maven/python-transpiler/src/test/resources/conformance/starred_arg_reach.py b/maven/python-transpiler/src/test/resources/conformance/starred_arg_reach.py new file mode 100644 index 00000000000..45665ea13dc --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/starred_arg_reach.py @@ -0,0 +1,50 @@ +# A method whose only caller sits inside a starred argument must still be +# built: the call is reached through the spread value. + + +class Query: + def __init__(self): + self.parts = [] + + def where(self, *conds): + self.parts.extend(conds) + return self + + def values(self, d): + self.parts.append(sorted(d.items())) + return self + + +class Table: + def update(self): + return Query() + + +def pick(registry, key): + return registry[key] + + +class Session: + def __init__(self): + self.log = [] + + def _pk_where(self, n): + return ["id=%d" % n, "ver=%d" % (n * 2)] + + def _tags(self, n): + return tuple("t%d" % i for i in range(n)) + + def flush(self, registry, n): + t = pick(registry, "t") + q = t.update().where(*self._pk_where(n)).values({"a": n}) + self.log.append(q.parts) + self.log.append(list(max(*self._tags(n + 2)))) + self.log.append(len([*self._tags(n)])) + + +s = Session() +reg = {"t": Table(), "u": 3} +s.flush(reg, 1) +s.flush(reg, 4) +for x in s.log: + print(x) diff --git a/maven/python-transpiler/src/test/resources/conformance/strings.out b/maven/python-transpiler/src/test/resources/conformance/strings.out index 20a22d65e1a..d72de3b9f05 100644 --- a/maven/python-transpiler/src/test/resources/conformance/strings.out +++ b/maven/python-transpiler/src/test/resources/conformance/strings.out @@ -24,3 +24,4 @@ encode error UnicodeEncodeError a b 1 3 3 41 +['0xfeff', '0xa', '0xa0', '0x200d'] diff --git a/maven/python-transpiler/src/test/resources/conformance/strings.py b/maven/python-transpiler/src/test/resources/conformance/strings.py index 508562742a9..92eadcbb9ea 100644 --- a/maven/python-transpiler/src/test/resources/conformance/strings.py +++ b/maven/python-transpiler/src/test/resources/conformance/strings.py @@ -53,3 +53,5 @@ def split(self): print(w) print(len("\ud800"), len("a\U0001F600b"), len("\udc00\ud800x"), len("x" * 40 + "\U0001F600")) +# Formal name aliases (NameAliases.txt), which Beautiful Soup uses. +print([hex(ord(c)) for c in "\N{BYTE ORDER MARK}\N{LINE FEED}\N{nbsp}\N{ZWJ}"]) diff --git a/maven/python-transpiler/src/test/resources/conformance/super_mro_uniform.out b/maven/python-transpiler/src/test/resources/conformance/super_mro_uniform.out new file mode 100644 index 00000000000..9168b202a6b --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/super_mro_uniform.out @@ -0,0 +1,7 @@ +Typed ['Typed', 'Base', 3] +Conv ['Conv', 'Typed', 'Base', 6] +Str ['Str', 'Typed', 'Base', 4] +Text ['Str', 'Conv', 'Typed', 'Base', 8] +Text2 ['Text2', 'Str', 'Conv', 'Typed', 'Base', 8] +['Text2', 'Text', 'Str', 'Conv', 'Typed', 'Base', 'object'] +['Text2', 'Str', 'Conv', 'Typed', 'patched', 4] ['Conv', 'Typed', 'patched', 2] diff --git a/maven/python-transpiler/src/test/resources/conformance/super_mro_uniform.py b/maven/python-transpiler/src/test/resources/conformance/super_mro_uniform.py new file mode 100644 index 00000000000..728a93b796b --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/super_mro_uniform.py @@ -0,0 +1,34 @@ +# super() in a class some subclass mixes another base into: the next +# class in the MRO is the same for every subclass (resolved statically), +# and patching a class between them after definition is still seen. +class Base: + def put(self, v): + return ["Base", v] + +class Typed(Base): + def put(self, v): + return ["Typed"] + super().put(v) + +class Conv(Typed): + def put(self, v): + return ["Conv"] + super().put(v * 2) + +class Str(Typed): + def put(self, v): + return ["Str"] + super().put(v + 1) + +class Text(Str, Conv): + pass + +class Text2(Text): + def put(self, v): + return ["Text2"] + super().put(v) + +for o in (Typed(), Conv(), Str(), Text(), Text2()): + print(type(o).__name__, o.put(3)) +print([c.__name__ for c in Text2.__mro__]) + +def patched(self, v): + return ["patched", v] +Base.put = patched +print(Text2().put(1), Conv().put(1)) diff --git a/maven/python-transpiler/src/test/resources/conformance/system_random.out b/maven/python-transpiler/src/test/resources/conformance/system_random.out new file mode 100644 index 00000000000..3b98c3795d9 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/system_random.out @@ -0,0 +1,13 @@ +0 1 300 bytes +True +ValueError +True +0 True +True +5 True +True a +True +NotImplementedError +NotImplementedError +12 24 0 0 +4 True diff --git a/maven/python-transpiler/src/test/resources/conformance/system_random.py b/maven/python-transpiler/src/test/resources/conformance/system_random.py new file mode 100644 index 00000000000..a44851fbc69 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/system_random.py @@ -0,0 +1,31 @@ +# The platform's entropy behind os.urandom, secrets, uuid4 and SystemRandom: +# nothing here can print a value, only what every value must satisfy. +import os +import random +import secrets +import uuid + +print(len(os.urandom(0)), len(os.urandom(1)), len(os.urandom(300)), type(os.urandom(4)).__name__) +print(os.urandom(16) != os.urandom(16)) +try: + os.urandom(-1) +except ValueError: + print("ValueError") +r = random.SystemRandom() +print(all(0.0 <= r.random() < 1.0 for _ in range(200))) +print(r.getrandbits(0), all(r.getrandbits(k) < (1 << k) for k in (1, 7, 8, 9, 31, 32, 33, 64, 65, 200))) +print(max(r.getrandbits(70).bit_length() for _ in range(64)) > 60) +print(len(r.randbytes(5)), all(3 <= r.randint(3, 9) <= 9 for _ in range(100))) +print(sorted(r.sample(range(10), 10)) == list(range(10)), r.choice("a")) +r.seed(1) +a = r.getrandbits(64) +r.seed(1) +print(a != r.getrandbits(64)) +for name in ("getstate", "setstate"): + try: + getattr(r, name)(*([None] if name == "setstate" else [])) + except NotImplementedError: + print("NotImplementedError") +print(len(secrets.token_bytes(12)), len(secrets.token_hex(12)), secrets.randbelow(1), secrets.randbits(0)) +u = uuid.uuid4() +print(u.version, u != uuid.uuid4()) diff --git a/maven/python-transpiler/src/test/resources/conformance/typed_lowerings.out b/maven/python-transpiler/src/test/resources/conformance/typed_lowerings.out new file mode 100644 index 00000000000..8fbdc719058 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/typed_lowerings.out @@ -0,0 +1,14 @@ +(True, False, True) +(False, True, False) +(False, True, True) +(3, 9) (3, 9) (2, 2.5) ('a', 'b') (5, 1000000000000000000000000000000) +(Odd(3), Odd(3)) (Odd(8), Odd(8)) +(['x', 2, 'x', 2, None], [1, None, None]) +(2, 4, False, False) (2, 2, True, False) (100000000000000000000, -1, False, None) +(2, True, True) (2, False, True) (5, False, True) (2, False, True) +(3, 3, False, False) +TypeError slice indices must be integers or None or have an __index__ method +(2, ['a', 'b']) +('patched any 1', True, 'patched any 12') +('patched min', 2) +(True, True, True) (1, 2) diff --git a/maven/python-transpiler/src/test/resources/conformance/typed_lowerings.py b/maven/python-transpiler/src/test/resources/conformance/typed_lowerings.py new file mode 100644 index 00000000000..18ad9e61730 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/typed_lowerings.py @@ -0,0 +1,91 @@ +# Typed lowerings with fast paths and generic fallbacks: any/all over a +# generator, two-argument min/max, extend with a literal list, str.find with +# a start of no known type, a str subscript compared by char, set(). + + +class Rule: + def __init__(self, on): + self.on = on + + +class Odd: + def __init__(self, v): + self.v = v + + def __lt__(self, o): + return self.v % 7 < o.v % 7 + + def __gt__(self, o): + return self.v % 7 > o.v % 7 + + def __repr__(self): + return "Odd(%d)" % self.v + + +class Idx: + def __index__(self): + return 2 + + +def flags(rules, limit): + hit = any(r.on for r in rules) + every = all(r.on for r in rules if r.on is not None) + deep = any(a * b > limit for a in range(4) for b in range(4) if a != b) + return hit, every, deep + + +def mins(a, b): + return min(a, b), max(a, b) + + +def grow(xs, a, b, c): + out = [] + out.extend([a, b]) + out.extend([a, b, c]) + xs.extend([c, c]) + return out, xs + + +def scan(text, start): + k = start + n = len(text) + while k < n and text[k] not in " =>": + k += 1 + q = text.find("=", start) + s = text.startswith("b", start) + return k, q, s, text[k] == ">" if k < n else None + + +def probe(text, start): + q = text.find("c", start) + return q, text.startswith("c", start), text.endswith("c", start) + + +def count(words): + seen = set() + for w in words: + seen.add(w) + return len(seen), sorted(seen) + + +print(flags([Rule(0), Rule(None), Rule(3)], 5)) +print(flags([Rule(None)], 100)) +print(flags([], -1)) +print(mins(3, 9), mins(9, 3), mins(2.5, 2), mins("b", "a"), mins(10 ** 30, 5)) +print(mins(Odd(3), Odd(10)), mins(Odd(8), Odd(1))) +print(grow([1], "x", 2, None)) +print(scan("ab c=d>", 0), scan("ab=c>", True), scan("abc>", 10 ** 20)) +print(probe("abcabc", Idx()), probe("abcabc", None), probe("abcabc", -2), probe("abcabc", 1)) +print(scan("x\U0001f600y=z>", 0)) +try: + probe("abc", "1") +except TypeError as e: + print("TypeError", e) +print(count(["a", "b", "a"])) +real_any, real_min = any, min +any = lambda it: "patched any %d" % len(list(it)) +min = lambda a, b: "patched min" +print(flags([Rule(1)], 0)) +print(mins(1, 2)) +any, min = real_any, real_min +print(flags([Rule(1)], 0), mins(1, 2)) diff --git a/maven/python-transpiler/src/test/resources/conformance/typed_str_params.out b/maven/python-transpiler/src/test/resources/conformance/typed_str_params.out new file mode 100644 index 00000000000..49a3d819dbd --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/typed_str_params.out @@ -0,0 +1,92 @@ +[('word', 'select'), ('ws', ' '), ('string', "'a b'"), ('ws', ' '), ('comment', '-- note\n'), ('word', 'from'), ('ws', ' '), ('string', '"t"'), ('ws', ' '), ('word', 'where'), ('ws', ' '), ('word', 'x')] +[('word', 'plain'), ('ws', ' '), ('word', 'words'), ('ws', ' '), ('word', 'only')] +[('word', 'a'), ('ws', ' '), ('string', "'b'"), ('ws', ' '), ('word', 'c')] +ValueError: Unterminated ' quoted token +TypeError +TypeError +AttributeError +AttributeError +'' [False, False, False, False, False, False] +' \t\n' [True, False, False, False, False, False] +'123' [False, True, True, True, False, True] +'\xb2' [False, True, False, True, False, True] +'\u0663' [False, True, True, True, False, True] +'abc' [False, False, False, False, True, True] +'abc1' [False, False, False, False, False, True] +'a b' [False, False, False, False, False, False] +'\xbd' [False, False, False, True, False, True] +-20 -20 [0, 10, -1, -1, True, True, False, False] [0, 13, 0, 0, True, True, True, True] [1, 4, -1, -1, False, True, False, False] +-20 -2 [0, 10, 0, 7, True, True, True, False] [0, 13, 0, 11, True, True, True, True] [1, 4, 1, 1, False, True, False, False] +-20 0 [0, 10, -1, -1, True, True, False, False] [0, 13, 0, 0, True, True, True, True] [1, 4, -1, -1, False, True, False, False] +-20 5 [0, 10, 0, 0, True, True, True, False] [0, 13, 0, 5, True, True, True, True] [1, 4, 1, 1, False, True, False, False] +-20 13 [0, 10, 0, 10, True, True, True, True] [0, 13, 0, 13, True, True, True, True] [1, 4, 1, 4, False, True, False, True] +-20 99 [0, 10, 0, 10, True, True, True, True] [0, 13, 0, 13, True, True, True, True] [1, 4, 1, 4, False, True, False, True] +-3 -20 [10, 10, -1, -1, True, True, False, False] [10, 13, -1, -1, True, True, False, False] [4, 4, -1, -1, False, True, False, False] +-3 -2 [10, 10, -1, -1, True, True, False, False] [10, 13, 10, 11, True, True, True, True] [4, 4, -1, -1, False, True, False, False] +-3 0 [10, 10, -1, -1, True, True, False, False] [10, 13, -1, -1, True, True, False, False] [4, 4, -1, -1, False, True, False, False] +-3 5 [10, 10, -1, -1, True, True, False, False] [10, 13, -1, -1, True, True, False, False] [4, 4, -1, -1, False, True, False, False] +-3 13 [10, 10, 10, 10, True, True, True, True] [10, 13, 10, 13, True, True, True, True] [4, 4, 4, 4, False, True, False, True] +-3 99 [10, 10, 10, 10, True, True, True, True] [10, 13, 10, 13, True, True, True, True] [4, 4, 4, 4, False, True, False, True] +0 -20 [0, 10, -1, -1, True, True, False, False] [0, 13, 0, 0, True, True, True, True] [1, 4, -1, -1, False, True, False, False] +0 -2 [0, 10, 0, 7, True, True, True, False] [0, 13, 0, 11, True, True, True, True] [1, 4, 1, 1, False, True, False, False] +0 0 [0, 10, -1, -1, True, True, False, False] [0, 13, 0, 0, True, True, True, True] [1, 4, -1, -1, False, True, False, False] +0 5 [0, 10, 0, 0, True, True, True, False] [0, 13, 0, 5, True, True, True, True] [1, 4, 1, 1, False, True, False, False] +0 13 [0, 10, 0, 10, True, True, True, True] [0, 13, 0, 13, True, True, True, True] [1, 4, 1, 4, False, True, False, True] +0 99 [0, 10, 0, 10, True, True, True, True] [0, 13, 0, 13, True, True, True, True] [1, 4, 1, 4, False, True, False, True] +2 -20 [3, 10, -1, -1, False, True, False, False] [2, 13, -1, -1, True, True, False, False] [4, 4, -1, -1, False, True, False, False] +2 -2 [3, 10, 3, 7, False, True, False, False] [2, 13, 2, 11, True, True, True, True] [4, 4, -1, -1, False, True, False, False] +2 0 [3, 10, -1, -1, False, True, False, False] [2, 13, -1, -1, True, True, False, False] [4, 4, -1, -1, False, True, False, False] +2 5 [3, 10, -1, -1, False, True, False, False] [2, 13, 2, 5, True, True, True, True] [4, 4, -1, -1, False, True, False, False] +2 13 [3, 10, 3, 10, False, True, False, True] [2, 13, 2, 13, True, True, True, True] [4, 4, 4, 4, False, True, False, True] +2 99 [3, 10, 3, 10, False, True, False, True] [2, 13, 2, 13, True, True, True, True] [4, 4, 4, 4, False, True, False, True] +7 -20 [7, 10, -1, -1, True, True, False, False] [7, 13, -1, -1, True, True, False, False] [-1, -1, -1, -1, False, False, False, False] +7 -2 [7, 10, 7, 7, True, True, True, False] [7, 13, 7, 11, True, True, True, True] [-1, -1, -1, -1, False, False, False, False] +7 0 [7, 10, -1, -1, True, True, False, False] [7, 13, -1, -1, True, True, False, False] [-1, -1, -1, -1, False, False, False, False] +7 5 [7, 10, -1, -1, True, True, False, False] [7, 13, -1, -1, True, True, False, False] [-1, -1, -1, -1, False, False, False, False] +7 13 [7, 10, 7, 10, True, True, True, True] [7, 13, 7, 13, True, True, True, True] [-1, -1, -1, -1, False, False, False, False] +7 99 [7, 10, 7, 10, True, True, True, True] [7, 13, 7, 13, True, True, True, True] [-1, -1, -1, -1, False, False, False, False] +13 -20 [-1, -1, -1, -1, False, False, False, False] [13, 13, -1, -1, True, True, False, False] [-1, -1, -1, -1, False, False, False, False] +13 -2 [-1, -1, -1, -1, False, False, False, False] [13, 13, -1, -1, True, True, False, False] [-1, -1, -1, -1, False, False, False, False] +13 0 [-1, -1, -1, -1, False, False, False, False] [13, 13, -1, -1, True, True, False, False] [-1, -1, -1, -1, False, False, False, False] +13 5 [-1, -1, -1, -1, False, False, False, False] [13, 13, -1, -1, True, True, False, False] [-1, -1, -1, -1, False, False, False, False] +13 13 [-1, -1, -1, -1, False, False, False, False] [13, 13, 13, 13, True, True, True, True] [-1, -1, -1, -1, False, False, False, False] +13 99 [-1, -1, -1, -1, False, False, False, False] [13, 13, 13, 13, True, True, True, True] [-1, -1, -1, -1, False, False, False, False] +99 -20 [-1, -1, -1, -1, False, False, False, False] [-1, -1, -1, -1, False, False, False, False] [-1, -1, -1, -1, False, False, False, False] +99 -2 [-1, -1, -1, -1, False, False, False, False] [-1, -1, -1, -1, False, False, False, False] [-1, -1, -1, -1, False, False, False, False] +99 0 [-1, -1, -1, -1, False, False, False, False] [-1, -1, -1, -1, False, False, False, False] [-1, -1, -1, -1, False, False, False, False] +99 5 [-1, -1, -1, -1, False, False, False, False] [-1, -1, -1, -1, False, False, False, False] [-1, -1, -1, -1, False, False, False, False] +99 13 [-1, -1, -1, -1, False, False, False, False] [-1, -1, -1, -1, False, False, False, False] [-1, -1, -1, -1, False, False, False, False] +99 99 [-1, -1, -1, -1, False, False, False, False] [-1, -1, -1, -1, False, False, False, False] [-1, -1, -1, -1, False, False, False, False] +[21, 21, 21, 21, False, False, False, False] +'a' 'a' +'c' 'IndexError: string index out of range' +'\U0001f600' 'IndexError: string index out of range' +'a' 'IndexError: string index out of range' +'c' 'IndexError: string index out of range' +'IndexError: string index out of range' 'IndexError: string index out of range' +'c' 'c' +'\U0001f600' 'IndexError: string index out of range' +'a' 'IndexError: string index out of range' +'IndexError: string index out of range' 'IndexError: string index out of range' +"IndexError: cannot fit 'int' into an index-sized integer" "IndexError: cannot fit 'int' into an index-sized integer" +'b' 'b' +e TypeError 2 +ababab [1, 1] sesese +258 11 6 +97 115 +99 108 +99 120 +IndexError: index out of range 101 +IndexError: index out of range 114 +IndexError: cannot fit 'int' into an index-sized integer IndexError: cannot fit 'int' into an index-sized integer +98 101 +0 1 0 1 +bcdef ab [1, 2, 3] (1, 2) b'xyz' +IndexError: cannot fit 'int' into an index-sized integer +IndexError: cannot fit 'int' into an index-sized integer +IndexError: cannot fit 'int' into an index-sized integer +IndexError: cannot fit 'int' into an index-sized integer +IndexError: range object index out of range +IndexError: range object index out of range +IndexError: cannot fit 'int' into an index-sized integer +IndexError: cannot fit 'int' into an index-sized integer diff --git a/maven/python-transpiler/src/test/resources/conformance/typed_str_params.py b/maven/python-transpiler/src/test/resources/conformance/typed_str_params.py new file mode 100644 index 00000000000..d41ea95be04 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/typed_str_params.py @@ -0,0 +1,119 @@ +# Functions whose annotations name str, int and bytes, called with what the +# annotation says, with something else, and with nothing the build can tell. + + +def lex(sql: str) -> list: + out = [] + i = 0 + while i < len(sql): + start = i + ch = sql[i] + if ch.isspace(): + i += 1 + while i < len(sql) and sql[i].isspace(): + i += 1 + out.append(("ws", sql[start:i])) + continue + if sql.startswith("--", i): + nl = sql.find("\n", i + 2) + i = len(sql) if nl == -1 else nl + 1 + out.append(("comment", sql[start:i])) + continue + if ch in ("'", '"'): + quote = ch + i += 1 + while i < len(sql): + if sql[i] == quote: + i += 1 + break + i += 1 + else: + raise ValueError(f"Unterminated {quote} quoted token") + out.append(("string", sql[start:i])) + continue + i += 1 + while i < len(sql) and not sql[i].isspace() and sql[i] not in "'\"": + i += 1 + out.append(("word", sql[start:i])) + return out + + +def kinds(s: str): + return [s.isspace(), s.isdigit(), s.isdecimal(), s.isnumeric(), s.isalpha(), s.isalnum()] + + +def probe(s: str, sub: str, a: int, b: int): + return [s.find(sub, a), s.rfind(sub, a), s.find(sub, a, b), s.rfind(sub, a, b), + s.startswith(sub, a), s.endswith(sub, a), s.startswith(sub, a, b), s.endswith(sub, a, b)] + + +def at(s: str, i: int): + try: + return s[i] + except IndexError as e: + return "IndexError: " + str(e) + except TypeError as e: + return "TypeError" + + +def byte_at(data: bytes, i: int): + try: + return data[i] + except IndexError as e: + return "IndexError: " + str(e) + + +def repeat(text: str, n: int): + return text * n + + +def total(data: bytes): + t = 0 + for b in data: + t += b + return t + + +class Text(str): + pass + + +values = {"sql": "select 'a b' -- note\nfrom \"t\" where x", "n": 3} +print(lex(values["sql"])) +print(lex("plain words only")) +print(lex(Text("a 'b' c"))) +try: + lex("bad 'never closed") +except ValueError as e: + print("ValueError:", e) +for bad in (None, 7, b"bytes", ["a", " ", "b"]): + try: + print(lex(bad)) + except (TypeError, AttributeError) as e: + print(type(e).__name__) + +for s in ("", " \t\n", "123", "²", "٣", "abc", "abc1", "a b", "½"): + print(ascii(s), kinds(s)) + +text = "abcabc\U0001f600abcabc" +for a in (-20, -3, 0, 2, 7, 13, 99): + for b in (-20, -2, 0, 5, 13, 99): + print(a, b, probe(text, "abc", a, b), probe(text, "", a, b), probe("abcabc", "bc", a, b)) +print(probe(values["sql"], "from", values["n"], 2 ** 70)) +for i in (0, 5, 6, 7, 12, 13, -1, -7, -13, -14, 2 ** 70, True): + print(ascii(at(text, i)), ascii(at("abc", i))) +print(at(values["sql"], values["n"]), at(values["sql"], "x"), at([1, 2, 3], 1)) +print(repeat("ab", 3), repeat([1], 2), repeat(values["sql"][:2], values["n"])) +print(total(b"\x01\x02\xff"), total(bytearray(b"\x05\x06")), total([1, 2, 3])) +for i in (0, 2, -1, 3, -4, 2 ** 70, True): + print(byte_at(b"abc", i), byte_at(values["sql"].encode(), i)) +print("abc".count("", 5), "abc".count("", 3), "abc".count("", 2, 1), "abc".count("b", -2 ** 70, 2 ** 70)) +big = 2 ** 70 +print("abcdef"[1:big], "abcdef"[-big:2], "abcdef"[big:], [1, 2, 3][-big:big], (1, 2)[:big], b"xyz"[-big:big]) +for seq in ([1, 2], (1, 2), range(3), bytearray(b"ab")): + for i in (big, -big): + try: + seq[i] + except IndexError as e: + print("IndexError:", e) + diff --git a/maven/python-transpiler/src/test/resources/conformance/typedcells.out b/maven/python-transpiler/src/test/resources/conformance/typedcells.out new file mode 100644 index 00000000000..d60ba5a1980 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/typedcells.out @@ -0,0 +1,8 @@ +9 7 +[990, 990, 990] +[101, 102] +now a string +NameError+again NameError5 +720 9 ababab +[5, 6, 9] [[2, 4], [2, 4], [2, 4]] +[(10, 20), (30,)] [(1, 2), (3,)] [1, 2, 3, 3] diff --git a/maven/python-transpiler/src/test/resources/conformance/typedcells.py b/maven/python-transpiler/src/test/resources/conformance/typedcells.py new file mode 100644 index 00000000000..55a18a0756a --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/typedcells.py @@ -0,0 +1,130 @@ +# Typed bodies over cells that closures share and rebind. + + +def counter(start: int): + n = start + + def bump(by=1): + nonlocal n + n += by + return n + + bump() + bump(5) + return n, bump + + +def late_binding(k: int): + fns = [] + for i in range(k): + fns.append(lambda: i * 10) + i = 99 + return [f() for f in fns] + + +def gen_sees_rebind(items): + total = 0 + g = (x + total for x in items) + total = 100 + return list(g) + + +def nonlocal_type_change(): + v = 1 + + def flip(): + nonlocal v + v = "now a string" + + flip() + return v + + +def unbound_then_bound(flag: bool): + def read(): + return y + + try: + read() + except NameError as e: + msg = type(e).__name__ + y = 5 + if flag: + del y + try: + read() + except NameError: + msg += "+again" + else: + msg += str(read()) + return msg + + +def recursive(n: int): + def fact(k): + return 1 if k <= 1 else k * fact(k - 1) + + return fact(n) + + +def param_cell(x: int, scale): + def mul(): + return x * scale + + x += 1 + return mul() + + +print(counter(3)[0], counter(0)[1]()) +print(late_binding(3)) +print(gen_sees_rebind([1, 2])) +print(nonlocal_type_change()) +print(unbound_then_bound(True), unbound_then_bound(False)) +print(recursive(6), param_cell(2, 3), param_cell(2, "ab")) + + +def runs(data): + out = [] + it = iter(data) + while True: + length = next(it, 128) + if length == 128: + break + # The first iterable is read now; only `it` is read later. + out.extend(next(it) for _ in range(length + 1)) + return out + + +def kept_late(xs: list): + gens = [] + for k in range(3): + gens.append(x * k for x in xs) + return [list(g) for g in gens] + + +print(runs([1, 5, 6, 0, 9, 128]), kept_late([1, 2])) + + +def rows(grid: list, values_only: bool): + for r in range(len(grid)): + cells = (grid[r][c] for c in range(len(grid[r]))) + if values_only: + yield tuple(v * 10 for v in cells) + else: + yield tuple(cells) + + +def gen_counter(k: int): + n = 0 + + def bump(): + nonlocal n + n += 1 + return n + + for _ in range(k): + yield bump() + yield n + + +print(list(rows([[1, 2], [3]], True)), list(rows([[1, 2], [3]], False)), list(gen_counter(3))) diff --git a/maven/python-transpiler/src/test/resources/conformance/typeddecorated.out b/maven/python-transpiler/src/test/resources/conformance/typeddecorated.out new file mode 100644 index 00000000000..76062f8ee06 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/typeddecorated.out @@ -0,0 +1,5 @@ +6 15 abab base 4 +1 +error negative -1 +30 base 3 derived base 2 derived Derived +<13> <6.0> HEY 6 diff --git a/maven/python-transpiler/src/test/resources/conformance/typeddecorated.py b/maven/python-transpiler/src/test/resources/conformance/typeddecorated.py new file mode 100644 index 00000000000..19453a9aaad --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/typeddecorated.py @@ -0,0 +1,77 @@ +# Decorated and rebound functions: typed bodies entered only by their door. +import functools + + +def logged(fn): + @functools.wraps(fn) + def wrapper(*a): + return "<" + str(fn(*a)) + ">" + return wrapper + + +class Base: + def __init__(self, w: int): + self._w = w + + @property + def width(self): + total = 0 + for i in range(self._w): + total += i + return total + + @width.setter + def width(self, v): + if v < 0: + raise ValueError("negative " + str(v)) + self._w = v + + @classmethod + def make(cls, n): + return cls(n * 2) + + @staticmethod + def twice(s): + return s + s + + def describe(self): + return "base " + str(self._w) + + +class Derived(Base): + @property + def width(self): + return super().width * 10 + + def describe(self): + return super().describe() + " derived" + + +@logged +def wrapped(x, y): + return x * y + 1 + + +if True: + def chosen(s): + return s.upper() +else: + def chosen(s): + return s + + +def main(): + b = Base(4) + print(b.width, Base.make(3).width, Base.twice("ab"), b.describe()) + b.width = 2 + print(b.width) + try: + b.width = -1 + except ValueError as e: + print("error", e) + d = Derived(3) + print(d.width, d.describe(), Derived.make(1).describe(), type(Derived.make(1)).__name__) + print(wrapped(3, 4), wrapped(2.5, 2), chosen("hey"), Base.twice(3)) + + +main() diff --git a/maven/python-transpiler/src/test/resources/conformance/typedfallback.out b/maven/python-transpiler/src/test/resources/conformance/typedfallback.out new file mode 100644 index 00000000000..354e8ac2041 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/typedfallback.out @@ -0,0 +1,11 @@ +box:20! True cm +sq:121! False cm +(3, ['5-1', '9-2', '3-3'], {3}) +['ab=2.', 'cde=5.', (['cde', '5'], 2), 'f=6.', (['f', '6'], 2)] +(1000000, '3/8.') +(8, '3/8.') +(True, 18, '4,5,6', (1, 3)) +(False, 0, '', ()) +(True, [1, 5], -8, -1) +(True, 8) (False, 2) +([9, 15], [-5, -4], [[3, 4], [3, 4], [3, 4]]) diff --git a/maven/python-transpiler/src/test/resources/conformance/typedfallback.py b/maven/python-transpiler/src/test/resources/conformance/typedfallback.py new file mode 100644 index 00000000000..f74176879c9 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/typedfallback.py @@ -0,0 +1,122 @@ +# Typed functions holding expressions only generic code can evaluate: the +# typed locals they read are boxed, what they answer comes back unboxed. + + +def fmt(a, b, sep="-", end="."): + return str(a) + sep + str(b) + end + + +class Box: + unit = "cm" + + def __init__(self, w: int, h: int): + self.w = w + self.h = h + + def area(self) -> int: + return self.w * self.h + + @classmethod + def square(cls, n): + return cls(n, n) + + def describe(self, prefix: str): + a = self.area() + inside = 0 < a <= 100 + label = fmt(prefix, a, sep=":", end="!") + return label + " " + str(inside) + " " + Box.unit + + +def scan(xs: list, lo: int, hi: int): + n = 0 + keep = [] + for x in xs: + if lo <= x < hi: + n += 1 + keep.append(fmt(x, n, end="")) + return n, keep, {len(keep), n} + + +def gen(words: list, k: int): + total = 0 + for w in words: + total += len(w) + yield fmt(w, total, sep="=") + if 3 < total < 2 ** k: + yield sorted([w, str(total)], key=len, reverse=True), len({w, str(total)}) + + +def star(args: list, big: int): + big = big * big * big * big + return max(*args, big // 10 ** 30), fmt(*args[:2], **{"sep": "/"}) + + +def main(): + b = Box(4, 5) + print(b.describe("box")) + print(Box.square(11).describe("sq")) + print(scan([1, 5, 9, 12, 3], 2, 10)) + print(list(gen(["ab", "cde", "f"], 4))) + print(star([3, 8, 2], 10 ** 9)) + print(star([3, 8, 2], 7)) + + +main() + + +def drained(xs: list, lim: int): + n = 0 + for x in xs: + n += 1 + # Generator expressions a consumer drains on the spot, reading locals. + return any(x > lim for x in xs), sum(x * n for x in xs), ",".join(str(x + n) for x in xs), \ + tuple(x for x in xs if x != lim) + + +print(drained([1, 2, 3], 2)) +print(drained([], 0)) + + +def lazy_any(xs: list, lim: int): + seen = [] + k = 0 + for x in xs: + k += x + # any stops at the first hit: the generator must stay lazy. + hit = any(seen.append(x) or x + k > lim for x in xs) + return hit, seen, max(x - k for x in xs), min((x for x in xs if x > lim), default=-1) + + +print(lazy_any([1, 5, 2, 9], 20)) + + +def padded_hit(rows: list, padding: int): + n = 0 + for r in rows: + n += len(r) + # Temporaries of the generic code inside the capturing lambda. + return any(r[-padding:] == "zz" for r in rows if len(r) > n // 10), n + + +print(padded_hit(["abzz", "cd", "zz"], 2), padded_hit(["ab"], 1)) + + +def kept_gens(xs: list, scale: int): + base = scale * 2 + out = [] + # Kept past the statement: base and scale never change, so the values + # captured now are the ones CPython reads later. + g = (x * base + scale for x in xs) + out.extend(x - base for x in xs) + return list(g), out, late_gens(xs) + + +def late_gens(xs: list): + late = [] + for k in range(3): + # k is rebound by the loop: this one must stay generic. + late.append(k + y for y in xs) + return [list(h) for h in late] + + +print(kept_gens([1, 2], 3)) diff --git a/maven/python-transpiler/src/test/resources/conformance/typedgen.out b/maven/python-transpiler/src/test/resources/conformance/typedgen.out new file mode 100644 index 00000000000..73034925f15 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/typedgen.out @@ -0,0 +1,19 @@ +['c', 'b', 'a', 'd'] +['b', 'c'] +[0, 3, 6, 9, 12] +[0, 2, 4, 6, ('ret', 6)] +[3, 9, 81, 6561] +[1099511627776, 1208925819614629174706176, 1461501637330902918203684832716283019655932542976, 2135987035920910082395021706169552114602704522356652769947041607822219725780640550022962086936576] +['the', 'quick', 'brown', 'fox'] +[3, 1, 9] +0 5 12 +accum 12 +[0, 1, 2, -1] ['caught at two', 'finally'] +0 1 +['finally'] +[0, 10, 20] ['enter', 'exit'] +['x', 'x'] [7, 7] [None, None] +[1, 2] +5 +early stopped +45 diff --git a/maven/python-transpiler/src/test/resources/conformance/typedgen.py b/maven/python-transpiler/src/test/resources/conformance/typedgen.py new file mode 100644 index 00000000000..08bb869dd8c --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/typedgen.py @@ -0,0 +1,165 @@ +# Generators with typed locals: values held across suspensions, flow facts +# that must not survive a back edge, send, return values, finally and with. + + +class Node: + def __init__(self, name, kids): + self.name = name + self.kids = kids + self.parent = None + + def walk(self): + yield self.name + for k in self.kids: + for n in k.walk(): + yield n + + def ancestors(self): + p = self.parent + while p is not None: + yield p.name + p = p.parent + + +def count(n: int, step: int): + i = 0 + total = 0 + while i < n: + total += i + yield i * step + i += 1 + return total + + +def big_ints(start: int): + x = start + for _ in range(4): + yield x + x = x * x + + +def words(text: str): + w = "" + for c in text: + if c == " ": + if w: + yield w + w = "" + else: + w += c + if w: + yield w + + +def maybe(xs): + last = None + for x in xs: + if last is not None: + yield last + x + last = None if x < 0 else x + + +def accum(): + total = 0 + while True: + got = yield total + if got is None: + return total + total += got + + +def guarded(log, n: int): + try: + for i in range(n): + yield i + if i == 2: + raise ValueError("at two") + except ValueError as e: + log.append("caught " + str(e)) + yield -1 + finally: + log.append("finally") + + +class Ctx: + def __init__(self, log): + self.log = log + + def __enter__(self): + self.log.append("enter") + return self + + def __exit__(self, *a): + self.log.append("exit") + return False + + +def within(log, n: int): + with Ctx(log): + for i in range(n): + yield i * 10 + + +def annotated(s: str): + # Called with an int too: the guess at the door must not hold. + yield s + yield s + + +def early(xs: list): + for x in xs: + if x == 3: + return "stopped" + yield x + + +def main(): + a = Node("a", []) + b = Node("b", [a]) + c = Node("c", [b, Node("d", [])]) + a.parent = b + b.parent = c + print(list(c.walk())) + print(list(a.ancestors())) + g = count(5, 3) + print(list(g)) + g = count(4, 2) + out = [] + while True: + try: + out.append(next(g)) + except StopIteration as e: + out.append(("ret", e.value)) + break + print(out) + print(list(big_ints(3))) + print(list(big_ints(2 ** 40))) + print(list(words(" the quick brown fox "))) + print(list(maybe([1, 2, -1, 4, 5]))) + acc = accum() + print(next(acc), acc.send(5), acc.send(7)) + try: + acc.send(None) + except StopIteration as e: + print("accum", e.value) + log = [] + print(list(guarded(log, 5)), log) + log = [] + g = guarded(log, 5) + print(next(g), next(g)) + g.close() + print(log) + log = [] + print(list(within(log, 3)), log) + print(list(annotated("x")), list(annotated(7)), list(annotated(None))) + print(list(early([1, 2, 3, 4]))) + g = early([5, 3]) + print(next(g)) + try: + next(g) + except StopIteration as e: + print("early", e.value) + print(sum(count(10, 1))) + + +main() diff --git a/maven/python-transpiler/src/test/resources/conformance/typedlambda.out b/maven/python-transpiler/src/test/resources/conformance/typedlambda.out new file mode 100644 index 00000000000..758a81dc845 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/typedlambda.out @@ -0,0 +1,4 @@ +(['a', 'bb', 'ccc'], ['bb/1', 'a/1', 'cc/1'], ['bbbb', 'aa', 'cccccc']) +(31, 3) +([3, 6], 3) +[2, 2, 2] diff --git a/maven/python-transpiler/src/test/resources/conformance/typedlambda.py b/maven/python-transpiler/src/test/resources/conformance/typedlambda.py new file mode 100644 index 00000000000..acbac962d3d --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/typedlambda.py @@ -0,0 +1,34 @@ +# Lambdas in typed functions: closures over locals that never change once +# bound capture their values; a loop variable keeps the function generic. + + +def keyed(rows: list, col: int): + width = col + 1 + by = sorted(rows, key=lambda r: (len(r) - width, r)) + f = lambda s: s[:width] + "/" + str(col) + return by, [f(r) for r in rows], list(map(lambda r: r * 2, rows)) + + +def defaults(n: int): + x = n * 10 + g = lambda y, x=x: x + y + return g(1), g(1, 2) + + +def nested_lam(xs: list, k: int): + m = k + 1 + h = lambda a: [b * m for b in a] + return h(xs), (lambda: m)() + + +def late_lambdas(n: int): + fs = [] + for i in range(n): + fs.append(lambda: i) + return [f() for f in fs] + + +print(keyed(["bb", "a", "ccc"], 1)) +print(defaults(3)) +print(nested_lam([1, 2], 2)) +print(late_lambdas(3)) diff --git a/maven/python-transpiler/src/test/resources/conformance/typedlambda2.out b/maven/python-transpiler/src/test/resources/conformance/typedlambda2.out new file mode 100644 index 00000000000..3a92e533ddd --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/typedlambda2.out @@ -0,0 +1,3 @@ +1k.!. +kk? +kerr k? diff --git a/maven/python-transpiler/src/test/resources/conformance/typedlambda2.py b/maven/python-transpiler/src/test/resources/conformance/typedlambda2.py new file mode 100644 index 00000000000..ceac67b1ed2 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/typedlambda2.py @@ -0,0 +1,27 @@ +def guard(fn): + try: + return fn() + except ValueError as e: + return "err " + str(e) + + +def invoke(f, args, info): + return f(*args) + info + + +def validate(cls: str, raw: int, hooks: list, plain, info: str): + v = raw + for d in hooks: + v = guard(lambda d=d, v=v: invoke(d, (cls, v), info)) + if plain is not None: + v = guard(lambda: invoke(plain, (cls, v), info)) + return v + + +def bad(c, v): + raise ValueError(c) + + +print(validate("k", 1, [lambda c, v: str(v) + c, lambda c, v: v + "!"], None, ".")) +print(validate("k", 2, [], lambda c, v: c * v, "?")) +print(validate("k", 3, [bad], lambda c, v: c + v, "?")) diff --git a/maven/python-transpiler/src/test/resources/conformance/typedloops2.out b/maven/python-transpiler/src/test/resources/conformance/typedloops2.out new file mode 100644 index 00000000000..6fc8124c1a1 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/typedloops2.out @@ -0,0 +1,2 @@ +([0, 6, 12, 18], 9) ([0, 2, 4], 2) +(51, 2) (6, 2) diff --git a/maven/python-transpiler/src/test/resources/conformance/typedloops2.py b/maven/python-transpiler/src/test/resources/conformance/typedloops2.py new file mode 100644 index 00000000000..7224e0b0839 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/typedloops2.py @@ -0,0 +1,22 @@ +# Loops whose source the typed body cannot see through. + + +def stepped(n: int, step): + out = [] + i = -1 + for i in range(0, n, step): + out.append(i * 2) + return out, i + + +def from_bytes(src): + total = 0 + for b in src: + total = total + b + for b in bytearray(b"\x01\x02"): + total += b + return total, b + + +print(stepped(10, 3), stepped(5, -1) if False else stepped(3, 1)) +print(from_bytes(b"\x10\x20"), from_bytes([1, 2])) diff --git a/maven/python-transpiler/src/test/resources/conformance/typednesteddef.out b/maven/python-transpiler/src/test/resources/conformance/typednesteddef.out new file mode 100644 index 00000000000..6d133c678da --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/typednesteddef.out @@ -0,0 +1,4 @@ +('TD', 'TY', 'name', '3t3', '4', 25, 25) +x<-old x ['ac', 'bd'] ac|bd +14 +([('Item', 'b0:b', 'object'), ('Item', 'b1:b', 'dict')], [2, 3, 0, 0]) diff --git a/maven/python-transpiler/src/test/resources/conformance/typednesteddef.py b/maven/python-transpiler/src/test/resources/conformance/typednesteddef.py new file mode 100644 index 00000000000..a234d457ad3 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/typednesteddef.py @@ -0,0 +1,92 @@ +# Nested functions with decorators and defaults in typed bodies. +import functools + + +def shout(fn): + @functools.wraps(fn) + def inner(*a, **k): + return str(fn(*a, **k)).upper() + + return inner + + +def build(tag: str, scale: int): + @shout + def name(x="d"): + return tag + x + + def times(v, k=scale * 2, *, sep=tag): + return sep.join([str(v)] * k) + + @functools.lru_cache(maxsize=None) + def sq(n): + return n * n + + return name(), name("y"), name.__name__, times(3), times(4, 1), sq(5), sq(5) + + +def counter_with_default(start: int): + n = start + + def bump(by=start): + nonlocal n + n += by + return n + + bump() + bump(10) + return n + + +def alias_of(old: str, new: str): + @property + def alias(self): + return getattr(self, new) + "<-" + old + + @alias.setter + def alias(self, value): + setattr(self, new, value) + + return alias + + +class Thing: + real = "r" + old = alias_of("old", "real") + + +def columns(lines: list, width: int): + return ["".join(line[i] for line in lines) for i in range(width)] + + +def columns2(lines: list, flag: bool): + if flag: + width = max(map(len, lines)) + return "|".join("".join(line[i] for line in lines) for i in range(width)) + return "" + + +print(build("t", 1)) +t = Thing() +t.old = "x" +print(t.old, t.real, columns(["ab", "cd"], 2), columns2(["ab", "cd"], True)) +print(counter_with_default(2)) + + +def make_classes(base_name: str, n: int): + out = [] + lut = bytearray(4) + pal = b"\x01\x02\x03\x04\x05" + lut[0:2] = pal[1:3] + for i in range(n): + class Item(dict if i % 2 else object): + tag = base_name + str(i) + + def show(self): + return self.tag + ":" + base_name + + out.append((Item.__name__, Item().show(), Item.__mro__[1].__name__)) + return out, list(lut) + + +print(make_classes("b", 2)) diff --git a/maven/python-transpiler/src/test/resources/conformance/typedrebound.out b/maven/python-transpiler/src/test/resources/conformance/typedrebound.out new file mode 100644 index 00000000000..c21b05cbd93 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/typedrebound.out @@ -0,0 +1,3 @@ +d2 d3 +default:utf-8:3 +mine:latin-1:4 diff --git a/maven/python-transpiler/src/test/resources/conformance/typedrebound.py b/maven/python-transpiler/src/test/resources/conformance/typedrebound.py new file mode 100644 index 00000000000..6edaa823b77 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/typedrebound.py @@ -0,0 +1,31 @@ +# Parameters a typed function rebinds to another type, not first thing. + + +class Parser: + def __init__(self, tag: str): + self.tag = tag + + +def parse(text: str, parser=None, encoding=None): + n = len(text) + if parser is None: + parser = Parser("default") + if encoding is None: + encoding = "utf-8" + return parser.tag + ":" + encoding + ":" + str(n) + + +def only_default(text: str, parser=None): + n = len(text) + if parser is None: + parser = Parser("d" + str(n)) + return parser.tag + + +def main(): + print(only_default("xy"), only_default("xyz")) + print(parse("abc")) + print(parse("abcd", Parser("mine"), "latin-1")) + + +main() diff --git a/maven/python-transpiler/src/test/resources/conformance/typedstar.out b/maven/python-transpiler/src/test/resources/conformance/typedstar.out new file mode 100644 index 00000000000..f78bec7468c --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/typedstar.out @@ -0,0 +1,5 @@ +1-2-x A +o:a,b:4 none::0 +(9, 0) (28, 2) + 1| 22|abc 004 +TypeError True diff --git a/maven/python-transpiler/src/test/resources/conformance/typedstar.py b/maven/python-transpiler/src/test/resources/conformance/typedstar.py new file mode 100644 index 00000000000..06fa8824f2d --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/typedstar.py @@ -0,0 +1,44 @@ +# *args, **kwargs and keyword-only parameters in typed bodies. + + +def joined(sep, *parts, upper=False): + out = sep.join(str(p) for p in parts) + return out.upper() if upper else out + + +def options(name, **kw): + keys = sorted(kw) + total = 0 + for k in keys: + total += len(str(kw[k])) + return name + ":" + ",".join(keys) + ":" + str(total) + + +def mixed(a, b=2, *rest, scale, **extra): + s = (a + b) * scale + for r in rest: + s += r + return s, len(extra) + + +class Fmt: + def __init__(self, width: int): + self.width = width + + def cells(self, *vals, fill=" "): + return "|".join(str(v).rjust(self.width, fill) for v in vals) + + +def main(): + print(joined("-", 1, 2, "x"), joined("+", "a", upper=True), joined(".")) + print(options("o", b=10, a="xy"), options("none")) + print(mixed(1, scale=3), mixed(1, 5, 7, 9, scale=2, z=1, y=2)) + f = Fmt(3) + print(f.cells(1, 22, "abc"), f.cells(4, fill="0")) + try: + mixed(1) + except TypeError as e: + print("TypeError", "scale" in str(e)) + + +main() diff --git a/maven/python-transpiler/src/test/resources/conformance/typedstmts.out b/maven/python-transpiler/src/test/resources/conformance/typedstmts.out new file mode 100644 index 00000000000..b7469dbce01 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/typedstmts.out @@ -0,0 +1,9 @@ +kept 1 set ['in', 'out -', 'in', 'out KeyError'] +done ['in', 1, 'out -', 'in', 'out -', 'in', 3, 'out -', 'in', 'out -'] +returned ['in', 'out -'] +3 +assert too big 3 +([('k', 2)], 'k') +(['b'], [2, 3], False) +unbound UnboundLocalError +2 5 5 diff --git a/maven/python-transpiler/src/test/resources/conformance/typedstmts.py b/maven/python-transpiler/src/test/resources/conformance/typedstmts.py new file mode 100644 index 00000000000..93910893faf --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/typedstmts.py @@ -0,0 +1,108 @@ +# Statements typed functions now lower themselves: assert, annotated +# assignment, global, local imports, del and with. + +counter = 0 + + +class Quiet: + def __init__(self, log: list, swallow: bool): + self.log = log + self.swallow = swallow + + def __enter__(self): + self.log.append("in") + return len(self.log) + + def __exit__(self, t, v, tb): + self.log.append("out " + (t.__name__ if t is not None else "-")) + return self.swallow + + +def bump(n: int): + global counter + counter += n + return counter + + +def guarded(log: list, x: int): + name = None + with Quiet(log, True) as k: + name = "set" + if x > 2: + raise KeyError(x) + name = "kept " + str(k) + # The exit swallowed the KeyError: name may still be "set". + return name if name is not None else "none" + + +def through(log: list, xs: list): + for x in xs: + with Quiet(log, False): + if x == 2: + continue + if x == 4: + break + if x == 5: + return "returned" + log.append(x) + return "done" + + +def asserted(n: int): + total: int = 0 + for i in range(n): + assert i < 3, "too big " + str(i) + total += i + return total + + +def imports(s: str): + import math + import os.path + from collections import OrderedDict as OD + d = OD() + d[s] = math.floor(2.5) + return list(d.items()), os.path.basename("/a/b/" + s) + + +def deleting(d: dict, keys: list): + tmp = [1, 2, 3] + for k in keys: + del d[k] + del tmp[0] + obj = Quiet([], False) + del obj.swallow + gone = hasattr(obj, "swallow") + x = d + del x + return sorted(d), tmp, gone + + +def unbound_after_del(d: dict): + x = d + del x + try: + print(x) + except NameError as e: + print("unbound", type(e).__name__) + + +def main(): + log = [] + print(guarded(log, 1), guarded(log, 3), log) + log = [] + print(through(log, [1, 2, 3, 4]), log) + log = [] + print(through(log, [5]), log) + print(asserted(3)) + try: + asserted(5) + except AssertionError as e: + print("assert", e) + print(imports("k")) + print(deleting({"a": 1, "b": 2, "c": 3}, ["a", "c"])) + unbound_after_del({}) + print(bump(2), bump(3), counter) + + +main() diff --git a/maven/python-transpiler/src/test/resources/conformance/typedsubaug.out b/maven/python-transpiler/src/test/resources/conformance/typedsubaug.out new file mode 100644 index 00000000000..dced967ea59 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/typedsubaug.out @@ -0,0 +1,4 @@ +[8, 'a', 4] [0, 7, 22] +1 +{'k': [1, 2, 2]} True +{'k': 'stt'} diff --git a/maven/python-transpiler/src/test/resources/conformance/typedsubaug.py b/maven/python-transpiler/src/test/resources/conformance/typedsubaug.py new file mode 100644 index 00000000000..10ebce3f162 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/typedsubaug.py @@ -0,0 +1,38 @@ +# Slice stores and augmented subscripts on containers of unknown type. + + +class Box: + def __init__(self): + self.d = {} + + def __getitem__(self, k): + return self.d.get(k, 0) + + def __setitem__(self, k, v): + self.d[k] = v + + +def fill(target, src, k): + n = 0 + for i in range(3): + n += i + target[1:3] = src + target[k] += n + target[k] *= 2 + return target + + +def grow(d, k, items): + for i in range(2): + d[k] += items + return d + + +b = Box() +b[0] = 1 +print(fill([1, 2, 3, 4], ["a"], 0), fill([0, 0, 0], (7, 8), 2)) +print(sorted(fill(b, None, "x").d.items(), key=str) if False else b[0]) +shared = [1] +d = {"k": shared} +print(grow(d, "k", [2]), shared is d["k"]) +print(grow({"k": "s"}, "k", "t")) diff --git a/maven/python-transpiler/src/test/resources/conformance/typedunbound.out b/maven/python-transpiler/src/test/resources/conformance/typedunbound.out new file mode 100644 index 00000000000..80a3c39f306 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/typedunbound.out @@ -0,0 +1,26 @@ +found b missing: cannot access local variable 'found' where it is not associated with a value +h|ey empty +['p', 'p', 'q'] +UnboundLocalError cannot access local variable 'last' where it is not associated with a value +(0.0, 1.5) [] +(-2.0, 5.0) [1, 2.0] +(0.0, 1.5) [1, 2.0] +-1 +3 +ValueError bad no +UnboundLocalError cannot access local variable 'flag' where it is not associated with a value +2 6 +0 +UnboundLocalError cannot access local variable 'i' where it is not associated with a value +UnboundLocalError cannot access local variable 's' where it is not associated with a value +ValueError value first +True +UnboundLocalError cannot access local variable 'rv' where it is not associated with a value +UnboundLocalError cannot access local variable 'rv' where it is not associated with a value +4 -1 False True +([6, 4, 2], [{'h': [1, 3, 2]}]) +UnboundLocalError cannot access local variable 'data' where it is not associated with a value +UnboundLocalError cannot access local variable 'data' where it is not associated with a value +(['d1'], 1) +([], 0) +UnboundLocalError cannot access local variable 'data' where it is not associated with a value diff --git a/maven/python-transpiler/src/test/resources/conformance/typedunbound.py b/maven/python-transpiler/src/test/resources/conformance/typedunbound.py new file mode 100644 index 00000000000..a85af875e9e --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/typedunbound.py @@ -0,0 +1,187 @@ +# Locals not every path binds, read in typed functions: checked at the read. + + +def pick(xs: list, want: str): + for x in xs: + if x == want: + found = x + break + try: + return "found " + found + except UnboundLocalError as e: + return "missing: " + str(e) + + +def parts(s: str): + if s: + head = s[0] + rest = s[1:] + n = len(s) + if n: + return head + "|" + rest + return "empty" + + +def loop_carried(rows: list): + out = [] + for r in rows: + if r is not None: + last = r + out.append(last) + return out + + +print(pick(["a", "b"], "b"), pick(["a"], "z")) +print(parts("hey"), parts("")) +print(loop_carried(["p", None, "q"])) +try: + loop_carried([None]) +except UnboundLocalError as e: + print(type(e).__name__, e) + + +calls = [] + + +def noisy(v): + calls.append(v) + return v + + +def branchy(p: bool, a, b, c): + n = 0 + for x in range(1, 3): + n += x + # The untaken branch, generic arithmetic over unknown values, must not run. + r = 0.0 if p else noisy(a) - b * c + n + s = noisy(b) * c - a if not p else 1.5 + return r, s + + +print(branchy(True, 1.0, 2.0, 3.0), calls) +print(branchy(False, 1, 2.0, "3" and 3), calls) +print(branchy(True, "a", [1], None), calls) + + +def fail(msg): + raise ValueError(msg) + + +def standalone(sa): + if sa is None: + flag = -1 + elif sa == "yes": + flag = 1 + elif sa == "maybe": + pass + else: + fail("bad " + sa) + total = flag * 2 + 1 + return total + + +for arg in (None, "yes", "no", "maybe"): + try: + print(standalone(arg)) + except (ValueError, UnboundLocalError) as e: + print(type(e).__name__, e) + + +def width(rows: list, headers: list) -> int: + n = len(rows[0]) if rows else len(headers) + return n + (rows[0][0] if rows else 0) + + +print(width([], ["a", "b"]), width([[3, 4, 5]], [])) + + +def boom(): + raise ValueError("value first") + + +def short(words: list, limit: int) -> str: + total = 0 + for i, w in enumerate(words): + total += len(w) + if total > limit: + return " ".join(words[: i + 1]) + while i > 0: + i -= 1 + return str(i) + + +def acc_unbound(xs: list): + for x in xs: + s = "" + s += x + s += boom() + return s + + +def confirmish(answer: str, abort: bool) -> bool: + if answer == "y": + rv = True + elif answer == "n": + rv = False + if abort and not rv: + return False + return rv + + +for call in (lambda: short(["ab", "cd"], 10), lambda: short([], 3), lambda: acc_unbound([]), + lambda: acc_unbound(["a"]), lambda: confirmish("y", True), lambda: confirmish("x", False), + lambda: confirmish("x", True)): + try: + print(call()) + except (ValueError, UnboundLocalError) as e: + print(type(e).__name__, e) + + +def ratio(a: int, b: int) -> int: + return a // b + 1 if b else -1 + + +def ratio2(a: float, b: float, ok: bool) -> bool: + return ok and a / b > 1.0 + + +print(ratio(7, 2), ratio(7, 0), ratio2(3.0, 0.0, False), ratio2(3.0, 2.0, True)) + + +class Swallow: + def __enter__(self): + return self + + def __exit__(self, *a): + return True + + +def headers(src: dict, fail: bool, scale: list): + with Swallow(): + if fail: + raise KeyError("x") + data = src + out = sorted((h * 2 for h in data["h"]), key=lambda x: -x) + return out, [data for s in scale] + + +for args in (({"h": [1, 3, 2]}, False, [1]), ({"h": [1]}, True, []), ({"h": [1]}, True, [1])): + try: + print(headers(*args)) + except UnboundLocalError as e: + print(type(e).__name__, e) + + +def elt_only(fail: bool, scale: list): + with Swallow(): + if fail: + raise KeyError("x") + data = "d" + return [data + str(s) for s in scale], sum(len(data) for s in scale) + + +for args in ((False, [1]), (True, []), (True, [2])): + try: + print(elt_only(*args)) + except UnboundLocalError as e: + print(type(e).__name__, e) diff --git a/maven/python-transpiler/src/test/resources/conformance/typedwalrus.out b/maven/python-transpiler/src/test/resources/conformance/typedwalrus.out new file mode 100644 index 00000000000..589962d8dd4 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/typedwalrus.out @@ -0,0 +1,4 @@ +(['hello', 'go'], False) +(['abc', 'def', 'g'], '') +(7, 2, [1, 2, 3]) +([1, 2, 3], 3) diff --git a/maven/python-transpiler/src/test/resources/conformance/typedwalrus.py b/maven/python-transpiler/src/test/resources/conformance/typedwalrus.py new file mode 100644 index 00000000000..5a008a5923b --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/typedwalrus.py @@ -0,0 +1,45 @@ +# Assignment expressions in typed bodies. +import re + + +def first_word(lines: list): + out = [] + for line in lines: + if (m := re.match(r"(\w+)", line)) and m.group(1) != "skip": + out.append(m.group(1)) + return out, m is None + + +def chunks(data: str, size: int): + pos = 0 + res = [] + while (piece := data[pos:pos + size]): + res.append(piece) + pos += size + return res, piece + + +def side_order(xs): + log = [] + + def f(v): + log.append(v) + return v + + total = f(1) + (y := f(2)) * f(3) + return total, y, log + + +def cell_walrus(seq): + def peek(): + return last + + last = None + found = [peek() for _ in seq if (last := _) or True] + return found, peek() + + +print(first_word(["hello world", "skip me", " ", "go"])) +print(chunks("abcdefg", 3)) +print(side_order(None)) +print(cell_walrus([1, 2, 3])) diff --git a/maven/python-transpiler/src/test/resources/conformance/typing_cast.out b/maven/python-transpiler/src/test/resources/conformance/typing_cast.out new file mode 100644 index 00000000000..ae424c5acec --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/typing_cast.out @@ -0,0 +1,2 @@ +True False 3 xx None [1] +6 diff --git a/maven/python-transpiler/src/test/resources/conformance/typing_cast.py b/maven/python-transpiler/src/test/resources/conformance/typing_cast.py new file mode 100644 index 00000000000..ac1891b9a09 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/typing_cast.py @@ -0,0 +1,30 @@ +# typing.cast answers its value, typed as the value is. +import typing +from typing import List, cast + + +class Rule: + def __init__(self, s): + self.s = s + + +class Strainer: + def __init__(self, names): + self.rules = cast(List[Rule], [Rule(n) for n in names]) + self.count = cast(int, len(names)) + self.label = typing.cast("str", "x" * self.count) + + def match(self, s): + for r in self.rules: + if r.s == s: + return True + return False + + +def side(v): + return cast(object, v) + + +st = Strainer(["a", "b"]) +print(st.match("b"), st.match("z"), st.count + 1, st.label, side(None), side([1])) +print(cast(str, 5) + 1) diff --git a/maven/python-transpiler/src/test/resources/conformance/typing_cast_class.out b/maven/python-transpiler/src/test/resources/conformance/typing_cast_class.out new file mode 100644 index 00000000000..b38a3c8f278 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/typing_cast_class.out @@ -0,0 +1,2 @@ +(9, 'set', 'Square') none +5 diff --git a/maven/python-transpiler/src/test/resources/conformance/typing_cast_class.py b/maven/python-transpiler/src/test/resources/conformance/typing_cast_class.py new file mode 100644 index 00000000000..5ee49412509 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/typing_cast_class.py @@ -0,0 +1,32 @@ +# typing.cast(T, v) to a compiled class: v typed as T, checked. +from typing import cast + + +class Shape: + def __init__(self, n): + self.n = n + self.kind = "plain" + + def area(self): + return self.n * self.n + + +class Square(Shape): + pass + + +def make(k): + return Square(k) if k else None + + +def build(k): + s = cast(Shape, make(k)) + if s is None: + return "none" + s.kind = "set" + return (s.area(), s.kind, type(s).__name__) + + +print(build(3), build(0)) +items = [cast(Shape, Square(i)) for i in range(3)] +print(sum(x.area() for x in items)) diff --git a/maven/python-transpiler/src/test/resources/conformance/unbound_class_call.out b/maven/python-transpiler/src/test/resources/conformance/unbound_class_call.out new file mode 100644 index 00000000000..a6b47338a5f --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/unbound_class_call.out @@ -0,0 +1,3 @@ +8 +True 3 +6 6 diff --git a/maven/python-transpiler/src/test/resources/conformance/unbound_class_call.py b/maven/python-transpiler/src/test/resources/conformance/unbound_class_call.py new file mode 100644 index 00000000000..f7eb683c4bd --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/unbound_class_call.py @@ -0,0 +1,63 @@ +class Text: + def get_text(self): + return "t" + + +class Item: + def __init__(self, w): + self.w = w + + +class Char(Item, Text): + def __init__(self, w, text): + Item.__init__(self, w) + Text.__init__(self) + self.text = text + + +c = Char(3, "x") + + +class Text3: + pass + + +class Char3(Item, Text3): + def __init__(self, w): + Item.__init__(self, w) + Text3.__init__(self, w * 2) + + +setattr(Text3, "__init__", lambda self, v: setattr(self, "t3", v)) +print(Char3(4).t3) + + +class Plain: + def __init__(self, v): + self.v = v + + +def same_init(k): + init = getattr(k, "__init__", None) + return init is Plain.__init__ + + +print(same_init(Plain), Plain(3).v) + + +class Text4: + pass + + +class Char4(Item, Text4): + def __init__(self, w): + Item.__init__(self, w) + Text4.__init__(self, w + 1) + + +def _name(*parts): + return "".join(parts) + + +setattr(Text4, _name("__in", "it__"), lambda self, v: setattr(self, "t4", v)) +print(Char4(5).t4, Char4(6).w) diff --git a/maven/python-transpiler/src/test/resources/conformance/unittest_.strict b/maven/python-transpiler/src/test/resources/conformance/unittest_.strict new file mode 100644 index 00000000000..409e2493b81 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/unittest_.strict @@ -0,0 +1,8 @@ +main:194 getattr with a computed name is reflection; write override = main.message in cn1-python.properties and its compliant body in cn1-python-overrides/main.message.py +unittest:1109 getattr with a computed name is reflection; write override = unittest._WritelnDecorator.__getattr__ in cn1-python.properties and its compliant body in cn1-python-overrides/unittest._WritelnDecorator.__getattr__.py +unittest:265 getattr with a computed name is reflection; write override = unittest.TestCase.__init__ in cn1-python.properties and its compliant body in cn1-python-overrides/unittest.TestCase.__init__.py +unittest:341 getattr with a computed name is reflection; write override = unittest.TestCase.run in cn1-python.properties and its compliant body in cn1-python-overrides/unittest.TestCase.run.py +unittest:927 getattr with a computed name is reflection; write override = unittest.TestLoader.loadTestsFromModule in cn1-python.properties and its compliant body in cn1-python-overrides/unittest.TestLoader.loadTestsFromModule.py +unittest:941 getattr with a computed name is reflection; write override = unittest.TestLoader.loadTestsFromName in cn1-python.properties and its compliant body in cn1-python-overrides/unittest.TestLoader.loadTestsFromName.py +unittest:952 getattr with a computed name is reflection; write override = unittest.TestLoader.loadTestsFromName in cn1-python.properties and its compliant body in cn1-python-overrides/unittest.TestLoader.loadTestsFromName.py +unittest:966 getattr with a computed name is reflection; write override = unittest.TestLoader.getTestCaseNames in cn1-python.properties and its compliant body in cn1-python-overrides/unittest.TestLoader.getTestCaseNames.py diff --git a/maven/python-transpiler/src/test/resources/conformance/unittest_mock_.strict b/maven/python-transpiler/src/test/resources/conformance/unittest_mock_.strict new file mode 100644 index 00000000000..f73504242f1 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/unittest_mock_.strict @@ -0,0 +1,22 @@ +unittest.mock:139 class NonCallableMock has no layout: its body binds __setattr__ +unittest.mock:158 setattr with a computed name is reflection; write override = unittest.mock.NonCallableMock.__init__ in cn1-python.properties and its compliant body in cn1-python-overrides/unittest.mock.NonCallableMock.__init__.py +unittest.mock:206 hasattr with a computed name is reflection; write override = unittest.mock.NonCallableMock.__getattr__ in cn1-python.properties and its compliant body in cn1-python-overrides/unittest.mock.NonCallableMock.__getattr__.py +unittest.mock:245 getattr with a computed name is reflection; write override = unittest.mock.NonCallableMock.configure_mock in cn1-python.properties and its compliant body in cn1-python-overrides/unittest.mock.NonCallableMock.configure_mock.py +unittest.mock:246 setattr with a computed name is reflection; write override = unittest.mock.NonCallableMock.configure_mock in cn1-python.properties and its compliant body in cn1-python-overrides/unittest.mock.NonCallableMock.configure_mock.py +unittest.mock:393 class Mock has no layout: base NonCallableMock has no layout +unittest.mock:404 class MagicMock has no layout: base Mock has no layout +unittest.mock:486 getattr with a computed name is reflection; write override = unittest.mock._resolve in cn1-python.properties and its compliant body in cn1-python-overrides/unittest.mock._resolve.py +unittest.mock:507 hasattr with a computed name is reflection; write override = unittest.mock._Patch.__enter__ in cn1-python.properties and its compliant body in cn1-python-overrides/unittest.mock._Patch.__enter__.py +unittest.mock:510 getattr with a computed name is reflection; write override = unittest.mock._Patch.__enter__ in cn1-python.properties and its compliant body in cn1-python-overrides/unittest.mock._Patch.__enter__.py +unittest.mock:515 setattr with a computed name is reflection; write override = unittest.mock._Patch.__enter__ in cn1-python.properties and its compliant body in cn1-python-overrides/unittest.mock._Patch.__enter__.py +unittest.mock:522 setattr with a computed name is reflection; write override = unittest.mock._Patch.__exit__ in cn1-python.properties and its compliant body in cn1-python-overrides/unittest.mock._Patch.__exit__.py +unittest.mock:524 delattr with a computed name is reflection; write override = unittest.mock._Patch.__exit__ in cn1-python.properties and its compliant body in cn1-python-overrides/unittest.mock._Patch.__exit__.py +unittest.mock:527 delattr with a computed name is reflection; write override = unittest.mock._Patch.__exit__ in cn1-python.properties and its compliant body in cn1-python-overrides/unittest.mock._Patch.__exit__.py +unittest.mock:529 setattr with a computed name is reflection; write override = unittest.mock._Patch.__exit__ in cn1-python.properties and its compliant body in cn1-python-overrides/unittest.mock._Patch.__exit__.py +unittest.mock:530 getattr with a computed name is reflection; write override = unittest.mock._Patch.__exit__ in cn1-python.properties and its compliant body in cn1-python-overrides/unittest.mock._Patch.__exit__.py +unittest.mock:531 setattr with a computed name is reflection; write override = unittest.mock._Patch.__exit__ in cn1-python.properties and its compliant body in cn1-python-overrides/unittest.mock._Patch.__exit__.py +unittest.mock:543 getattr with a computed name is reflection; write override = unittest.mock._Patch.__call__ in cn1-python.properties and its compliant body in cn1-python-overrides/unittest.mock._Patch.__call__.py +unittest.mock:545 setattr with a computed name is reflection; write override = unittest.mock._Patch.__call__ in cn1-python.properties and its compliant body in cn1-python-overrides/unittest.mock._Patch.__call__.py +unittest:265 getattr with a computed name is reflection; write override = unittest.TestCase.__init__ in cn1-python.properties and its compliant body in cn1-python-overrides/unittest.TestCase.__init__.py +unittest:341 getattr with a computed name is reflection; write override = unittest.TestCase.run in cn1-python.properties and its compliant body in cn1-python-overrides/unittest.TestCase.run.py +unittest:966 getattr with a computed name is reflection; write override = unittest.TestLoader.getTestCaseNames in cn1-python.properties and its compliant body in cn1-python-overrides/unittest.TestLoader.getTestCaseNames.py diff --git a/maven/python-transpiler/src/test/resources/conformance/weakref_.strict b/maven/python-transpiler/src/test/resources/conformance/weakref_.strict new file mode 100644 index 00000000000..6598e94640f --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/weakref_.strict @@ -0,0 +1,5 @@ +weakref:29 class ProxyType has no layout: its body binds __setattr__ +weakref:42 getattr with a computed name is reflection; write override = weakref.ProxyType.__getattr__ in cn1-python.properties and its compliant body in cn1-python-overrides/weakref.ProxyType.__getattr__.py +weakref:45 setattr with a computed name is reflection; write override = weakref.ProxyType.__setattr__ in cn1-python.properties and its compliant body in cn1-python-overrides/weakref.ProxyType.__setattr__.py +weakref:48 delattr with a computed name is reflection; write override = weakref.ProxyType.__delattr__ in cn1-python.properties and its compliant body in cn1-python-overrides/weakref.ProxyType.__delattr__.py +weakref:88 class CallableProxyType has no layout: base ProxyType has no layout diff --git a/maven/python-transpiler/src/test/resources/conformance/xdefault_.out b/maven/python-transpiler/src/test/resources/conformance/xdefault_.out new file mode 100644 index 00000000000..fc0a60a39b9 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/xdefault_.out @@ -0,0 +1,9 @@ +b none=True type=bool True True False +b2 none=False type=int False True +c none=False type=int False True x +c2 none=True type=int True +t none=False type=str True False +u none=False type=NoneType d none=False type=float +False False +tree:1 plain:2 -5 2 tree:3 plain:4 +urn:rel o None True diff --git a/maven/python-transpiler/src/test/resources/conformance/xdefault_/base.py b/maven/python-transpiler/src/test/resources/conformance/xdefault_/base.py new file mode 100644 index 00000000000..52b1ee23356 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/xdefault_/base.py @@ -0,0 +1,28 @@ +ROOT = "urn:" +NS = ROOT + "rel" + + +class Descriptor: + allow_none = False + namespace = None + + def __init__(self, name=None, **kw): + self.name = name + for k, v in kw.items(): + setattr(self, k, v) + + def check(self, value): + if value is None: + return self.allow_none + return isinstance(value, self.expected_type) + + def show(self): + return "%s none=%s type=%s" % (self.name, self.allow_none, self.expected_type.__name__) + + +class Typed(Descriptor): + expected_type = type(None) + + +def make(name, **kw): + return Typed(name, **kw) diff --git a/maven/python-transpiler/src/test/resources/conformance/xdefault_/main.py b/maven/python-transpiler/src/test/resources/conformance/xdefault_/main.py new file mode 100644 index 00000000000..218e4c45cc5 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/xdefault_/main.py @@ -0,0 +1,57 @@ +from base import Descriptor, Typed, make, NS + + +class Bool(Typed): + """Rebinds base fields as class-body defaults, in another module.""" + expected_type = bool + allow_none = True + + +class Count(Typed): + expected_type = int + pattern = "x" + + +b = Bool("b") +print(b.show(), b.check(None), b.check(True), b.check(3)) +b2 = Bool("b2", allow_none=False, expected_type=int) +print(b2.show(), b2.check(None), b2.check(3)) +c = Count("c") +print(c.show(), c.check(None), c.check(4), c.pattern) +c2 = Count("c2", allow_none=True) +print(c2.show(), c2.check(None)) +t = make("t", expected_type=str) +print(t.show(), t.check("s"), t.check(None)) +print(Typed("u").show(), Descriptor("d", expected_type=float).show()) +Bool.allow_none = False +print(b.check(None), b2.allow_none) + + +class Nested(Typed): + min = -5 + + def to_tree(self, v): + return "tree:%s" % v + + def emit(self, v): + return self.to_tree(v) + + +def plain(v): + return "plain:%s" % v + + +n = Nested("n") +n2 = Nested("n2", to_tree=plain, min=2) +print(n.emit(1), n2.emit(2), n.min, n2.min, n.to_tree(3), n2.to_tree(4)) + + +class Rel(Typed): + """Binds a base field to a constant global imported from another module.""" + expected_type = str + namespace = NS + + +r = Rel("r") +r2 = Rel("r2", namespace="o") +print(r.namespace, r2.namespace, Typed("v").namespace, r.check("s")) diff --git a/maven/python-transpiler/src/test/resources/conformance/xmixin_.out b/maven/python-transpiler/src/test/resources/conformance/xmixin_.out new file mode 100644 index 00000000000..83b085dd977 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/xmixin_.out @@ -0,0 +1,6 @@ +['a', 'b', '/b', 'thtml'] +['A', 'B', '/B', 'THTML'] a 4 0 0 +True True ['TagParser', 'Parser', 'Detects', 'object'] +True False True +[] None 0 +5 ['_first', 'count', 'data', 'pos', 'tags', 'upper'] diff --git a/maven/python-transpiler/src/test/resources/conformance/xmixin_/base.py b/maven/python-transpiler/src/test/resources/conformance/xmixin_/base.py new file mode 100644 index 00000000000..5420e70a1a9 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/xmixin_/base.py @@ -0,0 +1,19 @@ +class Parser: + def __init__(self, data): + self.data = data + self.pos = 0 + self.tags = [] + + def feed(self): + while self.pos < len(self.data): + c = self.data[self.pos] + if c == "<": + end = self.data.index(">", self.pos) + self.handle_tag(self.data[self.pos + 1:end]) + self.pos = end + 1 + else: + self.pos += 1 + return self.tags + + def handle_tag(self, name): + self.tags.append(name) diff --git a/maven/python-transpiler/src/test/resources/conformance/xmixin_/detect.py b/maven/python-transpiler/src/test/resources/conformance/xmixin_/detect.py new file mode 100644 index 00000000000..59b69cecfd0 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/xmixin_/detect.py @@ -0,0 +1,23 @@ +import re + + +class Detects(object): + """Stores on self only, like bs4's DetectsXMLParsedAsHTML.""" + + PREFIX: str = "x") +print(p.feed()) +print(p.upper, p._first, p.count, Detects.count, TagParser.count) +print(isinstance(p, Parser), isinstance(p, Detects), [k.__name__ for k in TagParser.__mro__]) +print(TagParser.looks_like(""), p.looks_like("")) +q = TagParser("") +print(q.feed(), q._first, q.count) +q.extra = 5 +print(q.extra, sorted(k for k in vars(p) if not k.startswith("__"))) diff --git a/maven/python-transpiler/src/test/resources/conformance/xmodsub_.out b/maven/python-transpiler/src/test/resources/conformance/xmodsub_.out new file mode 100644 index 00000000000..00a3bd25e3a --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/xmodsub_.out @@ -0,0 +1,11 @@ + 3 3 div 2 +14 4 html +['', ''] + 11 True True +odd o 0 1 +None s +root html 3 div +['builder', 'count', 'current', 'extra', 'name', 'parent'] 5 +False gone +['document', 'fragment:document', 'leaf', 'element'] [10, 10, 1, 1] +27 diff --git a/maven/python-transpiler/src/test/resources/conformance/xmodsub_/base.py b/maven/python-transpiler/src/test/resources/conformance/xmodsub_/base.py new file mode 100644 index 00000000000..cf969bf9580 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/xmodsub_/base.py @@ -0,0 +1,38 @@ +class Element: + def __init__(self, name): + self.name = name + self.parent = None + self.children = [] + + def label(self): + return "<" + self.kind() + " " + self.name + ">" + + def kind(self): + return "element" + + def add(self, child): + child.parent = self + self.children.append(child) + return child + + def depth(self): + d = 0 + p = self.parent + while p is not None: + d += 1 + p = p.parent + return d + + def total(self): + n = self.weight() + for c in self.children: + n += c.total() + return n + + def weight(self): + return 1 + + +class Leaf(Element): + def kind(self): + return "leaf" diff --git a/maven/python-transpiler/src/test/resources/conformance/xmodsub_/main.py b/maven/python-transpiler/src/test/resources/conformance/xmodsub_/main.py new file mode 100644 index 00000000000..396ff5a57aa --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/xmodsub_/main.py @@ -0,0 +1,75 @@ +from base import Element, Leaf +import base + + +class Document(Element): + """A subclass in another module: its own fields, overrides called from + the base module's compiled methods, super() and the inherited fields.""" + + def __init__(self, name, builder): + super().__init__(name) + self.builder = builder + self.stack = [self] + self.current = self + self.count = 0 + + def kind(self): + return "document" + + def weight(self): + return 10 + + def push(self, name): + e = self.current.add(Element(name)) + self.stack.append(e) + self.current = e + self.count += 1 + return e + + def pop(self): + self.stack.pop() + self.current = self.stack[-1] + + +class Fragment(Document): + def kind(self): + return "fragment:" + super().kind() + + +class Odd(base.Element): + @property + def label(self): + return "odd " + self.name + + +class Shadow(Leaf): + kind = None + + +d = Document("root", "html") +d.push("body") +d.push("p") +d.current.add(Leaf("text")) +d.pop() +d.push("div") +print(d.label(), d.count, len(d.stack), d.current.name, d.current.depth()) +print(d.total(), d.children[0].total(), d.builder) +print([c.label() for c in d.children[0].children]) +f = Fragment("frag", "xml") +f.push("x") +print(f.label(), f.total(), f.current.label(), isinstance(f, Element), isinstance(f, Document)) +o = Odd("o") +print(o.label, o.depth(), o.total()) +s = Shadow("s") +print(s.kind, s.name) +state = dict(d.__dict__) +g = Document.__new__(Document) +g.__dict__ = state +print(g.name, g.builder, g.count, g.current.name, g.label()) +g.extra = 5 +print(sorted(k for k in vars(g) if k != "children" and k != "stack"), g.extra) +del g.builder +print(hasattr(g, "builder"), getattr(g, "builder", "gone")) +items = [d, f, Leaf("l"), Element("e")] +print([x.kind() for x in items], [x.weight() for x in items]) +print(sum(x.total() for x in items)) diff --git a/maven/python-transpiler/src/test/resources/conformance/xmodtyped_.out b/maven/python-transpiler/src/test/resources/conformance/xmodtyped_.out new file mode 100644 index 00000000000..a1c96e646f8 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/xmodtyped_.out @@ -0,0 +1,12 @@ +[True, False, True, False] +[True, False, True, False] +True False True +['p', 'div', 'svg:p', 'skip:q'] ['a', 'ns:b'] +3 9 10 +empty empty +full full +yes yes no +True False False +True True +42 42 +['x', 'y'] ['x', 'y'] 0 diff --git a/maven/python-transpiler/src/test/resources/conformance/xmodtyped_/attrs.py b/maven/python-transpiler/src/test/resources/conformance/xmodtyped_/attrs.py new file mode 100644 index 00000000000..3a8a71167c6 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/xmodtyped_/attrs.py @@ -0,0 +1,15 @@ +"""A module that takes an instance's dict with vars(o): not its own +namespace, so its globals stay stable.""" + + +class Point: + def __init__(self, x, y): + self.x = x + self.y = y + + +def fields(p): + return sorted(vars(p)) + + +ORIGIN = Point(0, 0) diff --git a/maven/python-transpiler/src/test/resources/conformance/xmodtyped_/elements.py b/maven/python-transpiler/src/test/resources/conformance/xmodtyped_/elements.py new file mode 100644 index 00000000000..2701c2f37db --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/xmodtyped_/elements.py @@ -0,0 +1,64 @@ +"""Classes other modules walk, in the shape of bs4.element: a module +`__getattr__` that looks a deprecated name up in `globals()`, which reads +the namespace but binds nothing in it, so every class here stays a class +another module can name.""" + +_deprecated_names = {"OldTag": "Tag"} + + +def __getattr__(name): + if name in _deprecated_names: + return globals()[_deprecated_names[name]] + if name in globals(): + return None + raise AttributeError(name) + + +class Node: + def __init__(self, name): + self.name = name + self.prefix = None + self.size = 0 + + def label(self): + return self.name + + +class Tag(Node): + def __init__(self, name, prefix=None): + Node.__init__(self, name) + self.prefix = prefix + self.children = [] + + def __bool__(self): + return True + + def append(self, child): + self.children.append(child) + self.size += 1 + return child + + +class Bag: + def __init__(self): + self.items = [] + + def __len__(self): + return len(self.items) + + +def truthy(n: Node): + # A subclass another module declares answers its own truth. + return "yes" if n else "no" + + +def same(a: Node, b: Node): + # A subclass another module declares compares itself. + return a == b + + +def total(tags): + n = 0 + for t in tags: + n += t.size + return n diff --git a/maven/python-transpiler/src/test/resources/conformance/xmodtyped_/filters.py b/maven/python-transpiler/src/test/resources/conformance/xmodtyped_/filters.py new file mode 100644 index 00000000000..914c813bf89 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/xmodtyped_/filters.py @@ -0,0 +1,35 @@ +"""Code that walks another module's instances, in the shape of bs4.filter: +annotated parameters of a class `elements` compiles, fields read off +them, a method called through a value as well as directly.""" +from elements import Tag, Bag + + +class Strainer: + def __init__(self, name): + self.name = name + + def matches(self, tag: Tag) -> bool: + if not tag.prefix and tag.name != self.name: + return False + return tag.prefix != "skip" + + +def names(tags): + out = [] + for t in tags: + out.append(t.name if t.prefix is None else t.prefix + ":" + t.name) + return out + + +def fill(tag: Tag, n): + for i in range(n): + tag.append(Tag("c" + str(i))) + return tag.size + + +def count(bag: Bag): + return "full" if bag else "empty" + + +def check(fn, x): + return fn(x) diff --git a/maven/python-transpiler/src/test/resources/conformance/xmodtyped_/late.py b/maven/python-transpiler/src/test/resources/conformance/xmodtyped_/late.py new file mode 100644 index 00000000000..bcfcc241296 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/xmodtyped_/late.py @@ -0,0 +1,10 @@ +"""A module that writes its own namespace: its globals stay unstable.""" +value = 1 + + +def setup(): + globals()["value"] = 42 + + +def read(): + return value diff --git a/maven/python-transpiler/src/test/resources/conformance/xmodtyped_/main.py b/maven/python-transpiler/src/test/resources/conformance/xmodtyped_/main.py new file mode 100644 index 00000000000..f975f710f2f --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/xmodtyped_/main.py @@ -0,0 +1,50 @@ +import elements +import late +from attrs import ORIGIN, Point, fields +from elements import Node, Tag, Bag, truthy, same, total +from filters import Strainer, names, fill, count, check + + +class Empty(Node): + def __len__(self): + return 0 + + +class Keyed(Node): + def __eq__(self, other): + return isinstance(other, Node) and other.name == self.name + + __hash__ = Node.__hash__ + + +class Duck: + """No Tag: what the guards send to the generic versions.""" + + def __init__(self, name, prefix=None): + self.name = name + self.prefix = prefix + self.size = 7 + + def append(self, child): + self.size += 1 + return child + + +s = Strainer("p") +tags = [Tag("p"), Tag("div"), Tag("p", "svg"), Tag("q", "skip")] +print([s.matches(t) for t in tags]) +print([check(s.matches, t) for t in tags]) +print(s.matches(Duck("p")), check(s.matches, Duck("q")), s.matches(Duck("x", "svg"))) +print(names(tags), names([Duck("a"), Duck("b", "ns")])) +root = Tag("root") +print(fill(root, 3), fill(Duck("d"), 2), total([root, Tag("e"), Duck("f")])) +b = Bag() +print(count(b), check(count, b)) +b.items.append(1) +print(count(b), check(count, b)) +print(truthy(Tag("x")), truthy(Node("y")), truthy(Empty("z"))) +print(same(Keyed("a"), Node("a")), same(Node("a"), Node("a")), same(Keyed("a"), Keyed("b"))) +print(elements.OldTag is Tag, elements.Tag is Tag) +late.setup() +print(late.read(), late.value) +print(fields(ORIGIN), fields(Point(1, 2)), ORIGIN.x) diff --git a/maven/python-transpiler/src/test/resources/conformance/xshadow_.out b/maven/python-transpiler/src/test/resources/conformance/xshadow_.out new file mode 100644 index 00000000000..dd0a6e5a2cd --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/xshadow_.out @@ -0,0 +1,4 @@ +(0, 'float', 'unset', 1) +(5, 'int', 'set:g', 1) +0 float True +(7, 'int', 'set:g', 1) (0, 'float', 'unset', 1) diff --git a/maven/python-transpiler/src/test/resources/conformance/xshadow_/base.py b/maven/python-transpiler/src/test/resources/conformance/xshadow_/base.py new file mode 100644 index 00000000000..004e8935f35 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/xshadow_/base.py @@ -0,0 +1,20 @@ +class Desc: + def __get__(self, inst, cls): + if inst is None: + return self + return getattr(inst, "_fmt", "unset") + + def __set__(self, inst, value): + inst._fmt = "set:" + str(value) + + +class Base: + idx = 0 + kind = float + fmt = Desc() + + def __init__(self): + self.a = 1 + + def show(self): + return (self.idx, self.kind.__name__, self.fmt, self.a) diff --git a/maven/python-transpiler/src/test/resources/conformance/xshadow_/main.py b/maven/python-transpiler/src/test/resources/conformance/xshadow_/main.py new file mode 100644 index 00000000000..4a018642331 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/xshadow_/main.py @@ -0,0 +1,18 @@ +from base import Base + + +class Child(Base): + def __init__(self, i): + super().__init__() + self.idx = i + self.kind = int + self.fmt = "g" + + +b = Base() +print(b.show()) +c = Child(5) +print(c.show()) +print(Base.idx, Base.kind.__name__, isinstance(c, Base)) +c.idx += 2 +print(c.show(), b.show()) diff --git a/maven/python-transpiler/src/test/resources/conformance/xstore_.out b/maven/python-transpiler/src/test/resources/conformance/xstore_.out new file mode 100644 index 00000000000..1c0c931f896 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/xstore_.out @@ -0,0 +1,5 @@ +1 h:1 +'many' 7 +TypeError str +TypeError describe +[1, 2] h:0 diff --git a/maven/python-transpiler/src/test/resources/conformance/xstore_/holder.py b/maven/python-transpiler/src/test/resources/conformance/xstore_/holder.py new file mode 100644 index 00000000000..6bc0a3f1c9a --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/xstore_/holder.py @@ -0,0 +1,17 @@ +class Holder: + def __init__(self, **kw): + self.count = 0 + self.name = "h" + self.extra = kw + + def bump(self): + self.count = self.count + 1 + return self.count + + def describe(self): + return self.name + ":" + str(self.count) + + +class Other: + def __init__(self): + self.count = 1.5 diff --git a/maven/python-transpiler/src/test/resources/conformance/xstore_/main.py b/maven/python-transpiler/src/test/resources/conformance/xstore_/main.py new file mode 100644 index 00000000000..d6c7fb12d68 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/xstore_/main.py @@ -0,0 +1,18 @@ +from holder import Holder, Other +from poke import poke, poke_other + +h = Holder(a=1) +print(h.bump(), h.describe()) +poke(h) +print(repr(h.count), repr(h.name)) +try: + h.bump() +except TypeError as e: + print("TypeError", type(h.count).__name__) +try: + print(h.describe()) +except TypeError: + print("TypeError describe") +o = Other() +poke_other(o) +print(o.count, Holder().describe()) diff --git a/maven/python-transpiler/src/test/resources/conformance/xstore_/poke.py b/maven/python-transpiler/src/test/resources/conformance/xstore_/poke.py new file mode 100644 index 00000000000..98509d7a02d --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/xstore_/poke.py @@ -0,0 +1,7 @@ +def poke(h): + h.count = "many" + h.name = 7 + + +def poke_other(o): + o.count = [1, 2] diff --git a/maven/python-transpiler/src/test/resources/conformance/yieldtyped_.out b/maven/python-transpiler/src/test/resources/conformance/yieldtyped_.out new file mode 100644 index 00000000000..1e0a839c2b3 --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/yieldtyped_.out @@ -0,0 +1,5 @@ +47 +['root', 'ab', 'cde', 'f', 'gh'] +['AB', 'CDE', 'GH'] +AttributeError True +['X'] diff --git a/maven/python-transpiler/src/test/resources/conformance/yieldtyped_.py b/maven/python-transpiler/src/test/resources/conformance/yieldtyped_.py new file mode 100644 index 00000000000..2ffd994405c --- /dev/null +++ b/maven/python-transpiler/src/test/resources/conformance/yieldtyped_.py @@ -0,0 +1,58 @@ +# Iterating a generator method or a generator-expression property: the loop +# variable is typed by what the body yields, and checked as it arrives. + + +class Node: + def __init__(self, name, kids=None): + self.name = name + self.kids = kids or [] + self.weight = len(name) + + @property + def children(self): + return (k for k in self.kids) + + def walk(self): + yield self + for k in self.kids: + yield from k.walk() + + def leaves(self): + for k in self.kids: + if not k.kids: + yield k + + def total(self): + t = 0 + for c in self.children: + t += c.weight + for c in self.leaves(): + t += c.weight * 10 + return t + + def names(self): + return [n.name for n in self.walk()] + + +class Odd(Node): + def leaves(self): + yield "not a node" + + +def describe(n): + out = [] + for c in n.children: + out.append(c.name.upper()) + return out + + +tree = Node("root", [Node("ab"), Node("cde", [Node("f")]), Node("gh")]) +print(tree.total()) +print(tree.names()) +print(describe(tree)) +odd = Odd("odd", [Node("x")]) +try: + print(odd.total()) +except AttributeError as e: + print("AttributeError", "weight" in str(e)) +print(describe(odd)) diff --git a/maven/python-transpiler/third-party/cpython/LICENSE.txt b/maven/python-transpiler/third-party/cpython/LICENSE.txt new file mode 100644 index 00000000000..1c9c8bddbbf --- /dev/null +++ b/maven/python-transpiler/third-party/cpython/LICENSE.txt @@ -0,0 +1,46 @@ +PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2 +-------------------------------------------- + +1. This LICENSE AGREEMENT is between the Python Software Foundation +("PSF"), and the Individual or Organization ("Licensee") accessing and +otherwise using this software ("Python") in source or binary form and +its associated documentation. + +2. Subject to the terms and conditions of this License Agreement, PSF hereby +grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce, +analyze, test, perform and/or display publicly, prepare derivative works, +distribute, and otherwise use Python alone or in any derivative version, +provided, however, that PSF's License Agreement and PSF's notice of copyright, +i.e., "Copyright (c) 2001 Python Software Foundation; All Rights Reserved" +are retained in Python alone or in any derivative version prepared by Licensee. + +3. In the event Licensee prepares a derivative work that is based on +or incorporates Python or any part thereof, and wants to make +the derivative work available to others as provided herein, then +Licensee hereby agrees to include in any such work a brief summary of +the changes made to Python. + +4. PSF is making Python available to Licensee on an "AS IS" +basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR +IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND +DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS +FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT +INFRINGE ANY THIRD PARTY RIGHTS. + +5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON +FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS +A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON, +OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. + +6. This License Agreement will automatically terminate upon a material +breach of its terms and conditions. + +7. Nothing in this License Agreement shall be deemed to create any +relationship of agency, partnership, or joint venture between PSF and +Licensee. This License Agreement does not grant permission to use PSF +trademarks or trade name in a trademark sense to endorse or promote +products or services of Licensee, or any third party. + +8. By copying, installing or otherwise using Python, Licensee +agrees to be bound by the terms and conditions of this License +Agreement. diff --git a/maven/python-transpiler/third-party/pyyaml/LICENSE b/maven/python-transpiler/third-party/pyyaml/LICENSE new file mode 100644 index 00000000000..2f1b8e15e56 --- /dev/null +++ b/maven/python-transpiler/third-party/pyyaml/LICENSE @@ -0,0 +1,20 @@ +Copyright (c) 2017-2021 Ingy döt Net +Copyright (c) 2006-2016 Kirill Simonov + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/scripts/python-bench/build_parparvm.sh b/scripts/python-bench/build_parparvm.sh index 5b6140df54c..616ab131030 100755 --- a/scripts/python-bench/build_parparvm.sh +++ b/scripts/python-bench/build_parparvm.sh @@ -1,6 +1,9 @@ #!/bin/bash -# Builds one kernel as a native ParparVM executable, the way an iOS or native -# desktop build lowers it: Python -> Java -> bytecode -> C -> clang -O3. +# Builds one kernel as a native Linux application, the way a native desktop +# build lowers it: Python -> Java -> bytecode -> C -> clang, linked with the +# Linux port and its bundled SQLite. The port is the embedded variant (no +# GTK); run the binary with CN1_DISPLAY=headless. Linux only -- elsewhere use +# container/run.sh, which runs the whole table in a Linux container. # # build_parparvm.sh [maven repo] # @@ -8,7 +11,7 @@ # argument, else PYBENCH_M2, else /.m2-repo), never ~/.m2: concurrent checkouts overwrite each other's # snapshots there. Install them first: # -# cd maven && mvn -Dmaven.repo.local=$(pwd)/../.m2-repo -pl core,python-transpiler -am install -DskipTests +# cd maven && mvn -Dmaven.repo.local=$(pwd)/../.m2-repo -pl core,linux,python-transpiler -am install -DskipTests # JAVA_HOME=$JAVA17_HOME mvn -Dmaven.repo.local=$(pwd)/../.m2-repo -pl python-runtime install -DskipTests # mvn -Dmaven.repo.local=$(pwd)/../.m2-repo -f ../vm/pom.xml -pl JavaAPI,ByteCodeTranslator -am install -DskipTests # @@ -18,7 +21,9 @@ # # Output: scripts/python-bench/target// (and the translated # sources beside it). Needs JAVA17_HOME (javac for the generated code, which is -# Java 17) and JDK_8_HOME or JAVA_HOME (the translator), and clang. +# Java 17) and JDK_8_HOME or JAVA_HOME (the translator), clang, cmake, ninja +# and the embedded port's libraries (freetype, libpng, libjpeg, zlib, libcrypto, +# libcurl; see container/Containerfile). set -e HERE="$(cd "$(dirname "$0")" && pwd)" REPO="$(cd "$HERE/../.." && pwd)" @@ -30,17 +35,18 @@ J8="${JDK_8_HOME:-$JAVA_HOME}" CC="${CC:-clang}" art() { echo "$M2/$1/$2/$3/$2-$3.jar"; } CORE=$(art com/codenameone codenameone-core 8.0-SNAPSHOT) +LINUX=$(art com/codenameone codenameone-linux 8.0-SNAPSHOT) RUNTIME=$(art com/codenameone codenameone-python-runtime 8.0-SNAPSHOT) TRANSPILER=$(art com/codenameone codenameone-python-transpiler 8.0-SNAPSHOT) JAVAAPI=$(art com/codename1/parparvm JavaAPI 1.0-SNAPSHOT) TRANSLATOR=$(art com/codename1/parparvm ByteCodeTranslator 1.0-SNAPSHOT) -for j in "$CORE" "$RUNTIME" "$TRANSPILER" "$JAVAAPI" "$TRANSLATOR"; do +for j in "$CORE" "$LINUX" "$RUNTIME" "$TRANSPILER" "$JAVAAPI" "$TRANSLATOR"; do [ -f "$j" ] || { echo "missing $j -- install it (see the header of this script)" >&2; exit 1; } done W="$HERE/target/$K" rm -rf "$W" -mkdir -p "$W/src" "$W/gen/com/pybench" "$W/jclasses" "$W/javaapi" "$W/out" +mkdir -p "$W/src" "$W/gen/com/pybench" "$W/jclasses" "$W/javaapi" "$W/natives" "$W/out" # PY_SOURCES names another directory of programs (the conformance suite). SRC_DIR="${PY_SOURCES:-$HERE/kernels}" cp "$SRC_DIR/$K.py" "$W/src/" @@ -64,37 +70,32 @@ package com.pybench; public class PyBench { public static void main(String[] args) { + com.codename1.ui.Display.init(null); com.codename1.python.runtime.Py.setArgv("bench", args); System.exit(com.codename1.generated.python.PythonModules.runMain()); } } JAVA fi -# The runtime, and the one core package it uses (com.codename1.util: BigInteger, -# MathUtil). The whole core would drag in the UI and its natives. -# The translator reads class directories, not jars. -(cd "$W/javaapi" && unzip -qo "$JAVAAPI" 'java/*') -# zlib, gzip and zipfile run over core's JZlib port (io/gzip); its one -# networking class extends ConnectionRequest, which is UI, so it stays out. -(cd "$W/jclasses" && unzip -qo "$RUNTIME" 'com/*' && unzip -qo "$CORE" 'com/codename1/util/*' \ - && unzip -qo "$CORE" 'com/codename1/io/gzip/*' -x 'com/codename1/io/gzip/GZConnectionRequest*') -# The file system the runtime reaches through core's FileSystemStorage, over -# the host's files (hostfs/): the real class would bring the UI with it. -"$J17/bin/javac" -nowarn --release 17 -d "$W/jclasses" $(find "$HERE/hostfs" -name '*.java') +# The runtime, core and the Linux port, as an application ships them; +# dead-code elimination keeps what the program reaches. The translator reads +# class directories, not jars. +(cd "$W/javaapi" && unzip -qo "$JAVAAPI" 'java/*' 'com/*') +(cd "$W/jclasses" && unzip -qo "$RUNTIME" 'com/*' && unzip -qo "$CORE" 'com/*' && unzip -qo "$LINUX" 'com/*') +cp "$REPO"/Ports/LinuxPort/nativeSources/* "$W/natives/" [ -n "$APPCP" ] && cp -R "$W/appclasses/." "$W/jclasses/" "$J17/bin/javac" -nowarn --release 17 -cp "$W/jclasses" -d "$W/jclasses" $(find "$W/gen" -name '*.java') -"$J8/bin/java" -Xmx4g -cp "$TRANSLATOR" com.codename1.tools.translator.ByteCodeTranslator \ - clean "$W/javaapi;$W/jclasses" "$W/out" PyBench com.pybench PyBench 1.0 clean none \ +"$J8/bin/java" -Xmx4g -Dcn1.sqlite=true -Dcn1.linux.embedded=true -cp "$TRANSLATOR" \ + com.codename1.tools.translator.ByteCodeTranslator \ + clean "$W/javaapi;$W/jclasses;$W/natives" "$W/out" PyBench com.pybench PyBench 1.0 linux none \ > "$W/translate.log" 2>&1 || { tail -30 "$W/translate.log"; exit 1; } -# Compiled exactly as vm/selfhost compiles the self-hosted translator and its -# benchmarks, so the flags are the ones a shipped binary gets. -PYTHON=python3 -WINDOWS=0 -native_path() { echo "$1"; } # PY_OPT lowers the level for a build that tests behaviour, not speed: the -# conformance binary holds every program and takes minutes at -O3 with LTO. +# conformance binary holds every program and takes minutes at -O3. PY_OPT="${PY_OPT:--O3}" -[ "$PY_OPT" = "-O3" ] && CN1_SELFHOST_CFLAGS="-flto=thin $CN1_SELFHOST_CFLAGS" -. "$REPO/vm/selfhost/compile-dist.sh" -cn1_compile_dist "$W/out/dist" PyBench "$W/$K" "$PY_OPT" "$W/cc.log" +cmake -S "$W/out/dist" -B "$W/out/build" -G Ninja -DCMAKE_BUILD_TYPE=Release \ + -DCMAKE_C_COMPILER="$CC" -DCMAKE_C_FLAGS_RELEASE="$PY_OPT -DNDEBUG" > "$W/cc.log" 2>&1 \ + && cmake --build "$W/out/build" >> "$W/cc.log" 2>&1 || { tail -40 "$W/cc.log"; exit 1; } +cp "$W/out/build/PyBench" "$W/$K" +# The symbols, which the binary names by debuglink, for perf. +[ -f "$W/out/build/PyBench.debug" ] && cp "$W/out/build/PyBench.debug" "$W/PyBench.debug" diff --git a/scripts/python-bench/conformance_parparvm.sh b/scripts/python-bench/conformance_parparvm.sh index 8a9a6929546..407f7c2bb70 100755 --- a/scripts/python-bench/conformance_parparvm.sh +++ b/scripts/python-bench/conformance_parparvm.sh @@ -53,6 +53,10 @@ MARK="@@CN1CONF@@" echo " }" echo echo " public static void main(String[] args) {" + # The file system, sqlite and images are the Linux port's (build_parparvm.sh + # links it); without a Display there is no implementation behind + # FileSystemStorage and os.getcwd() is a NullPointerException. + echo " com.codename1.ui.Display.init(null);" echo " com.codename1.generated.python.PythonModules.registerAll();" for p in $progs; do echo " com.codename1.python.runtime.Py.setArgv(\"$p\", args);" @@ -65,15 +69,14 @@ MARK="@@CN1CONF@@" } > "$STAGE/PyBench.java" extra="" for p in $progs; do extra="$extra $CONF/$p.py"; done -if ! PY_SOURCES="$STAGE" PY_EXTRA_FILES="$extra" PY_DRIVER="$STAGE/PyBench.java" PY_OPT=-O1 \ - CN1_COMPILE_JOBS="$(getconf _NPROCESSORS_ONLN 2>/dev/null || echo 4)" \ +if ! PY_SOURCES="$STAGE" PY_EXTRA_FILES="$extra" PY_DRIVER="$STAGE/PyBench.java" PY_OPT="${PY_OPT:--O1}" \ "$HERE/build_parparvm.sh" "$K" > "$STAGE/build.log" 2>&1; then tail -40 "$STAGE/build.log" echo "BUILD FAILED" exit 1 fi got="$HERE/target/$K/output.txt" -(cd "$HERE/target/$K/src" && "../$K" > "$got" 2>&1) || true +(cd "$HERE/target/$K/src" && CN1_DISPLAY=headless "../$K" > "$got" 2>&1) || true python3 - "$CONF" "$got" "$MARK" $progs <<'PY' import difflib, sys conf, got, mark, progs = sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4:] diff --git a/scripts/python-bench/container/Containerfile b/scripts/python-bench/container/Containerfile new file mode 100644 index 00000000000..88c48bebf7f --- /dev/null +++ b/scripts/python-bench/container/Containerfile @@ -0,0 +1,37 @@ +# The benchmark machine: the native kernels are real Linux port binaries +# (build_parparvm.sh), measured beside CPython, PyPy and GraalPy on the same +# kernel source in the same container, so every column sees one kernel, one +# libc and one CPU budget. +# +# podman build -t cn1-python-bench -f scripts/python-bench/container/Containerfile . +# +# container/run.sh builds it and runs the table. +FROM docker.io/library/python:3.14-slim-bookworm + +ARG PYPY=pypy3.11-v7.3.19 +ARG GRAALPY=24.2.2 +ARG TEMURIN8=8u462b08 + +RUN apt-get update && apt-get install -y --no-install-recommends \ + clang cmake ninja-build pkg-config make time unzip curl ca-certificates bzip2 \ + libfreetype-dev libpng-dev libjpeg-dev zlib1g-dev libssl-dev libcurl4-openssl-dev \ + openjdk-17-jdk-headless linux-perf binutils \ + && rm -rf /var/lib/apt/lists/* + +# JDK 8 runs the translator, as on CI; Debian no longer packages one. +RUN set -e; arch=$(uname -m); case "$arch" in x86_64) t=x64;; aarch64) t=aarch64;; esac; \ + v=${TEMURIN8}; \ + curl -fsSL "https://github.com/adoptium/temurin8-binaries/releases/download/jdk${v%b*}-b${v#*b}/OpenJDK8U-jdk_${t}_linux_hotspot_${v}.tar.gz" \ + | tar -xz -C /opt && mv /opt/jdk8* /opt/jdk8 + +RUN set -e; arch=$(uname -m); case "$arch" in x86_64) p=linux64;; aarch64) p=aarch64;; esac; \ + curl -fsSL "https://downloads.python.org/pypy/${PYPY}-${p}.tar.bz2" | tar -xj -C /opt \ + && mv /opt/${PYPY}-${p} /opt/pypy + +RUN set -e; arch=$(uname -m); case "$arch" in x86_64) g=amd64;; aarch64) g=aarch64;; esac; \ + curl -fsSL "https://github.com/oracle/graalpython/releases/download/graal-${GRAALPY}/graalpy-${GRAALPY}-linux-${g}.tar.gz" \ + | tar -xz -C /opt && mv /opt/graalpy-* /opt/graalpy + +ENV JDK_8_HOME=/opt/jdk8 \ + CC=clang \ + CN1_DISPLAY=headless diff --git a/scripts/python-bench/container/run.sh b/scripts/python-bench/container/run.sh new file mode 100755 index 00000000000..d7ec0b35d3c --- /dev/null +++ b/scripts/python-bench/container/run.sh @@ -0,0 +1,23 @@ +#!/bin/bash +# Runs parparvm_table.py inside the benchmark container (Containerfile), with +# PyPy and GraalPy as extra columns. Arguments go to the table: +# +# scripts/python-bench/container/run.sh --rounds 5 sqlite_rows json_codec +# +# The checkout is mounted at /cn1; the framework comes from its own Maven +# repository (/.m2-repo, or PYBENCH_M2), installed with the commands in +# build_parparvm.sh's header. Uses podman, or docker when podman is absent. +# PYBENCH_OTHERS=0 leaves PyPy and GraalPy out, for quick iterations. +set -e +HERE="$(cd "$(dirname "$0")" && pwd)" +REPO="$(cd "$HERE/../../.." && pwd)" +M2="${PYBENCH_M2:-$REPO/.m2-repo}" +ENGINE="$(command -v podman || command -v docker)" +IMAGE=cn1-python-bench +"$ENGINE" build -q -t "$IMAGE" -f "$HERE/Containerfile" "$HERE" > /dev/null +OTHERS="--impl pypy=/opt/pypy/bin/pypy3 --impl graalpy=/opt/graalpy/bin/graalpy" +[ "${PYBENCH_OTHERS:-1}" = 0 ] && OTHERS="" +exec "$ENGINE" run --rm -v "$REPO":/cn1 -v "$M2":/m2 -w /cn1 \ + -e PYBENCH_M2=/m2 "$IMAGE" \ + sh -c 'export JAVA17_HOME=$(ls -d /usr/lib/jvm/java-17-openjdk-*); \ + exec python3 scripts/python-bench/parparvm_table.py "$@"' table $OTHERS "$@" diff --git a/scripts/python-bench/hostfs/com/codename1/io/FileSystemStorage.java b/scripts/python-bench/hostfs/com/codename1/io/FileSystemStorage.java index 377ef18d8cf..bd37c57428f 100644 --- a/scripts/python-bench/hostfs/com/codename1/io/FileSystemStorage.java +++ b/scripts/python-bench/hostfs/com/codename1/io/FileSystemStorage.java @@ -109,4 +109,30 @@ public long getLength(String url) { public long getLastModified(String url) { return file(url).lastModified(); } + + /// No caches directory: a caller (ConnectionRequest's download cache) falls back + /// to the application home, as on a port without one. + public boolean hasCachesDir() { + return false; + } + + public String getCachesDir() { + return null; + } + + public char getFileSystemSeparator() { + return '/'; + } + + public boolean isHidden(String url) { + return file(url).getName().startsWith("."); + } + + public String[] getRoots() { + return new String[] {SCHEME + "/"}; + } + + public String toNativePath(String url) { + return file(url).getPath(); + } } diff --git a/scripts/python-bench/kernels/bytes_codec.py b/scripts/python-bench/kernels/bytes_codec.py new file mode 100644 index 00000000000..f8586bf9836 --- /dev/null +++ b/scripts/python-bench/kernels/bytes_codec.py @@ -0,0 +1,20 @@ +# Bytes in, text out: what every converter does to a file before parsing it. +# UTF-8 and Latin-1 decoding, encoding back, byte indexing and bytes slicing. +from _harness import measure + + +def work(n): + chunk = ("naïve café — résumé

text

\n" * 8).encode("utf-8") + total = 0 + checksum = 0 + for i in range(n): + text = chunk.decode("utf-8") + total += len(text) + raw = text.encode("utf-8") + checksum = (checksum + raw[i % len(raw)]) & 0xffff + head = raw[: 16 + i % 32] + checksum = (checksum + len(head.decode("latin-1"))) & 0xffff + return "%d %d" % (total, checksum) + + +measure("bytes_codec", work, 40000, 5) diff --git a/scripts/python-bench/kernels/closures.py b/scripts/python-bench/kernels/closures.py new file mode 100644 index 00000000000..d62f02d045f --- /dev/null +++ b/scripts/python-bench/kernels/closures.py @@ -0,0 +1,28 @@ +# Functions as values: lambdas, closures over locals, sorted/map/filter with +# a key, and bound methods passed around -- what callbacks and visitor +# dispatch tables in the converters are made of. +from _harness import measure + + +def make_adder(k): + def add(x): + return x + k + return add + + +def work(n): + adders = [make_adder(k) for k in range(8)] + total = 0 + for i in range(n): + total += adders[i & 7](i) + total += (lambda x, y: x * y)(i & 15, 3) + items = [(i * 7919) % 1000 for i in range(n // 10)] + total += sum(sorted(items, key=lambda v: -v)[:10]) + total += sum(map(lambda v: v & 3, filter(lambda v: v % 3 == 0, items))) + handlers = {"a": str.upper, "b": str.lower, "c": str.strip} + for i in range(n // 10): + total += len(handlers["abc"[i % 3]](" Xy ")) + return str(total) + + +measure("closures", work, 400000, 5) diff --git a/scripts/python-bench/kernels/exceptions.py b/scripts/python-bench/kernels/exceptions.py new file mode 100644 index 00000000000..d98b2c2a3e3 --- /dev/null +++ b/scripts/python-bench/kernels/exceptions.py @@ -0,0 +1,37 @@ +# Exceptions as control flow: KeyError/AttributeError misses, getattr with a +# default and try/except/finally around small operations, as dict lookups +# with fallbacks and duck typing do throughout the converters. +from _harness import measure + + +class Thing: + def __init__(self, i): + self.a = i + + +def work(n): + d = {} + hits = 0 + for i in range(n): + key = i % 50 + try: + hits += d[key] + except KeyError: + d[key] = 1 + t = Thing(i) + hits += getattr(t, "b", 2) + try: + hits += t.c + except AttributeError: + hits += 3 + try: + if i % 100 == 0: + raise ValueError(i) + except ValueError as e: + hits += e.args[0] % 7 + finally: + hits += 1 + return str(hits) + + +measure("exceptions", work, 100000, 5) diff --git a/scripts/python-bench/kernels/generators.py b/scripts/python-bench/kernels/generators.py new file mode 100644 index 00000000000..fddc27e312a --- /dev/null +++ b/scripts/python-bench/kernels/generators.py @@ -0,0 +1,40 @@ +# Generator pipelines: the way bs4 walks a tree (descendants filtered by a +# predicate) and pdfminer streams tokens. +from _harness import measure + + +def numbers(n): + i = 0 + while i < n: + yield i + i += 1 + + +def evens(it): + for x in it: + if x % 2 == 0: + yield x + + +def walk(node): + yield node[0] + for child in node[1]: + yield from walk(child) + + +def tree(depth, fan): + if depth == 0: + return (depth, []) + return (depth, [tree(depth - 1, fan) for _ in range(fan)]) + + +def work(n): + s = sum(x * 3 for x in evens(numbers(n))) + t = tree(7, 4) + c = 0 + for _ in range(4): + c += sum(1 for d in walk(t) if d > 2) + return "%d %d" % (s, c) + + +measure("generators", work, 600000, 5) diff --git a/scripts/python-bench/kernels/json_codec.py b/scripts/python-bench/kernels/json_codec.py new file mode 100644 index 00000000000..f0209885e8c --- /dev/null +++ b/scripts/python-bench/kernels/json_codec.py @@ -0,0 +1,71 @@ +# JSON: decode an API-style document and walk it, the work behind every HTTP +# client and LLM SDK (the OpenAI responses `llm` reads are JSON). The result +# also folds in the decoder's edge cases, so a fast path that differs from +# CPython changes the answer, not only the time. +import json +from _harness import measure + + +def edge_cases(): + out = [] + out.append(json.loads('{"a": 1, "b": 2, "a": 3}')) + out.append(json.loads("[NaN, Infinity, -Infinity, 1e999, -0, -0.0]")) + out.append(json.loads("123456789012345678901234567890")) + out.append(json.loads('"\\ud83d\\ude00 \\u00e9 \\n"')) + out.append(json.loads('{"x": {"y": [1, 2]}}', object_pairs_hook=lambda p: ["pairs"] + p)) + out.append(json.loads('{"k": 1}', object_hook=lambda d: sorted(d.items()))) + out.append(json.loads('"a\tb"', strict=False)) + for bad in ('{"a" 1}', "[1, 2", '"a\tb"', "01", "[1,]", ""): + try: + json.loads(bad) + out.append("accepted " + bad) + except json.JSONDecodeError as e: + out.append(str(e)) + class S(str): + pass + + class I(int): + pass + + class Box: + def __init__(self, v): + self.v = v + + cyc = [] + cyc.append([cyc]) + out.append(json.dumps({"b": [1, 2.5, None, True, (3, "x")], "a": {"\u00e9\U0001f600": float("nan")}, + 3: 1e16, 2.5: -0.0, None: False, S("s"): I(7)})) + out.append(json.dumps({"z": 1, "a": [1, {"y": 2, "b": 3}], "\U0001f600": 0, "\ue000": 1}, sort_keys=True, + indent=2, ensure_ascii=False)) + out.append(json.dumps([Box(1), {"k": Box(2)}], default=lambda o: {"box": o.v}, separators=(",", ":"))) + out.append(json.dumps("\x7f\x00\t\"\\", ensure_ascii=True)) + for bad in (lambda: json.dumps(cyc), lambda: json.dumps(float("inf"), allow_nan=False), + lambda: json.dumps({(1, 2): 3}), lambda: json.dumps(object()), lambda: json.dumps({1: 2, "a": 3}, sort_keys=True)): + try: + out.append(bad()) + except (ValueError, TypeError) as e: + out.append(type(e).__name__ + ": " + str(e).split(" at 0x")[0]) + out.append(json.dumps({(1, 2): 3, "k": 1}, skipkeys=True)) + return repr(out) + + +def work(n): + items = [] + for i in range(n): + items.append({"id": i, "object": "chat.completion", "model": "gpt-4o-mini", + "choices": [{"index": 0, "message": {"role": "assistant", + "content": "Answer number %d é" % i}, + "finish_reason": "stop"}], + "usage": {"prompt_tokens": i % 97, "completion_tokens": i % 13, "total": i * 1.5}}) + doc = json.dumps({"data": items, "has_more": False}) + total = 0 + chars = 0 + for it in json.loads(doc)["data"]: + total += it["usage"]["prompt_tokens"] + it["usage"]["completion_tokens"] + chars += len(it["choices"][0]["message"]["content"]) + if it["usage"]["total"] != it["id"] * 1.5: + total -= 1 + return "%d %d %d %s" % (total, chars, len(doc), edge_cases()) + + +measure("json_codec", work, 20000, 5) diff --git a/scripts/python-bench/kernels/objects.py b/scripts/python-bench/kernels/objects.py new file mode 100644 index 00000000000..b5e69ebcd6d --- /dev/null +++ b/scripts/python-bench/kernels/objects.py @@ -0,0 +1,50 @@ +# Plain objects: construction, attribute reads and writes, method calls, +# properties and isinstance -- the shape of python-pptx's and openpyxl's +# element proxies and of bs4's Tag. +from _harness import measure + + +class Node: + def __init__(self, name, parent=None): + self.name = name + self.parent = parent + self.children = [] + self.attrs = {} + + def append(self, child): + self.children.append(child) + child.parent = self + return child + + @property + def depth(self): + d = 0 + p = self.parent + while p is not None: + d += 1 + p = p.parent + return d + + +class Text(Node): + def __init__(self, value, parent=None): + Node.__init__(self, "#text", parent) + self.value = value + + +def work(n): + root = Node("root") + cur = root + total = 0 + for i in range(n): + if i % 8 == 0: + cur = root.append(Node("p")) + t = cur.append(Text("w%d" % (i % 10))) + t.attrs["i"] = i + total += t.depth + len(t.value) + if isinstance(t, Text) and t.parent is cur: + total += 1 + return "%d %d" % (total, len(root.children)) + + +measure("objects", work, 100000, 5) diff --git a/scripts/python-bench/kernels/regex_text.py b/scripts/python-bench/kernels/regex_text.py new file mode 100644 index 00000000000..45ba71dd81b --- /dev/null +++ b/scripts/python-bench/kernels/regex_text.py @@ -0,0 +1,24 @@ +# Regular expressions over text: tokenizing, substitution and search, as the +# Markdown escaping and whitespace normalization in markdownify do. +import re +from _harness import measure + +WS = re.compile(r"\s+") +ESC = re.compile(r"([*_`\[\]])") +NUM = re.compile(r"\d+(?:\.\d+)?") + + +def work(n): + text = "Some *bold* text_with [links]\tand 12.5 numbers, 42 more words here. " * 4 + total = 0 + for i in range(n): + t = WS.sub(" ", text) + t = ESC.sub(r"\\\1", t) + total += len(t) + len(NUM.findall(t)) + m = re.match(r"(\w+) (\*?\w+\*?)", t) + if m: + total += len(m.group(2)) + return str(total) + + +measure("regex_text", work, 5000, 5) diff --git a/scripts/python-bench/kernels/sqlite_rows.py b/scripts/python-bench/kernels/sqlite_rows.py new file mode 100644 index 00000000000..eef3a889c4c --- /dev/null +++ b/scripts/python-bench/kernels/sqlite_rows.py @@ -0,0 +1,61 @@ +# SQLite the way sqlite-utils drives it when llm logs a reply: for each row +# the table's columns are read back (PRAGMA table_info), an INSERT is built +# as text from them, a JSON field is serialized, the row goes in with bound +# parameters and the statement's rows come back as tuples. In memory, so the +# disk's sync time stays out of it and only the Python side is measured. +import json +import sqlite3 + +from _harness import measure + + +def quote(name): + return "[" + name.replace("]", "]]") + "]" + + +def columns(conn, table): + return [row[1] for row in conn.execute("PRAGMA table_info(%s)" % quote(table)).fetchall()] + + +def insert(conn, table, record): + cols = columns(conn, table) + names = [k for k in record if k in cols] + sql = "INSERT INTO %s (%s) VALUES (%s)" % ( + quote(table), ", ".join(quote(n) for n in names), ", ".join("?" for _ in names)) + cur = conn.execute(sql, [record[n] for n in names]) + return cur.lastrowid + + +def work(n): + conn = sqlite3.connect(":memory:") + conn.execute("CREATE TABLE conversations (id TEXT PRIMARY KEY, name TEXT, model TEXT)") + conn.execute("CREATE TABLE responses (id TEXT PRIMARY KEY, model TEXT, prompt TEXT, " + "system TEXT, options_json TEXT, response TEXT, conversation_id TEXT, " + "duration_ms INTEGER, datetime_utc TEXT, input_tokens INTEGER, " + "output_tokens INTEGER)") + total = 0 + with conn: + insert(conn, "conversations", {"id": "c1", "name": "bench", "model": "echo"}) + for i in range(n): + options = {"temperature": 0.5 + (i % 5) / 10.0, "stop": ["\n", "END"], "seed": i} + total += insert(conn, "responses", { + "id": "r%06d" % i, + "model": "echo", + "prompt": "prompt number %d about %s" % (i, "alpha bravo"[: 1 + i % 11]), + "system": None, + "options_json": json.dumps(options), + "response": "reply %d" % (i * 7), + "conversation_id": "c1", + "duration_ms": i % 97, + "datetime_utc": "2026-11-08T10:%02d:%02d" % (i // 60 % 60, i % 60), + "input_tokens": i % 13, + "output_tokens": i % 17, + }) + for row in conn.execute("SELECT id, options_json, duration_ms FROM responses " + "WHERE conversation_id = ? ORDER BY id", ("c1",)): + total += row[2] + len(json.loads(row[1])["stop"]) + conn.close() + return total + + +measure("sqlite_rows", work, 3000, 5) diff --git a/scripts/python-bench/kernels/str_ops.py b/scripts/python-bench/kernels/str_ops.py new file mode 100644 index 00000000000..562676d507d --- /dev/null +++ b/scripts/python-bench/kernels/str_ops.py @@ -0,0 +1,24 @@ +# The string operations markdownify, bs4 and the converters run per node: +# slicing, find, replace, strip, startswith, join and %-formatting. +from _harness import measure + + +def work(n): + line = " Revenue & costs, 2024 " + out = [] + acc = 0 + for i in range(n): + s = line.strip() + a = s.find(">") + 1 + b = s.rfind("<") + cell = s[a:b].replace("&", "&") + if cell.startswith("Rev"): + acc += len(cell) + out.append("| %s | %d |" % (cell.lower(), i % 7)) + if len(out) == 64: + acc += len("\n".join(out)) + out = [] + return str(acc) + + +measure("str_ops", work, 300000, 5) diff --git a/scripts/python-bench/kernels/xml_etree.py b/scripts/python-bench/kernels/xml_etree.py new file mode 100644 index 00000000000..b638dd54f15 --- /dev/null +++ b/scripts/python-bench/kernels/xml_etree.py @@ -0,0 +1,31 @@ +# XML: build a document as text, parse it with ElementTree and walk it, the +# work behind DOCX, PPTX and XLSX (all zipped XML). +import xml.etree.ElementTree as ET +from _harness import measure + +NS = "http://schemas.openxmlformats.org/spreadsheetml/2006/main" + + +def work(rows): + parts = ['' % NS] + for r in range(rows): + parts.append('' % (r + 1)) + for c in range(6): + parts.append('%d' % ("ABCDEF"[c], r + 1, r * c)) + parts.append("") + parts.append("") + doc = "".join(parts) + root = ET.fromstring(doc) + total = 0 + cells = 0 + for row in root.iter("{%s}row" % NS): + for c in row.findall("{%s}c" % NS): + v = c.find("{%s}v" % NS) + total += int(v.text) + cells += 1 + if c.get("t") != "n": + total -= 1 + return "%d %d %d" % (total, cells, len(doc)) + + +measure("xml_etree", work, 6000, 5) diff --git a/scripts/python-bench/kernels/zz_closparts.py b/scripts/python-bench/kernels/zz_closparts.py new file mode 100644 index 00000000000..58436eed056 --- /dev/null +++ b/scripts/python-bench/kernels/zz_closparts.py @@ -0,0 +1,65 @@ +# Scratch: the closures kernel split into its parts, each timed alone. +import time + + +def make_adder(k): + def add(x): + return x + k + return add + + +ADDERS = [make_adder(k) for k in range(8)] +ITEMS = [(i * 7919) % 1000 for i in range(40000)] +HANDLERS = {"a": str.upper, "b": str.lower, "c": str.strip} + + +def p_adders(n): + t = 0 + for i in range(n): + t += ADDERS[i & 7](i) + return t + + +def p_lambda_call(n): + t = 0 + for i in range(n): + t += (lambda x, y: x * y)(i & 15, 3) + return t + + +def p_make_adders(n): + t = 0 + for i in range(n // 100): + a = [make_adder(k) for k in range(8)] + t += len(a) + return t + + +def p_sorted_key(n): + return sum(sorted(ITEMS, key=lambda v: -v)[:10]) + + +def p_map_filter(n): + return sum(map(lambda v: v & 3, filter(lambda v: v % 3 == 0, ITEMS))) + + +def p_unbound_str(n): + t = 0 + for i in range(n // 10): + t += len(HANDLERS["abc"[i % 3]](" Xy ")) + return t + + +PARTS = [("adders", p_adders), ("lambda_call", p_lambda_call), ("make_adders", p_make_adders), + ("sorted_key", p_sorted_key), ("map_filter", p_map_filter), ("unbound_str", p_unbound_str)] + +N = 400000 +for name, f in PARTS: + best = None + for _ in range(7): + t0 = time.perf_counter() + f(N) + dt = time.perf_counter() - t0 + if best is None or dt < best: + best = dt + print("PART", name, int(best * 1000000)) diff --git a/scripts/python-bench/kernels/zz_core.py b/scripts/python-bench/kernels/zz_core.py new file mode 100644 index 00000000000..9967f3c66e6 --- /dev/null +++ b/scripts/python-bench/kernels/zz_core.py @@ -0,0 +1,422 @@ +# Scratch: the cost of each core operation, alone, in ns per operation. +import time + + +class Node: + def __init__(self, name, parent=None): + self.name = name + self.parent = parent + self.children = [] + self.attrs = {"class": "x", "id": "y"} + + def get(self, key, default=None): + return self.attrs.get(key, default) + + def match(self, other, known=False): + return known or other is self + + def __bool__(self): + return True + + @property + def label(self): + return self.name + + +class Leaf(Node): + def __init__(self, name): + super().__init__(name) + + +def plain(a, b): + return a + + +def defaults(a, b=1, c=None): + return a + + +def star(*args): + return args[0] + + +def kw(**kws): + return kws + + +N = 200000 +NODE = Node("div") +OTHER = Node("span") +LST = list(range(50)) +S = "hello world, this is text" +D = {"a": 1, "b": 2, "c": 3} + + +def gen(n): + for i in range(n): + yield i + + +def p_call(n): + t = 0 + for _ in range(n): + t += plain(1, 2) + return t + + +def p_defaults(n): + t = 0 + for _ in range(n): + t += defaults(1) + return t + + +def p_kwcall(n): + t = 0 + for _ in range(n): + t += defaults(1, c=2) + return t + + +def p_star(n): + t = 0 + for _ in range(n): + t += star(1, 2) + return t + + +def p_method(n): + t = 0 + nd = NODE + for _ in range(n): + if nd.get("class") is not None: + t += 1 + return t + + +def p_method_kw(n): + t = 0 + nd = NODE + o = OTHER + for _ in range(n): + if nd.match(o, known=True): + t += 1 + return t + + +def p_attr(n): + t = 0 + nd = NODE + for _ in range(n): + if nd.parent is None: + t += 1 + return t + + +def p_setattr(n): + nd = Node("x") + for i in range(n): + nd.parent = i + return nd.parent + + +def p_property(n): + t = 0 + nd = NODE + for _ in range(n): + t += len(nd.label) + return t + + +def p_truth(n): + t = 0 + nd = NODE + for _ in range(n): + if nd: + t += 1 + return t + + +def p_isinstance(n): + t = 0 + nd = NODE + for _ in range(n): + if isinstance(nd, Node): + t += 1 + return t + + +def p_isinstance_str(n): + t = 0 + s = S + for _ in range(n): + if isinstance(s, str): + t += 1 + return t + + +def p_new(n): + t = 0 + for _ in range(n): + t += len(Node("a").name) + return t + + +def p_new_super(n): + t = 0 + for _ in range(n): + t += len(Leaf("a").name) + return t + + +def p_gen(n): + t = 0 + for i in gen(n): + t += i + return t + + +def p_next(n): + g = gen(n) + t = 0 + while True: + try: + i = next(g) + except StopIteration: + break + t += i + return t + + +def p_genexpr(n): + t = 0 + for _ in range(n // 50): + t += sum(x for x in LST) + return t + + +def p_listcomp(n): + t = 0 + for _ in range(n // 50): + t += len([x for x in LST if x & 1]) + return t + + +def p_try(n): + t = 0 + for i in range(n): + try: + t += i + except ValueError: + t -= 1 + return t + + +def p_raise(n): + t = 0 + for i in range(n // 10): + try: + raise ValueError("x") + except ValueError: + t += 1 + return t + + +def p_dictget(n): + t = 0 + d = D + for _ in range(n): + t += d.get("b", 0) + return t + + +def p_dictin(n): + t = 0 + d = D + for _ in range(n): + if "c" in d: + t += 1 + return t + + +def p_dictset(n): + d = {} + for i in range(n): + d[i & 255] = i + return len(d) + + +def p_getattr3(n): + t = 0 + nd = NODE + for _ in range(n): + if getattr(nd, "missing", None) is None: + t += 1 + return t + + +def p_strmeth(n): + t = 0 + s = S + for _ in range(n): + if s.startswith("hel"): + t += 1 + return t + + +def p_strip(n): + t = 0 + s = " abc " + for _ in range(n): + t += len(s.strip()) + return t + + +def p_strin(n): + t = 0 + s = S + for _ in range(n): + if "this" in s: + t += 1 + return t + + +def p_stridx(n): + t = 0 + s = S + for i in range(n): + if s[i & 15] == "l": + t += 1 + return t + + +def p_concat(n): + t = 0 + for i in range(n): + t += len("a" + S) + return t + + +def p_fstring(n): + t = 0 + for i in range(n): + t += len(f"<{S}>{i}") + return t + + +def p_join(n): + t = 0 + parts = ["a", "b", "c", "d"] + for _ in range(n): + t += len("".join(parts)) + return t + + +def p_split(n): + t = 0 + for _ in range(n): + t += len(S.split()) + return t + + +def p_append(n): + out = [] + for i in range(n): + out.append(i) + return len(out) + + +def p_len(n): + t = 0 + lst = LST + for _ in range(n): + t += len(lst) + return t + + +def p_listiter(n): + t = 0 + for _ in range(n // 50): + for x in LST: + t += x + return t + + +def p_closure(n): + k = 3 + + def f(x): + return x + k + t = 0 + for i in range(n): + t += f(i) + return t + + +def p_lambda_sort(n): + t = 0 + data = [(i * 7) % 50 for i in range(50)] + for _ in range(n // 50): + t += sorted(data, key=lambda x: -x)[0] + return t + + +def p_tuple_unpack(n): + t = 0 + for i in range(n): + a, b = i, 1 + t += a + b + return t + + +def p_eq_str(n): + t = 0 + s = "div" + for _ in range(n): + if s == "div": + t += 1 + return t + + +def p_int_arith(n): + t = 0 + for i in range(n): + t += (i * 3 + 1) % 7 + return t + + +PARTS = [ + ("call", p_call), ("defaults", p_defaults), ("kwcall", p_kwcall), ("star", p_star), + ("method", p_method), ("method_kw", p_method_kw), ("attr", p_attr), ("setattr", p_setattr), + ("property", p_property), ("truth", p_truth), ("isinstance", p_isinstance), + ("isinst_str", p_isinstance_str), ("new", p_new), ("new_super", p_new_super), ("gen", p_gen), + ("next", p_next), ("genexpr", p_genexpr), ("listcomp", p_listcomp), ("try", p_try), + ("raise", p_raise), ("dictget", p_dictget), ("dictin", p_dictin), ("dictset", p_dictset), + ("getattr3", p_getattr3), ("strmeth", p_strmeth), ("strip", p_strip), ("strin", p_strin), + ("stridx", p_stridx), ("concat", p_concat), ("fstring", p_fstring), ("join", p_join), + ("split", p_split), ("append", p_append), ("len", p_len), ("listiter", p_listiter), + ("closure", p_closure), ("sort_key", p_lambda_sort), ("unpack", p_tuple_unpack), + ("eq_str", p_eq_str), ("int_arith", p_int_arith), +] + + +def main(): + import os + only = os.environ.get("CORE_PART") + if only: + f = dict(PARTS)[only] + for _ in range(400): + f(N) + return + for name, f in PARTS: + best = None + for _ in range(5): + t0 = time.perf_counter() + f(N) + dt = time.perf_counter() - t0 + if best is None or dt < best: + best = dt + print("PART %-12s %7.1f" % (name, best * 1e9 / N)) + + +main() diff --git a/scripts/python-bench/kernels/zz_esc.py b/scripts/python-bench/kernels/zz_esc.py new file mode 100644 index 00000000000..00b539c8642 --- /dev/null +++ b/scripts/python-bench/kernels/zz_esc.py @@ -0,0 +1,188 @@ +# Scratch: the regular expressions markitdown spends its time in, each timed alone. +# Patterns are copied from markdownify and CPython 3.14's html.parser. +import re +import time + +re_whitespace = re.compile(r'[\t ]+') +re_all_whitespace = re.compile(r'[\t \r\n]+') +re_newline_whitespace = re.compile(r'[\t \r\n]*[\r\n][\t \r\n]*') +re_extract_newlines = re.compile(r'^(\n*)((?:.*[^\n])?)(\n*)$', flags=re.DOTALL) +re_escape_misc_chars = re.compile(r'([]\\&<`[>~=+|])') +re_escape_misc_dash_sequences = re.compile(r'(\s|^)(-+(?:\s|$))') +re_escape_misc_hashes = re.compile(r'(\s|^)(#{1,6}(?:\s|$))') +re_escape_misc_list_items = re.compile(r'((?:\s|^)[0-9]{1,9})([.)](?:\s|$))') +re_html_heading = re.compile(r'h(\d+)') + +interesting_normal = re.compile('[&<]') +starttagopen = re.compile('<[a-zA-Z]') +tagfind_tolerant = re.compile(r'([a-zA-Z][^\t\n\r\f />]*)(?:[\t\n\r\f ]|/(?!>))*') +attrfind_tolerant = re.compile(r""" + ( + (?<=['"\t\n\r\f /])[^\t\n\r\f />][^\t\n\r\f /=>]* # attribute name + ) + ([\t\n\r\f ]*=[\t\n\r\f ]* # value indicator + ('[^']*' # LITA-enclosed value + |"[^"]*" # LIT-enclosed value + |(?!['"])[^>\t\n\r\f ]* # bare value + ) + )? + (?:[\t\n\r\f ]|/(?!>))* # possibly followed by a space +""", re.VERBOSE) +locatetagend = re.compile(r""" + [a-zA-Z][^\t\n\r\f />]* # tag name + [\t\n\r\f /]* # optional whitespace before attribute name + (?:(?<=['"\t\n\r\f /])[^\t\n\r\f />][^\t\n\r\f /=>]* # attribute name + (?:[\t\n\r\f ]*=[\t\n\r\f ]* # value indicator + (?:'[^']*' # LITA-enclosed value + |"[^"]*" # LIT-enclosed value + |(?!['"])[^>\t\n\r\f ]* # bare value + ) + )? + [\t\n\r\f /]* # possibly followed by a space + )* + >? +""", re.VERBOSE) + +WORDS = ["the", "quick", "brown", "fox", "jumps", "over", "lazy", "dog", "Wikipedia", + "article", "history", "1999", "-", "#", "3.", "a|b", "x=y", "[ref]", "free"] + + +def texts(): + out = [] + k = 0 + for i in range(400): + n = 1 + (i * 7) % 23 + ws = [] + for j in range(n): + ws.append(WORDS[k % len(WORDS)]) + k += 1 + s = " ".join(ws) + if i % 5 == 0: + s = "\n" + s + if i % 7 == 0: + s = s + "\n\n" + if i % 3 == 0: + s = s.replace(" ", " \t", 2) + out.append(s) + return out + + +def html_doc(): + parts = [] + for i in range(300): + parts.append('
link %d' + ' text & more s
\n' % (i, i, i, i, i, i)) + return "".join(parts) + + +TEXTS = texts() +HTML = html_doc() + + +def p_extract(n): + t = 0 + for _ in range(n): + for s in TEXTS: + a, b, c = re_extract_newlines.match(s).groups() + t += len(a) + len(b) + len(c) + return t + + +def p_ws(n): + t = 0 + for _ in range(n): + for s in TEXTS: + x = re_all_whitespace.sub(' ', s) + y = re_newline_whitespace.sub('\n', s) + y = re_whitespace.sub(' ', y) + t += len(x) + len(y) + return t + + +def p_escape(n): + t = 0 + for _ in range(n): + for s in TEXTS: + x = re_escape_misc_chars.sub(r'\\\1', s) + x = re_escape_misc_dash_sequences.sub(r'\1\\\2', x) + x = re_escape_misc_hashes.sub(r'\1\\\2', x) + x = re_escape_misc_list_items.sub(r'\1\\\2', x) + t += len(x) + return t + + +def p_heading(n): + t = 0 + names = ["div", "h1", "span", "a", "h3", "p", "li", "td"] + for _ in range(n): + for i in range(400): + if re_html_heading.match(names[i & 7]) is not None: + t += 1 + return t + + +def p_scan(n): + # html.parser's goahead: find the next markup, then classify it. + t = 0 + raw = HTML + for _ in range(n): + i = 0 + end = len(raw) + while i < end: + m = interesting_normal.search(raw, i) + j = m.start() if m else end + if i < j: + t += j - i + i = j + if i == end: + break + if raw.startswith('<', i): + if starttagopen.match(raw, i): + m = locatetagend.match(raw, i + 1) + k = m.end() + tm = tagfind_tolerant.match(raw, i + 1) + p = tm.end() + while p < k: + am = attrfind_tolerant.match(raw, p) + if not am: + break + t += len(am.group(1)) + p = am.end() + i = k + else: + i = raw.find('>', i) + 1 + else: + i += 1 + return t + + +def part(name, f, n, repeat): + best = None + r = None + for _ in range(repeat): + t0 = time.perf_counter() + r = f(n) + dt = time.perf_counter() - t0 + if best is None or dt < best: + best = dt + print("PART", name, int(best * 1000000), r) + + +def main(): + import sys + which = sys.argv[1] if len(sys.argv) > 1 else "all" + for k in range(4): + pats = [(re_escape_misc_chars, r'\\\1'), (re_escape_misc_dash_sequences, r'\1\\\2'), + (re_escape_misc_hashes, r'\1\\\2'), (re_escape_misc_list_items, r'\1\\\2')] + p, r = pats[k] + def f(n, p=p, r=r): + t = 0 + for _ in range(n): + for s in TEXTS: + t += len(p.sub(r, s)) + return t + part("esc%d" % k, f, 20, 7) + part("esc_long", p_escape, 400, 1) + + +main() diff --git a/scripts/python-bench/kernels/zz_expat.py b/scripts/python-bench/kernels/zz_expat.py new file mode 100644 index 00000000000..7c3a0f92885 --- /dev/null +++ b/scripts/python-bench/kernels/zz_expat.py @@ -0,0 +1,64 @@ +# Scratch: expat event streams compared with CPython, then timed. +import os +import time +import xml.parsers.expat as E + +DOCS = [ + 't&xAB<tail\nline2', + 'x', + ']>&e; & ]]>', + '12\n \xe9中', +] + + +def events(doc, sep, buffered, ordered): + out = [] + p = E.ParserCreate(namespace_separator=sep) + p.buffer_text = buffered + p.ordered_attributes = ordered + p.StartElementHandler = lambda n, a: out.append(("S", n, a if ordered else sorted(a.items()))) + p.EndElementHandler = lambda n: out.append(("E", n)) + p.CharacterDataHandler = lambda d: out.append(("C", d)) + p.CommentHandler = lambda d: out.append(("#", d)) + p.StartNamespaceDeclHandler = lambda a, b: out.append(("NS", a, b)) + p.EndNamespaceDeclHandler = lambda a: out.append(("NE", a)) + p.ProcessingInstructionHandler = lambda a, b: out.append(("PI", a, b)) + try: + p.Parse(doc, True) + except E.ExpatError as e: + out.append(("ERR", str(e))) + return out + + +def big(): + parts = [''] + for i in range(2000): + parts.append('Run %d & more\n' % (i, i)) + parts.append('') + return "".join(parts).encode("utf-8") + + +def main(): + for d in DOCS + ['', '&bogus;', '']: + for sep in (None, "}"): + for bt in (False, True): + for od in (False, True): + print(events(d, sep, bt, od)) + data = big() + best = None + for _ in range(int(os.environ.get("REP", "7"))): + t0 = time.perf_counter() + for _ in range(5): + cnt = [0] + p = E.ParserCreate(namespace_separator="}") + p.buffer_text = True + p.StartElementHandler = lambda n, a: None + p.EndElementHandler = lambda n: None + p.CharacterDataHandler = lambda d: None + p.Parse(data, True) + dt = time.perf_counter() - t0 + best = dt if best is None or dt < best else best + print("PART parse", int(best * 1e6 / 5)) + + +main() diff --git a/scripts/python-bench/kernels/zz_gendrain.py b/scripts/python-bench/kernels/zz_gendrain.py new file mode 100644 index 00000000000..90a53d8c71c --- /dev/null +++ b/scripts/python-bench/kernels/zz_gendrain.py @@ -0,0 +1,50 @@ +# Scratch: one generator drained, repeated long enough to profile. +import sys + + +def numbers(n): + i = 0 + while i < n: + yield i + i += 1 + + +def p_drain(n): + s = 0 + for x in numbers(n): + s += x + return s + + +def p_sum_range(n): + return sum(range(n)) + + +def walk(node): + yield node[0] + for child in node[1]: + yield from walk(child) + + +def tree(depth, fan): + if depth == 0: + return (depth, []) + return (depth, [tree(depth - 1, fan) for _ in range(fan)]) + + +T = tree(7, 4) + + +def p_walk(n): + c = 0 + for _ in range(25): + for d in walk(T): + c += 1 + return c + + +which = sys.argv[1] if len(sys.argv) > 1 else "drain" +t = 0 +for _ in range(200): + t += p_drain(600000) if which == "drain" else p_walk(0) +print(t) diff --git a/scripts/python-bench/kernels/zz_genparts.py b/scripts/python-bench/kernels/zz_genparts.py new file mode 100644 index 00000000000..7969c60b56b --- /dev/null +++ b/scripts/python-bench/kernels/zz_genparts.py @@ -0,0 +1,120 @@ +# Scratch: the generators kernel split into its parts, each timed alone. +import time + + +def numbers(n): + i = 0 + while i < n: + yield i + i += 1 + + +def evens(it): + for x in it: + if x % 2 == 0: + yield x + + +def walk(node): + yield node[0] + for child in node[1]: + yield from walk(child) + + +def tree(depth, fan): + if depth == 0: + return (depth, []) + return (depth, [tree(depth - 1, fan) for _ in range(fan)]) + + +def p_while(n): + i = 0 + s = 0 + while i < n: + s += i + i += 1 + return s + + +def p_mod(n): + i = 0 + s = 0 + while i < n: + if i % 2 == 0: + s += i + i += 1 + return s + + +def p_drain(n): + s = 0 + for x in numbers(n): + s += x + return s + + +def p_filter(n): + s = 0 + for x in evens(numbers(n)): + s += x + return s + + +def p_sum_genexpr(n): + return sum(x * 3 for x in range(n)) + + +def p_sum_range(n): + return sum(range(n)) + + +def p_create(n): + c = 0 + for _ in range(n // 10): + for x in numbers(1): + c += x + return c + + +def p_tree(n): + return len(tree(7, 4)[1]) + + +T = tree(7, 4) + + +def p_walk(n): + c = 0 + for d in walk(T): + c += 1 + return c + + +def p_walk_filter_sum(n): + return sum(1 for d in walk(T) if d > 2) + + +def p_full(n): + s = sum(x * 3 for x in evens(numbers(n))) + c = 0 + for _ in range(4): + c += sum(1 for d in walk(T) if d > 2) + return s + c + + +PARTS = [("while", p_while), ("while_mod", p_mod), ("drain_gen", p_drain), + ("filter_gen", p_filter), ("sum_genexpr", p_sum_genexpr), + ("sum_range", p_sum_range), ("create_gen", p_create), ("tree", p_tree), + ("walk_yieldfrom", p_walk), ("walk_filter_sum", p_walk_filter_sum), + ("full", p_full)] + +N = 600000 +for name, f in PARTS: + best = None + for _ in range(7): + t0 = time.perf_counter() + f(N) + dt = time.perf_counter() - t0 + if best is None or dt < best: + best = dt + print("PART", name, int(best * 1000000)) diff --git a/scripts/python-bench/kernels/zz_gz.py b/scripts/python-bench/kernels/zz_gz.py new file mode 100644 index 00000000000..346d8895775 --- /dev/null +++ b/scripts/python-bench/kernels/zz_gz.py @@ -0,0 +1,131 @@ +import zlib, gzip, io, os, zipfile, struct +T = b'hello hello hello compression ' * 20 +ZL=bytes.fromhex('789ccb48cdc9c957c8402293f3730b8a528b8b33f3f350c447654765899705005fe8e499') +RAW=bytes.fromhex('cb48cdc9c957c8402293f3730b8a528b8b33f3f350c44765476589970500') +GZ=bytes.fromhex('1f8b08000000000002ffcb48cdc9c957c8402293f3730b8a528b8b33f3f350c44765476589970500527e086f58020000') +DICT=bytes.fromhex('78bb3ca206e7cb000b209348920aa3b2a3b2e4c902005fe8e499') +ZIP=bytes.fromhex('504b030414000000000083182250527e086f580200005802000005000000612e74787468656c6c6f2068656c6c6f2068656c6c6f20636f6d7072657373696f6e2068656c6c6f2068656c6c6f2068656c6c6f20636f6d7072657373696f6e2068656c6c6f2068656c6c6f2068656c6c6f20636f6d7072657373696f6e2068656c6c6f2068656c6c6f2068656c6c6f20636f6d7072657373696f6e2068656c6c6f2068656c6c6f2068656c6c6f20636f6d7072657373696f6e2068656c6c6f2068656c6c6f2068656c6c6f20636f6d7072657373696f6e2068656c6c6f2068656c6c6f2068656c6c6f20636f6d7072657373696f6e2068656c6c6f2068656c6c6f2068656c6c6f20636f6d7072657373696f6e2068656c6c6f2068656c6c6f2068656c6c6f20636f6d7072657373696f6e2068656c6c6f2068656c6c6f2068656c6c6f20636f6d7072657373696f6e2068656c6c6f2068656c6c6f2068656c6c6f20636f6d7072657373696f6e2068656c6c6f2068656c6c6f2068656c6c6f20636f6d7072657373696f6e2068656c6c6f2068656c6c6f2068656c6c6f20636f6d7072657373696f6e2068656c6c6f2068656c6c6f2068656c6c6f20636f6d7072657373696f6e2068656c6c6f2068656c6c6f2068656c6c6f20636f6d7072657373696f6e2068656c6c6f2068656c6c6f2068656c6c6f20636f6d7072657373696f6e2068656c6c6f2068656c6c6f2068656c6c6f20636f6d7072657373696f6e2068656c6c6f2068656c6c6f2068656c6c6f20636f6d7072657373696f6e2068656c6c6f2068656c6c6f2068656c6c6f20636f6d7072657373696f6e2068656c6c6f2068656c6c6f2068656c6c6f20636f6d7072657373696f6e20504b03041400000000000539a652738c05290001000000010000090000006469722f622e62696e000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9fa0a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbebfc0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8d9dadbdcdddedfe0e1e2e3e4e5e6e7e8e9eaebecedeeeff0f1f2f3f4f5f6f7f8f9fafbfcfdfeff504b0102140314000000000083182250527e086f5802000058020000050000000000000000000000800100000000612e747874504b010214031400000000000539a652738c0529000100000001000009000000000000000000000080017b0200006469722f622e62696e504b050600000000020002006a000000a20300000000') + +# zlib: decompress what CPython's zlib produced, and round-trip our own +print(zlib.decompress(ZL) == T, zlib.decompress(RAW, -15) == T, zlib.decompress(GZ, 31) == T, + zlib.decompress(GZ, 47) == T, zlib.decompress(ZL, 47) == T) +for level in (0, 1, 6, 9, -1): + c = zlib.compress(T, level) + print("level", level, zlib.decompress(c) == T, c[:1].hex(), len(c) < len(T) or level == 0) +print(hex(zlib.crc32(T)), hex(zlib.adler32(T)), zlib.crc32(b"abc", zlib.crc32(b"xyz")), + zlib.adler32(b""), zlib.crc32(b"")) +d = zlib.decompressobj(zdict=b"hello compression") +print("dict", d.decompress(DICT) == T, d.eof) + +# streaming, max_length, unused data +c = zlib.compressobj(9, zlib.DEFLATED, -15) +parts = [c.compress(T[i:i + 50]) for i in range(0, len(T), 50)] +parts.append(c.flush(zlib.Z_SYNC_FLUSH)) +parts.append(c.compress(b"tail")) +parts.append(c.flush()) +stream = b"".join(parts) +d = zlib.decompressobj(-15) +out = b"" +for i in range(0, len(stream), 7): + out += d.decompress(stream[i:i + 7]) +print("stream", out == T + b"tail", d.eof) +d = zlib.decompressobj() +first = d.decompress(ZL + b"extra", 100) +print("max_length", len(first), len(d.unconsumed_tail) > 0, d.eof) +rest = d.decompress(d.unconsumed_tail) +print("rest", first + rest == T, d.eof, d.unused_data) +try: + zlib.decompress(b"not zlib data") +except zlib.error as e: + print("error", e) +print("@L41", flush=True) +try: + zlib.decompress(ZL[:20]) +except zlib.error as e: + print("error", e) +print("@L45", flush=True) +print(zlib.MAX_WBITS, zlib.Z_BEST_COMPRESSION, zlib.DEFLATED) + +print("@L47", flush=True) +# gzip +print("@L48", flush=True) +print("gzip", gzip.decompress(GZ) == T, gzip.compress(T, mtime=0)[:10].hex(), + gzip.compress(T, 1, mtime=5)[:10].hex(), gzip.decompress(gzip.compress(T)) == T) +print("@L50", flush=True) +print("members", gzip.decompress(GZ + gzip.compress(b"!", mtime=0)) == T + b"!") +print("@L51", flush=True) +os.makedirs("gz", exist_ok=True) +print("@L52", flush=True) +with gzip.open("gz/f.txt.gz", "wt", encoding="utf-8") as f: + f.write("line one\nline two\n") +print("@L54", flush=True) +with gzip.open("gz/f.txt.gz", "rt", encoding="utf-8") as f: + print("text", f.readlines()) +print("@L56", flush=True) +with gzip.open("gz/f.txt.gz", "rb") as f: + print("binary", f.read(4), f.read()) +print("@L58", flush=True) +with open("gz/f.txt.gz", "rb") as f: + raw = f.read() +print("@L60", flush=True) +print("header", raw[:4].hex(), raw[10:16]) +buf = io.BytesIO() +with gzip.GzipFile(fileobj=buf, mode="wb", mtime=0) as g: + g.write(b"abc") + g.write(memoryview(b"def")) +print("fileobj", buf.getvalue()[:10].hex(), gzip.decompress(buf.getvalue())) +try: + gzip.decompress(b"plain") +except gzip.BadGzipFile as e: + print("bad", e) +try: + gzip.decompress(GZ[:-3]) +except EOFError as e: + print("eof", e) + +# zipfile: read CPython's archive +z = zipfile.ZipFile(io.BytesIO(ZIP)) +print(z.namelist(), [i.date_time for i in z.infolist()], [i.compress_type for i in z.infolist()]) +print(z.read("a.txt") == T, z.read("dir/b.bin") == bytes(range(256)), z.testzip()) +info = z.getinfo("a.txt") +print(info.file_size, hex(info.CRC), info.is_dir()) +with z.open("dir/b.bin") as f: + print(f.read(3)) +try: + z.getinfo("missing") +except KeyError as e: + print("KeyError", e) +z.close() + +# write, append and extract +with zipfile.ZipFile("gz/out.zip", "w", zipfile.ZIP_DEFLATED) as z: + z.writestr("x.txt", "text " * 50) + z.writestr(zipfile.ZipInfo("stored.bin", (2022, 2, 3, 4, 5, 6)), b"\x00\x01", zipfile.ZIP_STORED) + with z.open("w.txt", "w") as w: + w.write(b"written ") + w.write(b"through open") + z.mkdir("empty") + z.write("gz/f.txt.gz", "nested/f.gz") + z.comment = b"a comment" +with zipfile.ZipFile("gz/out.zip", "a") as z: + z.writestr("appended.txt", b"more") +print("is_zipfile", zipfile.is_zipfile("gz/out.zip"), zipfile.is_zipfile("gz/f.txt.gz")) +with zipfile.ZipFile("gz/out.zip") as z: + print(z.namelist(), z.comment) + print(z.read("x.txt") == b"text " * 50, z.read("w.txt"), z.read("appended.txt"), z.read("nested/f.gz") == raw) + print([(i.filename, i.compress_type, i.is_dir()) for i in z.infolist()]) + print(z.getinfo("stored.bin").date_time, z.getinfo("stored.bin").compress_size) + z.extractall("gz/ex") + print(sorted(os.listdir("gz/ex")), sorted(os.listdir("gz/ex/nested")), os.path.isdir("gz/ex/empty")) + p = zipfile.Path(z) + print(sorted(c.name for c in p.iterdir()), (p / "w.txt").read_text(), (p / "nested").is_dir()) +with open("gz/ex/w.txt") as f: + print(f.read()) +try: + zipfile.ZipFile(io.BytesIO(b"nope")) +except zipfile.BadZipFile as e: + print("BadZipFile", e) +try: + zipfile.ZipFile(io.BytesIO(), "w", zipfile.ZIP_LZMA + 100) +except NotImplementedError as e: + print("NotImplementedError", e) diff --git a/scripts/python-bench/kernels/zz_insert.py b/scripts/python-bench/kernels/zz_insert.py new file mode 100644 index 00000000000..8bc3013bd6d --- /dev/null +++ b/scripts/python-bench/kernels/zz_insert.py @@ -0,0 +1,13 @@ +import sqlite3 +from _harness import measure + +def work(n): + c = sqlite3.connect(":memory:") + c.execute("CREATE TABLE responses (id TEXT PRIMARY KEY, model TEXT, prompt TEXT)") + t = 0 + with c: + for i in range(n): + t += c.execute("INSERT INTO [responses] ([id], [model], [prompt]) VALUES (?, ?, ?)", ["r%d" % i, "echo", "p"]).lastrowid + return t + +measure("zz_insert", work, 20000, 5) diff --git a/scripts/python-bench/kernels/zz_lam.py b/scripts/python-bench/kernels/zz_lam.py new file mode 100644 index 00000000000..59acafb12d7 --- /dev/null +++ b/scripts/python-bench/kernels/zz_lam.py @@ -0,0 +1,42 @@ +import time + + +def p_inline(n): + t = 0 + for i in range(n): + t += (i & 15) * 3 + return t + + +def p_lambda(n): + t = 0 + for i in range(n): + t += (lambda x, y: x * y)(i & 15, 3) + return t + + +def p_lambda1(n): + t = 0 + for i in range(n): + t += (lambda x: x)(i) + return t + + +def p_and(n): + t = 0 + for i in range(n): + t += i & 15 + return t + + +PARTS = [("inline", p_inline), ("lambda", p_lambda), ("lambda1", p_lambda1), ("and", p_and)] +N = 400000 +for name, f in PARTS: + best = None + for _ in range(7): + t0 = time.perf_counter() + f(N) + dt = time.perf_counter() - t0 + if best is None or dt < best: + best = dt + print("PART", name, int(best * 1000000)) diff --git a/scripts/python-bench/kernels/zz_nodb.py b/scripts/python-bench/kernels/zz_nodb.py new file mode 100644 index 00000000000..6e1135226d7 --- /dev/null +++ b/scripts/python-bench/kernels/zz_nodb.py @@ -0,0 +1,58 @@ +# SQLite the way sqlite-utils drives it when llm logs a reply: for each row +# the table's columns are read back (PRAGMA table_info), an INSERT is built +# as text from them, a JSON field is serialized, the row goes in with bound +# parameters and the statement's rows come back as tuples. In memory, so the +# disk's sync time stays out of it and only the Python side is measured. +import json +import sqlite3 + +from _harness import measure + + +def quote(name): + return "[" + name.replace("]", "]]") + "]" + + +COLS = {"conversations": ["id", "name", "model"], "responses": ["id", "model", "prompt", "system", "options_json", "response", "conversation_id", "duration_ms", "datetime_utc", "input_tokens", "output_tokens"]} +def columns(conn, table): + return [row for row in COLS[table]] + + +def insert(conn, table, record): + cols = columns(conn, table) + names = [k for k in record if k in cols] + sql = "INSERT INTO %s (%s) VALUES (%s)" % ( + quote(table), ", ".join(quote(n) for n in names), ", ".join("?" for _ in names)) + vals = [record[n] for n in names] + return len(sql) + len(vals) + + +def work(n): + conn = None + ("CREATE TABLE conversations (id TEXT PRIMARY KEY, name TEXT, model TEXT)") + ("CREATE TABLE responses (id TEXT PRIMARY KEY, model TEXT, prompt TEXT, " + "system TEXT, options_json TEXT, response TEXT, conversation_id TEXT, " + "duration_ms INTEGER, datetime_utc TEXT, input_tokens INTEGER, " + "output_tokens INTEGER)") + total = 0 + if True: + insert(conn, "conversations", {"id": "c1", "name": "bench", "model": "echo"}) + for i in range(n): + options = {"temperature": 0.5 + (i % 5) / 10.0, "stop": ["\n", "END"], "seed": i} + total += insert(conn, "responses", { + "id": "r%06d" % i, + "model": "echo", + "prompt": "prompt number %d about %s" % (i, "alpha bravo"[: 1 + i % 11]), + "system": None, + "options_json": json.dumps(options), + "response": "reply %d" % (i * 7), + "conversation_id": "c1", + "duration_ms": i % 97, + "datetime_utc": "2026-11-08T10:%02d:%02d" % (i // 60 % 60, i % 60), + "input_tokens": i % 13, + "output_tokens": i % 17, + }) + return total + + +measure("sqlite_nodb", work, 3000, 5) diff --git a/scripts/python-bench/kernels/zz_pragma.py b/scripts/python-bench/kernels/zz_pragma.py new file mode 100644 index 00000000000..3f0ea3c3d01 --- /dev/null +++ b/scripts/python-bench/kernels/zz_pragma.py @@ -0,0 +1,12 @@ +import sqlite3 +from _harness import measure + +def work(n): + c = sqlite3.connect(":memory:") + c.execute("CREATE TABLE responses (id TEXT PRIMARY KEY, model TEXT, prompt TEXT, system TEXT, options_json TEXT, response TEXT, conversation_id TEXT, duration_ms INTEGER, datetime_utc TEXT, input_tokens INTEGER, output_tokens INTEGER)") + t = 0 + for i in range(n): + t += len([r[1] for r in c.execute("PRAGMA table_info([responses])").fetchall()]) + return t + +measure("zz_pragma", work, 5000, 5) diff --git a/scripts/python-bench/kernels/zz_re.py b/scripts/python-bench/kernels/zz_re.py new file mode 100644 index 00000000000..d46a855a73b --- /dev/null +++ b/scripts/python-bench/kernels/zz_re.py @@ -0,0 +1,136 @@ +# Scratch: markdownify's and bs4's regex calls, alone, in ns per call. +import re +import time + +re_whitespace = re.compile(r'[\t ]+') +re_all_whitespace = re.compile(r'[\t \r\n]+') +re_newline_whitespace = re.compile(r'[\t \r\n]*[\r\n][\t \r\n]*') +re_make_convert_fn_name = re.compile(r'[\[\]:-]') +re_escape_misc_chars = re.compile(r'([]\\&<`[>~=+|])') +re_escape_misc_dash_sequences = re.compile(r'(\s|^)(-+(?:\s|$))') +re_line_with_content = re.compile(r'^(.*)', flags=re.MULTILINE) +re_extract_newlines = re.compile(r'^(\n*)((?:.*[^\n])?)(\n*)$', flags=re.DOTALL) +re_word = re.compile(r'\w+') + +SHORT = "Hello world" +MID = "The quick brown fox jumps over the lazy dog, and then\n runs away again." +NL = "\n \n" +TAG = "div" + +N = 100000 + + +def p_ws_short(n): + t = 0 + for _ in range(n): + t += len(re_whitespace.sub(' ', SHORT)) + return t + + +def p_ws_mid(n): + t = 0 + for _ in range(n): + t += len(re_whitespace.sub(' ', MID)) + return t + + +def p_allws_mid(n): + t = 0 + for _ in range(n): + t += len(re_all_whitespace.sub(' ', MID)) + return t + + +def p_nlws_mid(n): + t = 0 + for _ in range(n): + t += len(re_newline_whitespace.sub('\n', MID)) + return t + + +def p_nlws_nl(n): + t = 0 + for _ in range(n): + t += len(re_newline_whitespace.sub('\n', NL)) + return t + + +def p_fn_name(n): + t = 0 + for _ in range(n): + t += len(re_make_convert_fn_name.sub("_", TAG)) + return t + + +def p_escape_grp(n): + t = 0 + for _ in range(n): + t += len(re_escape_misc_chars.sub(r'\\\1', MID)) + return t + + +def p_dash(n): + t = 0 + for _ in range(n): + t += len(re_escape_misc_dash_sequences.sub(r'\1\\\2', MID)) + return t + + +def p_line_fn(n): + t = 0 + for _ in range(n): + t += len(re_line_with_content.sub(lambda m: '> ' + m.group(1), MID)) + return t + + +def p_extract_nl(n): + t = 0 + for _ in range(n): + t += len(re_extract_newlines.match(MID).groups()) + return t + + +def p_match_short(n): + t = 0 + for _ in range(n): + if re_word.match(SHORT): + t += 1 + return t + + +def p_search_mid(n): + t = 0 + for _ in range(n): + if re_newline_whitespace.search(MID): + t += 1 + return t + + +PARTS = [ + ("ws_short", p_ws_short), ("ws_mid", p_ws_mid), ("allws_mid", p_allws_mid), ("nlws_mid", p_nlws_mid), + ("nlws_nl", p_nlws_nl), ("fn_name", p_fn_name), ("escape_grp", p_escape_grp), ("dash", p_dash), + ("line_fn", p_line_fn), ("extract_nl", p_extract_nl), ("match_short", p_match_short), + ("search_mid", p_search_mid), +] + + +def main(): + import os + only = os.environ.get("CORE_PART") + if only: + f = dict(PARTS)[only] + for _ in range(400): + f(N) + return + for name, f in PARTS: + best = None + for _ in range(5): + t0 = time.perf_counter() + f(N) + dt = time.perf_counter() - t0 + if best is None or dt < best: + best = dt + print("PART %-12s %7.1f" % (name, best * 1e9 / N)) + + +main() diff --git a/scripts/python-bench/kernels/zz_recall.py b/scripts/python-bench/kernels/zz_recall.py new file mode 100644 index 00000000000..1f4a63192cf --- /dev/null +++ b/scripts/python-bench/kernels/zz_recall.py @@ -0,0 +1,117 @@ +# Scratch: the cost of one re call, taken apart. Each part adds one step to the previous. +import re +import time + +P_FAIL = re.compile(r'h(\d+)') +P_NOGROUP = re.compile(r'd') +P_GROUP = re.compile(r'(d)') +P_NAMED = re.compile(r'(?Pd)') +P_THREE = re.compile(r'^(\n*)((?:.*[^\n])?)(\n*)$', flags=re.DOTALL) +S = "div" +N = 200000 + + +def p_fail(n): + t = 0 + for _ in range(n): + if P_FAIL.match(S) is None: + t += 1 + return t + + +def p_ok_nogroup(n): + t = 0 + for _ in range(n): + if P_NOGROUP.match(S) is not None: + t += 1 + return t + + +def p_ok_group(n): + t = 0 + for _ in range(n): + if P_GROUP.match(S) is not None: + t += 1 + return t + + +def p_ok_named(n): + t = 0 + for _ in range(n): + if P_NAMED.match(S) is not None: + t += 1 + return t + + +def p_truth(n): + t = 0 + for _ in range(n): + if P_NOGROUP.match(S): + t += 1 + return t + + +def p_end(n): + t = 0 + for _ in range(n): + t += P_NOGROUP.match(S).end() + return t + + +def p_group1(n): + t = 0 + for _ in range(n): + t += len(P_GROUP.match(S).group(1)) + return t + + +def p_groups3(n): + t = 0 + for _ in range(n): + a, b, c = P_THREE.match("\nabc\n").groups() + t += len(a) + len(b) + len(c) + return t + + +def p_match3(n): + t = 0 + for _ in range(n): + if P_THREE.match("\nabc\n") is not None: + t += 1 + return t + + +def p_loop(n): + t = 0 + for _ in range(n): + if S is not None: + t += 1 + return t + + +def part(name, f, n, repeat): + best = None + r = None + for _ in range(repeat): + t0 = time.perf_counter() + r = f(n) + dt = time.perf_counter() - t0 + if best is None or dt < best: + best = dt + print("PART %-14s %7.1f ns/call %s" % (name, best * 1e9 / n, r)) + + +def main(): + part("loop", p_loop, N, 7) + part("fail", p_fail, N, 7) + part("ok_nogroup", p_ok_nogroup, N, 7) + part("ok_group", p_ok_group, N, 7) + part("ok_named", p_ok_named, N, 7) + part("truth", p_truth, N, 7) + part("end", p_end, N, 7) + part("group1", p_group1, N, 7) + part("match3", p_match3, N, 7) + part("groups3", p_groups3, N, 7) + + +main() diff --git a/scripts/python-bench/kernels/zz_rehot.py b/scripts/python-bench/kernels/zz_rehot.py new file mode 100644 index 00000000000..3963263f70f --- /dev/null +++ b/scripts/python-bench/kernels/zz_rehot.py @@ -0,0 +1,186 @@ +# Scratch: the regular expressions markitdown spends its time in, each timed alone. +# Patterns are copied from markdownify and CPython 3.14's html.parser. +import re +import time + +re_whitespace = re.compile(r'[\t ]+') +re_all_whitespace = re.compile(r'[\t \r\n]+') +re_newline_whitespace = re.compile(r'[\t \r\n]*[\r\n][\t \r\n]*') +re_extract_newlines = re.compile(r'^(\n*)((?:.*[^\n])?)(\n*)$', flags=re.DOTALL) +re_escape_misc_chars = re.compile(r'([]\\&<`[>~=+|])') +re_escape_misc_dash_sequences = re.compile(r'(\s|^)(-+(?:\s|$))') +re_escape_misc_hashes = re.compile(r'(\s|^)(#{1,6}(?:\s|$))') +re_escape_misc_list_items = re.compile(r'((?:\s|^)[0-9]{1,9})([.)](?:\s|$))') +re_html_heading = re.compile(r'h(\d+)') + +interesting_normal = re.compile('[&<]') +starttagopen = re.compile('<[a-zA-Z]') +tagfind_tolerant = re.compile(r'([a-zA-Z][^\t\n\r\f />]*)(?:[\t\n\r\f ]|/(?!>))*') +attrfind_tolerant = re.compile(r""" + ( + (?<=['"\t\n\r\f /])[^\t\n\r\f />][^\t\n\r\f /=>]* # attribute name + ) + ([\t\n\r\f ]*=[\t\n\r\f ]* # value indicator + ('[^']*' # LITA-enclosed value + |"[^"]*" # LIT-enclosed value + |(?!['"])[^>\t\n\r\f ]* # bare value + ) + )? + (?:[\t\n\r\f ]|/(?!>))* # possibly followed by a space +""", re.VERBOSE) +locatetagend = re.compile(r""" + [a-zA-Z][^\t\n\r\f />]* # tag name + [\t\n\r\f /]* # optional whitespace before attribute name + (?:(?<=['"\t\n\r\f /])[^\t\n\r\f />][^\t\n\r\f /=>]* # attribute name + (?:[\t\n\r\f ]*=[\t\n\r\f ]* # value indicator + (?:'[^']*' # LITA-enclosed value + |"[^"]*" # LIT-enclosed value + |(?!['"])[^>\t\n\r\f ]* # bare value + ) + )? + [\t\n\r\f /]* # possibly followed by a space + )* + >? +""", re.VERBOSE) + +WORDS = ["the", "quick", "brown", "fox", "jumps", "over", "lazy", "dog", "Wikipedia", + "article", "history", "1999", "-", "#", "3.", "a|b", "x=y", "[ref]", "free"] + + +def texts(): + out = [] + k = 0 + for i in range(400): + n = 1 + (i * 7) % 23 + ws = [] + for j in range(n): + ws.append(WORDS[k % len(WORDS)]) + k += 1 + s = " ".join(ws) + if i % 5 == 0: + s = "\n" + s + if i % 7 == 0: + s = s + "\n\n" + if i % 3 == 0: + s = s.replace(" ", " \t", 2) + out.append(s) + return out + + +def html_doc(): + parts = [] + for i in range(300): + parts.append('
link %d' + ' text & more s
\n' % (i, i, i, i, i, i)) + return "".join(parts) + + +TEXTS = texts() +HTML = html_doc() + + +def p_extract(n): + t = 0 + for _ in range(n): + for s in TEXTS: + a, b, c = re_extract_newlines.match(s).groups() + t += len(a) + len(b) + len(c) + return t + + +def p_ws(n): + t = 0 + for _ in range(n): + for s in TEXTS: + x = re_all_whitespace.sub(' ', s) + y = re_newline_whitespace.sub('\n', s) + y = re_whitespace.sub(' ', y) + t += len(x) + len(y) + return t + + +def p_escape(n): + t = 0 + for _ in range(n): + for s in TEXTS: + x = re_escape_misc_chars.sub(r'\\\1', s) + x = re_escape_misc_dash_sequences.sub(r'\1\\\2', x) + x = re_escape_misc_hashes.sub(r'\1\\\2', x) + x = re_escape_misc_list_items.sub(r'\1\\\2', x) + t += len(x) + return t + + +def p_heading(n): + t = 0 + names = ["div", "h1", "span", "a", "h3", "p", "li", "td"] + for _ in range(n): + for i in range(400): + if re_html_heading.match(names[i & 7]) is not None: + t += 1 + return t + + +def p_scan(n): + # html.parser's goahead: find the next markup, then classify it. + t = 0 + raw = HTML + for _ in range(n): + i = 0 + end = len(raw) + while i < end: + m = interesting_normal.search(raw, i) + j = m.start() if m else end + if i < j: + t += j - i + i = j + if i == end: + break + if raw.startswith('<', i): + if starttagopen.match(raw, i): + m = locatetagend.match(raw, i + 1) + k = m.end() + tm = tagfind_tolerant.match(raw, i + 1) + p = tm.end() + while p < k: + am = attrfind_tolerant.match(raw, p) + if not am: + break + t += len(am.group(1)) + p = am.end() + i = k + else: + i = raw.find('>', i) + 1 + else: + i += 1 + return t + + +def part(name, f, n, repeat): + best = None + r = None + for _ in range(repeat): + t0 = time.perf_counter() + r = f(n) + dt = time.perf_counter() - t0 + if best is None or dt < best: + best = dt + print("PART", name, int(best * 1000000), r) + + +def main(): + import os + only = os.environ.get("CORE_PART") + if only: + f = {"extract": p_extract, "ws": p_ws, "escape": p_escape, "heading": p_heading, "scan": p_scan}[only] + for _ in range(100000): + f(1) + return + part("extract_newlines", p_extract, 20, 7) + part("whitespace_subs", p_ws, 20, 7) + part("escape_subs", p_escape, 20, 7) + part("heading_match", p_heading, 50, 7) + part("html_scan", p_scan, 10, 7) + + +main() diff --git a/scripts/python-bench/kernels/zz_shapes.py b/scripts/python-bench/kernels/zz_shapes.py new file mode 100644 index 00000000000..5c02c1e655e --- /dev/null +++ b/scripts/python-bench/kernels/zz_shapes.py @@ -0,0 +1,157 @@ +# Scratch: the hot shapes of the MarkItDown PDF and HTML paths, alone, in ns per operation. +import logging +import time + +log = logging.getLogger("shapes") + + +class Ref: + def __init__(self, objid): + self.objid = objid + + def resolve(self): + return self.objid + + +class Tag: + def __init__(self, name, attrs): + self.name = name + self.attrs = attrs + + def match(self, other, _known_rules=False): + return _known_rules and other.name == self.name + + +def resolve_all(x, depth=0): + if isinstance(x, Ref): + return resolve_all(x.resolve(), depth + 1) + elif isinstance(x, (list, tuple)): + return type(x)(resolve_all(v, depth + 1) for v in x) + elif isinstance(x, dict): + return {k: resolve_all(v, depth + 1) for k, v in x.items()} + return x + + +N = 200000 +OBJ = {"Type": "Font", "W": [1, 2, Ref(3), (4, 5)], "D": Ref({"a": 1})} +ATTRS = {"stroke": True, "fill": None, "linewidth": 1.0, "dash": None, "x0": 3.5} +TAGS = [Tag("a", {}), Tag("div", {}), Tag("a", {}), Tag("span", {})] * 5 +PROBE = Tag("a", {}) + + +def p_resolve_all(n): + t = 0 + for _ in range(n // 20): + t += len(resolve_all(OBJ)) + return t + + +def p_isinst_tuple(n): + t = 0 + x = 3.5 + for _ in range(n): + if isinstance(x, (int, float)): + t += 1 + return t + + +def p_type_call_genexpr(n): + t = 0 + x = (1, 2, 3, 4) + for _ in range(n // 4): + t += len(type(x)(v for v in x)) + return t + + +def p_dictcomp(n): + t = 0 + for _ in range(n // 5): + t += len({k: v for k, v in ATTRS.items()}) + return t + + +def p_dict_filter_map(n): + t = 0 + for _ in range(n // 5): + t += len(dict(filter(lambda kv: kv[1] is not None, map(lambda kv: (kv[0], kv[1]), ATTRS.items())))) + return t + + +def p_gen_kwmethod(n): + t = 0 + for _ in range(n // 20): + t += sum(1 for i in TAGS if PROBE.match(i, _known_rules=True)) + return t + + +def p_log_debug(n): + t = 0 + for i in range(n): + log.debug("token %r", i) + t += 1 + return t + + +def p_bytes_slice(n): + t = 0 + b = b"/Name 12 0 R << /Type /Page >> stream" + for i in range(n): + if b[i & 15:(i & 15) + 1] == b"/": + t += 1 + return t + + +def p_bytes_find(n): + t = 0 + b = b"/Name 12 0 R << /Type /Page >> stream" + for _ in range(n): + t += b.find(b">>", 3) + return t + + +def p_float_mul(n): + t = 0.0 + a, b, c, d, e, f = 1.0, 0.0, 0.0, 1.0, 3.0, 4.0 + for i in range(n): + x = float(i & 7) + t += a * x + c * x + e + return t + + +def p_tuple_build(n): + t = 0 + for i in range(n): + r = (i, i + 1, i + 2, i + 3) + t += r[2] + return t + + +PARTS = [ + ("resolve_all", p_resolve_all), ("isinst_tuple", p_isinst_tuple), + ("type_genexpr", p_type_call_genexpr), ("dictcomp", p_dictcomp), + ("dict_filtmap", p_dict_filter_map), ("gen_kwmeth", p_gen_kwmethod), + ("log_debug", p_log_debug), ("bytes_slice", p_bytes_slice), ("bytes_find", p_bytes_find), + ("float_mul", p_float_mul), ("tuple_build", p_tuple_build), +] + + +def main(): + import os + only = os.environ.get("CORE_PART") + if only: + f = dict(PARTS)[only] + for _ in range(400): + f(N) + return + for name, f in PARTS: + best = None + for _ in range(5): + t0 = time.perf_counter() + f(N) + dt = time.perf_counter() - t0 + if best is None or dt < best: + best = dt + print("PART %-12s %7.1f" % (name, best * 1e9 / N)) + + +main() diff --git a/scripts/python-bench/kernels/zz_sqlconf.py b/scripts/python-bench/kernels/zz_sqlconf.py new file mode 100644 index 00000000000..107acf17fc3 --- /dev/null +++ b/scripts/python-bench/kernels/zz_sqlconf.py @@ -0,0 +1,173 @@ +import contextlib +import hashlib +import io +from _harness import measure + +def _body(): + import datetime + import sqlite3 + + con = sqlite3.connect(":memory:") + cur = con.cursor() + cur.execute("CREATE TABLE movie(id INTEGER PRIMARY KEY, title TEXT NOT NULL UNIQUE, year INTEGER, score REAL, poster BLOB)") + print(cur.description, cur.rowcount) + cur.execute("INSERT INTO movie(title, year, score) VALUES (?, ?, ?)", ("Monty Python", 1975, 8.2)) + print("lastrowid", cur.lastrowid, "rowcount", cur.rowcount, "in_tx", con.in_transaction) + data = [("And Now for Something", 1971, 7.5), ("Life of Brian", 1979, 8.0), ("Meaning of Life", 1983, 7.6)] + cur.executemany("INSERT INTO movie(title, year, score) VALUES (?, ?, ?)", data) + print("many rowcount", cur.rowcount) + con.commit() + print("after commit in_tx", con.in_transaction, "total", con.total_changes) + + for row in cur.execute("SELECT id, title, year, score FROM movie ORDER BY year"): + print(row, [type(v).__name__ for v in row]) + print([d[0] for d in cur.description]) + + cur.execute("SELECT title FROM movie WHERE year > :y AND score >= :s", {"y": 1974, "s": 7.9}) + print(cur.fetchall()) + cur.execute("SELECT ?2, ?1", ("a", "b")) + print(cur.fetchone()) + cur.execute("SELECT count(*), max(score), min(title) FROM movie") + print(cur.fetchone()) + print(cur.fetchone()) + + cur.execute("UPDATE movie SET score = score + 0.5 WHERE year < ?", (1980,)) + print("updated", cur.rowcount) + con.rollback() + print(con.execute("SELECT score FROM movie WHERE year = 1975").fetchone()) + + con.execute("UPDATE movie SET poster = ? WHERE id = 1", (b"\x00\x01\xff",)) + con.execute("INSERT INTO movie(title, year) VALUES ('Untitled', NULL)") + for r in con.execute("SELECT poster, year, score FROM movie WHERE id IN (1, 5) ORDER BY id"): + print(r) + + try: + con.execute("INSERT INTO movie(title) VALUES (?)", ("Life of Brian",)) + except sqlite3.IntegrityError as e: + print("IntegrityError", e) + try: + con.execute("SELECT * FROM no_such_table") + except sqlite3.OperationalError as e: + print("OperationalError", e) + try: + con.execute("SELECT ?", (1, 2)) + except sqlite3.ProgrammingError as e: + print("ProgrammingError", e) + try: + con.execute("SELECT 1; SELECT 2") + except sqlite3.ProgrammingError as e: + print("ProgrammingError", e) + try: + con.execute("SELECT :a", {"b": 1}) + except sqlite3.ProgrammingError as e: + print("ProgrammingError", e) + print(issubclass(sqlite3.IntegrityError, sqlite3.DatabaseError), issubclass(sqlite3.Error, Exception)) + con.commit() + + con.row_factory = sqlite3.Row + r = con.execute("SELECT id, title AS name FROM movie WHERE id = 2").fetchone() + print(r["name"], r["NAME"], r[0], r.keys(), tuple(r), len(r)) + con.row_factory = None + + con.executescript(""" + CREATE TABLE log(id INTEGER PRIMARY KEY AUTOINCREMENT, msg TEXT); + -- a comment; with a semicolon + INSERT INTO log(msg) VALUES ('one; two'); + INSERT INTO log(msg) VALUES ('three'); + CREATE TRIGGER t AFTER INSERT ON log BEGIN UPDATE log SET msg = upper(msg) WHERE id = new.id; END; + INSERT INTO log(msg) VALUES ('four'); + """) + print(con.execute("SELECT msg FROM log ORDER BY id").fetchall()) + + with con: + con.execute("INSERT INTO log(msg) VALUES ('ctx')") + try: + with con: + con.execute("INSERT INTO log(msg) VALUES ('lost')") + raise ValueError("boom") + except ValueError: + pass + print(con.execute("SELECT count(*) FROM log").fetchone()) + + + class Point: + def __init__(self, x, y): + self.x, self.y = x, y + + + sqlite3.register_adapter(Point, lambda p: "%f;%f" % (p.x, p.y)) + sqlite3.register_converter("point", lambda b: tuple(float(v) for v in b.split(b";"))) + con2 = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_DECLTYPES | sqlite3.PARSE_COLNAMES) + con2.execute("CREATE TABLE p(pt point, d date, ts timestamp)") + con2.execute("INSERT INTO p VALUES (?, ?, ?)", (Point(1, 2.5), datetime.date(2024, 2, 29), + datetime.datetime(2024, 1, 2, 3, 4, 5, 600))) + print(con2.execute("SELECT pt, d, ts FROM p").fetchone()) + print(con2.execute('SELECT pt AS "p [point]" FROM p').fetchone()) + print(con2.execute("SELECT pt FROM p").description[0][0]) + con2.close() + try: + con2.execute("SELECT 1") + except sqlite3.ProgrammingError as e: + print("ProgrammingError", e) + + con.text_factory = bytes + print(con.execute("SELECT 'abc'").fetchone()) + con.text_factory = str + + for line in con.iterdump(): + if "movie" in line or "log" in line: + print(line) + print(sqlite3.complete_statement("SELECT 1;"), sqlite3.complete_statement("SELECT 1")) + + con3 = sqlite3.connect(":memory:", autocommit=False) + print("autocommit False in_tx", con3.in_transaction) + con3.execute("CREATE TABLE a(x)") + con3.commit() + print("still", con3.in_transaction) + con3.close() + con4 = sqlite3.connect(":memory:", isolation_level=None) + con4.execute("CREATE TABLE a(x)") + con4.execute("INSERT INTO a VALUES (1)") + print("isolation None in_tx", con4.in_transaction) + con4.execute("BEGIN") + print("explicit", con4.in_transaction) + con4.execute("INSERT INTO a VALUES (2)") + con4.execute("ROLLBACK") + print(con4.execute("SELECT * FROM a").fetchall()) + print(sqlite3.paramstyle, sqlite3.apilevel) + con.close() + + # User-defined functions, as sqlite-utils and llm register them. + fconn = sqlite3.connect(":memory:") + fconn.create_function("plus_one", 1, lambda v: None if v is None else v + 1) + fconn.create_function("joined", -1, lambda *a: "|".join(str(x) for x in a)) + fconn.create_function("blob_len", 1, lambda b: len(b)) + print(fconn.execute("SELECT plus_one(41), plus_one(NULL), plus_one(1.5)").fetchone()) + print(fconn.execute("SELECT joined(1, 'two', 3.0)").fetchone()) + print(fconn.execute("SELECT blob_len(?)", (b"abcd",)).fetchone()) + fconn.execute("CREATE TABLE t (v INTEGER)") + fconn.executemany("INSERT INTO t VALUES (?)", [(1,), (2,), (3,)]) + print(fconn.execute("SELECT sum(plus_one(v)) FROM t").fetchone()) + def boom(v): + raise ValueError("no") + fconn.create_function("boom", 1, boom) + try: + fconn.execute("SELECT boom(1)").fetchone() + except sqlite3.OperationalError as e: + print("error:", e) + fconn.close() + +_out = [] + +def work(n): + if not _out: + buf = io.StringIO() + with contextlib.redirect_stdout(buf): + _body() + text = buf.getvalue() + import sys + sys.stderr.write("<<>>\n") + _out.append("%d %s" % (len(text), hashlib.sha256(text.encode("utf-8")).hexdigest())) + return _out[0] + +measure("zz_sqlconf", work, 1, 1) diff --git a/scripts/python-bench/kernels/zz_sqlconf_body.py b/scripts/python-bench/kernels/zz_sqlconf_body.py new file mode 100644 index 00000000000..cce350389c9 --- /dev/null +++ b/scripts/python-bench/kernels/zz_sqlconf_body.py @@ -0,0 +1,152 @@ +import datetime +import sqlite3 + +con = sqlite3.connect(":memory:") +cur = con.cursor() +cur.execute("CREATE TABLE movie(id INTEGER PRIMARY KEY, title TEXT NOT NULL UNIQUE, year INTEGER, score REAL, poster BLOB)") +print(cur.description, cur.rowcount) +cur.execute("INSERT INTO movie(title, year, score) VALUES (?, ?, ?)", ("Monty Python", 1975, 8.2)) +print("lastrowid", cur.lastrowid, "rowcount", cur.rowcount, "in_tx", con.in_transaction) +data = [("And Now for Something", 1971, 7.5), ("Life of Brian", 1979, 8.0), ("Meaning of Life", 1983, 7.6)] +cur.executemany("INSERT INTO movie(title, year, score) VALUES (?, ?, ?)", data) +print("many rowcount", cur.rowcount) +con.commit() +print("after commit in_tx", con.in_transaction, "total", con.total_changes) + +for row in cur.execute("SELECT id, title, year, score FROM movie ORDER BY year"): + print(row, [type(v).__name__ for v in row]) +print([d[0] for d in cur.description]) + +cur.execute("SELECT title FROM movie WHERE year > :y AND score >= :s", {"y": 1974, "s": 7.9}) +print(cur.fetchall()) +cur.execute("SELECT ?2, ?1", ("a", "b")) +print(cur.fetchone()) +cur.execute("SELECT count(*), max(score), min(title) FROM movie") +print(cur.fetchone()) +print(cur.fetchone()) + +cur.execute("UPDATE movie SET score = score + 0.5 WHERE year < ?", (1980,)) +print("updated", cur.rowcount) +con.rollback() +print(con.execute("SELECT score FROM movie WHERE year = 1975").fetchone()) + +con.execute("UPDATE movie SET poster = ? WHERE id = 1", (b"\x00\x01\xff",)) +con.execute("INSERT INTO movie(title, year) VALUES ('Untitled', NULL)") +for r in con.execute("SELECT poster, year, score FROM movie WHERE id IN (1, 5) ORDER BY id"): + print(r) + +try: + con.execute("INSERT INTO movie(title) VALUES (?)", ("Life of Brian",)) +except sqlite3.IntegrityError as e: + print("IntegrityError", e) +try: + con.execute("SELECT * FROM no_such_table") +except sqlite3.OperationalError as e: + print("OperationalError", e) +try: + con.execute("SELECT ?", (1, 2)) +except sqlite3.ProgrammingError as e: + print("ProgrammingError", e) +try: + con.execute("SELECT 1; SELECT 2") +except sqlite3.ProgrammingError as e: + print("ProgrammingError", e) +try: + con.execute("SELECT :a", {"b": 1}) +except sqlite3.ProgrammingError as e: + print("ProgrammingError", e) +print(issubclass(sqlite3.IntegrityError, sqlite3.DatabaseError), issubclass(sqlite3.Error, Exception)) +con.commit() + +con.row_factory = sqlite3.Row +r = con.execute("SELECT id, title AS name FROM movie WHERE id = 2").fetchone() +print(r["name"], r["NAME"], r[0], r.keys(), tuple(r), len(r)) +con.row_factory = None + +con.executescript(""" + CREATE TABLE log(id INTEGER PRIMARY KEY AUTOINCREMENT, msg TEXT); + -- a comment; with a semicolon + INSERT INTO log(msg) VALUES ('one; two'); + INSERT INTO log(msg) VALUES ('three'); + CREATE TRIGGER t AFTER INSERT ON log BEGIN UPDATE log SET msg = upper(msg) WHERE id = new.id; END; + INSERT INTO log(msg) VALUES ('four'); +""") +print(con.execute("SELECT msg FROM log ORDER BY id").fetchall()) + +with con: + con.execute("INSERT INTO log(msg) VALUES ('ctx')") +try: + with con: + con.execute("INSERT INTO log(msg) VALUES ('lost')") + raise ValueError("boom") +except ValueError: + pass +print(con.execute("SELECT count(*) FROM log").fetchone()) + + +class Point: + def __init__(self, x, y): + self.x, self.y = x, y + + +sqlite3.register_adapter(Point, lambda p: "%f;%f" % (p.x, p.y)) +sqlite3.register_converter("point", lambda b: tuple(float(v) for v in b.split(b";"))) +con2 = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_DECLTYPES | sqlite3.PARSE_COLNAMES) +con2.execute("CREATE TABLE p(pt point, d date, ts timestamp)") +con2.execute("INSERT INTO p VALUES (?, ?, ?)", (Point(1, 2.5), datetime.date(2024, 2, 29), + datetime.datetime(2024, 1, 2, 3, 4, 5, 600))) +print(con2.execute("SELECT pt, d, ts FROM p").fetchone()) +print(con2.execute('SELECT pt AS "p [point]" FROM p').fetchone()) +print(con2.execute("SELECT pt FROM p").description[0][0]) +con2.close() +try: + con2.execute("SELECT 1") +except sqlite3.ProgrammingError as e: + print("ProgrammingError", e) + +con.text_factory = bytes +print(con.execute("SELECT 'abc'").fetchone()) +con.text_factory = str + +for line in con.iterdump(): + if "movie" in line or "log" in line: + print(line) +print(sqlite3.complete_statement("SELECT 1;"), sqlite3.complete_statement("SELECT 1")) + +con3 = sqlite3.connect(":memory:", autocommit=False) +print("autocommit False in_tx", con3.in_transaction) +con3.execute("CREATE TABLE a(x)") +con3.commit() +print("still", con3.in_transaction) +con3.close() +con4 = sqlite3.connect(":memory:", isolation_level=None) +con4.execute("CREATE TABLE a(x)") +con4.execute("INSERT INTO a VALUES (1)") +print("isolation None in_tx", con4.in_transaction) +con4.execute("BEGIN") +print("explicit", con4.in_transaction) +con4.execute("INSERT INTO a VALUES (2)") +con4.execute("ROLLBACK") +print(con4.execute("SELECT * FROM a").fetchall()) +print(sqlite3.paramstyle, sqlite3.apilevel) +con.close() + +# User-defined functions, as sqlite-utils and llm register them. +fconn = sqlite3.connect(":memory:") +fconn.create_function("plus_one", 1, lambda v: None if v is None else v + 1) +fconn.create_function("joined", -1, lambda *a: "|".join(str(x) for x in a)) +fconn.create_function("blob_len", 1, lambda b: len(b)) +print(fconn.execute("SELECT plus_one(41), plus_one(NULL), plus_one(1.5)").fetchone()) +print(fconn.execute("SELECT joined(1, 'two', 3.0)").fetchone()) +print(fconn.execute("SELECT blob_len(?)", (b"abcd",)).fetchone()) +fconn.execute("CREATE TABLE t (v INTEGER)") +fconn.executemany("INSERT INTO t VALUES (?)", [(1,), (2,), (3,)]) +print(fconn.execute("SELECT sum(plus_one(v)) FROM t").fetchone()) +def boom(v): + raise ValueError("no") +fconn.create_function("boom", 1, boom) +try: + fconn.execute("SELECT boom(1)").fetchone() +except sqlite3.OperationalError as e: + print("error:", e) +fconn.close() diff --git a/scripts/python-bench/run_bench.py b/scripts/python-bench/run_bench.py index a52095afca2..e3f3dab0ba9 100644 --- a/scripts/python-bench/run_bench.py +++ b/scripts/python-bench/run_bench.py @@ -44,10 +44,10 @@ def kernels(): if f.endswith(".py") and not f.startswith("_")) -def timed(cmd, cwd=None): +def timed(cmd, cwd=None, env=None): """Runs cmd and answers (stdout, wall seconds).""" start = time.perf_counter() - proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + proc = subprocess.Popen(cmd, cwd=cwd, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = proc.communicate() wall = time.perf_counter() - start if proc.returncode != 0: @@ -55,14 +55,14 @@ def timed(cmd, cwd=None): return out.decode("utf-8"), wall -def peak_rss(cmd, cwd=None): +def peak_rss(cmd, cwd=None, env=None): """Peak resident set of one run of cmd, measured in a child of its own so that RUSAGE_CHILDREN holds that run and nothing else.""" probe = ("import resource,subprocess,sys;" "subprocess.run(sys.argv[1:],stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,check=True);" "r=resource.getrusage(resource.RUSAGE_CHILDREN).ru_maxrss;" "print(r if sys.platform=='darwin' else r*1024)") - out = subprocess.run([sys.executable, "-c", probe] + cmd, cwd=cwd, check=True, + out = subprocess.run([sys.executable, "-c", probe] + cmd, cwd=cwd, env=env, check=True, stdout=subprocess.PIPE).stdout return int(out.strip()) diff --git a/scripts/python/gen-unicodedata.py b/scripts/python/gen-unicodedata.py new file mode 100644 index 00000000000..9d8bff22bd0 --- /dev/null +++ b/scripts/python/gen-unicodedata.py @@ -0,0 +1,140 @@ +#!/usr/bin/env python3 +# Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. +# Licensed under the GNU General Public License version 2 with the Classpath +# exception, as the rest of the Codename One Python runtime. +"""Regenerate the data section of the runtime's unicodedata module. + +The source of truth is the host CPython's own unicodedata module (which is +built from the Unicode Character Database), so run this with the CPython +whose Unicode version the runtime should report: + + python3 scripts/python/gen-unicodedata.py + +It rewrites everything between the BEGIN/END GENERATED DATA markers of +maven/python-transpiler/src/main/resources/com/codename1/python/stdlib/unicodedata.py. +""" + +import base64 +import os +import re +import unicodedata as u +import zlib + +ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +TARGET = os.path.join(ROOT, "maven", "python-transpiler", "src", "main", "resources", + "com", "codename1", "python", "stdlib", "unicodedata.py") +CHUNK = 30000 +MAX = 0x110000 +SBASE, SCOUNT = 0xAC00, 11172 + + +def varint(out, v): + while v >= 128: + out.append((v & 127) | 128) + v >>= 7 + out.append(v) + + +def emit(lines, name, data): + text = base64.b64encode(zlib.compress(bytes(data), 9)).decode("ascii") + lines.append(name + " = (") + for i in range(0, len(text), CHUNK): + lines.append(' "' + text[i:i + CHUNK] + '",') + lines.append(")") + + +def main(): + lines = ["# Data derived from the Unicode Character Database, Unicode " + u.unidata_version + ",", + "# copyright Unicode, Inc., Unicode License v3. Generated by", + "# scripts/python/gen-unicodedata.py from CPython's unicodedata.", + "unidata_version = " + repr(u.unidata_version)] + + # properties as runs of records + recs, rec_ids, runs = [], {}, bytearray() + prev, length = None, 0 + for cp in range(MAX): + c = chr(cp) + r = (u.category(c), u.bidirectional(c), u.combining(c), u.mirrored(c), u.east_asian_width(c)) + if r != prev: + if prev is not None: + varint(runs, length) + varint(runs, rec_ids[prev]) + if r not in rec_ids: + rec_ids[r] = len(recs) + recs.append(r) + prev, length = r, 0 + length += 1 + varint(runs, length) + varint(runs, rec_ids[prev]) + emit(lines, "_D_RECORDS", "\n".join("%s,%s,%d,%d,%s" % r for r in recs).encode("ascii")) + emit(lines, "_D_RUNS", runs) + + # names: algorithmic ranges, then tokenized explicit names + ranges, named = [], [] + for cp in range(MAX): + n = u.name(chr(cp), None) + if n is None or SBASE <= cp < SBASE + SCOUNT: + continue + h = "%04X" % cp + if n.endswith("-" + h): + prefix = n[:-len(h)] + if ranges and ranges[-1][0] == prefix and ranges[-1][2] == cp - 1: + ranges[-1][2] = cp + else: + ranges.append([prefix, cp, cp]) + else: + named.append((cp, n)) + # front coding: one character (chr(48 + k)) for the k leading characters + # shared with the previous name, then the rest of the name + cps, text, last, prev = bytearray(), [], -1, "" + for cp, n in named: + varint(cps, cp - last) + last = cp + k = 0 + while k < len(n) and k < len(prev) and k < 60 and n[k] == prev[k]: + k += 1 + text.append(chr(48 + k) + n[k:]) + prev = n + emit(lines, "_D_NAMES", "\n".join(text).encode("ascii")) + emit(lines, "_D_NAME_CPS", cps) + lines.append("_NAME_RANGES = [") + for p, a, b in ranges: + lines.append(" (%r, 0x%X, 0x%X)," % (p, a, b)) + lines.append("]") + + # decompositions, numerics, composition exclusions + dec, num, excl, last, nlast = [], [], [], 0, 0 + for cp in range(MAX): + c = chr(cp) + d = "" if SBASE <= cp < SBASE + SCOUNT else u.decomposition(c) + if d: + dec.append("%X %s" % (cp - last, d)) + last = cp + parts = d.split(" ") + if not parts[0].startswith("<") and len(parts) == 2 and u.normalize("NFC", c) != c: + excl.append(cp) + nv = u.numeric(c, None) + if nv is not None: + de, di = u.decimal(c, None), u.digit(c, None) + num.append("%X:%s:%s:%r" % (cp - nlast, "" if de is None else de, "" if di is None else di, nv)) + nlast = cp + emit(lines, "_D_DECOMP", "\n".join(dec).encode("ascii")) + emit(lines, "_D_NUMERIC", "\n".join(num).encode("ascii")) + lines.append("_COMPOSITION_EXCLUSIONS = [") + for i in range(0, len(excl), 8): + lines.append(" " + ", ".join("0x%X" % x for x in excl[i:i + 8]) + ",") + lines.append("]") + + with open(TARGET, encoding="ascii") as f: + src = f.read() + begin, end = "# --- BEGIN GENERATED DATA ---\n", "# --- END GENERATED DATA ---\n" + a, b = src.index(begin) + len(begin), src.index(end) + src = src[:a] + "\n".join(lines) + "\n" + src[b:] + with open(TARGET, "w", encoding="ascii", newline="\n") as f: + f.write(src) + print("records=%d runs=%d names=%d ranges=%d decomp=%d numeric=%d excl=%d size=%d" + % (len(recs), len(runs), len(named), len(ranges), len(dec), len(num), len(excl), len(src))) + + +if __name__ == "__main__": + main() diff --git a/vm/ByteCodeTranslator/src/cn1_db_sqlite_impl.h b/vm/ByteCodeTranslator/src/cn1_db_sqlite_impl.h index 3ba260e6646..21aeda80e50 100644 --- a/vm/ByteCodeTranslator/src/cn1_db_sqlite_impl.h +++ b/vm/ByteCodeTranslator/src/cn1_db_sqlite_impl.h @@ -55,6 +55,10 @@ /* Generated by the translator; supplies __NEW_java_io_IOException and its constructor. Needed by * both branches below, so it sits above the gate. */ #include "java_io_IOException.h" +#include "java_lang_String.h" +#include "java_lang_Long.h" +#include "java_lang_Double.h" +#include "java_lang_Integer.h" /* * The engine builds its ciphers only when the translator emitted the marker below, so the keying @@ -177,6 +181,150 @@ static JAVA_OBJECT cn1DbBlobToByteArray(CODENAME_ONE_THREAD_STATE, const void* b return arr; } +/** Binds a java.lang.String read in place: no byte[] is made for it. Latin-1 storage that is all + * ASCII is already UTF-8; other Latin-1 storage is encoded into a temporary buffer; UTF-16 + * storage goes to sqlite3_bind_text16, in the machine's byte order, which is what that call + * reads. SQLITE_TRANSIENT has SQLite copy the text, so nothing here outlives the call. An empty + * string binds a non-null pointer: a null one would be SQL NULL. */ +/** Binds a String and answers SQLite's code; the throwing form below checks it. */ +static int cn1DbBindStringStatus(sqlite3_stmt* stmt, JAVA_INT index, JAVA_OBJECT value) { + int n; + int rc; + if (value == JAVA_NULL) { + return sqlite3_bind_null(stmt, index); + } + n = ((struct obj__java_lang_String*)value)->java_lang_String_count; + if (n == 0) { + rc = sqlite3_bind_text(stmt, index, "", 0, SQLITE_TRANSIENT); + } else if (cn1StrIsLatin1(value)) { + const unsigned char* p = (const unsigned char*)cn1StrChars(value); + int i = 0; + while (i < n && p[i] < 0x80) { + i++; + } + if (i == n) { + rc = sqlite3_bind_text(stmt, index, (const char*)p, n, SQLITE_TRANSIENT); + } else { + unsigned char* out = (unsigned char*)malloc((size_t)n * 2); + int o = i; + if (out == NULL) { + return SQLITE_NOMEM; + } + memcpy(out, p, (size_t)i); + for (; i < n; i++) { + if (p[i] < 0x80) { + out[o++] = p[i]; + } else { + out[o++] = (unsigned char)(0xC0 | (p[i] >> 6)); + out[o++] = (unsigned char)(0x80 | (p[i] & 0x3F)); + } + } + rc = sqlite3_bind_text(stmt, index, (const char*)out, o, SQLITE_TRANSIENT); + free(out); + } + } else { + rc = sqlite3_bind_text16(stmt, index, cn1StrChars(value), n * 2, SQLITE_TRANSIENT); + } + return rc; +} + +static void cn1DbBindString(CODENAME_ONE_THREAD_STATE, sqlite3_stmt* stmt, JAVA_INT index, JAVA_OBJECT value) { + cn1DbCheckBind(threadStateData, stmt, cn1DbBindStringStatus(stmt, index, value), index); +} + +/** Binds every element of `params` by its type and answers SQLite's code: SQLITE_OK, an engine + * failure, or CN1_DB_BIND_UNHANDLED for a type bound only on the Java side (Short, Boolean, + * anything that is bound by its toString), so the caller can take that path instead. The array + * is read in place. A box is read through its own accessor, which knows whether it is a tagged + * immediate; a String is any of its class twins. */ +#define CN1_DB_BIND_UNHANDLED (-2) +static int cn1DbBindAll(CODENAME_ONE_THREAD_STATE, sqlite3_stmt* stmt, JAVA_OBJECT params) { + JAVA_ARRAY arr = (JAVA_ARRAY)params; + JAVA_OBJECT* items = (JAVA_OBJECT*)CN1_ARRAY_DATA(arr); + int n = arr->length; + int i; + for (i = 0; i < n; i++) { + JAVA_OBJECT v = items[i]; + int rc; + struct clazz* cls; + if (v == JAVA_NULL) { + rc = sqlite3_bind_null(stmt, i + 1); + } else { + cls = CN1_CLASS_OF(v); + if (cn1IsStringClass(cls)) { + rc = cn1DbBindStringStatus(stmt, i + 1, v); + } else if (cls == &class__java_lang_Long) { + rc = sqlite3_bind_int64(stmt, i + 1, java_lang_Long_cn1Value___R_long(threadStateData, v)); + } else if (cls == &class__java_lang_Double) { + rc = sqlite3_bind_double(stmt, i + 1, java_lang_Double_cn1Value___R_double(threadStateData, v)); + } else if (cls == &class__java_lang_Integer) { + rc = sqlite3_bind_int64(stmt, i + 1, java_lang_Integer_cn1Value___R_int(threadStateData, v)); + } else if (cls == &class_array1__JAVA_BYTE) { + JAVA_ARRAY b = (JAVA_ARRAY)v; + rc = sqlite3_bind_blob(stmt, i + 1, b->length > 0 ? CN1_ARRAY_DATA(b) : (const void*)"", + b->length, SQLITE_TRANSIENT); + } else { + return CN1_DB_BIND_UNHANDLED; + } + } + if (rc != SQLITE_OK) { + return rc; + } + } + return SQLITE_OK; +} + +/** A text column as a java.lang.String, decoded from the engine's UTF-8 straight into the + * string: no byte[] is made for it. Null for SQL NULL. */ +static JAVA_OBJECT cn1DbColString(CODENAME_ONE_THREAD_STATE, sqlite3_stmt* stmt, JAVA_INT col) { + const unsigned char* text; + int length; + if (sqlite3_column_type(stmt, col) == SQLITE_NULL) { + return JAVA_NULL; + } + text = sqlite3_column_text(stmt, col); + length = sqlite3_column_bytes(stmt, col); + return newStringFromUtf8Len(threadStateData, text != NULL ? (const char*)text : "", length); +} + +/** Every column of the current row into `out` as Database.getValue reads each -- null, Long, + * Double, String or byte[] by storage class -- written straight into the caller's array: no + * call per column and nothing allocated but the values (a Long or Double that fits a tagged + * word allocates nothing either). False, writing nothing, when the array is too short. */ +static JAVA_BOOLEAN cn1DbRowValues(CODENAME_ONE_THREAD_STATE, sqlite3_stmt* stmt, JAVA_OBJECT out) { + JAVA_ARRAY arr = (JAVA_ARRAY)out; + int n = sqlite3_column_count(stmt); + int i; + if (out == JAVA_NULL || arr->length < n) { + return JAVA_FALSE; + } + for (i = 0; i < n; i++) { + JAVA_OBJECT v; + switch (sqlite3_column_type(stmt, i)) { + case SQLITE_NULL: + v = JAVA_NULL; + break; + case SQLITE_INTEGER: + v = java_lang_Long_valueOf___long_R_java_lang_Long(threadStateData, sqlite3_column_int64(stmt, i)); + break; + case SQLITE_FLOAT: + v = java_lang_Double_valueOf___double_R_java_lang_Double(threadStateData, sqlite3_column_double(stmt, i)); + break; + case SQLITE_BLOB: { + const void* bytes = sqlite3_column_blob(stmt, i); + v = cn1DbBlobToByteArray(threadStateData, bytes, sqlite3_column_bytes(stmt, i)); + break; + } + default: + v = cn1DbColString(threadStateData, stmt, i); + break; + } + CN1_WRITE_BARRIER(out, v); + ((JAVA_ARRAY_OBJECT*)CN1_ARRAY_DATA(arr))[i] = v; + } + return JAVA_TRUE; +} + #endif /* CN1_DB_ENGINE_PRESENT */ /* @@ -424,6 +572,12 @@ JAVA_BOOLEAN PREFIX##_sqlDbInTransaction___long(CODENAME_ONE_THREAD_STATE, JAVA_ } \ JAVA_BOOLEAN PREFIX##_sqlDbInTransaction___long_R_boolean(CODENAME_ONE_THREAD_STATE, JAVA_LONG dbPeer) { \ return PREFIX##_sqlDbInTransaction___long(threadStateData, dbPeer); \ +} \ +JAVA_LONG PREFIX##_sqlDbChanges___long_R_long(CODENAME_ONE_THREAD_STATE, JAVA_LONG dbPeer) { \ + return (JAVA_LONG)sqlite3_changes((sqlite3*)(intptr_t)dbPeer); \ +} \ +JAVA_LONG PREFIX##_sqlDbLastInsertRowid___long_R_long(CODENAME_ONE_THREAD_STATE, JAVA_LONG dbPeer) { \ + return (JAVA_LONG)sqlite3_last_insert_rowid((sqlite3*)(intptr_t)dbPeer); \ } \ \ JAVA_VOID PREFIX##_sqlDbExecScript___long_java_lang_String(CODENAME_ONE_THREAD_STATE, JAVA_LONG dbPeer, JAVA_OBJECT sql) { \ @@ -574,6 +728,17 @@ JAVA_BOOLEAN PREFIX##_sqlColIsNull___long_int(CODENAME_ONE_THREAD_STATE, JAVA_LO JAVA_BOOLEAN PREFIX##_sqlColIsNull___long_int_R_boolean(CODENAME_ONE_THREAD_STATE, JAVA_LONG stmtPeer, JAVA_INT col) { \ return PREFIX##_sqlColIsNull___long_int(threadStateData, stmtPeer, col); \ } \ +/* The Database.COLUMN_* constant for a value's storage class. */ \ +JAVA_INT PREFIX##_sqlColType___long_int_R_int(CODENAME_ONE_THREAD_STATE, JAVA_LONG stmtPeer, JAVA_INT col) {\ + switch (sqlite3_column_type((sqlite3_stmt*)(intptr_t)stmtPeer, col)) { \ + case SQLITE_NULL: return 0; \ + case SQLITE_INTEGER: return 1; \ + case SQLITE_FLOAT: return 2; \ + case SQLITE_TEXT: return 3; \ + case SQLITE_BLOB: return 4; \ + default: return -1; \ + } \ +} \ \ JAVA_OBJECT PREFIX##_sqlColText___long_int(CODENAME_ONE_THREAD_STATE, JAVA_LONG stmtPeer, JAVA_INT col) { \ sqlite3_stmt* stmt = (sqlite3_stmt*)(intptr_t)stmtPeer; \ @@ -594,6 +759,71 @@ JAVA_OBJECT PREFIX##_sqlColText___long_int_R_byte_1ARRAY(CODENAME_ONE_THREAD_STA return PREFIX##_sqlColText___long_int(threadStateData, stmtPeer, col); \ } \ \ +JAVA_VOID PREFIX##_sqlStmtBindString___long_int_java_lang_String(CODENAME_ONE_THREAD_STATE, JAVA_LONG stmtPeer, JAVA_INT index, JAVA_OBJECT value) { \ + cn1DbBindString(threadStateData, (sqlite3_stmt*)(intptr_t)stmtPeer, index, value); \ +} \ +JAVA_OBJECT PREFIX##_sqlColString___long_int_R_java_lang_String(CODENAME_ONE_THREAD_STATE, JAVA_LONG stmtPeer, JAVA_INT col) { \ + return cn1DbColString(threadStateData, (sqlite3_stmt*)(intptr_t)stmtPeer, col); \ +} \ +JAVA_BOOLEAN PREFIX##_sqlRowValues___long_java_lang_Object_1ARRAY_R_boolean(CODENAME_ONE_THREAD_STATE, JAVA_LONG stmtPeer, JAVA_OBJECT out) { \ + return cn1DbRowValues(threadStateData, (sqlite3_stmt*)(intptr_t)stmtPeer, out); \ +} \ +/* The status forms: SQLite's own result code back, never a Java exception. A throw unwinds \ + * through every Java frame with a handler on the way, and each such frame pays a setjmp and \ + * keeps its locals in memory on every call; a caller on a hot path checks a code instead. \ + * The message of a failure is read afterwards, from the connection. */ \ +JAVA_INT PREFIX##_sqlStmtStepStatus___long_R_int(CODENAME_ONE_THREAD_STATE, JAVA_LONG stmtPeer) { \ + return sqlite3_step((sqlite3_stmt*)(intptr_t)stmtPeer); \ +} \ +/* Binds `params`, steps the statement to its end, discarding any rows, and resets it: one \ + * update run in one call. 0 when it ran; -3 when the statement takes another number of \ + * parameters; CN1_DB_BIND_UNHANDLED when a parameter is bound only on the Java side (nothing \ + * ran); otherwise SQLite's code, its message on the connection. When it ran, `counts`, if \ + * not null, receives the changes and the last row id, written in place. */ \ +JAVA_INT PREFIX##_sqlStmtRunStatus___long_java_lang_Object_1ARRAY_long_1ARRAY_R_int(CODENAME_ONE_THREAD_STATE, JAVA_LONG stmtPeer, JAVA_OBJECT params, JAVA_OBJECT counts) { \ + sqlite3_stmt* stmt = (sqlite3_stmt*)(intptr_t)stmtPeer; \ + int rc; \ + if (sqlite3_bind_parameter_count(stmt) != ((JAVA_ARRAY)params)->length) { \ + return -3; \ + } \ + rc = cn1DbBindAll(threadStateData, stmt, params); \ + if (rc != SQLITE_OK) { \ + return rc; \ + } \ + do { \ + rc = sqlite3_step(stmt); \ + } while (rc == SQLITE_ROW); \ + sqlite3_reset(stmt); \ + if (rc != SQLITE_DONE) { \ + return rc; \ + } \ + if (counts != JAVA_NULL && ((JAVA_ARRAY)counts)->length >= 2) { \ + sqlite3* db = sqlite3_db_handle(stmt); \ + JAVA_ARRAY_LONG* out = (JAVA_ARRAY_LONG*)CN1_ARRAY_DATA((JAVA_ARRAY)counts); \ + out[0] = sqlite3_changes(db); \ + out[1] = sqlite3_last_insert_rowid(db); \ + } \ + return 0; \ +} \ +JAVA_LONG PREFIX##_sqlStmtPrepareStatus___long_java_lang_String_R_long(CODENAME_ONE_THREAD_STATE, JAVA_LONG dbPeer, JAVA_OBJECT sql) { \ + sqlite3_stmt* stmt = NULL; \ + if (sqlite3_prepare_v2((sqlite3*)(intptr_t)dbPeer, stringToUTF8(threadStateData, sql), -1, &stmt, NULL) != SQLITE_OK) { \ + return 0; \ + } \ + return (JAVA_LONG)(intptr_t)stmt; \ +} \ +JAVA_INT PREFIX##_sqlStmtFinalizeStatus___long_R_int(CODENAME_ONE_THREAD_STATE, JAVA_LONG stmtPeer) { \ + return stmtPeer == 0 ? SQLITE_OK : sqlite3_finalize((sqlite3_stmt*)(intptr_t)stmtPeer); \ +} \ +JAVA_OBJECT PREFIX##_sqlDbErrorText___long_R_java_lang_String(CODENAME_ONE_THREAD_STATE, JAVA_LONG dbPeer) { \ + const char* text = sqlite3_errmsg((sqlite3*)(intptr_t)dbPeer); \ + return newStringFromUtf8Len(threadStateData, text, (int)strlen(text)); \ +} \ +JAVA_OBJECT PREFIX##_sqlColNameString___long_int_R_java_lang_String(CODENAME_ONE_THREAD_STATE, JAVA_LONG stmtPeer, JAVA_INT col) { \ + const char* name = sqlite3_column_name((sqlite3_stmt*)(intptr_t)stmtPeer, col); \ + return name == NULL ? JAVA_NULL : newStringFromUtf8Len(threadStateData, name, (int)strlen(name)); \ +} \ + \ JAVA_OBJECT PREFIX##_sqlColBlob___long_int(CODENAME_ONE_THREAD_STATE, JAVA_LONG stmtPeer, JAVA_INT col) { \ sqlite3_stmt* stmt = (sqlite3_stmt*)(intptr_t)stmtPeer; \ const void* bytes = sqlite3_column_blob(stmt, col); \ @@ -618,6 +848,72 @@ JAVA_LONG PREFIX##_sqlColLong___long_int_R_long(CODENAME_ONE_THREAD_STATE, JAVA_ return sqlite3_column_int64((sqlite3_stmt*)(intptr_t)stmtPeer, col); \ } + +/* + * SQL functions written in Java. SQLite calls cn1DbJavaFunction on the thread stepping the + * statement, which hands the call to CALLBACK -- a static Java method of the port, taking + * (long ctx, int id, int argc, long argv), that reads the arguments and sets the result back + * through the value and result natives below. The id is the function's slot in the port's + * SqlFunctionBridge; nothing Java is held by the engine. + */ +#define CN1_DB_DEFINE_FUNCTION_NATIVES(PREFIX, CALLBACK) \ +extern JAVA_VOID CALLBACK(CODENAME_ONE_THREAD_STATE, JAVA_LONG ctx, JAVA_INT id, JAVA_INT argc, JAVA_LONG argv); \ +static void PREFIX##_javaFunction(sqlite3_context* c, int argc, sqlite3_value** v) { \ + CALLBACK(getThreadLocalData(), (JAVA_LONG)(intptr_t)c, (JAVA_INT)(intptr_t)sqlite3_user_data(c), \ + argc, (JAVA_LONG)(intptr_t)v); \ +} \ +JAVA_INT PREFIX##_sqlDbCreateFunction___long_byte_1ARRAY_int_int_R_int(CODENAME_ONE_THREAD_STATE, JAVA_LONG dbPeer, JAVA_OBJECT name, JAVA_INT argc, JAVA_INT id) { \ + JAVA_ARRAY arr = (JAVA_ARRAY)name; \ + char buf[256]; \ + int n = arr->length < 255 ? arr->length : 255; \ + memcpy(buf, CN1_ARRAY_DATA(arr), n); \ + buf[n] = 0; \ + return sqlite3_create_function_v2((sqlite3*)(intptr_t)dbPeer, buf, argc, SQLITE_UTF8, \ + (void*)(intptr_t)id, id < 0 ? NULL : PREFIX##_javaFunction, NULL, NULL, NULL); \ +} \ +JAVA_INT PREFIX##_sqlValueType___long_int_R_int(CODENAME_ONE_THREAD_STATE, JAVA_LONG argv, JAVA_INT i) { \ + return sqlite3_value_type(((sqlite3_value**)(intptr_t)argv)[i]); \ +} \ +JAVA_LONG PREFIX##_sqlValueLong___long_int_R_long(CODENAME_ONE_THREAD_STATE, JAVA_LONG argv, JAVA_INT i) { \ + return (JAVA_LONG)sqlite3_value_int64(((sqlite3_value**)(intptr_t)argv)[i]); \ +} \ +JAVA_DOUBLE PREFIX##_sqlValueDouble___long_int_R_double(CODENAME_ONE_THREAD_STATE, JAVA_LONG argv, JAVA_INT i) { \ + return sqlite3_value_double(((sqlite3_value**)(intptr_t)argv)[i]); \ +} \ +JAVA_OBJECT PREFIX##_sqlValueText___long_int_R_byte_1ARRAY(CODENAME_ONE_THREAD_STATE, JAVA_LONG argv, JAVA_INT i) { \ + sqlite3_value* v = ((sqlite3_value**)(intptr_t)argv)[i]; \ + const unsigned char* t = sqlite3_value_text(v); \ + return cn1DbBlobToByteArray(threadStateData, t, t == NULL ? 0 : sqlite3_value_bytes(v)); \ +} \ +JAVA_OBJECT PREFIX##_sqlValueBlob___long_int_R_byte_1ARRAY(CODENAME_ONE_THREAD_STATE, JAVA_LONG argv, JAVA_INT i) { \ + sqlite3_value* v = ((sqlite3_value**)(intptr_t)argv)[i]; \ + const void* b = sqlite3_value_blob(v); \ + return cn1DbBlobToByteArray(threadStateData, b, b == NULL ? 0 : sqlite3_value_bytes(v)); \ +} \ +JAVA_VOID PREFIX##_sqlResultNull___long(CODENAME_ONE_THREAD_STATE, JAVA_LONG ctx) { \ + sqlite3_result_null((sqlite3_context*)(intptr_t)ctx); \ +} \ +JAVA_VOID PREFIX##_sqlResultLong___long_long(CODENAME_ONE_THREAD_STATE, JAVA_LONG ctx, JAVA_LONG v) { \ + sqlite3_result_int64((sqlite3_context*)(intptr_t)ctx, (sqlite3_int64)v); \ +} \ +JAVA_VOID PREFIX##_sqlResultDouble___long_double(CODENAME_ONE_THREAD_STATE, JAVA_LONG ctx, JAVA_DOUBLE v) { \ + sqlite3_result_double((sqlite3_context*)(intptr_t)ctx, v); \ +} \ +JAVA_VOID PREFIX##_sqlResultText___long_byte_1ARRAY(CODENAME_ONE_THREAD_STATE, JAVA_LONG ctx, JAVA_OBJECT v) { \ + JAVA_ARRAY arr = (JAVA_ARRAY)v; \ + sqlite3_result_text((sqlite3_context*)(intptr_t)ctx, arr->length > 0 ? (const char*)CN1_ARRAY_DATA(arr) : "", \ + arr->length, SQLITE_TRANSIENT); \ +} \ +JAVA_VOID PREFIX##_sqlResultBlob___long_byte_1ARRAY(CODENAME_ONE_THREAD_STATE, JAVA_LONG ctx, JAVA_OBJECT v) { \ + JAVA_ARRAY arr = (JAVA_ARRAY)v; \ + sqlite3_result_blob((sqlite3_context*)(intptr_t)ctx, arr->length > 0 ? CN1_ARRAY_DATA(arr) : (const void*)"", \ + arr->length, SQLITE_TRANSIENT); \ +} \ +JAVA_VOID PREFIX##_sqlResultError___long_byte_1ARRAY(CODENAME_ONE_THREAD_STATE, JAVA_LONG ctx, JAVA_OBJECT v) { \ + JAVA_ARRAY arr = (JAVA_ARRAY)v; \ + sqlite3_result_error((sqlite3_context*)(intptr_t)ctx, (const char*)CN1_ARRAY_DATA(arr), arr->length); \ +} + #else /* !CN1_DB_ENGINE_PRESENT */ #include @@ -652,6 +948,8 @@ JAVA_BOOLEAN PREFIX##_sqlDbIsCipherAvailable___R_boolean(CODENAME_ONE_THREAD_STA JAVA_VOID PREFIX##_sqlDbClose___long(CODENAME_ONE_THREAD_STATE, JAVA_LONG d) { } \ JAVA_BOOLEAN PREFIX##_sqlDbInTransaction___long(CODENAME_ONE_THREAD_STATE, JAVA_LONG d) { return JAVA_FALSE; } \ JAVA_BOOLEAN PREFIX##_sqlDbInTransaction___long_R_boolean(CODENAME_ONE_THREAD_STATE, JAVA_LONG d) { return JAVA_FALSE; } \ +JAVA_LONG PREFIX##_sqlDbChanges___long_R_long(CODENAME_ONE_THREAD_STATE, JAVA_LONG d) { return 0; } \ +JAVA_LONG PREFIX##_sqlDbLastInsertRowid___long_R_long(CODENAME_ONE_THREAD_STATE, JAVA_LONG d) { return 0; } \ JAVA_VOID PREFIX##_sqlDbExecScript___long_java_lang_String(CODENAME_ONE_THREAD_STATE, JAVA_LONG d, JAVA_OBJECT s) { cn1DbThrowUnavailable(threadStateData); } \ JAVA_LONG PREFIX##_sqlStmtPrepare___long_java_lang_String(CODENAME_ONE_THREAD_STATE, JAVA_LONG d, JAVA_OBJECT s) { cn1DbThrowUnavailable(threadStateData); return 0; } \ JAVA_LONG PREFIX##_sqlStmtPrepare___long_java_lang_String_R_long(CODENAME_ONE_THREAD_STATE, JAVA_LONG d, JAVA_OBJECT s) { cn1DbThrowUnavailable(threadStateData); return 0; } \ @@ -673,8 +971,18 @@ JAVA_OBJECT PREFIX##_sqlColName___long_int(CODENAME_ONE_THREAD_STATE, JAVA_LONG JAVA_OBJECT PREFIX##_sqlColName___long_int_R_byte_1ARRAY(CODENAME_ONE_THREAD_STATE, JAVA_LONG s, JAVA_INT c) { return JAVA_NULL; } \ JAVA_BOOLEAN PREFIX##_sqlColIsNull___long_int(CODENAME_ONE_THREAD_STATE, JAVA_LONG s, JAVA_INT c) { return JAVA_TRUE; } \ JAVA_BOOLEAN PREFIX##_sqlColIsNull___long_int_R_boolean(CODENAME_ONE_THREAD_STATE, JAVA_LONG s, JAVA_INT c) { return JAVA_TRUE; } \ +JAVA_INT PREFIX##_sqlColType___long_int_R_int(CODENAME_ONE_THREAD_STATE, JAVA_LONG s, JAVA_INT c) { return -1; } \ JAVA_OBJECT PREFIX##_sqlColText___long_int(CODENAME_ONE_THREAD_STATE, JAVA_LONG s, JAVA_INT c) { return JAVA_NULL; } \ JAVA_OBJECT PREFIX##_sqlColText___long_int_R_byte_1ARRAY(CODENAME_ONE_THREAD_STATE, JAVA_LONG s, JAVA_INT c) { return JAVA_NULL; } \ +JAVA_VOID PREFIX##_sqlStmtBindString___long_int_java_lang_String(CODENAME_ONE_THREAD_STATE, JAVA_LONG s, JAVA_INT i, JAVA_OBJECT v) { } \ +JAVA_OBJECT PREFIX##_sqlColString___long_int_R_java_lang_String(CODENAME_ONE_THREAD_STATE, JAVA_LONG s, JAVA_INT c) { return JAVA_NULL; } \ +JAVA_OBJECT PREFIX##_sqlColNameString___long_int_R_java_lang_String(CODENAME_ONE_THREAD_STATE, JAVA_LONG s, JAVA_INT c) { return JAVA_NULL; } \ +JAVA_BOOLEAN PREFIX##_sqlRowValues___long_java_lang_Object_1ARRAY_R_boolean(CODENAME_ONE_THREAD_STATE, JAVA_LONG s, JAVA_OBJECT o) { return JAVA_FALSE; } \ +JAVA_INT PREFIX##_sqlStmtStepStatus___long_R_int(CODENAME_ONE_THREAD_STATE, JAVA_LONG s) { return 1; } \ +JAVA_INT PREFIX##_sqlStmtFinalizeStatus___long_R_int(CODENAME_ONE_THREAD_STATE, JAVA_LONG s) { return 0; } \ +JAVA_INT PREFIX##_sqlStmtRunStatus___long_java_lang_Object_1ARRAY_long_1ARRAY_R_int(CODENAME_ONE_THREAD_STATE, JAVA_LONG s, JAVA_OBJECT o, JAVA_OBJECT c) { return 1; } \ +JAVA_LONG PREFIX##_sqlStmtPrepareStatus___long_java_lang_String_R_long(CODENAME_ONE_THREAD_STATE, JAVA_LONG d, JAVA_OBJECT q) { return 0; } \ +JAVA_OBJECT PREFIX##_sqlDbErrorText___long_R_java_lang_String(CODENAME_ONE_THREAD_STATE, JAVA_LONG d) { return JAVA_NULL; } \ JAVA_OBJECT PREFIX##_sqlColBlob___long_int(CODENAME_ONE_THREAD_STATE, JAVA_LONG s, JAVA_INT c) { return JAVA_NULL; } \ JAVA_OBJECT PREFIX##_sqlColBlob___long_int_R_byte_1ARRAY(CODENAME_ONE_THREAD_STATE, JAVA_LONG s, JAVA_INT c) { return JAVA_NULL; } \ JAVA_DOUBLE PREFIX##_sqlColDouble___long_int(CODENAME_ONE_THREAD_STATE, JAVA_LONG s, JAVA_INT c) { return 0; } \ @@ -682,6 +990,22 @@ JAVA_DOUBLE PREFIX##_sqlColDouble___long_int_R_double(CODENAME_ONE_THREAD_STATE, JAVA_LONG PREFIX##_sqlColLong___long_int(CODENAME_ONE_THREAD_STATE, JAVA_LONG s, JAVA_INT c) { return 0; } \ JAVA_LONG PREFIX##_sqlColLong___long_int_R_long(CODENAME_ONE_THREAD_STATE, JAVA_LONG s, JAVA_INT c) { return 0; } + +/* No engine: no database opens, so no function is ever called; creating one fails. */ +#define CN1_DB_DEFINE_FUNCTION_NATIVES(PREFIX, CALLBACK) \ +JAVA_INT PREFIX##_sqlDbCreateFunction___long_byte_1ARRAY_int_int_R_int(CODENAME_ONE_THREAD_STATE, JAVA_LONG d, JAVA_OBJECT n, JAVA_INT a, JAVA_INT id) { return 1; } \ +JAVA_INT PREFIX##_sqlValueType___long_int_R_int(CODENAME_ONE_THREAD_STATE, JAVA_LONG a, JAVA_INT i) { return 5; } \ +JAVA_LONG PREFIX##_sqlValueLong___long_int_R_long(CODENAME_ONE_THREAD_STATE, JAVA_LONG a, JAVA_INT i) { return 0; } \ +JAVA_DOUBLE PREFIX##_sqlValueDouble___long_int_R_double(CODENAME_ONE_THREAD_STATE, JAVA_LONG a, JAVA_INT i) { return 0; } \ +JAVA_OBJECT PREFIX##_sqlValueText___long_int_R_byte_1ARRAY(CODENAME_ONE_THREAD_STATE, JAVA_LONG a, JAVA_INT i) { return JAVA_NULL; } \ +JAVA_OBJECT PREFIX##_sqlValueBlob___long_int_R_byte_1ARRAY(CODENAME_ONE_THREAD_STATE, JAVA_LONG a, JAVA_INT i) { return JAVA_NULL; } \ +JAVA_VOID PREFIX##_sqlResultNull___long(CODENAME_ONE_THREAD_STATE, JAVA_LONG c) { } \ +JAVA_VOID PREFIX##_sqlResultLong___long_long(CODENAME_ONE_THREAD_STATE, JAVA_LONG c, JAVA_LONG v) { } \ +JAVA_VOID PREFIX##_sqlResultDouble___long_double(CODENAME_ONE_THREAD_STATE, JAVA_LONG c, JAVA_DOUBLE v) { } \ +JAVA_VOID PREFIX##_sqlResultText___long_byte_1ARRAY(CODENAME_ONE_THREAD_STATE, JAVA_LONG c, JAVA_OBJECT v) { } \ +JAVA_VOID PREFIX##_sqlResultBlob___long_byte_1ARRAY(CODENAME_ONE_THREAD_STATE, JAVA_LONG c, JAVA_OBJECT v) { } \ +JAVA_VOID PREFIX##_sqlResultError___long_byte_1ARRAY(CODENAME_ONE_THREAD_STATE, JAVA_LONG c, JAVA_OBJECT v) { } + #endif /* CN1_DB_ENGINE_PRESENT */ #endif /* CN1_DB_SQLITE_IMPL_H */ diff --git a/vm/ByteCodeTranslator/src/cn1_globals.h b/vm/ByteCodeTranslator/src/cn1_globals.h index 1b10dcdbfa7..a93fb2f2cc6 100644 --- a/vm/ByteCodeTranslator/src/cn1_globals.h +++ b/vm/ByteCodeTranslator/src/cn1_globals.h @@ -816,7 +816,11 @@ typedef struct clazz* JAVA_CLASS; * which every application links -- fails to link for those. The macro only * expands where an aastore exists, which is exactly where the class is kept * alive. The branch hint is the part that carries over. */ \ - if(__builtin_expect(cn1__comp != NULL && !instanceofFunction(cn1__comp->classId, GET_CLASS_ID(value)), 0)) { \ + /* An Object[] takes anything and an exact match needs no walk: both are + * answered here, so the usual store makes no call at all. */ \ + if(__builtin_expect(cn1__comp != NULL && cn1__comp->classId != cn1_class_id_java_lang_Object \ + && cn1__comp->classId != GET_CLASS_ID(value) \ + && !instanceofFunction(cn1__comp->classId, GET_CLASS_ID(value)), 0)) { \ cn1ThrowTypeError(threadStateData, __NEW_INSTANCE_java_lang_ArrayStoreException(threadStateData), CN1_CLASS_OF(value)->clsName, NULL); \ } \ } \ @@ -825,7 +829,7 @@ typedef struct clazz* JAVA_CLASS; #define BC_CHECKCAST_CHECKED(typeOfCheckCast, targetName) { \ if(SP[-1].data.o != JAVA_NULL) { \ int tmpCheckCastId = GET_CLASS_ID(SP[-1].data.o); \ - if(!instanceofFunction(typeOfCheckCast, tmpCheckCastId)) { \ + if(tmpCheckCastId != (typeOfCheckCast) && !instanceofFunction(typeOfCheckCast, tmpCheckCastId)) { \ cn1ThrowTypeError(threadStateData, __NEW_INSTANCE_java_lang_ClassCastException(threadStateData), CN1_CLASS_OF(SP[-1].data.o)->clsName, targetName); \ } \ } \ @@ -835,13 +839,7 @@ typedef struct clazz* JAVA_CLASS; // (*--SP) rather than (*pop(&SP)), which is the same decrement-then-dereference -// and avoids taking SP's address. A method that emits setjmp declares SP volatile -// so longjmp cannot clobber it (see CN1_DECLARE_SP); &SP is then -// `struct elementStruct *volatile *`, and pop() takes `struct elementStruct **`, -// so every pop in such a method passed a pointer that discarded the very -// qualifier the frame variant exists to apply. That was ~9,100 warnings in one -// application build, and it was the compiler being right: writing through the -// unqualified pointer is not the volatile access the declaration asked for. +// and avoids taking SP's address, so SP can stay in a register. #define POP_INT() ((*--SP).data.i) #define POP_OBJ() ((*--SP).data.o) #define POP_OBJ_NO_RELEASE() ((*--SP).data.o) @@ -1462,7 +1460,7 @@ extern struct JavaObjectPrototype cn1TaggedProxy[CN1_TAG_COUNT]; #define CN1_TAG_CODE(o) (((uintptr_t)(o)) & CN1_TAG_MASK) #define CN1_IS_TAGGED(o) (CN1_TAG_CODE(o) != 0) // A function rather than a macro so the argument is evaluated exactly once; every caller -// passes an lvalue, but SP[-1].data.o through a volatile SP would otherwise be three loads. +// passes an lvalue, and a macro would evaluate SP[-1].data.o three times. static inline struct clazz* cn1ClassOf(JAVA_OBJECT o) { uintptr_t cn1__code = ((uintptr_t)o) & CN1_TAG_MASK; struct JavaObjectPrototype* cn1__p = cn1__code ? &cn1TaggedProxy[cn1__code] @@ -1794,7 +1792,17 @@ struct CN1BuilderAccess { // indicates a try/catch block currently in frame struct TryBlock { - jmp_buf destination; + // The jmp_buf a throw resumes at, in the frame that set it up -- never a copy. + // A generated method shares ONE jmp_buf among all of its handlers and tells + // them apart by `handler`, which the longjmp delivers as setjmp's result: + // a setjmp per handler at every method entry, and a memcpy of the whole + // jmp_buf (~200 bytes on arm64) at every try entry, were what a try cost. + jmp_buf* destination; + // Which of the method's handlers this block is (a DEFINE_CATCH_BLOCK constant, + // never 0); 1 for a block whose jmp_buf is its own (the runtime's C call sites). + // Read back after the jump from the block the throw stopped at: every throw + // path leaves tryBlockOffset on the block that caught. + JAVA_INT handler; struct CN1StackBuffer* nativeBuffers; struct CN1BuilderAccess* builderAccess; @@ -1864,11 +1872,20 @@ struct TryBlock { #define CN1_SATB_FRESH_INLINE(o) 0 #else // The filter is only sound while the sweep grants EVERY fresh object a cycle of grace. -// Single-core mode (see cn1GcSingleCore in cn1_globals.m) reclaims fresh objects that -// were allocated before the cycle began, so there a fresh reference is logged like any -// other; cn1GcFreshFilter is set once, at the first collection, and never changes. +// Every BiBOP cycle reclaims the unmarked fresh objects on PRE-CYCLE pages -- pages retired +// before it began (cn1GcHybridBeginConcurrent in cn1_globals.m) -- so a fresh reference to +// an object on one of those is logged like any other. Every other fresh object keeps its +// grace and stays filtered, which is what keeps a concurrent mark's log sized by the live +// set rather than by the allocation rate (issue 5537: 2.7M fresh references logged in one +// cycle when all of them were). A stop-the-world cycle parks the mutators while the barrier +// is armed, so it turns the filter off outright (cn1GcFreshFilter) and also frees fresh +// legacy objects. extern JAVA_BOOLEAN cn1GcFreshFilter; -#define CN1_SATB_FRESH_INLINE(o) (cn1GcFreshFilter && CN1_OBJ_MARK_IS_FRESH((o), __ATOMIC_RELAXED)) +#define CN1_SATB_ON_PRE_CYCLE_PAGE(o) (CN1_OBJ_HEAPPOS(o) == CN1_BIBOP_HEAP_POS \ + && __atomic_load_n(&((CN1BibopPage*)((uintptr_t)(o) \ + & ~((uintptr_t)CN1_BIBOP_PAGE_SIZE - 1)))->gcPreCycle, __ATOMIC_RELAXED)) +#define CN1_SATB_FRESH_INLINE(o) (cn1GcFreshFilter && CN1_OBJ_MARK_IS_FRESH((o), __ATOMIC_RELAXED) \ + && !CN1_SATB_ON_PRE_CYCLE_PAGE(o)) #endif // Two halves share the gate. The SATB half runs only while a mark is in progress. The // GENERATIONAL half (single-core mode only, see cn1GcSingleCore) runs always: a young @@ -1992,6 +2009,42 @@ extern void cn1SatbBulkQuiesce(void); } } while(0) #endif +// A reference field store at the call site. set_field_X used to be a function per field +// holding both barrier macros, and at clang's -inline-threshold=50 every one of them stayed +// a call: three of them were 16% of a Python generator's resume. The header now maps a +// plain reference setter onto this (see ByteCodeClass): off-mark, with no generational +// barrier, a store is a flag test and a store. Anything else takes cn1SetRefFieldSlow, +// which runs the same two macros the setter ran, in the same order, so barrier semantics +// are unchanged -- only where the code lives moved. +extern void cn1SetRefFieldSlow(JAVA_OBJECT target, JAVA_OBJECT* addr, JAVA_OBJECT value); +static inline void cn1InlSetRefField(JAVA_OBJECT target, size_t offset, JAVA_OBJECT value) { + JAVA_OBJECT* addr = (JAVA_OBJECT*)((char*)target + offset); +#if defined(CN1_DISABLE_SATB) + if(__builtin_expect(cn1GcGenBarrier, 0)) { +#else + if(__builtin_expect(gcSatbActive | cn1GcGenBarrier, 0)) { +#endif + cn1SetRefFieldSlow(target, addr, value); + return; + } + *addr = value; +} + +// The same for a static: no owning object, so the generational half has nothing to +// remember (CN1_GEN_REMEMBER tests its target for null) and the insertion and deletion +// halves run exactly as the static setter ran them. +static inline void cn1InlSetStaticRef(JAVA_OBJECT* addr, JAVA_OBJECT value) { +#if defined(CN1_DISABLE_SATB) + if(__builtin_expect(cn1GcGenBarrier, 0)) { +#else + if(__builtin_expect(gcSatbActive | cn1GcGenBarrier, 0)) { +#endif + cn1SetRefFieldSlow(JAVA_NULL, addr, value); + return; + } + *addr = value; +} + // ---- java.lang.ref support ------------------------------------------------- // A WeakReference's referent is NOT traced by the generated mark function. That // function calls cn1GcDiscoverReference instead (see ByteCodeClass), handing over @@ -3334,7 +3387,12 @@ extern JAVA_OBJECT cn1BibopFastNew(CODENAME_ONE_THREAD_STATE, int size, struct c * mid-use -> the intermittent Windows WebSocket-reader use-after-free. On platforms with * signal-stop this just makes the cheaper cooperative path usable; a no-op when conservative * roots are off. */ -#define CN1_YIELD_THREAD do { struct ThreadLocalData* __cn1yts = getThreadLocalData(); CN1_GC_PARK_CAPTURE(__cn1yts); __cn1yts->threadActive = JAVA_FALSE; } while(0) +/* The _TS forms take the state the native was called with (threadStateData) instead of + * looking it up: the same struct getThreadLocalData() answers for the running thread, + * virtual or not, without its pthread_once, key read and virtual-thread lookup -- which + * cost as much as sqlite3_step itself on a statement of one row. */ +#define CN1_YIELD_THREAD_TS(ts) do { struct ThreadLocalData* __cn1yts = (ts); CN1_GC_PARK_CAPTURE(__cn1yts); __cn1yts->threadActive = JAVA_FALSE; } while(0) +#define CN1_YIELD_THREAD CN1_YIELD_THREAD_TS(getThreadLocalData()) /* The capture is cleared through a macro of its own because gcParkCaptured only * EXISTS when conservative roots are compiled in. Referencing it unconditionally * meant -DCN1_DISABLE_CONSERVATIVE_GC_ROOTS -- the A/B arm vm/CLAUDE.md documents @@ -3368,7 +3426,8 @@ extern JAVA_OBJECT cn1BibopFastNew(CODENAME_ONE_THREAD_STATE, int size, struct c scans every registered virtual thread whether or not it is running. Going active is cn1GcTryResumeActive's handshake, retried until the collector is not holding this thread; see there for why a plain store of threadActive is not enough. */ -#define CN1_RESUME_THREAD do { struct ThreadLocalData* __cn1rts = getThreadLocalData(); CN1_STALL_T0(__cn1rt0); do { while (__cn1rts->threadBlockedByGC){ if(!cn1VirtualThreadYieldIfVirtual()) { usleep((JAVA_INT)1000); } } } while(__cn1rts->gcPthreadValid && !cn1GcTryResumeActive(__cn1rts)); CN1_GC_PARK_RELEASE(__cn1rts); CN1_STALL_ADD(__cn1rt0, CN1_STALL_NATIVE_RESUME, __cn1rts); } while(0) +#define CN1_RESUME_THREAD_TS(ts) do { struct ThreadLocalData* __cn1rts = (ts); CN1_STALL_T0(__cn1rt0); do { while (__cn1rts->threadBlockedByGC){ if(!cn1VirtualThreadYieldIfVirtual()) { usleep((JAVA_INT)1000); } } } while(__cn1rts->gcPthreadValid && !cn1GcTryResumeActive(__cn1rts)); CN1_GC_PARK_RELEASE(__cn1rts); CN1_STALL_ADD(__cn1rt0, CN1_STALL_NATIVE_RESUME, __cn1rts); } while(0) +#define CN1_RESUME_THREAD CN1_RESUME_THREAD_TS(getThreadLocalData()) extern struct ThreadLocalData* getThreadLocalData(); @@ -3394,7 +3453,20 @@ extern struct ThreadLocalData* getThreadLocalData(); threadStateData->blocks[threadStateData->tryBlockOffset].nativeBuffers = threadStateData->nativeBuffers; \ threadStateData->blocks[threadStateData->tryBlockOffset].builderAccess = threadStateData->builderAccess; \ threadStateData->blocks[threadStateData->tryBlockOffset].exceptionClass = classId; \ - memcpy(threadStateData->blocks[threadStateData->tryBlockOffset].destination, destinationJump, sizeof(jmp_buf)); \ + threadStateData->blocks[threadStateData->tryBlockOffset].destination = &(destinationJump); \ + threadStateData->blocks[threadStateData->tryBlockOffset].handler = 1; \ + threadStateData->tryBlockOffset++; \ + } + +// A generated try entry: `handlerId` is the handler's DEFINE_CATCH_BLOCK constant, +// and the jmp_buf is the method's one, set up by CN1_TRY_ENTRY. +#define BEGIN_TRY_H(classId, handlerId) {\ + threadStateData->blocks[threadStateData->tryBlockOffset].monitor = 0; \ + threadStateData->blocks[threadStateData->tryBlockOffset].nativeBuffers = threadStateData->nativeBuffers; \ + threadStateData->blocks[threadStateData->tryBlockOffset].builderAccess = threadStateData->builderAccess; \ + threadStateData->blocks[threadStateData->tryBlockOffset].exceptionClass = classId; \ + threadStateData->blocks[threadStateData->tryBlockOffset].destination = &cn1TryJmp; \ + threadStateData->blocks[threadStateData->tryBlockOffset].handler = handlerId; \ threadStateData->tryBlockOffset++; \ } @@ -3429,10 +3501,23 @@ extern void releaseForReturnInException(CODENAME_ONE_THREAD_STATE, int cn1Locals #define END_TRY(offset) threadStateData->tryBlockOffset = methodBlockOffset + offset - 1 -#define DEFINE_CATCH_BLOCK(destinationJump, labelName, restoreToCn1LocalsBeginInThread) jmp_buf destinationJump; \ +// The one setjmp of a method with handlers, ahead of its DEFINE_CATCH_BLOCKs. A +// throw resumes here with the catching handler's constant, and control falls +// through the DEFINE_CATCH_BLOCKs to the one that owns it. Every handler used to +// take a setjmp of its own here, at method entry, so a method with four handlers +// paid four on every call whether or not its try was ever reached. +#define CN1_TRY_ENTRY() jmp_buf cn1TryJmp; \ + int cn1TryCaught = 0; \ + if(CN1_TRY_SETJMP(cn1TryJmp)) { \ + cn1TryCaught = threadStateData->blocks[threadStateData->tryBlockOffset].handler; \ + } \ + SP = cn1SpEntry; \ + __asm__ __volatile__("" : : "r"(cn1SpEntry) : "memory"); + +#define DEFINE_CATCH_BLOCK(destinationJump, labelName, restoreToCn1LocalsBeginInThread) \ + enum { destinationJump = __COUNTER__ + 2 }; \ { \ - int currentOffset CN1_UNUSED = threadStateData->tryBlockOffset; \ - if(CN1_TRY_SETJMP(destinationJump)) { \ + if(cn1TryCaught == destinationJump) { \ threadStateData->callStackOffset = currentCodenameOneCallStackOffset; \ threadStateData->threadObjectStackOffset = restoreToCn1LocalsBeginInThread; \ SP = &stack[1]; \ @@ -3443,6 +3528,7 @@ extern void releaseForReturnInException(CODENAME_ONE_THREAD_STATE, int cn1Locals } extern JAVA_VOID java_lang_Throwable_fillInStack__(CODENAME_ONE_THREAD_STATE, JAVA_OBJECT ex); +extern JAVA_OBJECT cn1ThrowableStack(CODENAME_ONE_THREAD_STATE, JAVA_OBJECT ex); /* @@ -3699,6 +3785,37 @@ extern void cn1InstallFaultHandler(void); #define CHECK_ARRAY_ACCESS_EXPR(array, bounds) CN1_ARRAY_ACCESS_GUARD_EXPR(array, bounds) #define CHECK_ARRAY_ACCESS_WITH_ARGS(array, bounds) CN1_ARRAY_ACCESS_GUARD(array, bounds) +// One check for a whole run of constant-index loads of one array, emitted by the +// translator for b[i], b[i+1], ... b[bound] in straight-line code that nothing +// else in can throw or write (BytecodeMethod.analyzeConstantIndexRuns), at the +// FIRST load of the run; the loads after it are emitted unchecked. Checked one by +// one, the cold path of every load kept clang from keeping the array header in a +// register, and the branches between the loads kept it from fusing eight byte +// loads into one 64-bit load. +// +// The exception is the one Java would throw. The guard for the first load runs +// first, so null is a NullPointerException and an index past the end at the first +// load reports itself. Past that, the run is ascending by one and nothing +// observable happens in it, so the first load that would fail is the one at +// ->length, and that is the index reported. Diverges like CN1_ARRAY_ACCESS_GUARD: +// the run's unchecked loads can never execute after a failed check. +// +// Within one expression -- b[0] & 0xff | (b[1] & 0xff) << 8 -- C leaves the +// operands of | unsequenced. The guarded load is the leftmost, innermost one, and +// clang (the only compiler translated code is built with, clang-cl on Windows +// included) emits a binary operator's left operand first; LLVM never hoists a load +// it cannot prove dereferenceable above the noreturn call that may precede it. +#define CN1_ARRAY_RUN_GUARD(array, index, bound) \ + do { \ + JAVA_OBJECT __cn1RgA = (array); \ + CN1_ARRAY_ACCESS_GUARD(__cn1RgA, (index)); \ + if(__builtin_expect(((unsigned int)(bound)) >= (unsigned int)(((JAVA_ARRAY)__cn1RgA)->length), 0)) { cn1ThrowArrayIndexOrDie(threadStateData, ((JAVA_ARRAY)__cn1RgA)->length); } \ + } while(0) + +// The expression form of the guard above: guards the run, then reads the element. +#define CN1_ARRAY_ELEMENT_RUN(dataType, array, index, bound) \ + ({ JAVA_OBJECT __cn1RgE = (array); CN1_ARRAY_RUN_GUARD(__cn1RgE, (index), (bound)); ((dataType*) CN1_ARRAY_DATA((JAVA_ARRAY)__cn1RgE))[(index)]; }) + #ifdef CN1_INCLUDE_NPE_CHECKS #define CHECK_NPE_TOP_OF_STACK() if(SP[-1].data.o == JAVA_NULL) { THROW_NULL_POINTER_EXCEPTION(); } #define CHECK_NPE_AT_STACK(pos) if(SP[-pos].data.o == JAVA_NULL) { THROW_NULL_POINTER_EXCEPTION(); } @@ -4297,7 +4414,7 @@ static inline void cn1InitMethodStackInline(CODENAME_ONE_THREAD_STATE, JAVA_OBJE threadStateData->callStackOffset++; } -// How SP is declared, and why it is a parameter rather than a fixed token. +// How SP is declared, and why it is never volatile. // // ParparVM compiles a try/catch into a setjmp region, so the edges leaving it // are abnormal ones. SP is modified all through that region -- every push and @@ -4314,97 +4431,105 @@ static inline void cn1InitMethodStackInline(CODENAME_ONE_THREAD_STATE, JAVA_OBJE // method with a short-circuit condition inside a try was enough to trigger it, // which means app code, not just the framework. // -// `volatile` goes on the POINTER, not the pointee: `struct elementStruct* volatile SP` -// keeps SP itself in memory so longjmp cannot clobber it, while stack slot -// accesses through it stay ordinary. Writing `volatile struct elementStruct* SP` -// would instead make every operand-stack read and write volatile, which is a -// different -- and expensive -- statement. +// The fix is to keep SP DEAD across that edge, not to keep it in memory. Every +// frame records where SP starts in a const, cn1SpEntry, and CN1_TRY_ENTRY assigns +// SP from it on both returns of the setjmp; the catch blocks then assign it again +// (&stack[1]) before anything reads it. Nothing modified since the setjmp is ever +// read after a longjmp, which is what C99 asks, and no version of SP is live where +// the abnormal edges meet, which is what gcc needs. +// +// SP used to be `volatile` here instead, and that sent every push and pop of a +// method with a try through memory -- a load and a store of SP for each, and the +// whole operand stack with them. A Python `for` loop has a try (it closes a +// generator it abandons), so a trivial loop body cost 70ns an iteration against +// CPython's 50. CN1_TRY_ENTRY is emitted as a method's first statement, before any +// instruction has pushed, so cn1SpEntry is also where SP stands when it runs. // -// Only frames that actually emit setjmp pay for it; BytecodeMethod picks the -// _VSP variant using the same test it already uses to decide whether locals are -// volatile. -#define CN1_DECLARE_SP(spQualifier, spPosition) \ - struct elementStruct* spQualifier SP CN1_UNUSED = &stack[spPosition]; +// What volatile also did, by accident, was keep the frame in memory: the compiler +// could not tell which slot a store through SP hit, so no local slot ever lived in a +// register. With SP in a register clang can tell, and it promoted a frameless +// frame's locals to registers -- a catch then read the values they held at the +// setjmp, and a transaction's catch rolled back the wrong connection (BackendOrmTest). +// So CN1_TRY_ENTRY hands the frame's address to an empty asm: the frame has escaped, +// every slot is stored before any call, and a throw happens only inside a call, so +// the catch reads what the slots held when it was thrown. +#define CN1_DECLARE_SP(spPosition) \ + struct elementStruct* const cn1SpEntry CN1_UNUSED = &stack[spPosition]; \ + struct elementStruct* SP CN1_UNUSED = cn1SpEntry; // we need to zero out the values with memset otherwise we will run into a problem // when invoking release on pre-existing object which might be garbage -#define DEFINE_METHOD_STACK_IMPL(spQualifier, stackSize, localsStackSize, spPosition, classNameId, methodNameId) \ +#define DEFINE_METHOD_STACK_IMPL(stackSize, localsStackSize, spPosition, classNameId, methodNameId) \ const int cn1LocalsBeginInThread = threadStateData->threadObjectStackOffset; \ struct elementStruct* locals CN1_UNUSED = &threadStateData->threadObjectStack[cn1LocalsBeginInThread]; \ struct elementStruct* stack = &threadStateData->threadObjectStack[threadStateData->threadObjectStackOffset + localsStackSize]; \ - CN1_DECLARE_SP(spQualifier, spPosition) \ + CN1_DECLARE_SP(spPosition) \ cn1InitMethodStackInline(threadStateData, (JAVA_OBJECT)1, stackSize, localsStackSize, classNameId, methodNameId); \ const int currentCodenameOneCallStackOffset CN1_UNUSED = threadStateData->callStackOffset;\ int* const cn1CurrentLine CN1_UNUSED = &threadStateData->callStackLine[currentCodenameOneCallStackOffset - 1]; \ int methodBlockOffset CN1_UNUSED = threadStateData->tryBlockOffset; -#define DEFINE_METHOD_STACK(stackSize, localsStackSize, spPosition, classNameId, methodNameId) DEFINE_METHOD_STACK_IMPL(, stackSize, localsStackSize, spPosition, classNameId, methodNameId) -#define DEFINE_METHOD_STACK_VSP(stackSize, localsStackSize, spPosition, classNameId, methodNameId) DEFINE_METHOD_STACK_IMPL(volatile, stackSize, localsStackSize, spPosition, classNameId, methodNameId) +#define DEFINE_METHOD_STACK(stackSize, localsStackSize, spPosition, classNameId, methodNameId) DEFINE_METHOD_STACK_IMPL(stackSize, localsStackSize, spPosition, classNameId, methodNameId) -#define DEFINE_INSTANCE_METHOD_STACK_IMPL(spQualifier, stackSize, localsStackSize, spPosition, classNameId, methodNameId) \ +#define DEFINE_INSTANCE_METHOD_STACK_IMPL(stackSize, localsStackSize, spPosition, classNameId, methodNameId) \ const int cn1LocalsBeginInThread = threadStateData->threadObjectStackOffset; \ struct elementStruct* locals CN1_UNUSED = &threadStateData->threadObjectStack[cn1LocalsBeginInThread]; \ struct elementStruct* stack = &threadStateData->threadObjectStack[threadStateData->threadObjectStackOffset + localsStackSize]; \ - CN1_DECLARE_SP(spQualifier, spPosition) \ + CN1_DECLARE_SP(spPosition) \ cn1InitMethodStackInline(threadStateData, __cn1ThisObject, stackSize, localsStackSize, classNameId, methodNameId); \ const int currentCodenameOneCallStackOffset CN1_UNUSED = threadStateData->callStackOffset;\ int* const cn1CurrentLine CN1_UNUSED = &threadStateData->callStackLine[currentCodenameOneCallStackOffset - 1]; \ int methodBlockOffset CN1_UNUSED = threadStateData->tryBlockOffset; -#define DEFINE_INSTANCE_METHOD_STACK(stackSize, localsStackSize, spPosition, classNameId, methodNameId) DEFINE_INSTANCE_METHOD_STACK_IMPL(, stackSize, localsStackSize, spPosition, classNameId, methodNameId) -#define DEFINE_INSTANCE_METHOD_STACK_VSP(stackSize, localsStackSize, spPosition, classNameId, methodNameId) DEFINE_INSTANCE_METHOD_STACK_IMPL(volatile, stackSize, localsStackSize, spPosition, classNameId, methodNameId) +#define DEFINE_INSTANCE_METHOD_STACK(stackSize, localsStackSize, spPosition, classNameId, methodNameId) DEFINE_INSTANCE_METHOD_STACK_IMPL(stackSize, localsStackSize, spPosition, classNameId, methodNameId) -#define DEFINE_METHOD_STACK_FAST_REF_IMPL(spQualifier, stackSize, localsStackSize, spPosition) \ +#define DEFINE_METHOD_STACK_FAST_REF_IMPL(stackSize, localsStackSize, spPosition) \ const int cn1LocalsBeginInThread = threadStateData->threadObjectStackOffset; \ struct elementStruct* locals CN1_UNUSED = &threadStateData->threadObjectStack[cn1LocalsBeginInThread]; \ struct elementStruct* stack = &threadStateData->threadObjectStack[threadStateData->threadObjectStackOffset + localsStackSize]; \ - CN1_DECLARE_SP(spQualifier, spPosition) \ + CN1_DECLARE_SP(spPosition) \ cn1_init_method_stack_fast(threadStateData, (JAVA_OBJECT)1, stackSize, localsStackSize, JAVA_TRUE); \ const int currentCodenameOneCallStackOffset CN1_UNUSED = threadStateData->callStackOffset;\ int* const cn1CurrentLine CN1_UNUSED = &threadStateData->callStackLine[currentCodenameOneCallStackOffset - 1]; \ int methodBlockOffset CN1_UNUSED = threadStateData->tryBlockOffset; -#define DEFINE_METHOD_STACK_FAST_REF(stackSize, localsStackSize, spPosition) DEFINE_METHOD_STACK_FAST_REF_IMPL(, stackSize, localsStackSize, spPosition) -#define DEFINE_METHOD_STACK_FAST_REF_VSP(stackSize, localsStackSize, spPosition) DEFINE_METHOD_STACK_FAST_REF_IMPL(volatile, stackSize, localsStackSize, spPosition) +#define DEFINE_METHOD_STACK_FAST_REF(stackSize, localsStackSize, spPosition) DEFINE_METHOD_STACK_FAST_REF_IMPL(stackSize, localsStackSize, spPosition) -#define DEFINE_INSTANCE_METHOD_STACK_FAST_REF_IMPL(spQualifier, stackSize, localsStackSize, spPosition) \ +#define DEFINE_INSTANCE_METHOD_STACK_FAST_REF_IMPL(stackSize, localsStackSize, spPosition) \ const int cn1LocalsBeginInThread = threadStateData->threadObjectStackOffset; \ struct elementStruct* locals CN1_UNUSED = &threadStateData->threadObjectStack[cn1LocalsBeginInThread]; \ struct elementStruct* stack = &threadStateData->threadObjectStack[threadStateData->threadObjectStackOffset + localsStackSize]; \ - CN1_DECLARE_SP(spQualifier, spPosition) \ + CN1_DECLARE_SP(spPosition) \ cn1_init_method_stack_fast(threadStateData, __cn1ThisObject, stackSize, localsStackSize, JAVA_TRUE); \ const int currentCodenameOneCallStackOffset CN1_UNUSED = threadStateData->callStackOffset;\ int* const cn1CurrentLine CN1_UNUSED = &threadStateData->callStackLine[currentCodenameOneCallStackOffset - 1]; \ int methodBlockOffset CN1_UNUSED = threadStateData->tryBlockOffset; -#define DEFINE_INSTANCE_METHOD_STACK_FAST_REF(stackSize, localsStackSize, spPosition) DEFINE_INSTANCE_METHOD_STACK_FAST_REF_IMPL(, stackSize, localsStackSize, spPosition) -#define DEFINE_INSTANCE_METHOD_STACK_FAST_REF_VSP(stackSize, localsStackSize, spPosition) DEFINE_INSTANCE_METHOD_STACK_FAST_REF_IMPL(volatile, stackSize, localsStackSize, spPosition) +#define DEFINE_INSTANCE_METHOD_STACK_FAST_REF(stackSize, localsStackSize, spPosition) DEFINE_INSTANCE_METHOD_STACK_FAST_REF_IMPL(stackSize, localsStackSize, spPosition) -#define DEFINE_METHOD_STACK_FAST_PRIMITIVE_IMPL(spQualifier, stackSize, localsStackSize, spPosition) \ +#define DEFINE_METHOD_STACK_FAST_PRIMITIVE_IMPL(stackSize, localsStackSize, spPosition) \ const int cn1LocalsBeginInThread = threadStateData->threadObjectStackOffset; \ struct elementStruct* locals CN1_UNUSED = &threadStateData->threadObjectStack[cn1LocalsBeginInThread]; \ struct elementStruct* stack = &threadStateData->threadObjectStack[threadStateData->threadObjectStackOffset + localsStackSize]; \ - CN1_DECLARE_SP(spQualifier, spPosition) \ + CN1_DECLARE_SP(spPosition) \ cn1_init_method_stack_fast(threadStateData, (JAVA_OBJECT)1, stackSize, localsStackSize, JAVA_FALSE); \ const int currentCodenameOneCallStackOffset CN1_UNUSED = threadStateData->callStackOffset;\ int* const cn1CurrentLine CN1_UNUSED = &threadStateData->callStackLine[currentCodenameOneCallStackOffset - 1]; \ int methodBlockOffset CN1_UNUSED = threadStateData->tryBlockOffset; -#define DEFINE_METHOD_STACK_FAST_PRIMITIVE(stackSize, localsStackSize, spPosition) DEFINE_METHOD_STACK_FAST_PRIMITIVE_IMPL(, stackSize, localsStackSize, spPosition) -#define DEFINE_METHOD_STACK_FAST_PRIMITIVE_VSP(stackSize, localsStackSize, spPosition) DEFINE_METHOD_STACK_FAST_PRIMITIVE_IMPL(volatile, stackSize, localsStackSize, spPosition) +#define DEFINE_METHOD_STACK_FAST_PRIMITIVE(stackSize, localsStackSize, spPosition) DEFINE_METHOD_STACK_FAST_PRIMITIVE_IMPL(stackSize, localsStackSize, spPosition) -#define DEFINE_INSTANCE_METHOD_STACK_FAST_PRIMITIVE_IMPL(spQualifier, stackSize, localsStackSize, spPosition) \ +#define DEFINE_INSTANCE_METHOD_STACK_FAST_PRIMITIVE_IMPL(stackSize, localsStackSize, spPosition) \ const int cn1LocalsBeginInThread = threadStateData->threadObjectStackOffset; \ struct elementStruct* locals CN1_UNUSED = &threadStateData->threadObjectStack[cn1LocalsBeginInThread]; \ struct elementStruct* stack = &threadStateData->threadObjectStack[threadStateData->threadObjectStackOffset + localsStackSize]; \ - CN1_DECLARE_SP(spQualifier, spPosition) \ + CN1_DECLARE_SP(spPosition) \ cn1_init_method_stack_fast(threadStateData, __cn1ThisObject, stackSize, localsStackSize, JAVA_FALSE); \ const int currentCodenameOneCallStackOffset CN1_UNUSED = threadStateData->callStackOffset;\ int* const cn1CurrentLine CN1_UNUSED = &threadStateData->callStackLine[currentCodenameOneCallStackOffset - 1]; \ int methodBlockOffset CN1_UNUSED = threadStateData->tryBlockOffset; -#define DEFINE_INSTANCE_METHOD_STACK_FAST_PRIMITIVE(stackSize, localsStackSize, spPosition) DEFINE_INSTANCE_METHOD_STACK_FAST_PRIMITIVE_IMPL(, stackSize, localsStackSize, spPosition) -#define DEFINE_INSTANCE_METHOD_STACK_FAST_PRIMITIVE_VSP(stackSize, localsStackSize, spPosition) DEFINE_INSTANCE_METHOD_STACK_FAST_PRIMITIVE_IMPL(volatile, stackSize, localsStackSize, spPosition) +#define DEFINE_INSTANCE_METHOD_STACK_FAST_PRIMITIVE(stackSize, localsStackSize, spPosition) DEFINE_INSTANCE_METHOD_STACK_FAST_PRIMITIVE_IMPL(stackSize, localsStackSize, spPosition) #define CN1_FAST_RETURN_RELEASE() \ threadStateData->threadObjectStackOffset = cn1LocalsBeginInThread; \ @@ -4419,14 +4544,13 @@ static inline void cn1InitMethodStackInline(CODENAME_ONE_THREAD_STATE, JAVA_OBJE // no callStackOffset bump. The method body (PUSH/POP/SP ops, arithmetic, calls) // is emitted byte-for-byte unchanged; it just operates on this local SP. Frame // elimination is GC-trivial here -- it changes nothing the collector sees. -#define DEFINE_METHOD_STACK_FRAMELESS_IMPL(spQualifier, stackSize, localsStackSize, spPosition) \ +#define DEFINE_METHOD_STACK_FRAMELESS_IMPL(stackSize, localsStackSize, spPosition) \ struct elementStruct cn1_frameless_frame[(localsStackSize) + (stackSize)]; \ struct elementStruct* locals CN1_UNUSED = &cn1_frameless_frame[0]; \ struct elementStruct* stack = &cn1_frameless_frame[localsStackSize]; \ - CN1_DECLARE_SP(spQualifier, spPosition) + CN1_DECLARE_SP(spPosition) -#define DEFINE_METHOD_STACK_FRAMELESS(stackSize, localsStackSize, spPosition) DEFINE_METHOD_STACK_FRAMELESS_IMPL(, stackSize, localsStackSize, spPosition) -#define DEFINE_METHOD_STACK_FRAMELESS_VSP(stackSize, localsStackSize, spPosition) DEFINE_METHOD_STACK_FRAMELESS_IMPL(volatile, stackSize, localsStackSize, spPosition) +#define DEFINE_METHOD_STACK_FRAMELESS(stackSize, localsStackSize, spPosition) DEFINE_METHOD_STACK_FRAMELESS_IMPL(stackSize, localsStackSize, spPosition) // The two names a try/catch needs that a frameless frame does not otherwise define. // Emitted ONLY into frameless methods that contain one, so the other 90% of frameless @@ -5042,9 +5166,8 @@ static inline struct elementStruct* popAndRelease(CODENAME_ONE_THREAD_STATE, str // Inlined: POP_INT/POP_LONG/POP_OBJ hit this on every pop, including hot return paths // (return POP_LONG()). It was a non-inline call -- pure overhead for a pointer decrement. -// Returns the new SP rather than writing through a pointer to it, so the caller's -// SP keeps whatever qualifiers its frame gave it. The pointer-taking form -// discarded volatile on every frame that declares SP volatile; see POP_MANY. +// Returns the new SP rather than writing through a pointer to it, so the caller +// never takes SP's address and can keep it in a register. extern struct elementStruct* cn1PopMany(CODENAME_ONE_THREAD_STATE, int count, struct elementStruct* sp); diff --git a/vm/ByteCodeTranslator/src/cn1_globals.m b/vm/ByteCodeTranslator/src/cn1_globals.m index 4025282ac7e..c1d42e54b19 100644 --- a/vm/ByteCodeTranslator/src/cn1_globals.m +++ b/vm/ByteCodeTranslator/src/cn1_globals.m @@ -1213,6 +1213,9 @@ static inline int cn1GcIsOld(JAVA_OBJECT o, int m) { // Because grace no longer covers every fresh object, the barriers stop filtering fresh // references (cn1GcFreshFilter): a released thread moving a pre-cycle fresh object from // an unscanned container into a scanned one must be logged, exactly as an old object is. +// Concurrent cycles take the pre-cycle pages the same way (cn1GcHybridBeginConcurrent) but +// keep the filter, narrowed: it no longer skips a fresh object on a pre-cycle page +// (CN1_SATB_ON_PRE_CYCLE_PAGE), and every other fresh object still has its grace. // // "One core" is the online CPU count, or the core count the scaling matrix emulates with // CN1_GC_MARK_THREADS=1. Evaluated once; the mode cannot change within a process. @@ -1363,9 +1366,8 @@ static JAVA_BOOLEAN cn1GcHybridDecide(void) { // once the thread filled and retired that page or once a stop-the-world cycle held it // (cn1BibopRetireHeldThreadPages), on 1 and 4 markers, on master and before #5940 alike. // The root is the allocation page, not a stack word. It is not avoidable in a concurrent -// cycle: the owner bumps that page while the cycle runs, and the barriers filter fresh -// references there (cn1GcFreshFilter) on the strength of grace, so freeing an unmarked -// fresh slot on it would be unsound -- and the clear must match what the sweep frees. It +// cycle: the owner bumps that page while the cycle runs, so an unmarked fresh slot on it +// may have been allocated after the roots were scanned and freeing it would be unsound -- and the clear must match what the sweep frees. It // is bounded: one page per size class per thread, released at the next page fill or the // next stop-the-world hold. A test that asserts a weak referent clears must therefore // retire the page first (or use a referent off the page heap), never just wait. @@ -1381,8 +1383,7 @@ static inline int cn1GcSweepReclaimsObj(JAVA_OBJECT o, int mark) { return 1; } #ifndef CN1_DISABLE_BIBOP - if(cn1GcStwCycle && CN1_OBJ_HEAPPOS(o) == CN1_BIBOP_HEAP_POS - && CN1_OBJ_CLASS(o) != 0) { + if(CN1_OBJ_HEAPPOS(o) == CN1_BIBOP_HEAP_POS && CN1_OBJ_CLASS(o) != 0) { CN1BibopPage* pg = (CN1BibopPage*)((uintptr_t)o & ~((uintptr_t)CN1_BIBOP_PAGE_SIZE - 1)); return pg->gcPreCycle; } @@ -1997,15 +1998,24 @@ static void init_gc_thresholds() { } +// The element type id of each reference array class, indexed by the array's id less the +// first reference array id (cn1_array_start_offset+100). Generated: a reference array +// has an id only when the program has that array class, so neither its dimension nor its +// element can be computed from the id. +extern const int cn1RefArrayComponent[]; + int instanceofFunction(int sourceClass, int destId) { if(sourceClass == destId) { return JAVA_TRUE; } - if (sourceClass == cn1_array_1_id_JAVA_INT && destId == cn1_class_id_java_lang_Object) { - int foo = 1; - } - if (destId == cn1_array_1_id_JAVA_INT && sourceClass == cn1_class_id_java_lang_Object) { - int foo = 1; + /* EVERYTHING IS AN OBJECT, arrays included, so this needs no table. It is + * the question the array-store check asks of every store into an Object[] + * (backend builds turn that check on), and the walk below answered it by + * scanning the stored value's whole supertype list for Object, which it + * reaches last: measured as 3.5% of llm's log writer, transpiled Python + * storing into Object[] slots on nearly every call. */ + if(sourceClass == cn1_class_id_java_lang_Object) { + return JAVA_TRUE; } if(sourceClass >= cn1_array_start_offset || destId >= cn1_array_start_offset) { @@ -2025,27 +2035,26 @@ int instanceofFunction(int sourceClass, int destId) { if (sourceClass < refArrayStartOffset || destId < refArrayStartOffset) { if (sourceClass >= refArrayStartOffset) { // We need to deal with things like (int[][] instanceof Object[]) - int srcDim = (sourceClass - refArrayStartOffset)%3+1; + int srcDim = 1; + int element = cn1RefArrayComponent[sourceClass - refArrayStartOffset]; + while (element >= refArrayStartOffset) { + srcDim++; + element = cn1RefArrayComponent[element - refArrayStartOffset]; + } int destDim = (destId - cn1_array_start_offset)%4; if (srcDim < destDim) { - if (srcDim > 1) { - sourceClass = sourceClass-1; - } else { - sourceClass =(sourceClass - refArrayStartOffset)/3; - } + sourceClass = cn1RefArrayComponent[sourceClass - refArrayStartOffset]; return instanceofFunction(sourceClass, destId-1); } } // if either is primitive, then they must be the same type. return sourceClass == destId; } - int srcDimension = (sourceClass - refArrayStartOffset)%3+1; - int destDimension = (destId - refArrayStartOffset)%3+1; - - int sourceClassComponentTypeId = srcDimension > 1 ? sourceClass-1 : (sourceClass - refArrayStartOffset)/3; - int destClassComponentTypeId = destDimension > 1 ? destId-1 : (destId - refArrayStartOffset)/3; - return instanceofFunction(sourceClassComponentTypeId, destClassComponentTypeId); + // Element against element. An array of fewer dimensions reaches a class id while + // the other is still an array, and the tests above answer that. + return instanceofFunction(cn1RefArrayComponent[sourceClass - refArrayStartOffset], + cn1RefArrayComponent[destId - refArrayStartOffset]); } int* i = classInstanceOf[destId]; @@ -2108,7 +2117,8 @@ void cn1InvokeFinalizer(CODENAME_ONE_THREAD_STATE, JAVA_OBJECT obj, void (*ptr)( threadStateData->blocks[threadStateData->tryBlockOffset].exceptionClass = 0; // catch-all threadStateData->blocks[threadStateData->tryBlockOffset].nativeBuffers = threadStateData->nativeBuffers; threadStateData->blocks[threadStateData->tryBlockOffset].builderAccess = threadStateData->builderAccess; - memcpy(threadStateData->blocks[threadStateData->tryBlockOffset].destination, __finTryJmp, sizeof(jmp_buf)); + threadStateData->blocks[threadStateData->tryBlockOffset].destination = &__finTryJmp; + threadStateData->blocks[threadStateData->tryBlockOffset].handler = 1; threadStateData->tryBlockOffset++; ptr(threadStateData, obj); threadStateData->tryBlockOffset = __savedTryBlock; @@ -4111,7 +4121,7 @@ static inline int cn1SatbNeedsEnqueue(JAVA_OBJECT object) { int epoch = atomic_load_explicit(&bibopGcEpoch, memory_order_acquire); int mark = CN1_OBJ_MARK_LOAD(object, __ATOMIC_ACQUIRE); #ifndef CN1_SATB_LOG_FRESH - if(mark == -1 && cn1GcFreshFilter) return 0; + if(mark == -1 && cn1GcFreshFilter && !CN1_SATB_ON_PRE_CYCLE_PAGE(object)) return 0; #endif if(mark == epoch && epoch == atomic_load_explicit(&bibopGcEpoch, memory_order_acquire)) { #ifdef CN1_GC_CONFORM @@ -5584,7 +5594,7 @@ static void gcMarkGraceWalkPages(CODENAME_ONE_THREAD_STATE) { continue; // another marker claimed this page } } - // Single-core mode: a pre-cycle page's fresh slots get no grace, so they are not + // A pre-cycle page's fresh slots get no grace, so they are not // roots either; the reachable ones were marked by the root drain. if(gp->gcPreCycle) { continue; @@ -8463,6 +8473,11 @@ JAVA_INT java_lang_System_identityHashCode___java_lang_Object_R_int(CODENAME_ONE static CN1BibopPage* _Atomic bibopSweepStack; // Treiber-ish (push CAS / swap); see above static pthread_mutex_t bibopMutex = PTHREAD_MUTEX_INITIALIZER; static pthread_once_t bibopOnce = PTHREAD_ONCE_INIT; +/* Set as cn1BibopDoInit's last act. The allocation path reads it before it calls + * pthread_once: that call is a jump through a dyld stub, paid by every allocation of + * the program to learn what one load says. A thread that reads 0 takes pthread_once, + * which is what waits for an initialisation still under way. */ +static _Atomic int bibopReady = 0; // Non-static: also read/written by the inlined bump fast path (cn1_globals.h). _Atomic long bibopBytesSinceGc = 0; _Atomic long bibopGcTriggerBytes = CN1_BIBOP_GC_TRIGGER_BYTES; @@ -8585,6 +8600,7 @@ static void cn1BibopDoInit() { atexit(cn1BibopExitReport); } #endif + atomic_store_explicit(&bibopReady, 1, memory_order_release); } @@ -9159,14 +9175,30 @@ static JAVA_BOOLEAN cn1GcHybridDecide(void) { return cn1GcHybridGen ? JAVA_TRUE : JAVA_FALSE; } -// A CONCURRENT cycle in a process that runs stop-the-world cycles too (outside a -// generational phase). Two things a stop-the-world cycle changed are restored: the -// fresh-reference filter, sound only while every fresh object gets grace, and any pages -// still flagged pre-cycle because a stop-the-world sweep was skipped -- they go back on the -// sweep stack with their grace. Being a full trace, it also discards the remembered set. -// A stop-the-world cycle turned concurrent before it began marking (the virtual-thread -// handshake). The concurrent restore below undoes what the stop-the-world start did: the -// fresh filter, the pre-cycle pages, and a set taken for a major (discarded with the rest). +// A CONCURRENT cycle. It takes the pre-cycle pages exactly as a stop-the-world cycle does: +// every page retired before the cycle began (the whole sweep stack) loses grace, and the +// barriers log a fresh reference to an object on one of those pages like any other +// (CN1_SATB_ON_PRE_CYCLE_PAGE). The filter itself stays on for every other fresh object, +// which keeps its grace: logging those is issue 5537's runaway log. +// +// WHY A CONCURRENT CYCLE CAN DO THIS. Grace exists for objects the mark may not have seen +// because they were allocated WHILE it ran. A retired page takes no allocation until a +// sweep hands it back, so every fresh slot on a page retired before this cycle began +// predates the cycle: reachable, it is reached from the roots or through the snapshot the +// barrier keeps -- the same two guarantees every old object already lives on -- and +// unreachable, it is garbage now. Objects allocated during the cycle land on pages their +// threads own, which no sweep touches, or on pages retired during it, which go onto the +// NEW sweep stack unflagged and keep the ordinary grace. +// +// What the old rule cost, measured on a 600k-element generator pipeline with ~5MB live: +// grace kept every object allocated since the previous sweep, so each trigger's worth of +// garbage survived one whole extra cycle and was traced as a root in it. The first two +// cycles reclaimed 0KB and 1.2MB, the heap settled at about three triggers (75MB of pages +// for 5MB live), and the grace pass traced 3.65M dead objects over six cycles. +// +// Being a full trace, it also discards the remembered set. A stop-the-world cycle turned +// concurrent before it began marking (the virtual-thread handshake) comes through here +// too, and keeps the pages that start already detached: nothing has been scanned yet. static void cn1GcHybridAbandonStw(void) { cn1GcHybridGen = 0; cn1GcHybridBeginConcurrent(); @@ -9176,16 +9208,7 @@ static void cn1GcHybridBeginConcurrent(void) { cn1GcHybridLastWasMinor = JAVA_FALSE; cn1GcHybridLastWasMajor = JAVA_FALSE; cn1GcFreshFilter = JAVA_TRUE; - while(cn1GcPreCycleList != 0) { - CN1BibopPage* l = cn1GcPreCycleList; - cn1GcPreCycleList = l->nextPool; - l->gcPreCycle = JAVA_FALSE; - CN1BibopPage* sh = atomic_load_explicit(&bibopSweepStack, memory_order_relaxed); - do { - l->nextPool = sh; - } while(!atomic_compare_exchange_weak_explicit(&bibopSweepStack, &sh, l, - memory_order_release, memory_order_relaxed)); - } + cn1BibopDetachPreCycle(); // The barrier stays armed once a phase has run (it records into a set this discards // every concurrent cycle, a full trace). The next phase still opens with a major. if(cn1GcGenBarrier) { @@ -12407,7 +12430,9 @@ JAVA_OBJECT cn1BibopAllocRecycledNoZero(CODENAME_ONE_THREAD_STATE, int size, str } static JAVA_OBJECT cn1BibopAlloc(CODENAME_ONE_THREAD_STATE, int size, struct clazz* parent) { - pthread_once(&bibopOnce, cn1BibopDoInit); + if(__builtin_expect(!atomic_load_explicit(&bibopReady, memory_order_acquire), 0)) { + pthread_once(&bibopOnce, cn1BibopDoInit); + } CN1_CLAZZ_REGISTER(parent); int ci = cn1BibopSizeToClass[size]; if(ci < 0) { @@ -13456,7 +13481,7 @@ static void cn1BibopSweep(CODENAME_ONE_THREAD_STATE) { } else if(m == -1 && !(preCycle && CN1_OBJ_CLASS(o) != 0 )) { // fresh, never marked -> one cycle of grace (legacy parity). Not on a - // pre-cycle page in single-core mode: allocated before every root scan + // pre-cycle page: allocated before the cycle began // and still unmarked, it is garbage and falls to the reclaim below. // (parentCls == 0 is a mid-construction object; it always keeps grace.) CN1_OBJ_MARK_STORE(o, V, __ATOMIC_RELAXED); @@ -17477,14 +17502,14 @@ void gcMarkObject(CODENAME_ONE_THREAD_STATE, JAVA_OBJECT obj, JAVA_BOOLEAN force // grace pass traces at all (an old object reachable ONLY through a fresh one). // Embedded primitives returned above, so nothing reference-bearing is lost. // - // Not for a child on a PRE-CYCLE page in single-core mode: that page is neither + // Not for a child on a PRE-CYCLE page: that page is neither // walked nor graced (its unmarked fresh slots are freed), so the skip's premise -- // "kept and traced on its own account anyway" -- is false there, and skipping left a // kept object pointing at a freed child. The verifier caught it on the first cycle. if(cn1GcGraceTraceFresh && !force && markSnapshot == -1 && CN1_OBJ_HEAPPOS(obj) == CN1_BIBOP_HEAP_POS - && !(cn1GcStwCycle && ((CN1BibopPage*)((uintptr_t)obj - & ~((uintptr_t)CN1_BIBOP_PAGE_SIZE - 1)))->gcPreCycle)) { + && !((CN1BibopPage*)((uintptr_t)obj + & ~((uintptr_t)CN1_BIBOP_PAGE_SIZE - 1)))->gcPreCycle) { #ifdef CN1_GC_CONFORM atomic_fetch_add_explicit(&cn1GraceFreshSkipped, 1, memory_order_relaxed); #endif @@ -18655,7 +18680,11 @@ JAVA_OBJECT cn1AllocFused(CODENAME_ONE_THREAD_STATE, int totalSize, struct clazz * Off unless CN1_ALLOC_SITES is set: one env read via pthread_once, then a * relaxed load, so a census build that does not ask for it pays a branch. */ +/* A power of two. A program of generated code has more sites than this; raise it with + * -DCN1_ALLOC_SITE_SLOTS when the report prints an overflow. */ +#ifndef CN1_ALLOC_SITE_SLOTS #define CN1_ALLOC_SITE_SLOTS 8192 +#endif #define CN1_ALLOC_SITE_PROBES 64 struct CN1AllocSiteRow { _Atomic(void*) pc; @@ -18668,6 +18697,15 @@ JAVA_OBJECT cn1AllocFused(CODENAME_ONE_THREAD_STATE, int totalSize, struct clazz static pthread_once_t cn1AllocSiteOnce = PTHREAD_ONCE_INIT; static int cn1AllocSiteEnabled = 0; +/* How many frames above the allocation call a site is named by. 0 is the caller of + * allocArray; when every site comes out as one shared helper (a generated array store, + * the varargs path), build with -DCN1_ALLOC_SITE_DEPTH=1 and -fno-omit-frame-pointer to + * name the helper's callers instead. A constant, because __builtin_return_address needs + * one. */ +#ifndef CN1_ALLOC_SITE_DEPTH +#define CN1_ALLOC_SITE_DEPTH 0 +#endif + static void cn1ResolveAllocSiteFlag(void) { cn1AllocSiteEnabled = getenv("CN1_ALLOC_SITES") != 0; } @@ -18726,7 +18764,12 @@ static void cn1ReportAllocSites(void) { snapPc[i] = atomic_load_explicit(&cn1AllocSiteRows[i].pc, memory_order_relaxed); snapCls[i] = atomic_load_explicit(&cn1AllocSiteRows[i].cls, memory_order_relaxed); } - for(int shown = 0 ; shown < 40 ; shown++) { + /* CN1_ALLOC_SITES= prints n rows where 40 is not the whole story. */ + int siteRows = getenv("CN1_ALLOC_SITES") != 0 ? atoi(getenv("CN1_ALLOC_SITES")) : 0; + if(siteRows < 40) { + siteRows = 40; + } + for(int shown = 0 ; shown < siteRows ; shown++) { int best = -1; long long bestBytes = 0; for(int i = 0 ; i < CN1_ALLOC_SITE_SLOTS ; i++) { @@ -18743,9 +18786,16 @@ static void cn1ReportAllocSites(void) { #if !defined(_WIN32) { Dl_info info; - if(dladdr(snapPc[best], &info) != 0 && info.dli_sname != 0) { - sym = info.dli_sname; - off = (long)((char*)snapPc[best] - (char*)info.dli_saddr); + if(dladdr(snapPc[best], &info) != 0) { + if(info.dli_sname != 0) { + sym = info.dli_sname; + off = (long)((char*)snapPc[best] - (char*)info.dli_saddr); + } else if(info.dli_fbase != 0) { + /* No dynamic symbol (a static function, or a stripped binary): the + * offset into the file, which addr2line -e resolves. */ + sym = "file"; + off = (long)((char*)snapPc[best] - (char*)info.dli_fbase); + } } } #endif @@ -18762,6 +18812,28 @@ static void cn1ReportAllocSites(void) { } #endif +#ifdef CN1_ALLOC_CENSUS +/* CN1_ALLOC_SITES_ARRAY=: name an array allocation by the return address n frames above + * allocArray, found by walking frame pointers, instead of by the build-time + * CN1_ALLOC_SITE_DEPTH. One build then answers "who calls the helper" and "who calls that" + * without a rebuild in between. Needs -fno-omit-frame-pointer, as the scalar walk does. */ +static int cn1AllocArrayDepth = -1; +static void* cn1ArraySitePc(void** fp, void* fallback) { + int d; + if(cn1AllocArrayDepth < 0) { + const char* v = getenv("CN1_ALLOC_SITES_ARRAY"); + cn1AllocArrayDepth = v != 0 ? atoi(v) : 0; + } + if(cn1AllocArrayDepth <= 0) { + return fallback; + } + for(d = 0; d < cn1AllocArrayDepth && fp != 0; d++) { + fp = (void**)fp[0]; + } + return fp != 0 && fp[1] != 0 ? fp[1] : fallback; +} +#endif + JAVA_OBJECT allocArray(CODENAME_ONE_THREAD_STATE, int length, struct clazz* type, int primitiveSize, int dim) { // primitiveSize and dim are stored in a BYTE each (see struct JavaArrayPrototype). // Every in-tree caller passes a sizeof() of at most 8 and a dimension of at most 4, so @@ -18774,9 +18846,39 @@ JAVA_OBJECT allocArray(CODENAME_ONE_THREAD_STATE, int length, struct clazz* type // Size and address both come from CN1_ARRAY_* so they cannot drift apart; the // eight bytes this used to add on top were dead (see cn1_globals.h). #ifdef CN1_ALLOC_CENSUS - cn1RecordAllocSite(__builtin_return_address(0), type, CN1_ARRAY_ALLOC_BYTES(actualSize)); + cn1RecordAllocSite(cn1ArraySitePc((void**)__builtin_frame_address(0), __builtin_return_address(CN1_ALLOC_SITE_DEPTH)), + type, CN1_ARRAY_ALLOC_BYTES(actualSize)); +#endif + JAVA_ARRAY array = 0; +#if !defined(CN1_DISABLE_BIBOP) && defined(CN1_CONSERVATIVE_GC_ROOTS) && !defined(CN1_GC_INSTRUMENT) + /* A small array takes the bump slot a small object takes (cn1BibopFastAlloc), here + * rather than three calls down: codenameOneGcMalloc, cn1BibopAlloc and the slot + * initializer between them cost more than the allocation they lead to, and code + * that passes arguments and builds tuples allocates little else. Everything the + * long way decides before it reaches a bump slot is tested first, so anything but + * the plain case still goes that way: a class not registered yet, a real-time trap + * or memory limit, a suspended application, a heap not set up. The length test + * also keeps a size that overflowed int away from the size table. The bytes are + * charged when the page is retired, as an object's are. */ + if(__builtin_expect((unsigned int)length <= (unsigned int)CN1_BIBOP_MAX_OBJECT + && (size_t)CN1_ARRAY_ALLOC_BYTES(actualSize) <= (size_t)CN1_BIBOP_MAX_OBJECT + && type != 0 && type->cn1ClazzRegistered + && !threadStateData->rtAllocTrap && cn1RtMemoryLimitBytes <= 0 && !isAppSuspended + && atomic_load_explicit(&bibopReady, memory_order_acquire), 1)) { + int bytes = (int)CN1_ARRAY_ALLOC_BYTES(actualSize); + array = (JAVA_ARRAY)cn1BibopFastAlloc(threadStateData, bytes, type, cn1BibopSizeToClass[bytes], + cn1ClazzIndexOf(type)); + if(array == 0) { + /* A page the sweep gave a free list has no bump room, which is every page + * of a heap that has reached its working size. */ + array = (JAVA_ARRAY)cn1BibopAllocRecycled(threadStateData, bytes, type, cn1BibopSizeToClass[bytes]); + } + } + if(array == 0) #endif - JAVA_ARRAY array = (JAVA_ARRAY)codenameOneGcMalloc(threadStateData, (int)CN1_ARRAY_ALLOC_BYTES(actualSize), type); + { + array = (JAVA_ARRAY)codenameOneGcMalloc(threadStateData, (int)CN1_ARRAY_ALLOC_BYTES(actualSize), type); + } (*array).length = length; (*array).dimensions = dim; (*array).primitiveSize = primitiveSize; @@ -19219,6 +19321,24 @@ JAVA_OBJECT newStringFromUtf8Len(CODENAME_ONE_THREAD_STATE, const char* str, int if(length < 0) { length = 0; } + /* All ASCII -- most text a database or a protocol hands over -- decodes to its + own bytes, straight into a compact string: no widening into a unit buffer + for cn1StringFromUnits to scan and narrow again. Eight bytes per test. */ + { + int k = 0; + unsigned long long high = 0; + for(; k + 8 <= length ; k += 8) { + unsigned long long w; + memcpy(&w, str + k, 8); + high |= w; + } + for(; k < length ; k++) { + high |= (unsigned char)str[k]; + } + if((high & 0x8080808080808080ULL) == 0) { + return newStringFromAsciiLen(threadStateData, str, length); + } + } /* One UTF-16 unit per input BYTE is always enough: a 1-byte sequence yields 1, and the only multi-unit case (a 4-byte sequence yielding a surrogate pair) yields 2 units from 4 bytes. An invalid byte yields exactly one U+FFFD. */ @@ -19524,7 +19644,7 @@ JAVA_OBJECT xmlvm_create_java_string(CODENAME_ONE_THREAD_STATE, const char *chr) // fillInStack's null-check skips trace building entirely: throwing it // allocates nothing and calls nothing. JAVA_OBJECT cn1PreallocSOE = JAVA_NULL; -extern void set_field_java_lang_Throwable_stack(JAVA_OBJECT __cn1Val, JAVA_OBJECT __cn1T); +extern void (set_field_java_lang_Throwable_stack)(JAVA_OBJECT __cn1Val, JAVA_OBJECT __cn1T); void cn1ThrowStackOverflow(CODENAME_ONE_THREAD_STATE) { JAVA_OBJECT soe = cn1PreallocSOE; @@ -20085,7 +20205,12 @@ static long long cn1StallPercentileUs(int cause, double q) { // by omission (see the entry-point note on cn1RecordAllocation). The overflow // row is how a reader learns the bound was reached instead of trusting a total // that quietly excludes it. +// A profiling build of a larger app may pass -DCN1_ALLOC_PROFILE_SLOTS=32768: +// the musl failure above is the static Linux binary's; a dynamic macOS one +// with 16646 classes prints at 32768. +#ifndef CN1_ALLOC_PROFILE_SLOTS #define CN1_ALLOC_PROFILE_SLOTS 8192 +#endif static _Atomic long long cn1AllocProfBytes[CN1_ALLOC_PROFILE_SLOTS]; static _Atomic long cn1AllocProfCount[CN1_ALLOC_PROFILE_SLOTS]; // Atomic like the counters beside it. Several mutators allocating the same class @@ -20205,11 +20330,41 @@ static int cn1SlotClassFor(int size, int allow16) { return 0; } +#ifdef CN1_ALLOC_CENSUS +/* CN1_ALLOC_SITES_SCALAR=: object allocations join the CN1_ALLOC_SITES table too, each + * named by the return address n frames above this function, found by walking frame + * pointers -- the allocator's fast path is inlined into callers at different depths, so no + * one fixed __builtin_return_address names the code that wrote `new`. Needs a build with + * -fno-omit-frame-pointer; a chain that ends early stops the walk. */ +static int cn1AllocScalarDepth = -1; +static void cn1RecordScalarSite(struct clazz* parent, int size) { + void** fp; + int d; + if(cn1AllocScalarDepth < 0) { + const char* v = getenv("CN1_ALLOC_SITES_SCALAR"); + cn1AllocScalarDepth = v != 0 ? atoi(v) : 0; + } + if(cn1AllocScalarDepth <= 0) { + return; + } + fp = (void**)__builtin_frame_address(0); + for(d = 1; d < cn1AllocScalarDepth && fp != 0; d++) { + fp = (void**)fp[0]; + } + if(fp != 0 && fp[1] != 0) { + cn1RecordAllocSite(fp[1], parent, size); + } +} +#endif + void cn1RecordAllocation(struct clazz* parent, int size) { int id; if(parent == 0) { return; } +#ifdef CN1_ALLOC_CENSUS + cn1RecordScalarSite(parent, size); +#endif // Before the id range check, so a class past the table still contributes its // sizes -- the out-of-range row says a class is missing, this says what size // it was. @@ -21106,6 +21261,12 @@ JAVA_OBJECT fromNSString(CODENAME_ONE_THREAD_STATE, NSString* str) { return stringToUTF8Len(threadStateData, str, NULL); } +/* Encoded straight from the String's own characters into the thread's buffer. It went + * through String.getBytes("UTF-8") -- a charset lookup by name and a byte[] per call -- + * and a database binding a short text paid more for that than for sqlite3_bind_text. + * The bytes are getBytes' own: a UTF-16 String goes through the encoder it uses + * (an unpaired surrogate becomes U+FFFD), and Latin-1 is one or two bytes a char. */ +extern size_t cn1Utf8EncodeChars(const JAVA_ARRAY_CHAR* src, size_t len, JAVA_ARRAY_BYTE* out); const char* stringToUTF8Len(CODENAME_ONE_THREAD_STATE, JAVA_OBJECT str, JAVA_INT* lengthOut) { if(lengthOut != NULL) { *lengthOut = 0; @@ -21113,34 +21274,38 @@ JAVA_OBJECT fromNSString(CODENAME_ONE_THREAD_STATE, NSString* str) { if(str == NULL) { return NULL; } - if (utf8String == JAVA_NULL) { - utf8String = newStringFromCString(threadStateData, "UTF-8"); - removeObjectFromHeapCollection(threadStateData, utf8String); - removeObjectFromHeapCollection(threadStateData, ((struct obj__java_lang_String*)utf8String)->java_lang_String_value); - } - - JAVA_ARRAY byteArray = (JAVA_ARRAY)java_lang_String_getBytes___java_lang_String_R_byte_1ARRAY(threadStateData, str, utf8String); - JAVA_ARRAY_BYTE* data = CN1_ARRAY_DATA(byteArray); - - JAVA_INT len = byteArray->length; - - if(threadStateData->utf8Buffer == 0) { - threadStateData->utf8Buffer = malloc(len + 1); - threadStateData->utf8BufferSize = len+1; - } else { - if(threadStateData->utf8BufferSize < len + 1) { + JAVA_INT count = ((struct obj__java_lang_String*)str)->java_lang_String_count; + int latin1 = cn1StrIsLatin1(str); + const void* chars = cn1StrChars(str); + size_t need = (size_t)count * (latin1 ? 2 : 3) + 1; + if(threadStateData->utf8Buffer == 0 || (size_t)threadStateData->utf8BufferSize < need) { + if(threadStateData->utf8Buffer != 0) { free(threadStateData->utf8Buffer); - threadStateData->utf8Buffer = malloc(len + 1); - threadStateData->utf8BufferSize = len+1; } + threadStateData->utf8Buffer = malloc(need); + threadStateData->utf8BufferSize = (JAVA_INT)need; + } + unsigned char* out = (unsigned char*)threadStateData->utf8Buffer; + JAVA_INT n = 0; + if(latin1) { + const unsigned char* in = (const unsigned char*)chars; + for(JAVA_INT i = 0; i < count; i++) { + unsigned int c = in[i]; + if(c < 0x80) { + out[n++] = (unsigned char)c; + } else { + out[n++] = (unsigned char)(0xC0 | (c >> 6)); + out[n++] = (unsigned char)(0x80 | (c & 0x3F)); + } + } + } else { + n = (JAVA_INT)cn1Utf8EncodeChars((const JAVA_ARRAY_CHAR*)chars, (size_t)count, (JAVA_ARRAY_BYTE*)out); } - char* cs = threadStateData->utf8Buffer; - memcpy(cs, data, len); - cs[len] = '\0'; + out[n] = '\0'; if(lengthOut != NULL) { - *lengthOut = len; + *lengthOut = n; } - return cs; + return (const char*)out; } #if defined(__APPLE__) && defined(__OBJC__) @@ -21296,7 +21461,7 @@ void throwException(CODENAME_ONE_THREAD_STATE, JAVA_OBJECT exceptionArg) { int off = threadStateData->tryBlockOffset; cn1BuilderAccessUnwind(threadStateData, threadStateData->blocks[off].builderAccess); cn1StackBufferUnwind(threadStateData, threadStateData->blocks[off].nativeBuffers); - CN1_TRY_LONGJMP(threadStateData->blocks[off].destination, 1); + CN1_TRY_LONGJMP(*threadStateData->blocks[off].destination, 1); return; } threadStateData->tryBlockOffset--; @@ -21942,3 +22107,11 @@ static void cn1RtAccount(int size) { JAVA_LONG cn1RtThreadAllocViolations(CODENAME_ONE_THREAD_STATE) { return threadStateData->rtAllocViolations; } + +// The barrier half of cn1InlSetRefField (cn1_globals.h): exactly what a generated +// reference setter runs, insertion barrier then deletion barrier then the store. +void cn1SetRefFieldSlow(JAVA_OBJECT target, JAVA_OBJECT* addr, JAVA_OBJECT value) { + CN1_WRITE_BARRIER(target, value); + CN1_SATB_DELETE(addr); + *addr = value; +} diff --git a/vm/ByteCodeTranslator/src/cn1_intrinsics.h b/vm/ByteCodeTranslator/src/cn1_intrinsics.h index 3d4a83afd02..ac29fe448d4 100644 --- a/vm/ByteCodeTranslator/src/cn1_intrinsics.h +++ b/vm/ByteCodeTranslator/src/cn1_intrinsics.h @@ -132,6 +132,79 @@ static inline JAVA_BOOLEAN cn1InlListAdd(CODENAME_ONE_THREAD_STATE, JAVA_OBJECT } #endif +// Boxing at the call site. valueOf and xxxValue on Integer, Long and Double were plain +// calls into nativeMethods.m, and the generated files compile at -inline-threshold=50, so a +// tagged box -- a shift and an OR -- still cost a call per value: 5% of a Python generator +// drain was Long.valueOf alone. The tag work is done here; everything else (the clinit a +// first box must force, a value outside the tag range, a heap box, null) goes through the +// out-of-line function exactly as before. The prototypes are declared here rather than +// included because a class the program never boxes may have none, and an unused inline +// naming an undeclared function is still a compile error. +#if CN1_TAGGED_ACTIVE +extern int cn1__clinit_java_lang_Integer; +extern int cn1__clinit_java_lang_Long; +extern int cn1__clinit_java_lang_Double; +#endif +JAVA_OBJECT java_lang_Integer_valueOf___int_R_java_lang_Integer(CODENAME_ONE_THREAD_STATE, JAVA_INT i); +JAVA_OBJECT java_lang_Long_valueOf___long_R_java_lang_Long(CODENAME_ONE_THREAD_STATE, JAVA_LONG i); +JAVA_OBJECT java_lang_Double_valueOf___double_R_java_lang_Double(CODENAME_ONE_THREAD_STATE, JAVA_DOUBLE d); +JAVA_INT java_lang_Integer_intValue___R_int(CODENAME_ONE_THREAD_STATE, JAVA_OBJECT o); +JAVA_LONG java_lang_Long_longValue___R_long(CODENAME_ONE_THREAD_STATE, JAVA_OBJECT o); +JAVA_DOUBLE java_lang_Double_doubleValue___R_double(CODENAME_ONE_THREAD_STATE, JAVA_OBJECT o); + +static inline JAVA_OBJECT cn1InlBoxInt(CODENAME_ONE_THREAD_STATE, JAVA_INT v) { +#if CN1_TAGGED_ACTIVE + if(__builtin_expect(__atomic_load_n(&cn1__clinit_java_lang_Integer, __ATOMIC_ACQUIRE) != 0, 1)) { + return CN1_TAG_INT(v); + } +#endif + return java_lang_Integer_valueOf___int_R_java_lang_Integer(threadStateData, v); +} +static inline JAVA_OBJECT cn1InlBoxLong(CODENAME_ONE_THREAD_STATE, JAVA_LONG v) { +#if CN1_TAGGED_EXTRA_ACTIVE + if(__builtin_expect(CN1_LONG_TAGGABLE(v) && __atomic_load_n(&cn1__clinit_java_lang_Long, __ATOMIC_ACQUIRE) != 0, 1)) { + return CN1_TAG_LONG_VAL(v); + } +#endif + return java_lang_Long_valueOf___long_R_java_lang_Long(threadStateData, v); +} +static inline JAVA_OBJECT cn1InlBoxDouble(CODENAME_ONE_THREAD_STATE, JAVA_DOUBLE d) { +#if CN1_TAGGED_EXTRA_ACTIVE + union { JAVA_DOUBLE d; uint64_t b; } u; + u.d = d; + if(__builtin_expect(CN1_DOUBLE_TAGGABLE_BITS(u.b) && __atomic_load_n(&cn1__clinit_java_lang_Double, __ATOMIC_ACQUIRE) != 0, 1)) { + return CN1_TAG_DOUBLE_BITS(u.b); + } +#endif + return java_lang_Double_valueOf___double_R_java_lang_Double(threadStateData, d); +} +static inline JAVA_INT cn1InlUnboxInt(CODENAME_ONE_THREAD_STATE, JAVA_OBJECT o) { +#if CN1_TAGGED_ACTIVE + if(__builtin_expect(CN1_TAG_CODE(o) == CN1_TAG_INTEGER, 1)) { + return CN1_UNTAG_INT(o); + } +#endif + return java_lang_Integer_intValue___R_int(threadStateData, o); +} +static inline JAVA_LONG cn1InlUnboxLong(CODENAME_ONE_THREAD_STATE, JAVA_OBJECT o) { +#if CN1_TAGGED_EXTRA_ACTIVE + if(__builtin_expect(CN1_TAG_CODE(o) == CN1_TAG_LONG, 1)) { + return CN1_UNTAG_LONG(o); + } +#endif + return java_lang_Long_longValue___R_long(threadStateData, o); +} +static inline JAVA_DOUBLE cn1InlUnboxDouble(CODENAME_ONE_THREAD_STATE, JAVA_OBJECT o) { +#if CN1_TAGGED_EXTRA_ACTIVE + if(__builtin_expect(CN1_TAG_CODE(o) == CN1_TAG_DOUBLE, 1)) { + union { JAVA_DOUBLE d; uint64_t b; } u; + u.b = CN1_UNTAG_DOUBLE_BITS(o); + return u.d; + } +#endif + return java_lang_Double_doubleValue___R_double(threadStateData, o); +} + #if defined(__has_include) #if __has_include("java_lang_StringBuilder.h") && __has_include("java_lang_String.h") #include "java_lang_StringBuilder.h" @@ -142,6 +215,27 @@ static inline JAVA_BOOLEAN cn1InlListAdd(CODENAME_ONE_THREAD_STATE, JAVA_OBJECT #ifdef CN1_HAVE_SB_INTRINSICS +// cn1StrChars and cn1StrIsLatin1 (nativeMethods.m), for the inline bodies below. +// Those two are functions in another translation unit, so without link-time +// optimisation an inlined charAt was still two calls: a loop over a string paid +// them for every character. The store is still named in one place per form -- +// keep these two and their out-of-line twins the same. +extern struct clazz class_array1__JAVA_BYTE; +static inline __attribute__((always_inline)) void* cn1InlStrChars(JAVA_OBJECT s) { + JAVA_OBJECT v = ((struct obj__java_lang_String*)s)->java_lang_String_value; + if(v == JAVA_NULL) { + return (void*)((char*)s + ((sizeof(struct obj__java_lang_String) + 7) & ~(size_t)7)); + } + return CN1_ARRAY_DATA((JAVA_ARRAY)v); +} +static inline __attribute__((always_inline)) int cn1InlStrIsLatin1(JAVA_OBJECT s) { + JAVA_OBJECT v = ((struct obj__java_lang_String*)s)->java_lang_String_value; + if(v == JAVA_NULL) { + return CN1_OBJ_CLASS(s) == &class__java_lang_String_i8; + } + return CN1_OBJ_CLASS(((JAVA_ARRAY)v)) == &class_array1__JAVA_BYTE; +} + // Heap builders take the protected native path. Keep lock scopes out of these // small inline bodies so escape-proven stack builders retain their fast path. @@ -304,9 +398,9 @@ static inline JAVA_OBJECT cn1InlStrReplace(CODENAME_ONE_THREAD_STATE, JAVA_OBJEC CN1_KEEP_NATIVE_OWNER(sourceOwner, str); if(oldChar == newChar) return str; struct obj__java_lang_String* s = (struct obj__java_lang_String*)str; - if(cn1StrIsLatin1(str)) { + if(cn1InlStrIsLatin1(str)) { int count = s->java_lang_String_count; - const uint8_t* input = (const uint8_t*)cn1StrChars(str); + const uint8_t* input = (const uint8_t*)cn1InlStrChars(str); if(oldChar > 255 || memchr(input, oldChar, (size_t)count) == 0) return str; if(newChar <= 255) { JAVA_ARRAY_BYTE* output; @@ -345,22 +439,22 @@ static inline __attribute__((always_inline)) JAVA_BOOLEAN cn1InlStrEquals( if(count == 0) return JAVA_TRUE; int ah = a->java_lang_String_hashCode, bh = b->java_lang_String_hashCode; if(ah != 0 && bh != 0 && ah != bh) return JAVA_FALSE; - int al = cn1StrIsLatin1(self); - int bl = cn1StrIsLatin1(other); + int al = cn1InlStrIsLatin1(self); + int bl = cn1InlStrIsLatin1(other); if(al && bl) { - const uint8_t* x = (const uint8_t*)cn1StrChars(self); - const uint8_t* y = (const uint8_t*)cn1StrChars(other); + const uint8_t* x = (const uint8_t*)cn1InlStrChars(self); + const uint8_t* y = (const uint8_t*)cn1InlStrChars(other); return cn1CompactBytesEqual(x, y, (size_t)count); } - const uint16_t* ax = (const uint16_t*)cn1StrChars(self); - const uint16_t* bx = (const uint16_t*)cn1StrChars(other); + const uint16_t* ax = (const uint16_t*)cn1InlStrChars(self); + const uint16_t* bx = (const uint16_t*)cn1InlStrChars(other); if(!al && !bl) { return cn1CompactBytesEqual(ax, bx, (size_t)count * sizeof(uint16_t)); } - return al ? cn1CompactMixedEquals((const uint8_t*)cn1StrChars(self), + return al ? cn1CompactMixedEquals((const uint8_t*)cn1InlStrChars(self), bx, (size_t)count) - : cn1CompactMixedEquals((const uint8_t*)cn1StrChars(other), + : cn1CompactMixedEquals((const uint8_t*)cn1InlStrChars(other), ax, (size_t)count); } @@ -378,10 +472,10 @@ static inline JAVA_INT cn1InlStrHash(CODENAME_ONE_THREAD_STATE, JAVA_OBJECT s) { } JAVA_INT end = count; JAVA_INT i = 0; - if(cn1StrIsLatin1(s)) { + if(cn1InlStrIsLatin1(s)) { // Latin-1: (b & 0xff) IS the char value, so the hash is bit-identical to // the same text stored as char[]. 4-way reassociation mirrors the char path. - JAVA_ARRAY_BYTE* b = (JAVA_ARRAY_BYTE*)cn1StrChars(s); + JAVA_ARRAY_BYTE* b = (JAVA_ARRAY_BYTE*)cn1InlStrChars(s); for (; i + 4 <= end; i += 4) { hash = hash * 923521 + (b[i] & 0xff) * 29791 @@ -393,7 +487,7 @@ static inline JAVA_INT cn1InlStrHash(CODENAME_ONE_THREAD_STATE, JAVA_OBJECT s) { hash = 31 * hash + (b[i] & 0xff); } } else { - JAVA_ARRAY_CHAR* chars = (JAVA_ARRAY_CHAR*)cn1StrChars(s); + JAVA_ARRAY_CHAR* chars = (JAVA_ARRAY_CHAR*)cn1InlStrChars(s); for (; i + 4 <= end; i += 4) { hash = hash * 923521 + chars[i] * 29791 @@ -419,10 +513,10 @@ static inline JAVA_CHAR cn1InlStrCharAt(CODENAME_ONE_THREAD_STATE, JAVA_OBJECT s if(__builtin_expect((unsigned int)index < (unsigned int)t->java_lang_String_count, 1)) { JAVA_INT o = index; // Latin-1 vs UTF-16 chosen by the store, named in one place. - if(cn1StrIsLatin1(s)) { - return (JAVA_CHAR)(((JAVA_ARRAY_BYTE*)cn1StrChars(s))[o] & 0xff); + if(cn1InlStrIsLatin1(s)) { + return (JAVA_CHAR)(((JAVA_ARRAY_BYTE*)cn1InlStrChars(s))[o] & 0xff); } - return ((JAVA_ARRAY_CHAR*)cn1StrChars(s))[o]; + return ((JAVA_ARRAY_CHAR*)cn1InlStrChars(s))[o]; } return java_lang_String_charAt___int_R_char(threadStateData, s, index); // throws } diff --git a/vm/ByteCodeTranslator/src/cn1_sqlite3.c b/vm/ByteCodeTranslator/src/cn1_sqlite3.c index dfbcb65d7c8..d6a2f920239 100644 --- a/vm/ByteCodeTranslator/src/cn1_sqlite3.c +++ b/vm/ByteCodeTranslator/src/cn1_sqlite3.c @@ -86,9 +86,12 @@ #undef NSLog #endif -/* Codename One runs the database from several threads, and serialised mode is what makes that - * safe without the caller holding a lock. */ -#define SQLITE_THREADSAFE 1 +/* Multi-thread mode: no mutex on a connection or a statement, which serialised mode took on every + * call. A Database is not thread safe in Codename One -- ThreadSafeDatabase is the wrapper for + * sharing one -- and the backend's Db holds its monitor around every use of a handle. Not 0: + * the backend pool keeps connections on several threads at once, and SQLite's global state + * (allocator, page cache, VFS list) still needs its own mutexes for that. */ +#define SQLITE_THREADSAFE 2 /* Keep temporary tables and indices in memory: an app sandbox has no useful temp directory. */ #define SQLITE_TEMP_STORE 2 diff --git a/vm/ByteCodeTranslator/src/com/codename1/tools/translator/ByteCodeClass.java b/vm/ByteCodeTranslator/src/com/codename1/tools/translator/ByteCodeClass.java index 32ec47b4338..e1e42344a50 100644 --- a/vm/ByteCodeTranslator/src/com/codename1/tools/translator/ByteCodeClass.java +++ b/vm/ByteCodeTranslator/src/com/codename1/tools/translator/ByteCodeClass.java @@ -153,6 +153,38 @@ private static boolean hasNativeBlocks(String cls) { return false; } + /// Maps each plain reference setter onto cn1InlSetRefField (cn1_globals.h), so a + /// store is inlined at the call site instead of being a call: with both barrier + /// macros in its body a setter is far over clang's -inline-threshold=50, and every + /// reference store in the program was a call. Volatile fields, a Reference's + /// referent and builds with field null checks keep the out-of-line setter, whose + /// stores are atomic or checked. Emitted after the struct, for offsetof. + private void appendInlineRefSetters(StringBuilder b) { + if (Util.getProperty("fieldNullChecks", "false").equals("true")) { + return; + } + for (ByteCodeField fld : fullFieldList) { + if (!fld.isObjectType() || fld.isVolatile() || isReferenceReferent(clsName, fld)) { + continue; + } + String declGuard = targetGuardFor(fld.getClsName().replace('/', '_').replace('$', '_').replace('-', '_'), + fld.getFieldName()); + if (declGuard == null) { + declGuard = targetGuardFor(clsName, fld.getFieldName()); + } + if (declGuard != null) { + b.append("#if ").append(declGuard).append("\n"); + } + b.append("#define set_field_").append(clsName).append("_").append(fld.getFieldName()) + .append("(cn1__v, cn1__t) cn1InlSetRefField((cn1__t), offsetof(struct obj__") + .append(clsName).append(", ").append(fld.getClsName()).append("_") + .append(fld.getFieldName()).append("), (cn1__v))\n"); + if (declGuard != null) { + b.append("#endif\n"); + } + } + } + private static boolean isReferenceReferent(String owningClass, ByteCodeField fld) { return REFERENCE_CLASS.equals(owningClass) && REFERENCE_REFERENT_FIELD.equals(fld.getFieldName()) @@ -1222,7 +1254,8 @@ public String generateCCode(List allClasses) { // Accessors below test completion before fetching thread context. The // recursion flag in class__X is set before and cannot publish it. - b.append("static int __").append(clsName).append("_LOADED__=0;\n"); + // Not static: the header's inline static getters (see the header emitter) read it. + b.append("int __").append(clsName).append("_LOADED__=0;\n"); staticFieldList = new ArrayList(); buildStaticFieldList(staticFieldList); String enumValuesField = null; @@ -1317,12 +1350,14 @@ public String generateCCode(List allClasses) { b.append(" = 0;\n"); } - // static getter + // static getter. Parenthesized: the header maps the name onto an + // inline fast path with a function-like macro. b.append(bf.getCDefinition()); - b.append(" get_static_"); + b.append(" (get_static_"); b.append(clsName); b.append("_"); b.append(bf.getFieldName().replace('$', '_').replace('-', '_')); + b.append(")"); // Match the initializer's acquire/release completion check. // TLS lookup and initialization are cold after the first access. // No guard at all for an eagerly initialized class: it was @@ -1366,7 +1401,14 @@ public String generateCCode(List allClasses) { b.append(bf.getClsName()); b.append(bf.isObjectType() ? "(threadStateData);\n " : "(getThreadLocalData());\n "); } - if (bf.isObjectType()) { + if (bf.isObjectType() && !bf.isVolatile()) { + // The barriers and the store, behind one flag test: with both + // barrier macros expanded here every static was 330 bytes of + // setter, 10 MB of a program with thirty thousand of them. + // cn1SetRefFieldSlow runs the same two macros in the same order. + b.append("cn1InlSetStaticRef((JAVA_OBJECT*)&STATIC_FIELD_").append(bf.getClsName()) + .append("_").append(bf.getFieldName()).append(", __cn1StaticVal);"); + } else if (bf.isObjectType()) { // SATB insertion barrier: record the reference being stored, so // a static that takes a child mid-mark keeps it alive. b.append("CN1_WRITE_BARRIER(JAVA_NULL, __cn1StaticVal);\n "); @@ -1374,7 +1416,9 @@ public String generateCCode(List allClasses) { b.append("CN1_SATB_DELETE(&STATIC_FIELD_").append(bf.getClsName()) .append("_").append(bf.getFieldName()).append(");\n "); } - if (bf.isVolatile()) { + if (bf.isObjectType() && !bf.isVolatile()) { //NOPMD EmptyControlStatement - stored above + // cn1InlSetStaticRef stored it. + } else if (bf.isVolatile()) { b.append("atomic_store_explicit(&STATIC_FIELD_"); b.append(bf.getClsName()); b.append("_"); @@ -1483,13 +1527,26 @@ public String generateCCode(List allClasses) { // Instance field setters don't use thread context directly. // CN1_SETTER_INLINE: see its definition in cn1_globals.h. - b.append("CN1_SETTER_INLINE void set_field_"); + // Parenthesized: the header may map this name onto cn1InlSetRefField with a + // function-like macro (appendInlineRefSetters), which must not rewrite the + // definition itself. + b.append("CN1_SETTER_INLINE void (set_field_"); b.append(clsName); b.append("_"); b.append(fld.getFieldName()); - b.append("("); + b.append(")("); b.append(fld.getCDefinition()); - if(fld.isObjectType()) { + boolean mapped = fld.isObjectType() && !fld.isVolatile() && nullCheck.length() == 0 + && !isReferenceReferent(clsName, fld); + if(mapped) { + // The header maps this setter onto cn1InlSetRefField (appendInlineRefSetters), + // so nothing calls the function; it is the same code, and not a second + // expansion of both barriers -- 320 bytes a field, 12 MB of a program with + // forty thousand of them. + b.append(" __cn1Val, JAVA_OBJECT __cn1T) {\n cn1InlSetRefField(__cn1T, offsetof(struct obj__") + .append(clsName).append(", ").append(fld.getClsName()).append("_") + .append(fld.getFieldName()).append("), __cn1Val);\n}\n\n"); + } else if(fld.isObjectType()) { b.append(" __cn1Val, JAVA_OBJECT __cn1T) {\n ").append(nullCheck).append(" "); // SATB insertion barrier: record the reference being stored, so an object // linked into the graph mid-mark is kept alive even when the container it @@ -1507,7 +1564,9 @@ public String generateCCode(List allClasses) { } else { b.append(" __cn1Val, JAVA_OBJECT __cn1T) {\n ").append(nullCheck).append(" "); } - if(isReferenceReferent(clsName, fld)) { + if(mapped) { //NOPMD EmptyControlStatement - stored above + // cn1InlSetRefField stored it. + } else if(isReferenceReferent(clsName, fld)) { // Reference.clear() and the constructor both land here, and the collector // stores JAVA_NULL into the same word concurrently. Atomic for the reason // spelled out on the getter above. @@ -1984,7 +2043,9 @@ public String generateCCode(List allClasses) { } } else { for(BytecodeMethod m : virtualMethodList) { - m.appendVirtualMethodC(clsName, b, offset); + if(!inheritsThunk(m, offset)) { + m.appendVirtualMethodC(clsName, b, offset); + } offset++; } } @@ -2451,9 +2512,12 @@ private boolean isDefaultInterfaceMethod(BytecodeMethod method, List bm, ByteCodeClass base) { // append super stub BytecodeMethod.setAcceptStaticOnEquals(true); + // Nothing is written for an inherited method: the header names the + // declaring class's function under this class's name (appendSuperStubHeader). + // A forwarding function per class and inherited method was 430,000 functions + // and 27 MB of one program whose classes share a wide base class. for(BytecodeMethod m : base.methods) { if(!m.isPrivate() && !bm.contains(m)) { - m.appendSuperCall(b, clsName); bm.add(m); } } @@ -2463,6 +2527,21 @@ private void appendSuperStub(StringBuilder b, List bm, ByteCodeC BytecodeMethod.setAcceptStaticOnEquals(false); } + /// Whether this class's dispatch thunk for the method in `slot` is the base + /// class's: the method is inherited, not overridden here, it sits in the same + /// vtable slot, and both thunks resolve the receiver's class the same way. The + /// thunk reads the slot out of the receiver's own vtable, so the base class's + /// dispatches a subclass instance exactly as a second copy would. + private boolean inheritsThunk(BytecodeMethod m, int slot) { + ByteCodeClass base = baseClassObject; + return !isInterface && base != null && !base.isInterface + && !"java_lang_Class".equals(clsName) && !"java_lang_Class".equals(base.clsName) + && !m.isVirtualOverriden() + && slot < base.virtualMethodList.size() + && base.virtualMethodList.get(slot) == m //NOPMD CompareObjectsWithEquals - the same method object is an inherited one + && Parser.canReceiveTagged(clsName) == Parser.canReceiveTagged(base.clsName); + } + private boolean hasMethodInBaseClass(BytecodeMethod method) { if(baseClassObject == null) { return false; @@ -2512,7 +2591,17 @@ private void appendSuperStubHeader(StringBuilder b, List bm, Byt // append super stub for(BytecodeMethod m : base.methods) { if(!m.isPrivate() && !bm.contains(m)) { - m.appendMethodHeader(b, clsName); + if(m.isNative()) { + m.appendMethodHeader(b, clsName); + } else { + // The inherited method under this class's name IS the declaring + // class's function; its header is included through the base class. + b.append("#define "); + m.appendFunctionPointer(b, clsName); + b.append(" "); + m.appendFunctionPointer(b); + b.append("\n"); + } bm.add(m); } } @@ -2810,7 +2899,17 @@ public String generateCHeader() { appendDefaultInterfaceStubHeaders(b, bm); } + int thunkSlot = -1; for(BytecodeMethod m : virtualMethodList) { + thunkSlot++; + if(inheritsThunk(m, thunkSlot)) { + b.append("#define virtual_"); + m.appendFunctionPointer(b, clsName); + b.append(" virtual_"); + m.appendFunctionPointer(b, baseClassObject.clsName); + b.append("\n"); + continue; + } if(m.isVirtualOverriden()) { b.append("#define virtual_"); b.append(m.getClsName()); @@ -2861,6 +2960,29 @@ public String generateCHeader() { } b.append(bf.getCDefinition()); b.append(" v);\n"); + if (!bf.isVolatile()) { + // Inline fast path: a read of an initialized class's static is a + // flag test and a load. The getter was a call per read -- a Python + // constant (None, a small int) is a static field, and 6% of a + // generator drain was spent calling two of these. The out-of-line + // getter still runs the initializer the first time. Inside its own + // expansion the macro's name is not expanded again. + String getter = "get_static_" + clsName + "_" + bf.getFieldName().replace('$', '_').replace('-', '_'); + String storage = "STATIC_FIELD_" + clsName + "_" + bf.getFieldName(); + // Variadic: hand-written natives call the getter with the thread + // state (IOSNative.m passes threadStateData), which the unprototyped + // declaration accepts; a "()" macro made every such call a + // preprocessor error and broke every iOS and macOS app build. + b.append("#define ").append(getter).append("(...) "); + if (eagerInit(clsName)) { + b.append("(").append(storage).append(")\n"); + } else { + b.append("(__atomic_load_n(&__").append(clsName) + .append("_LOADED__, __ATOMIC_ACQUIRE) ? ").append(storage) + .append(" : ").append(getter).append("(__VA_ARGS__))\n"); + b.append("extern int __").append(clsName).append("_LOADED__;\n"); + } + } } } else { b.append("#define get_static_"); @@ -2945,6 +3067,7 @@ public String generateCHeader() { b.append(" unsigned char __cn1InlineStorage[16] __attribute__((aligned(16)));\n"); } b.append("};\n\n"); + appendInlineRefSetters(b); b.append("\n\n#endif //__"); diff --git a/vm/ByteCodeTranslator/src/com/codename1/tools/translator/BytecodeMethod.java b/vm/ByteCodeTranslator/src/com/codename1/tools/translator/BytecodeMethod.java index c326f52f1b9..57debb7cdc3 100644 --- a/vm/ByteCodeTranslator/src/com/codename1/tools/translator/BytecodeMethod.java +++ b/vm/ByteCodeTranslator/src/com/codename1/tools/translator/BytecodeMethod.java @@ -626,6 +626,9 @@ private static boolean isFramelessObjectOpcode(int op) { /** Set while emitting: this method is frameless AND contains a try/catch, so its * frame needs the two extra names CN1_FRAMELESS_TRY_FRAME defines. */ private boolean framelessHasTryCatch; + /// The local slots a handler can read, from handlerLiveSlots on the raw + /// bytecode; null when it could not tell, and then every local is volatile. + private Set handlerLiveSlots; /** @return true if a return in this method must unwind the try-block stack itself. */ public boolean isFramelessWithTryCatch() { @@ -702,9 +705,9 @@ private boolean isFramelessEligibleImpl() { // currentCodenameOneCallStackOffset); CN1_FRAMELESS_TRY_FRAME supplies // both, emitted only into the methods that need them. The setjmp // requirement was already met independently: volatileLocals is set by - // the same instruction scan and selects the _VSP frame variant, so the - // locals and SP are volatile here exactly as they are in an ordinary - // frame. + // the same instruction scan, so the locals are volatile here exactly as + // they are in an ordinary frame, and CN1_TRY_ENTRY restarts SP after the + // setjmp in both. continue; } if (i instanceof LabelInstruction || i instanceof LineNumber || i instanceof LocalVariable) { @@ -843,6 +846,20 @@ private boolean isFramelessEligibleImpl() { hasRealInstruction = true; continue; } + if (i instanceof LambdaCarriers.IndirectCall) { + // The call a lambda carrier's interface method makes through its fn + // field: arguments taken off the method-local operand array and the + // C parameters, the result pushed back -- self-contained exactly as + // an Invoke is, and allowed on the same terms. Unrecognized, it gave + // EVERY carrier method a full frame, and every transpiled Python call + // goes through one (PyFunction.Body1..BodyN): a frame set up and torn + // down per call, to load a field and jump. + if (!obj) { + return false; + } + hasRealInstruction = true; + continue; + } if (i instanceof LambdaCarriers.FunctionAddress) { // Pushes a function's address as a long constant -- no call, no object. // It is the one custom instruction of every lambda factory, and treating @@ -1846,6 +1863,8 @@ public void appendMethodC(StringBuilder b) { // optimize()'s return fast-paths (plain return, no frame release) so it must // be set first. frameless = isFramelessEligible(); + // Before optimize(), which fuses the loads and stores this has to see. + handlerLiveSlots = computeHandlerLiveSlots(); // Phase 1 of frame-exit retirement shares the raw-bytecode requirement, and // more strictly: it reads OTHER methods' bodies too, so it cannot run here at // all. See freezeRetireCandidates, which Parser calls before any rewrite. @@ -1916,9 +1935,6 @@ public void appendMethodC(StringBuilder b) { break; } } - // Selects the _VSP variant of whichever frame macro is emitted - // below; empty for the ordinary ones so nothing else changes. - String spVariant = volatileLocals ? "_VSP" : ""; Set added = new HashSet(); // Sorted, not in localVariables iteration order: that is a HashSet, so the // order of these declarations varied between builds of the same input. @@ -1932,7 +1948,15 @@ public void appendMethodC(StringBuilder b) { if (!added.contains(variableName) && (barebone || lv.getQualifier() != 'o')) { added.add(variableName); b.append(" "); - if (volatileLocals) { + // A slot no handler can read needs no volatile even here: what + // longjmp leaves in it is indeterminate, but it is written again + // before anything reads it. Most of a loop that catches -- every + // temporary -- is like that, and volatile put each of them in + // memory on every access. + // A slot past maxLocals is one optimize() made up, which the + // bytecode pass never saw: it stays volatile. + if (volatileLocals && (handlerLiveSlots == null || lv.getIndex() >= maxLocals + || handlerLiveSlots.contains(lv.getIndex()))) { b.append("volatile "); } switch (lv.getQualifier()) { @@ -1972,7 +1996,7 @@ public void appendMethodC(StringBuilder b) { b.append(".initialized) __STATIC_INITIALIZER_").append(framelessCls); b.append("(threadStateData);\n"); } - b.append(" DEFINE_METHOD_STACK_FRAMELESS").append(spVariant).append("("); + b.append(" DEFINE_METHOD_STACK_FRAMELESS").append("("); b.append(maxStack); b.append(", "); b.append(maxLocals); @@ -1994,12 +2018,12 @@ public void appendMethodC(StringBuilder b) { if(methodName.equals("__CLINIT__")) { if (useFastMethodStack) { if (usePrimitiveFastFrame) { - b.append(" DEFINE_METHOD_STACK_FAST_PRIMITIVE").append(spVariant).append("("); + b.append(" DEFINE_METHOD_STACK_FAST_PRIMITIVE").append("("); } else { - b.append(" DEFINE_METHOD_STACK_FAST_REF").append(spVariant).append("("); + b.append(" DEFINE_METHOD_STACK_FAST_REF").append("("); } } else { - b.append(" DEFINE_METHOD_STACK").append(spVariant).append("("); + b.append(" DEFINE_METHOD_STACK").append("("); } } else { // Guard omitted for an eagerly initialized class (see @@ -2013,23 +2037,23 @@ public void appendMethodC(StringBuilder b) { } if (useFastMethodStack) { if (usePrimitiveFastFrame) { - b.append(" DEFINE_METHOD_STACK_FAST_PRIMITIVE").append(spVariant).append("("); + b.append(" DEFINE_METHOD_STACK_FAST_PRIMITIVE").append("("); } else { - b.append(" DEFINE_METHOD_STACK_FAST_REF").append(spVariant).append("("); + b.append(" DEFINE_METHOD_STACK_FAST_REF").append("("); } } else { - b.append(" DEFINE_METHOD_STACK").append(spVariant).append("("); + b.append(" DEFINE_METHOD_STACK").append("("); } } } else { if (useFastMethodStack) { if (usePrimitiveFastFrame) { - b.append(" DEFINE_INSTANCE_METHOD_STACK_FAST_PRIMITIVE").append(spVariant).append("("); + b.append(" DEFINE_INSTANCE_METHOD_STACK_FAST_PRIMITIVE").append("("); } else { - b.append(" DEFINE_INSTANCE_METHOD_STACK_FAST_REF").append(spVariant).append("("); + b.append(" DEFINE_INSTANCE_METHOD_STACK_FAST_REF").append("("); } } else { - b.append(" DEFINE_INSTANCE_METHOD_STACK").append(spVariant).append("("); + b.append(" DEFINE_INSTANCE_METHOD_STACK").append("("); } } // The frameless branch above already emitted its complete macro @@ -2049,8 +2073,10 @@ public void appendMethodC(StringBuilder b) { b.append(");\n"); } } else { - b.append(" struct elementStruct*").append(volatileLocals ? " volatile" : "") - .append(" SP = &threadStateData->threadObjectStack[threadStateData->threadObjectStackOffset];\n"); + // As CN1_DECLARE_SP: CN1_TRY_ENTRY restarts SP from cn1SpEntry. + b.append(" struct elementStruct* const cn1SpEntry CN1_UNUSED = &threadStateData->threadObjectStack[") + .append("threadStateData->threadObjectStackOffset];\n") + .append(" struct elementStruct* SP = cn1SpEntry;\n"); } // Frame-exit retirement scope. Emitted here because `locals` exists from // the DEFINE_*_METHOD_STACK macro above, and because a declaration at the @@ -2749,6 +2775,142 @@ public void addMultiArray(String desc, int dims) { addInstruction(new MultiArray(desc, dims)); } + /// The local slots live on entry to any exception handler, by a backward + /// liveness pass over the raw bytecode, where every handler is also a + /// successor of each instruction its range covers. Answers null -- "all of + /// them" -- for anything it does not model: JSR/RET, or an instruction kind + /// that is not plain bytecode and might touch a local. + private Set computeHandlerLiveSlots() { + int n = instructions.size(); + Map labelAt = new HashMap(); + List tries = new ArrayList(); + for (int i = 0; i < n; i++) { + Instruction ins = instructions.get(i); + if (ins instanceof LabelInstruction) { + labelAt.put(((LabelInstruction) ins).getLabel(), i); + } else if (ins instanceof TryCatch) { + tries.add((TryCatch) ins); + } + } + if (tries.isEmpty()) { + return new HashSet(); + } + int[] handlerOf = new int[tries.size()]; + int[] fromOf = new int[tries.size()]; + int[] toOf = new int[tries.size()]; + for (int t = 0; t < tries.size(); t++) { + Integer h = labelAt.get(tries.get(t).getHandler()); + Integer a = labelAt.get(tries.get(t).getStart()); + Integer z = labelAt.get(tries.get(t).getEnd()); + if (h == null || a == null || z == null) { + return null; + } + handlerOf[t] = h; + fromOf[t] = a; + toOf[t] = z; + } + int[][] succ = new int[n][]; + int[] use = new int[n]; + int[] def = new int[n]; + for (int i = 0; i < n; i++) { + Instruction ins = instructions.get(i); + use[i] = -1; + def[i] = -1; + int[] next = i + 1 < n ? new int[] {i + 1} : new int[0]; + if (ins instanceof VarOp) { + int op = ins.getOpcode(); + int v = ((VarOp) ins).getIndex(); + if (op == Opcodes.RET) { + return null; + } + if (op >= Opcodes.ILOAD && op <= Opcodes.ALOAD) { + use[i] = v; + } else if (op >= Opcodes.ISTORE && op <= Opcodes.ASTORE) { + def[i] = v; + } else { + return null; + } + } else if (ins instanceof IInc) { + use[i] = ((IInc) ins).getVar(); + } else if (ins instanceof Jump) { + int op = ins.getOpcode(); + if (op == Opcodes.JSR) { + return null; + } + Integer target = labelAt.get(((Jump) ins).getLabel()); + if (target == null) { + return null; + } + next = op == Opcodes.GOTO ? new int[] {target} + : (i + 1 < n ? new int[] {i + 1, target} : new int[] {target}); + } else if (ins instanceof SwitchInstruction) { + SwitchInstruction sw = (SwitchInstruction) ins; + Label[] ls = sw.getLabels(); + next = new int[ls.length + 1]; + Integer d = labelAt.get(sw.getDefaultLabel()); + if (d == null) { + return null; + } + next[0] = d; + for (int k = 0; k < ls.length; k++) { + Integer target = labelAt.get(ls[k]); + if (target == null) { + return null; + } + next[k + 1] = target; + } + } else if (ins instanceof BasicInstruction) { + int op = ins.getOpcode(); + if ((op >= Opcodes.IRETURN && op <= Opcodes.RETURN) || op == Opcodes.ATHROW) { + next = new int[0]; + } + } else if (!(ins instanceof LabelInstruction || ins instanceof TryCatch + || ins instanceof LineNumber || ins instanceof Invoke + || ins instanceof Field || ins instanceof TypeInstruction + || ins instanceof Ldc || ins instanceof MultiArray)) { + return null; + } + succ[i] = next; + } + // live[i]: slots live on entry to instruction i. A slot read in a handler + // must survive anywhere that handler can be entered from, which is the + // handler's own live-in set joined unkilled into each covered instruction. + List> live = new ArrayList>(n); + for (int i = 0; i < n; i++) { + live.add(new HashSet()); + } + boolean changed = true; + while (changed) { + changed = false; + for (int i = n - 1; i >= 0; i--) { + Set in = new HashSet(); + for (int s : succ[i]) { + in.addAll(live.get(s)); + } + if (def[i] >= 0) { + in.remove(def[i]); + } + if (use[i] >= 0) { + in.add(use[i]); + } + for (int t = 0; t < handlerOf.length; t++) { + if (i >= fromOf[t] && i < toOf[t]) { + in.addAll(live.get(handlerOf[t])); + } + } + if (!in.equals(live.get(i))) { + live.set(i, in); + changed = true; + } + } + } + Set out = new HashSet(); + for (int h : handlerOf) { + out.addAll(live.get(h)); + } + return out; + } + public void addTryCatchBlock(Label start, Label end, Label handler, String type) { addInstruction(new TryCatch(start, end, handler, type)); } @@ -3817,7 +3979,8 @@ public void appendOnDeviceDebugInvokeThunk(String declaringClsName, StringBuilde b.append(" threadStateData->blocks[threadStateData->tryBlockOffset].exceptionClass = 0;\n"); b.append(" threadStateData->blocks[threadStateData->tryBlockOffset].nativeBuffers = threadStateData->nativeBuffers;\n"); b.append(" threadStateData->blocks[threadStateData->tryBlockOffset].builderAccess = threadStateData->builderAccess;\n"); - b.append(" memcpy(threadStateData->blocks[threadStateData->tryBlockOffset].destination, __tryJmp, sizeof(jmp_buf));\n"); + b.append(" threadStateData->blocks[threadStateData->tryBlockOffset].destination = &__tryJmp;\n"); + b.append(" threadStateData->blocks[threadStateData->tryBlockOffset].handler = 1;\n"); b.append(" threadStateData->tryBlockOffset++;\n"); // Emit the actual call b.append(" "); @@ -4171,6 +4334,150 @@ void analyzeBoundsChecks() { private static final int[] NO_HANDLERS = new int[0]; + /** + * Bounds checks for a run of constant-index loads of one array, such as the + * {@code b[0] & 0xff | (b[1] & 0xff) << 8 | ...} that reads a little-endian word: + * the first load checks the run's highest index and the rest are marked safe. + * + * Checked one at a time, each load carried a cold path that rejoined the fast + * one, so clang reloaded the array's length and data offset before every byte + * and could not fuse eight adjacent byte loads into one 64-bit load: BLAKE2b's + * 128 message bytes cost about 640 instructions where C spends 16 loads. + * + * Moving a check earlier is only invisible to the program if nothing it could + * observe happens in between, so a run is accepted only when + *
    + *
  • the method has no exception handler and no switch (a handler could read + * a local written inside the run; a switch is control flow not modelled);
  • + *
  • the indices are non-negative constants, ascending by exactly one, on one + * array local that nothing in the run writes;
  • + *
  • everything else in the run is a local load or a primitive local store, a + * constant, a conversion, or arithmetic that cannot throw (no integer + * division), and every label in it is the target of nothing.
  • + *
+ * Then a failure anywhere in the run is the first load at or past + * {@code length}, which {@code CN1_ARRAY_RUN_GUARD} reports with that index, and + * no write the program could see happened before it. + */ + void analyzeConstantIndexRuns() { + if (DISABLE_BCE || isDisableNullAndArrayBoundsChecks()) { + return; + } + java.util.ArrayList r = new java.util.ArrayList(instructions.size()); + java.util.HashSet