├── .gitignore ├── Dockerfile ├── LICENSE.txt ├── MANIFEST.in ├── README.md ├── inlinec.pth ├── inlinec ├── __init__.py ├── codec │ ├── __init__.py │ ├── compile.py │ ├── parser.py │ └── register.py └── inlinec.py ├── pytest.ini ├── setup.cfg ├── setup.py └── tests └── test_param.py /.gitignore: -------------------------------------------------------------------------------- 1 | .venv 2 | build 3 | dist 4 | **/**/__pycache__ 5 | .python-version 6 | .vscode 7 | *.c 8 | *.o 9 | *.cpython* 10 | **/**/*egg* 11 | *.ipynb* 12 | *.out* 13 | *.pytest* -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM ubuntu:latest 2 | 3 | COPY / /home 4 | 5 | WORKDIR /home 6 | 7 | RUN apt update && \ 8 | apt install -y python3.8 python3.8-dev python3-pip && \ 9 | python3.8 setup.py install 10 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include inlinec.pth -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Inline C 2 | Effortlessly write inline C functions in Python source code 3 | ```python 4 | # coding: inlinec 5 | from inlinec import inlinec 6 | 7 | @inlinec 8 | def Q_rsqrt(number): 9 | float Q_rsqrt( float number ) 10 | { 11 | long i; 12 | float x2, y; 13 | const float threehalfs = 1.5F; 14 | 15 | x2 = number * 0.5F; 16 | y = number; 17 | i = * ( long * ) &y; // evil floating point bit level hacking 18 | i = 0x5f3759df - ( i >> 1 ); // what the fuck? 19 | y = * ( float * ) &i; 20 | y = y * ( threehalfs - ( x2 * y * y ) ); // 1st iteration 21 | 22 | return y; 23 | } 24 | 25 | print(Q_rsqrt(1.234)) 26 | ``` 27 | Inlinec supports gnu-specific c extensions, so you're likely to have reasonable success #includeing glibc headers. 28 | 29 | Inspired by [Pyxl](https://github.com/pyxl4/pyxl4) 30 | 31 | # How does this work? 32 | Python has a mechanism for creating custom codecs, which given an input token stream, produce an output token stream. Inlinec consumes the entire token stream, runs a fault-tolerant parser on it ([parso](https://github.com/davidhalter/parso)), finds which function nodes are annotated with an `@inlinec` decorator, creates a `ctypes` wrapper for the content of the function, and replaces the function body with a call to the ctypes wrapper. The import for the wrapper is lifted to the top of the file. Once this transformation has been made, the source code is re-tokenized and the Python interpreter only sees the transformed source. 33 | So a function like this: 34 | ```python 35 | @inlinec 36 | def test(): 37 | #include 38 | void test() { 39 | printf("Hello, world"); 40 | } 41 | ``` 42 | Gets turned into: 43 | ```python 44 | from test_8281231239129310 import lib as test_8281231239129310_lib, ffii as test_8281231239129310_ffi 45 | 46 | @inlinec 47 | def test(): 48 | return test_8281231239129310_lib.test() 49 | ``` 50 | In theory, this allows inline c functions to be called with a one-time compilation overhead and the same performance characteristics as ctypes -- the underlying FFI library. 51 | 52 | # Limitations 53 | Note: This is just a proof of concept 54 | 55 | * Passing pointers to C functions does not currently work (aside from strings) 56 | * Shells out to `gcc -E` to preprocess the source code 57 | * Compilation is not cached and takes a long time every run 58 | * Compilation pollutes the current directory with .so, .o, .c files 59 | * The source file is parsed multiple times unnecessarily 60 | * Many more 61 | 62 | 63 | # Installation 64 | Inlinec requires a C compiler to be installed on the system (tested with GCC and Clang), as well as the python development libraries to be installed (python3-dev). 65 | To play around with it in a container you can use the provided Dockerfile, just run docker build, exec into a shell in the container, and you have a working installation of inlinec. 66 | ```bash 67 | > docker build -t inlinec . && docker run -it inlinec bash 68 | ``` -------------------------------------------------------------------------------- /inlinec.pth: -------------------------------------------------------------------------------- 1 | import inlinec.codec.register -------------------------------------------------------------------------------- /inlinec/__init__.py: -------------------------------------------------------------------------------- 1 | from .inlinec import inlinec -------------------------------------------------------------------------------- /inlinec/codec/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ssize-t/inlinec/20eca6bf8556a77906ba5f420f09006d6daf4355/inlinec/codec/__init__.py -------------------------------------------------------------------------------- /inlinec/codec/compile.py: -------------------------------------------------------------------------------- 1 | from typing import * 2 | from cffi import FFI 3 | from pycparserext.ext_c_parser import GnuCParser 4 | from pycparser import c_ast 5 | from subprocess import Popen, PIPE 6 | 7 | 8 | def extract_signature( 9 | func_name: str, body: str 10 | ) -> Optional[Tuple[str, List[Tuple[str, str]]]]: 11 | signature = None 12 | 13 | class FuncDefVisitor(c_ast.NodeVisitor): 14 | def visit_FuncDeclExt(self, node): 15 | nonlocal signature # bad 16 | # so much badness below 17 | def get_typ_str(node): 18 | if isinstance(node, c_ast.PtrDecl): 19 | return f"{' '.join(node.type.type.names)}*" 20 | else: 21 | return " ".join(node.type.names) 22 | 23 | def get_arg_name(node): 24 | if isinstance(node, c_ast.PtrDecl): 25 | return node.type.declname 26 | else: 27 | return node.declname 28 | 29 | if get_arg_name(node.children()[1][1]) == func_name: 30 | return_typ = get_typ_str(node.children()[1][1]) 31 | params = node.children()[0][1] 32 | signature = ( 33 | return_typ, 34 | [(get_arg_name(p.type), get_typ_str(p.type)) for p in params] 35 | if params 36 | else [], 37 | ) 38 | 39 | parser = GnuCParser() 40 | ast = parser.parse(body) 41 | v = FuncDefVisitor() 42 | v.visit(ast) 43 | # ast.show() 44 | 45 | return signature 46 | 47 | 48 | def preprocess(src: str) -> str: 49 | # pcpp does not work correctly with includes, plus it evals #ifs 50 | # Typedef gcc directives to satisfy pycparser 51 | # src = '''#define __attribute__(x) 52 | # #define __extension__ 53 | # #define __inline 54 | # #define __restrict 55 | # #definie __asm__ 56 | # ''' + src 57 | p = Popen(["gcc", "-E", "-"], stdout=PIPE, stdin=PIPE, stderr=PIPE) 58 | src = p.communicate(input=src.encode("ascii"))[0].decode() 59 | # from pcpp import Preprocessor 60 | # p = Preprocessor() 61 | # p.add_path('/Library/Developer/CommandLineTools/usr/lib/clang/11.0.0/include') 62 | # p.parse(src) 63 | # oh = StringIO() 64 | # p.write(oh) 65 | # src = oh.getvalue() 66 | return src 67 | 68 | 69 | def compile( 70 | module_name: str, func_name: str, src: str 71 | ) -> Tuple[str, List[Tuple[str, str]]]: 72 | preprocessed_src = preprocess(src) 73 | sig = extract_signature(func_name, preprocessed_src) 74 | if not sig: 75 | raise Exception("Failed to extract signature for %s", func_name) 76 | ffibuilder = FFI() 77 | ffibuilder.dlopen(None) 78 | ffibuilder.cdef(f"{sig[0]} {func_name}({','.join(v[1] for v in sig[1])});") 79 | 80 | ffibuilder.set_source(module_name, src) 81 | ffibuilder.compile(verbose=False) 82 | 83 | return sig 84 | -------------------------------------------------------------------------------- /inlinec/codec/parser.py: -------------------------------------------------------------------------------- 1 | import parso 2 | from parso.python.tree import PythonNode 3 | from typing import * 4 | from tokenize import generate_tokens, TokenInfo, INDENT 5 | from io import StringIO 6 | from uuid import uuid4 7 | from inlinec.codec.compile import compile 8 | 9 | 10 | def token_at(line_no: int, typ: int, tokens: List[TokenInfo]) -> Optional[TokenInfo]: 11 | for t in tokens: 12 | if t.start[0] >= line_no and t.type == typ: 13 | return t 14 | 15 | 16 | def ffc(typ: str, node: PythonNode) -> Optional[PythonNode]: 17 | for x in node.children: 18 | if x.type == typ: 19 | return x 20 | 21 | 22 | def find_decorated_nodes(mod: PythonNode) -> List[PythonNode]: 23 | decorated = [] 24 | q = [mod] 25 | while q: 26 | n = q.pop() 27 | if not hasattr(n, "children"): 28 | continue 29 | decorator_found = False 30 | for x in n.children: 31 | if not decorator_found and x.type == "decorator": 32 | name = ffc("name", x).value 33 | if name == "inlinec": 34 | decorator_found = True 35 | continue 36 | elif decorator_found and x.type == "funcdef": 37 | decorated.append(x) 38 | if hasattr(x, "children"): 39 | q.append(x) 40 | 41 | return decorated 42 | 43 | 44 | def chain(start_val, *funcs): 45 | v = start_val 46 | for f in funcs: 47 | vp = f(v) 48 | if not vp: 49 | return None 50 | v = vp 51 | return v 52 | 53 | 54 | def gen_call( 55 | qual: str, 56 | func_name: str, 57 | params: List[Tuple[str, str]], 58 | return_typ: str, 59 | annotated_params: Dict[str, str], 60 | ) -> str: 61 | convert_params = [] 62 | for param, typ in params: 63 | param = ( 64 | f'{param}.encode("ascii")' if typ == "char*" else 65 | f'{param}.encode("ascii")' if typ == "char" else 66 | param 67 | ) 68 | convert_params.append(param) 69 | convert_ret = ( 70 | (lambda ret_val: f'{qual}_ffi.string({ret_val}).decode("ascii")') 71 | if return_typ == "char*" 72 | else lambda ret_val: ret_val 73 | ) 74 | return "return " + convert_ret(f'{qual}_lib.{func_name}({",".join([p for p in convert_params if p is not None])})') 75 | 76 | 77 | def gen_import(qual: str) -> str: 78 | return f"from {qual} import lib as {qual}_lib, ffi as {qual}_ffi\n" 79 | 80 | def gen_qual(alias: str, func_name: str) -> str: 81 | return f'{alias}__{func_name}' 82 | 83 | def transform(lines: List[str]) -> str: 84 | src = "".join(lines) 85 | mod = parso.parse(src) 86 | tokens = list(generate_tokens(StringIO(src).readline)) 87 | cfuncs = find_decorated_nodes(mod) 88 | aliases = {cf: str(uuid4()).replace('-', '_') for cf in cfuncs} 89 | imports = ["\n"] + [gen_import(gen_qual(cf.name.value, alias)) for cf, alias in aliases.items()] 90 | lines = imports + lines[1:] 91 | offset = len(imports) - 1 92 | 93 | for func in cfuncs: 94 | name = func.name.value 95 | alias = aliases[func] 96 | qual = gen_qual(name, alias) 97 | startl = func.start_pos[0] + offset 98 | endl = func.end_pos[0] + offset 99 | body = "".join(lines[startl:endl]) 100 | 101 | sig = compile(qual, func.name.value, body) 102 | 103 | annotated_params = {} 104 | for p in func.get_params(): 105 | if p.annotation: 106 | annotated_params[p.name.value] = p.annotation.value 107 | 108 | indent = token_at(startl - offset, INDENT, tokens).string 109 | lines[startl] = indent + gen_call( 110 | qual, name, sig[1], sig[0], annotated_params 111 | ) 112 | for i in range(startl + 1, endl - 1): 113 | lines[i] = "" 114 | 115 | return "".join(lines) 116 | -------------------------------------------------------------------------------- /inlinec/codec/register.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import codecs, io, encodings 3 | from encodings import utf_8 4 | from inlinec.codec.parser import transform 5 | 6 | 7 | def inlinec_transform(stream): 8 | output = transform(stream.readlines()) 9 | return output.rstrip() 10 | 11 | 12 | def inlinec_transform_string(input): 13 | stream = io.StringIO(bytes(input).decode("utf-8")) 14 | return inlinec_transform(stream) 15 | 16 | 17 | def inlinec_decode(input, errors="strict"): 18 | return inlinec_transform_string(input), len(input) 19 | 20 | 21 | class InlinecIncrementalDecoder(utf_8.IncrementalDecoder): 22 | def decode(self, input, final=False): 23 | self.buffer += input 24 | if final: 25 | buff = self.buffer 26 | self.buffer = b"" 27 | return super(InlinecIncrementalDecoder, self).decode( 28 | inlinec_transform_string(buff).encode("utf-8"), final=True 29 | ) 30 | else: 31 | return "" 32 | 33 | 34 | class InlinecStreamReader(utf_8.StreamReader): 35 | def __init__(self, *args, **kwargs): 36 | codecs.StreamReader.__init__(self, *args, **kwargs) 37 | self.stream = io.StringIO(inlinec_transform(self.stream)) 38 | 39 | 40 | def search_function(encoding): 41 | if encoding != "inlinec": 42 | return None 43 | utf8 = encodings.search_function("utf8") 44 | return codecs.CodecInfo( 45 | name="inlinec", 46 | encode=utf8.encode, 47 | decode=inlinec_decode, 48 | incrementalencoder=utf8.incrementalencoder, 49 | incrementaldecoder=InlinecIncrementalDecoder, 50 | streamreader=InlinecStreamReader, 51 | streamwriter=utf8.streamwriter, 52 | ) 53 | 54 | 55 | codecs.register(search_function) 56 | -------------------------------------------------------------------------------- /inlinec/inlinec.py: -------------------------------------------------------------------------------- 1 | def inlinec(func): 2 | return func -------------------------------------------------------------------------------- /pytest.ini: -------------------------------------------------------------------------------- 1 | [pytest] 2 | doctest_encoding = inlinec -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [metadata] 2 | description-file = README.md -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup 2 | from distutils.sysconfig import get_python_lib 3 | 4 | SITE_PACKAGES_PATH = get_python_lib() 5 | 6 | setup( 7 | name="inlinec", 8 | version="0.0.1", 9 | packages=["inlinec", "inlinec.codec"], 10 | description="Effortlessly write inline C functions", 11 | author="George Kharchenko", 12 | author_email="kharchenko.george@gmail.com", 13 | keywords=["C", "inline", "ffi", "ctypes", "pyxl"], 14 | download_url="https://github.com/georgek42/inlinec/archive/0.0.1.tar.gz", 15 | data_files=[(SITE_PACKAGES_PATH, ["inlinec.pth"])], 16 | install_requires=["parso", "pycparserext", "cffi"], 17 | ) 18 | 19 | -------------------------------------------------------------------------------- /tests/test_param.py: -------------------------------------------------------------------------------- 1 | # coding: inlinec 2 | from inlinec import inlinec 3 | from pytest import raises 4 | 5 | def test_char_arg(): 6 | @inlinec 7 | def test_char_arg(a): 8 | _Bool test_char_arg(char a) { 9 | return a == 'a'; 10 | } 11 | 12 | assert test_char_arg('a') 13 | 14 | def test_int_arg(): 15 | @inlinec 16 | def test_int_arg(a): 17 | _Bool test_int_arg(int a) { 18 | return a == 1; 19 | } 20 | 21 | assert test_int_arg(1) 22 | 23 | def test_bool_arg(): 24 | @inlinec 25 | def test_bool_arg(t): 26 | _Bool test_bool_arg(_Bool t) { 27 | return t == 1; 28 | } 29 | 30 | assert test_bool_arg(True) 31 | assert not test_bool_arg(False) 32 | 33 | def test_wchar_t_arg(): 34 | @inlinec 35 | def test_wchar_t_arg(t): 36 | #include 37 | _Bool test_wchar_t_arg(wchar_t t) { 38 | return t == L'\x57'; 39 | } 40 | 41 | assert test_wchar_t_arg('W') 42 | 43 | def test_uchar_arg(): 44 | @inlinec 45 | def test_byte_arg(b): 46 | _Bool test_byte_arg(unsigned char b) { 47 | return b == 0; 48 | } 49 | 50 | assert test_byte_arg(0) 51 | 52 | def test_short_arg(): 53 | @inlinec 54 | def test_short_arg(c): 55 | _Bool test_short_arg(short c) { 56 | return c == 32767; 57 | } 58 | 59 | assert test_short_arg(32767) 60 | 61 | with raises(OverflowError): 62 | test_short_arg(99999) 63 | 64 | with raises(OverflowError): 65 | test_short_arg(-99999) 66 | 67 | def test_ushort_arg(): 68 | @inlinec 69 | def test_ushort_arg(c): 70 | _Bool test_ushort_arg(unsigned short c) { 71 | return c == 32767; 72 | } 73 | 74 | assert test_ushort_arg(32767) 75 | 76 | with raises(OverflowError): 77 | assert test_ushort_arg(-32767) 78 | 79 | def test_int_arg(): 80 | @inlinec 81 | def test_int_arg(i): 82 | _Bool test_int_arg(int i) { 83 | return i == 123456; 84 | } 85 | 86 | assert test_int_arg(123456) 87 | 88 | def test_uint_arg(): 89 | @inlinec 90 | def test_uint_arg(i): 91 | _Bool test_uint_arg(unsigned int i) { 92 | return i == 123456; 93 | } 94 | 95 | test_uint_arg(123456) 96 | 97 | with raises(OverflowError): 98 | test_uint_arg(-123456) 99 | 100 | def test_long_arg(): 101 | @inlinec 102 | def test_long_arg(i): 103 | _Bool test_long_arg(long i) { 104 | return i == 2147483647; 105 | } 106 | 107 | test_long_arg(2147483647) 108 | 109 | def test_ulong_arg(): 110 | @inlinec 111 | def test_ulong_arg(i): 112 | _Bool test_ulong_arg(unsigned long i) { 113 | return i == 4294967295; 114 | } 115 | 116 | test_ulong_arg(4294967295); 117 | 118 | with raises(OverflowError): 119 | test_ulong_arg(-1) 120 | 121 | def test_long_long_arg(): 122 | @inlinec 123 | def test_long_long_arg(i): 124 | _Bool test_long_long_arg(long long i) { 125 | return i == 9223372036854775806; 126 | } 127 | 128 | test_long_long_arg(9223372036854775806) 129 | 130 | def test_ulong_long_arg(): 131 | @inlinec 132 | def test_ulong_long_arg(i): 133 | _Bool test_ulong_long_arg(unsigned long long i) { 134 | return i == 18446744073709551613UL; 135 | } 136 | 137 | test_ulong_long_arg(18446744073709551613) 138 | 139 | with raises(OverflowError): 140 | test_ulong_long_arg(-1) 141 | 142 | def test_size_t_arg(): 143 | @inlinec 144 | def test_size_t_arg(i): 145 | typedef long unsigned int size_t; 146 | _Bool test_size_t_arg(size_t i) { 147 | return i == 9223372036854775806; 148 | } 149 | 150 | test_size_t_arg(9223372036854775806) 151 | 152 | with raises(OverflowError): 153 | test_size_t_arg(-1) 154 | 155 | def test_ssize_t_arg(): 156 | @inlinec 157 | def test_ssize_t_arg(i): 158 | # include 159 | _Bool test_ssize_t_arg(ssize_t i) { 160 | return i == -1; 161 | } 162 | 163 | test_ssize_t_arg(-1) 164 | 165 | def test_float_arg(): 166 | @inlinec 167 | def test_float_arg(f): 168 | _Bool test_float_arg(float f) { 169 | return f == 340282346638528859811704183484516925440.0000000000000000; 170 | } 171 | 172 | test_float_arg(340282346638528859811704183484516925440.0000000000000000) 173 | 174 | def test_double_arg(): 175 | @inlinec 176 | def test_double_arg(d): 177 | _Bool test_double_arg(double d) { 178 | return d == 179769313486231570814527423731704356798070567525844996598917476803157260780028538760589558632766878171540458953514382464234321326889464182768467546703537516986049910576551282076245490090389328944075868508455133942304583236903222948165808559332123348274797826204144723168738177180919299881250404026184124858368.000000000000000; 179 | } 180 | 181 | test_double_arg(179769313486231570814527423731704356798070567525844996598917476803157260780028538760589558632766878171540458953514382464234321326889464182768467546703537516986049910576551282076245490090389328944075868508455133942304583236903222948165808559332123348274797826204144723168738177180919299881250404026184124858368.000000000000000) 182 | 183 | def test_long_double_arg(): 184 | @inlinec 185 | def test_long_double_arg(ld): 186 | _Bool test_long_double_arg(long double ld) { 187 | return ld == 179769313486231570814527423731704356798070567525844996598917476803157260780028538760589558632766878171540458953514382464234321326889464182768467546703537516986049910576551282076245490090389328944075868508455133942304583236903222948165808559332123348274797826204144723168738177180919299881250404026184124858368.000000000000000; 188 | } 189 | 190 | test_long_double_arg(179769313486231570814527423731704356798070567525844996598917476803157260780028538760589558632766878171540458953514382464234321326889464182768467546703537516986049910576551282076245490090389328944075868508455133942304583236903222948165808559332123348274797826204144723168738177180919299881250404026184124858368.000000000000000) 191 | 192 | def test_c_char_p_arg(): 193 | @inlinec 194 | def test_c_char_p_arg(s): 195 | #include 196 | _Bool test_c_char_p_arg(char *s) { 197 | return strcmp(s, "Hello, world!"); 198 | } 199 | 200 | test_c_char_p_arg("Hello, world!") 201 | 202 | def test_wchar_p_arg(): 203 | @inlinec 204 | def test_wchar_p_arg(t): 205 | #include 206 | _Bool test_wchar_p_arg(wchar_t *t) { 207 | return wcscmp(t, L"Helloo"); 208 | } 209 | 210 | assert test_wchar_p_arg('Hello') 211 | --------------------------------------------------------------------------------