基线重置,TransPyC 不再作为直接脚手架主仓库

This commit is contained in:
TermiNexus committed 2026-09-09 14:44:44 +08:00
1 parent 7ab8bef3b5
commit a433f79f54
3250 files changed
+109 -681665

No files matched your search

-98
View File
@@ -1,98 +0,0 @@
# Python
**/__pycache__/
*.py[cod]
*$py.class
*.so
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg
# 编译输出
*.exe
*.out
*.o
*.obj
*.a
*.lib
*.dll
*.so
.transpyc_cache/
/includes/
includes.binary/
includes.binary_asan/
includes/openssl/.openssl_358_C
# 调试文件
*.p2c
debug.txt
*.ll
# 备份文件
* copy.py
* copy.c
# IDE
.vscode/
.idea/
*.swp
*.swo
*~
# 排除独立仓库的目录
ViperOS/
ViperTemplateProject/
TransPyV/
# 磁盘镜像
*.img
*.vmdk
*.7z
*.fd
# 日志文件
*.log
# 字体文件
*.ttc
*.ttf
# VMware
Undo/vmware/
# Trae AI
.trae/
# 编译
**/output/
**/temp/
**/.tpv_build/
# wiki
/wiki/
# VRTE
/VRTE/
/includes_rowptr_bk/
/Venom/
/ViperOS_/
/TPVAppBK/
/TPVAppBK2/
# 性能分析产物
PROF/
*.prof
+18
View File
@@ -0,0 +1,18 @@
{
"configurations": [
{
"name": "windows-gcc-x64",
"includePath": [
"${workspaceFolder}/**"
],
"compilerPath": "D:/msys64/mingw64/bin/gcc.exe",
"cStandard": "${default}",
"cppStandard": "${default}",
"intelliSenseMode": "windows-gcc-x64",
"compilerArgs": [
""
]
}
],
"version": 4
}
+24
View File
@@ -0,0 +1,24 @@
{
"version": "0.2.0",
"configurations": [
{
"name": "C/C++ Runner: Debug Session",
"type": "cppdbg",
"request": "launch",
"args": [],
"stopAtEntry": false,
"externalConsole": true,
"cwd": "d:/Desktop/TransPyC",
"program": "d:/Desktop/TransPyC/build/Debug/outDebug",
"MIMode": "gdb",
"miDebuggerPath": "gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
]
}
]
}
+67
View File
@@ -0,0 +1,67 @@
{
"C_Cpp_Runner.cCompilerPath": "gcc",
"C_Cpp_Runner.cppCompilerPath": "g++",
"C_Cpp_Runner.debuggerPath": "gdb",
"C_Cpp_Runner.cStandard": "",
"C_Cpp_Runner.cppStandard": "",
"C_Cpp_Runner.msvcBatchPath": "C:/Program Files/Microsoft Visual Studio/2022/Community/VC/Auxiliary/Build/vcvarsall.bat",
"C_Cpp_Runner.useMsvc": false,
"C_Cpp_Runner.warnings": [
"-Wall",
"-Wextra",
"-Wpedantic",
"-Wshadow",
"-Wformat=2",
"-Wcast-align",
"-Wconversion",
"-Wsign-conversion",
"-Wnull-dereference"
],
"C_Cpp_Runner.msvcWarnings": [
"/W4",
"/permissive-",
"/w14242",
"/w14287",
"/w14296",
"/w14311",
"/w14826",
"/w44062",
"/w44242",
"/w14905",
"/w14906",
"/w14263",
"/w44265",
"/w14928"
],
"C_Cpp_Runner.enableWarnings": true,
"C_Cpp_Runner.warningsAsError": false,
"C_Cpp_Runner.compilerArgs": [],
"C_Cpp_Runner.linkerArgs": [],
"C_Cpp_Runner.includePaths": [],
"C_Cpp_Runner.includeSearch": [
"*",
"**/*"
],
"C_Cpp_Runner.excludeSearch": [
"**/build",
"**/build/**",
"**/.*",
"**/.*/**",
"**/.vscode",
"**/.vscode/**"
],
"C_Cpp_Runner.useAddressSanitizer": false,
"C_Cpp_Runner.useUndefinedSanitizer": false,
"C_Cpp_Runner.useLeakSanitizer": false,
"C_Cpp_Runner.showCompilationTime": false,
"C_Cpp_Runner.useLinkTimeOptimization": false,
"C_Cpp_Runner.msvcSecureNoWarnings": false,
"python.analysis.extraPaths": [
"./includes"
],
"python.autoComplete.extraPaths": [
"./includes"
],
"python-envs.defaultEnvManager": "ms-python.python:system",
"cmake.sourceDirectory": "D:/Users/TermiNexus/Desktop/TransPyC/includes/vqt6"
}
-640
View File
@@ -1,640 +0,0 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2026 TermiNexus
Everyone is permitted to copy and distribute verbatim copies of this
license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which are precisely the products it is most important to protect.
Therefore, we have designed this version of the GPL to prohibit the
practice for those products. If such problems arise substantially in
other domains, we stand ready to extend this provision to those domains
in future versions of the GPL, as needed to protect the freedom of
users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these
conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under
section 7. This requirement modifies the requirement in section 4
to "keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional permissions, to the whole of the work, and all its
parts, regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the Corresponding
Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in
accord with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a fee), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission,
provided you inform other peers where the object code and
Corresponding Source of the work are being offered to the general
public at no charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for
incorporation into a dwelling. In determining whether a product is a
consumer product, doubtful cases shall be resolved in favor of
coverage. For a particular product received by a particular user,
"normally used" refers to a typical or common use of that class of
product, regardless of the status of the particular user or of the way
in which the particular user actually uses, or expects or is expected
to use, the product. A product is a consumer product regardless of
whether the product has substantial commercial, industrial or
non-consumer uses, unless such uses represent the only significant
mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to
install and execute modified versions of a covered work in that User
Product from a modified version of its Corresponding Source. The
information must suffice to ensure that the continued functioning of
the modified object code is in no case prevented or interfered with
solely because modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include
a requirement to continue to provide support service, warranty, or
updates for a work that has been modified or installed by the
recipient, or for the User Product in which it has been modified or
installed. Access to a network may be denied when the modification
itself materially and adversely affects the operation of the network
or violates the rules and protocols for communication across the
network.
Corresponding Source conveyed, and Installation Information
provided, in accord with this section must be in a format that is
publicly documented (and with an implementation available to the
public in source code form), and must require no special password or
key for unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders
of that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material,
or requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors
or authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions
of it) with contractual assumptions of liability to the recipient,
for any liability that these contractual assumptions directly
impose on those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions; the
above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise is void, and will
automatically terminate your rights under this License (including any
patent licenses granted under the third paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a result of peer-to-peer transmission to receive
a copy likewise does not require acceptance. However, nothing other
than this License grants you permission to propagate or modify any
covered work. These actions infringe copyright if you do not accept
this License. Therefore, by modifying or propagating a covered work,
you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization (or substantially all its assets), or an organization
merging with another organization. If propagation of a covered work
results from an entity transaction, each party to that transaction
who receives a copy of the work also receives whatever licenses to the
work the party's predecessor in interest had or could give under the
previous paragraph, plus a right to possession of the Corresponding
Source of the work from the predecessor in interest, if the
predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, and import the contents of the
covered work in whole or in part. This license is granted for the
duration of the covered work's copyright. This license is granted for
the duration of the covered work's copyright.
If you convey a covered work, knowing that it is reliant on a patent
that has not been made available to the public in source code form, or
that you has not been made aware of, then your license under this
License for the covered work is terminated.
A "contributor's essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, and import the contents of the
covered work in whole or in part, on terms that are inconsistent with
this License; provided that you also convey the source code of the
work under this License.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement
or otherwise) that contradict the conditions of this License, they do
not excuse you from the conditions of this License. If you cannot
convey a covered work so as to satisfy simultaneously your obligations
under this License and any other pertinent obligations, then as a
consequence you may not convey it at all. For example, if you agree to
terms that obligate you to collect a royalty for further conveying
from those to whom you convey the Program, the only way you could
satisfy both those terms and this License would be to refrain entirely
from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised or new versions of
the GNU General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in
detail to address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you may choose to
follow the terms and conditions either of that numbered version or of
any later version published by the Free Software Foundation. If the
Program does not specify a version number of the GNU General Public
License, you may choose any version ever published by the Free
Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT
WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND
PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE
DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR
CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES
AND/OR CONONIES THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR
DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL
DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM
(INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED
INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE
OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH
HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these
terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) 2026 TermiNexus
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program 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 for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
TransPyC Copyright (C) 2026 TermiNexus
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. For more information on this, and how to apply and follow
the GNU GPL, see <https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your
program into proprietary programs. If your program is a subroutine
library, you may consider it more useful to permit linking proprietary
applications with the library. If this is what you want to do, use
the GNU Lesser General Public License instead of this License. But
first, please read <https://www.gnu.org/licenses/why-not-lgpl.html>.
-9
View File
@@ -1,9 +0,0 @@
{
"mcpServers": {
"transpyc-tools": {
"command": "python",
"args": ["MCP/transpyc_mcp/server.py"],
"cwd": "D:\\Users\\TermiNexus\\Desktop\\TransPyC"
}
}
}
-69
View File
@@ -1,69 +0,0 @@
# TransPyC / TransPyV MCP 工具集
通过 **MCP(Model Context Protocol)** 操作 Viper 编译器生态的工具协议与接入说明。
本目录定义了一套标准化的 MCP 工具集,让 AI 助手/客户端能够:
- 编译 **TPC**(TransPyC,CPython 实现的编译器)管辖的 Viper 工程与单文件
- 构建并驱动 **TPV**(TransPyV,Viper 自举编译器)及自举链验证
- 运行回归测试、读取日志 / AST / SHA1 映射等诊断信息
## 目录
| 文件 | 说明 |
|------|------|
| `README.md` | 本文件:总览与快速接入 |
| `protocol.md` | MCP 协议规范:工具定义、执行约定、输出格式、安全约束 |
| `tools/` | 各工具的 JSON schema(可选生成,供客户端加载) |
| `transpyc_mcp/` | MCP 服务器实现(stdio,零依赖) |
## 快速接入
MCP 目录下已创建 `.mcp.json`(位于 `MCP/.mcp.json`),客户端(IDE/工具)按其中 cwd+args 自动注册 MCP 服务器 `transpyc-tools`(服务器代码位于 `MCP/transpyc_mcp/`,stdio 零依赖,也可手动 `python MCP/transpyc_mcp/server.py` 启动):
```json
{
"mcpServers": {
"transpyc-tools": {
"command": "python",
"args": ["MCP/transpyc_mcp/server.py"],
"cwd": "D:\\Users\\TermiNexus\\Desktop\\TransPyC"
}
}
}
```
实现规范见 [protocol.md](protocol.md)。工具命名空间前缀约定:
| 前缀 | 作用对象 |
|------|----------|
| `tpc_` | TPC(TransPyC 编译器 / Projectrans 工程体系) |
| `tpv_` | TPV(TransPyV 自举编译器 / 自举链) |
| `tp_` | 只读诊断(AST / 日志 / SHA1 映射) |
## 常用命令速查(协议映射)
| 目标 | 协议工具 | 底层命令 |
|------|----------|----------|
| 编译单个测试 | `tpc_run_test` | `python Projectrans.py --project Test/<Name>/project.json --clean --run` |
| 编译任意工程 | `tpc_build` | `python Projectrans.py --project <project.json> [--clean] [--run] ...` |
| 单文件转 LLVM IR | `tpc_build_file` | `python TransPyC.py -f <in.vp> -o <out.ll>` |
| 全量回归 | `tpc_run_regression` | `python Test/regression_test.py` |
| 清理并编译 | `tpc_clean_project` | `python Projectrans.py --project <p> --clean`(清理后继续完整编译) |
| 清全局缓存 | `tpc_clear_cache` | `python Projectrans.py --project <p> --clear-cache` |
| 重建 includes | `tpc_rebuild_includes` | `python Projectrans.py --project <p> --rebuild-includes` |
| 构建 TPV | `tpv_build` | `python Projectrans.py --project TransPyV/project.json --clean` |
| 自举链验证 | `tpv_bootstrap` | Phase A/B/C(TPC 编译 TPV → tpv.exe → tpv2 → tpv3) |
| TPV 编译工程 | `tpv_compile_project` | `TransPyV\output\TransPyV.exe --project <p> --clean` |
| 解析 AST | `tp_read_ast` | `python -c "import vast; ..."`(内部调用 vast) |
| 读日志 | `tp_read_log` | 读取项目内日志文件末尾 N 行 |
| 读 SHA1 映射 | `tp_sha1_map` | 读取 `temp/_sha1_map.txt` |
## 关键约束(摘自 protocol.md)
- 一律不手动删除文件;清理用 `--clean` / `--rebuild-includes` / `--clear-cache`
- 编译输出仅返回**末尾 N 行**(默认 50),避免长日志污染上下文
- 同一工程目录禁止并行编译(temp/output 冲突)
- TPC 编译错误 **fail-fast**:立即返回错误,不静默兜底
- 修改 TPV `.vp` 源码后必须清缓存 + Phase A 全量重建才生效(SHA1 缓存复用旧 .ll)
- 非生产环境默认推荐 `--asan`;ASan/非 ASan 切换必须 `--rebuild-includes` 重建 includes.binary 缓存
-445
View File
@@ -1,445 +0,0 @@
# TransPyC / TransPyV MCP 协议规范
版本:2026-08(v1) · 适用根目录:`D:\Users\TermiNexus\Desktop\TransPyC`
---
## 1. 概述
本协议定义通过 MCP 操作 Viper 编译器生态的**工具集、执行约定与安全约束**,
覆盖两大编译器:
| 名称 | 实现 | 入口 | 说明 |
|------|------|------|------|
| **TPC** | CPython | `TransPyC.py`(单文件)/ `Projectrans.py`(工程级) | 主路径编译器,所有 `Test/` 依赖它 |
| **TPV** | Viper(自举) | `TransPyV\output\TransPyV.exe` | Viper 语言自写编译器,由 TPC 编译产出 |
客户端(AI 助手等)通过 MCP 服务器的工具调用完成:编译、构建、回归测试、诊断。
---
## 2. 服务器信息
| 字段 | 值 |
|------|-----|
| name | `transpyc-tools` |
| description | TransPyC/TransPyV Viper 编译器控制服务器 |
| transport | stdio |
| protocol | MCP 2025-03-26 / 2024-11-05 兼容 |
| cwd | `D:\Users\TermiNexus\Desktop\TransPyC` |
工具命名空间前缀:`tpc_`(TPC 操作)、`tpv_`(TPV/自举操作)、`tp_`(只读诊断)。
---
## 3. 术语与路径约定
- **project.json**:工程配置,位于 `<工程>/project.json`;`Test/` 下每个子目录即一个测试工程
- **工程编译**:`Projectrans.py --project <path>` 两阶段(Phase1 声明生成 + Phase2 翻译/编译/链接)
- **单文件编译**:`TransPyC.py -f <in.vp> -o <out.ll>`,生成 LLVM IR(可再 `-cc`/`-run` 链接运行)
- **TPV 产物**:`TransPyV\output\TransPyV.exe`(根目录 `TransPyV.exe` 可能为旧版,验证必须用 output 新版)
- **自举链**:Phase A(TPC 编译 TransPyV → tpv.exe)→ Phase B(tpv.exe 编译自身 → tpv2)→ Phase C(tpv2 → tpv3)
- **缓存目录**:工程 `temp/`、`output/`、`.tpv_build/`;全局 `.transpyc_cache/`(含 `.vpi` / `.stub.ll` / `.doc.json`)
- **SHA1 映射**:`<工程>/temp/_sha1_map.txt`,记录源码 SHA1 → 中间产物
路径参数一律使用**相对根目录**或根目录内绝对路径;禁止指向根目录之外。
---
## 4. 工具清单(总览)
| # | 工具 | 分类 | 作用 |
|---|------|------|------|
| 1 | `tpc_build` | TPC 工程 | 编译任意 Viper 工程(两阶段 + 可选清理/运行/重建) |
| 2 | `tpc_build_file` | TPC 单文件 | 单文件 .vp → LLVM IR(可选链接运行) |
| 3 | `tpc_run_test` | TPC 测试 | 编译并运行单个 `Test/<Name>` 工程 |
| 4 | `tpc_run_regression` | TPC 测试 | 全量回归(遍历 `Test/*` 编译 + 运行判定) |
| 5 | `tpc_clean_project` | TPC 维护 | 清理工程 `output/` 与 `temp/`(--clean) |
| 6 | `tpc_clear_cache` | TPC 维护 | 清除全局 `.transpyc_cache`(--clear-cache) |
| 7 | `tpc_rebuild_includes` | TPC 维护 | 删除 includes.binary 并重编译所有 includes |
| 8 | `tpv_build` | TPV 构建 | TPC 编译 TransPyV → `TransPyV\output\TransPyV.exe` |
| 9 | `tpv_bootstrap` | TPV 自举 | 执行自举链 Phase A/B/C 并对比产物 |
| 10 | `tpv_compile_project` | TPV 编译 | 用 TPV.exe 编译任意工程(参数同 `tpc_build`) |
| 11 | `tpv_run_test` | TPV 测试 | 运行 `TransPyV/Test` 自测(含 NegativeTest/Sha1Test) |
| 12 | `tp_read_ast` | 诊断 | 解析 .vp 源码输出 AST dump(vast) |
| 13 | `tp_read_log` | 诊断 | 读取项目内日志/输出文件末尾 N 行 |
| 14 | `tp_sha1_map` | 诊断 | 读取工程 SHA1 映射(_sha1_map.txt) |
---
## 5. 执行约定
### 5.1 工作目录
所有命令在 `D:\Users\TermiNexus\Desktop\TransPyC`(根目录)执行;路径参数先规范化(`resolve`)再校验。
### 5.2 Python 解释器
统一使用 `python`(**Python 3.12**)。禁止使用系统内置 3.10。
约定:`t.py` / `c.py` 为语言基础模块,**不参与编译**。
### 5.3 清理策略
**禁止手动删除文件**。清理一律通过工具参数映射到命令行选项:
- `--clean`:清理 `output/` 与 `temp/`
- `--rebuild-includes`:删除 includes.binary 预编译缓存并重编译 includes
- `--clear-cache`:清除 `.transpyc_cache` 全局缓存
### 5.4 串行与并发
- **同一工程目录禁止并行编译**(temp/output 共享,冲突会损坏产物)
- 服务端维护按工程路径的锁;客户端不应并发发起同一工程的两个 build
- TPC 并行 worker 数由编译器按可用内存自动限制(`_PickWorkerCount`),服务端不干预
### 5.5 缓存与重建
- `.vp` 源码 SHA1 未变时,缓存命中会复用旧 `.ll`/`.vpi`
- **修改 TPC 的 `.py` 编译逻辑后**:需 `--clear-cache` + `--rebuild-includes` 才彻底生效
- **修改 TPV 的 `.vp` 源码后**:必须 `tpv_build`(内含 `--clean`)做 Phase A 全量重建,否则新逻辑不生效
- 编译器(TPC 侧)输出内容不可靠时(如 `bitcast i8* null t` 类垃圾 IR),应 `--clear-cache` 后重编
### 5.6 fail-fast
TPC 编译错误必须立即终止并原样返回错误(traceback 风格),**不兜底、不静默发明值**。
工具返回值中的 `ok=false` + `exit_code!=0` 即表示失败,客户端应停止后续依赖操作。
### 5.7 环境依赖
- `llc`(LLVM 静态编译器)、`clang++`(mingw-w64 链接器)须在 PATH
- TPV 运行时需 **≥ 1 GiB 空闲内存**(启动时 `malloc(1<<30)` 内存池)
- ASan 模式(`--asan`)需 clang64 环境
### 5.8 ASan 推荐(非生产环境默认启用)
**默认启用**(`asan` 参数默认 true,非生产环境):`--asan`(opt -passes=asan 插桩 + 链接 -fsanitize=address),
可捕获越界读写、use-after-free 等运行时内存错误;**生产环境显式传 `asan: false` 关闭**(性能与体积开销)。
注意:ASan 与非 ASan 构建共享 includes.binary 缓存时会互相污染(ASan 插桩 obj 在普通链接下报 `undefined symbol: __asan_*`),
**切换模式必须 `--rebuild-includes` 重建缓存**。
---
## 6. 工具详细定义
> 每个工具给出:`name` / `description` / `inputSchema`(JSON Schema)/ `command`(底层执行)/ `output`(返回结构)。
> 所有 `command` 均以工作目录为根,路径参数经规范化与**根目录白名单校验**后方可拼接。
### 6.1 tpc_build — 编译 Viper 工程(两阶段)
- description:用 TransPyC 编译任意工程,对应 `Projectrans.py --project`。支持清理、运行、阶段选择、缓存维护。
- inputSchema:
```json
{
"type": "object",
"properties": {
"project": {"type": "string", "description": "project.json 路径(相对根),如 Test/CoroTest/project.json"},
"clean": {"type": "boolean", "default": false, "description": "先清理 output/temp 再编译"},
"run": {"type": "boolean", "default": false, "description": "编译成功后立即运行产物"},
"phase": {"type": "string", "enum": ["1", "2", "all"], "default": "all", "description": "阶段:1=声明生成,2=翻译+编译,all=全部"},
"rebuild_includes": {"type": "boolean", "default": false, "description": "删除 includes.binary 并重编译 includes"},
"clear_cache": {"type": "boolean", "default": false, "description": "清除全局 .transpyc_cache"},
"asan": {"type": "boolean", "default": true, "description": "ASan 插桩(默认启用)"},
"nowarn_register": {"type": "boolean", "default": false, "description": "抑制外部函数返回类型未登记 WARN"},
"src": {"type": "string", "description": "覆盖 source_dir"},
"temp": {"type": "string", "description": "覆盖 temp_dir"},
"output": {"type": "string", "description": "覆盖 output_dir"},
"cc": {"type": "string", "description": "覆盖 LLVM 编译器命令"}
},
"required": ["project"]
}
```
- command:
```powershell
python Projectrans.py --project <project> [--clean] [--run] [--phase <1|2|all>] [--rebuild-includes] [--clear-cache] [--asan] [--nowarn-register] [--src <src>] [--temp <temp>] [--output <output>] [--cc <cc>]
```
- output:见 §7;`artifacts.exe` 取 `output_dir` 下新生成的可执行文件路径(依 project.json 的 `linker.output`)。
### 6.2 tpc_build_file — 单文件编译
- description:单文件 `.vp` → LLVM IR(`TransPyC.py -f`),可选 `-cc` 链接 + `-run` 运行。
- inputSchema:
```json
{
"type": "object",
"properties": {
"input": {"type": "string", "description": "输入 .vp 路径(相对根)"},
"output": {"type": "string", "description": "输出 .ll 路径(相对根)"},
"run": {"type": "boolean", "default": false, "description": "链接并运行"},
"args": {"type": "string", "description": "运行时参数(空格分隔)"},
"level": {"type": "string", "description": "切片级别,数字或 s"},
"encoding": {"type": "string", "default": "utf-8"},
"cc": {"type": "string", "description": "覆盖编译命令(默认见 lib/constants/config)"},
"cflags": {"type": "string", "description": "覆盖编译标志"}
},
"required": ["input", "output"]
}
```
- command:
```powershell
python TransPyC.py -f <input> -o <output> [-cc <cc>] [-cflags <cflags>] [-run] [-args <args>] [-level <level>] [-e <encoding>]
```
### 6.3 tpc_run_test — 编译并运行单个测试
- description:对 `Test/<Name>` 执行 `--clean --run`(等价手工验证单测试)。
- inputSchema:
```json
{
"type": "object",
"properties": {
"name": {"type": "string", "description": "测试名,即 Test/ 下子目录名,如 CoroTest"},
"rebuild_includes": {"type": "boolean", "default": false},
"clear_cache": {"type": "boolean", "default": false},
"asan": {"type": "boolean", "default": true}
},
"required": ["name"]
}
```
- command:
```powershell
python Projectrans.py --project Test/<name>/project.json --clean --run [--rebuild-includes] [--clear-cache] [--asan]
```
- 说明:测试工程无 `linker.output` 时产物为 `Test/<name>/output/<name>.exe`(由 project.json 决定)。
### 6.4 tpc_run_regression — 全量回归
- description:运行 `Test/regression_test.py`(遍历所有含 project.json 的测试,编译 + 运行 + 关键词判定)。
- inputSchema:
```json
{
"type": "object",
"properties": {
"name": {"type": "string", "description": "可选:只跑匹配名字的测试(按需实现过滤)"},
"timeout": {"type": "integer", "default": 300, "description": "单测试编译超时秒数"}
},
"required": []
}
```
- command:
```powershell
python Test/regression_test.py
```
- 说明:默认全量耗时较长;客户端应按需使用 `name` 过滤或分片调用。
### 6.5 tpc_clean_project — 清理并编译工程
- description:执行 `Projectrans.py --clean`——先清理 `output/` 与 `temp/`,**随后仍继续完整编译流程**(`--clean` 是编译前置步骤,非独立清理命令)。等价 `tpc_build(clean=true)`,仅不含运行。
- inputSchema:`{ "project": {"type":"string"} }`,required: ["project"]。
- command:`python Projectrans.py --project <project> --clean`
### 6.6 tpc_clear_cache — 清除全局缓存
- description:清除 `.transpyc_cache`(`.vpi` / `.stub.ll` / `.doc.json`),解决缓存腐化。
- inputSchema:`{ "project": {"type":"string"} }`,required: ["project"]。
- command:`python Projectrans.py --project <project> --clear-cache`
- 说明:腐化典型症状——`(1<<N)` 被求值为 1、类型推断退化导致指针截断、`bitcast i8* null t` 垃圾 IR。
### 6.7 tpc_rebuild_includes — 重建 includes 预编译缓存
- description:删除 includes.binary 并重编译所有 includes。
- inputSchema:`{ "project": {"type":"string"} }`,required: ["project"]。
- command:`python Projectrans.py --project <project> --rebuild-includes`
- 说明:修改 `includes/` 下基础模块后必须执行,否则旧符号表残留。### 6.8 tpv_build — 构建 TransPyV
- description:用 TPC 编译 TransPyV(自举第一阶段),产物 `TransPyV\output\TransPyV.exe`。
- inputSchema:
```json
{
"type": "object",
"properties": {
"clean": {"type": "boolean", "default": true, "description": "默认全量清理重建(TPV 源码改动必须清缓存)"},
"rebuild_includes": {"type": "boolean", "default": true, "description": "TPC 侧 includes 改动时置 true"},
"clear_cache": {"type": "boolean", "default": true, "description": "TPC 侧编译器逻辑改动时置 true"}
"asan": {"type": "boolean", "default": true, "description": "ASan 插桩(默认启用,编译器自身带 ASan 可定位内部崩溃)"}
},
"required": []
}
```
- command:
```powershell
python Projectrans.py --project TransPyV/project.json --clean [--rebuild-includes] [--clear-cache]
```
- output:`artifacts.exe = TransPyV/output/TransPyV.exe`
- 注意:**验证 TPV 行为必须用 `TransPyV\output\TransPyV.exe`**;根目录 `TransPyV.exe` 可能为旧版。TPV 源码 `.vp` SHA1 不变时不清缓存会复用旧 `.ll`,新逻辑不生效。
### 6.9 tpv_bootstrap — 自举链验证
- description:执行 Phase A/B/C 自举,验证 TPV 能编译自身(B/C 阶段由 tpv.exe 驱动)。
- inputSchema:
```json
{
"type": "object",
"properties": {
"phases": {"type": "array", "items": {"type": "string", "enum": ["A", "B", "C"]}, "description": "默认 [A,B,C]"},
"compare": {"type": "boolean", "default": true, "description": "对比相邻阶段产物(如 tpv vs tpv2 的 sha1)"}
},
"required": []
}
```
- command(示意):
```powershell
# Phase A:TPC 编译 TransPyV → tpv.exe
python Projectrans.py --project TransPyV/project.json --clean
# Phase B:tpv.exe 编译自身 → tpv2
TransPyV\output\TransPyV.exe --project TransPyV/project.json --clean --output TransPyV/output2
# Phase C:tpv2 编译自身 → tpv3
TransPyV\output\tpv2.exe --project TransPyV/project.json --clean --output TransPyV/output3
```
- 说明:B/C 阶段的 `--project` 参数与 TPC `Projectrans.py` 一致;产物命名/目录按实现约定。服务器应返回各阶段 exit_code 与产物路径,供客户端对比。
### 6.10 tpv_compile_project — 用 TPV 编译工程
- description:用 `TransPyV\output\TransPyV.exe` 编译任意工程(参数同 `tpc_build`)。
- inputSchema:同 `tpc_build`(project/clean/run/phase/...)。
- command:
```powershell
TransPyV\output\TransPyV.exe --project <project> [--clean] [--run] [--phase <1|2|all>] [--rebuild-includes] [--clear-cache]
```
- 说明:用于验证 TPV 对既有工程的兼容性;TPV 运行需 ≥ 1 GiB 空闲内存。
### 6.11 tpv_run_test — 运行 TPV 自测
- description:运行 `TransPyV/Test` 下编译器自测(App 用例 + NegativeTest + Sha1Test)。
- inputSchema:
```json
{
"type": "object",
"properties": {
"suite": {"type": "string", "enum": ["App", "NegativeTest", "Sha1Test", "all"], "default": "all"},
"filter": {"type": "string", "description": "按名字过滤(可选)"}
},
"required": []
}
```
- command(示意):`TransPyV\output\TransPyV.exe --project TransPyV/Test/project.vpj --clean --run`(或按 suite 分目录调用)。
- 说明:Test 工程配置在 `TransPyV/Test/project.vpj`,参数透传方式与 `tpv_compile_project` 一致。
### 6.12 tp_read_ast — 解析 AST
- description:解析指定 `.vp` 源码,返回 vast AST dump(compact)与符号级信息。
- inputSchema:
```json
{
"type": "object",
"properties": {
"file": {"type": "string", "description": ".vp 源文件路径(相对根)"},
"dump": {"type": "string", "enum": ["compact", "full"], "default": "compact"}
},
"required": ["file"]
}
```
- command(示意):`python -c "import vast as ast,io; print(ast.dump(ast.parse(open(r'<file>',encoding='utf-8').read())))"`
- 用途:定位 AST 形态(如 `-> None` 是 Constant(CONST_NONE)、`await` 节点位置、extern/export 软关键字标志)。
### 6.13 tp_read_log — 读取日志
- description:读取项目内文本文件(1.log、deps.json、stub.ll 等)末尾 N 行或按正则过滤。
- inputSchema:
```json
{
"type": "object",
"properties": {
"file": {"type": "string", "description": "文件路径(相对根),如 1.log"},
"lines": {"type": "integer", "default": 50, "description": "返回末尾行数"},
"pattern": {"type": "string", "description": "正则过滤(可选)"}
},
"required": ["file"]
}
```
- 说明:用于崩溃栈定位、输出核对;避免整文件灌入上下文。
### 6.14 tp_sha1_map — 读取 SHA1 映射
- description:读取工程 `temp/_sha1_map.txt`,确认哪些源码命中缓存(诊断缓存腐化)。
- inputSchema:
```json
{
"type": "object",
"properties": {
"project": {"type": "string", "description": "工程目录(相对根),如 Test/CoroTest"},
"filter": {"type": "string", "description": "按文件名过滤(可选)"}
},
"required": ["project"]
}
```
- command:读取 `<project>/temp/_sha1_map.txt`(不存在则返回 `ok=false, error="sha1 map not found"`)。
---
## 7. 输出格式
所有工具返回统一 JSON 结构:
```json
{
"ok": true,
"exit_code": 0,
"stdout": "…编译末尾 50 行…",
"stderr": "…错误末尾 50 行…",
"artifacts": {
"exe": "Test/CoroTest/output/CoroTest.exe",
"ir": "…",
"logs": ["Test/CoroTest/output/…"]
},
"elapsed_ms": 12345
}
```
约定:
- `ok=false` 且 `exit_code!=0` 即失败;`stderr` 原样保留(traceback 风格),**禁止改写/兜底**
- `stdout`/`stderr` 默认截断为**末尾 50 行**(`tp_read_log` 可通过 `lines` 调整),防止长日志污染上下文
- `artifacts` 为可选;无产物时省略该字段
- 运行超时:编译 300s、程序运行 30s(与 `Test/regression_test.py` 对齐);超时返回 `ok=false, error="timeout"`
## 8. 安全约束
1. **路径白名单**:所有 `file`/`project`/`src`/`temp`/`output` 参数必须先规范化,且必须位于根目录 `D:\Users\TermiNexus\Desktop\TransPyC` 内;越界即拒绝(`ok=false, error="path outside root"`)
2. **命令白名单**:工具只拼接本协议 §6 中列出的固定命令模板与参数;参数值经 shell 分隔(`shlex.split`)传入,**禁止拼接任意 shell**
3. **不手动删文件**:清理仅通过 `--clean` / `--rebuild-includes` / `--clear-cache`
4. **不执行任意代码**:`tp_read_ast` 只解析不执行;编译类工具只跑编译器
5. **串行锁**:同一工程路径并发 build 会被拒绝(`error="project busy"`)
6. **内存保护**:TPV 相关工具调用前检查可用内存 ≥ 1 GiB,不足则拒绝并提示
## 9. 错误码
| code | 含义 |
|------|------|
| 0 | 成功 |
| 1 | 编译/运行失败(stdout/stderr 携带详情) |
| 2 | 参数错误(缺 required / 非法 enum) |
| 3 | 路径越界(安全约束 §8.1) |
| 4 | 文件不存在(如 project.json / sha1_map) |
| 5 | 工程忙(并发冲突,§5.4/§8.5) |
| 6 | 超时(编译 > 300s / 运行 > 30s) |
| 7 | 内存不足(TPV 需 ≥ 1 GiB) |
## 10. 扩展
- **工具演进**:新增工具沿用前缀约定与 §6 模板;破坏性变更 bump 协议版本号
- **只读优先**:诊断类(`tp_`)保持纯只读,可被客户端安全探测
- **推荐工作流**:改 TPC/TPV 源码 → `tpc_clear_cache`/`tpv_build`(全量重建)→ 目标测试 `tpc_run_test` → 必要时 `tp_read_ast`/`tp_sha1_map` 定位根因 → `tp_read_log` 核对
-363
View File
@@ -1,363 +0,0 @@
[
{
"name": "tpc_build",
"description": "用 TransPyC 编译任意 Viper 工程(Projectrans.py --project,两阶段)",
"inputSchema": {
"type": "object",
"properties": {
"type": "string",
"description": "project.json 路径(相对根),如 Test/CoroTest/project.json",
"clean": {
"type": "boolean",
"default": false
},
"run": {
"type": "boolean",
"default": false
},
"phase": {
"type": "string",
"enum": [
"1",
"2",
"all"
],
"default": "all"
},
"rebuild_includes": {
"type": "boolean",
"default": false
},
"clear_cache": {
"type": "boolean",
"default": false
},
"asan": {
"type": "boolean",
"default": true,
"description": "ASan 插桩(默认启用)"
},
"nowarn_register": {
"type": "boolean",
"default": false
},
"src": {
"type": "string"
},
"temp": {
"type": "string"
},
"output": {
"type": "string"
},
"cc": {
"type": "string"
}
},
"required": [
"project"
]
}
},
{
"name": "tpc_build_file",
"description": "单文件 .vp → LLVM IR(TransPyC.py -f),可选链接运行",
"inputSchema": {
"type": "object",
"properties": {
"input": {
"type": "string",
"description": "输入 .vp 路径(相对根)"
},
"output": {
"type": "string",
"description": "输出 .ll 路径"
},
"run": {
"type": "boolean",
"default": false
},
"args": {
"type": "string"
},
"level": {
"type": "string"
},
"encoding": {
"type": "string",
"default": "utf-8"
},
"cc": {
"type": "string"
},
"cflags": {
"type": "string"
}
},
"required": [
"input",
"output"
]
}
},
{
"name": "tpc_run_test",
"description": "编译并运行单个 Test/<Name>(--clean --run)",
"inputSchema": {
"type": "object",
"properties": {
"name": {
"type": "string",
"description": "Test/ 下子目录名,如 CoroTest"
},
"rebuild_includes": {
"type": "boolean",
"default": false
},
"clear_cache": {
"type": "boolean",
"default": false
},
"asan": {
"type": "boolean",
"default": true,
"description": "ASan 插桩(默认启用)"
}
},
"required": [
"name"
]
}
},
{
"name": "tpc_run_regression",
"description": "全量回归(Test/regression_test.py)",
"inputSchema": {
"type": "object",
"properties": {
"name": {
"type": "string",
"description": "可选过滤测试名"
},
"timeout": {
"type": "integer",
"default": 300
},
"asan": {
"type": "boolean",
"default": true,
"description": "ASan 插桩(默认启用)"
}
},
"required": []
}
},
{
"name": "tpc_clean_project",
"description": "清理并编译工程(--clean,清理后继续完整编译流程)",
"inputSchema": {
"type": "object",
"properties": {
"type": "string",
"description": "project.json 路径(相对根),如 Test/CoroTest/project.json"
},
"required": [
"project"
]
}
},
{
"name": "tpc_clear_cache",
"description": "清除全局 .transpyc_cache(--clear-cache)",
"inputSchema": {
"type": "object",
"properties": {
"type": "string",
"description": "project.json 路径(相对根),如 Test/CoroTest/project.json"
},
"required": [
"project"
]
}
},
{
"name": "tpc_rebuild_includes",
"description": "重建 includes.binary 预编译缓存(--rebuild-includes)",
"inputSchema": {
"type": "object",
"properties": {
"type": "string",
"description": "project.json 路径(相对根),如 Test/CoroTest/project.json"
},
"required": [
"project"
]
}
},
{
"name": "tpv_build",
"description": "TPC 编译 TransPyV → TransPyV/output/TransPyV.exe(Phase A)",
"inputSchema": {
"type": "object",
"properties": {
"clean": {
"type": "boolean",
"default": true
},
"rebuild_includes": {
"type": "boolean",
"default": true
},
"clear_cache": {
"type": "boolean",
"default": true
},
"asan": {
"type": "boolean",
"default": true,
"description": "ASan 插桩(默认启用,编译器自身带 ASan 可定位内部崩溃)"
}
},
"required": []
}
},
{
"name": "tpv_bootstrap",
"description": "自举链 Phase A/B/C 验证并对比产物",
"inputSchema": {
"type": "object",
"properties": {
"phases": {
"type": "array",
"items": {
"type": "string",
"enum": [
"A",
"B",
"C"
]
},
"default": [
"A",
"B",
"C"
]
},
"compare": {
"type": "boolean",
"default": true
}
},
"required": []
}
},
{
"name": "tpv_compile_project",
"description": "用 TransPyV/output/TransPyV.exe 编译工程(参数同 tpc_build)",
"inputSchema": {
"type": "object",
"properties": {
"name": {
"type": "string",
"description": "可选过滤测试名"
},
"timeout": {
"type": "integer",
"default": 300
}
},
"required": [
"project"
]
}
},
{
"name": "tpv_run_test",
"description": "运行 TransPyV/Test 自测(App/NegativeTest/Sha1Test)",
"inputSchema": {
"type": "object",
"properties": {
"suite": {
"type": "string",
"enum": [
"App",
"NegativeTest",
"Sha1Test",
"all"
],
"default": "all"
},
"filter": {
"type": "string"
}
},
"required": []
}
},
{
"name": "tp_read_ast",
"description": "解析 .vp 源码输出 vast AST dump",
"inputSchema": {
"type": "object",
"properties": {
"file": {
"type": "string",
"description": ".vp 源文件路径(相对根)"
},
"dump": {
"type": "string",
"enum": [
"compact",
"full"
],
"default": "compact"
}
},
"required": [
"file"
]
}
},
{
"name": "tp_read_log",
"description": "读取项目内文本文件末尾 N 行或正则过滤",
"inputSchema": {
"type": "object",
"properties": {
"file": {
"type": "string",
"description": "文件路径(相对根),如 1.log"
},
"lines": {
"type": "integer",
"default": 50
},
"pattern": {
"type": "string"
}
},
"required": [
"file"
]
}
},
{
"name": "tp_sha1_map",
"description": "读取工程 temp/_sha1_map.txt(诊断缓存命中)",
"inputSchema": {
"type": "object",
"properties": {
"project": {
"type": "string",
"description": "工程目录(相对根),如 Test/CoroTest"
},
"filter": {
"type": "string"
}
},
"required": [
"project"
]
}
}
]
-8
View File
@@ -1,8 +0,0 @@
# -*- coding: utf-8 -*-
"""transpyc_mcp - TransPyC/TransPyV MCP 服务器包
实现 MCP/ 协议(stdio transport,零第三方依赖)。
入口:python -m transpyc_mcp.server
"""
__version__ = '1.0.0'
-596
View File
@@ -1,596 +0,0 @@
# -*- coding: utf-8 -*-
"""transpyc_mcp.server - TransPyC/TransPyV MCP 服务器
实现 MCP/ 协议(v2026-08):
- stdio transport,newline-delimited JSON-RPC 2.0
- 14 个工具(tpc_/tpv_/tp_),schema 从 MCP/tools/tools.json 加载
- 安全:路径白名单 / 命令白名单 / 工程串行锁 / 内存保护
- 输出:统一 {ok, exit_code, stdout, stderr, artifacts, elapsed_ms},日志末尾 50 行
启动:python -m transpyc_mcp.server(cwd = 项目根)
"""
from __future__ import annotations
import ctypes
import hashlib
import json
import os
import shlex
import subprocess
import sys
import time
from typing import Any, Callable
# ---------------------------------------------------------------------------
# 常量
# ---------------------------------------------------------------------------
def _find_root() -> str:
"""向上定位项目根(含 Projectrans.py 的目录),兼容服务器位于 MCP/transpyc_mcp 下。"""
d: str = os.path.dirname(os.path.abspath(__file__))
while True:
if os.path.isfile(os.path.join(d, "Projectrans.py")):
return d
parent: str = os.path.dirname(d)
if parent == d:
return d
d = parent
_ROOT: str = _find_root()
_TOOLS_JSON: str = os.path.join(_ROOT, 'MCP', 'tools', 'tools.json')
_COMPILE_TIMEOUT: int = 300
_RUN_TIMEOUT: int = 30
_REGRESSION_TIMEOUT: int = 1800
_LOG_TAIL: int = 50
_PROTOCOL_VERSION: str = '2024-11-05'
_SERVER_INFO: dict[str, str] = {'name': 'transpyc-tools', 'version': '1.0.0'}
_TPV_PROJECT: str = os.path.join('TransPyV', 'project.json')
_TPV_EXE: str = os.path.join('TransPyV', 'output', 'TransPyV.exe')
# ---------------------------------------------------------------------------
# 安全:路径白名单
# ---------------------------------------------------------------------------
class _PathError(ValueError):
pass
def _resolve(path: str) -> str:
"""规范化并校验路径必须位于项目根内(拒绝越界)。"""
p: str = path
if not os.path.isabs(p):
p = os.path.join(_ROOT, p)
p = os.path.normpath(p)
if not (p == _ROOT or p.startswith(_ROOT + os.sep)):
raise _PathError(f'path outside root: {path}')
return p
# ---------------------------------------------------------------------------
# 命令执行与输出截断
# ---------------------------------------------------------------------------
def _tail(text: str, n: int = _LOG_TAIL) -> str:
lines: list[str] = text.splitlines()
if len(lines) <= n:
return text
return '\n'.join(lines[-n:])
def _run(cmd: list[str], timeout: int = _COMPILE_TIMEOUT, cwd: str | None = None) -> dict[str, Any]:
"""执行白名单命令,返回统一结果结构。"""
t0: float = time.perf_counter()
try:
r: subprocess.CompletedProcess = subprocess.run(
cmd, cwd=cwd or _ROOT, capture_output=True, text=True,
encoding='utf-8', errors='replace', timeout=timeout,
)
return {
'ok': r.returncode == 0,
'exit_code': r.returncode,
'stdout': _tail(r.stdout),
'stderr': _tail(r.stderr),
'elapsed_ms': int((time.perf_counter() - t0) * 1000),
}
except subprocess.TimeoutExpired:
return {'ok': False, 'exit_code': 6, 'stdout': '', 'stderr': f'timeout after {timeout}s',
'elapsed_ms': timeout * 1000}
except Exception as e: # 捕获启动失败等
return {'ok': False, 'exit_code': 1, 'stdout': '', 'stderr': str(e),
'elapsed_ms': int((time.perf_counter() - t0) * 1000)}
def _result_ok(**kw: Any) -> dict[str, Any]:
base: dict[str, Any] = {'ok': True, 'exit_code': 0, 'stdout': '', 'stderr': '', 'elapsed_ms': 0}
base.update(kw)
return base
def _result_err(code: int, msg: str) -> dict[str, Any]:
return {'ok': False, 'exit_code': code, 'stdout': '', 'stderr': msg, 'elapsed_ms': 0}
# ---------------------------------------------------------------------------
# 工程串行锁
# ---------------------------------------------------------------------------
_BUSY: set[str] = set()
def _with_lock(key: str, fn: Callable[[], dict[str, Any]]) -> dict[str, Any]:
if key in _BUSY:
return _result_err(5, f'project busy: {key}')
_BUSY.add(key)
try:
return fn()
finally:
_BUSY.discard(key)
# ---------------------------------------------------------------------------
# 内存保护(TPV 需 >= 1 GiB)
# ---------------------------------------------------------------------------
def _available_gb() -> float:
try:
class _M(ctypes.Structure):
_fields_ = [('length', ctypes.c_ulong), ('memory_load', ctypes.c_ulong),
('total_phys', ctypes.c_ulonglong), ('avail_phys', ctypes.c_ulonglong),
('total_page', ctypes.c_ulonglong), ('avail_page', ctypes.c_ulonglong),
('total_virtual', ctypes.c_ulonglong), ('avail_virtual', ctypes.c_ulonglong),
('avail_ext', ctypes.c_ulonglong)]
m: _M = _M()
m.length = ctypes.sizeof(_M)
ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(m))
return m.avail_phys / (1024.0 ** 3)
except Exception:
return 99.0
def _check_memory() -> str | None:
if _available_gb() < 1.0:
return 'insufficient memory (< 1 GiB) for TPV'
return None
# ---------------------------------------------------------------------------
# 工具:参数构造辅助
# ---------------------------------------------------------------------------
def _build_project_cmd(args: dict[str, Any], project: str, exe: str | None = None) -> list[str]:
"""构造工程编译命令(exe=None 用 TPC Projectrans.py;否则用 TPV exe)。"""
cmd: list[str] = [sys.executable, 'Projectrans.py'] if exe is None else [exe]
cmd += ['--project', project]
if args.get('clean'):
cmd.append('--clean')
if args.get('run'):
cmd.append('--run')
phase: str = args.get('phase', 'all')
if phase in ('1', '2'):
cmd += ['--phase', phase]
if args.get('rebuild_includes'):
cmd.append('--rebuild-includes')
if args.get('clear_cache'):
cmd.append('--clear-cache')
if args.get('asan', True):
cmd.append('--asan')
if args.get('nowarn_register'):
cmd.append('--nowarn-register')
for opt in ('src', 'temp', 'output', 'cc'):
if args.get(opt):
cmd += [f'--{opt}', str(args[opt])]
return cmd
def _find_exe(project: str) -> dict[str, str]:
"""从 project.json 的 linker.output 定位产物 exe(相对根)。"""
proj_path: str = _resolve(project)
proj_dir: str = os.path.dirname(proj_path)
try:
with open(proj_path, 'r', encoding='utf-8') as f:
cfg: dict[str, Any] = json.load(f)
except Exception:
return {}
out_name: str = str(cfg.get('linker', {}).get('output', ''))
out_dir: str = str(cfg.get('output_dir', 'output'))
if out_name:
exe: str = os.path.join(proj_dir, out_dir, out_name)
if os.path.isfile(exe):
return {'exe': os.path.relpath(exe, _ROOT)}
# 兜底:output 目录下最新 .exe
out_abs: str = os.path.join(proj_dir, out_dir)
if os.path.isdir(out_abs):
cands: list[str] = [os.path.join(out_abs, f) for f in os.listdir(out_abs)
if f.lower().endswith('.exe')]
if cands:
latest: str = max(cands, key=os.path.getmtime)
return {'exe': os.path.relpath(latest, _ROOT)}
return {}
# ---------------------------------------------------------------------------
# 工具:tpc_ 系列
# ---------------------------------------------------------------------------
def _tpc_build(args: dict[str, Any]) -> dict[str, Any]:
project: str = str(args.get('project', ''))
if not project:
return _result_err(2, 'missing required argument: project')
proj_path: str = _resolve(project)
if not os.path.isfile(proj_path):
return _result_err(4, f'project not found: {project}')
def run() -> dict[str, Any]:
cmd: list[str] = _build_project_cmd(args, project)
res: dict[str, Any] = _run(cmd)
if res['ok']:
res['artifacts'] = _find_exe(project)
return res
return _with_lock(project, run)
def _tpc_build_file(args: dict[str, Any]) -> dict[str, Any]:
input_f: str = str(args.get('input', ''))
output_f: str = str(args.get('output', ''))
if not input_f or not output_f:
return _result_err(2, 'missing required arguments: input, output')
in_path: str = _resolve(input_f)
out_path: str = _resolve(output_f)
if not os.path.isfile(in_path):
return _result_err(4, f'input not found: {input_f}')
cmd: list[str] = [sys.executable, 'TransPyC.py', '-f', in_path, '-o', out_path]
if args.get('cc'):
cmd += ['-cc', str(args['cc'])]
if args.get('cflags'):
cmd += ['-cflags', str(args['cflags'])]
if args.get('run'):
cmd.append('-run')
if args.get('args'):
cmd += ['-args', str(args['args'])]
if args.get('level'):
cmd += ['-level', str(args['level'])]
cmd += ['-e', str(args.get('encoding', 'utf-8'))]
res: dict[str, Any] = _run(cmd)
if res['ok']:
res['artifacts'] = {'ir': output_f}
return res
def _tpc_run_test(args: dict[str, Any]) -> dict[str, Any]:
name: str = str(args.get('name', ''))
if not name:
return _result_err(2, 'missing required argument: name')
project: str = os.path.join('Test', name, 'project.json')
proj_path: str = _resolve(project)
if not os.path.isfile(proj_path):
return _result_err(4, f'test project not found: {project}')
cargs: dict[str, Any] = dict(args)
cargs['clean'] = True
cargs['run'] = True
def run() -> dict[str, Any]:
cmd: list[str] = _build_project_cmd(cargs, project)
res: dict[str, Any] = _run(cmd, timeout=_RUN_TIMEOUT + _COMPILE_TIMEOUT)
if res['ok']:
res['artifacts'] = _find_exe(project)
return res
return _with_lock(project, run)
def _tpc_run_regression(args: dict[str, Any]) -> dict[str, Any]:
timeout: int = int(args.get('timeout', _REGRESSION_TIMEOUT))
cmd: list[str] = [sys.executable, os.path.join('Test', 'regression_test.py')]
return _run(cmd, timeout=timeout)
def _tpc_flag_only(args: dict[str, Any], flag: str) -> dict[str, Any]:
project: str = str(args.get('project', ''))
if not project:
return _result_err(2, 'missing required argument: project')
proj_path: str = _resolve(project)
if not os.path.isfile(proj_path):
return _result_err(4, f'project not found: {project}')
def run() -> dict[str, Any]:
return _run([sys.executable, 'Projectrans.py', '--project', project, flag])
return _with_lock(project, run)
def _tpc_clean_project(args: dict[str, Any]) -> dict[str, Any]:
return _tpc_flag_only(args, '--clean')
def _tpc_clear_cache(args: dict[str, Any]) -> dict[str, Any]:
return _tpc_flag_only(args, '--clear-cache')
def _tpc_rebuild_includes(args: dict[str, Any]) -> dict[str, Any]:
return _tpc_flag_only(args, '--rebuild-includes')
# ---------------------------------------------------------------------------
# 工具:tpv_ 系列
# ---------------------------------------------------------------------------
def _tpv_build(args: dict[str, Any]) -> dict[str, Any]:
proj_path: str = _resolve(_TPV_PROJECT)
if not os.path.isfile(proj_path):
return _result_err(4, f'project not found: {_TPV_PROJECT}')
if args.get('clear_cache'):
return _result_err(2, 'clear_cache unsupported on tpv_build; use tpc_clear_cache on TPC side first')
def run() -> dict[str, Any]:
cmd: list[str] = [sys.executable, 'Projectrans.py', '--project', _TPV_PROJECT, '--clean']
if args.get('asan', True):
cmd.append('--asan')
if args.get('rebuild_includes'):
cmd.append('--rebuild-includes')
res: dict[str, Any] = _run(cmd)
if res['ok']:
exe: str = os.path.join(_ROOT, _TPV_EXE)
res['artifacts'] = {'exe': _TPV_EXE if os.path.isfile(exe) else ''}
return res
return _with_lock(_TPV_PROJECT, run)
def _sha1_file(path: str) -> str:
h: hashlib._Hash = hashlib.sha1()
with open(path, 'rb') as f:
for chunk in iter(lambda: f.read(65536), b''):
h.update(chunk)
return h.hexdigest()
def _tpv_bootstrap(args: dict[str, Any]) -> dict[str, Any]:
mem_err: str | None = _check_memory()
if mem_err:
return _result_err(7, mem_err)
phases: list[str] = list(args.get('phases') or ['A', 'B', 'C'])
compare: bool = bool(args.get('compare', True))
out_dirs: dict[str, str] = {'A': 'TransPyV/output', 'B': 'TransPyV/output_b', 'C': 'TransPyV/output_c'}
steps: list[dict[str, Any]] = []
# Phase A:TPC 编译 TransPyV → output/TransPyV.exe
if 'A' in phases:
res: dict[str, Any] = _run([sys.executable, 'Projectrans.py', '--project', _TPV_PROJECT, '--clean', '--asan'])
steps.append({'phase': 'A', 'exe': _TPV_EXE, **res})
if not res['ok']:
return {'ok': False, 'exit_code': res['exit_code'], 'stdout': res['stdout'],
'stderr': 'bootstrap Phase A failed\n' + res['stderr'],
'artifacts': {'steps': steps}, 'elapsed_ms': res['elapsed_ms']}
else:
steps.append({'phase': 'A', 'exe': _TPV_EXE, 'ok': True, 'exit_code': 0, 'stdout': '', 'stderr': '(skipped)'})
# Phase B/C:上一阶段 exe 编译自身到下一 output 目录
for idx, ph in enumerate(('B', 'C')):
if ph not in phases:
steps.append({'phase': ph, 'ok': True, 'exit_code': 0, 'stdout': '', 'stderr': '(skipped)'})
continue
prev_dir: str = out_dirs['A'] if idx == 0 else out_dirs['B']
prev_exe: str = os.path.join(_ROOT, prev_dir, 'TransPyV.exe')
if not os.path.isfile(prev_exe):
steps.append({'phase': ph, 'ok': False, 'exit_code': 4,
'stdout': '', 'stderr': f'previous exe missing: {prev_exe}'})
return {'ok': False, 'exit_code': 4, 'stdout': '', 'stderr': f'bootstrap Phase {ph} missing input',
'artifacts': {'steps': steps}, 'elapsed_ms': 0}
out_dir: str = out_dirs[ph]
r: dict[str, Any] = _run([prev_exe, '--project', _TPV_PROJECT, '--clean', '--output', out_dir])
steps.append({'phase': ph, 'exe': os.path.join(out_dir, 'TransPyV.exe'), **r})
if not r['ok']:
return {'ok': False, 'exit_code': r['exit_code'], 'stdout': r['stdout'],
'stderr': f'bootstrap Phase {ph} failed\n' + r['stderr'],
'artifacts': {'steps': steps}, 'elapsed_ms': r['elapsed_ms']}
# 对比各阶段产物 SHA1(自举一致性)
artifacts: dict[str, Any] = {'steps': steps}
if compare:
hashes: dict[str, str] = {}
for ph in phases:
exe_rel: str = os.path.join(out_dirs[ph], 'TransPyV.exe')
exe_abs: str = os.path.join(_ROOT, exe_rel)
hashes[ph] = _sha1_file(exe_abs) if os.path.isfile(exe_abs) else ''
artifacts['hashes'] = hashes
artifacts['identical'] = len(set(hashes.values()) - {''}) <= 1
return _result_ok(stdout=json.dumps(artifacts, ensure_ascii=False, indent=2),
artifacts=artifacts)
def _tpv_compile_project(args: dict[str, Any]) -> dict[str, Any]:
project: str = str(args.get('project', ''))
if not project:
return _result_err(2, 'missing required argument: project')
proj_path: str = _resolve(project)
if not os.path.isfile(proj_path):
return _result_err(4, f'project not found: {project}')
exe: str = os.path.join(_ROOT, _TPV_EXE)
if not os.path.isfile(exe):
return _result_err(4, f'TPV not built yet; run tpv_build first: {_TPV_EXE}')
mem_err: str | None = _check_memory()
if mem_err:
return _result_err(7, mem_err)
def run() -> dict[str, Any]:
cmd: list[str] = _build_project_cmd(args, project, exe=exe)
res: dict[str, Any] = _run(cmd)
if res['ok']:
res['artifacts'] = _find_exe(project)
return res
return _with_lock(project, run)
def _tpv_run_test(args: dict[str, Any]) -> dict[str, Any]:
exe: str = os.path.join(_ROOT, _TPV_EXE)
if not os.path.isfile(exe):
return _result_err(4, f'TPV not built yet; run tpv_build first: {_TPV_EXE}')
mem_err: str | None = _check_memory()
if mem_err:
return _result_err(7, mem_err)
suite: str = str(args.get('suite', 'all'))
proj: str = os.path.join('TransPyV', 'Test', 'project.vpj')
if not os.path.isfile(_resolve(proj)):
return _result_err(4, f'TPV test project not found: {proj}')
cmd: list[str] = [exe, '--project', proj, '--clean', '--run']
return _with_lock(proj, lambda: _run(cmd))
# ---------------------------------------------------------------------------
# 工具:tp_ 系列(只读诊断)
# ---------------------------------------------------------------------------
def _tp_read_ast(args: dict[str, Any]) -> dict[str, Any]:
file: str = str(args.get('file', ''))
if not file:
return _result_err(2, 'missing required argument: file')
fpath: str = _resolve(file)
if not os.path.isfile(fpath):
return _result_err(4, f'file not found: {file}')
if fpath.lower().endswith('.py') or fpath.lower().endswith('.vp'):
lib: str = os.path.join(_ROOT, 'lib')
if lib not in sys.path:
sys.path.insert(0, lib)
try:
import vast as ast # noqa: PLC0415
except Exception as e:
return _result_err(1, f'vast import failed: {e}')
with open(fpath, 'r', encoding='utf-8', errors='replace') as f:
src: str = f.read()
try:
tree: Any = ast.parse(src)
dump: str = args.get('dump', 'compact')
text: str = ast.dump(tree, indent=2) if dump == 'full' else ast.dump(tree)
except Exception as e:
return _result_err(1, f'parse failed: {e}')
return _result_ok(stdout=text)
return _result_err(2, f'unsupported file type: {file} (only .vp/.py)')
def _tp_read_log(args: dict[str, Any]) -> dict[str, Any]:
file: str = str(args.get('file', ''))
if not file:
return _result_err(2, 'missing required argument: file')
fpath: str = _resolve(file)
if not os.path.isfile(fpath):
return _result_err(4, f'file not found: {file}')
lines: int = int(args.get('lines', _LOG_TAIL))
try:
with open(fpath, 'r', encoding='utf-8', errors='replace') as f:
content: str = f.read()
except Exception as e:
return _result_err(1, f'read failed: {e}')
pattern: str = str(args.get('pattern', ''))
if pattern:
import re # noqa: PLC0415
try:
content = '\n'.join(l for l in content.splitlines() if re.search(pattern, l))
except Exception as e:
return _result_err(2, f'invalid pattern: {e}')
return _result_ok(stdout=_tail(content, max(1, lines)))
def _tp_sha1_map(args: dict[str, Any]) -> dict[str, Any]:
project: str = str(args.get('project', ''))
if not project:
return _result_err(2, 'missing required argument: project')
map_rel: str = os.path.join(project, 'temp', '_sha1_map.txt')
map_path: str = _resolve(map_rel)
if not os.path.isfile(map_path):
return _result_err(4, f'sha1 map not found: {map_rel}')
with open(map_path, 'r', encoding='utf-8', errors='replace') as f:
content: str = f.read()
filt: str = str(args.get('filter', ''))
if filt:
content = '\n'.join(l for l in content.splitlines() if filt in l)
return _result_ok(stdout=_tail(content, 200))
# ---------------------------------------------------------------------------
# 工具分派表
# ---------------------------------------------------------------------------
DISPATCH: dict[str, Callable[[dict[str, Any]], dict[str, Any]]] = {
'tpc_build': _tpc_build,
'tpc_build_file': _tpc_build_file,
'tpc_run_test': _tpc_run_test,
'tpc_run_regression': _tpc_run_regression,
'tpc_clean_project': _tpc_clean_project,
'tpc_clear_cache': _tpc_clear_cache,
'tpc_rebuild_includes': _tpc_rebuild_includes,
'tpv_build': _tpv_build,
'tpv_bootstrap': _tpv_bootstrap,
'tpv_compile_project': _tpv_compile_project,
'tpv_run_test': _tpv_run_test,
'tp_read_ast': _tp_read_ast,
'tp_read_log': _tp_read_log,
'tp_sha1_map': _tp_sha1_map,
}
def _load_tools() -> list[dict[str, Any]]:
try:
with open(_TOOLS_JSON, 'r', encoding='utf-8') as f:
tools: list[dict[str, Any]] = json.load(f)
if isinstance(tools, list):
return tools
except Exception:
pass
# 兜底:从分派表生成最小 schema
return [{'name': n, 'description': n, 'inputSchema': {'type': 'object', 'properties': {}, 'required': []}}
for n in DISPATCH]
# ---------------------------------------------------------------------------
# JSON-RPC 处理
# ---------------------------------------------------------------------------
def _rpc_result(msg: dict[str, Any], result: Any) -> dict[str, Any]:
return {'jsonrpc': '2.0', 'id': msg.get('id'), 'result': result}
def _rpc_error(msg: dict[str, Any], code: int, message: str) -> dict[str, Any]:
return {'jsonrpc': '2.0', 'id': msg.get('id'),
'error': {'code': code, 'message': message}}
def _handle(msg: dict[str, Any]) -> dict[str, Any] | None:
method: str = str(msg.get('method', ''))
if method == 'initialize':
return _rpc_result(msg, {
'protocolVersion': _PROTOCOL_VERSION,
'capabilities': {'tools': {}},
'serverInfo': _SERVER_INFO,
})
if method in ('notifications/initialized', 'notifications/cancelled'):
return None
if method == 'tools/list':
return _rpc_result(msg, {'tools': _load_tools()})
if method == 'tools/call':
params: dict[str, Any] = msg.get('params') or {}
name: str = str(params.get('name', ''))
fn: Callable[[dict[str, Any]], dict[str, Any]] | None = DISPATCH.get(name)
if fn is None:
return _rpc_error(msg, -32602, f'unknown tool: {name}')
args: dict[str, Any] = params.get('arguments') or {}
if not isinstance(args, dict):
return _rpc_error(msg, -32602, 'arguments must be an object')
try:
result: dict[str, Any] = fn(args)
except _PathError as e:
result = _result_err(3, str(e))
except Exception as e: # 工具内部未预期异常
result = _result_err(1, f'{type(e).__name__}: {e}')
text: str = json.dumps(result, ensure_ascii=False, indent=2)
return _rpc_result(msg, {'content': [{'type': 'text', 'text': text}],
'isError': not result.get('ok', True)})
if msg.get('id') is None:
return None # 其它 notification
return _rpc_error(msg, -32601, f'method not found: {method}')
def main() -> None:
"""stdio 循环:逐行读 JSON-RPC 请求,逐行写响应。"""
for line in sys.stdin:
line = line.strip()
if not line:
continue
try:
msg: dict[str, Any] = json.loads(line)
except Exception:
continue
resp: dict[str, Any] | None = _handle(msg)
if resp is not None:
sys.stdout.write(json.dumps(resp, ensure_ascii=False) + '\n')
sys.stdout.flush()
if __name__ == '__main__':
main()
-53
View File
@@ -1,53 +0,0 @@
# -*- coding: utf-8 -*-
"""非阻塞式 Windows Toast 通知工具。
用法:
python Notify.py "标题(任务事项内容)" ["正文(可选)"]
替代旧的阻塞式 `msg *` 弹窗,通知右下角弹出后自动消失,无需手动点击。
"""
import subprocess
import sys
def SendToast(Title: str, Body: str = ""):
"""发送一条非阻塞式 Windows Toast 通知(Balloon Tip)。
参数:
Title: 通知标题,即"本次完成的任务事项内容",用于识别是谁完成了什么任务。
Body: 通知正文,可省略。
"""
# 转义 PowerShell 单引号,防止任务内容中的特殊字符破坏脚本
# BalloonTipText 不能为空,Body 省略时用默认正文
TitleEsc = Title.replace("'", "''")
BodyEsc = (Body if Body else "任务完成").replace("'", "''")
PsScript = (
"Add-Type -AssemblyName System.Windows.Forms; "
"Add-Type -AssemblyName System.Drawing; "
"$n = New-Object System.Windows.Forms.NotifyIcon; "
"$n.Icon = [System.Drawing.SystemIcons]::Information; "
"$n.BalloonTipIcon = 'Info'; "
"$n.BalloonTipTitle = '{0}'; "
"$n.BalloonTipText = '{1}'; "
"$n.Visible = $true; "
"$n.ShowBalloonTip(5000); "
"Start-Sleep -Milliseconds 6000; "
"$n.Dispose()"
).format(TitleEsc, BodyEsc)
try:
subprocess.run(
["powershell", "-NoProfile", "-WindowStyle", "Hidden", "-Command", PsScript],
check=True,
timeout=15,
)
except Exception as Ex:
sys.stderr.write("Notify failed: %s\n" % Ex)
sys.exit(1)
if __name__ == "__main__":
if len(sys.argv) < 2:
sys.stderr.write("Usage: python Notify.py <Title> [Body]\n")
sys.exit(2)
SendToast(sys.argv[1], sys.argv[2] if len(sys.argv) > 2 else "")
-56
View File
@@ -1,56 +0,0 @@
#!/usr/bin/env python3
"""ProjectTrans.py - 工程级 TransPyC 翻译器"""
import lib._bootstrap # noqa: F401 设置 sys.path(项目根 + lib/includes)
from lib.Projectrans import (
compute_sha1, _check_annotation_for_export, sha1_file,
get_file_dependencies, find_reachable_files_from_entries,
topological_sort_files, Phase1Generator, DeclarationGenerator,
Phase2Translator, _parallel_translate_worker,
save_sha1_map, Load_sha1_map, get_sha1_map_store, clear_sha1_map_store,
Load_project_config, resolve_paths, main
)
__all__ = [
'compute_sha1', '_check_annotation_for_export', 'sha1_file',
'get_file_dependencies', 'find_reachable_files_from_entries',
'topological_sort_files', 'Phase1Generator', 'DeclarationGenerator',
'Phase2Translator', '_parallel_translate_worker',
'save_sha1_map', 'Load_sha1_map', 'get_sha1_map_store', 'clear_sha1_map_store',
'Load_project_config', 'resolve_paths', 'main'
]
if __name__ == '__main__':
# 主进程性能剖析:整次编译过程(Phase1 声明生成 + Phase2 翻译/编译/链接)
# 自动导出 cProfile dump 到 ./PROF/main_prof_{pid}.prof(与 worker 子进程
# worker_prof_*.prof 同目录,可用 PROF/1.py 合并分析)。主进程 profile 主要
# 覆盖 Phase1/依赖扫描/编译调度/链接等主进程侧耗时;worker 内部 CPU 分布
# 仍由 _ProfileWorker 的 worker_prof_*.prof 覆盖(多进程下主进程 cProfile
# 看不到子进程内部热点,两者互补)。
import cProfile as _cProfile
import os as _os
import sys as _sys
import time as _time
from lib.Projectrans.Phase2Translator import PROF_DIR as _PROF_DIR
_main_prof: _cProfile.Profile = _cProfile.Profile()
_main_prof.enable()
_start_ts: float = _time.perf_counter()
try:
main()
_timing_status: str = '成功'
except BaseException:
_timing_status = '失败'
raise
finally:
_main_prof.disable()
_elapsed_s: float = _time.perf_counter() - _start_ts
_timing_msg: str = f'[TIMING] 编译{_timing_status},总耗时 {_elapsed_s:.2f}s'
print(_timing_msg, file=_sys.stderr)
try:
_os.makedirs(_PROF_DIR, exist_ok=True)
_main_prof.dump_stats(_os.path.join(_PROF_DIR, f'main_prof_{_os.getpid()}.prof'))
with open(_os.path.join(_PROF_DIR, 'main_time.txt'), 'w', encoding='utf-8') as _tf:
_tf.write(f'{_timing_status}\t{_elapsed_s:.2f}\n')
except Exception:
pass
-76
View File
@@ -1,76 +0,0 @@
# TransPyC
**TransPyC** 是一种基于 Python 语法的系统级编程语言编译器,将 Python 子集(通过 `t`/`c` 模块类型注解赋予 LLVM 语义)编译为原生机器码。它不是 Python 的子集,也不是 C 的语法糖——它拥有独立的类型系统、两阶段编译模型和 SHA1 命名空间机制,适用于操作系统内核、嵌入式系统、驱动程序等底层开发场景。
## 能力证明
TransPyC 已用自身实现以下组件,证明其作为系统级语言的成熟度:
- **ViperOS** —— 真实操作系统内核([ViperOS/](ViperOS/)),含 gdt/idt/isr/mm/sched,可在 QEMU 启动
- **自研 Python 解析器** —— [includes/ast/](includes/ast/)(4,176 LOC),用 TransPyC 自己写的词法+语法+AST,覆盖 CPython 几乎全部语法
- **自研 LLVM IR 生成库** —— [includes/llvmlite/](includes/llvmlite/)(~1,500 LOC),用 TransPyC 自己写的 IR 文本生成器,18/18 测试通过
- **zlib 移植** —— [Test/ZlibTest/](Test/ZlibTest/),完整 deflate/inflate/huffman/checksum(~1,900 LOC)
- **Win32 FFI 绑定** —— [includes/w32/](includes/w32/),file/memory/process/sync/console 全覆盖
- **泛型容器** —— [includes/linkedlist.vp](includes/linkedlist.vp),`@t.NoVTable` + PEP 695 递归泛型继承 `class GNode(GSListNode[GNode])`
## 核心设计理念
- **Python 语法,LLVM 语义**:源文件是合法的 Python 语法,但通过 `t` 模块类型注解赋予 LLVM 级别的语义
- **类型注解即编译指令**:类型注解决定 LLVM IR 的生成,不是可选的提示
- **两阶段编译**:先提取声明接口(`.vpi` + `.stub.ll`),再翻译源文件为含代码的 `.ll`
- **SHA1 命名空间**:每个源文件按内容 SHA1 哈希命名,自动消除跨模块符号冲突
- **零运行时开销**:编译为原生代码,无 GC、无解释器、无虚拟机
## 自举进展
TransPyC 正在追求**完全自举**——用 TransPyC 重写 TransPyC 编译器自身。当前状态:
- ✅ **前端**:`includes/ast/` 已替代 Python `ast` 模块依赖
- ✅ **后端**:`includes/llvmlite/` 已替代 Python `llvmlite` 依赖
- ⏳ **中间层**:`lib/core`(~20K LOC)待用 TransPyC 重写
详见 [wiki/13-bootstrapping.md](wiki/13-bootstrapping.md)。
## 模块总览
Viper 语言通过两个核心模块提供类型和操作支持:
| 模块 | 用途 | 导入方式 |
|------|------|----------|
| `t` | 类型定义系统 | `import t` |
| `c` | C 语言操作指令 | `import c` |
## 快速上手
1. **环境**:Python 3.12+、LLVM(llc/clang)、Windows(当前主平台)
2. **构建项目**:在项目目录运行 `python ../Projectrans.py build`(详见 [wiki/12-project.md](wiki/12-project.md))
3. **示例**:参考 [Test/](Test/) 下 30+ 测试项目(AstTest/ZlibTest/NoVTableTest/LLvmLiteTest 等)
4. **写第一个程序**:
```python
import t, c
from stdint import *
import stdio
def main() -> CInt | CExport:
stdio.printf("Hello, Viper!\n")
return 0
```
## 文档索引
| 文件 | 内容 |
|------|------|
| [01-overview.md](wiki/01-overview.md) | 语言概述、两阶段编译流程、SHA1 命名空间、`t.CDefine`/`t.CExport`/`t.CInline` 深度解析 |
| [02-type-system.md](wiki/02-type-system.md) | 类型系统(基本类型、指针、数组、结构体、联合体、枚举、typedef、`__attribute__`) |
| [03-variables.md](wiki/03-variables.md) | 变量声明与赋值(含 `t.CDefine` 常量) |
| [04-functions.md](wiki/04-functions.md) | 函数定义与调用(含 `t.CExport`、`t.CInline`、`t.CDefine` 函数、`@c.CReturn`) |
| [05-classes.md](wiki/05-classes.md) | 类与数据布局(结构体、联合体、枚举、typedef、位域) |
| [06-oop.md](wiki/06-oop.md) | 面向对象与运算符重载(`@t.Object`、`@t.CVTable`、`@t.NoVTable`、继承、dunder 方法) |
| [07-control-flow.md](wiki/07-control-flow.md) | 控制流(条件、循环、match) |
| [08-c-operations.md](wiki/08-c-operations.md) | C 语言操作(指针、内联汇编、FFI 外部函数声明、LLVM IR 内联) |
| [09-exceptions.md](wiki/09-exceptions.md) | 异常处理 |
| [10-imports.md](wiki/10-imports.md) | 模块与导入系统(存根生成、SHA1 命名空间与导入) |
| [11-builtins.md](wiki/11-builtins.md) | 内置函数与运算符 |
| [12-project.md](wiki/12-project.md) | 项目配置与构建(增量编译、SHA1 映射) |
| [13-bootstrapping.md](wiki/13-bootstrapping.md) | 自举可行性分析(当前进展、剩余工作、路径规划) |
-85
View File
@@ -1,85 +0,0 @@
更复杂的 泛型
复杂原始(仿Python)函数装饰器
# main 收集(和 导入模块的自动执行)
元类型
# @p.set
# 函数的描述符用装饰器而不是返回值
崩溃/返回作用域 回调
# 假鸭子
# f-string 自动 snprintf
# __doc__(后续需完善)
# 自动索引
# testcheck默认中文
vdebug 工具和 vsdt 工具
多态 ops 允许单个函数拥有装饰器(可修改,走函数指针)
协程关键字支持
with 出入多态
# 哈希表
内联快速迭代器
出栈调用函数
# 构造函数隐式参数
小数组直接栈上创建+ i in [xxx]
# 字符串索引
单函数 @t.CVTable
import 自动执行代码
限制全局 import 符号到局部(其他文件import而本文件没import,但是仍然生效不报错)
生成器表达式
await 表达式(平台无关协程支持)
# 统一 mpool 和 mbuddy 接口
MCViper after 自举
# Ptr解引用含义冲突,a[x]与ptr[x]冲突
__iter__ 期望 for a, b in __iter__
init_set 构造
不在乎编译器时间的大小优化(无关符号剔除)
给 linkedlist 库改成 node 库,或者拆分 linkedlist 库
TPV 的 typedef 名是硬编码的,后期尝试修正
TPV 再次支持泛型能力检查和字节序
不应编码class X[T搜索泛型
string的"%"格式化
TPV 避免虚类问题,参见 ast/base.vp:224行
TPV 虚类判断问题,参见 ast/parser.vp:2037行
替换式实现注入猴子,带有含函数指针检测和函数指针还原
高级 define(时间戳,版本,config项)
更多新关键字
编译期表达式计算
结构子(反射型 runtime lookup 鸭子(看起来像跑起来像,就是鸭子,愿意))
函数前后父子构造钩子
元对象协议 MOP 的编译期版本
多分派实验
Mixin 方法直接调用的合法性静态检查:MixinC2.outer2(c) 用非组合类实例直接调用,编译通过(兜底 this_adjust 前移)但运行期越界——Mixin 方法必须经组合类实例调用。日后"编译器提前报错预警"功能需在调用处验证 self 类型的组合完整性(NoVTableCrossMixinTest Test 2/3 边界)
if not c.CIf(T.__lt__):
c.CError("...")
c.CError(f"File {T.__T_file__},{T.__T_line__}.....")
def a(b: str, *args: rawptr[list], **kwargs: rawptr[dict]):
# args和kwargs是栈上分配的list/dict
# ========== 去除 Handles 层(计划 2026-08-21,StringTest Phase A 字段分裂已修复) ==========
# 目标:删除 lib/core/Handles/(32 文件 469 模块函数 98.9% 纯 _g_gen 委托壳),逻辑并入 Gen
# 子对象,调用点改 self.Gen.X 真源(防字段分裂),管线经 gen 对象调用,删 _g_gen 注入。
# 阶段 0: 基线——StringTest Phase A 修复已验证通过
# 阶段 1: 常量/数据类/实体类迁入 Gen(Translator/TypeRegistry/ExprHandle/ExprCallHandle/13 数据类/常量,保留 HT 别名)
# 阶段 2A: HandlesType(558)→TypeGen*/ClassGen*/StmtGenCif
# 阶段 2B: HandlesStruct(476)→StructGenMixin; HandlesExpr(417)→ExprGen*
# 阶段 2C: HandlesVar(269)→VarGenMixin; HandlesExprCall(217)+ExprCall* 6 文件(104 _g_gen 样板)→CallGen*
# 阶段 2D: HandlesClassDef(120)→ClassGen*; HandlesImports(84)→ImportsGenMixin; HandlesFunctions(40)→FuncGen*
# 阶段 2E: 小模块 Body/Enum/Nonlocal/Return/If/While/For/Match/Assign/AnnAssign/AugAssign/Main/ExprOps/Base/ForHandle* 删除
# 阶段 3: 管线入口改造(BuildPipeline/Phase1/2/StubMerger*/VpiReader/Converter ~60-70 处)+ main/BuildPipeline _g_gen 注入块删除
# 阶段 4: 删 Handles/ 目录、清 import、全量自举验证(Phase A/B/C)
# 风险: 字段分裂铁律(一律 self.Gen.宿主.字段 真源); Translator 395 处 HT 类型注解用别名; 链式调用深度
$env:TPC_ASAN="0"
-70
View File
@@ -1,70 +0,0 @@
# TODO
## BUG:list[对象类型] 元素 store/load 不一致(llc 并行误报失败根因)
**状态**:**已根修(TPC `_HandleSizeofLlvm` 联合类型 sizeof)**,句柄数组保留(`0810f9f`)
### 现象
- TPV 编译器(tpv.exe)Phase B `run_llc_parallel` 并行跑 llc 时,`list[vthreading.Thread]` 存线程对象
- `join(0)` 正常等待,`join(1)` 立即返回 alive=0,失败槽 Result=-1 误报(ClassArrayTest 反复失败)
### 根因(插桩 [LLC-DBG2] 证实)
1. **`list[对象]` 的 elem_size=0(真正根因,2026-08-19 定位)**:
- `_list.vp.__init__` 的 `T.__sizeof__()` 在特化后 T 被还原为 `X | t.CPtr`(BinOp 联合)
- TPC `_HandleSizeofLlvm`(HandlesExprCall.py)对 BinOp 节点落到 else 返回 **0** → `__elem_size__=0`
- 后果:append 每次都写 `data + count*0 = data[0]`(同槽覆盖),get(0)==get(1) 同一槽 → 线程句柄错乱
- **修复**:`_HandleSizeofLlvm` 对含 t.CPtr 的联合类型返回 8(指针大小)
2. 叠加效应:`j=0` 的 `close()` 把对象 handle 置 NULL → `j=1` 的 join 用 NULL 句柄 → WAIT_FAILED
### 相关提交链
`42aa90c`(c.Deref 增强) → `4bd254a`(槽间距) → `3f3e3d5`(STARTUPINFOA 清零) → `645e8e0`(指针元素) → `88778dc`(定位插桩) → `0810f9f`(句柄数组绕开)
---
## BUG:list[t.CPtr] 特化 "Undefined method 'append'"
**状态**:**已根修(TPC)**,待验证
### 现象
- TPC 编译 `handles: list[t.CPtr] = list[t.CPtr](_mbuddy)` → `Exception: Undefined method 'append' in class 'list[CPtr]' (no function declaration found for 'list[CPtr].append')`
### 根因(TPC 泛型特化名/模板替换不一致)
1. **`_resolve_generic_slice_type` 对 `t.CPtr` 返回 raw_name='CPtr'**(裸名)→ `_specialize_generic_class` 的 `type_map['T']='CPtr'` → 模板 `item: T` 替换为 `item: CPtr` → **CPtr 不在顶层作用域 → append 方法声明注册失败**
2. **mangled 名不一致**:特化端 spec_name=`list[ptr]`(type_arg 规范化 'ptr'),查找端(`FindStructNameInAnnotation`)/声明端(`DeclarationGenerator`)生成 `list[CPtr]` / `list[i8*]` → 找不到
### 修复(TPC,2026-08-19)
- `HandlesExprCall._resolve_generic_slice_type`:t.CPtr 的 raw_name 保留带前缀 `'t.CPtr'`(可解析),去掉 'CPtr' 裸名特殊处理
- `HandlesClassDef._specialize_generic_class`:cptr_params/class_type_names 判定改 `tn_bare`(`'t.CPtr'`→`'CPtr'` 内建,不当类类型)
- `SymbolUtils.FindStructNameInAnnotation`:`CPtr`/`t.CPtr` → `'ptr'`(查找端类名与特化端统一)
- `DeclarationGenerator`:`CPtr` → `'ptr'`(声明端 mangled 统一,避免 `list[i8*]` vs `list[ptr]`)
### 待办
- [x] 重建 TPV 验证:TPC 编译 BuildPipeline.vp 通过(编译问题已解)
- [ ] **list[ptr].append 运行崩溃(见下节)**
- [ ] **TPV 侧(tpv.exe 编译其他项目)同类逻辑**:ClassGenGeneric._mangle_generic_class_name / TypeGenResolve 的 slice 解析对 t.CPtr 的规范化(需 TPC 重建后排查,若 tpv.exe 编译含 list[t.CPtr] 的项目报同样错需对称修复)
---
## BUG:list[ptr].append 运行期读零页崩溃(编译已过)
**状态**:**未根修**,当前 BuildPipeline 用 `list[str]` 绕开(TPV `dc5bb21`)
### 现象
- TPC `2f0d52e`/`6ff76f3`/`c02f7db` 后编译通过,但 tpv.exe 运行期崩溃:
- ASAN: access-violation on 0x0000000000f8/0x128/0x148(地址随构建变化,读零页)
- 栈:`list[ptr].append` ← `run_llc_parallel` ← `RunMultiFileProject`
- 插桩 [LLC-DBG2] 确认 **list[ptr] 构造完全正常**:
`handles=… pool=ede31ff990 count=0 cap=8 elem=8 data=…`(pool 有效、elem_size=8 已生效)
### 分析
- elem_size 修复已生效(崩溃地址从 0xf8 变 0x128/0x148),构造正常 → 崩溃在 append 方法体
- `list[str]` 全库验证稳定、`list[ptr]` 崩溃 → 差异在 **`item: t.CPtr` 参数类型** 与 **`elem_ptr[0] = item` 的 store 生成**(TPC 特化 list[ptr] 时)
- 疑似:TPC 对 `t.CPtr`(无联合)作为泛型方法参数的类型解析 / `elem_ptr[0]` 的 store 宽度与类型不匹配
### 排查方向(TBD)
- 看 list[ptr].append 生成的 .ll / 反汇编 append 指令
- 对比 list[str].append 与 list[ptr].append 的 IR(store 宽度、参数类型)
- TPC 侧 `_HandleSubscriptStoreLlvm` 对 `elem_ptr[0] = item`(item 为 t.CPtr)的分支
### 相关提交
`2f0d52e`(特化根修) → `6ff76f3`(CPtr sizeof) → `c02f7db`(NameError) → `0d2e912`(定位插桩) → `dc5bb21`(list[str] 绕开)
-204
View File
@@ -1,204 +0,0 @@
import t, c
from stdint import *
import stdio
import stdlib
import string
import memhub
import argparse
import testcheck
# 全局 MBuddy 指针
_mbuddy: memhub.MemBuddy | t.CPtr
@t.CExport
def main() -> int:
global _mbuddy
testcheck.begin("ArgparseTest: 命令行参数解析")
# 初始化内存管理器
arena: bytes = stdlib.malloc(16 * 1024 * 1024)
if arena is None:
testcheck.fail("malloc arena failed")
return 1
_mbuddy = memhub.MemBuddy(arena, 16 * 1024 * 1024)
argparse._mbuddy = _mbuddy
# 构造模拟 argv: myprog --input test.txt -c 42 --verbose output.dat
argv_buf: bytes = _mbuddy.alloc(8 * 7) # 7 个指针
argv: str | t.CPtr = argv_buf
# argv[0] = "myprog"
s0: bytes = _mbuddy.alloc(16)
string.strcpy(s0, "myprog")
argv0: str | t.CPtr = t.CPtr(t.CUInt64T(argv))
argv0[0] = s0
# argv[1] = "--input"
s1: bytes = _mbuddy.alloc(16)
string.strcpy(s1, "--input")
argv1: str | t.CPtr = t.CPtr(t.CUInt64T(argv) + 8)
argv1[0] = s1
# argv[2] = "test.txt"
s2: bytes = _mbuddy.alloc(16)
string.strcpy(s2, "test.txt")
argv2: str | t.CPtr = t.CPtr(t.CUInt64T(argv) + 16)
argv2[0] = s2
# argv[3] = "-c"
s3: bytes = _mbuddy.alloc(8)
string.strcpy(s3, "-c")
argv3: str | t.CPtr = t.CPtr(t.CUInt64T(argv) + 24)
argv3[0] = s3
# argv[4] = "42"
s4: bytes = _mbuddy.alloc(8)
string.strcpy(s4, "42")
argv4: str | t.CPtr = t.CPtr(t.CUInt64T(argv) + 32)
argv4[0] = s4
# argv[5] = "--verbose"
s5: bytes = _mbuddy.alloc(16)
string.strcpy(s5, "--verbose")
argv5: str | t.CPtr = t.CPtr(t.CUInt64T(argv) + 40)
argv5[0] = s5
# argv[6] = "output.dat"
s6: bytes = _mbuddy.alloc(16)
string.strcpy(s6, "output.dat")
argv6: str | t.CPtr = t.CPtr(t.CUInt64T(argv) + 48)
argv6[0] = s6
argc: INT = 7
# ============================================================
# Test 1: 基本解析 (--input, -c, --verbose, output)
# ============================================================
testcheck.section("Test 1: 基本解析")
parser = argparse.ArgumentParser("myprog", "A test program for argparse", pool=_mbuddy)
parser.add_argument("--input", "-i", argparse.STRING, 0, None, True, argparse.STORE, "input file path")
parser.add_argument("--count", "-c", argparse.INT, 1, None, False, argparse.STORE, "repeat count")
parser.add_argument("--verbose", "-v", argparse.BOOL, 0, None, False, argparse.STORE_TRUE, "enable verbose output")
parser.add_argument("output", None, argparse.STRING, 0, None, False, argparse.STORE, "output file path")
args = parser.parse_args(argc, argv)
if args is not None:
testcheck.ok("parse_args returned non-NULL")
inp: str = args.get_str("input")
cnt: INT = args.get_int("count")
verb: INT = args.get_bool("verbose")
out: str = args.get_str("output")
testcheck.check(string.strcmp(inp, "test.txt") == 0, "input = test.txt", "input mismatch")
testcheck.check(cnt == 42, "count = 42", "count mismatch")
testcheck.check(verb == True, "verbose = True", "verbose mismatch")
testcheck.check(string.strcmp(out, "output.dat") == 0, "output = output.dat", "output mismatch")
argparse.release(args)
else:
testcheck.fail("parse_args returned NULL")
# ============================================================
# Test 2: --name=value 语法
# ============================================================
testcheck.section("Test 2: --name=value 语法")
argv2_buf: bytes = _mbuddy.alloc(8 * 3)
argv2: str | t.CPtr = argv2_buf
a0: bytes = _mbuddy.alloc(16)
string.strcpy(a0, "myprog")
a0_ptr: str | t.CPtr = t.CPtr(t.CUInt64T(argv2))
a0_ptr[0] = a0
a1: bytes = _mbuddy.alloc(32)
string.strcpy(a1, "--input=hello.txt")
a1_ptr: str | t.CPtr = t.CPtr(t.CUInt64T(argv2) + 8)
a1_ptr[0] = a1
a2: bytes = _mbuddy.alloc(16)
string.strcpy(a2, "output2.dat")
a2_ptr: str | t.CPtr = t.CPtr(t.CUInt64T(argv2) + 16)
a2_ptr[0] = a2
args2 = parser.parse_args(3, argv2)
if args2 is not None:
testcheck.ok("parse_args returned non-NULL")
inp2: str = args2.get_str("input")
cnt2: INT = args2.get_int("count")
out2: str = args2.get_str("output")
testcheck.check(string.strcmp(inp2, "hello.txt") == 0, "input = hello.txt", "input mismatch")
testcheck.check(cnt2 == 1, "count = 1 (default)", "count mismatch")
testcheck.check(string.strcmp(out2, "output2.dat") == 0, "output = output2.dat", "output mismatch")
argparse.release(args2)
else:
testcheck.fail("parse_args returned NULL")
# ============================================================
# Test 3: -v COUNT 计数动作
# ============================================================
testcheck.section("Test 3: COUNT 计数动作")
argv3_buf: bytes = _mbuddy.alloc(8 * 4)
argv3_arr: str | t.CPtr = argv3_buf
b0: bytes = _mbuddy.alloc(8)
string.strcpy(b0, "myprog")
b0_ptr: str | t.CPtr = t.CPtr(t.CUInt64T(argv3_arr))
b0_ptr[0] = b0
b1: bytes = _mbuddy.alloc(8)
string.strcpy(b1, "-v")
b1_ptr: str | t.CPtr = t.CPtr(t.CUInt64T(argv3_arr) + 8)
b1_ptr[0] = b1
b2: bytes = _mbuddy.alloc(8)
string.strcpy(b2, "-v")
b2_ptr: str | t.CPtr = t.CPtr(t.CUInt64T(argv3_arr) + 16)
b2_ptr[0] = b2
b3: bytes = _mbuddy.alloc(16)
string.strcpy(b3, "output3.dat")
b3_ptr: str | t.CPtr = t.CPtr(t.CUInt64T(argv3_arr) + 24)
b3_ptr[0] = b3
parser2 = argparse.ArgumentParser("myprog", "Count test", pool=_mbuddy)
parser2.add_argument("--verbose", "-v", argparse.BOOL, 0, None, False, argparse.COUNT, "verbosity level")
parser2.add_argument("output", None, argparse.STRING, 0, None, False, argparse.STORE, "output file")
args3 = parser2.parse_args(4, argv3_arr)
if args3 is not None:
testcheck.ok("parse_args returned non-NULL")
verb3: INT = args3.get_int("verbose")
out3: str = args3.get_str("output")
testcheck.check(verb3 == 2, "verbose = 2 (counted)", "verbose count mismatch")
testcheck.check(string.strcmp(out3, "output3.dat") == 0, "output = output3.dat", "output mismatch")
argparse.release(args3)
else:
testcheck.fail("parse_args returned NULL")
# ============================================================
# Test 4: 关键字参数调用 add_argument
# ============================================================
testcheck.section("Test 4: 关键字参数")
parser3 = argparse.ArgumentParser("myprog", "Keyword arg test", pool=_mbuddy)
parser3.add_argument("--input", short="-i", arg_type=argparse.STRING, default=0, default_str=None, required=False, action=argparse.STORE, help="input file")
parser3.add_argument("--count", short="-c", arg_type=argparse.INT, default=1, required=False, action=argparse.STORE, help="count")
parser3.add_argument("--verbose", short="-v", arg_type=argparse.BOOL, default=0, required=False, action=argparse.STORE_TRUE, help="verbose")
parser3.add_argument("output", arg_type=argparse.STRING, default=0, required=False, action=argparse.STORE, help="output file")
args4 = parser3.parse_args(argc, argv)
if args4 is not None:
testcheck.ok("parse_args returned non-NULL")
inp4: str = args4.get_str("input")
cnt4: INT = args4.get_int("count")
out4: str = args4.get_str("output")
testcheck.check(string.strcmp(inp4, "test.txt") == 0, "input = test.txt", "input mismatch")
testcheck.check(cnt4 == 42, "count = 42", "count mismatch")
testcheck.check(string.strcmp(out4, "output.dat") == 0, "output = output.dat", "output mismatch")
argparse.release(args4)
else:
testcheck.fail("parse_args returned NULL")
return testcheck.end()
@@ -1 +0,0 @@
{"argparse": "104b74146bf17483", "memhub": "2408ce147bac090b", "stdio": "285b6aa29a34754d", "viperio": "2c175afd85852faf", "main": "356c943c53331be0", "hashtable": "4c1f8f779b98eab9", "string": "4c39369ffedaddac", "stdlib": "6c658cc728d0bbf4", "testcheck": "748d0424e8976fa0", "atom": "aa246c6e6aa30484", "w32.win32console": "bbdf3bbd4c3bc28c", "win32console": "bbdf3bbd4c3bc28c", "stdint": "f5522571bcce7bcb", "w32.win32base": "fc980acec33d69a7", "win32base": "fc980acec33d69a7"}
Binary file not shown.
@@ -1 +0,0 @@
{"argparse": "104b74146bf17483", "memhub": "2408ce147bac090b", "stdio": "285b6aa29a34754d", "viperio": "2c175afd85852faf", "main": "356c943c53331be0", "hashtable": "4c1f8f779b98eab9", "string": "4c39369ffedaddac", "stdlib": "6c658cc728d0bbf4", "testcheck": "748d0424e8976fa0", "atom": "aa246c6e6aa30484", "w32.win32console": "bbdf3bbd4c3bc28c", "win32console": "bbdf3bbd4c3bc28c", "stdint": "f5522571bcce7bcb", "w32.win32base": "fc980acec33d69a7", "win32base": "fc980acec33d69a7"}
@@ -1 +0,0 @@
{"argparse": "104b74146bf17483", "memhub": "2408ce147bac090b", "stdio": "285b6aa29a34754d", "viperio": "2c175afd85852faf", "main": "356c943c53331be0", "hashtable": "4c1f8f779b98eab9", "string": "4c39369ffedaddac", "stdlib": "6c658cc728d0bbf4", "testcheck": "748d0424e8976fa0", "atom": "aa246c6e6aa30484", "w32.win32console": "bbdf3bbd4c3bc28c", "win32console": "bbdf3bbd4c3bc28c", "stdint": "f5522571bcce7bcb", "w32.win32base": "fc980acec33d69a7", "win32base": "fc980acec33d69a7"}
@@ -1 +0,0 @@
{"argparse": "104b74146bf17483", "memhub": "2408ce147bac090b", "stdio": "285b6aa29a34754d", "viperio": "2c175afd85852faf", "main": "356c943c53331be0", "hashtable": "4c1f8f779b98eab9", "string": "4c39369ffedaddac", "stdlib": "6c658cc728d0bbf4", "testcheck": "748d0424e8976fa0", "atom": "aa246c6e6aa30484", "w32.win32console": "bbdf3bbd4c3bc28c", "win32console": "bbdf3bbd4c3bc28c", "stdint": "f5522571bcce7bcb", "w32.win32base": "fc980acec33d69a7", "win32base": "fc980acec33d69a7"}
-30
View File
@@ -1,30 +0,0 @@
{
"$schema": "https://raw.githubusercontent.com/TermiNexus/TransPyC/main/schemas/project-schema.json",
"name": "ArgparseTest",
"version": "1.0.0",
"source_dir": "./App",
"build_dir": "./.tpv_build",
"compiler": {
"cmd": "llc",
"flags": ["-filetype=obj", "-relocation-model=pic"]
},
"linker": {
"cmd": "clang++",
"flags": ["-Wl,--allow-multiple-definition", "-lmsvcrt", "-lucrt", "-lpthread", "-lmingwex", "-lkernel32"],
"output": "ArgparseTest.exe"
},
"includes": [
"../../includes"
],
"target": {
"triple": "x86_64-pc-windows-gnu",
"datalayout": "e-m:w-p270:32:32-p271:32:32-p272:64:64-i64:64-f80:128-n8:16:32:64-S128"
},
"options": {
"slice_level": 3,
"sha1_slice_level": 1,
"target": "llvm",
"strict_mode": true,
"startup": false
}
}
Whitespace-only changes.
@@ -1,23 +0,0 @@
"""
Auto-generated Python stub file from stdio.vp
Module: stdio
"""
import t, c
def printf(fmt: t.CConst | str, *args) -> int | t.State: pass
def fprintf(stream: bytes, fmt: t.CConst | str, *args) -> int | t.State: pass
def sprintf(buf: bytes, fmt: t.CConst | str, *args) -> int | t.State: pass
def snprintf(buf: bytes, size: t.CSizeT, fmt: t.CConst | str, *args) -> int | t.State: pass
def puts(s: t.CConst | str) -> int | t.State: pass
def fputs(s: t.CConst | str, stream: bytes) -> int | t.State: pass
def fgets(buf: bytes, size: int, stream: bytes) -> bytes | t.State: pass
def fflush(stream: bytes) -> int | t.State: pass
@@ -1 +0,0 @@
f5522571bcce7bcb
@@ -1,22 +0,0 @@
"""
Auto-generated Python stub file from stdlib.vp
Module: stdlib
"""
import c
from stdint import *
import t
def malloc(size: t.CSizeT) -> t.CVoid | t.CPtr | t.State: pass
def calloc(nmemb: t.CSizeT, size: t.CSizeT) -> t.CVoid | t.CPtr | t.State: pass
def realloc(p: t.CVoid | t.CPtr, size: t.CSizeT) -> t.CVoid | t.CPtr | t.State: pass
def free(p: t.CVoid | t.CPtr) -> t.State: pass
def system(cmd: t.CConst | t.CChar | t.CPtr) -> INT | t.State: pass
def exit(status: int) -> t.State: pass
@@ -1 +0,0 @@
285b6aa29a34754d|bbdf3bbd4c3bc28c|f5522571bcce7bcb|fc980acec33d69a7
@@ -1,31 +0,0 @@
"""
Auto-generated Python stub file from testcheck.vp
Module: testcheck
"""
import t, c
import stdio
from w32.win32console import SetConsoleOutputCP, SetConsoleCP
CP_UTF8: t.CDefine = 65001
_pass_count: t.CExtern | t.CInt
_fail_count: t.CExtern | t.CInt
_total_pass: t.CExtern | t.CInt
_total_fail: t.CExtern | t.CInt
def begin(name: str) -> t.CInt: pass
def section(name: str) -> t.CInt: pass
def ok(msg: str) -> t.CInt: pass
def fail(msg: str) -> t.CInt: pass
def check(cond: t.CInt, ok_msg: str, fail_msg: str) -> t.CInt: pass
def info(msg: str) -> t.CInt: pass
def end() -> t.CInt: pass
def summary() -> t.CInt: pass
@@ -1 +0,0 @@
{"d:\\Users\\TermiNexus\\Desktop\\TransPyC\\Test\\ArgparseTest\\App\\main.vp": {"sha1": "356c943c53331be0", "mtime": 1786094432.8905191, "size": 7983}, "d:\\Users\\TermiNexus\\Desktop\\TransPyC\\includes\\argparse.vp": {"sha1": "104b74146bf17483", "mtime": 1786093784.9537544, "size": 17304}, "d:\\Users\\TermiNexus\\Desktop\\TransPyC\\includes\\atom.vp": {"sha1": "aa246c6e6aa30484", "mtime": 1785389628.701967, "size": 1198}, "d:\\Users\\TermiNexus\\Desktop\\TransPyC\\includes\\hashtable.vp": {"sha1": "4c1f8f779b98eab9", "mtime": 1786093272.094484, "size": 9754}, "d:\\Users\\TermiNexus\\Desktop\\TransPyC\\includes\\memhub.vp": {"sha1": "2408ce147bac090b", "mtime": 1786323167.9697752, "size": 33121}, "d:\\Users\\TermiNexus\\Desktop\\TransPyC\\includes\\stdint.vp": {"sha1": "f5522571bcce7bcb", "mtime": 1785563642.3805652, "size": 4356}, "d:\\Users\\TermiNexus\\Desktop\\TransPyC\\includes\\stdio.vp": {"sha1": "285b6aa29a34754d", "mtime": 1785332415.1829746, "size": 561}, "d:\\Users\\TermiNexus\\Desktop\\TransPyC\\includes\\stdlib.vp": {"sha1": "6c658cc728d0bbf4", "mtime": 1785750602.5446548, "size": 413}, "d:\\Users\\TermiNexus\\Desktop\\TransPyC\\includes\\string.vp": {"sha1": "4c39369ffedaddac", "mtime": 1786188859.6154988, "size": 12277}, "d:\\Users\\TermiNexus\\Desktop\\TransPyC\\includes\\testcheck.vp": {"sha1": "748d0424e8976fa0", "mtime": 1785332415.20287, "size": 1919}, "d:\\Users\\TermiNexus\\Desktop\\TransPyC\\includes\\viperio.vp": {"sha1": "2c175afd85852faf", "mtime": 1786320035.0415876, "size": 1685}, "d:\\Users\\TermiNexus\\Desktop\\TransPyC\\includes\\w32\\win32base.vp": {"sha1": "fc980acec33d69a7", "mtime": 1785332415.2228394, "size": 2653}, "d:\\Users\\TermiNexus\\Desktop\\TransPyC\\includes\\w32\\win32console.vp": {"sha1": "bbdf3bbd4c3bc28c", "mtime": 1781200703.5338137, "size": 5604}}
-13
View File
@@ -1,13 +0,0 @@
104b74146bf17483:includes/argparse.vp
2408ce147bac090b:includes/memhub.vp
285b6aa29a34754d:includes/stdio.vp
2c175afd85852faf:includes/viperio.vp
356c943c53331be0:main.vp
4c1f8f779b98eab9:includes/hashtable.vp
4c39369ffedaddac:includes/string.vp
6c658cc728d0bbf4:includes/stdlib.vp
748d0424e8976fa0:includes/testcheck.vp
aa246c6e6aa30484:includes/atom.vp
bbdf3bbd4c3bc28c:includes/w32\win32console.vp
f5522571bcce7bcb:includes/stdint.vp
fc980acec33d69a7:includes/w32\win32base.vp
Whitespace-only changes.
@@ -1,26 +0,0 @@
"""
Auto-generated Python stub file from atom.vp
Module: atom
"""
import t, c
ATOMIC_RELAXED: t.CDefine = 0
ATOMIC_CONSUME: t.CDefine = 1
ATOMIC_ACQUIRE: t.CDefine = 2
ATOMIC_RELEASE: t.CDefine = 3
ATOMIC_ACQ_REL: t.CDefine = 4
ATOMIC_SEQ_CST: t.CDefine = 5
def __atomic_test_and_set(ptr: t.CUInt64T | t.CPtr, order: t.CInt) -> t.CBool: pass
def __atomic_clear(ptr: t.CUInt64T | t.CPtr, order: t.CInt) -> t.CVoid: pass
def __atomic_thread_fence(order: t.CInt) -> t.CVoid: pass
def __atomic_signal_fence(order: t.CInt) -> t.CVoid: pass
def __atomic_always_lock_free(size: t.CSizeT, ptr: t.CVoid | t.CPtr) -> t.CBool: pass
def __atomic_is_lock_free(size: t.CSizeT, ptr: t.CVoid | t.CPtr) -> t.CBool: pass
@@ -1 +0,0 @@
f5522571bcce7bcb|fc980acec33d69a7
-138
View File
@@ -1,138 +0,0 @@
"""
Auto-generated Python stub file from w32.win32console.vp
Module: w32.win32console
"""
import c
import t
from stdint import *
from w32.win32base import *
ENABLE_PROCESSED_INPUT: t.CDefine = 0x0001
ENABLE_LINE_INPUT: t.CDefine = 0x0002
ENABLE_ECHO_INPUT: t.CDefine = 0x0004
ENABLE_WINDOW_INPUT: t.CDefine = 0x0008
ENABLE_MOUSE_INPUT: t.CDefine = 0x0010
ENABLE_INSERT_MODE: t.CDefine = 0x0020
ENABLE_QUICK_EDIT_MODE: t.CDefine = 0x0040
ENABLE_EXTENDED_FLAGS: t.CDefine = 0x0080
ENABLE_PROCESSED_OUTPUT: t.CDefine = 0x0001
ENABLE_WRAP_AT_EOL_OUTPUT: t.CDefine = 0x0002
ENABLE_VIRTUAL_TERMINAL_PROCESSING: t.CDefine = 0x0004
DISABLE_NEWLINE_AUTO_RETURN: t.CDefine = 0x0008
ENABLE_LVB_GRID_WORLDWIDE: t.CDefine = 0x0010
FOREGROUND_BLUE: t.CDefine = 0x0001
FOREGROUND_GREEN: t.CDefine = 0x0002
FOREGROUND_RED: t.CDefine = 0x0004
FOREGROUND_INTENSITY: t.CDefine = 0x0008
BACKGROUND_BLUE: t.CDefine = 0x0010
BACKGROUND_GREEN: t.CDefine = 0x0020
BACKGROUND_RED: t.CDefine = 0x0040
BACKGROUND_INTENSITY: t.CDefine = 0x0080
KEY_EVENT: t.CDefine = 0x0001
MOUSE_EVENT: t.CDefine = 0x0002
WINDOW_BUFFER_SIZE_EVENT: t.CDefine = 0x0004
MENU_EVENT: t.CDefine = 0x0008
FOCUS_EVENT: t.CDefine = 0x0010
class COORD:
X: SHORT
Y: SHORT
class SMALL_RECT:
Left: SHORT
Top: SHORT
Right: SHORT
Bottom: SHORT
class CONSOLE_SCREEN_BUFFER_INFO:
dwSize: COORD
dwCursorPosition: COORD
wAttributes: WORD
srWindow: SMALL_RECT
dwMaximumWindowSize: COORD
class CONSOLE_CURSOR_INFO:
dwSize: ULONG
bVisible: BOOL
class CHAR_INFO:
UnicodeChar: WCHAR
Attributes: WORD
class KEY_EVENT_RECORD:
bKeyDown: BOOL
wRepeatCount: WORD
wVirtualKeyCode: WORD
wVirtualScanCode: WORD
uChar: WCHAR
dwControlKeyState: ULONG
class MOUSE_EVENT_RECORD:
dwMousePosition: COORD
dwButtonState: ULONG
dwControlKeyState: ULONG
dwEventFlags: ULONG
class WINDOW_BUFFER_SIZE_RECORD:
dwSize: COORD
class INPUT_RECORD:
EventType: WORD
Event: KEY_EVENT_RECORD
def SetConsoleOutputCP(codepage: UINT) -> BOOL | t.State: pass
def SetConsoleCP(codepage: UINT) -> BOOL | t.State: pass
def GetConsoleCP() -> UINT | t.State: pass
def GetConsoleOutputCP() -> UINT | t.State: pass
def GetConsoleScreenBufferInfo(hConsoleOutput: HANDLE, lpConsoleScreenBufferInfo: CONSOLE_SCREEN_BUFFER_INFO | t.CPtr) -> BOOL | t.State: pass
def SetConsoleScreenBufferSize(hConsoleOutput: HANDLE, dwSize: COORD) -> BOOL | t.State: pass
def SetConsoleCursorPosition(hConsoleOutput: HANDLE, dwCursorPosition: COORD) -> BOOL | t.State: pass
def GetConsoleCursorInfo(hConsoleOutput: HANDLE, lpConsoleCursorInfo: CONSOLE_CURSOR_INFO | t.CPtr) -> BOOL | t.State: pass
def SetConsoleCursorInfo(hConsoleOutput: HANDLE, lpConsoleCursorInfo: CONSOLE_CURSOR_INFO | t.CPtr) -> BOOL | t.State: pass
def SetConsoleTextAttribute(hConsoleOutput: HANDLE, wAttributes: WORD) -> BOOL | t.State: pass
def FillConsoleOutputCharacterA(hConsoleOutput: HANDLE, cCharacter: t.CChar, nLength: ULONG, dwWriteCoord: COORD, lpNumberOfCharsWritten: ULONG | t.CPtr) -> BOOL | t.State: pass
def FillConsoleOutputCharacterW(hConsoleOutput: HANDLE, cCharacter: WCHAR, nLength: ULONG, dwWriteCoord: COORD, lpNumberOfCharsWritten: ULONG | t.CPtr) -> BOOL | t.State: pass
def FillConsoleOutputAttribute(hConsoleOutput: HANDLE, wAttribute: WORD, nLength: ULONG, dwWriteCoord: COORD, lpNumberOfAttrsWritten: ULONG | t.CPtr) -> BOOL | t.State: pass
def WriteConsoleA(hConsoleOutput: HANDLE, lpBuffer: t.CConst | VOIDPTR, nNumberOfCharsToWrite: ULONG, lpNumberOfCharsWritten: ULONG | t.CPtr, lpReserved: VOIDPTR) -> BOOL | t.State: pass
def WriteConsoleW(hConsoleOutput: HANDLE, lpBuffer: t.CConst | VOIDPTR, nNumberOfCharsToWrite: ULONG, lpNumberOfCharsWritten: ULONG | t.CPtr, lpReserved: VOIDPTR) -> BOOL | t.State: pass
def ReadConsoleA(hConsoleInput: HANDLE, lpBuffer: VOIDPTR, nNumberOfCharsToRead: ULONG, lpNumberOfCharsRead: ULONG | t.CPtr, pInputControl: VOIDPTR) -> BOOL | t.State: pass
def ReadConsoleW(hConsoleInput: HANDLE, lpBuffer: VOIDPTR, nNumberOfCharsToRead: ULONG, lpNumberOfCharsRead: ULONG | t.CPtr, pInputControl: VOIDPTR) -> BOOL | t.State: pass
def GetConsoleMode(hConsoleHandle: HANDLE, lpMode: ULONG | t.CPtr) -> BOOL | t.State: pass
def SetConsoleMode(hConsoleHandle: HANDLE, dwMode: ULONG) -> BOOL | t.State: pass
def ReadConsoleInputA(hConsoleInput: HANDLE, lpBuffer: INPUT_RECORD | t.CPtr, nLength: ULONG, lpNumberOfEventsRead: ULONG | t.CPtr) -> BOOL | t.State: pass
def ReadConsoleInputW(hConsoleInput: HANDLE, lpBuffer: INPUT_RECORD | t.CPtr, nLength: ULONG, lpNumberOfEventsRead: ULONG | t.CPtr) -> BOOL | t.State: pass
def GetNumberOfConsoleInputEvents(hConsoleInput: HANDLE, lpNumberOfEvents: ULONG | t.CPtr) -> BOOL | t.State: pass
def FlushConsoleInputBuffer(hConsoleInput: HANDLE) -> BOOL | t.State: pass
def SetConsoleTitleA(lpConsoleTitle: LPCSTR) -> BOOL | t.State: pass
def SetConsoleTitleW(lpConsoleTitle: LPCWSTR) -> BOOL | t.State: pass
def GetConsoleTitleA(lpConsoleTitle: CHARPTR, nSize: ULONG) -> ULONG | t.State: pass
def GetConsoleTitleW(lpConsoleTitle: WCHARPTR, nSize: ULONG) -> ULONG | t.State: pass
def AllocConsole() -> BOOL | t.State: pass
def FreeConsole() -> BOOL | t.State: pass
def SetConsoleWindowInfo(hConsoleOutput: HANDLE, bAbsolute: BOOL, lpConsoleWindow: SMALL_RECT | t.CPtr) -> BOOL | t.State: pass
def ScrollConsoleScreenBufferA(hConsoleOutput: HANDLE, lpScrollRectangle: SMALL_RECT | t.CPtr, lpClipRectangle: SMALL_RECT | t.CPtr, dwDestinationOrigin: COORD, lpFill: CHAR_INFO | t.CPtr) -> BOOL | t.State: pass
Whitespace-only changes.
-100
View File
@@ -1,100 +0,0 @@
"""
Auto-generated Python stub file from stdint.vp
Module: stdint
"""
import c
import t
INT: t.CTypedef = t.CInt
INTPTR: t.CTypedef = t.CInt | t.CPtr
BOOL: t.CTypedef = t.CInt
UINT: t.CTypedef = t.CUnsignedInt
UINTPTR: t.CTypedef = UINT | t.CPtr
BYTE: t.CTypedef = t.CUnsignedChar
BYTEPTR: t.CTypedef = BYTE | t.CPtr
WORD: t.CTypedef = t.CUInt16T
DWORD: t.CTypedef = t.CUInt32T
QWORD: t.CTypedef = t.CUInt64T
TCHAR: t.CTypedef = t.CChar
CHARLIST: t.CTypedef = str | t.CPtr
VOID: t.CTypedef = t.CVoid
SHORT: t.CTypedef = t.CShort
SHORTPTR: t.CTypedef = t.CShort | t.CPtr
USHORT: t.CTypedef = t.CUnsignedShort
USHORTPTR: t.CTypedef = t.CUnsignedShort | t.CPtr
LONGLONG: t.CTypedef = t.CLongLong
ULONGLONG: t.CTypedef = t.CUnsignedLongLong
LONG: t.CTypedef = t.CLong
ULONG: t.CTypedef = t.CUnsignedLong
WCHAR: t.CTypedef = WORD
WCHARPTR: t.CTypedef = WORD | t.CPtr
CHARPTR: t.CTypedef = t.CChar | t.CPtr
FSIZE_t: t.CTypedef = DWORD
LBA_t: t.CTypedef = DWORD
VOIDPTR: t.CTypedef = t.CVoid | t.CPtr
FLOAT: t.CTypedef = t.CFloat
DOUBLE: t.CTypedef = t.CDouble
FLOAT8: t.CTypedef = t.CFloat8T
FLOAT16: t.CTypedef = t.CFloat16T
FLOAT32: t.CTypedef = t.CFloat32T
FLOAT64: t.CTypedef = t.CFloat64T
FLOAT128: t.CTypedef = t.CFloat128T
INT8: t.CTypedef = t.CInt8T
INT16: t.CTypedef = t.CInt16T
INT32: t.CTypedef = t.CInt32T
INT64: t.CTypedef = t.CInt64T
UINT8: t.CTypedef = t.CUInt8T
UINT16: t.CTypedef = t.CUInt16T
UINT32: t.CTypedef = t.CUInt32T
UINT64: t.CTypedef = t.CUInt64T
INT8PTR: t.CTypedef = t.CInt8T | t.CPtr
INT16PTR: t.CTypedef = t.CInt16T | t.CPtr
INT32PTR: t.CTypedef = t.CInt32T | t.CPtr
INT64PTR: t.CTypedef = t.CInt64T | t.CPtr
UINT8PTR: t.CTypedef = t.CUInt8T | t.CPtr
UINT16PTR: t.CTypedef = t.CUInt16T | t.CPtr
UINT32PTR: t.CTypedef = t.CUInt32T | t.CPtr
UINT64PTR: t.CTypedef = t.CUInt64T | t.CPtr
CHAR8: t.CTypedef = t.CChar8T
CHAR16: t.CTypedef = t.CChar16T
CHAR32: t.CTypedef = t.CChar32T
CHAR8PTR: t.CTypedef = t.CChar8T | t.CPtr
CHAR16PTR: t.CTypedef = t.CChar16T | t.CPtr
CHAR32PTR: t.CTypedef = t.CChar32T | t.CPtr
i8: t.CTypedef = t.CInt8T
i16: t.CTypedef = t.CInt16T
i32: t.CTypedef = t.CInt32T
i64: t.CTypedef = t.CInt64T
u8: t.CTypedef = t.CUInt8T
u16: t.CTypedef = t.CUInt16T
u32: t.CTypedef = t.CUInt32T
u64: t.CTypedef = t.CUInt64T
SIZE_T: t.CTypedef = t.CSizeT
SSIZE_T: t.CTypedef = t.CPtrDiffT
PTRDIFF_T: t.CTypedef = t.CPtrDiffT
int8_t: t.CTypedef = t.CInt8T
int16_t: t.CTypedef = t.CInt16T
int32_t: t.CTypedef = t.CInt32T
int64_t: t.CTypedef = t.CInt64T
uint8_t: t.CTypedef = t.CUInt8T
uint16_t: t.CTypedef = t.CUInt16T
uint32_t: t.CTypedef = t.CUInt32T
uint64_t: t.CTypedef = t.CUInt64T
size_t: t.CTypedef = t.CSizeT
ssize_t: t.CTypedef = t.CPtrDiffT
ptrdiff_t: t.CTypedef = t.CPtrDiffT
intptr_t: t.CTypedef = t.CIntPtrT
uintptr_t: t.CTypedef = t.CUIntPtrT
wchar_t: t.CTypedef = t.CWCharT
char8_t: t.CTypedef = t.CChar8T
char16_t: t.CTypedef = t.CChar16T
char32_t: t.CTypedef = t.CChar32T
float8_t: t.CTypedef = t.CFloat8T
float16_t: t.CTypedef = t.CFloat16T
float32_t: t.CTypedef = t.CFloat32T
float64_t: t.CTypedef = t.CFloat64T
float128_t: t.CTypedef = t.CFloat128T
_Bool: t.CTypedef = t.CBool
@@ -1 +0,0 @@
f5522571bcce7bcb
-100
View File
@@ -1,100 +0,0 @@
"""
Auto-generated Python stub file from w32.win32base.vp
Module: w32.win32base
"""
import c
import t
from stdint import *
HANDLE: t.CTypedef = VOIDPTR
LPCSTR: t.CTypedef = t.CConst | t.CChar | t.CPtr
LPCWSTR: t.CTypedef = t.CConst | t.CUnsignedShort | t.CPtr
INVALID_HANDLE_VALUE: t.CDefine = -1
NULL: t.CDefine = 0
TRUE: t.CDefine = 1
FALSE: t.CDefine = 0
INFINITE: t.CDefine = 0xFFFFFFFF
WAIT_FAILED: t.CDefine = 0xFFFFFFFF
WAIT_OBJECT_0: t.CDefine = 0
WAIT_TIMEOUT: t.CDefine = 258
WAIT_ABANDONED: t.CDefine = 0x80
MAX_PATH: t.CDefine = 260
ERROR_SUCCESS: t.CDefine = 0
ERROR_FILE_NOT_FOUND: t.CDefine = 2
ERROR_ACCESS_DENIED: t.CDefine = 5
ERROR_INSUFFICIENT_BUFFER: t.CDefine = 122
class SECURITY_ATTRIBUTES:
nLength: ULONG
lpSecurityDescriptor: VOIDPTR
bInheritHandle: BOOL
class OVERLAPPED:
Internal: ULONGLONG
InternalHigh: ULONGLONG
Offset: ULONG
OffsetHigh: ULONG
hEvent: HANDLE
class FILETIME:
dwLowDateTime: DWORD
dwHighDateTime: DWORD
class SYSTEMTIME:
wYear: WORD
wMonth: WORD
wDayOfWeek: WORD
wDay: WORD
wHour: WORD
wMinute: WORD
wSecond: WORD
wMilliseconds: WORD
class GUID:
Data1: DWORD
Data2: WORD
Data3: WORD
Data4: BYTEPTR
class LARGE_INTEGER:
QuadPart: LONGLONG
class ULARGE_INTEGER:
QuadPart: ULONGLONG
def GetLastError() -> ULONG | t.State: pass
def SetLastError(dwErrCode: ULONG) -> t.State: pass
def CloseHandle(hObject: HANDLE) -> BOOL | t.State: pass
def GetProcAddress(hModule: HANDLE, lpProcName: LPCSTR) -> VOIDPTR | t.State: pass
def GetModuleHandleA(lpModuleName: LPCSTR) -> HANDLE | t.State: pass
def GetModuleHandleW(lpModuleName: LPCWSTR) -> HANDLE | t.State: pass
def LoadLibraryA(lpLibFileName: LPCSTR) -> HANDLE | t.State: pass
def LoadLibraryW(lpLibFileName: LPCWSTR) -> HANDLE | t.State: pass
def FreeLibrary(hLibModule: HANDLE) -> BOOL | t.State: pass
def GetSystemTime(lpSystemTime: SYSTEMTIME | t.CPtr) -> t.State: pass
def GetLocalTime(lpSystemTime: SYSTEMTIME | t.CPtr) -> t.State: pass
def FileTimeToSystemTime(lpFileTime: FILETIME | t.CPtr, lpSystemTime: SYSTEMTIME | t.CPtr) -> BOOL | t.State: pass
def SystemTimeToFileTime(lpSystemTime: SYSTEMTIME | t.CPtr, lpFileTime: FILETIME | t.CPtr) -> BOOL | t.State: pass
def QueryPerformanceCounter(lpPerformanceCount: LARGE_INTEGER | t.CPtr) -> BOOL | t.State: pass
def QueryPerformanceFrequency(lpFrequency: LARGE_INTEGER | t.CPtr) -> BOOL | t.State: pass
def Sleep(dwMilliseconds: ULONG) -> t.State: pass
def SleepEx(dwMilliseconds: ULONG, bAlertable: BOOL) -> ULONG | t.State: pass
def GetTickCount() -> ULONG | t.State: pass
def GetTickCount64() -> ULONGLONG | t.State: pass
def GetCommandLineA() -> CHARPTR | t.State: pass
-256
View File
@@ -1,256 +0,0 @@
from stdint import *
import t, c
from t import CInt, CExport
from stdio import printf
import memhub
import stdlib
import sys
import string
import ast
import w32.win32console
# MBuddy arena 大小:1MB
ARENA_SIZE: t.CDefine = 1048576
# mpool 内存大小:512KB
POOL_SIZE: t.CDefine = 524288
# dump 缓冲区大小:256KB
DUMP_SIZE: t.CDefine = 262144
def classify_list(lst: list[ast.AST | t.CPtr] | t.CPtr, depth: t.CInt):
"""递归遍历 list[AST | t.CPtr] 容器,逐元素分类(orelse/args/comparators 等)"""
if lst is None:
return
n: t.CSizeT = lst.__len__()
i: t.CSizeT = 0
while i < n:
classify_print(lst.get(i), depth + 1)
i += 1
def classify_print(node: ast.AST | t.CPtr, depth: t.CInt):
"""递归遍历 parse 树,用 isinstance 运行时判定每个节点的类别并打印。
依赖 TPV isinstance 的 vtable 子类集合比较:
- isinstance(node, ast.Stmt) → 语句节点(Assign/If/For/While/...)
- isinstance(node, ast.ExprNode) → 表达式节点(Name/Constant/BinOp/...)
- 两者皆非 → 其他(Module/Expression/...)
验证运行时(非编译期静态)正确区分 Stmt 与 ExprNode。
"""
if node is None:
return
sp: t.CInt = 0
while sp < depth:
printf(" ")
sp += 1
if isinstance(node, ast.Stmt) != 0:
printf("STMT %s\n", node.type_name())
elif isinstance(node, ast.ExprNode) != 0:
printf("EXPR %s\n", node.type_name())
else:
printf("OTHER %s\n", node.type_name())
# 按 kind 遍历语句持有的表达式字段(语句 body 块均在 children)。
# 属性访问前先 cast 成具体节点类:node 静态类型是 ast.AST,
# 直接访问 node.value 会在 AST 基类字段表 fast-fail(按需过滤原则)。
k: t.CInt = node.kind()
if k == ast.ASTKind.Assign:
asg: ast.Assign | t.CPtr = (ast.Assign | t.CPtr)(node)
classify_print(asg.value, depth + 1)
elif k == ast.ASTKind.If:
ifn: ast.If | t.CPtr = (ast.If | t.CPtr)(node)
classify_print(ifn.test, depth + 1)
classify_list(ifn.orelse, depth + 1)
elif k == ast.ASTKind.While:
whl: ast.While | t.CPtr = (ast.While | t.CPtr)(node)
classify_print(whl.test, depth + 1)
classify_list(whl.orelse, depth + 1)
elif k == ast.ASTKind.For:
for_nd: ast.For | t.CPtr = (ast.For | t.CPtr)(node)
classify_print(for_nd.iter, depth + 1)
classify_print(for_nd.target, depth + 1)
classify_list(for_nd.orelse, depth + 1)
elif k == ast.ASTKind.Return:
ret_nd: ast.Return | t.CPtr = (ast.Return | t.CPtr)(node)
classify_print(ret_nd.value, depth + 1)
elif k == ast.ASTKind.Expr:
expr_nd: ast.Expr | t.CPtr = (ast.Expr | t.CPtr)(node)
classify_print(expr_nd.value, depth + 1)
elif k == ast.ASTKind.BinOp:
bin_nd: ast.BinOp | t.CPtr = (ast.BinOp | t.CPtr)(node)
classify_print(bin_nd.left, depth + 1)
classify_print(bin_nd.right, depth + 1)
elif k == ast.ASTKind.UnaryOp:
una_nd: ast.UnaryOp | t.CPtr = (ast.UnaryOp | t.CPtr)(node)
classify_print(una_nd.operand, depth + 1)
elif k == ast.ASTKind.Compare:
cmp_nd: ast.Compare | t.CPtr = (ast.Compare | t.CPtr)(node)
classify_print(cmp_nd.left, depth + 1)
classify_list(cmp_nd.comparators, depth + 1)
elif k == ast.ASTKind.BoolOp:
bool_nd: ast.BoolOp | t.CPtr = (ast.BoolOp | t.CPtr)(node)
classify_list(bool_nd.values, depth + 1)
elif k == ast.ASTKind.Call:
call_nd: ast.Call | t.CPtr = (ast.Call | t.CPtr)(node)
classify_print(call_nd.func, depth + 1)
classify_list(call_nd.args, depth + 1)
else:
pass
# children(语句 body 块)
if node.children is not None:
n: t.CSizeT = node.children.__len__()
i: t.CSizeT = 0
while i < n:
classify_print(node.children.get(i), depth + 1)
i += 1
def main() -> CInt | CExport:
w32.win32console.SetConsoleCP(65001)
w32.win32console.SetConsoleOutputCP(65001)
printf("AST Comprehensive Test Start\n")
# 初始化全局 MBuddy 内存分配器
arena: bytes = stdlib.malloc(ARENA_SIZE)
if arena == None:
printf("FAIL: arena alloc failed\n")
return 1
mbuddy_obj: memhub.MemBuddy | t.CPtr = memhub.MemBuddy(arena, ARENA_SIZE)
if mbuddy_obj == None:
printf("FAIL: mbuddy init failed\n")
return 1
sys._mbuddy = mbuddy_obj
ast._mbuddy = mbuddy_obj
# 为 ast 解析器创建 mpool
pool_mem: bytes = stdlib.malloc(POOL_SIZE)
if pool_mem == None:
printf("FAIL: malloc for pool failed\n")
return 1
pool: memhub.MemPool | t.CPtr = memhub.MemPool(pool_mem, POOL_SIZE)
if pool == None:
printf("FAIL: memhub.MemPool init failed\n")
return 1
# dump 缓冲区(独立分配)
dump_mem: bytes = stdlib.malloc(DUMP_SIZE)
if dump_mem == None:
printf("FAIL: malloc for dump failed\n")
return 1
dump_buf: t.CChar | t.CPtr = t.CChar(dump_mem, t.CPtr)
# 综合测试源码:覆盖 CPython 主要语法
src: str = """x = 1
y = 2
z = x + y
a = x - y
b = x * y
c = x / y
d = x == y
e = x < y
f = x > y
g = x and y
h = x or y
i = not x
def foo(a, b):
return a + b
result = foo(x, y)
if x > 0:
print(x)
else:
print(y)
for i in range(10):
print(i)
while x > 0:
x = x - 1
class Point:
pass
"""
printf("Parsing comprehensive source...\n")
# 解析
ast._init_tables(pool)
lx_dbg: t.CPtr = ast.new_lexer(pool)
if lx_dbg == None:
printf("FAIL: new_lexer returned None\n")
stdlib.free(pool_mem)
stdlib.free(dump_mem)
return 1
ast._lexer_init(lx_dbg, src, pool)
tokens_dbg: t.CPtr = ast.tokenize(lx_dbg)
if tokens_dbg == None:
printf("FAIL: tokenize returned None\n")
stdlib.free(pool_mem)
stdlib.free(dump_mem)
return 1
tree: ast.AST | t.CPtr = ast.parse_tokens(pool, tokens_dbg)
if tree == None:
printf("FAIL: parse returned None\n")
stdlib.free(pool_mem)
stdlib.free(dump_mem)
return 1
printf("PASS: parse succeeded\n")
# dump AST
printf("Calling ast.dump...\n")
ast.dump(tree, dump_buf, DUMP_SIZE)
printf("ast.dump returned, now printing buffer...\n")
printf("=== AST DUMP ===\n%s\n=== END ===\n", dump_buf)
# ============================================================
# Stmt/Expr 运行时区分测试(isinstance vtable 子类集合比较)
# ============================================================
printf("=== STMT/EXPR RUNTIME DISTINGUISH TEST ===\n")
classify_print(tree, 0)
# 断言 1: Module 既非 Stmt 亦非 ExprNode(顶层容器)
if isinstance(tree, ast.Stmt) != 0 or isinstance(tree, ast.ExprNode) != 0:
printf("FAIL: Module misclassified as Stmt/ExprNode\n")
else:
printf("PASS: Module is neither Stmt nor ExprNode\n")
# 断言 2: 顶层 body 每条语句均为 Stmt
top_ok: t.CInt = 1
top_n: t.CSizeT = tree.children.__len__()
i2: t.CSizeT = 0
while i2 < top_n:
top_node: ast.AST | t.CPtr = tree.children.get(i2)
if isinstance(top_node, ast.Stmt) == 0:
top_ok = 0
printf("FAIL: top-level node not Stmt: %s\n", top_node.type_name())
i2 += 1
if top_ok != 0:
printf("PASS: all %lld top-level nodes are Stmt\n", top_n)
# 断言 3: Assign 是 Stmt 且不是 ExprNode
first_assign: ast.Assign | t.CPtr = (ast.Assign | t.CPtr)(tree.children.get(0))
if isinstance(first_assign, ast.Stmt) != 0 and isinstance(first_assign, ast.ExprNode) == 0:
printf("PASS: Assign is Stmt, not ExprNode\n")
else:
printf("FAIL: Assign classification wrong\n")
# 断言 4: Assign.value(表达式)是 ExprNode 且不是 Stmt
if isinstance(first_assign.value, ast.ExprNode) != 0 \
and isinstance(first_assign.value, ast.Stmt) == 0:
printf("PASS: Assign.value is ExprNode (%s)\n", first_assign.value.type_name())
else:
printf("FAIL: Assign.value not ExprNode\n")
# 断言 5: 表达式语句 Expr(如 print(x))属于 Stmt(Statement 语义)
if top_n >= 15:
if_node: ast.If | t.CPtr = (ast.If | t.CPtr)(tree.children.get(14))
if if_node.children is not None and if_node.children.__len__() > 0:
expr_stmt: ast.Expr | t.CPtr = (ast.Expr | t.CPtr)(if_node.children.get(0))
if isinstance(expr_stmt, ast.Stmt) != 0 and isinstance(expr_stmt, ast.ExprNode) == 0:
printf("PASS: Expr(stmt) is Stmt, not ExprNode (%s)\n", expr_stmt.type_name())
else:
printf("FAIL: Expr(stmt) classification wrong\n")
printf("=== END RUNTIME TEST ===\n")
stdlib.free(pool_mem)
stdlib.free(dump_mem)
return 0
-1
View File
@@ -1 +0,0 @@
├ INFO: [剥离] 调试段已移除 (llvm-strip)
-29
View File
@@ -1,29 +0,0 @@
{
"$schema": "https://raw.githubusercontent.com/TermiNexus/TransPyC/main/schemas/project-schema.json",
"name": "AstTest",
"version": "1.0.0",
"source_dir": "./App",
"build_dir": "./.tpv_build",
"compiler": {
"cmd": "llc",
"flags": ["-filetype=obj", "-relocation-model=pic"]
},
"linker": {
"cmd": "clang++",
"flags": ["-lmsvcrt", "-lucrt", "-lpthread", "-lmingwex", "-lkernel32", "-Wl,--allow-multiple-definition"],
"output": "AstTest.exe"
},
"includes": [
"../../includes"
],
"target": {
"triple": "x86_64-pc-windows-gnu",
"datalayout": "e-m:w-p270:32:32-p271:32:32-p272:64:64-i64:64-f80:128-n8:16:32:64-S128"
},
"options": {
"slice_level": 3,
"sha1_slice_level": 1,
"target": "llvm",
"strict_mode": true
}
}
-18
View File
@@ -1,18 +0,0 @@
from stdint import *
import w32.win32console
import t, c
from t import CInt, CExport
import memhub
import mbuddytest
def main() -> CInt | CExport:
w32.win32console.SetConsoleCP(65001)
w32.win32console.SetConsoleOutputCP(65001)
# memhub 的 [MEMDBG] 悬空/重复 free 检测默认开启(_memdbg_enable=1)。
# BuddyTest 含"故意双重 free,期望静默拒绝且状态不损坏"的负向用例,
# 若保持开启会在第二次 free 处终止进程 → 在此关闭 debug 模式。
memhub._memdbg_enable = 0
return mbuddytest.mbuddy_main()
-545
View File
@@ -1,545 +0,0 @@
import t, c
from t import CInt, CPtr, CChar, CUInt8T, CUInt32T, CUInt64T, CSizeT
import viperlib
import viperio
import stdlib
import memhub
import string
import testcheck
import w32.win32process
import w32.win32sync
import w32.win32base
# 线程函数: 在共享 MBuddy 上执行 alloc/free (测试 spinlock 线程安全)
def _thread_alloc_free(param: t.CVoid | t.CPtr) -> t.CUInt32T:
bd: memhub.MemBuddy | t.CPtr = (memhub.MemBuddy | t.CPtr)(param)
i: CInt
for i in range(100):
p: bytes = bd.alloc(32)
if p != None:
p_c: CUInt8T | CPtr = CPtr(p)
p_c[0] = CUInt8T(i & 0xFF)
bd.free(p)
return 0
def mbuddy_main() -> CInt:
buf: bytes = stdlib.malloc(256)
testcheck.begin("BuddyTest: 伙伴系统内存分配器测试")
# === 基础 alloc/free 测试 ===
testcheck.section("基础 alloc/free")
arena: bytes = stdlib.malloc(65536)
bd: memhub.MemBuddy | CPtr = memhub.MemBuddy(arena, 65536)
viperlib.snprintf(buf, 256, "stats=%lu, free_count=%lu", bd.stats(), bd.free_count())
testcheck.info(buf)
p1: bytes = bd.alloc(16)
p2: bytes = bd.alloc(64)
p3: bytes = bd.alloc(256)
testcheck.check(p1 != None and p2 != None and p3 != None,
"3 allocs OK", "alloc FAILED")
# 写入数据验证指针可用
p_c: CUInt8T | CPtr = CPtr(p1)
p_c[0] = CUInt8T(0xAB)
p_c[1] = CUInt8T(0xCD)
viperlib.snprintf(buf, 256, "p1[0]=0x%x p1[1]=0x%x", p_c[0], p_c[1])
testcheck.info(buf)
testcheck.check(p_c[0] == CUInt8T(0xAB) and p_c[1] == CUInt8T(0xCD),
"write/read OK", "write/read FAILED")
bd.free(p1)
bd.free(p2)
bd.free(p3)
testcheck.ok("3 frees OK")
# 释放后验证合并: free_count 应回到初始分解块数 (10)
# 4096-264 内非 2 的幂: 65536-264=65272 二进制分解为 10 个 2 的幂块
testcheck.check(bd.free_count() == 10,
"coalesce: free_count=10 OK", "coalesce: free_count != 10")
# 合并后应能分配大块
big: bytes = bd.alloc(16000)
testcheck.check(big != None, "big alloc OK", "big alloc FAILED")
bd.free(big)
stdlib.free(arena)
# === calloc 测试 (验证清零) ===
testcheck.section("calloc 清零")
arena2: bytes = stdlib.malloc(4096)
viperlib.snprintf(buf, 256, "arena2 = %p", arena2)
testcheck.info(buf)
bd2: memhub.MemBuddy | CPtr = memhub.MemBuddy(arena2, 4096)
dirty: bytes = bd2.alloc(64)
viperlib.snprintf(buf, 256, "dirty = %p", dirty)
testcheck.info(buf)
d_c: CUInt8T | CPtr = CPtr(dirty)
i: CInt
for i in range(64):
d_c[i] = CUInt8T(0xFF)
bd2.free(dirty)
cl: bytes = bd2.calloc(8, 8)
viperlib.snprintf(buf, 256, "cl = %p (arena2=%p, dirty was=%p)", cl, arena2, dirty)
testcheck.info(buf)
if cl != None:
cl_c: CUInt8T | CPtr = CPtr(cl)
all_zero: CInt = 1
j: CInt
for j in range(64):
if cl_c[j] != 0:
all_zero = 0
break
testcheck.check(all_zero == 1, "calloc zeroed OK", "calloc NOT zeroed")
bd2.free(cl)
else:
testcheck.fail("calloc FAILED")
stdlib.free(arena2)
# === realloc 扩展测试 ===
testcheck.section("realloc 扩展")
arena3: bytes = stdlib.malloc(4096)
bd3: memhub.MemBuddy | CPtr = memhub.MemBuddy(arena3, 4096)
rp: bytes = bd3.alloc(32)
rp_c: CUInt8T | CPtr = CPtr(rp)
k: CInt
for k in range(32):
rp_c[k] = CUInt8T(k + 1)
rp2: bytes = bd3.realloc(rp, 128)
if rp2 != None:
rp2_c: CUInt8T | CPtr = CPtr(rp2)
ok: CInt = 1
m: CInt
for m in range(32):
if rp2_c[m] != CUInt8T(m + 1):
ok = 0
break
testcheck.check(ok == 1, "realloc grow data preserved OK", "realloc grow data LOST")
bd3.free(rp2)
else:
testcheck.fail("realloc grow FAILED")
stdlib.free(arena3)
# === 原地收缩测试 (验证无泄漏) ===
testcheck.section("原地收缩 (realloc shrink)")
arena_shrink: bytes = stdlib.malloc(4096)
bds: memhub.MemBuddy | CPtr = memhub.MemBuddy(arena_shrink, 4096)
sp: bytes = bds.alloc(256)
testcheck.check(sp != None, "alloc 256 OK", "alloc 256 FAILED")
fc_before: CSizeT = bds.free_count()
# realloc 到更小尺寸: 256+8=264 -> order 4 (512); 32+8=40 -> order 1 (64)
# new_order(1) <= old_order(4), 应原地返回同一指针
sp2: bytes = bds.realloc(sp, 32)
fc_after: CSizeT = bds.free_count()
testcheck.check(sp2 == sp, "shrink same ptr OK", "shrink ptr changed")
testcheck.check(fc_after == fc_before, "shrink no leak OK", "shrink LEAKED blocks")
# 验证数据仍可读写
sp_c: CUInt8T | CPtr = CPtr(sp2)
sp_c[0] = CUInt8T(0x42)
testcheck.check(sp_c[0] == CUInt8T(0x42), "shrink data OK", "shrink data FAILED")
bds.free(sp2)
testcheck.check(bds.free_count() == 6, "shrink+free coalesce OK", "shrink+free coalesce FAILED")
stdlib.free(arena_shrink)
# === 边界情况测试 ===
testcheck.section("边界情况")
arena4: bytes = stdlib.malloc(4096)
bd4: memhub.MemBuddy | CPtr = memhub.MemBuddy(arena4, 4096)
# alloc(0) 应返回 None
z: bytes = bd4.alloc(0)
testcheck.check(z == None, "alloc(0)=None OK", "alloc(0) should be None")
# free(None) 应安全
bd4.free(None)
testcheck.ok("free(None) safe")
# realloc(None, size) 等价于 alloc
rn: bytes = bd4.realloc(None, 32)
testcheck.check(rn != None, "realloc(None)=alloc OK", "realloc(None) FAILED")
bd4.free(rn)
# realloc(ptr, 0) 等价于 free
rz: bytes = bd4.alloc(32)
rz2: bytes = bd4.realloc(rz, 0)
testcheck.check(rz2 == None, "realloc(ptr,0)=free OK", "realloc(ptr,0) should be None")
stdlib.free(arena4)
# === 非法指针防护测试 ===
testcheck.section("非法指针防护")
arena5: bytes = stdlib.malloc(4096)
bd5: memhub.MemBuddy | CPtr = memhub.MemBuddy(arena5, 4096)
valid: bytes = bd5.alloc(32)
testcheck.check(valid != None, "alloc for illegal test OK", "alloc FAILED")
# 1. free 随机地址 (地址 1)
bd5.free(t.CVoid(t.CUInt64T(1), t.CPtr))
testcheck.ok("free(addr=1) ignored")
# 2. free NULL
bd5.free(None)
testcheck.ok("free(NULL) ignored")
# 3. free 越界指针 (arena 之前)
bd5.free(t.CVoid(t.CUInt64T(arena5), t.CPtr))
testcheck.ok("free(before arena) ignored")
# 4. free 越界指针 (arena 之后)
bd5.free(t.CVoid(t.CUInt64T(arena5) + 99999, t.CPtr))
testcheck.ok("free(after arena) ignored")
# 5. free 未对齐指针 (arena + 1, 在 mem 区域内但不对齐)
bd5.free(t.CVoid(t.CUInt64T(bd5.base) + 1, t.CPtr))
testcheck.ok("free(misaligned) ignored")
# 6. 验证合法 free 仍正常工作 (释放后应能再次分配)
bd5.free(valid)
retry5: bytes = bd5.alloc(32)
testcheck.check(retry5 != None, "valid free still works OK", "valid free BROKEN")
if retry5 != None:
bd5.free(retry5)
# 7. realloc 非法指针应返回 None
r_illegal: bytes = bd5.realloc(t.CVoid(t.CUInt64T(1), t.CPtr), 64)
testcheck.check(r_illegal == None, "realloc(illegal)=None OK", "realloc(illegal) should be None")
stdlib.free(arena5)
# === OOM 内存耗尽测试 ===
testcheck.section("OOM 内存耗尽")
arena6: bytes = stdlib.malloc(4096)
bd6: memhub.MemBuddy | CPtr = memhub.MemBuddy(arena6, 4096)
# 持续分配直到失败
alloc_count: CInt = 0
ptrs_arr: bytes = stdlib.malloc(8 * 256) # 存储指针的数组
ptrs: CUInt64T | CPtr = CPtr(ptrs_arr)
while alloc_count < 256:
p: bytes = bd6.alloc(32)
if p == None:
break
ptrs[alloc_count] = t.CUInt64T(p)
alloc_count += 1
viperlib.snprintf(buf, 256, "allocated %d blocks before OOM", alloc_count)
testcheck.info(buf)
testcheck.check(alloc_count > 0, "OOM: got some allocs OK", "OOM: no allocs at all")
# 尝试再分配应失败
oom_p: bytes = bd6.alloc(32)
testcheck.check(oom_p == None, "OOM: alloc fails OK", "OOM: alloc should fail")
# 释放一个块后应能再次分配
if alloc_count > 0:
first_ptr: bytes = t.CVoid(ptrs[0], t.CPtr)
bd6.free(first_ptr)
retry: bytes = bd6.alloc(32)
testcheck.check(retry != None, "OOM: free+alloc OK", "OOM: free+alloc FAILED")
if retry != None:
bd6.free(retry)
# 释放所有块
idx: CInt = 1
while idx < alloc_count:
cur_p: bytes = t.CVoid(ptrs[idx], t.CPtr)
bd6.free(cur_p)
idx += 1
# 全部释放后应能合并回初始分解块数 (6)
testcheck.check(bd6.free_count() == 6,
"OOM: full coalesce OK", "OOM: free_count != 6 after full free")
stdlib.free(ptrs_arr)
stdlib.free(arena6)
# === 空闲链表状态测试 ===
testcheck.section("空闲链表状态")
arena7: bytes = stdlib.malloc(4096)
bd7: memhub.MemBuddy | CPtr = memhub.MemBuddy(arena7, 4096)
# 初始: 非 2 的幂 arena (4096-264=3832) 二进制分解为 6 个块
testcheck.check(bd7.free_count() == 6, "init: 6 free blocks OK", "init: free_count != 6")
# 分配后: 空闲块数应增加 (分裂产生多个小块)
a1: bytes = bd7.alloc(32)
fc1: CSizeT = bd7.free_count()
viperlib.snprintf(buf, 256, "after alloc(32): free_count=%lu", fc1)
testcheck.info(buf)
testcheck.check(fc1 > 1, "after alloc: split OK", "after alloc: no split")
# 再分配
a2: bytes = bd7.alloc(32)
fc2: CSizeT = bd7.free_count()
testcheck.check(fc2 >= 1, "after 2nd alloc: free >= 1 OK", "after 2nd alloc: free < 1")
# 释放 a1: 空闲块数应增加
bd7.free(a1)
fc3: CSizeT = bd7.free_count()
testcheck.check(fc3 > fc2, "after free a1: free increased OK", "after free a1: free not increased")
# 释放 a2: 应合并, 空闲块数回到初始 6 块
bd7.free(a2)
testcheck.check(bd7.free_count() == 6,
"after free all: coalesced to 6 OK", "after free all: free_count != 6")
stdlib.free(arena7)
# === with 上下文管理器测试 ===
testcheck.section("with 上下文管理器")
arena8: bytes = stdlib.malloc(4096)
with memhub.MemBuddy(arena8, 4096) as wbd:
wp1: bytes = wbd.alloc(32)
wp2: bytes = wbd.alloc(64)
testcheck.check(wp1 != None and wp2 != None,
"with: allocs OK", "with: allocs FAILED")
# 退出 with 块时 __exit__ 自动 reset
# 退出后重新进入,验证 reset 生效
with memhub.MemBuddy(arena8, 4096) as wbd2:
wp3: bytes = wbd2.alloc(1024)
testcheck.check(wp3 != None, "with: reset+realloc OK", "with: reset+realloc FAILED")
stdlib.free(arena8)
# === 双重 free 检测测试 ===
testcheck.section("双重 free 检测")
arena_df: bytes = stdlib.malloc(4096)
bd_df: memhub.MemBuddy | CPtr = memhub.MemBuddy(arena_df, 4096)
df: bytes = bd_df.alloc(64)
testcheck.check(df != None, "df: alloc OK", "df: alloc FAILED")
# 第一次 free
bd_df.free(df)
fc_df1: CSizeT = bd_df.free_count()
testcheck.ok("first free OK")
# 第二次 free (双重 free) — 应被静默拒绝
bd_df.free(df)
fc_df2: CSizeT = bd_df.free_count()
testcheck.check(fc_df2 == fc_df1, "double free rejected OK", "double free CORRUPTED state")
# 验证分配器仍正常工作
df2: bytes = bd_df.alloc(64)
testcheck.check(df2 != None, "df: alloc after double-free OK", "df: alloc after double-free FAILED")
if df2 != None:
bd_df.free(df2)
stdlib.free(arena_df)
# === 自检功能测试 ===
testcheck.section("自检功能")
arena_sc: bytes = stdlib.malloc(4096)
bd_sc: memhub.MemBuddy | CPtr = memhub.MemBuddy(arena_sc, 4096)
# 初始状态自检
testcheck.check(bd_sc.self_check() == 0, "self_check init OK", "self_check init FAILED")
# 分配后自检
sc_p1: bytes = bd_sc.alloc(32)
sc_p2: bytes = bd_sc.alloc(128)
testcheck.check(bd_sc.self_check() == 0, "self_check after alloc OK", "self_check after alloc FAILED")
# 部分释放后自检
bd_sc.free(sc_p1)
testcheck.check(bd_sc.self_check() == 0, "self_check after partial free OK", "self_check after partial free FAILED")
# 全部释放后自检 (应合并回单个大块)
bd_sc.free(sc_p2)
testcheck.check(bd_sc.self_check() == 0, "self_check after full free OK", "self_check after full free FAILED")
# 双重 free 后自检 (验证状态未损坏)
sc_p3: bytes = bd_sc.alloc(64)
bd_sc.free(sc_p3)
bd_sc.free(sc_p3) # 双重 free,应被拒绝
testcheck.check(bd_sc.self_check() == 0, "self_check after double-free OK", "self_check after double-free CORRUPTED")
stdlib.free(arena_sc)
# === 并发多线程测试 (spinlock) ===
testcheck.section("并发多线程 (spinlock)")
arena_mt: bytes = stdlib.malloc(65536)
bd_mt: memhub.MemBuddy | CPtr = memhub.MemBuddy(arena_mt, 65536)
NUM_THREADS: CInt = 4
handles_arr: bytes = stdlib.malloc(8 * 4)
handles: CUInt64T | CPtr = CPtr(handles_arr)
tid: CUInt32T = 0
# 创建 4 个线程并发 alloc/free
t_idx: CInt
for t_idx in range(NUM_THREADS):
h: bytes = w32.win32process.CreateThread(None, 0, _thread_alloc_free, t.CVoid(t.CUInt64T(bd_mt), t.CPtr), 0, c.Addr(tid))
handles[t_idx] = CUInt64T(h)
# 等待所有线程完成
for t_idx in range(NUM_THREADS):
h: bytes = t.CVoid(handles[t_idx], t.CPtr)
w32.win32sync.WaitForSingleObject(h, w32.win32base.INFINITE)
w32.win32base.CloseHandle(h)
# 验证分配器状态: 自检通过,所有块已合并
testcheck.check(bd_mt.self_check() == 0, "mt: self_check OK", "mt: self_check FAILED")
testcheck.check(bd_mt.free_count() == 10, "mt: free_count=10 OK", "mt: free_count != 10 (leaked)")
viperlib.snprintf(buf, 256, "mt: free_count=%lu", bd_mt.free_count())
testcheck.info(buf)
stdlib.free(handles_arr)
stdlib.free(arena_mt)
# === 极端边界测试 ===
testcheck.section("极端边界")
# 1. 分配尺寸恰巧是块边界
arena_ex: bytes = stdlib.malloc(4096)
bd_ex: memhub.MemBuddy | CPtr = memhub.MemBuddy(arena_ex, 4096)
# 24 + 16 = 40 > 32(8 头 + 8 哨兵),需要 order 1 (64 字节)
exact_fit: bytes = bd_ex.alloc(24)
testcheck.check(exact_fit != None, "exact fit order 0 OK", "exact fit order 0 FAILED")
# 25 + 16 = 41 > 32, 需要 order 1 (64 字节)
over_fit: bytes = bd_ex.alloc(25)
testcheck.check(over_fit != None, "over by 1 byte OK", "over by 1 byte FAILED")
bd_ex.free(exact_fit)
bd_ex.free(over_fit)
testcheck.check(bd_ex.free_count() == 6, "boundary: coalesce OK", "boundary: coalesce FAILED")
# 2. 单次分配接近最大块上限(order6=2048,非 2 的幂 arena 的最大分解块)
# 可用数据区 = 2048 - 8(头) - 8(哨兵),alloc(max_usable) 的 needed 恰好
# = 2048,正好填满 order6 最大块
max_usable: CSizeT = 2048 - 16
viperlib.snprintf(buf, 256, "mem_size=%lu, max_block=2048, max_usable=%lu", bd_ex.mem_size, max_usable)
testcheck.info(buf)
# 恰好用完 order6 块(其余 5 个分解块空闲)
exact_max: bytes = bd_ex.alloc(max_usable)
testcheck.check(exact_max != None, "exact max alloc OK", "exact max alloc FAILED")
testcheck.check(bd_ex.free_count() == 5, "max alloc: 5 free blocks left OK", "max alloc: free_count != 5")
bd_ex.free(exact_max)
testcheck.check(bd_ex.free_count() == 6, "max free: coalesce OK", "max free: coalesce FAILED")
# 再次分配同样大小 — 验证合并后可再次使用
exact_max2: bytes = bd_ex.alloc(max_usable)
testcheck.check(exact_max2 != None, "exact max re-alloc OK", "exact max re-alloc FAILED")
bd_ex.free(exact_max2)
# 3. 分配超过 arena 上限 — 应失败
over_max: bytes = bd_ex.alloc(bd_ex.mem_size)
testcheck.check(over_max == None, "over max: fails OK", "over max: should fail")
over_max2: bytes = bd_ex.alloc(max_usable + 1)
testcheck.check(over_max2 == None, "max+1: fails OK", "max+1: should fail")
stdlib.free(arena_ex)
# 4. Arena 太小 (仅够 free_lists 开销, 264 字节)
arena_tiny: bytes = stdlib.malloc(264)
bd_tiny: memhub.MemBuddy | CPtr = memhub.MemBuddy(arena_tiny, 264)
testcheck.check(bd_tiny.stats() == 0, "tiny arena: stats=0 OK", "tiny arena: stats != 0")
tiny_p: bytes = bd_tiny.alloc(32)
testcheck.check(tiny_p == None, "tiny arena: alloc fails OK", "tiny arena: should fail")
stdlib.free(arena_tiny)
# 5. Arena 刚好够一个最小块 (264 + 32 = 296)
arena_one: bytes = stdlib.malloc(296)
bd_one: memhub.MemBuddy | CPtr = memhub.MemBuddy(arena_one, 296)
testcheck.check(bd_one.stats() == 32, "one block: stats=32 OK", "one block: stats != 32")
# 最小块 32 字节 = 数据 16 + 头 8 + 哨兵 8,alloc(16) 恰好填满
one_p: bytes = bd_one.alloc(16)
testcheck.check(one_p != None, "one block: alloc OK", "one block: alloc FAILED")
one_p2: bytes = bd_one.alloc(16)
testcheck.check(one_p2 == None, "one block: OOM OK", "one block: should be OOM")
bd_one.free(one_p)
testcheck.check(bd_one.free_count() == 1, "one block: free OK", "one block: free FAILED")
stdlib.free(arena_one)
# 6. 2 的幂 arena vs 非 2 的幂 arena
arena_pow2: bytes = stdlib.malloc(512)
bd_pow2: memhub.MemBuddy | CPtr = memhub.MemBuddy(arena_pow2, 512)
# 512 - 264 = 248, 二进制分解 = 128+64+32 = 224 (尾 24 字节碎片不入池)
testcheck.check(bd_pow2.stats() == 224, "pow2 arena: stats=224 OK", "pow2 arena: stats != 224")
stdlib.free(arena_pow2)
arena_non2: bytes = stdlib.malloc(500)
bd_non2: memhub.MemBuddy | CPtr = memhub.MemBuddy(arena_non2, 500)
# 500 - 264 = 236, 二进制分解 = 128+64+32 = 224 (尾 12 字节碎片不入池)
testcheck.check(bd_non2.stats() == 224, "non-pow2 arena: stats=224 OK", "non-pow2 arena: stats != 224")
stdlib.free(arena_non2)
# 7. 压力测试: 反复 alloc/free 同一尺寸 1000 次
arena_stress: bytes = stdlib.malloc(4096)
bd_stress: memhub.MemBuddy | CPtr = memhub.MemBuddy(arena_stress, 4096)
s: CInt
for s in range(1000):
sp: bytes = bd_stress.alloc(64)
if sp != None:
sp_c: CUInt8T | CPtr = CPtr(sp)
sp_c[0] = CUInt8T(s & 0xFF)
bd_stress.free(sp)
testcheck.check(bd_stress.self_check() == 0, "stress: self_check OK", "stress: self_check FAILED")
testcheck.check(bd_stress.free_count() == 6, "stress: free_count=6 OK", "stress: leaked")
stdlib.free(arena_stress)
# 8. 分配全部最小块然后全部释放
arena_fill: bytes = stdlib.malloc(4096)
bd_fill: memhub.MemBuddy | CPtr = memhub.MemBuddy(arena_fill, 4096)
fill_count: CInt = 0
fill_ptrs_arr: bytes = stdlib.malloc(8 * 256)
fill_ptrs: CUInt64T | CPtr = CPtr(fill_ptrs_arr)
fc: CInt
for fc in range(256):
fp: bytes = bd_fill.alloc(24)
if fp == None:
break
fill_ptrs[fill_count] = t.CUInt64T(fp)
fill_count += 1
viperlib.snprintf(buf, 256, "fill: %d min blocks allocated", fill_count)
testcheck.info(buf)
testcheck.check(fill_count > 0, "fill: got blocks OK", "fill: no blocks")
testcheck.check(bd_fill.self_check() == 0, "fill: self_check OK", "fill: self_check FAILED")
# 全部释放
fi: CInt
for fi in range(fill_count):
fp2: bytes = t.CVoid(fill_ptrs[fi], t.CPtr)
bd_fill.free(fp2)
testcheck.check(bd_fill.free_count() == 6, "fill: all freed OK", "fill: leaked after free all")
testcheck.check(bd_fill.self_check() == 0, "fill: self_check after free OK", "fill: self_check FAILED")
stdlib.free(fill_ptrs_arr)
stdlib.free(arena_fill)
stdlib.free(buf)
return testcheck.end()
@@ -1 +0,0 @@
{"w32.win32process": "067c78e9f121dce3", "win32process": "067c78e9f121dce3", "w32.win32sync": "06f53cc594b4ac6c", "win32sync": "06f53cc594b4ac6c", "memhub": "2408ce147bac090b", "stdio": "285b6aa29a34754d", "viperio": "2c175afd85852faf", "mbuddytest": "490084d59cf67c44", "string": "4c39369ffedaddac", "stdlib": "6c658cc728d0bbf4", "stdarg": "71e0a3ffcb3ebfad", "testcheck": "748d0424e8976fa0", "atom": "aa246c6e6aa30484", "viperlib": "bba983c61a970f7c", "w32.win32console": "bbdf3bbd4c3bc28c", "win32console": "bbdf3bbd4c3bc28c", "stdint": "f5522571bcce7bcb", "w32.win32base": "fc980acec33d69a7", "win32base": "fc980acec33d69a7"}
-29
View File
@@ -1,29 +0,0 @@
{
"$schema": "https://raw.githubusercontent.com/TermiNexus/TransPyC/main/schemas/project-schema.json",
"name": "BuddyTest",
"version": "1.0.0",
"source_dir": "./App",
"build_dir": "./.tpv_build",
"compiler": {
"cmd": "llc",
"flags": ["-filetype=obj", "-relocation-model=pic"]
},
"linker": {
"cmd": "clang++",
"flags": ["-lmsvcrt", "-lucrt", "-lpthread", "-lmingwex", "-lkernel32", "-Wl,--allow-multiple-definition"],
"output": "BuddyTest.exe"
},
"includes": [
"../../includes"
],
"target": {
"triple": "x86_64-pc-windows-gnu",
"datalayout": "e-m:w-p270:32:32-p271:32:32-p272:64:64-i64:64-f80:128-n8:16:32:64-S128"
},
"options": {
"slice_level": 3,
"sha1_slice_level": 1,
"target": "llvm",
"strict_mode": true
}
}
@@ -1 +0,0 @@
f5522571bcce7bcb|fc980acec33d69a7
-136
View File
@@ -1,136 +0,0 @@
"""
Auto-generated Python stub file from w32.win32process.vp
Module: w32.win32process
"""
import c
import t
from stdint import *
from w32.win32base import *
PROCESS_TERMINATE: t.CDefine = 0x0001
PROCESS_CREATE_THREAD: t.CDefine = 0x0002
PROCESS_VM_OPERATION: t.CDefine = 0x0008
PROCESS_VM_READ: t.CDefine = 0x0010
PROCESS_VM_WRITE: t.CDefine = 0x0020
PROCESS_QUERY_INFORMATION: t.CDefine = 0x0400
PROCESS_ALL_ACCESS: t.CDefine = 0x001FFFFF
THREAD_TERMINATE: t.CDefine = 0x0001
THREAD_SUSPEND_RESUME: t.CDefine = 0x0002
THREAD_GET_CONTEXT: t.CDefine = 0x0008
THREAD_SET_CONTEXT: t.CDefine = 0x0010
THREAD_QUERY_INFORMATION: t.CDefine = 0x0040
THREAD_ALL_ACCESS: t.CDefine = 0x001FFFFF
CREATE_SUSPENDED: t.CDefine = 0x00000004
CREATE_NEW_CONSOLE: t.CDefine = 0x00000010
CREATE_NEW_PROCESS_GROUP: t.CDefine = 0x00000200
CREATE_NO_WINDOW: t.CDefine = 0x08000000
DETACHED_PROCESS: t.CDefine = 0x00000008
STARTF_USESHOWWINDOW: t.CDefine = 0x00000001
STARTF_USESTDHANDLES: t.CDefine = 0x00000100
SW_HIDE: t.CDefine = 0
SW_SHOW: t.CDefine = 5
SW_MINIMIZE: t.CDefine = 6
NORMAL_PRIORITY_CLASS: t.CDefine = 0x00000020
IDLE_PRIORITY_CLASS: t.CDefine = 0x00000040
HIGH_PRIORITY_CLASS: t.CDefine = 0x00000080
REALTIME_PRIORITY_CLASS: t.CDefine = 0x00000100
BELOW_NORMAL_PRIORITY_CLASS: t.CDefine = 0x00004000
ABOVE_NORMAL_PRIORITY_CLASS: t.CDefine = 0x00008000
STILL_ACTIVE: t.CDefine = 259
class STARTUPINFOA:
cb: ULONG
lpReserved: CHARPTR
lpDesktop: CHARPTR
lpTitle: CHARPTR
dwX: ULONG
dwY: ULONG
dwXSize: ULONG
dwYSize: ULONG
dwXCountChars: ULONG
dwYCountChars: ULONG
dwFillAttribute: ULONG
dwFlags: ULONG
wShowWindow: WORD
cbReserved2: WORD
lpReserved2: VOIDPTR
hStdInput: HANDLE
hStdOutput: HANDLE
hStdError: HANDLE
class STARTUPINFOW:
cb: ULONG
lpReserved: WCHARPTR
lpDesktop: WCHARPTR
lpTitle: WCHARPTR
dwX: ULONG
dwY: ULONG
dwXSize: ULONG
dwYSize: ULONG
dwXCountChars: ULONG
dwYCountChars: ULONG
dwFillAttribute: ULONG
dwFlags: ULONG
wShowWindow: WORD
cbReserved2: WORD
lpReserved2: VOIDPTR
hStdInput: HANDLE
hStdOutput: HANDLE
hStdError: HANDLE
class PROCESS_INFORMATION:
hProcess: HANDLE
hThread: HANDLE
dwProcessId: ULONG
dwThreadId: ULONG
def CreateProcessA(lpApplicationName: LPCSTR, lpCommandLine: CHARPTR, lpProcessAttributes: SECURITY_ATTRIBUTES | t.CPtr, lpThreadAttributes: SECURITY_ATTRIBUTES | t.CPtr, bInheritHandles: BOOL, dwCreationFlags: ULONG, lpEnvironment: VOIDPTR, lpCurrentDirectory: LPCSTR, lpStartupInfo: STARTUPINFOA | t.CPtr, lpProcessInformation: PROCESS_INFORMATION | t.CPtr) -> BOOL | t.State: pass
def CreateProcessW(lpApplicationName: LPCWSTR, lpCommandLine: WCHARPTR, lpProcessAttributes: SECURITY_ATTRIBUTES | t.CPtr, lpThreadAttributes: SECURITY_ATTRIBUTES | t.CPtr, bInheritHandles: BOOL, dwCreationFlags: ULONG, lpEnvironment: VOIDPTR, lpCurrentDirectory: LPCWSTR, lpStartupInfo: STARTUPINFOW | t.CPtr, lpProcessInformation: PROCESS_INFORMATION | t.CPtr) -> BOOL | t.State: pass
def TerminateProcess(hProcess: HANDLE, uExitCode: UINT) -> BOOL | t.State: pass
def GetExitCodeProcess(hProcess: HANDLE, lpExitCode: ULONG | t.CPtr) -> BOOL | t.State: pass
def GetExitCodeThread(hThread: HANDLE, lpExitCode: ULONG | t.CPtr) -> BOOL | t.State: pass
def OpenProcess(dwDesiredAccess: ULONG, bInheritHandle: BOOL, dwProcessId: ULONG) -> HANDLE | t.State: pass
def GetCurrentProcess() -> HANDLE | t.State: pass
def GetCurrentProcessId() -> ULONG | t.State: pass
def CreateThread(lpThreadAttributes: SECURITY_ATTRIBUTES | t.CPtr, dwStackSize: t.CSizeT, lpStartAddress: VOIDPTR, lpParameter: VOIDPTR, dwCreationFlags: ULONG, lpThreadId: ULONG | t.CPtr) -> HANDLE | t.State: pass
def OpenThread(dwDesiredAccess: ULONG, bInheritHandle: BOOL, dwThreadId: ULONG) -> HANDLE | t.State: pass
def SuspendThread(hThread: HANDLE) -> ULONG | t.State: pass
def ResumeThread(hThread: HANDLE) -> ULONG | t.State: pass
def TerminateThread(hThread: HANDLE, dwExitCode: ULONG) -> BOOL | t.State: pass
def GetCurrentThread() -> HANDLE | t.State: pass
def GetCurrentThreadId() -> ULONG | t.State: pass
def GetThreadId(hThread: HANDLE) -> ULONG | t.State: pass
def GetProcessId(hProcess: HANDLE) -> ULONG | t.State: pass
def SetThreadPriority(hThread: HANDLE, nPriority: INT) -> BOOL | t.State: pass
def GetThreadPriority(hThread: HANDLE) -> INT | t.State: pass
def ExitProcess(uExitCode: UINT) -> VOID | t.State: pass
def ExitThread(dwExitCode: ULONG) -> VOID | t.State: pass
def TlsAlloc() -> ULONG | t.State: pass
def TlsFree(dwTlsIndex: ULONG) -> BOOL | t.State: pass
def TlsGetValue(dwTlsIndex: ULONG) -> VOIDPTR | t.State: pass
def TlsSetValue(dwTlsIndex: ULONG, lpTlsValue: VOIDPTR) -> BOOL | t.State: pass
@@ -1 +0,0 @@
f5522571bcce7bcb|fc980acec33d69a7
-109
View File
@@ -1,109 +0,0 @@
"""
Auto-generated Python stub file from w32.win32sync.vp
Module: w32.win32sync
"""
import c
import t
from stdint import *
from w32.win32base import *
class CRITICAL_SECTION:
DebugInfo: VOIDPTR
LockCount: LONG
RecursionCount: LONG
OwningThread: HANDLE
LockSemaphore: HANDLE
SpinCount: QWORD
def InitializeCriticalSection(lpCriticalSection: CRITICAL_SECTION | t.CPtr) -> VOID | t.State: pass
def EnterCriticalSection(lpCriticalSection: CRITICAL_SECTION | t.CPtr) -> VOID | t.State: pass
def LeaveCriticalSection(lpCriticalSection: CRITICAL_SECTION | t.CPtr) -> VOID | t.State: pass
def DeleteCriticalSection(lpCriticalSection: CRITICAL_SECTION | t.CPtr) -> VOID | t.State: pass
def TryEnterCriticalSection(lpCriticalSection: CRITICAL_SECTION | t.CPtr) -> BOOL | t.State: pass
def SetCriticalSectionSpinCount(lpCriticalSection: CRITICAL_SECTION | t.CPtr, dwSpinCount: ULONG) -> ULONG | t.State: pass
def InitializeCriticalSectionAndSpinCount(lpCriticalSection: CRITICAL_SECTION | t.CPtr, dwSpinCount: ULONG) -> BOOL | t.State: pass
def CreateMutexA(lpMutexAttributes: SECURITY_ATTRIBUTES | t.CPtr, bInitialOwner: BOOL, lpName: LPCSTR) -> HANDLE | t.State: pass
def CreateMutexW(lpMutexAttributes: SECURITY_ATTRIBUTES | t.CPtr, bInitialOwner: BOOL, lpName: LPCWSTR) -> HANDLE | t.State: pass
def OpenMutexA(dwDesiredAccess: ULONG, bInheritHandle: BOOL, lpName: LPCSTR) -> HANDLE | t.State: pass
def OpenMutexW(dwDesiredAccess: ULONG, bInheritHandle: BOOL, lpName: LPCWSTR) -> HANDLE | t.State: pass
def ReleaseMutex(hMutex: HANDLE) -> BOOL | t.State: pass
def CreateEventA(lpEventAttributes: SECURITY_ATTRIBUTES | t.CPtr, bManualReset: BOOL, bInitialState: BOOL, lpName: LPCSTR) -> HANDLE | t.State: pass
def CreateEventW(lpEventAttributes: SECURITY_ATTRIBUTES | t.CPtr, bManualReset: BOOL, bInitialState: BOOL, lpName: LPCWSTR) -> HANDLE | t.State: pass
def OpenEventA(dwDesiredAccess: ULONG, bInheritHandle: BOOL, lpName: LPCSTR) -> HANDLE | t.State: pass
def OpenEventW(dwDesiredAccess: ULONG, bInheritHandle: BOOL, lpName: LPCWSTR) -> HANDLE | t.State: pass
def SetEvent(hEvent: HANDLE) -> BOOL | t.State: pass
def ResetEvent(hEvent: HANDLE) -> BOOL | t.State: pass
def PulseEvent(hEvent: HANDLE) -> BOOL | t.State: pass
def CreateSemaphoreA(lpSemaphoreAttributes: SECURITY_ATTRIBUTES | t.CPtr, lInitialCount: LONG, lMaximumCount: LONG, lpName: LPCSTR) -> HANDLE | t.State: pass
def CreateSemaphoreW(lpSemaphoreAttributes: SECURITY_ATTRIBUTES | t.CPtr, lInitialCount: LONG, lMaximumCount: LONG, lpName: LPCWSTR) -> HANDLE | t.State: pass
def OpenSemaphoreA(dwDesiredAccess: ULONG, bInheritHandle: BOOL, lpName: LPCSTR) -> HANDLE | t.State: pass
def OpenSemaphoreW(dwDesiredAccess: ULONG, bInheritHandle: BOOL, lpName: LPCWSTR) -> HANDLE | t.State: pass
def ReleaseSemaphore(hSemaphore: HANDLE, lReleaseCount: LONG, lpPreviousCount: LONG | t.CPtr) -> BOOL | t.State: pass
def WaitForSingleObject(hHandle: HANDLE, dwMilliseconds: ULONG) -> ULONG | t.State: pass
def WaitForSingleObjectEx(hHandle: HANDLE, dwMilliseconds: ULONG, bAlertable: BOOL) -> ULONG | t.State: pass
def WaitForMultipleObjects(nCount: ULONG, lpHandles: VOIDPTR, bWaitAll: BOOL, dwMilliseconds: ULONG) -> ULONG | t.State: pass
def WaitForMultipleObjectsEx(nCount: ULONG, lpHandles: VOIDPTR, bWaitAll: BOOL, dwMilliseconds: ULONG, bAlertable: BOOL) -> ULONG | t.State: pass
def InitializeSRWLock(SRWLock: VOIDPTR) -> VOID | t.State: pass
def AcquireSRWLockExclusive(SRWLock: VOIDPTR) -> VOID | t.State: pass
def AcquireSRWLockShared(SRWLock: VOIDPTR) -> VOID | t.State: pass
def ReleaseSRWLockExclusive(SRWLock: VOIDPTR) -> VOID | t.State: pass
def ReleaseSRWLockShared(SRWLock: VOIDPTR) -> VOID | t.State: pass
CONDITION_VARIABLE_LOCKMODE_SHARED: t.CDefine = 0x1
def InitializeConditionVariable(ConditionVariable: VOIDPTR) -> VOID | t.State: pass
def SleepConditionVariableCS(ConditionVariable: VOIDPTR, CriticalSection: CRITICAL_SECTION | t.CPtr, dwMilliseconds: ULONG) -> BOOL | t.State: pass
def SleepConditionVariableSRW(ConditionVariable: VOIDPTR, SRWLock: VOIDPTR, dwMilliseconds: ULONG, Flags: ULONG) -> BOOL | t.State: pass
def WakeConditionVariable(ConditionVariable: VOIDPTR) -> VOID | t.State: pass
def WakeAllConditionVariable(ConditionVariable: VOIDPTR) -> VOID | t.State: pass
INIT_ONCE_STATIC_INIT: t.CDefine = 0x00000001
INIT_ONCE_CHECK_ONLY: t.CDefine = 0x00000002
INIT_ONCE_ASYNC: t.CDefine = 0x00000004
INIT_ONCE_INIT_FAILED: t.CDefine = 0x00000008
class INIT_ONCE:
Ptr: t.CPtr
def InitOnceExecuteOnce(InitOnce: INIT_ONCE | t.CPtr, InitFn: VOIDPTR, Parameter: VOIDPTR, Context: VOIDPTR | t.CPtr) -> BOOL | t.State: pass
Whitespace-only changes.
-23
View File
@@ -1,23 +0,0 @@
"""
Auto-generated Python stub file from stdio.vp
Module: stdio
"""
import t, c
def printf(fmt: t.CConst | str, *args) -> int | t.State: pass
def fprintf(stream: bytes, fmt: t.CConst | str, *args) -> int | t.State: pass
def sprintf(buf: bytes, fmt: t.CConst | str, *args) -> int | t.State: pass
def snprintf(buf: bytes, size: t.CSizeT, fmt: t.CConst | str, *args) -> int | t.State: pass
def puts(s: t.CConst | str) -> int | t.State: pass
def fputs(s: t.CConst | str, stream: bytes) -> int | t.State: pass
def fgets(buf: bytes, size: int, stream: bytes) -> bytes | t.State: pass
def fflush(stream: bytes) -> int | t.State: pass
@@ -1 +0,0 @@
{}
-13
View File
@@ -1,13 +0,0 @@
"""
Auto-generated Python stub file from main.vp
Module: main
"""
from stdint import *
import w32.win32console
import t, c
from t import CInt, CExport
import mbuddytest
def main() -> CInt | CExport: pass
-86
View File
@@ -1,86 +0,0 @@
"""
Auto-generated Python stub file from w32.winsock2.vp
Module: w32.winsock2
"""
import t, c
from stdint import *
from w32.win32base import *
WINSOCK_VERSION: t.CDefine = 0x0202 # 2.2
AF_INET: t.CDefine = 2
AF_INET6: t.CDefine = 23
SOCK_STREAM: t.CDefine = 1 # TCP
SOCK_DGRAM: t.CDefine = 2 # UDP
SOCK_RAW: t.CDefine = 3 # 原始套接字
IPPROTO_TCP: t.CDefine = 6
IPPROTO_UDP: t.CDefine = 17
SOL_SOCKET: t.CDefine = 0xFFFF # WinSock2 值
SO_RCVTIMEO: t.CDefine = 0x1006 # WinSock2 值
SO_SNDTIMEO: t.CDefine = 0x1005 # WinSock2 值
SO_REUSEADDR: t.CDefine = 0x0004 # WinSock2 值
INADDR_ANY: t.CDefine = 0
SOCKET_ERROR: t.CDefine = -1
INVALID_SOCKET: t.CDefine = 0xFFFFFFFF # WinSock2: ~0
MSG_NOSIGNAL: t.CDefine = 0 # Windows 不支持,设为 0
SD_SEND: t.CDefine = 1
SD_RECV: t.CDefine = 0
SD_BOTH: t.CDefine = 2
class WSASocketAddr:
family: u16
port: u16
addr: u32
zero: u64
class WSAData:
wVersion: WORD
wHighVersion: WORD
szDescription: BYTE
szSystemStatus: BYTE
iMaxSockets: u16
iMaxUdpDg: u16
lpVendorInfo: CHARPTR
class WSAHostEnt:
h_name: CHARPTR
h_aliases: CHARPTR
h_addrtype: SHORT
h_length: SHORT
h_addr_list: CHARPTR
class WinTimeVal:
tv_sec: LONG
tv_usec: LONG
def WSAStartup(wVersionRequested: WORD, lpWSAData: WSAData | t.CPtr) -> INT | t.State: pass
def WSACleanup() -> INT | t.State: pass
def WSAGetLastError() -> INT | t.State: pass
def socket(family: INT, type: INT, protocol: INT) -> u64 | t.State: pass
def closesocket(s: u64) -> INT | t.State: pass
def connect(s: u64, name: WSASocketAddr | t.CPtr, namelen: INT) -> INT | t.State: pass
def send(s: u64, buf: t.CVoid | t.CPtr, len: INT, flags: INT) -> INT | t.State: pass
def recv(s: u64, buf: t.CVoid | t.CPtr, len: INT, flags: INT) -> INT | t.State: pass
def bind(s: u64, name: WSASocketAddr | t.CPtr, namelen: INT) -> INT | t.State: pass
def listen(s: u64, backlog: INT) -> INT | t.State: pass
def accept(s: u64, addr: WSASocketAddr | t.CPtr, addrlen: INT | t.CPtr) -> u64 | t.State: pass
def setsockopt(s: u64, level: INT, optname: INT, optval: t.CVoid | t.CPtr, optlen: INT) -> INT | t.State: pass
def shutdown(s: u64, how: INT) -> INT | t.State: pass
def gethostbyname(name: t.CChar | t.CConst | t.CPtr) -> WSAHostEnt | t.CPtr | t.State: pass
def ntohs(netshort: u16) -> u16 | t.State: pass
def htons(hostshort: u16) -> u16 | t.State: pass
def inet_addr(cp: t.CChar | t.CConst | t.CPtr) -> u32 | t.State: pass
@@ -1 +0,0 @@
f5522571bcce7bcb
-22
View File
@@ -1,22 +0,0 @@
"""
Auto-generated Python stub file from stdlib.vp
Module: stdlib
"""
import c
from stdint import *
import t
def malloc(size: t.CSizeT) -> t.CVoid | t.CPtr | t.State: pass
def calloc(nmemb: t.CSizeT, size: t.CSizeT) -> t.CVoid | t.CPtr | t.State: pass
def realloc(p: t.CVoid | t.CPtr, size: t.CSizeT) -> t.CVoid | t.CPtr | t.State: pass
def free(p: t.CVoid | t.CPtr) -> t.State: pass
def system(cmd: t.CConst | t.CChar | t.CPtr) -> INT | t.State: pass
def exit(status: int) -> t.State: pass
Whitespace-only changes.
-20
View File
@@ -1,20 +0,0 @@
"""
Auto-generated Python stub file from stdarg.vp
Module: stdarg
"""
import c
import t
def va_start(args: t.CPtr, last_arg: t.CPtr) -> t.State: pass
def va_arg(args: t.CPtr, type: t.CPtr) -> t.CPtr | t.State: pass
def va_end(args: t.CPtr) -> t.State | t.State: pass
va_list: t.CTypedef = t.CUnsignedChar | t.CPtr
def arg(type: t.CType) -> t.State: pass
-91
View File
@@ -1,91 +0,0 @@
"""
Auto-generated Python stub file from w32.win32memory.vp
Module: w32.win32memory
"""
import c
import t
from stdint import *
from w32.win32base import *
MEM_COMMIT: t.CDefine = 0x00001000
MEM_RESERVE: t.CDefine = 0x00002000
MEM_DECOMMIT: t.CDefine = 0x00004000
MEM_RELEASE: t.CDefine = 0x00008000
MEM_FREE: t.CDefine = 0x00010000
MEM_RESET: t.CDefine = 0x00080000
MEM_TOP_DOWN: t.CDefine = 0x00100000
MEM_WRITE_WATCH: t.CDefine = 0x00200000
MEM_PHYSICAL: t.CDefine = 0x00400000
MEM_LARGE_PAGES: t.CDefine = 0x20000000
PAGE_NOACCESS: t.CDefine = 0x01
PAGE_READONLY: t.CDefine = 0x02
PAGE_READWRITE: t.CDefine = 0x04
PAGE_WRITECOPY: t.CDefine = 0x08
PAGE_EXECUTE: t.CDefine = 0x10
PAGE_EXECUTE_READ: t.CDefine = 0x20
PAGE_EXECUTE_READWRITE: t.CDefine = 0x40
PAGE_EXECUTE_WRITECOPY: t.CDefine = 0x80
PAGE_GUARD: t.CDefine = 0x100
PAGE_NOCACHE: t.CDefine = 0x200
PAGE_WRITECOMBINE: t.CDefine = 0x400
HEAP_NO_SERIALIZE: t.CDefine = 0x00000001
HEAP_GROWABLE: t.CDefine = 0x00000002
HEAP_GENERATE_EXCEPTIONS: t.CDefine = 0x00000004
HEAP_ZERO_MEMORY: t.CDefine = 0x00000008
HEAP_REALLOC_IN_PLACE_ONLY: t.CDefine = 0x00000010
class MEMORY_BASIC_INFORMATION:
BaseAddress: VOIDPTR
AllocationBase: VOIDPTR
AllocationProtect: ULONG
RegionSize: t.CSizeT
State: ULONG
Protect: ULONG
Type: ULONG
def VirtualAlloc(lpAddress: VOIDPTR, dwSize: t.CSizeT, flAllocationType: ULONG, flProtect: ULONG) -> VOIDPTR | t.State: pass
def VirtualFree(lpAddress: VOIDPTR, dwSize: t.CSizeT, dwFreeType: ULONG) -> BOOL | t.State: pass
def VirtualProtect(lpAddress: VOIDPTR, dwSize: t.CSizeT, flNewProtect: ULONG, lpflOldProtect: ULONG | t.CPtr) -> BOOL | t.State: pass
def VirtualQuery(lpAddress: t.CConst | VOIDPTR, lpBuffer: MEMORY_BASIC_INFORMATION | t.CPtr, dwLength: t.CSizeT) -> t.CSizeT | t.State: pass
def VirtualLock(lpAddress: VOIDPTR, dwSize: t.CSizeT) -> BOOL | t.State: pass
def VirtualUnlock(lpAddress: VOIDPTR, dwSize: t.CSizeT) -> BOOL | t.State: pass
def GetProcessHeap() -> HANDLE | t.State: pass
def HeapCreate(flOptions: ULONG, dwInitialSize: t.CSizeT, dwMaximumSize: t.CSizeT) -> HANDLE | t.State: pass
def HeapDestroy(hHeap: HANDLE) -> BOOL | t.State: pass
def HeapAlloc(hHeap: HANDLE, dwFlags: ULONG, dwBytes: t.CSizeT) -> VOIDPTR | t.State: pass
def HeapReAlloc(hHeap: HANDLE, dwFlags: ULONG, lpMem: VOIDPTR, dwBytes: t.CSizeT) -> VOIDPTR | t.State: pass
def HeapFree(hHeap: HANDLE, dwFlags: ULONG, lpMem: VOIDPTR) -> BOOL | t.State: pass
def HeapSize(hHeap: HANDLE, dwFlags: ULONG, lpMem: t.CConst | VOIDPTR) -> t.CSizeT | t.State: pass
def HeapValidate(hHeap: HANDLE, dwFlags: ULONG, lpMem: t.CConst | VOIDPTR) -> BOOL | t.State: pass
def HeapCompact(hHeap: HANDLE, dwFlags: ULONG) -> t.CSizeT | t.State: pass
def GlobalAlloc(uFlags: UINT, dwBytes: t.CSizeT) -> VOIDPTR | t.State: pass
def GlobalFree(hMem: VOIDPTR) -> VOIDPTR | t.State: pass
def GlobalLock(hMem: VOIDPTR) -> VOIDPTR | t.State: pass
def GlobalUnlock(hMem: VOIDPTR) -> BOOL | t.State: pass
def GlobalSize(hMem: VOIDPTR) -> t.CSizeT | t.State: pass
def LocalAlloc(uFlags: UINT, dwBytes: t.CSizeT) -> VOIDPTR | t.State: pass
def LocalFree(hMem: VOIDPTR) -> VOIDPTR | t.State: pass
@@ -1 +0,0 @@
285b6aa29a34754d|bbdf3bbd4c3bc28c|f5522571bcce7bcb|fc980acec33d69a7
-31
View File
@@ -1,31 +0,0 @@
"""
Auto-generated Python stub file from testcheck.vp
Module: testcheck
"""
import t, c
import stdio
from w32.win32console import SetConsoleOutputCP, SetConsoleCP
CP_UTF8: t.CDefine = 65001
_pass_count: t.CExtern | t.CInt
_fail_count: t.CExtern | t.CInt
_total_pass: t.CExtern | t.CInt
_total_fail: t.CExtern | t.CInt
def begin(name: str) -> t.CInt: pass
def section(name: str) -> t.CInt: pass
def ok(msg: str) -> t.CInt: pass
def fail(msg: str) -> t.CInt: pass
def check(cond: t.CInt, ok_msg: str, fail_msg: str) -> t.CInt: pass
def info(msg: str) -> t.CInt: pass
def end() -> t.CInt: pass
def summary() -> t.CInt: pass
@@ -1 +0,0 @@
{"d:\\Users\\TermiNexus\\Desktop\\TransPyC\\Test\\BuddyTest\\App\\main.vp": {"sha1": "5e430ae5bf7af3a2", "mtime": 1782224154.785576, "size": 260}, "d:\\Users\\TermiNexus\\Desktop\\TransPyC\\Test\\BuddyTest\\App\\mbuddytest.vp": {"sha1": "490084d59cf67c44", "mtime": 1786381983.7502325, "size": 19771}, "d:\\Users\\TermiNexus\\Desktop\\TransPyC\\includes\\atom.vp": {"sha1": "aa246c6e6aa30484", "mtime": 1785389628.701967, "size": 1198}, "d:\\Users\\TermiNexus\\Desktop\\TransPyC\\includes\\memhub.vp": {"sha1": "2408ce147bac090b", "mtime": 1786323167.9697752, "size": 33121}, "d:\\Users\\TermiNexus\\Desktop\\TransPyC\\includes\\stdarg.vp": {"sha1": "71e0a3ffcb3ebfad", "mtime": 1781258888.113146, "size": 277}, "d:\\Users\\TermiNexus\\Desktop\\TransPyC\\includes\\stdint.vp": {"sha1": "f5522571bcce7bcb", "mtime": 1785563642.3805652, "size": 4356}, "d:\\Users\\TermiNexus\\Desktop\\TransPyC\\includes\\stdio.vp": {"sha1": "285b6aa29a34754d", "mtime": 1785332415.1829746, "size": 561}, "d:\\Users\\TermiNexus\\Desktop\\TransPyC\\includes\\stdlib.vp": {"sha1": "6c658cc728d0bbf4", "mtime": 1785750602.5446548, "size": 413}, "d:\\Users\\TermiNexus\\Desktop\\TransPyC\\includes\\string.vp": {"sha1": "4c39369ffedaddac", "mtime": 1786188859.6154988, "size": 12277}, "d:\\Users\\TermiNexus\\Desktop\\TransPyC\\includes\\testcheck.vp": {"sha1": "748d0424e8976fa0", "mtime": 1785332415.20287, "size": 1919}, "d:\\Users\\TermiNexus\\Desktop\\TransPyC\\includes\\viperio.vp": {"sha1": "2c175afd85852faf", "mtime": 1786320035.0415876, "size": 1685}, "d:\\Users\\TermiNexus\\Desktop\\TransPyC\\includes\\viperlib.vp": {"sha1": "bba983c61a970f7c", "mtime": 1786320034.4835327, "size": 59458}, "d:\\Users\\TermiNexus\\Desktop\\TransPyC\\includes\\w32\\win32base.vp": {"sha1": "fc980acec33d69a7", "mtime": 1785332415.2228394, "size": 2653}, "d:\\Users\\TermiNexus\\Desktop\\TransPyC\\includes\\w32\\win32console.vp": {"sha1": "bbdf3bbd4c3bc28c", "mtime": 1781200703.5338137, "size": 5604}, "d:\\Users\\TermiNexus\\Desktop\\TransPyC\\includes\\w32\\win32process.vp": {"sha1": "067c78e9f121dce3", "mtime": 1781200703.5409546, "size": 4802}, "d:\\Users\\TermiNexus\\Desktop\\TransPyC\\includes\\w32\\win32sync.vp": {"sha1": "06f53cc594b4ac6c", "mtime": 1782297500.2581685, "size": 4726}}
-16
View File
@@ -1,16 +0,0 @@
067c78e9f121dce3:includes/w32\win32process.vp
06f53cc594b4ac6c:includes/w32\win32sync.vp
2408ce147bac090b:includes/memhub.vp
285b6aa29a34754d:includes/stdio.vp
2c175afd85852faf:includes/viperio.vp
490084d59cf67c44:mbuddytest.vp
4c39369ffedaddac:includes/string.vp
5e430ae5bf7af3a2:main.vp
6c658cc728d0bbf4:includes/stdlib.vp
71e0a3ffcb3ebfad:includes/stdarg.vp
748d0424e8976fa0:includes/testcheck.vp
aa246c6e6aa30484:includes/atom.vp
bba983c61a970f7c:includes/viperlib.vp
bbdf3bbd4c3bc28c:includes/w32\win32console.vp
f5522571bcce7bcb:includes/stdint.vp
fc980acec33d69a7:includes/w32\win32base.vp
Binary file not shown.
Whitespace-only changes.
-26
View File
@@ -1,26 +0,0 @@
"""
Auto-generated Python stub file from atom.vp
Module: atom
"""
import t, c
ATOMIC_RELAXED: t.CDefine = 0
ATOMIC_CONSUME: t.CDefine = 1
ATOMIC_ACQUIRE: t.CDefine = 2
ATOMIC_RELEASE: t.CDefine = 3
ATOMIC_ACQ_REL: t.CDefine = 4
ATOMIC_SEQ_CST: t.CDefine = 5
def __atomic_test_and_set(ptr: t.CUInt64T | t.CPtr, order: t.CInt) -> t.CBool: pass
def __atomic_clear(ptr: t.CUInt64T | t.CPtr, order: t.CInt) -> t.CVoid: pass
def __atomic_thread_fence(order: t.CInt) -> t.CVoid: pass
def __atomic_signal_fence(order: t.CInt) -> t.CVoid: pass
def __atomic_always_lock_free(size: t.CSizeT, ptr: t.CVoid | t.CPtr) -> t.CBool: pass
def __atomic_is_lock_free(size: t.CSizeT, ptr: t.CVoid | t.CPtr) -> t.CBool: pass
@@ -1 +0,0 @@
f5522571bcce7bcb|fc980acec33d69a7
-138
View File
@@ -1,138 +0,0 @@
"""
Auto-generated Python stub file from w32.win32console.vp
Module: w32.win32console
"""
import c
import t
from stdint import *
from w32.win32base import *
ENABLE_PROCESSED_INPUT: t.CDefine = 0x0001
ENABLE_LINE_INPUT: t.CDefine = 0x0002
ENABLE_ECHO_INPUT: t.CDefine = 0x0004
ENABLE_WINDOW_INPUT: t.CDefine = 0x0008
ENABLE_MOUSE_INPUT: t.CDefine = 0x0010
ENABLE_INSERT_MODE: t.CDefine = 0x0020
ENABLE_QUICK_EDIT_MODE: t.CDefine = 0x0040
ENABLE_EXTENDED_FLAGS: t.CDefine = 0x0080
ENABLE_PROCESSED_OUTPUT: t.CDefine = 0x0001
ENABLE_WRAP_AT_EOL_OUTPUT: t.CDefine = 0x0002
ENABLE_VIRTUAL_TERMINAL_PROCESSING: t.CDefine = 0x0004
DISABLE_NEWLINE_AUTO_RETURN: t.CDefine = 0x0008
ENABLE_LVB_GRID_WORLDWIDE: t.CDefine = 0x0010
FOREGROUND_BLUE: t.CDefine = 0x0001
FOREGROUND_GREEN: t.CDefine = 0x0002
FOREGROUND_RED: t.CDefine = 0x0004
FOREGROUND_INTENSITY: t.CDefine = 0x0008
BACKGROUND_BLUE: t.CDefine = 0x0010
BACKGROUND_GREEN: t.CDefine = 0x0020
BACKGROUND_RED: t.CDefine = 0x0040
BACKGROUND_INTENSITY: t.CDefine = 0x0080
KEY_EVENT: t.CDefine = 0x0001
MOUSE_EVENT: t.CDefine = 0x0002
WINDOW_BUFFER_SIZE_EVENT: t.CDefine = 0x0004
MENU_EVENT: t.CDefine = 0x0008
FOCUS_EVENT: t.CDefine = 0x0010
class COORD:
X: SHORT
Y: SHORT
class SMALL_RECT:
Left: SHORT
Top: SHORT
Right: SHORT
Bottom: SHORT
class CONSOLE_SCREEN_BUFFER_INFO:
dwSize: COORD
dwCursorPosition: COORD
wAttributes: WORD
srWindow: SMALL_RECT
dwMaximumWindowSize: COORD
class CONSOLE_CURSOR_INFO:
dwSize: ULONG
bVisible: BOOL
class CHAR_INFO:
UnicodeChar: WCHAR
Attributes: WORD
class KEY_EVENT_RECORD:
bKeyDown: BOOL
wRepeatCount: WORD
wVirtualKeyCode: WORD
wVirtualScanCode: WORD
uChar: WCHAR
dwControlKeyState: ULONG
class MOUSE_EVENT_RECORD:
dwMousePosition: COORD
dwButtonState: ULONG
dwControlKeyState: ULONG
dwEventFlags: ULONG
class WINDOW_BUFFER_SIZE_RECORD:
dwSize: COORD
class INPUT_RECORD:
EventType: WORD
Event: KEY_EVENT_RECORD
def SetConsoleOutputCP(codepage: UINT) -> BOOL | t.State: pass
def SetConsoleCP(codepage: UINT) -> BOOL | t.State: pass
def GetConsoleCP() -> UINT | t.State: pass
def GetConsoleOutputCP() -> UINT | t.State: pass
def GetConsoleScreenBufferInfo(hConsoleOutput: HANDLE, lpConsoleScreenBufferInfo: CONSOLE_SCREEN_BUFFER_INFO | t.CPtr) -> BOOL | t.State: pass
def SetConsoleScreenBufferSize(hConsoleOutput: HANDLE, dwSize: COORD) -> BOOL | t.State: pass
def SetConsoleCursorPosition(hConsoleOutput: HANDLE, dwCursorPosition: COORD) -> BOOL | t.State: pass
def GetConsoleCursorInfo(hConsoleOutput: HANDLE, lpConsoleCursorInfo: CONSOLE_CURSOR_INFO | t.CPtr) -> BOOL | t.State: pass
def SetConsoleCursorInfo(hConsoleOutput: HANDLE, lpConsoleCursorInfo: CONSOLE_CURSOR_INFO | t.CPtr) -> BOOL | t.State: pass
def SetConsoleTextAttribute(hConsoleOutput: HANDLE, wAttributes: WORD) -> BOOL | t.State: pass
def FillConsoleOutputCharacterA(hConsoleOutput: HANDLE, cCharacter: t.CChar, nLength: ULONG, dwWriteCoord: COORD, lpNumberOfCharsWritten: ULONG | t.CPtr) -> BOOL | t.State: pass
def FillConsoleOutputCharacterW(hConsoleOutput: HANDLE, cCharacter: WCHAR, nLength: ULONG, dwWriteCoord: COORD, lpNumberOfCharsWritten: ULONG | t.CPtr) -> BOOL | t.State: pass
def FillConsoleOutputAttribute(hConsoleOutput: HANDLE, wAttribute: WORD, nLength: ULONG, dwWriteCoord: COORD, lpNumberOfAttrsWritten: ULONG | t.CPtr) -> BOOL | t.State: pass
def WriteConsoleA(hConsoleOutput: HANDLE, lpBuffer: t.CConst | VOIDPTR, nNumberOfCharsToWrite: ULONG, lpNumberOfCharsWritten: ULONG | t.CPtr, lpReserved: VOIDPTR) -> BOOL | t.State: pass
def WriteConsoleW(hConsoleOutput: HANDLE, lpBuffer: t.CConst | VOIDPTR, nNumberOfCharsToWrite: ULONG, lpNumberOfCharsWritten: ULONG | t.CPtr, lpReserved: VOIDPTR) -> BOOL | t.State: pass
def ReadConsoleA(hConsoleInput: HANDLE, lpBuffer: VOIDPTR, nNumberOfCharsToRead: ULONG, lpNumberOfCharsRead: ULONG | t.CPtr, pInputControl: VOIDPTR) -> BOOL | t.State: pass
def ReadConsoleW(hConsoleInput: HANDLE, lpBuffer: VOIDPTR, nNumberOfCharsToRead: ULONG, lpNumberOfCharsRead: ULONG | t.CPtr, pInputControl: VOIDPTR) -> BOOL | t.State: pass
def GetConsoleMode(hConsoleHandle: HANDLE, lpMode: ULONG | t.CPtr) -> BOOL | t.State: pass
def SetConsoleMode(hConsoleHandle: HANDLE, dwMode: ULONG) -> BOOL | t.State: pass
def ReadConsoleInputA(hConsoleInput: HANDLE, lpBuffer: INPUT_RECORD | t.CPtr, nLength: ULONG, lpNumberOfEventsRead: ULONG | t.CPtr) -> BOOL | t.State: pass
def ReadConsoleInputW(hConsoleInput: HANDLE, lpBuffer: INPUT_RECORD | t.CPtr, nLength: ULONG, lpNumberOfEventsRead: ULONG | t.CPtr) -> BOOL | t.State: pass
def GetNumberOfConsoleInputEvents(hConsoleInput: HANDLE, lpNumberOfEvents: ULONG | t.CPtr) -> BOOL | t.State: pass
def FlushConsoleInputBuffer(hConsoleInput: HANDLE) -> BOOL | t.State: pass
def SetConsoleTitleA(lpConsoleTitle: LPCSTR) -> BOOL | t.State: pass
def SetConsoleTitleW(lpConsoleTitle: LPCWSTR) -> BOOL | t.State: pass
def GetConsoleTitleA(lpConsoleTitle: CHARPTR, nSize: ULONG) -> ULONG | t.State: pass
def GetConsoleTitleW(lpConsoleTitle: WCHARPTR, nSize: ULONG) -> ULONG | t.State: pass
def AllocConsole() -> BOOL | t.State: pass
def FreeConsole() -> BOOL | t.State: pass
def SetConsoleWindowInfo(hConsoleOutput: HANDLE, bAbsolute: BOOL, lpConsoleWindow: SMALL_RECT | t.CPtr) -> BOOL | t.State: pass
def ScrollConsoleScreenBufferA(hConsoleOutput: HANDLE, lpScrollRectangle: SMALL_RECT | t.CPtr, lpClipRectangle: SMALL_RECT | t.CPtr, dwDestinationOrigin: COORD, lpFill: CHAR_INFO | t.CPtr) -> BOOL | t.State: pass
-81
View File
@@ -1,81 +0,0 @@
"""
Auto-generated Python stub file from w32.fileio.vp
Module: w32.fileio
"""
import t, c
from stdint import *
import stdio
import w32.win32base
import w32.win32file
class MODE(t.CEnum):
R = 0
W = 1
A = 2
RP = 3
WP = 4
AP = 5
X = 6
XP = 7
class FRESULT(t.CEnum):
OK = 0
ERR = -1
ERR_CLOSED = -2
ERR_PERM = -3
ERR_IO = -4
ERR_NOTFOUND = -5
SEEK_SET: t.CDefine = 0
SEEK_CUR: t.CDefine = 1
SEEK_END: t.CDefine = 2
INVALID_SET_FILE_POINTER: t.CDefine = -1
SHARE_READ: t.CDefine = 0x00000001
SHARE_WRITE: t.CDefine = 0x00000002
SHARE_DELETE: t.CDefine = 0x00000004
class File:
handle: w32.win32base.HANDLE
closed: bool
can_read: bool
can_write: bool
is_append: bool
_share_mode: ULONG
def __init__(self: File, filename: str, mode: ULONG, share: ULONG = SHARE_READ) -> t.CInt: pass
def __enter__(self: File) -> 'File' | t.CPtr: pass
def __exit__(self: File) -> t.CInt: pass
def read(self: File, buf: bytes, count: ULONG) -> LONG: pass
def write(self: File, buf: bytes, count: ULONG) -> LONG: pass
def write_str(self: File, s: str) -> LONG: pass
def seek(self: File, offset: LONG, origin: ULONG) -> LONG: pass
def tell(self: File) -> LONG: pass
def close(self: File) -> LONG: pass
def flush(self: File) -> LONG: pass
def size(self: File) -> LONGLONG: pass
def readline(self: File, buf: bytes, max_count: ULONG) -> LONG: pass
def read_all(self: File, buf: bytes, max_count: ULONG) -> LONG: pass
class FileW:
handle: w32.win32base.HANDLE
closed: bool
can_read: bool
can_write: bool
is_append: bool
_share_mode: ULONG
def __init__(self: FileW, filename: w32.win32base.LPCWSTR, mode: ULONG, share: ULONG = SHARE_READ) -> t.CInt: pass
def __enter__(self: FileW) -> 'FileW' | t.CPtr: pass
def __exit__(self: FileW) -> t.CInt: pass
def read(self: FileW, buf: bytes, count: ULONG) -> LONG: pass
def write(self: FileW, buf: bytes, count: ULONG) -> LONG: pass
def write_str(self: FileW, s: str) -> LONG: pass
def seek(self: FileW, offset: LONG, origin: ULONG) -> LONG: pass
def tell(self: FileW) -> LONG: pass
def close(self: FileW) -> LONG: pass
def flush(self: FileW) -> LONG: pass
def size(self: FileW) -> LONGLONG: pass
def readline(self: FileW, buf: bytes, max_count: ULONG) -> LONG: pass
def read_all(self: FileW, buf: bytes, max_count: ULONG) -> LONG: pass
def open(filename: str, mode: ULONG, share: ULONG = SHARE_READ) -> File | t.CPtr: pass
def openw(filename: w32.win32base.LPCWSTR, mode: ULONG, share: ULONG = SHARE_READ) -> FileW | t.CPtr: pass
Whitespace-only changes.
-100
View File
@@ -1,100 +0,0 @@
"""
Auto-generated Python stub file from stdint.vp
Module: stdint
"""
import c
import t
INT: t.CTypedef = t.CInt
INTPTR: t.CTypedef = t.CInt | t.CPtr
BOOL: t.CTypedef = t.CInt
UINT: t.CTypedef = t.CUnsignedInt
UINTPTR: t.CTypedef = UINT | t.CPtr
BYTE: t.CTypedef = t.CUnsignedChar
BYTEPTR: t.CTypedef = BYTE | t.CPtr
WORD: t.CTypedef = t.CUInt16T
DWORD: t.CTypedef = t.CUInt32T
QWORD: t.CTypedef = t.CUInt64T
TCHAR: t.CTypedef = t.CChar
CHARLIST: t.CTypedef = str | t.CPtr
VOID: t.CTypedef = t.CVoid
SHORT: t.CTypedef = t.CShort
SHORTPTR: t.CTypedef = t.CShort | t.CPtr
USHORT: t.CTypedef = t.CUnsignedShort
USHORTPTR: t.CTypedef = t.CUnsignedShort | t.CPtr
LONGLONG: t.CTypedef = t.CLongLong
ULONGLONG: t.CTypedef = t.CUnsignedLongLong
LONG: t.CTypedef = t.CLong
ULONG: t.CTypedef = t.CUnsignedLong
WCHAR: t.CTypedef = WORD
WCHARPTR: t.CTypedef = WORD | t.CPtr
CHARPTR: t.CTypedef = t.CChar | t.CPtr
FSIZE_t: t.CTypedef = DWORD
LBA_t: t.CTypedef = DWORD
VOIDPTR: t.CTypedef = t.CVoid | t.CPtr
FLOAT: t.CTypedef = t.CFloat
DOUBLE: t.CTypedef = t.CDouble
FLOAT8: t.CTypedef = t.CFloat8T
FLOAT16: t.CTypedef = t.CFloat16T
FLOAT32: t.CTypedef = t.CFloat32T
FLOAT64: t.CTypedef = t.CFloat64T
FLOAT128: t.CTypedef = t.CFloat128T
INT8: t.CTypedef = t.CInt8T
INT16: t.CTypedef = t.CInt16T
INT32: t.CTypedef = t.CInt32T
INT64: t.CTypedef = t.CInt64T
UINT8: t.CTypedef = t.CUInt8T
UINT16: t.CTypedef = t.CUInt16T
UINT32: t.CTypedef = t.CUInt32T
UINT64: t.CTypedef = t.CUInt64T
INT8PTR: t.CTypedef = t.CInt8T | t.CPtr
INT16PTR: t.CTypedef = t.CInt16T | t.CPtr
INT32PTR: t.CTypedef = t.CInt32T | t.CPtr
INT64PTR: t.CTypedef = t.CInt64T | t.CPtr
UINT8PTR: t.CTypedef = t.CUInt8T | t.CPtr
UINT16PTR: t.CTypedef = t.CUInt16T | t.CPtr
UINT32PTR: t.CTypedef = t.CUInt32T | t.CPtr
UINT64PTR: t.CTypedef = t.CUInt64T | t.CPtr
CHAR8: t.CTypedef = t.CChar8T
CHAR16: t.CTypedef = t.CChar16T
CHAR32: t.CTypedef = t.CChar32T
CHAR8PTR: t.CTypedef = t.CChar8T | t.CPtr
CHAR16PTR: t.CTypedef = t.CChar16T | t.CPtr
CHAR32PTR: t.CTypedef = t.CChar32T | t.CPtr
i8: t.CTypedef = t.CInt8T
i16: t.CTypedef = t.CInt16T
i32: t.CTypedef = t.CInt32T
i64: t.CTypedef = t.CInt64T
u8: t.CTypedef = t.CUInt8T
u16: t.CTypedef = t.CUInt16T
u32: t.CTypedef = t.CUInt32T
u64: t.CTypedef = t.CUInt64T
SIZE_T: t.CTypedef = t.CSizeT
SSIZE_T: t.CTypedef = t.CPtrDiffT
PTRDIFF_T: t.CTypedef = t.CPtrDiffT
int8_t: t.CTypedef = t.CInt8T
int16_t: t.CTypedef = t.CInt16T
int32_t: t.CTypedef = t.CInt32T
int64_t: t.CTypedef = t.CInt64T
uint8_t: t.CTypedef = t.CUInt8T
uint16_t: t.CTypedef = t.CUInt16T
uint32_t: t.CTypedef = t.CUInt32T
uint64_t: t.CTypedef = t.CUInt64T
size_t: t.CTypedef = t.CSizeT
ssize_t: t.CTypedef = t.CPtrDiffT
ptrdiff_t: t.CTypedef = t.CPtrDiffT
intptr_t: t.CTypedef = t.CIntPtrT
uintptr_t: t.CTypedef = t.CUIntPtrT
wchar_t: t.CTypedef = t.CWCharT
char8_t: t.CTypedef = t.CChar8T
char16_t: t.CTypedef = t.CChar16T
char32_t: t.CTypedef = t.CChar32T
float8_t: t.CTypedef = t.CFloat8T
float16_t: t.CTypedef = t.CFloat16T
float32_t: t.CTypedef = t.CFloat32T
float64_t: t.CTypedef = t.CFloat64T
float128_t: t.CTypedef = t.CFloat128T
_Bool: t.CTypedef = t.CBool
-192
View File
@@ -1,192 +0,0 @@
"""
Auto-generated Python stub file from w32.win32file.vp
Module: w32.win32file
"""
import c
import t
from stdint import *
from w32.win32base import *
GENERIC_READ: t.CDefine = 0x80000000
GENERIC_WRITE: t.CDefine = 0x40000000
GENERIC_EXECUTE: t.CDefine = 0x20000000
GENERIC_ALL: t.CDefine = 0x10000000
FILE_SHARE_READ: t.CDefine = 0x00000001
FILE_SHARE_WRITE: t.CDefine = 0x00000002
FILE_SHARE_DELETE: t.CDefine = 0x00000004
CREATE_NEW: t.CDefine = 1
CREATE_ALWAYS: t.CDefine = 2
OPEN_EXISTING: t.CDefine = 3
OPEN_ALWAYS: t.CDefine = 4
TRUNCATE_EXISTING: t.CDefine = 5
FILE_ATTRIBUTE_READONLY: t.CDefine = 0x00000001
FILE_ATTRIBUTE_HIDDEN: t.CDefine = 0x00000002
FILE_ATTRIBUTE_SYSTEM: t.CDefine = 0x00000004
FILE_ATTRIBUTE_DIRECTORY: t.CDefine = 0x00000010
FILE_ATTRIBUTE_ARCHIVE: t.CDefine = 0x00000020
FILE_ATTRIBUTE_NORMAL: t.CDefine = 0x00000080
FILE_ATTRIBUTE_TEMPORARY: t.CDefine = 0x00000100
FILE_ATTRIBUTE_COMPRESSED: t.CDefine = 0x00000800
FILE_ATTRIBUTE_OFFLINE: t.CDefine = 0x00001000
FILE_ATTRIBUTE_ENCRYPTED: t.CDefine = 0x00004000
FILE_FLAG_WRITE_THROUGH: t.CDefine = 0x80000000
FILE_FLAG_OVERLAPPED: t.CDefine = 0x40000000
FILE_FLAG_NO_BUFFERING: t.CDefine = 0x20000000
FILE_FLAG_RANDOM_ACCESS: t.CDefine = 0x10000000
FILE_FLAG_SEQUENTIAL_SCAN: t.CDefine = 0x08000000
FILE_FLAG_DELETE_ON_CLOSE: t.CDefine = 0x04000000
FILE_FLAG_BACKUP_SEMANTICS: t.CDefine = 0x02000000
FILE_FLAG_POSIX_SEMANTICS: t.CDefine = 0x01000000
FILE_BEGIN: t.CDefine = 0
FILE_CURRENT: t.CDefine = 1
FILE_END: t.CDefine = 2
STD_INPUT_HANDLE: t.CDefine = t.CUnsignedLong(-10)
STD_OUTPUT_HANDLE: t.CDefine = t.CUnsignedLong(-11)
STD_ERROR_HANDLE: t.CDefine = t.CUnsignedLong(-12)
MOVEFILE_REPLACE_EXISTING: t.CDefine = 0x00000001
MOVEFILE_COPY_ALLOWED: t.CDefine = 0x00000002
MOVEFILE_WRITE_THROUGH: t.CDefine = 0x00000008
class BY_HANDLE_FILE_INFORMATION:
dwFileAttributes: ULONG
ftCreationTime: FILETIME
ftLastAccessTime: FILETIME
ftLastWriteTime: FILETIME
dwVolumeSerialNumber: ULONG
nFileSizeHigh: ULONG
nFileSizeLow: ULONG
nNumberOfLinks: ULONG
nFileIndexHigh: ULONG
nFileIndexLow: ULONG
class WIN32_FIND_DATAA:
dwFileAttributes: ULONG
ftCreationTime: FILETIME
ftLastAccessTime: FILETIME
ftLastWriteTime: FILETIME
nFileSizeHigh: ULONG
nFileSizeLow: ULONG
dwReserved0: ULONG
dwReserved1: ULONG
cFileName: t.CArray[t.CChar, 260]
cAlternateFileName: t.CArray[t.CChar, 14]
class WIN32_FIND_DATAW:
dwFileAttributes: ULONG
ftCreationTime: FILETIME
ftLastAccessTime: FILETIME
ftLastWriteTime: FILETIME
nFileSizeHigh: ULONG
nFileSizeLow: ULONG
dwReserved0: ULONG
dwReserved1: ULONG
cFileName: t.CArray[t.CUInt16T, 260]
cAlternateFileName: t.CArray[t.CUInt16T, 14]
def CreateFileA(lpFileName: LPCSTR, dwDesiredAccess: ULONG, dwShareMode: ULONG, lpSecurityAttributes: SECURITY_ATTRIBUTES | t.CPtr, dwCreationDisposition: ULONG, dwFlagsAndAttributes: ULONG, hTemplateFile: HANDLE) -> HANDLE | t.State: pass
def CreateFileW(lpFileName: LPCWSTR, dwDesiredAccess: ULONG, dwShareMode: ULONG, lpSecurityAttributes: SECURITY_ATTRIBUTES | t.CPtr, dwCreationDisposition: ULONG, dwFlagsAndAttributes: ULONG, hTemplateFile: HANDLE) -> HANDLE | t.State: pass
def ReadFile(hFile: HANDLE, lpBuffer: VOIDPTR, nNumberOfBytesToRead: ULONG, lpNumberOfBytesRead: ULONG | t.CPtr, lpOverlapped: OVERLAPPED | t.CPtr) -> BOOL | t.State: pass
def WriteFile(hFile: HANDLE, lpBuffer: t.CConst | VOIDPTR, nNumberOfBytesToWrite: ULONG, lpNumberOfBytesWritten: ULONG | t.CPtr, lpOverlapped: OVERLAPPED | t.CPtr) -> BOOL | t.State: pass
def SetFilePointer(hFile: HANDLE, lDistanceToMove: LONG, lpDistanceToMoveHigh: LONG | t.CPtr, dwMoveMethod: ULONG) -> LONG | t.State: pass
def SetFilePointerEx(hFile: HANDLE, liDistanceToMove: LARGE_INTEGER | t.CPtr, lpNewFilePointer: LARGE_INTEGER | t.CPtr, dwMoveMethod: ULONG) -> BOOL | t.State: pass
def GetFileSize(hFile: HANDLE, lpFileSizeHigh: ULONG | t.CPtr) -> ULONG | t.State: pass
def GetFileSizeEx(hFile: HANDLE, lpFileSize: LARGE_INTEGER | t.CPtr) -> BOOL | t.State: pass
def SetEndOfFile(hFile: HANDLE) -> BOOL | t.State: pass
def FlushFileBuffers(hFile: HANDLE) -> BOOL | t.State: pass
def GetFileType(hFile: HANDLE) -> ULONG | t.State: pass
def GetFileAttributesA(lpFileName: LPCSTR) -> ULONG | t.State: pass
def GetFileAttributesW(lpFileName: LPCWSTR) -> ULONG | t.State: pass
def SetFileAttributesA(lpFileName: LPCSTR, dwFileAttributes: ULONG) -> BOOL | t.State: pass
def SetFileAttributesW(lpFileName: LPCWSTR, dwFileAttributes: ULONG) -> BOOL | t.State: pass
def DeleteFileA(lpFileName: LPCSTR) -> BOOL | t.State: pass
def DeleteFileW(lpFileName: LPCWSTR) -> BOOL | t.State: pass
def MoveFileA(lpExistingFileName: LPCSTR, lpNewFileName: LPCSTR) -> BOOL | t.State: pass
def MoveFileW(lpExistingFileName: LPCWSTR, lpNewFileName: LPCWSTR) -> BOOL | t.State: pass
def MoveFileExA(lpExistingFileName: LPCSTR, lpNewFileName: LPCSTR, dwFlags: ULONG) -> BOOL | t.State: pass
def MoveFileExW(lpExistingFileName: LPCWSTR, lpNewFileName: LPCWSTR, dwFlags: ULONG) -> BOOL | t.State: pass
def CopyFileA(lpExistingFileName: LPCSTR, lpNewFileName: LPCSTR, bFailIfExists: BOOL) -> BOOL | t.State: pass
def CopyFileW(lpExistingFileName: LPCWSTR, lpNewFileName: LPCWSTR, bFailIfExists: BOOL) -> BOOL | t.State: pass
def CreateDirectoryA(lpPathName: LPCSTR, lpSecurityAttributes: SECURITY_ATTRIBUTES | t.CPtr) -> BOOL | t.State: pass
def CreateDirectoryW(lpPathName: LPCWSTR, lpSecurityAttributes: SECURITY_ATTRIBUTES | t.CPtr) -> BOOL | t.State: pass
def RemoveDirectoryA(lpPathName: LPCSTR) -> BOOL | t.State: pass
def RemoveDirectoryW(lpPathName: LPCWSTR) -> BOOL | t.State: pass
def FindFirstFileA(lpFileName: LPCSTR, lpFindFileData: WIN32_FIND_DATAA | t.CPtr) -> HANDLE | t.State: pass
def FindFirstFileW(lpFileName: LPCWSTR, lpFindFileData: WIN32_FIND_DATAW | t.CPtr) -> HANDLE | t.State: pass
def FindNextFileA(hFindFile: HANDLE, lpFindFileData: WIN32_FIND_DATAA | t.CPtr) -> BOOL | t.State: pass
def FindNextFileW(hFindFile: HANDLE, lpFindFileData: WIN32_FIND_DATAW | t.CPtr) -> BOOL | t.State: pass
def FindClose(hFindFile: HANDLE) -> BOOL | t.State: pass
def GetStdHandle(nStdHandle: ULONG) -> HANDLE | t.State: pass
def SetStdHandle(nStdHandle: ULONG, hHandle: HANDLE) -> BOOL | t.State: pass
def GetFileInformationByHandle(hFile: HANDLE, lpFileInformation: BY_HANDLE_FILE_INFORMATION | t.CPtr) -> BOOL | t.State: pass
def LockFile(hFile: HANDLE, dwFileOffsetLow: ULONG, dwFileOffsetHigh: ULONG, nNumberOfBytesToLockLow: ULONG, nNumberOfBytesToLockHigh: ULONG) -> BOOL | t.State: pass
def UnlockFile(hFile: HANDLE, dwFileOffsetLow: ULONG, dwFileOffsetHigh: ULONG, nNumberOfBytesToUnlockLow: ULONG, nNumberOfBytesToUnlockHigh: ULONG) -> BOOL | t.State: pass
def GetTempPathA(nBufferLength: ULONG, lpBuffer: CHARPTR) -> ULONG | t.State: pass
def GetTempPathW(nBufferLength: ULONG, lpBuffer: WCHARPTR) -> ULONG | t.State: pass
def GetTempFileNameA(lpPathName: LPCSTR, lpPrefixString: LPCSTR, uUnique: UINT, lpTempFileName: CHARPTR) -> UINT | t.State: pass
def GetTempFileNameW(lpPathName: LPCWSTR, lpPrefixString: LPCWSTR, uUnique: UINT, lpTempFileName: WCHARPTR) -> UINT | t.State: pass
def GetCurrentDirectoryA(nBufferLength: ULONG, lpBuffer: CHARPTR) -> ULONG | t.State: pass
def GetCurrentDirectoryW(nBufferLength: ULONG, lpBuffer: WCHARPTR) -> ULONG | t.State: pass
def SetCurrentDirectoryA(lpPathName: LPCSTR) -> BOOL | t.State: pass
def SetCurrentDirectoryW(lpPathName: LPCWSTR) -> BOOL | t.State: pass
def GetModuleFileNameA(hModule: HANDLE, lpFilename: CHARPTR, nSize: ULONG) -> ULONG | t.State: pass
def GetModuleFileNameW(hModule: HANDLE, lpFilename: WCHARPTR, nSize: ULONG) -> ULONG | t.State: pass
HANDLE_FLAG_INHERIT: t.CDefine = 0x00000001
HANDLE_FLAG_PROTECT_FROM_CLOSE: t.CDefine = 0x00000002
def CreatePipe(hReadPipe: HANDLE | t.CPtr, hWritePipe: HANDLE | t.CPtr, lpPipeAttributes: SECURITY_ATTRIBUTES | t.CPtr, nSize: ULONG) -> BOOL | t.State: pass
def SetHandleInformation(hObject: HANDLE, dwMask: ULONG, dwFlags: ULONG) -> BOOL | t.State: pass
def DuplicateHandle(hSourceProcessHandle: HANDLE, hSourceHandle: HANDLE, hTargetProcessHandle: HANDLE, lpTargetHandle: HANDLE | t.CPtr, dwDesiredAccess: ULONG, bInheritHandle: BOOL, dwOptions: ULONG) -> BOOL | t.State: pass
DUPLICATE_SAME_ACCESS: t.CDefine = 0x00000002
@@ -1 +0,0 @@
f5522571bcce7bcb
-100
View File
@@ -1,100 +0,0 @@
"""
Auto-generated Python stub file from w32.win32base.vp
Module: w32.win32base
"""
import c
import t
from stdint import *
HANDLE: t.CTypedef = VOIDPTR
LPCSTR: t.CTypedef = t.CConst | t.CChar | t.CPtr
LPCWSTR: t.CTypedef = t.CConst | t.CUnsignedShort | t.CPtr
INVALID_HANDLE_VALUE: t.CDefine = -1
NULL: t.CDefine = 0
TRUE: t.CDefine = 1
FALSE: t.CDefine = 0
INFINITE: t.CDefine = 0xFFFFFFFF
WAIT_FAILED: t.CDefine = 0xFFFFFFFF
WAIT_OBJECT_0: t.CDefine = 0
WAIT_TIMEOUT: t.CDefine = 258
WAIT_ABANDONED: t.CDefine = 0x80
MAX_PATH: t.CDefine = 260
ERROR_SUCCESS: t.CDefine = 0
ERROR_FILE_NOT_FOUND: t.CDefine = 2
ERROR_ACCESS_DENIED: t.CDefine = 5
ERROR_INSUFFICIENT_BUFFER: t.CDefine = 122
class SECURITY_ATTRIBUTES:
nLength: ULONG
lpSecurityDescriptor: VOIDPTR
bInheritHandle: BOOL
class OVERLAPPED:
Internal: ULONGLONG
InternalHigh: ULONGLONG
Offset: ULONG
OffsetHigh: ULONG
hEvent: HANDLE
class FILETIME:
dwLowDateTime: DWORD
dwHighDateTime: DWORD
class SYSTEMTIME:
wYear: WORD
wMonth: WORD
wDayOfWeek: WORD
wDay: WORD
wHour: WORD
wMinute: WORD
wSecond: WORD
wMilliseconds: WORD
class GUID:
Data1: DWORD
Data2: WORD
Data3: WORD
Data4: BYTEPTR
class LARGE_INTEGER:
QuadPart: LONGLONG
class ULARGE_INTEGER:
QuadPart: ULONGLONG
def GetLastError() -> ULONG | t.State: pass
def SetLastError(dwErrCode: ULONG) -> t.State: pass
def CloseHandle(hObject: HANDLE) -> BOOL | t.State: pass
def GetProcAddress(hModule: HANDLE, lpProcName: LPCSTR) -> VOIDPTR | t.State: pass
def GetModuleHandleA(lpModuleName: LPCSTR) -> HANDLE | t.State: pass
def GetModuleHandleW(lpModuleName: LPCWSTR) -> HANDLE | t.State: pass
def LoadLibraryA(lpLibFileName: LPCSTR) -> HANDLE | t.State: pass
def LoadLibraryW(lpLibFileName: LPCWSTR) -> HANDLE | t.State: pass
def FreeLibrary(hLibModule: HANDLE) -> BOOL | t.State: pass
def GetSystemTime(lpSystemTime: SYSTEMTIME | t.CPtr) -> t.State: pass
def GetLocalTime(lpSystemTime: SYSTEMTIME | t.CPtr) -> t.State: pass
def FileTimeToSystemTime(lpFileTime: FILETIME | t.CPtr, lpSystemTime: SYSTEMTIME | t.CPtr) -> BOOL | t.State: pass
def SystemTimeToFileTime(lpSystemTime: SYSTEMTIME | t.CPtr, lpFileTime: FILETIME | t.CPtr) -> BOOL | t.State: pass
def QueryPerformanceCounter(lpPerformanceCount: LARGE_INTEGER | t.CPtr) -> BOOL | t.State: pass
def QueryPerformanceFrequency(lpFrequency: LARGE_INTEGER | t.CPtr) -> BOOL | t.State: pass
def Sleep(dwMilliseconds: ULONG) -> t.State: pass
def SleepEx(dwMilliseconds: ULONG, bAlertable: BOOL) -> ULONG | t.State: pass
def GetTickCount() -> ULONG | t.State: pass
def GetTickCount64() -> ULONGLONG | t.State: pass
def GetCommandLineA() -> CHARPTR | t.State: pass
-268
View File
@@ -1,268 +0,0 @@
import t
from stdint import *
from stdio import printf
from stdlib import malloc
import testcheck
# ============================================================
# 测试 1:@property getter
# ============================================================
class Rect:
width: t.CInt
height: t.CInt
def __new__(self, w: t.CInt, h: t.CInt) -> 'Rect' | t.CPtr:
return t.CPtr(malloc(Rect.__sizeof__()))
def __init__(self, w: t.CInt, h: t.CInt):
self.width = w
self.height = h
@property
def area(self) -> t.CInt:
return self.width * self.height
@property
def is_square(self) -> bool:
return self.width == self.height
def test_property_getter():
testcheck.section("@property getter")
r1: Rect = Rect(3, 4)
testcheck.check(r1.area == 12, "area == 12", "area expect 12")
testcheck.check(not r1.is_square, "not square", "should not be square")
r2: Rect = Rect(5, 5)
testcheck.check(r2.area == 25, "square area == 25", "square area expect 25")
testcheck.check(r2.is_square, "is_square", "should be square")
# ============================================================
# 测试 2:@property.setter
# ============================================================
class Temperature:
_celsius: t.CDouble
def __new__(self, celsius_val: t.CDouble) -> 'Temperature' | t.CPtr:
return t.CPtr(malloc(Temperature.__sizeof__()))
def __init__(self, celsius_val: t.CDouble):
self._celsius = celsius_val
@property
def celsius(self) -> t.CDouble:
return self._celsius
@celsius.setter
def celsius(self, val: t.CDouble):
self._celsius = val
@property
def fahrenheit(self) -> t.CDouble:
return self._celsius * 1.8 + 32.0
def test_property_setter():
testcheck.section("@property.setter")
tmp1: Temperature = Temperature(0.0)
testcheck.check(tmp1.fahrenheit > 31.9 and tmp1.fahrenheit < 32.1, "0C == 32F", "0C expect 32F")
tmp1.celsius = 100.0
testcheck.check(tmp1.fahrenheit > 211.9 and tmp1.fahrenheit < 212.1, "100C == 212F", "100C expect 212F")
testcheck.check(tmp1.celsius > 99.9 and tmp1.celsius < 100.1, "celsius == 100", "celsius expect 100")
# ============================================================
# 测试 3:@property.getter(重新定义 getter)
# ============================================================
class Counter:
_count: t.CInt
def __new__(self) -> 'Counter' | t.CPtr:
return t.CPtr(malloc(Counter.__sizeof__()))
def __init__(self):
self._count = 0
@property
def value(self) -> t.CInt:
return self._count
@value.setter
def value(self, v: t.CInt):
self._count = v
def test_property_getter_redef():
testcheck.section("@property.getter redef")
cnt: Counter = Counter()
testcheck.check(cnt.value == 0, "init == 0", "init expect 0")
cnt.value = 42
testcheck.check(cnt.value == 42, "set == 42", "set expect 42")
# ============================================================
# 测试 4:@property.deleter
# ============================================================
class Config:
_value: t.CInt
_deleted: t.CInt
def __new__(self, v: t.CInt) -> 'Config' | t.CPtr:
return t.CPtr(malloc(Config.__sizeof__()))
def __init__(self, v: t.CInt):
self._value = v
self._deleted = 0
@property
def value(self) -> t.CInt:
return self._value
@value.setter
def value(self, v: t.CInt):
self._value = v
@value.deleter
def value(self):
self._value = 0
self._deleted = 1
def is_deleted(self) -> bool:
return self._deleted != 0
def test_property_deleter():
testcheck.section("@property.deleter")
cfg: Config = Config(99)
testcheck.check(cfg.value == 99, "init == 99", "init expect 99")
testcheck.check(not cfg.is_deleted(), "not deleted", "should not be deleted")
del cfg.value
testcheck.check(cfg.value == 0, "after del == 0", "after del expect 0")
testcheck.check(cfg.is_deleted(), "is_deleted", "should be deleted")
# ============================================================
# 测试 5:@staticmethod
# ============================================================
class MathUtils:
@staticmethod
def add(a: t.CInt, b: t.CInt) -> t.CInt:
return a + b
@staticmethod
def max_val(a: t.CInt, b: t.CInt) -> t.CInt:
return a if a > b else b
def test_staticmethod():
testcheck.section("@staticmethod")
# 通过类名调用
testcheck.check(MathUtils.add(3, 4) == 7, "MathUtils.add(3,4)==7", "MathUtils.add(3,4) expect 7")
testcheck.check(MathUtils.max_val(5, 10) == 10, "MathUtils.max(5,10)==10", "MathUtils.max(5,10) expect 10")
# ============================================================
# 测试 6:@classmethod
# ============================================================
class Point:
x: t.CDouble
y: t.CDouble
def __new__(self, x: t.CDouble, y: t.CDouble) -> 'Point' | t.CPtr:
return t.CPtr(malloc(Point.__sizeof__()))
def __init__(self, x: t.CDouble, y: t.CDouble):
self.x = x
self.y = y
@classmethod
def origin(cls: Point) -> Point:
return Point(0.0, 0.0)
@classmethod
def from_int(cls: Point, x: t.CInt, y: t.CInt) -> Point:
return Point(x * 1.0, y * 1.0)
def dist_sq(self) -> t.CDouble:
return self.x * self.x + self.y * self.y
def test_classmethod():
testcheck.section("@classmethod")
# 通过类名调用
p1: Point = Point.origin()
testcheck.check(p1.x > -0.01 and p1.x < 0.01, "origin.x ~= 0", "origin.x expect ~0")
testcheck.check(p1.y > -0.01 and p1.y < 0.01, "origin.y ~= 0", "origin.y expect ~0")
testcheck.check(p1.dist_sq() < 0.01, "origin.dist ~= 0", "origin.dist expect ~0")
p2: Point = Point.from_int(3, 4)
testcheck.check(p2.x > 2.99 and p2.x < 3.01, "from_int(3,4).x ~= 3", "from_int(3,4).x expect ~3")
testcheck.check(p2.y > 3.99 and p2.y < 4.01, "from_int(3,4).y ~= 4", "from_int(3,4).y expect ~4")
testcheck.check(p2.dist_sq() > 24.99 and p2.dist_sq() < 25.01, "dist_sq ~= 25", "dist_sq expect ~25")
# ============================================================
# 测试 7:综合测试 — @property + @staticmethod + @classmethod
# ============================================================
class Circle:
_radius: t.CDouble
def __new__(self, r: t.CDouble) -> 'Circle' | t.CPtr:
return t.CPtr(malloc(Circle.__sizeof__()))
def __init__(self, r: t.CDouble):
self._radius = r
@property
def radius(self) -> t.CDouble:
return self._radius
@radius.setter
def radius(self, val: t.CDouble):
self._radius = val
@property
def area(self) -> t.CDouble:
return 3.14159265 * self._radius * self._radius
@staticmethod
def is_unit(r: t.CDouble) -> bool:
return r > 0.99 and r < 1.01
@classmethod
def unit(cls: Circle) -> Circle:
return Circle(1.0)
def test_combined():
testcheck.section("Combined @property + @staticmethod + @classmethod")
# 先测试直接构造
cr0: Circle = Circle(1.0)
testcheck.check(cr0.radius > 0.99 and cr0.radius < 1.01, "direct radius ~= 1", "direct radius expect ~1")
testcheck.check(cr0.area > 3.14 and cr0.area < 3.15, "direct area ~= pi", "direct area expect ~pi")
cr0.radius = 2.0
testcheck.check(cr0.radius > 1.99 and cr0.radius < 2.01, "direct radius 2.0", "direct radius expect 2.0")
testcheck.check(cr0.area > 12.56 and cr0.area < 12.58, "direct area ~= 4pi", "direct area expect ~4pi")
# 测试 classmethod
cr1: Circle = Circle.unit()
testcheck.check(cr1.radius > 0.99 and cr1.radius < 1.01, "unit radius ~= 1", "unit radius expect ~1")
testcheck.check(Circle.is_unit(1.0), "is_unit(1.0)", "is_unit(1.0) should be true")
testcheck.check(not Circle.is_unit(2.0), "not is_unit(2.0)", "is_unit(2.0) should be false")
# ============================================================
# 主函数
# ============================================================
def main() -> t.CInt | t.CExport:
testcheck.begin("Builtin Decorator Test")
test_property_getter()
test_property_setter()
test_property_getter_redef()
test_property_deleter()
test_staticmethod()
test_classmethod()
test_combined()
return testcheck.end()
@@ -1 +0,0 @@
{"stdio": "285b6aa29a34754d", "stdlib": "6c658cc728d0bbf4", "testcheck": "748d0424e8976fa0", "w32.win32console": "bbdf3bbd4c3bc28c", "win32console": "bbdf3bbd4c3bc28c", "stdint": "f5522571bcce7bcb", "w32.win32base": "fc980acec33d69a7", "win32base": "fc980acec33d69a7"}
-39
View File
@@ -1,39 +0,0 @@
{
"name": "BuiltinDecoratorTest",
"version": "1.0.0",
"source_dir": "./App",
"build_dir": "./.tpv_build",
"compiler": {
"cmd": "llc",
"flags": [
"-filetype=obj",
"-relocation-model=pic"
]
},
"linker": {
"cmd": "clang++",
"flags": [
"-Wl,--allow-multiple-definition",
"-lmsvcrt",
"-lucrt",
"-lpthread",
"-lmingwex",
"-lkernel32",
"-luser32"
],
"output": "BuiltinDecoratorTest.exe"
},
"includes": [
"../../includes"
],
"target": {
"triple": "x86_64-pc-windows-gnu",
"datalayout": "e-m:w-p270:32:32-p271:32:32-p272:64:64-i64:64-f80:128-n8:16:32:64-S128"
},
"options": {
"slice_level": 3,
"sha1_slice_level": 1,
"target": "llvm",
"strict_mode": true
}
}
Whitespace-only changes.
@@ -1,23 +0,0 @@
"""
Auto-generated Python stub file from stdio.vp
Module: stdio
"""
import t, c
def printf(fmt: t.CConst | str, *args) -> int | t.State: pass
def fprintf(stream: bytes, fmt: t.CConst | str, *args) -> int | t.State: pass
def sprintf(buf: bytes, fmt: t.CConst | str, *args) -> int | t.State: pass
def snprintf(buf: bytes, size: t.CSizeT, fmt: t.CConst | str, *args) -> int | t.State: pass
def puts(s: t.CConst | str) -> int | t.State: pass
def fputs(s: t.CConst | str, stream: bytes) -> int | t.State: pass
def fgets(buf: bytes, size: int, stream: bytes) -> bytes | t.State: pass
def fflush(stream: bytes) -> int | t.State: pass
@@ -1 +0,0 @@
f5522571bcce7bcb
@@ -1,22 +0,0 @@
"""
Auto-generated Python stub file from stdlib.vp
Module: stdlib
"""
import c
from stdint import *
import t
def malloc(size: t.CSizeT) -> t.CVoid | t.CPtr | t.State: pass
def calloc(nmemb: t.CSizeT, size: t.CSizeT) -> t.CVoid | t.CPtr | t.State: pass
def realloc(p: t.CVoid | t.CPtr, size: t.CSizeT) -> t.CVoid | t.CPtr | t.State: pass
def free(p: t.CVoid | t.CPtr) -> t.State: pass
def system(cmd: t.CConst | t.CChar | t.CPtr) -> INT | t.State: pass
def exit(status: int) -> t.State: pass
@@ -1 +0,0 @@
285b6aa29a34754d|bbdf3bbd4c3bc28c|f5522571bcce7bcb|fc980acec33d69a7
@@ -1,31 +0,0 @@
"""
Auto-generated Python stub file from testcheck.vp
Module: testcheck
"""
import t, c
import stdio
from w32.win32console import SetConsoleOutputCP, SetConsoleCP
CP_UTF8: t.CDefine = 65001
_pass_count: t.CExtern | t.CInt
_fail_count: t.CExtern | t.CInt
_total_pass: t.CExtern | t.CInt
_total_fail: t.CExtern | t.CInt
def begin(name: str) -> t.CInt: pass
def section(name: str) -> t.CInt: pass
def ok(msg: str) -> t.CInt: pass
def fail(msg: str) -> t.CInt: pass
def check(cond: t.CInt, ok_msg: str, fail_msg: str) -> t.CInt: pass
def info(msg: str) -> t.CInt: pass
def end() -> t.CInt: pass
def summary() -> t.CInt: pass
@@ -1 +0,0 @@
{"d:\\Users\\TermiNexus\\Desktop\\TransPyC\\Test\\BuiltinDecoratorTest\\App\\main.vp": {"sha1": "e3ac223bdaf94a0c", "mtime": 1782110312.4550886, "size": 8488}, "d:\\Users\\TermiNexus\\Desktop\\TransPyC\\includes\\stdint.vp": {"sha1": "f5522571bcce7bcb", "mtime": 1785563642.3805652, "size": 4356}, "d:\\Users\\TermiNexus\\Desktop\\TransPyC\\includes\\stdio.vp": {"sha1": "285b6aa29a34754d", "mtime": 1785332415.1829746, "size": 561}, "d:\\Users\\TermiNexus\\Desktop\\TransPyC\\includes\\stdlib.vp": {"sha1": "6c658cc728d0bbf4", "mtime": 1785750602.5446548, "size": 413}, "d:\\Users\\TermiNexus\\Desktop\\TransPyC\\includes\\testcheck.vp": {"sha1": "748d0424e8976fa0", "mtime": 1785332415.20287, "size": 1919}, "d:\\Users\\TermiNexus\\Desktop\\TransPyC\\includes\\w32\\win32base.vp": {"sha1": "fc980acec33d69a7", "mtime": 1785332415.2228394, "size": 2653}, "d:\\Users\\TermiNexus\\Desktop\\TransPyC\\includes\\w32\\win32console.vp": {"sha1": "bbdf3bbd4c3bc28c", "mtime": 1781200703.5338137, "size": 5604}}
@@ -1,7 +0,0 @@
285b6aa29a34754d:includes/stdio.vp
6c658cc728d0bbf4:includes/stdlib.vp
748d0424e8976fa0:includes/testcheck.vp
bbdf3bbd4c3bc28c:includes/w32\win32console.vp
e3ac223bdaf94a0c:main.vp
f5522571bcce7bcb:includes/stdint.vp
fc980acec33d69a7:includes/w32\win32base.vp
@@ -1 +0,0 @@
f5522571bcce7bcb|fc980acec33d69a7
@@ -1,138 +0,0 @@
"""
Auto-generated Python stub file from w32.win32console.vp
Module: w32.win32console
"""
import c
import t
from stdint import *
from w32.win32base import *
ENABLE_PROCESSED_INPUT: t.CDefine = 0x0001
ENABLE_LINE_INPUT: t.CDefine = 0x0002
ENABLE_ECHO_INPUT: t.CDefine = 0x0004
ENABLE_WINDOW_INPUT: t.CDefine = 0x0008
ENABLE_MOUSE_INPUT: t.CDefine = 0x0010
ENABLE_INSERT_MODE: t.CDefine = 0x0020
ENABLE_QUICK_EDIT_MODE: t.CDefine = 0x0040
ENABLE_EXTENDED_FLAGS: t.CDefine = 0x0080
ENABLE_PROCESSED_OUTPUT: t.CDefine = 0x0001
ENABLE_WRAP_AT_EOL_OUTPUT: t.CDefine = 0x0002
ENABLE_VIRTUAL_TERMINAL_PROCESSING: t.CDefine = 0x0004
DISABLE_NEWLINE_AUTO_RETURN: t.CDefine = 0x0008
ENABLE_LVB_GRID_WORLDWIDE: t.CDefine = 0x0010
FOREGROUND_BLUE: t.CDefine = 0x0001
FOREGROUND_GREEN: t.CDefine = 0x0002
FOREGROUND_RED: t.CDefine = 0x0004
FOREGROUND_INTENSITY: t.CDefine = 0x0008
BACKGROUND_BLUE: t.CDefine = 0x0010
BACKGROUND_GREEN: t.CDefine = 0x0020
BACKGROUND_RED: t.CDefine = 0x0040
BACKGROUND_INTENSITY: t.CDefine = 0x0080
KEY_EVENT: t.CDefine = 0x0001
MOUSE_EVENT: t.CDefine = 0x0002
WINDOW_BUFFER_SIZE_EVENT: t.CDefine = 0x0004
MENU_EVENT: t.CDefine = 0x0008
FOCUS_EVENT: t.CDefine = 0x0010
class COORD:
X: SHORT
Y: SHORT
class SMALL_RECT:
Left: SHORT
Top: SHORT
Right: SHORT
Bottom: SHORT
class CONSOLE_SCREEN_BUFFER_INFO:
dwSize: COORD
dwCursorPosition: COORD
wAttributes: WORD
srWindow: SMALL_RECT
dwMaximumWindowSize: COORD
class CONSOLE_CURSOR_INFO:
dwSize: ULONG
bVisible: BOOL
class CHAR_INFO:
UnicodeChar: WCHAR
Attributes: WORD
class KEY_EVENT_RECORD:
bKeyDown: BOOL
wRepeatCount: WORD
wVirtualKeyCode: WORD
wVirtualScanCode: WORD
uChar: WCHAR
dwControlKeyState: ULONG
class MOUSE_EVENT_RECORD:
dwMousePosition: COORD
dwButtonState: ULONG
dwControlKeyState: ULONG
dwEventFlags: ULONG
class WINDOW_BUFFER_SIZE_RECORD:
dwSize: COORD
class INPUT_RECORD:
EventType: WORD
Event: KEY_EVENT_RECORD
def SetConsoleOutputCP(codepage: UINT) -> BOOL | t.State: pass
def SetConsoleCP(codepage: UINT) -> BOOL | t.State: pass
def GetConsoleCP() -> UINT | t.State: pass
def GetConsoleOutputCP() -> UINT | t.State: pass
def GetConsoleScreenBufferInfo(hConsoleOutput: HANDLE, lpConsoleScreenBufferInfo: CONSOLE_SCREEN_BUFFER_INFO | t.CPtr) -> BOOL | t.State: pass
def SetConsoleScreenBufferSize(hConsoleOutput: HANDLE, dwSize: COORD) -> BOOL | t.State: pass
def SetConsoleCursorPosition(hConsoleOutput: HANDLE, dwCursorPosition: COORD) -> BOOL | t.State: pass
def GetConsoleCursorInfo(hConsoleOutput: HANDLE, lpConsoleCursorInfo: CONSOLE_CURSOR_INFO | t.CPtr) -> BOOL | t.State: pass
def SetConsoleCursorInfo(hConsoleOutput: HANDLE, lpConsoleCursorInfo: CONSOLE_CURSOR_INFO | t.CPtr) -> BOOL | t.State: pass
def SetConsoleTextAttribute(hConsoleOutput: HANDLE, wAttributes: WORD) -> BOOL | t.State: pass
def FillConsoleOutputCharacterA(hConsoleOutput: HANDLE, cCharacter: t.CChar, nLength: ULONG, dwWriteCoord: COORD, lpNumberOfCharsWritten: ULONG | t.CPtr) -> BOOL | t.State: pass
def FillConsoleOutputCharacterW(hConsoleOutput: HANDLE, cCharacter: WCHAR, nLength: ULONG, dwWriteCoord: COORD, lpNumberOfCharsWritten: ULONG | t.CPtr) -> BOOL | t.State: pass
def FillConsoleOutputAttribute(hConsoleOutput: HANDLE, wAttribute: WORD, nLength: ULONG, dwWriteCoord: COORD, lpNumberOfAttrsWritten: ULONG | t.CPtr) -> BOOL | t.State: pass
def WriteConsoleA(hConsoleOutput: HANDLE, lpBuffer: t.CConst | VOIDPTR, nNumberOfCharsToWrite: ULONG, lpNumberOfCharsWritten: ULONG | t.CPtr, lpReserved: VOIDPTR) -> BOOL | t.State: pass
def WriteConsoleW(hConsoleOutput: HANDLE, lpBuffer: t.CConst | VOIDPTR, nNumberOfCharsToWrite: ULONG, lpNumberOfCharsWritten: ULONG | t.CPtr, lpReserved: VOIDPTR) -> BOOL | t.State: pass
def ReadConsoleA(hConsoleInput: HANDLE, lpBuffer: VOIDPTR, nNumberOfCharsToRead: ULONG, lpNumberOfCharsRead: ULONG | t.CPtr, pInputControl: VOIDPTR) -> BOOL | t.State: pass
def ReadConsoleW(hConsoleInput: HANDLE, lpBuffer: VOIDPTR, nNumberOfCharsToRead: ULONG, lpNumberOfCharsRead: ULONG | t.CPtr, pInputControl: VOIDPTR) -> BOOL | t.State: pass
def GetConsoleMode(hConsoleHandle: HANDLE, lpMode: ULONG | t.CPtr) -> BOOL | t.State: pass
def SetConsoleMode(hConsoleHandle: HANDLE, dwMode: ULONG) -> BOOL | t.State: pass
def ReadConsoleInputA(hConsoleInput: HANDLE, lpBuffer: INPUT_RECORD | t.CPtr, nLength: ULONG, lpNumberOfEventsRead: ULONG | t.CPtr) -> BOOL | t.State: pass
def ReadConsoleInputW(hConsoleInput: HANDLE, lpBuffer: INPUT_RECORD | t.CPtr, nLength: ULONG, lpNumberOfEventsRead: ULONG | t.CPtr) -> BOOL | t.State: pass
def GetNumberOfConsoleInputEvents(hConsoleInput: HANDLE, lpNumberOfEvents: ULONG | t.CPtr) -> BOOL | t.State: pass
def FlushConsoleInputBuffer(hConsoleInput: HANDLE) -> BOOL | t.State: pass
def SetConsoleTitleA(lpConsoleTitle: LPCSTR) -> BOOL | t.State: pass
def SetConsoleTitleW(lpConsoleTitle: LPCWSTR) -> BOOL | t.State: pass
def GetConsoleTitleA(lpConsoleTitle: CHARPTR, nSize: ULONG) -> ULONG | t.State: pass
def GetConsoleTitleW(lpConsoleTitle: WCHARPTR, nSize: ULONG) -> ULONG | t.State: pass
def AllocConsole() -> BOOL | t.State: pass
def FreeConsole() -> BOOL | t.State: pass
def SetConsoleWindowInfo(hConsoleOutput: HANDLE, bAbsolute: BOOL, lpConsoleWindow: SMALL_RECT | t.CPtr) -> BOOL | t.State: pass
def ScrollConsoleScreenBufferA(hConsoleOutput: HANDLE, lpScrollRectangle: SMALL_RECT | t.CPtr, lpClipRectangle: SMALL_RECT | t.CPtr, dwDestinationOrigin: COORD, lpFill: CHAR_INFO | t.CPtr) -> BOOL | t.State: pass
@@ -1 +0,0 @@
{}
@@ -1,110 +0,0 @@
"""
Auto-generated Python stub file from main.vp
Module: main
"""
import c
import t
from stdint import *
from stdio import printf
from stdlib import malloc
import testcheck
class Rect:
width: t.CInt
height: t.CInt
def __new__(self: Rect, w: t.CInt, h: t.CInt) -> 'Rect' | t.CPtr: pass
def __init__(self: Rect, w: t.CInt, h: t.CInt) -> t.CInt: pass
@property
def area(self: Rect) -> t.CInt: pass
@property
def is_square(self: Rect) -> bool: pass
def test_property_getter() -> t.CInt: pass
class Temperature:
_celsius: t.CDouble
def __new__(self: Temperature, celsius_val: t.CDouble) -> 'Temperature' | t.CPtr: pass
def __init__(self: Temperature, celsius_val: t.CDouble) -> t.CInt: pass
@property
def celsius(self: Temperature) -> t.CDouble: pass
@celsius.setter
def celsius(self: Temperature, val: t.CDouble) -> t.CInt: pass
@property
def fahrenheit(self: Temperature) -> t.CDouble: pass
def test_property_setter() -> t.CInt: pass
class Counter:
_count: t.CInt
def __new__(self: Counter) -> 'Counter' | t.CPtr: pass
def __init__(self: Counter) -> t.CInt: pass
@property
def value(self: Counter) -> t.CInt: pass
@value.setter
def value(self: Counter, v: t.CInt) -> t.CInt: pass
def test_property_getter_redef() -> t.CInt: pass
class Config:
_value: t.CInt
_deleted: t.CInt
def __new__(self: Config, v: t.CInt) -> 'Config' | t.CPtr: pass
def __init__(self: Config, v: t.CInt) -> t.CInt: pass
@property
def value(self: Config) -> t.CInt: pass
@value.setter
def value(self: Config, v: t.CInt) -> t.CInt: pass
@value.deleter
def value(self: Config) -> t.CInt: pass
def is_deleted(self: Config) -> bool: pass
def test_property_deleter() -> t.CInt: pass
class MathUtils:
@staticmethod
def add(a: t.CInt, b: t.CInt) -> t.CInt: pass
@staticmethod
def max_val(a: t.CInt, b: t.CInt) -> t.CInt: pass
def test_staticmethod() -> t.CInt: pass
class Point:
x: t.CDouble
y: t.CDouble
def __new__(self: Point, x: t.CDouble, y: t.CDouble) -> 'Point' | t.CPtr: pass
def __init__(self: Point, x: t.CDouble, y: t.CDouble) -> t.CInt: pass
@classmethod
def origin(cls: Point) -> Point: pass
@classmethod
def from_int(cls: Point, x: t.CInt, y: t.CInt) -> Point: pass
def dist_sq(self: Point) -> t.CDouble: pass
def test_classmethod() -> t.CInt: pass
class Circle:
_radius: t.CDouble
def __new__(self: Circle, r: t.CDouble) -> 'Circle' | t.CPtr: pass
def __init__(self: Circle, r: t.CDouble) -> t.CInt: pass
@property
def radius(self: Circle) -> t.CDouble: pass
@radius.setter
def radius(self: Circle, val: t.CDouble) -> t.CInt: pass
@property
def area(self: Circle) -> t.CDouble: pass
@staticmethod
def is_unit(r: t.CDouble) -> bool: pass
@classmethod
def unit(cls: Circle) -> Circle: pass
def test_combined() -> t.CInt: pass
def main() -> t.CInt | t.CExport: pass
Whitespace-only changes.
@@ -1,100 +0,0 @@
"""
Auto-generated Python stub file from stdint.vp
Module: stdint
"""
import c
import t
INT: t.CTypedef = t.CInt
INTPTR: t.CTypedef = t.CInt | t.CPtr
BOOL: t.CTypedef = t.CInt
UINT: t.CTypedef = t.CUnsignedInt
UINTPTR: t.CTypedef = UINT | t.CPtr
BYTE: t.CTypedef = t.CUnsignedChar
BYTEPTR: t.CTypedef = BYTE | t.CPtr
WORD: t.CTypedef = t.CUInt16T
DWORD: t.CTypedef = t.CUInt32T
QWORD: t.CTypedef = t.CUInt64T
TCHAR: t.CTypedef = t.CChar
CHARLIST: t.CTypedef = str | t.CPtr
VOID: t.CTypedef = t.CVoid
SHORT: t.CTypedef = t.CShort
SHORTPTR: t.CTypedef = t.CShort | t.CPtr
USHORT: t.CTypedef = t.CUnsignedShort
USHORTPTR: t.CTypedef = t.CUnsignedShort | t.CPtr
LONGLONG: t.CTypedef = t.CLongLong
ULONGLONG: t.CTypedef = t.CUnsignedLongLong
LONG: t.CTypedef = t.CLong
ULONG: t.CTypedef = t.CUnsignedLong
WCHAR: t.CTypedef = WORD
WCHARPTR: t.CTypedef = WORD | t.CPtr
CHARPTR: t.CTypedef = t.CChar | t.CPtr
FSIZE_t: t.CTypedef = DWORD
LBA_t: t.CTypedef = DWORD
VOIDPTR: t.CTypedef = t.CVoid | t.CPtr
FLOAT: t.CTypedef = t.CFloat
DOUBLE: t.CTypedef = t.CDouble
FLOAT8: t.CTypedef = t.CFloat8T
FLOAT16: t.CTypedef = t.CFloat16T
FLOAT32: t.CTypedef = t.CFloat32T
FLOAT64: t.CTypedef = t.CFloat64T
FLOAT128: t.CTypedef = t.CFloat128T
INT8: t.CTypedef = t.CInt8T
INT16: t.CTypedef = t.CInt16T
INT32: t.CTypedef = t.CInt32T
INT64: t.CTypedef = t.CInt64T
UINT8: t.CTypedef = t.CUInt8T
UINT16: t.CTypedef = t.CUInt16T
UINT32: t.CTypedef = t.CUInt32T
UINT64: t.CTypedef = t.CUInt64T
INT8PTR: t.CTypedef = t.CInt8T | t.CPtr
INT16PTR: t.CTypedef = t.CInt16T | t.CPtr
INT32PTR: t.CTypedef = t.CInt32T | t.CPtr
INT64PTR: t.CTypedef = t.CInt64T | t.CPtr
UINT8PTR: t.CTypedef = t.CUInt8T | t.CPtr
UINT16PTR: t.CTypedef = t.CUInt16T | t.CPtr
UINT32PTR: t.CTypedef = t.CUInt32T | t.CPtr
UINT64PTR: t.CTypedef = t.CUInt64T | t.CPtr
CHAR8: t.CTypedef = t.CChar8T
CHAR16: t.CTypedef = t.CChar16T
CHAR32: t.CTypedef = t.CChar32T
CHAR8PTR: t.CTypedef = t.CChar8T | t.CPtr
CHAR16PTR: t.CTypedef = t.CChar16T | t.CPtr
CHAR32PTR: t.CTypedef = t.CChar32T | t.CPtr
i8: t.CTypedef = t.CInt8T
i16: t.CTypedef = t.CInt16T
i32: t.CTypedef = t.CInt32T
i64: t.CTypedef = t.CInt64T
u8: t.CTypedef = t.CUInt8T
u16: t.CTypedef = t.CUInt16T
u32: t.CTypedef = t.CUInt32T
u64: t.CTypedef = t.CUInt64T
SIZE_T: t.CTypedef = t.CSizeT
SSIZE_T: t.CTypedef = t.CPtrDiffT
PTRDIFF_T: t.CTypedef = t.CPtrDiffT
int8_t: t.CTypedef = t.CInt8T
int16_t: t.CTypedef = t.CInt16T
int32_t: t.CTypedef = t.CInt32T
int64_t: t.CTypedef = t.CInt64T
uint8_t: t.CTypedef = t.CUInt8T
uint16_t: t.CTypedef = t.CUInt16T
uint32_t: t.CTypedef = t.CUInt32T
uint64_t: t.CTypedef = t.CUInt64T
size_t: t.CTypedef = t.CSizeT
ssize_t: t.CTypedef = t.CPtrDiffT
ptrdiff_t: t.CTypedef = t.CPtrDiffT
intptr_t: t.CTypedef = t.CIntPtrT
uintptr_t: t.CTypedef = t.CUIntPtrT
wchar_t: t.CTypedef = t.CWCharT
char8_t: t.CTypedef = t.CChar8T
char16_t: t.CTypedef = t.CChar16T
char32_t: t.CTypedef = t.CChar32T
float8_t: t.CTypedef = t.CFloat8T
float16_t: t.CTypedef = t.CFloat16T
float32_t: t.CTypedef = t.CFloat32T
float64_t: t.CTypedef = t.CFloat64T
float128_t: t.CTypedef = t.CFloat128T
_Bool: t.CTypedef = t.CBool
@@ -1 +0,0 @@
f5522571bcce7bcb
@@ -1,100 +0,0 @@
"""
Auto-generated Python stub file from w32.win32base.vp
Module: w32.win32base
"""
import c
import t
from stdint import *
HANDLE: t.CTypedef = VOIDPTR
LPCSTR: t.CTypedef = t.CConst | t.CChar | t.CPtr
LPCWSTR: t.CTypedef = t.CConst | t.CUnsignedShort | t.CPtr
INVALID_HANDLE_VALUE: t.CDefine = -1
NULL: t.CDefine = 0
TRUE: t.CDefine = 1
FALSE: t.CDefine = 0
INFINITE: t.CDefine = 0xFFFFFFFF
WAIT_FAILED: t.CDefine = 0xFFFFFFFF
WAIT_OBJECT_0: t.CDefine = 0
WAIT_TIMEOUT: t.CDefine = 258
WAIT_ABANDONED: t.CDefine = 0x80
MAX_PATH: t.CDefine = 260
ERROR_SUCCESS: t.CDefine = 0
ERROR_FILE_NOT_FOUND: t.CDefine = 2
ERROR_ACCESS_DENIED: t.CDefine = 5
ERROR_INSUFFICIENT_BUFFER: t.CDefine = 122
class SECURITY_ATTRIBUTES:
nLength: ULONG
lpSecurityDescriptor: VOIDPTR
bInheritHandle: BOOL
class OVERLAPPED:
Internal: ULONGLONG
InternalHigh: ULONGLONG
Offset: ULONG
OffsetHigh: ULONG
hEvent: HANDLE
class FILETIME:
dwLowDateTime: DWORD
dwHighDateTime: DWORD
class SYSTEMTIME:
wYear: WORD
wMonth: WORD
wDayOfWeek: WORD
wDay: WORD
wHour: WORD
wMinute: WORD
wSecond: WORD
wMilliseconds: WORD
class GUID:
Data1: DWORD
Data2: WORD
Data3: WORD
Data4: BYTEPTR
class LARGE_INTEGER:
QuadPart: LONGLONG
class ULARGE_INTEGER:
QuadPart: ULONGLONG
def GetLastError() -> ULONG | t.State: pass
def SetLastError(dwErrCode: ULONG) -> t.State: pass
def CloseHandle(hObject: HANDLE) -> BOOL | t.State: pass
def GetProcAddress(hModule: HANDLE, lpProcName: LPCSTR) -> VOIDPTR | t.State: pass
def GetModuleHandleA(lpModuleName: LPCSTR) -> HANDLE | t.State: pass
def GetModuleHandleW(lpModuleName: LPCWSTR) -> HANDLE | t.State: pass
def LoadLibraryA(lpLibFileName: LPCSTR) -> HANDLE | t.State: pass
def LoadLibraryW(lpLibFileName: LPCWSTR) -> HANDLE | t.State: pass
def FreeLibrary(hLibModule: HANDLE) -> BOOL | t.State: pass
def GetSystemTime(lpSystemTime: SYSTEMTIME | t.CPtr) -> t.State: pass
def GetLocalTime(lpSystemTime: SYSTEMTIME | t.CPtr) -> t.State: pass
def FileTimeToSystemTime(lpFileTime: FILETIME | t.CPtr, lpSystemTime: SYSTEMTIME | t.CPtr) -> BOOL | t.State: pass
def SystemTimeToFileTime(lpSystemTime: SYSTEMTIME | t.CPtr, lpFileTime: FILETIME | t.CPtr) -> BOOL | t.State: pass
def QueryPerformanceCounter(lpPerformanceCount: LARGE_INTEGER | t.CPtr) -> BOOL | t.State: pass
def QueryPerformanceFrequency(lpFrequency: LARGE_INTEGER | t.CPtr) -> BOOL | t.State: pass
def Sleep(dwMilliseconds: ULONG) -> t.State: pass
def SleepEx(dwMilliseconds: ULONG, bAlertable: BOOL) -> ULONG | t.State: pass
def GetTickCount() -> ULONG | t.State: pass
def GetTickCount64() -> ULONGLONG | t.State: pass
def GetCommandLineA() -> CHARPTR | t.State: pass
-777
View File
@@ -1,777 +0,0 @@
import t, c
# ============================================================
# PyObject — 所有 Python 对象的基类
# ============================================================
class PyObject:
ob_refcnt: t.CLong
ob_type: t.CPtr
# ============================================================
# 引用计数
# ============================================================
def Py_INCREF(op: PyObject | t.CPtr) -> t.CVoid | t.State: pass
def Py_DECREF(op: PyObject | t.CPtr) -> t.CVoid | t.State: pass
def Py_XINCREF(op: PyObject | t.CPtr) -> t.CVoid | t.State: pass
def Py_XDECREF(op: PyObject | t.CPtr) -> t.CVoid | t.State: pass
def Py_DecRef(op: PyObject | t.CPtr) -> t.CVoid | t.State: pass
# ============================================================
# 解释器初始化/终止
# ============================================================
def Py_Initialize() -> t.CVoid | t.State: pass
def Py_Finalize() -> t.CVoid | t.State: pass
def Py_InitializeEx(initsigs: t.CInt) -> t.CVoid | t.State: pass
def Py_FinalizeEx() -> t.CInt | t.State: pass
def Py_IsInitialized() -> t.CInt | t.State: pass
# ============================================================
# PyConfig
# ============================================================
class PySTATUS:
func: t.CConst | str
err_msg: t.CConst | str
exitcode: t.CInt
class PyPreConfig:
_config_version: t.CInt
_config_init: t.CInt
parse_argv: t.CInt
isolated: t.CInt
use_environment: t.CInt
utf8_mode: t.CInt
coerce_c_locale: t.CInt
C_locale_warnings: t.CInt
allocator: t.CInt
dev_mode: t.CInt
class PyWideStringList:
length: t.CSizeT
items: t.CPtr
class PyConfig:
_config_version: t.CInt
_config_init: t.CInt
isolated: t.CInt
use_environment: t.CInt
dev_mode: t.CInt
install_signal_handlers: t.CInt
use_hash_seed: t.CInt
hash_seed: t.CUnsignedLong
faulthandler: t.CInt
tracemalloc: t.CInt
import_time: t.CInt
show_ref_count: t.CInt
dump_refs: t.CInt
dump_refs_file: t.CConst | str
malloc_stats: t.CInt
filesystem_errors: t.CInt
pycache_prefix: t.CConst | str
parse_argv: t.CInt
argv: PyWideStringList
program_name: t.CConst | str
xoptions: PyWideStringList
warnoptions: PyWideStringList
site_import: t.CInt
bytes_warning: t.CInt
warn_default_encoding: t.CInt
inspect: t.CInt
interactive: t.CInt
optimization_level: t.CInt
parser_debug: t.CInt
verbose: t.CInt
quiet: t.CInt
home: t.CConst | str
pythonpath_env: t.CConst | str
module_search_paths: PyWideStringList
module_search_paths_set: t.CInt
executable: t.CConst | str
base_executable: t.CConst | str
prefix: t.CConst | str
base_prefix: t.CConst | str
exec_prefix: t.CConst | str
base_exec_prefix: t.CConst | str
platlibdir: t.CConst | str
stdio_filename: t.CConst | str
def PyConfig_InitPythonConfig(config: PyConfig | t.CPtr) -> t.CVoid | t.State: pass
def PyConfig_InitIsolatedConfig(config: PyConfig | t.CPtr) -> t.CVoid | t.State: pass
def PyConfig_Clear(config: PyConfig | t.CPtr) -> t.CVoid | t.State: pass
def PyConfig_Read(config: PyConfig | t.CPtr) -> PySTATUS | t.State: pass
def Py_InitializeFromConfig(config: PyConfig | t.CPtr) -> PySTATUS | t.State: pass
def Py_DecodeLocale(s: t.CConst | str) -> str | t.State: pass
def PyStatus_Exception(status: PySTATUS) -> t.CInt | t.State: pass
# ============================================================
# 整数操作 (PyLong)
# ============================================================
def PyLong_FromLong(v: t.CInt) -> PyObject | t.CPtr | t.State: pass
def PyLong_FromUnsignedLong(v: t.CUnsignedLong) -> PyObject | t.CPtr | t.State: pass
def PyLong_FromLongLong(v: t.CLong) -> PyObject | t.CPtr | t.State: pass
def PyLong_FromUnsignedLongLong(v: t.CUnsignedLong) -> PyObject | t.CPtr | t.State: pass
def PyLong_FromSsize_t(v: t.CPtrDiffT) -> PyObject | t.CPtr | t.State: pass
def PyLong_FromSize_t(v: t.CSizeT) -> PyObject | t.CPtr | t.State: pass
def PyLong_FromDouble(v: t.CDouble) -> PyObject | t.CPtr | t.State: pass
def PyLong_AsLong(obj: PyObject | t.CPtr) -> t.CInt | t.State: pass
def PyLong_AsUnsignedLong(obj: PyObject | t.CPtr) -> t.CUnsignedLong | t.State: pass
def PyLong_AsLongLong(obj: PyObject | t.CPtr) -> t.CLong | t.State: pass
def PyLong_AsUnsignedLongLong(obj: PyObject | t.CPtr) -> t.CUnsignedLong | t.State: pass
def PyLong_AsDouble(obj: PyObject | t.CPtr) -> t.CDouble | t.State: pass
def PyLong_AsSsize_t(obj: PyObject | t.CPtr) -> t.CPtrDiffT | t.State: pass
def PyLong_AsSize_t(obj: PyObject | t.CPtr) -> t.CSizeT | t.State: pass
# ============================================================
# 浮点数操作 (PyFloat)
# ============================================================
def PyFloat_FromDouble(v: t.CDouble) -> PyObject | t.CPtr | t.State: pass
def PyFloat_AsDouble(obj: PyObject | t.CPtr) -> t.CDouble | t.State: pass
def PyFloat_FromString(s: PyObject | t.CPtr) -> PyObject | t.CPtr | t.State: pass
# ============================================================
# 字符串操作 (PyUnicode / PyBytes)
# ============================================================
def PyUnicode_FromString(u: t.CConst | str) -> PyObject | t.CPtr | t.State: pass
def PyUnicode_FromStringAndSize(u: t.CConst | str, size: t.CSizeT) -> PyObject | t.CPtr | t.State: pass
def PyUnicode_FromFormat(fmt: t.CConst | str) -> PyObject | t.CPtr | t.State: pass
def PyUnicode_AsUTF8(obj: PyObject | t.CPtr) -> str | t.State: pass
def PyUnicode_AsUTF8AndSize(obj: PyObject | t.CPtr, size: t.CPtrDiffT | t.CPtr) -> str | t.State: pass
def PyUnicode_AsWideChar(obj: PyObject | t.CPtr, wbuf: t.CPtr, bufsize: t.CSizeT) -> t.CSizeT | t.State: pass
def PyUnicode_GetLength(obj: PyObject | t.CPtr) -> t.CPtrDiffT | t.State: pass
def PyUnicode_ReadChar(obj: PyObject | t.CPtr, idx: t.CSizeT) -> t.CUInt32T | t.State: pass
def PyUnicode_WriteChar(obj: PyObject | t.CPtr, idx: t.CSizeT, ch: t.CUInt32T) -> t.CInt | t.State: pass
def PyUnicode_Compare(l: PyObject | t.CPtr, r: PyObject | t.CPtr) -> t.CInt | t.State: pass
def PyUnicode_Concat(l: PyObject | t.CPtr, r: PyObject | t.CPtr) -> PyObject | t.CPtr | t.State: pass
def PyUnicode_Contains(container: PyObject | t.CPtr, element: PyObject | t.CPtr) -> t.CInt | t.State: pass
def PyUnicode_Format(fmt: PyObject | t.CPtr, args: PyObject | t.CPtr) -> PyObject | t.CPtr | t.State: pass
def PyUnicode_InternInPlace(s: PyObject | t.CPtr | t.CPtr) -> t.CVoid | t.State: pass
def PyUnicode_InternFromString(u: t.CConst | str) -> PyObject | t.CPtr | t.State: pass
def PyBytes_FromString(v: t.CConst | str) -> PyObject | t.CPtr | t.State: pass
def PyBytes_FromStringAndSize(v: t.CConst | str, size: t.CSizeT) -> PyObject | t.CPtr | t.State: pass
def PyBytes_AsString(obj: PyObject | t.CPtr) -> str | t.State: pass
def PyBytes_Size(obj: PyObject | t.CPtr) -> t.CSizeT | t.State: pass
def PyBytes_FromObject(o: PyObject | t.CPtr) -> PyObject | t.CPtr | t.State: pass
def PyBytes_FromFormat(fmt: t.CConst | str) -> PyObject | t.CPtr | t.State: pass
# ============================================================
# 布尔 / None
# ============================================================
def PyBool_FromLong(v: t.CLong) -> PyObject | t.CPtr | t.State: pass
Py_True: PyObject | t.CPtr | t.State
Py_False: PyObject | t.CPtr | t.State
Py_None: PyObject | t.CPtr | t.State
# ============================================================
# 列表操作 (PyList)
# ============================================================
def PyList_New(len: t.CSizeT) -> PyObject | t.CPtr | t.State: pass
def PyList_Size(lst: PyObject | t.CPtr) -> t.CSizeT | t.State: pass
def PyList_GetItem(lst: PyObject | t.CPtr, idx: t.CSizeT) -> PyObject | t.CPtr | t.State: pass
def PyList_SetItem(lst: PyObject | t.CPtr, idx: t.CSizeT, item: PyObject | t.CPtr) -> t.CInt | t.State: pass
def PyList_Insert(lst: PyObject | t.CPtr, idx: t.CSizeT, item: PyObject | t.CPtr) -> t.CInt | t.State: pass
def PyList_Append(lst: PyObject | t.CPtr, item: PyObject | t.CPtr) -> t.CInt | t.State: pass
def PyList_GetSlice(lst: PyObject | t.CPtr, lo: t.CSizeT, hi: t.CSizeT) -> PyObject | t.CPtr | t.State: pass
def PyList_SetSlice(lst: PyObject | t.CPtr, lo: t.CSizeT, hi: t.CSizeT, items: PyObject | t.CPtr) -> t.CInt | t.State: pass
def PyList_Sort(lst: PyObject | t.CPtr) -> t.CInt | t.State: pass
def PyList_Reverse(lst: PyObject | t.CPtr) -> t.CInt | t.State: pass
def PyList_AsTuple(lst: PyObject | t.CPtr) -> PyObject | t.CPtr | t.State: pass
# ============================================================
# 元组操作 (PyTuple)
# ============================================================
def PyTuple_New(len: t.CSizeT) -> PyObject | t.CPtr | t.State: pass
def PyTuple_Size(tup: PyObject | t.CPtr) -> t.CSizeT | t.State: pass
def PyTuple_GetItem(tup: PyObject | t.CPtr, idx: t.CSizeT) -> PyObject | t.CPtr | t.State: pass
def PyTuple_SetItem(tup: PyObject | t.CPtr, idx: t.CSizeT, item: PyObject | t.CPtr) -> t.CInt | t.State: pass
def PyTuple_GetSlice(tup: PyObject | t.CPtr, lo: t.CSizeT, hi: t.CSizeT) -> PyObject | t.CPtr | t.State: pass
def PyTuple_Pack(n: t.CSizeT) -> PyObject | t.CPtr | t.State: pass
# ============================================================
# 字典操作 (PyDict)
# ============================================================
def PyDict_New() -> PyObject | t.CPtr | t.State: pass
def PyDict_GetItem(d: PyObject | t.CPtr, key: PyObject | t.CPtr) -> PyObject | t.CPtr | t.State: pass
def PyDict_GetItemString(d: PyObject | t.CPtr, key: t.CConst | str) -> PyObject | t.CPtr | t.State: pass
def PyDict_SetItem(d: PyObject | t.CPtr, key: PyObject | t.CPtr, val: PyObject | t.CPtr) -> t.CInt | t.State: pass
def PyDict_SetItemString(d: PyObject | t.CPtr, key: t.CConst | str, val: PyObject | t.CPtr) -> t.CInt | t.State: pass
def PyDict_DelItem(d: PyObject | t.CPtr, key: PyObject | t.CPtr) -> t.CInt | t.State: pass
def PyDict_DelItemString(d: PyObject | t.CPtr, key: t.CConst | str) -> t.CInt | t.State: pass
def PyDict_Size(d: PyObject | t.CPtr) -> t.CSizeT | t.State: pass
def PyDict_Keys(d: PyObject | t.CPtr) -> PyObject | t.CPtr | t.State: pass
def PyDict_Values(d: PyObject | t.CPtr) -> PyObject | t.CPtr | t.State: pass
def PyDict_Items(d: PyObject | t.CPtr) -> PyObject | t.CPtr | t.State: pass
def PyDict_Copy(d: PyObject | t.CPtr) -> PyObject | t.CPtr | t.State: pass
def PyDict_Clear(d: PyObject | t.CPtr) -> t.CVoid | t.State: pass
def PyDict_Contains(d: PyObject | t.CPtr, key: PyObject | t.CPtr) -> t.CInt | t.State: pass
def PyDict_Next(d: PyObject | t.CPtr, pos: t.CPtrDiffT | t.CPtr, key: PyObject | t.CPtr | t.CPtr, val: PyObject | t.CPtr | t.CPtr) -> t.CInt | t.State: pass
def PyDict_Merge(d: PyObject | t.CPtr, other: PyObject | t.CPtr, override: t.CInt) -> t.CInt | t.State: pass
def PyDict_Update(d: PyObject | t.CPtr, other: PyObject | t.CPtr) -> t.CInt | t.State: pass
# ============================================================
# 对象通用操作
# ============================================================
def PyObject_Str(obj: PyObject | t.CPtr) -> PyObject | t.CPtr | t.State: pass
def PyObject_Repr(obj: PyObject | t.CPtr) -> PyObject | t.CPtr | t.State: pass
def PyObject_Type(obj: PyObject | t.CPtr) -> PyObject | t.CPtr | t.State: pass
def PyObject_IsInstance(obj: PyObject | t.CPtr, cls: PyObject | t.CPtr) -> t.CInt | t.State: pass
def PyObject_IsSubclass(obj: PyObject | t.CPtr, cls: PyObject | t.CPtr) -> t.CInt | t.State: pass
def PyObject_HasAttr(obj: PyObject | t.CPtr, name: PyObject | t.CPtr) -> t.CInt | t.State: pass
def PyObject_HasAttrString(obj: PyObject | t.CPtr, name: t.CConst | str) -> t.CInt | t.State: pass
def PyObject_GetAttr(obj: PyObject | t.CPtr, name: PyObject | t.CPtr) -> PyObject | t.CPtr | t.State: pass
def PyObject_GetAttrString(obj: PyObject | t.CPtr, name: t.CConst | str) -> PyObject | t.CPtr | t.State: pass
def PyObject_SetAttr(obj: PyObject | t.CPtr, name: PyObject | t.CPtr, val: PyObject | t.CPtr) -> t.CInt | t.State: pass
def PyObject_SetAttrString(obj: PyObject | t.CPtr, name: t.CConst | str, val: PyObject | t.CPtr) -> t.CInt | t.State: pass
def PyObject_DelAttr(obj: PyObject | t.CPtr, name: PyObject | t.CPtr) -> t.CInt | t.State: pass
def PyObject_DelAttrString(obj: PyObject | t.CPtr, name: t.CConst | str) -> t.CInt | t.State: pass
def PyObject_Call(callable: PyObject | t.CPtr, args: PyObject | t.CPtr, kwargs: PyObject | t.CPtr) -> PyObject | t.CPtr | t.State: pass
def PyObject_CallObject(callable: PyObject | t.CPtr, args: PyObject | t.CPtr) -> PyObject | t.CPtr | t.State: pass
def PyObject_CallNoArgs(callable: PyObject | t.CPtr) -> PyObject | t.CPtr | t.State: pass
def PyObject_CallOneArg(callable: PyObject | t.CPtr, arg: PyObject | t.CPtr) -> PyObject | t.CPtr | t.State: pass
def PyObject_IsTrue(obj: PyObject | t.CPtr) -> t.CInt | t.State: pass
def PyObject_Not(obj: PyObject | t.CPtr) -> t.CInt | t.State: pass
def PyObject_RichCompare(o1: PyObject | t.CPtr, o2: PyObject | t.CPtr, opid: t.CInt) -> PyObject | t.CPtr | t.State: pass
def PyObject_RichCompareBool(o1: PyObject | t.CPtr, o2: PyObject | t.CPtr, opid: t.CInt) -> t.CInt | t.State: pass
def PyObject_Hash(obj: PyObject | t.CPtr) -> t.CLong | t.State: pass
def PyObject_Length(obj: PyObject | t.CPtr) -> t.CSizeT | t.State: pass
def PyObject_GetItem(obj: PyObject | t.CPtr, key: PyObject | t.CPtr) -> PyObject | t.CPtr | t.State: pass
def PyObject_SetItem(obj: PyObject | t.CPtr, key: PyObject | t.CPtr, val: PyObject | t.CPtr) -> t.CInt | t.State: pass
def PyObject_DelItem(obj: PyObject | t.CPtr, key: PyObject | t.CPtr) -> t.CInt | t.State: pass
def PyObject_Dir(obj: PyObject | t.CPtr) -> PyObject | t.CPtr | t.State: pass
def PyObject_GetIter(obj: PyObject | t.CPtr) -> PyObject | t.CPtr | t.State: pass
def PyIter_Next(obj: PyObject | t.CPtr) -> PyObject | t.CPtr | t.State: pass
# ============================================================
# 比较常量
# ============================================================
Py_LT: t.CInt | t.State
Py_LE: t.CInt | t.State
Py_EQ: t.CInt | t.State
Py_NE: t.CInt | t.State
Py_GT: t.CInt | t.State
Py_GE: t.CInt | t.State
# ============================================================
# 模块操作
# ============================================================
def PyImport_ImportModule(name: t.CConst | str) -> PyObject | t.CPtr | t.State: pass
def PyImport_Import(name: PyObject | t.CPtr) -> PyObject | t.CPtr | t.State: pass
def PyImport_ImportModuleLevelObject(name: PyObject | t.CPtr, globs: PyObject | t.CPtr, locs: PyObject | t.CPtr, fromlist: PyObject | t.CPtr, level: t.CInt) -> PyObject | t.CPtr | t.State: pass
def PyImport_ReloadModule(mod: PyObject | t.CPtr) -> PyObject | t.CPtr | t.State: pass
def PyImport_AddModule(name: t.CConst | str) -> PyObject | t.CPtr | t.State: pass
def PyImport_GetModuleDict() -> PyObject | t.CPtr | t.State: pass
def PyImport_ImportModuleEx(name: t.CConst | str, globs: PyObject | t.CPtr, locs: PyObject | t.CPtr, fromlist: PyObject | t.CPtr) -> PyObject | t.CPtr | t.State: pass
# ============================================================
# 模块创建
# ============================================================
class PyMethodDef:
ml_name: t.CConst | str
ml_meth: t.CPtr
ml_flags: t.CInt
ml_doc: t.CConst | str
class PyModuleDef_Base:
ob_base: PyObject
m_init: t.CPtr
m_index: t.CSizeT
m_copy: PyObject | t.CPtr
class PyModuleDef:
m_base: PyModuleDef_Base
m_name: t.CConst | str
m_doc: t.CConst | str
m_size: t.CPtrDiffT
m_methods: PyMethodDef | t.CPtr
m_slots: t.CPtr
m_traverse: t.CPtr
m_clear: t.CPtr
m_free: t.CPtr
def PyModule_Create(mod: PyModuleDef | t.CPtr) -> PyObject | t.CPtr | t.State: pass
def PyModule_Create2(mod: PyModuleDef | t.CPtr, ver: t.CInt) -> PyObject | t.CPtr | t.State: pass
def PyModule_GetName(mod: PyObject | t.CPtr) -> str | t.State: pass
def PyModule_GetDict(mod: PyObject | t.CPtr) -> PyObject | t.CPtr | t.State: pass
def PyModule_GetFilenameObject(mod: PyObject | t.CPtr) -> PyObject | t.CPtr | t.State: pass
def PyModule_AddObject(mod: PyObject | t.CPtr, name: t.CConst | str, val: PyObject | t.CPtr) -> t.CInt | t.State: pass
def PyModule_AddObjectRef(mod: PyObject | t.CPtr, name: t.CConst | str, val: PyObject | t.CPtr) -> t.CInt | t.State: pass
def PyModule_AddIntConstant(mod: PyObject | t.CPtr, name: t.CConst | str, val: t.CLong) -> t.CInt | t.State: pass
def PyModule_AddStringConstant(mod: PyObject | t.CPtr, name: t.CConst | str, val: t.CConst | str) -> t.CInt | t.State: pass
# ============================================================
# GIL 管理
# ============================================================
def PyGILState_Ensure() -> t.CInt | t.State: pass
def PyGILState_Release(state: t.CInt) -> t.CVoid | t.State: pass
def PyEval_SaveThread() -> t.CPtr | t.State: pass
def PyEval_RestoreThread(tstate: t.CPtr) -> t.CVoid | t.State: pass
def PyEval_AcquireThread(tstate: t.CPtr) -> t.CVoid | t.State: pass
def PyEval_ReleaseThread(tstate: t.CPtr) -> t.CVoid | t.State: pass
def PyEval_AcquireLock() -> t.CVoid | t.State: pass
def PyEval_ReleaseLock() -> t.CVoid | t.State: pass
def PyEval_ThreadsInitialized() -> t.CInt | t.State: pass
def PyEval_InitThreads() -> t.CVoid | t.State: pass
# ============================================================
# 错误处理
# ============================================================
def PyErr_Occurred() -> PyObject | t.CPtr | t.State: pass
def PyErr_Clear() -> t.CVoid | t.State: pass
def PyErr_Fetch(tp: PyObject | t.CPtr | t.CPtr, val: PyObject | t.CPtr | t.CPtr, tb: PyObject | t.CPtr | t.CPtr) -> t.CVoid | t.State: pass
def PyErr_Restore(tp: PyObject | t.CPtr, val: PyObject | t.CPtr, tb: PyObject | t.CPtr) -> t.CVoid | t.State: pass
def PyErr_NormalizeException(tp: PyObject | t.CPtr | t.CPtr, val: PyObject | t.CPtr | t.CPtr, tb: PyObject | t.CPtr | t.CPtr) -> t.CVoid | t.State: pass
def PyErr_SetString(tp: PyObject | t.CPtr, msg: t.CConst | str) -> t.CVoid | t.State: pass
def PyErr_SetObject(tp: PyObject | t.CPtr, val: PyObject | t.CPtr) -> t.CVoid | t.State: pass
def PyErr_BadArgument() -> t.CPtr | t.State: pass
def PyErr_NoMemory() -> t.CPtr | t.State: pass
def PyErr_Print() -> t.CVoid | t.State: pass
def PyErr_ExceptionMatches(exc: PyObject | t.CPtr) -> t.CInt | t.State: pass
def PyErr_GivenExceptionMatches(given: PyObject | t.CPtr, exc: PyObject | t.CPtr) -> t.CInt | t.State: pass
# ============================================================
# 内置异常类型
# ============================================================
PyExc_BaseException: PyObject | t.CPtr | t.State
PyExc_Exception: PyObject | t.CPtr | t.State
PyExc_TypeError: PyObject | t.CPtr | t.State
PyExc_ValueError: PyObject | t.CPtr | t.State
PyExc_RuntimeError: PyObject | t.CPtr | t.State
PyExc_KeyError: PyObject | t.CPtr | t.State
PyExc_IndexError: PyObject | t.CPtr | t.State
PyExc_AttributeError: PyObject | t.CPtr | t.State
PyExc_ImportError: PyObject | t.CPtr | t.State
PyExc_OSError: PyObject | t.CPtr | t.State
PyExc_IOError: PyObject | t.CPtr | t.State
PyExc_ZeroDivisionError: PyObject | t.CPtr | t.State
PyExc_OverflowError: PyObject | t.CPtr | t.State
PyExc_MemoryError: PyObject | t.CPtr | t.State
PyExc_NameError: PyObject | t.CPtr | t.State
PyExc_StopIteration: PyObject | t.CPtr | t.State
PyExc_NotImplementedError: PyObject | t.CPtr | t.State
PyExc_SyntaxError: PyObject | t.CPtr | t.State
PyExc_FileNotFoundError: PyObject | t.CPtr | t.State
PyExc_PermissionError: PyObject | t.CPtr | t.State
PyExc_IsADirectoryError: PyObject | t.CPtr | t.State
PyExc_NotADirectoryError: PyObject | t.CPtr | t.State
# ============================================================
# 内置函数
# ============================================================
def Py_BuildValue(fmt: t.CConst | str) -> PyObject | t.CPtr | t.State: pass
def Py_VaBuildValue(fmt: t.CConst | str, va: t.CPtr) -> PyObject | t.CPtr | t.State: pass
# ============================================================
# 类型检查
# ============================================================
def PyLong_Check(obj: PyObject | t.CPtr) -> t.CInt | t.State: pass
def PyFloat_Check(obj: PyObject | t.CPtr) -> t.CInt | t.State: pass
def PyUnicode_Check(obj: PyObject | t.CPtr) -> t.CInt | t.State: pass
def PyBytes_Check(obj: PyObject | t.CPtr) -> t.CInt | t.State: pass
def PyList_Check(obj: PyObject | t.CPtr) -> t.CInt | t.State: pass
def PyTuple_Check(obj: PyObject | t.CPtr) -> t.CInt | t.State: pass
def PyDict_Check(obj: PyObject | t.CPtr) -> t.CInt | t.State: pass
def PyBool_Check(obj: PyObject | t.CPtr) -> t.CInt | t.State: pass
def PyNone_Check(obj: PyObject | t.CPtr) -> t.CInt | t.State: pass
# ============================================================
# 内存管理
# ============================================================
def PyMem_Malloc(size: t.CSizeT) -> t.CPtr | t.State: pass
def PyMem_Realloc(ptr: t.CPtr, size: t.CSizeT) -> t.CPtr | t.State: pass
def PyMem_Free(ptr: t.CPtr) -> t.CVoid | t.State: pass
def PyMem_Calloc(nelem: t.CSizeT, elsize: t.CSizeT) -> t.CPtr | t.State: pass
def PyObject_Malloc(size: t.CSizeT) -> t.CPtr | t.State: pass
def PyObject_Realloc(ptr: t.CPtr, size: t.CSizeT) -> t.CPtr | t.State: pass
def PyObject_Free(ptr: t.CPtr) -> t.CVoid | t.State: pass
def PyObject_Calloc(nelem: t.CSizeT, elsize: t.CSizeT) -> t.CPtr | t.State: pass
def PyObject_Init(obj: PyObject | t.CPtr, tp: t.CPtr) -> PyObject | t.CPtr | t.State: pass
def PyObject_InitVar(obj: PyObject | t.CPtr, tp: t.CPtr, size: t.CSizeT) -> PyObject | t.CPtr | t.State: pass
# ============================================================
# 文件操作
# ============================================================
def PyFile_FromString(filename: t.CConst | str, mode: t.CConst | str) -> PyObject | t.CPtr | t.State: pass
def PyFile_AsFile(file: PyObject | t.CPtr) -> t.CPtr | t.State: pass
def PyFile_WriteObject(obj: PyObject | t.CPtr, file: PyObject | t.CPtr, flags: t.CInt) -> t.CInt | t.State: pass
def PyFile_WriteString(s: t.CConst | str, file: PyObject | t.CPtr) -> t.CInt | t.State: pass
# ============================================================
# 编译/执行
# ============================================================
def Py_CompileString(s: t.CConst | str, filename: t.CConst | str, start: t.CInt) -> PyObject | t.CPtr | t.State: pass
def PyEval_EvalCode(code: PyObject | t.CPtr, globs: PyObject | t.CPtr, locs: PyObject | t.CPtr) -> PyObject | t.CPtr | t.State: pass
def PyEval_EvalCodeEx(code: PyObject | t.CPtr, globs: PyObject | t.CPtr, locs: PyObject | t.CPtr, args: PyObject | t.CPtr | t.CPtr, argc: t.CInt, kws: PyObject | t.CPtr | t.CPtr, kwc: t.CInt, defs: PyObject | t.CPtr | t.CPtr, defc: t.CInt, kwdefs: PyObject | t.CPtr, closure: PyObject | t.CPtr) -> PyObject | t.CPtr | t.State: pass
def PyEval_EvalFrame(frame: t.CPtr) -> PyObject | t.CPtr | t.State: pass
def PyEval_CallObject(callable: PyObject | t.CPtr, args: PyObject | t.CPtr) -> PyObject | t.CPtr | t.State: pass
def PyEval_CallFunction(callable: PyObject | t.CPtr, fmt: t.CConst | str) -> PyObject | t.CPtr | t.State: pass
def PyEval_CallMethod(obj: PyObject | t.CPtr, method: t.CConst | str, fmt: t.CConst | str) -> PyObject | t.CPtr | t.State: pass
# ============================================================
# PyRun
# ============================================================
def PyRun_SimpleString(cmd: t.CConst | str) -> t.CInt | t.State: pass
def PyRun_SimpleFile(fp: t.CPtr, filename: t.CConst | str) -> t.CInt | t.State: pass
def PyRun_AnyFile(fp: t.CPtr, filename: t.CConst | str) -> t.CInt | t.State: pass
def PyRun_String(s: t.CConst | str, start: t.CInt, globs: PyObject | t.CPtr, locs: PyObject | t.CPtr) -> PyObject | t.CPtr | t.State: pass
def PyRun_File(fp: t.CPtr, filename: t.CConst | str, start: t.CInt, globs: PyObject | t.CPtr, locs: PyObject | t.CPtr) -> PyObject | t.CPtr | t.State: pass
Py_single_input: t.CInt | t.State
Py_file_input: t.CInt | t.State
Py_eval_input: t.CInt | t.State
# ============================================================
# Capsule
# ============================================================
def PyCapsule_New(ptr: t.CPtr, name: t.CConst | str, dtor: t.CPtr) -> PyObject | t.CPtr | t.State: pass
def PyCapsule_GetPointer(cap: PyObject | t.CPtr, name: t.CConst | str) -> t.CPtr | t.State: pass
def PyCapsule_GetName(cap: PyObject | t.CPtr) -> str | t.State: pass
def PyCapsule_IsValid(cap: PyObject | t.CPtr, name: t.CConst | str) -> t.CInt | t.State: pass
def PyCapsule_SetPointer(cap: PyObject | t.CPtr, ptr: t.CPtr) -> t.CInt | t.State: pass
def PyCapsule_SetName(cap: PyObject | t.CPtr, name: t.CConst | str) -> t.CInt | t.State: pass
def PyCapsule_SetDestructor(cap: PyObject | t.CPtr, dtor: t.CPtr) -> t.CInt | t.State: pass
# ============================================================
# 序列操作
# ============================================================
def PySequence_Check(obj: PyObject | t.CPtr) -> t.CInt | t.State: pass
def PySequence_Size(obj: PyObject | t.CPtr) -> t.CSizeT | t.State: pass
def PySequence_Length(obj: PyObject | t.CPtr) -> t.CSizeT | t.State: pass
def PySequence_Concat(o1: PyObject | t.CPtr, o2: PyObject | t.CPtr) -> PyObject | t.CPtr | t.State: pass
def PySequence_Repeat(obj: PyObject | t.CPtr, count: t.CSizeT) -> PyObject | t.CPtr | t.State: pass
def PySequence_GetItem(obj: PyObject | t.CPtr, idx: t.CSizeT) -> PyObject | t.CPtr | t.State: pass
def PySequence_SetItem(obj: PyObject | t.CPtr, idx: t.CSizeT, val: PyObject | t.CPtr) -> t.CInt | t.State: pass
def PySequence_DelItem(obj: PyObject | t.CPtr, idx: t.CSizeT) -> t.CInt | t.State: pass
def PySequence_GetSlice(obj: PyObject | t.CPtr, start: t.CSizeT, end: t.CSizeT) -> PyObject | t.CPtr | t.State: pass
def PySequence_SetSlice(obj: PyObject | t.CPtr, start: t.CSizeT, end: t.CSizeT, val: PyObject | t.CPtr) -> t.CInt | t.State: pass
def PySequence_DelSlice(obj: PyObject | t.CPtr, start: t.CSizeT, end: t.CSizeT) -> t.CInt | t.State: pass
def PySequence_Contains(obj: PyObject | t.CPtr, val: PyObject | t.CPtr) -> t.CInt | t.State: pass
def PySequence_Index(obj: PyObject | t.CPtr, val: PyObject | t.CPtr) -> t.CSizeT | t.State: pass
def PySequence_Count(obj: PyObject | t.CPtr, val: PyObject | t.CPtr) -> t.CSizeT | t.State: pass
def PySequence_List(obj: PyObject | t.CPtr) -> PyObject | t.CPtr | t.State: pass
def PySequence_Tuple(obj: PyObject | t.CPtr) -> PyObject | t.CPtr | t.State: pass
# ============================================================
# 映射操作
# ============================================================
def PyMapping_Check(obj: PyObject | t.CPtr) -> t.CInt | t.State: pass
def PyMapping_Size(obj: PyObject | t.CPtr) -> t.CSizeT | t.State: pass
def PyMapping_Length(obj: PyObject | t.CPtr) -> t.CSizeT | t.State: pass
def PyMapping_HasKey(obj: PyObject | t.CPtr, key: PyObject | t.CPtr) -> t.CInt | t.State: pass
def PyMapping_HasKeyString(obj: PyObject | t.CPtr, key: t.CConst | str) -> t.CInt | t.State: pass
def PyMapping_GetItemString(obj: PyObject | t.CPtr, key: t.CConst | str) -> PyObject | t.CPtr | t.State: pass
def PyMapping_SetItemString(obj: PyObject | t.CPtr, key: t.CConst | str, val: PyObject | t.CPtr) -> t.CInt | t.State: pass
def PyMapping_Keys(obj: PyObject | t.CPtr) -> PyObject | t.CPtr | t.State: pass
def PyMapping_Values(obj: PyObject | t.CPtr) -> PyObject | t.CPtr | t.State: pass
def PyMapping_Items(obj: PyObject | t.CPtr) -> PyObject | t.CPtr | t.State: pass
# ============================================================
# 数字操作
# ============================================================
def PyNumber_Add(o1: PyObject | t.CPtr, o2: PyObject | t.CPtr) -> PyObject | t.CPtr | t.State: pass
def PyNumber_Subtract(o1: PyObject | t.CPtr, o2: PyObject | t.CPtr) -> PyObject | t.CPtr | t.State: pass
def PyNumber_Multiply(o1: PyObject | t.CPtr, o2: PyObject | t.CPtr) -> PyObject | t.CPtr | t.State: pass
def PyNumber_MatrixMultiply(o1: PyObject | t.CPtr, o2: PyObject | t.CPtr) -> PyObject | t.CPtr | t.State: pass
def PyNumber_FloorDivide(o1: PyObject | t.CPtr, o2: PyObject | t.CPtr) -> PyObject | t.CPtr | t.State: pass
def PyNumber_TrueDivide(o1: PyObject | t.CPtr, o2: PyObject | t.CPtr) -> PyObject | t.CPtr | t.State: pass
def PyNumber_Modulo(o1: PyObject | t.CPtr, o2: PyObject | t.CPtr) -> PyObject | t.CPtr | t.State: pass
def PyNumber_Power(o1: PyObject | t.CPtr, o2: PyObject | t.CPtr, o3: PyObject | t.CPtr) -> PyObject | t.CPtr | t.State: pass
def PyNumber_Negative(obj: PyObject | t.CPtr) -> PyObject | t.CPtr | t.State: pass
def PyNumber_Positive(obj: PyObject | t.CPtr) -> PyObject | t.CPtr | t.State: pass
def PyNumber_Absolute(obj: PyObject | t.CPtr) -> PyObject | t.CPtr | t.State: pass
def PyNumber_Invert(obj: PyObject | t.CPtr) -> PyObject | t.CPtr | t.State: pass
def PyNumber_Lshift(o1: PyObject | t.CPtr, o2: PyObject | t.CPtr) -> PyObject | t.CPtr | t.State: pass
def PyNumber_Rshift(o1: PyObject | t.CPtr, o2: PyObject | t.CPtr) -> PyObject | t.CPtr | t.State: pass
def PyNumber_And(o1: PyObject | t.CPtr, o2: PyObject | t.CPtr) -> PyObject | t.CPtr | t.State: pass
def PyNumber_Xor(o1: PyObject | t.CPtr, o2: PyObject | t.CPtr) -> PyObject | t.CPtr | t.State: pass
def PyNumber_Or(o1: PyObject | t.CPtr, o2: PyObject | t.CPtr) -> PyObject | t.CPtr | t.State: pass
def PyNumber_Index(obj: PyObject | t.CPtr) -> PyObject | t.CPtr | t.State: pass
def PyNumber_Long(obj: PyObject | t.CPtr) -> PyObject | t.CPtr | t.State: pass
def PyNumber_Float(obj: PyObject | t.CPtr) -> PyObject | t.CPtr | t.State: pass
def PyNumber_Check(obj: PyObject | t.CPtr) -> t.CInt | t.State: pass
# ============================================================
# 弱引用
# ============================================================
def PyWeakref_NewRef(obj: PyObject | t.CPtr, cb: PyObject | t.CPtr) -> PyObject | t.CPtr | t.State: pass
def PyWeakref_GetObject(ref: PyObject | t.CPtr) -> PyObject | t.CPtr | t.State: pass
def PyWeakref_Check(obj: PyObject | t.CPtr) -> t.CInt | t.State: pass
# ============================================================
# 属性描述符
# ============================================================
class PyGetSetDef:
name: t.CConst | str
get: t.CPtr
set: t.CPtr
doc: t.CConst | str
closure: t.CPtr
class PyMemberDef:
name: t.CConst | str
type: t.CInt
offset: t.CPtrDiffT
flags: t.CInt
doc: t.CConst | str
# ============================================================
# sys 模块
# ============================================================
def PySys_GetObject(name: t.CConst | str) -> PyObject | t.CPtr | t.State: pass
def PySys_SetObject(name: t.CConst | str, val: PyObject | t.CPtr) -> t.CInt | t.State: pass
def PySys_ResetWarnOptions() -> t.CVoid | t.State: pass
def PySys_AddWarnOption(s: PyObject | t.CPtr) -> t.CVoid | t.State: pass
def PySYS_AddXOption(s: PyObject | t.CPtr) -> t.CVoid | t.State: pass
def PySys_WriteStdout(fmt: t.CConst | str) -> t.CVoid | t.State: pass
def PySys_WriteStderr(fmt: t.CConst | str) -> t.CVoid | t.State: pass
def PySys_FormatStdout(fmt: t.CConst | str) -> t.CVoid | t.State: pass
def PySys_FormatStderr(fmt: t.CConst | str) -> t.CVoid | t.State: pass
# ============================================================
# 内存视图
# ============================================================
def PyMemoryView_FromObject(obj: PyObject | t.CPtr) -> PyObject | t.CPtr | t.State: pass
def PyMemoryView_GetContiguous(obj: PyObject | t.CPtr, btype: t.CInt, order: t.CChar) -> PyObject | t.CPtr | t.State: pass
def PyMemoryView_Check(obj: PyObject | t.CPtr) -> t.CInt | t.State: pass
# ============================================================
# set / frozenset
# ============================================================
def PySet_New(iterable: PyObject | t.CPtr) -> PyObject | t.CPtr | t.State: pass
def PySet_Add(s: PyObject | t.CPtr, key: PyObject | t.CPtr) -> t.CInt | t.State: pass
def PySet_Discard(s: PyObject | t.CPtr, key: PyObject | t.CPtr) -> t.CInt | t.State: pass
def PySet_Contains(s: PyObject | t.CPtr, key: PyObject | t.CPtr) -> t.CInt | t.State: pass
def PySet_Size(s: PyObject | t.CPtr) -> t.CSizeT | t.State: pass
def PySet_Clear(s: PyObject | t.CPtr) -> t.CVoid | t.State: pass
def PySet_Check(obj: PyObject | t.CPtr) -> t.CInt | t.State: pass
def PyFrozenSet_New(iterable: PyObject | t.CPtr) -> PyObject | t.CPtr | t.State: pass
def PyFrozenSet_Check(obj: PyObject | t.CPtr) -> t.CInt | t.State: pass
# ============================================================
# slice
# ============================================================
def PySlice_New(start: PyObject | t.CPtr, stop: PyObject | t.CPtr, step: PyObject | t.CPtr) -> PyObject | t.CPtr | t.State: pass
def PySlice_GetIndicesEx(sl: PyObject | t.CPtr, length: t.CSizeT, start: t.CSizeT | t.CPtr, stop: t.CSizeT | t.CPtr, step: t.CSizeT | t.CPtr, slicelen: t.CSizeT | t.CPtr) -> t.CInt | t.State: pass
def PySlice_Unpack(sl: PyObject | t.CPtr, start: t.CPtrDiffT | t.CPtr, stop: t.CPtrDiffT | t.CPtr, step: t.CPtrDiffT | t.CPtr) -> t.CVoid | t.State: pass
def PySlice_AdjustIndices(length: t.CSizeT, start: t.CPtrDiffT | t.CPtr, stop: t.CPtrDiffT | t.CPtr, step: t.CPtrDiffT) -> t.CSizeT | t.State: pass
def PySlice_Check(obj: PyObject | t.CPtr) -> t.CInt | t.State: pass
# ============================================================
# 类型包装类 — 带运算符重载
# ============================================================
# --- PyLongObj: Python 整数包装 ---
class PyLongObj:
ptr: PyObject | t.CPtr
def __new__(self) -> 'PyLongObj' | t.CPtr:
return t.CPtr(malloc(PyLongObj.__sizeof__()))
@staticmethod
def from_long(val: t.CLong) -> 'PyLongObj' | t.CPtr:
obj: PyLongObj | t.CPtr = PyLongObj()
obj.ptr = PyLong_FromLong(val)
return obj
def __add__(self, other: PyLongObj | t.CPtr) -> 'PyLongObj' | t.CPtr:
res: PyLongObj | t.CPtr = PyLongObj()
res.ptr = PyNumber_Add(self.ptr, other.ptr)
return res
def __sub__(self, other: PyLongObj | t.CPtr) -> 'PyLongObj' | t.CPtr:
res: PyLongObj | t.CPtr = PyLongObj()
res.ptr = PyNumber_Subtract(self.ptr, other.ptr)
return res
def __mul__(self, other: PyLongObj | t.CPtr) -> 'PyLongObj' | t.CPtr:
res: PyLongObj | t.CPtr = PyLongObj()
res.ptr = PyNumber_Multiply(self.ptr, other.ptr)
return res
def __neg__(self) -> 'PyLongObj' | t.CPtr:
res: PyLongObj | t.CPtr = PyLongObj()
res.ptr = PyNumber_Negative(self.ptr)
return res
def to_long(self) -> t.CLong:
return PyLong_AsLong(self.ptr)
def __str__(self) -> PyObject | t.CPtr:
return PyObject_Str(self.ptr)
def dec_ref(self):
Py_DecRef(self.ptr)
# --- PyFloatObj: Python 浮点数包装 ---
class PyFloatObj:
ptr: PyObject | t.CPtr
def __new__(self) -> 'PyFloatObj' | t.CPtr:
return t.CPtr(malloc(PyFloatObj.__sizeof__()))
@staticmethod
def from_double(val: t.CDouble) -> 'PyFloatObj' | t.CPtr:
obj: PyFloatObj | t.CPtr = PyFloatObj()
obj.ptr = PyFloat_FromDouble(val)
return obj
def __add__(self, other: PyFloatObj | t.CPtr) -> 'PyFloatObj' | t.CPtr:
res: PyFloatObj | t.CPtr = PyFloatObj()
res.ptr = PyNumber_Add(self.ptr, other.ptr)
return res
def __sub__(self, other: PyFloatObj | t.CPtr) -> 'PyFloatObj' | t.CPtr:
res: PyFloatObj | t.CPtr = PyFloatObj()
res.ptr = PyNumber_Subtract(self.ptr, other.ptr)
return res
def __mul__(self, other: PyFloatObj | t.CPtr) -> 'PyFloatObj' | t.CPtr:
res: PyFloatObj | t.CPtr = PyFloatObj()
res.ptr = PyNumber_Multiply(self.ptr, other.ptr)
return res
def __truediv__(self, other: PyFloatObj | t.CPtr) -> 'PyFloatObj' | t.CPtr:
res: PyFloatObj | t.CPtr = PyFloatObj()
res.ptr = PyNumber_TrueDivide(self.ptr, other.ptr)
return res
def __neg__(self) -> 'PyFloatObj' | t.CPtr:
res: PyFloatObj | t.CPtr = PyFloatObj()
res.ptr = PyNumber_Negative(self.ptr)
return res
def to_double(self) -> t.CDouble:
return PyFloat_AsDouble(self.ptr)
def __str__(self) -> PyObject | t.CPtr:
return PyObject_Str(self.ptr)
def dec_ref(self):
Py_DecRef(self.ptr)
# --- PyUnicodeObj: Python 字符串包装 ---
class PyUnicodeObj:
ptr: PyObject | t.CPtr
def __new__(self) -> 'PyUnicodeObj' | t.CPtr:
return t.CPtr(malloc(PyUnicodeObj.__sizeof__()))
@staticmethod
def from_string(s: t.CChar | t.CPtr) -> 'PyUnicodeObj' | t.CPtr:
obj: PyUnicodeObj | t.CPtr = PyUnicodeObj()
obj.ptr = PyUnicode_FromString(s)
return obj
def __add__(self, other: PyUnicodeObj | t.CPtr) -> 'PyUnicodeObj' | t.CPtr:
res: PyUnicodeObj | t.CPtr = PyUnicodeObj()
res.ptr = PyUnicode_Concat(self.ptr, other.ptr)
return res
def __len__(self) -> t.CPtrDiffT:
return PyUnicode_GetLength(self.ptr)
def as_utf8(self) -> t.CChar | t.CPtr:
return PyUnicode_AsUTF8(self.ptr)
def __str__(self) -> PyObject | t.CPtr:
return self.ptr
def dec_ref(self):
Py_DecRef(self.ptr)
# --- PyListObj: Python 列表包装 ---
class PyListObj:
ptr: PyObject | t.CPtr
def __new__(self) -> 'PyListObj' | t.CPtr:
return t.CPtr(malloc(PyListObj.__sizeof__()))
@staticmethod
def new() -> 'PyListObj' | t.CPtr:
obj: PyListObj | t.CPtr = PyListObj()
obj.ptr = PyList_New(0)
return obj
def __getitem__(self, idx: t.CSizeT) -> PyObject | t.CPtr:
return PyList_GetItem(self.ptr, idx)
def __setitem__(self, idx: t.CSizeT, val: PyObject | t.CPtr):
PyList_SetItem(self.ptr, idx, val)
def __len__(self) -> t.CSizeT:
return PyList_Size(self.ptr)
def append(self, item: PyObject | t.CPtr) -> t.CInt:
return PyList_Append(self.ptr, item)
def dec_ref(self):
Py_DecRef(self.ptr)
# --- PyDictObj: Python 字典包装 ---
class PyDictObj:
ptr: PyObject | t.CPtr
def __new__(self) -> 'PyDictObj' | t.CPtr:
return t.CPtr(malloc(PyDictObj.__sizeof__()))
@staticmethod
def new() -> 'PyDictObj' | t.CPtr:
obj: PyDictObj | t.CPtr = PyDictObj()
obj.ptr = PyDict_New()
return obj
def __getitem__(self, key: PyObject | t.CPtr) -> PyObject | t.CPtr:
return PyDict_GetItem(self.ptr, key)
def __setitem__(self, key: PyObject | t.CPtr, val: PyObject | t.CPtr):
PyDict_SetItem(self.ptr, key, val)
def __len__(self) -> t.CSizeT:
return PyDict_Size(self.ptr)
def get_string(self, key: t.CChar | t.CPtr) -> PyObject | t.CPtr:
return PyDict_GetItemString(self.ptr, key)
def set_string(self, key: t.CChar | t.CPtr, val: PyObject | t.CPtr):
PyDict_SetItemString(self.ptr, key, val)
def dec_ref(self):
Py_DecRef(self.ptr)
-359
View File
@@ -1,359 +0,0 @@
import t, c
from t import CInt, CLong, CDouble, CPtr, CSizeT
from stdio import printf
import cpython
import testcheck
def test_init_finalize():
testcheck.section("Py_Initialize / Py_Finalize")
cpython.Py_Initialize()
testcheck.check(cpython.Py_IsInitialized() != 0, "Py_Initialize succeeded", "Py_Initialize succeeded")
cpython.Py_Finalize()
testcheck.check(cpython.Py_IsInitialized() == 0, "Py_Finalize succeeded", "Py_Finalize succeeded")
def test_long_operations():
testcheck.section("PyLong operations")
cpython.Py_Initialize()
# 创建整数
py_num: cpython.PyObject | CPtr = cpython.PyLong_FromLong(12345)
testcheck.check(py_num != 0, "PyLong_FromLong != NULL", "PyLong_FromLong != NULL")
# 整数转字符串
py_str: cpython.PyObject | CPtr = cpython.PyObject_Str(py_num)
testcheck.check(py_str != 0, "PyObject_Str != NULL", "PyObject_Str != NULL")
# 获取 C 字符串
c_str: t.CChar | CPtr = cpython.PyUnicode_AsUTF8(py_str)
testcheck.check(c_str != 0, "PyUnicode_AsUTF8 != NULL", "PyUnicode_AsUTF8 != NULL")
printf(" PyLong_FromLong(12345) -> str = %s\n", c_str)
# 读取回来
val: CLong = cpython.PyLong_AsLong(py_num)
testcheck.check(val == 12345, "PyLong_AsLong == 12345", "PyLong_AsLong == 12345")
# 负数
py_neg: cpython.PyObject | CPtr = cpython.PyLong_FromLong(-999)
neg_val: CLong = cpython.PyLong_AsLong(py_neg)
testcheck.check(neg_val == -999, "PyLong_FromLong(-999) == -999", "PyLong_FromLong(-999) == -999")
# 浮点数转整数
py_dbl: cpython.PyObject | CPtr = cpython.PyFloat_FromDouble(3.14159)
testcheck.check(py_dbl != 0, "PyFloat_FromDouble != NULL", "PyFloat_FromDouble != NULL")
dbl_val: CDouble = cpython.PyFloat_AsDouble(py_dbl)
testcheck.check(dbl_val > 3.14 and dbl_val < 3.15, "PyFloat_AsDouble ~= 3.14", "PyFloat_AsDouble ~= 3.14")
# 清理
cpython.Py_DecRef(py_dbl)
cpython.Py_DecRef(py_neg)
cpython.Py_DecRef(py_str)
cpython.Py_DecRef(py_num)
cpython.Py_Finalize()
def test_string_operations():
testcheck.section("PyUnicode operations")
cpython.Py_Initialize()
# 从 C 字符串创建
py_s1: cpython.PyObject | CPtr = cpython.PyUnicode_FromString("Hello, Viper!")
testcheck.check(py_s1 != 0, "PyUnicode_FromString != NULL", "PyUnicode_FromString != NULL")
# 获取 UTF8
utf8: t.CChar | CPtr = cpython.PyUnicode_AsUTF8(py_s1)
testcheck.check(utf8 != 0, "AsUTF8 != NULL", "AsUTF8 != NULL")
printf(" PyUnicode_FromString -> %s\n", utf8)
# 字符串长度
length: CLong = cpython.PyUnicode_GetLength(py_s1)
testcheck.check(length == 13, "GetLength == 13", "GetLength == 13")
# 字符串拼接
py_s2: cpython.PyObject | CPtr = cpython.PyUnicode_FromString(" World")
py_concat: cpython.PyObject | CPtr = cpython.PyUnicode_Concat(py_s1, py_s2)
concat_utf8: t.CChar | CPtr = cpython.PyUnicode_AsUTF8(py_concat)
testcheck.check(py_concat != 0, "Concat != NULL", "Concat != NULL")
printf(" Concat -> %s\n", concat_utf8)
# 清理
cpython.Py_DecRef(py_concat)
cpython.Py_DecRef(py_s2)
cpython.Py_DecRef(py_s1)
cpython.Py_Finalize()
def test_list_operations():
testcheck.section("PyList operations")
cpython.Py_Initialize()
# 创建列表
py_list: cpython.PyObject | CPtr = cpython.PyList_New(0)
testcheck.check(py_list != 0, "PyList_New != NULL", "PyList_New != NULL")
# Append 元素
py_i1: cpython.PyObject | CPtr = cpython.PyLong_FromLong(10)
py_i2: cpython.PyObject | CPtr = cpython.PyLong_FromLong(20)
py_i3: cpython.PyObject | CPtr = cpython.PyLong_FromLong(30)
cpython.PyList_Append(py_list, py_i1)
cpython.PyList_Append(py_list, py_i2)
cpython.PyList_Append(py_list, py_i3)
# 检查大小
list_size: CSizeT = cpython.PyList_Size(py_list)
testcheck.check(list_size == 3, "PyList_Size == 3", "PyList_Size == 3")
# 获取元素
item0: cpython.PyObject | CPtr = cpython.PyList_GetItem(py_list, 0)
val0: CLong = cpython.PyLong_AsLong(item0)
testcheck.check(val0 == 10, "list[0] == 10", "list[0] == 10")
item2: cpython.PyObject | CPtr = cpython.PyList_GetItem(py_list, 2)
val2: CLong = cpython.PyLong_AsLong(item2)
testcheck.check(val2 == 30, "list[2] == 30", "list[2] == 30")
# 清理
cpython.Py_DecRef(py_i3)
cpython.Py_DecRef(py_i2)
cpython.Py_DecRef(py_i1)
cpython.Py_DecRef(py_list)
cpython.Py_Finalize()
def test_dict_operations():
testcheck.section("PyDict operations")
cpython.Py_Initialize()
# 创建字典
py_dict: cpython.PyObject | CPtr = cpython.PyDict_New()
testcheck.check(py_dict != 0, "PyDict_New != NULL", "PyDict_New != NULL")
# 设置键值对
py_key1: cpython.PyObject | CPtr = cpython.PyUnicode_FromString("name")
py_val1: cpython.PyObject | CPtr = cpython.PyUnicode_FromString("Viper")
cpython.PyDict_SetItem(py_dict, py_key1, py_val1)
py_key2: cpython.PyObject | CPtr = cpython.PyUnicode_FromString("version")
py_val2: cpython.PyObject | CPtr = cpython.PyLong_FromLong(1)
cpython.PyDict_SetItem(py_dict, py_key2, py_val2)
# 检查大小
dict_size: CSizeT = cpython.PyDict_Size(py_dict)
testcheck.check(dict_size == 2, "PyDict_Size == 2", "PyDict_Size == 2")
# 获取值
got_val: cpython.PyObject | CPtr = cpython.PyDict_GetItem(py_dict, py_key1)
testcheck.check(got_val != 0, "GetItem(name) != NULL", "GetItem(name) != NULL")
got_str: t.CChar | CPtr = cpython.PyUnicode_AsUTF8(got_val)
testcheck.check(got_str != 0, "name == Viper", "name == Viper")
printf(" dict['name'] = %s\n", got_str)
# 使用 GetItemString
got_ver: cpython.PyObject | CPtr = cpython.PyDict_GetItemString(py_dict, "version")
testcheck.check(got_ver != 0, "GetItemString(version) != NULL", "GetItemString(version) != NULL")
ver_val: CLong = cpython.PyLong_AsLong(got_ver)
testcheck.check(ver_val == 1, "version == 1", "version == 1")
# 清理
cpython.Py_DecRef(py_val2)
cpython.Py_DecRef(py_key2)
cpython.Py_DecRef(py_val1)
cpython.Py_DecRef(py_key1)
cpython.Py_DecRef(py_dict)
cpython.Py_Finalize()
def test_pyrun_string():
testcheck.section("PyRun_SimpleString")
cpython.Py_Initialize()
# 执行简单 Python 代码
rc: CInt = cpython.PyRun_SimpleString("print('Hello from embedded Python!')")
testcheck.check(rc == 0, "PyRun_SimpleString == 0", "PyRun_SimpleString == 0")
# 执行赋值
rc2: CInt = cpython.PyRun_SimpleString("x = 6 * 7")
testcheck.check(rc2 == 0, "PyRun_SimpleString(assign) == 0", "PyRun_SimpleString(assign) == 0")
# 读取结果
rc3: CInt = cpython.PyRun_SimpleString("print(f'The answer is {x}')")
testcheck.check(rc3 == 0, "PyRun_SimpleString(print) == 0", "PyRun_SimpleString(print) == 0")
cpython.Py_Finalize()
def test_import_module():
testcheck.section("PyImport_ImportModule")
cpython.Py_Initialize()
# 导入 math 模块
math_mod: cpython.PyObject | CPtr = cpython.PyImport_ImportModule("math")
testcheck.check(math_mod != 0, "import math != NULL", "import math != NULL")
if math_mod != 0:
# 获取 math.pi
pi_val: cpython.PyObject | CPtr = cpython.PyObject_GetAttrString(math_mod, "pi")
testcheck.check(pi_val != 0, "math.pi != NULL", "math.pi != NULL")
if pi_val != 0:
pi_dbl: CDouble = cpython.PyFloat_AsDouble(pi_val)
testcheck.check(pi_dbl > 3.14 and pi_dbl < 3.15, "math.pi ~= 3.14", "math.pi ~= 3.14")
printf(" math.pi = %f\n", pi_dbl)
cpython.Py_DecRef(pi_val)
# 获取 math.sqrt 函数
sqrt_func: cpython.PyObject | CPtr = cpython.PyObject_GetAttrString(math_mod, "sqrt")
testcheck.check(sqrt_func != 0, "math.sqrt != NULL", "math.sqrt != NULL")
if sqrt_func != 0:
cpython.Py_DecRef(sqrt_func)
cpython.Py_DecRef(math_mod)
cpython.Py_Finalize()
def test_operator_overload():
testcheck.section("Operator Overload (PyLongObj / PyFloatObj / PyUnicodeObj / PyListObj / PyDictObj)")
cpython.Py_Initialize()
# --- PyLongObj: from_long, to_long, +, -, *, - (neg) ---
a: cpython.PyLongObj | CPtr = cpython.PyLongObj.from_long(10)
b: cpython.PyLongObj | CPtr = cpython.PyLongObj.from_long(3)
testcheck.check(a != 0 and b != 0, "PyLongObj.from_long != NULL", "PyLongObj.from_long != NULL")
add_r: cpython.PyLongObj | CPtr = a + b
testcheck.check(add_r.to_long() == 13, "PyLongObj 10 + 3 == 13", "PyLongObj 10 + 3 == 13")
sub_r: cpython.PyLongObj | CPtr = a - b
testcheck.check(sub_r.to_long() == 7, "PyLongObj 10 - 3 == 7", "PyLongObj 10 - 3 == 7")
mul_r: cpython.PyLongObj | CPtr = a * b
testcheck.check(mul_r.to_long() == 30, "PyLongObj 10 * 3 == 30", "PyLongObj 10 * 3 == 30")
neg_r: cpython.PyLongObj | CPtr = -b
testcheck.check(neg_r.to_long() == -3, "PyLongObj -3 == -3", "PyLongObj -3 == -3")
mul_r.dec_ref()
sub_r.dec_ref()
add_r.dec_ref()
neg_r.dec_ref()
b.dec_ref()
a.dec_ref()
# --- PyFloatObj: from_double, to_double, +, -, *, /, - (neg) ---
fa: cpython.PyFloatObj | CPtr = cpython.PyFloatObj.from_double(10.0)
fb: cpython.PyFloatObj | CPtr = cpython.PyFloatObj.from_double(4.0)
testcheck.check(fa != 0 and fb != 0, "PyFloatObj.from_double != NULL", "PyFloatObj.from_double != NULL")
fadd: cpython.PyFloatObj | CPtr = fa + fb
testcheck.check(fadd.to_double() == 14.0, "PyFloatObj 10.0 + 4.0 == 14.0", "PyFloatObj 10.0 + 4.0 == 14.0")
fsub: cpython.PyFloatObj | CPtr = fa - fb
testcheck.check(fsub.to_double() == 6.0, "PyFloatObj 10.0 - 4.0 == 6.0", "PyFloatObj 10.0 - 4.0 == 6.0")
fmul: cpython.PyFloatObj | CPtr = fa * fb
testcheck.check(fmul.to_double() == 40.0, "PyFloatObj 10.0 * 4.0 == 40.0", "PyFloatObj 10.0 * 4.0 == 40.0")
fdiv: cpython.PyFloatObj | CPtr = fa / fb
testcheck.check(fdiv.to_double() == 2.5, "PyFloatObj 10.0 / 4.0 == 2.5", "PyFloatObj 10.0 / 4.0 == 2.5")
fneg: cpython.PyFloatObj | CPtr = -fb
testcheck.check(fneg.to_double() == -4.0, "PyFloatObj -4.0 == -4.0", "PyFloatObj -4.0 == -4.0")
fadd.dec_ref()
fsub.dec_ref()
fmul.dec_ref()
fdiv.dec_ref()
fneg.dec_ref()
fb.dec_ref()
fa.dec_ref()
# --- PyUnicodeObj: from_string, as_utf8, len, + (concat) ---
sa: cpython.PyUnicodeObj | CPtr = cpython.PyUnicodeObj.from_string("Hello")
sb: cpython.PyUnicodeObj | CPtr = cpython.PyUnicodeObj.from_string(" World")
testcheck.check(sa != 0 and sb != 0, "PyUnicodeObj.from_string != NULL", "PyUnicodeObj.from_string != NULL")
sc: cpython.PyUnicodeObj | CPtr = sa + sb
sc_utf8: t.CChar | CPtr = sc.as_utf8()
testcheck.check(sc_utf8 != 0, "PyUnicodeObj concat != NULL", "PyUnicodeObj concat != NULL")
if sc_utf8 != 0:
printf(" PyUnicodeObj 'Hello' + ' World' = %s\n", sc_utf8)
sa_len: t.CPtrDiffT = len(sa)
testcheck.check(sa_len == 5, "PyUnicodeObj len('Hello') == 5", "PyUnicodeObj len('Hello') == 5")
sc.dec_ref()
sb.dec_ref()
sa.dec_ref()
# --- PyListObj: new, append, len, [], []= ---
lst: cpython.PyListObj | CPtr = cpython.PyListObj.new()
testcheck.check(lst != 0, "PyListObj.new != NULL", "PyListObj.new != NULL")
if lst != 0:
e1: cpython.PyObject | CPtr = cpython.PyLong_FromLong(100)
e2: cpython.PyObject | CPtr = cpython.PyLong_FromLong(200)
e3: cpython.PyObject | CPtr = cpython.PyLong_FromLong(300)
lst.append(e1)
lst.append(e2)
lst.append(e3)
testcheck.check(len(lst) == 3, "PyListObj len == 3", "PyListObj len == 3")
item0: cpython.PyObject | CPtr = lst[t.CSizeT(0)]
testcheck.check(cpython.PyLong_AsLong(item0) == 100, "PyListObj lst[0] == 100", "PyListObj lst[0] == 100")
# __setitem__
e4: cpython.PyObject | CPtr = cpython.PyLong_FromLong(999)
lst[t.CSizeT(1)] = e4
item1: cpython.PyObject | CPtr = lst[t.CSizeT(1)]
testcheck.check(cpython.PyLong_AsLong(item1) == 999, "PyListObj lst[1] = 999", "PyListObj lst[1] = 999")
cpython.Py_DecRef(e4)
cpython.Py_DecRef(e3)
cpython.Py_DecRef(e2)
cpython.Py_DecRef(e1)
lst.dec_ref()
# --- PyDictObj: new, [], []=, len, set_string, get_string ---
dct: cpython.PyDictObj | CPtr = cpython.PyDictObj.new()
testcheck.check(dct != 0, "PyDictObj.new != NULL", "PyDictObj.new != NULL")
if dct != 0:
dk1: cpython.PyObject | CPtr = cpython.PyUnicode_FromString("lang")
dv1: cpython.PyObject | CPtr = cpython.PyUnicode_FromString("Viper")
dct[dk1] = dv1
testcheck.check(len(dct) == 1, "PyDictObj len == 1", "PyDictObj len == 1")
got_lang: cpython.PyObject | CPtr = dct[dk1]
got_str: t.CChar | CPtr = cpython.PyUnicode_AsUTF8(got_lang)
testcheck.check(got_str != 0, "PyDictObj dct['lang'] == Viper", "PyDictObj dct['lang'] == Viper")
if got_str != 0:
printf(" PyDictObj dct['lang'] = %s\n", got_str)
# get_string / set_string
dct.set_string("ver", cpython.PyLong_FromLong(3))
got_ver: cpython.PyObject | CPtr = dct.get_string("ver")
testcheck.check(got_ver != 0 and cpython.PyLong_AsLong(got_ver) == 3, "PyDictObj get_string('ver') == 3", "PyDictObj get_string('ver') == 3")
cpython.Py_DecRef(dv1)
cpython.Py_DecRef(dk1)
dct.dec_ref()
cpython.Py_Finalize()
def main() -> CInt | t.CExport:
testcheck.begin("CPython Integration Test")
test_init_finalize()
test_long_operations()
test_string_operations()
test_list_operations()
test_dict_operations()
test_pyrun_string()
test_import_module()
test_operator_overload()
return testcheck.end()
@@ -1 +0,0 @@
{"stdio": "285b6aa29a34754d", "cpython": "7081f34a72ebafa8", "testcheck": "748d0424e8976fa0", "w32.win32console": "bbdf3bbd4c3bc28c", "win32console": "bbdf3bbd4c3bc28c", "stdint": "f5522571bcce7bcb", "w32.win32base": "fc980acec33d69a7", "win32base": "fc980acec33d69a7"}
-35
View File
@@ -1,35 +0,0 @@
{
"$schema": "https://raw.githubusercontent.com/TermiNexus/TransPyC/main/schemas/project-schema.json",
"name": "CPythonTest",
"version": "1.0.0",
"source_dir": "./App",
"build_dir": "./.tpv_build",
"compiler": {
"cmd": "llc",
"flags": ["-filetype=obj", "-relocation-model=pic"]
},
"linker": {
"cmd": "clang++",
"flags": [
"-L", "D:\\Python312\\libs",
"-lmsvcrt", "-lucrt", "-lpthread", "-lmingwex",
"-lkernel32", "-luser32",
"-lpython312",
"-Wl,--allow-multiple-definition"
],
"output": "CPythonTest.exe"
},
"includes": [
"../../includes"
],
"target": {
"triple": "x86_64-pc-windows-gnu",
"datalayout": "e-m:w-p270:32:32-p271:32:32-p272:64:64-i64:64-f80:128-n8:16:32:64-S128"
},
"options": {
"slice_level": 3,
"sha1_slice_level": 1,
"target": "llvm",
"strict_mode": false
}
}
Whitespace-only changes.
@@ -1,23 +0,0 @@
"""
Auto-generated Python stub file from stdio.vp
Module: stdio
"""
import t, c
def printf(fmt: t.CConst | str, *args) -> int | t.State: pass
def fprintf(stream: bytes, fmt: t.CConst | str, *args) -> int | t.State: pass
def sprintf(buf: bytes, fmt: t.CConst | str, *args) -> int | t.State: pass
def snprintf(buf: bytes, size: t.CSizeT, fmt: t.CConst | str, *args) -> int | t.State: pass
def puts(s: t.CConst | str) -> int | t.State: pass
def fputs(s: t.CConst | str, stream: bytes) -> int | t.State: pass
def fgets(buf: bytes, size: int, stream: bytes) -> bytes | t.State: pass
def fflush(stream: bytes) -> int | t.State: pass
Loaded 100 of 3250 files, more files were not shown because too many files have changed in this diff. Show more