Skip to main content

一个将python函数翻译为c++函数并运行的jit编译器

Project description

将python函数翻译为c++函数并运行

1. 安装

pip install l0n0lc

2. hello_world.py

import l0n0lc as lc
import math


@lc.映射函数(math.ceil, ['<cmath>'])
def cpp_ceil(v):
    return f'std::ceil({lc.toCString(v)});'


@lc.映射函数(print, ['<iostream>'])
def cpp_cout(*args):
    code = f'std::cout'
    for arg in args:
        code += f'<< {lc.toCString(arg)} << " "'
    code += '<< std::endl;'
    return code


def py_cin(v):
    pass


@lc.映射函数(py_cin, ['<iostream>'])
def cpp_cin(v):
    return f'std::cout << u8"请输入>>>"; std::cin >> {v};'


@lc.直接调用函数
def test_直接调用():
    return 123


def test_other_fn(a: int, b: int) -> int:
    return a - b


@lc.jit()
def test编译的函数(a: int, b: int) -> int:
    return a * b


@lc.jit(每次运行都重新编译=True)
def test_add(a: int, b: int) -> int:
    if a > 1:
        return a + b
    for i in range(1, 10, 2):
        a += i
    for i in [1, 2, 3]:
        a += i
    a = math.ceil(12.5)
    cc = {'a': 1, 'b': 2}
    cc['c'] = 3
    print('输出map:')
    for ii in cc:
        print(ii.first, ii.second)  # type: ignore
    aa = [1, 3, 2]
    aa[0] = 134
    print('输出list:')
    for i in range(3):
        print(i, aa[i])
    print('Hello World', a, b)
    print('test_other_fn', test_other_fn(a, b))
    print('test编译的函数', test编译的函数(a, b))
    v = 0
    vv = True and (False or 1)
    print('vv:', vv)
    while (True):
        py_cin(v)
        if v > 100:
            break
        else:
            print('输入的', v, '小于等于100')
    return a + b + 1 + test_直接调用() + v


print('结果:', test_add(1, 3))

3. 运行hello_world.py

uv run tests/hello_world.py
# 输入: b'1\n2\n100\n101\n'
Module(
  body=[
    FunctionDef(
      name='test编译的函数',
      args=arguments(
        posonlyargs=[],
        args=[
          arg(
            arg='a',
            annotation=Name(id='int', ctx=Load())),
          arg(
            arg='b',
            annotation=Name(id='int', ctx=Load()))],
        kwonlyargs=[],
        kw_defaults=[],
        defaults=[]),
      body=[
        Return(
          value=BinOp(
            left=Name(id='a', ctx=Load()),
            op=Mult(),
            right=Name(id='b', ctx=Load())))],
      decorator_list=[
        Call(
          func=Attribute(
            value=Name(id='lc', ctx=Load()),
            attr='jit',
            ctx=Load()),
          args=[],
          keywords=[])],
      returns=Name(id='int', ctx=Load()))],
  type_ignores=[])
