CodeSampleX

Пример

llvmlite 0.49.0rc1: binding

Проверенный пример — pypi llvmlite 0.49.0rc1: binding. Контракт выполнен на python 3.12 · linux debian/x64 · docker и пройден.

sha256:c7ca60b9be79febc50708cb7e552aa2e90b573b435a3313ac61e4f6638b03c86

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. MIT-0

Свидетельства выполнения

Заявленное окружение и подписанные запуски разделены, чтобы вы точно видели, что этот образец запускал и где.

Основа свидетельства
Подписанный контракт пройден
Квитанции проверки
1
Ключи подписи, собравшие его
1
Заявленная среда linux 24 · ubuntu · glibc 2.39 x64 pip

Среды запусков проверки

Окружение Контракт Этапы Запуск
python 3.12 · linux debian/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · python@1python:3.12-slim@sha256:09f7da3bc104…
2026-09-19

Кейс

HOW
Цель
verify llvmlite.binding in pkg:pypi/llvmlite@0.49.0rc1
Пакеты
Символы
  • llvmlite.binding
Создан
2026-09-17T16:57:35Z

Контракт

  1. llvmlite.binding.initialize raises RuntimeError because LLVM initialization is handled automatically
  2. llvmlite.binding.initialize_native_target and initialize_native_asmprinter configure the native target machine
  3. llvmlite.binding.parse_assembly parses and verifies LLVM IR assembly module
  4. llvmlite.binding.create_mcjit_compiler creates an execution engine to compile and invoke functions

Файлы

  • PROMPT.md
  • csx.json
  • requirements.txt
  • sample.py
  • spec.json
  • test/__init__.py
  • test/contract.py

Скачать артефакт с исходным кодом (tar.gz)

Исходный код

PROMPT.md
Clean-room public code sample — generation instructions

Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.

A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.

Goal: verify llvmlite.binding in pkg:pypi/llvmlite@0.49.0rc1
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:pypi/llvmlite@0.49.0rc1
Demonstrate these symbols/APIs:
  - llvmlite.binding

Rules:
  - One focused purpose; the smallest project that proves the goal.
  - Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
  - Pin every dependency with a lockfile so resolution is reproducible.
  - No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
  - No personal names, emails, company names, or project identifiers of any kind.
  - No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
  - Keep it under 200 files and 256KB packed.
csx.json
{"case":{"caseId":"case:sha256:533a64871e623272dc831c8140001bc0204977af2255c57242ccc435f541b145","contract":["llvmlite.binding.initialize raises RuntimeError because LLVM initialization is handled automatically","llvmlite.binding.initialize_native_target and initialize_native_asmprinter configure the native target machine","llvmlite.binding.parse_assembly parses and verifies LLVM IR assembly module","llvmlite.binding.create_mcjit_compiler creates an execution engine to compile and invoke functions"],"goal":"verify llvmlite.binding in pkg:pypi/llvmlite@0.49.0rc1","kind":"HOW","packages":["pkg:pypi/llvmlite@0.49.0rc1"],"schemaVersion":1,"symbols":["llvmlite.binding"]},"contractCommand":["python","test/contract.py"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"pypi","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"pip","schemaVersion":1},"license":"MIT-0","packages":["pkg:pypi/llvmlite@0.49.0rc1"],"schemaVersion":1,"subject":"pkg:pypi/llvmlite@0.49.0rc1","symbols":["llvmlite.binding"],"verifierAdapter":"python@1"}
requirements.txt
llvmlite==0.49.0rc1
sample.py
"""Demonstration of LLVM binding operations using llvmlite.binding."""

import ctypes
import llvmlite.binding as llvm


def initialize_llvm_targets() -> llvm.TargetMachine:
    """Initialize native LLVM targets and return a target machine for the default host."""
    llvm.initialize_native_target()
    llvm.initialize_native_asmprinter()
    target = llvm.Target.from_default_triple()
    return target.create_target_machine()


def parse_and_verify_module(ir_code: str) -> llvm.ModuleRef:
    """Parse LLVM IR assembly text and verify the module structure."""
    mod = llvm.parse_assembly(ir_code)
    mod.verify()
    return mod


def compile_and_execute_binary_op(
    mod: llvm.ModuleRef,
    target_machine: llvm.TargetMachine,
    func_name: str,
    arg1: int,
    arg2: int,
) -> int:
    """Create an MCJIT execution engine, compile the function, and invoke it."""
    engine = llvm.create_mcjit_compiler(mod, target_machine)
    engine.finalize_object()
    engine.run_static_constructors()

    func_ptr = engine.get_function_address(func_name)
    cfunc = ctypes.CFUNCTYPE(ctypes.c_int32, ctypes.c_int32, ctypes.c_int32)(func_ptr)
    return int(cfunc(arg1, arg2))
spec.json
{
  "schemaVersion": 1,
  "goal": "verify llvmlite.binding in pkg:pypi/llvmlite@0.49.0rc1",
  "kind": "HOW",
  "packages": [
    "pkg:pypi/llvmlite@0.49.0rc1"
  ],
  "symbols": [
    "llvmlite.binding"
  ]
}
test/__init__.py
"""Tests package."""
test/contract.py
"""Contract verification test for llvmlite.binding."""

import os
import sys

# Ensure sample module can be imported from root directory
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

import llvmlite.binding as llvm
from sample import (
    initialize_llvm_targets,
    parse_and_verify_module,
    compile_and_execute_binary_op,
)


def test_deprecated_initialize_raises_runtime_error() -> None:
    """Assertion 1: llvmlite.binding.initialize raises RuntimeError because LLVM initialization is handled automatically."""
    raised = False
    try:
        llvm.initialize()
    except RuntimeError as exc:
        raised = True
        assert "deprecated" in str(exc)
        assert "LLVM initialization is now handled automatically" in str(exc)

    assert raised, "Expected RuntimeError when calling deprecated llvm.initialize()"


def test_initialize_native_targets_and_target_machine() -> None:
    """Assertion 2: llvmlite.binding.initialize_native_target and initialize_native_asmprinter configure the native target machine."""
    tm = initialize_llvm_targets()
    assert tm is not None

    triple = llvm.get_default_triple()
    assert isinstance(triple, str)
    assert len(triple) > 0

    target = llvm.Target.from_default_triple()
    assert target.name is not None
    assert len(target.name) > 0


def test_parse_and_verify_assembly() -> None:
    """Assertion 3: llvmlite.binding.parse_assembly parses and verifies LLVM IR assembly module."""
    ir = """
    define i32 @add(i32 %a, i32 %b) {
    entry:
      %sum = add i32 %a, %b
      ret i32 %sum
    }
    """
    mod = parse_and_verify_module(ir)
    assert "add" in str(mod)


def test_mcjit_execution_engine_compiles_and_executes() -> None:
    """Assertion 4: llvmlite.binding.create_mcjit_compiler creates an execution engine to compile and invoke functions."""
    tm = initialize_llvm_targets()
    ir = """
    define i32 @multiply(i32 %x, i32 %y) {
    entry:
      %prod = mul i32 %x, %y
      ret i32 %prod
    }
    """
    mod = parse_and_verify_module(ir)
    result = compile_and_execute_binary_op(mod, tm, "multiply", 6, 7)
    assert result == 42


def main() -> None:
    test_deprecated_initialize_raises_runtime_error()
    test_initialize_native_targets_and_target_machine()
    test_parse_and_verify_assembly()
    test_mcjit_execution_engine_compiles_and_executes()
    print("All contract assertions passed.")


if __name__ == "__main__":
    main()

Исходный сидер

аноним