Module(
  body=[
    FunctionDef(
      name='test_add',
      args=arguments(
        posonlyargs=[],
        args=[
          arg(
            arg='a',
            annotation=Name(id='int', ctx=Load())),
          arg(
            arg='b',
            annotation=Name(id='int', ctx=Load()))],
        kwonlyargs=[],
        kw_defaults=[],
        defaults=[]),
      body=[
        If(
          test=Compare(
            left=Name(id='a', ctx=Load()),
            ops=[
              Gt()],
            comparators=[
              Constant(value=1)]),
          body=[
            Return(
              value=BinOp(
                left=Name(id='a', ctx=Load()),
                op=Add(),
                right=Name(id='b', ctx=Load())))],
          orelse=[]),
        For(
          target=Name(id='i', ctx=Store()),
          iter=Call(
            func=Name(id='range', ctx=Load()),
            args=[
              Constant(value=1),
              Constant(value=10),
              Constant(value=2)],
            keywords=[]),
          body=[
            AugAssign(
              target=Name(id='a', ctx=Store()),
              op=Add(),
              value=Name(id='i', ctx=Load()))],
          orelse=[]),
        For(
          target=Name(id='i', ctx=Store()),
          iter=List(
            elts=[
              Constant(value=1),
              Constant(value=2),
              Constant(value=3)],
            ctx=Load()),
          body=[
            AugAssign(
              target=Name(id='a', ctx=Store()),
              op=Add(),
              value=Name(id='i', ctx=Load()))],
          orelse=[]),
        Assign(
          targets=[
            Name(id='a', ctx=Store())],
          value=Call(
            func=Attribute(
              value=Name(id='math', ctx=Load()),
              attr='ceil',
              ctx=Load()),
            args=[
              Constant(value=12.5)],
            keywords=[])),
        Assign(
          targets=[
            Name(id='cc', ctx=Store())],
          value=Dict(
            keys=[
              Constant(value='a'),
              Constant(value='b')],
            values=[
              Constant(value=1),
              Constant(value=2)])),
        Assign(
          targets=[
            Subscript(
              value=Name(id='cc', ctx=Load()),
              slice=Constant(value='c'),
              ctx=Store())],
          value=Constant(value=3)),
        Expr(
          value=Call(
            func=Name(id='print', ctx=Load()),
            args=[
              Constant(value='输出map:')],
            keywords=[])),
        For(
          target=Name(id='ii', ctx=Store()),
          iter=Name(id='cc', ctx=Load()),
          body=[
            Expr(
              value=Call(
                func=Name(id='print', ctx=Load()),
                args=[
                  Attribute(
                    value=Name(id='ii', ctx=Load()),
                    attr='first',
                    ctx=Load()),
                  Attribute(
                    value=Name(id='ii', ctx=Load()),
                    attr='second',
                    ctx=Load())],
                keywords=[]))],
          orelse=[]),
        Assign(
          targets=[
            Name(id='aa', ctx=Store())],
          value=List(
            elts=[
              Constant(value=1),
              Constant(value=3),
              Constant(value=2)],
            ctx=Load())),
        Assign(
          targets=[
            Subscript(
              value=Name(id='aa', ctx=Load()),
              slice=Constant(value=0),
              ctx=Store())],
          value=Constant(value=134)),
        Expr(
          value=Call(
            func=Name(id='print', ctx=Load()),
            args=[
              Constant(value='输出list:')],
            keywords=[])),
        For(
          target=Name(id='i', ctx=Store()),
          iter=Call(
            func=Name(id='range', ctx=Load()),
            args=[
              Constant(value=3)],
            keywords=[]),
          body=[
            Expr(
              value=Call(
                func=Name(id='print', ctx=Load()),
                args=[
                  Name(id='i', ctx=Load()),
                  Subscript(
                    value=Name(id='aa', ctx=Load()),
                    slice=Name(id='i', ctx=Load()),
                    ctx=Load())],
                keywords=[]))],
          orelse=[]),
        Expr(
          value=Call(
            func=Name(id='print', ctx=Load()),
            args=[
              Constant(value='Hello World'),
              Name(id='a', ctx=Load()),
              Name(id='b', ctx=Load())],
            keywords=[])),
        Expr(
          value=Call(
            func=Name(id='print', ctx=Load()),
            args=[
              Constant(value='test_other_fn'),
              Call(
                func=Name(id='test_other_fn', ctx=Load()),
                args=[
                  Name(id='a', ctx=Load()),
                  Name(id='b', ctx=Load())],
                keywords=[])],
            keywords=[])),
        Expr(
          value=Call(
            func=Name(id='print', ctx=Load()),
            args=[
              Constant(value='test编译的函数'),
              Call(
                func=Name(id='test编译的函数', ctx=Load()),
                args=[
                  Name(id='a', ctx=Load()),
                  Name(id='b', ctx=Load())],
                keywords=[])],
            keywords=[])),
        Assign(
          targets=[
            Name(id='v', ctx=Store())],
          value=Constant(value=0)),
        Assign(
          targets=[
            Name(id='vv', ctx=Store())],
          value=BoolOp(
            op=And(),
            values=[
              Constant(value=True),
              BoolOp(
                op=Or(),
                values=[
                  Constant(value=False),
                  Constant(value=1)])])),
        Expr(
          value=Call(
            func=Name(id='print', ctx=Load()),
            args=[
              Constant(value='vv:'),
              Name(id='vv', ctx=Load())],
            keywords=[])),
        While(
          test=Constant(value=True),
          body=[
            Expr(
              value=Call(
                func=Name(id='py_cin', ctx=Load()),
                args=[
                  Name(id='v', ctx=Load())],
                keywords=[])),
            If(
              test=Compare(
                left=Name(id='v', ctx=Load()),
                ops=[
                  Gt()],
                comparators=[
                  Constant(value=100)]),
              body=[
                Break()],
              orelse=[
                Expr(
                  value=Call(
                    func=Name(id='print', ctx=Load()),
                    args=[
                      Constant(value='输入的'),
                      Name(id='v', ctx=Load()),
                      Constant(value='小于等于100')],
                    keywords=[]))])],
          orelse=[]),
        Return(
          value=BinOp(
            left=BinOp(
              left=BinOp(
                left=BinOp(
                  left=Name(id='a', ctx=Load()),
                  op=Add(),
                  right=Name(id='b', ctx=Load())),
                op=Add(),
                right=Constant(value=1)),
              op=Add(),
              right=Call(
                func=Name(id='test_直接调用', ctx=Load()),
                args=[],
                keywords=[])),
            op=Add(),
            right=Name(id='v', ctx=Load())))],
      decorator_list=[
        Call(
          func=Attribute(
            value=Name(id='lc', ctx=Load()),
            attr='jit',
            ctx=Load()),
          args=[],
          keywords=[
            keyword(
              arg='每次运行都重新编译',
              value=Constant(value=True))])],
      returns=Name(id='int', ctx=Load()))],
  type_ignores=[])
输出map: 
c 3 
a 1 
b 2 
输出list: 
0 134 
1 3 
2 2 
Hello World 13 3 
test_other_fn 10 
test编译的函数 39 
vv: 1 
请输入>>>输入的 1 小于等于100 
请输入>>>输入的 2 小于等于100 
请输入>>>输入的 100 小于等于100 
请输入>>>Module(
  body=[
    FunctionDef(
      name='test_other_fn',
      args=arguments(
        posonlyargs=[],
        args=[
          arg(
            arg='a',
            annotation=Name(id='int', ctx=Load())),
          arg(
            arg='b',
            annotation=Name(id='int', ctx=Load()))],
        kwonlyargs=[],
        kw_defaults=[],
        defaults=[]),
      body=[
        Return(
          value=BinOp(
            left=Name(id='a', ctx=Load()),
            op=Sub(),
            right=Name(id='b', ctx=Load())))],
      decorator_list=[],
      returns=Name(id='int', ctx=Load()))],
  type_ignores=[])
结果: 241

4. 查看输出文件

ls -al ./l0n0lcoutput
total 32
drwxr-xr-x  2 root root  4096 Sep 16 03:28 .
drwxrwxrwx 11 1000 1000  4096 Sep 16 03:18 ..
-rw-r--r--  1 root root   284 Sep 16 03:28 sum_and_filter_@e48c1f185531e3af.cpp
-rw-r--r--  1 root root    83 Sep 16 03:28 sum_and_filter_@e48c1f185531e3af.h
-rwxr-xr-x  1 root root 15616 Sep 16 03:28 sum_and_filter_@e48c1f185531e3af.so

5. sum_and_filter_@e48c1f185531e3af.cpp

#include "sum_and_filter_@e48c1f185531e3af.h"
extern "C" int64_t sum_and_filter (int64_t n)
{
  auto total = ((int64_t)(0));
  for (int64_t x = 0; x < n; ++x)
  {
    if ((x % 2 == 0))
    {
      total = total + x;
    }

    {
      total = total - x;
    }

  }

  return total;
}

6. sum_and_filter_@e48c1f185531e3af.h

#include <cstdint>
#include <string>
extern "C" int64_t sum_and_filter (int64_t n);

7. test_add_@6a812a013615c16d.cpp

#include "test_add_@6a812a013615c16d.h"
extern "C" int64_t test_add (int64_t a, int64_t b)
{
  if ((a > 1))
  {
    return a + b;
  }

  for (int64_t i = 1; i < 10; i += 2)
  {
    a = a + i;
  }

  for (auto i : {1,2,3})
  {
    a = a + i;
  }

  a = std::ceil(12.5);;
  std::unordered_map<std::string, int64_t> cc = {{ u8"a", 1 },{ u8"b", 2 }};
  cc[u8"c"] = 3;
  std::cout<< u8"输出map:" << " "<< std::endl;
  for (auto ii : cc)
  {
    std::cout<< ii.first << " "<< ii.second << " "<< std::endl;
  }

  int64_t aa[] = {1,3,2};
  aa[0] = 134;
  std::cout<< u8"输出list:" << " "<< std::endl;
  for (int64_t i = 0; i < 3; ++i)
  {
    std::cout<< i << " "<< aa[i] << " "<< std::endl;
  }

  std::cout<< u8"Hello World" << " "<< a << " "<< b << " "<< std::endl;
  std::cout<< u8"test_other_fn" << " "<< test_other_fn(a,b) << " "<< std::endl;
  std::cout<< u8"test编译的函数" << " "<< function_74657374e7bc96e8af91e79a84e587bde695b0(a,b) << " "<< std::endl;
  auto v = 0;
  auto vv = true&&false||1;
  std::cout<< u8"vv:" << " "<< vv << " "<< std::endl;
  while (true)
  {
    std::cout << u8"请输入>>>"; std::cin >> v;
    if ((v > 100))
    {
      break;
    }

    {
      std::cout<< u8"输入的" << " "<< v << " "<< u8"小于等于100" << " "<< std::endl;
    }

  }

  return a + b + 1 + 123 + v;
}

8. test_add_@6a812a013615c16d.h

#include "test_other_fn_@75fdd928ab58a8e3.h"
#include "test编译的函数_@3bf4501e0408a243.h"
#include <cmath>
#include <cstdint>
#include <iostream>
#include <string>
#include <unordered_map>
extern "C" int64_t test_add (int64_t a, int64_t b);

9. test_other_fn_@75fdd928ab58a8e3.cpp

#include "test_other_fn_@75fdd928ab58a8e3.h"
extern "C" int64_t test_other_fn (int64_t a, int64_t b)
{
  return a - b;
}

10. test_other_fn_@75fdd928ab58a8e3.h

#include <cstdint>
#include <string>
extern "C" int64_t test_other_fn (int64_t a, int64_t b);

11. test编译的函数_@3bf4501e0408a243.cpp

#include "test编译的函数_@3bf4501e0408a243.h"
extern "C" int64_t /*test编译的函数*/ function_74657374e7bc96e8af91e79a84e587bde695b0 (int64_t a, int64_t b)
{
  return a * b;
}

12. test编译的函数_@3bf4501e0408a243.h

#include <cstdint>
#include <string>
extern "C" int64_t /*test编译的函数*/ function_74657374e7bc96e8af91e79a84e587bde695b0 (int64_t a, int64_t b);

Project details


Release history Release notifications | RSS feed

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

l0n0lc-0.8.6.tar.gz (16.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

l0n0lc-0.8.6-py3-none-any.whl (15.7 kB view details)

Uploaded Python 3

File details

Details for the file l0n0lc-0.8.6.tar.gz.

File metadata

  • Download URL: l0n0lc-0.8.6.tar.gz
  • Upload date:
  • Size: 16.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.11.13

File hashes

Hashes for l0n0lc-0.8.6.tar.gz
Algorithm Hash digest
SHA256 8012f3d1de9b3432fe5c9dda7de4d585a54962eb9b955167a2bfbab168ad619c
MD5 e47860f0f953b859a56c4209c006e852
BLAKE2b-256 114691038c707f2666e9484c06e304136ea182efb1ac503f0709d66ba76d36bd

See more details on using hashes here.

File details

Details for the file l0n0lc-0.8.6-py3-none-any.whl.

File metadata

  • Download URL: l0n0lc-0.8.6-py3-none-any.whl
  • Upload date:
  • Size: 15.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.11.13

File hashes

Hashes for l0n0lc-0.8.6-py3-none-any.whl
Algorithm Hash digest
SHA256 7c6c7ccf7911331dc58187f9b01ab3e0580ad94f5601b66bd4ad402660d2cca7
MD5 a7c7edf5a8847fee16d1da9f006d14f0
BLAKE2b-256 5d4704846465818b5ff10be6da097142598d3e760cf9a06ed88361b9f0ff6eb4

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page