Skip to content

clang python bindings #89214

Closed
Closed

Description

@marcus7070

Project description
I'm trying to package another program that makes use of clang_9 python bindings: https://github.com/llvm/llvm-project/tree/master/clang/bindings/python

I don't have any experience with clang so I might be wrong, but I think nixpkgs currently doesn't include them. I was expecting them to be copied from src/bindings/python to an output in this expression: https://github.com/NixOS/nixpkgs/blob/master/pkgs/development/compilers/llvm/9/clang/default.nix

I don't think there are any specific maintainers of llvm for me to ping for help either.

Activity

  1. added
    0.kind: packaging request
    on May 30, 2020
  2. added
    6.topic: python
    on May 31, 2020
  3. stale commented on Nov 27, 2020

    @stale

    I marked this as stale due to inactivity. → More info

  4. added
    2.status: stale
    on Nov 27, 2020
  5. bjornfor commented on Sep 1, 2021

    @bjornfor
    Contributor

    I made a packaging attempt here: bjornfor@63d7b5a. The major thing that's missing is how to make the python module (or libclang) find system headers. It'd be nice to have some sort of wrapper, but how to wrap a python module? (As a workaround one can wrap the python interpreter.)

  6. removed
    2.status: stale
    on Sep 1, 2021
  7. WizardUli commented on Sep 5, 2021

    @WizardUli

    @bjornfor Nix does not have global python modules by design! 🙂 You always have to use wrapper like python3.withPackages.

    I don't quite understand your question though. What are system headers?

    Nevertheless I've just spent a few hours playing with your attempt and the only thing missing for the new package to be usable when put to buildPythonPackage.propagatedBuildInputs of other packages are metadata.
    I've just added a proper pyproject.toml and setup.cfg and installed the package using

    python -m pip --no-cache-dir install --no-clean --no-deps --no-index --no-build-isolation --prefix="$python" ../bindings/python
    

    which correctly generated required metadata into site-packages.
    I'd like to use nixpkgs's buildPythonPackage or other functions though but I don't know how YET. I'll investigate further.

  8. bjornfor commented on Sep 5, 2021

    @bjornfor
    Contributor

    I don't quite understand your question though. What are system headers?

    I mean files like stdio.h and iostream. I had to wrap the python interpreter to make things work (i.e. have the clang.cindex python module find those files). I used nixpkgs clang-tools/wrapper as inspiration.

    Nevertheless I've just spent a few hours playing with your attempt and the only thing missing for the new package to be usable when put to buildPythonPackage.propagatedBuildInputs of other packages are metadata.

    Yay!

    But what metadata? My first thought was meta.{homepage,license} etc. but then it looks like you're talking about something different. Where did you put that python -m pip --no-cache-dir install ... command? Ah, you ran it manually? Why? Did you try python3.pkgs.withPackages (ps: [ ps.libclang_12 ])?

  9. WizardUli commented on Sep 5, 2021

    @WizardUli

    Have a look at 5b2bbd54b2052b3eef34838ef1e71db83baf0053.
    You can build it by nix build .#python3Packages.libclang_12 or nix-build ./. -A python3Packages.libclang_12
    and you can drop into a shell with clang bindings installed by:

    nix-shell -E 'let pkgs = import ./. {}; in pkgs.mkShell { packages = [ (pkgs.python3.withPackages (ps: with ps; [ libclang_12 ])) ]; }'
    
  10. WizardUli commented on Sep 5, 2021

    @WizardUli

    By metadata I mean:

    $ ls -la result-python/lib/python3.8/site-packages/clang-12.0.dist-info/
    total 32
    dr-xr-xr-x 2 root root 4096 jan  1  1970 .
    dr-xr-xr-x 4 root root 4096 jan  1  1970 ..
    -r--r--r-- 1 root root   62 jan  1  1970 direct_url.json
    -r--r--r-- 1 root root    4 jan  1  1970 INSTALLER
    -r--r--r-- 1 root root  168 jan  1  1970 METADATA
    -r--r--r-- 1 root root  915 jan  1  1970 RECORD
    -r--r--r-- 1 root root    0 jan  1  1970 REQUESTED
    -r--r--r-- 1 root root    6 jan  1  1970 top_level.txt
    -r--r--r-- 1 root root   92 jan  1  1970 WHEEL
    
  11. bjornfor commented on Sep 14, 2021

    @bjornfor
    Contributor

    #137069 includes a "python3Packages.clang: init at 5.0 and 11.0" commit.

  12. samuela commented on Sep 16, 2021

    @samuela
    Member

    I can confirm that I got clang python packages working in #137069. We can add any other versions people need once that lands!

  13. WizardUli commented on Sep 18, 2021

    @WizardUli

    I can confirm that I got clang python packages working in #137069. We can add any other versions people need once that lands!

    The clang python package introduced in #137069 has a major flaw though. It does not have a default link to the libclang and using it directly fails on

    clang.cindex.LibclangError: lib/libclang.so: cannot open shared object file: No such file or directory. To provide a path to libclang use Config.set_library_path() or Config.set_library_file().
    

    @bjornfor 's approach is much better IMHO because:

    1. It does not use the PYPI package but directly (re)uses the same source code clang compiler and libclang library is built from.
    2. It provides default link to a matching libclang by patching a default in https://github.com/bjornfor/nixpkgs/blob/63d7b5a236889f223fbfc4b96b2a63b212dba1ae/pkgs/development/compilers/llvm/12/clang/cindex-library-path.patch

    The only thing that was missing was that it must by installed by pip to the final destination and not just be cp-ed there otherwise while being directly usable by python interpret it is not usable by python's build system and cannot be used as a dependency in other packages then.

  14. stale commented on Apr 25, 2022

    @stale

    I marked this as stale due to inactivity. → More info

  15. danderson commented on May 15, 2022

    @danderson
    Contributor

    I'm trying to upgrade the CadQuery derivation, but due to a tree of dependency changes, I now also need clang's python bindings to exist.

    @grawp the commit you referenced for "how to make the pip installation work" no longer exists. Do you still have WIP code to demonstrate how you got pip to work correctly? IIUC, it's the only blocker to getting @bjornfor's changes into a formal PR, so that I can start walking back up the dependency tree and upgrade the derivation I care about :)

  16. bjornfor commented on May 16, 2022

    @bjornfor
    Contributor

    Oh, that reminds me:

    It'd be nice to have some sort of wrapper, but how to wrap a python module? (As a workaround one can wrap the python interpreter.)

    I recently wrote a python implementation of the clang wrapper and injected it to the python libclang package __init__.py. It feels a bit hack'y, because importing clang.cindex sets env vars $CPATH and $CPLUS_INCLUDE_PATH, but at least it only affects the python process importing that specific module (instead of all python processes having that module available).

    You can find the implementation below. (Sorry, I don't have time to make a PR yet, but just wanted to get this out there.)

    libclang-inject-header-paths.py.in:

    # This code is (to be) appended to the python libclang module __init__.py file.
    #
    # Pushing wrapping into the module itself, instead of the python interpreter,
    # minimizes leaking environment variables like $CPATH (which, when containing
    # *clang* headers, breaks gcc).
    #
    # Still, after the libclang/cindex module has been imported, the python process
    # can no longer be used to invoke gcc as the $CPATH etc. envvars set here break
    # it. But that's luckily a rare use case.
    #
    # Inspired by <nixpkgs>/pkgs/development/tools/clang-tools/wrapper.
    
    
    def _buildcpath(args):
        """Extract and return include paths from the given compiler include
        options.
    
        Signature: List[str] -> List[str]
        """
        path = []
        after = []
        while len(args) > 0:
            if args[0] == "-isystem":
                args.pop(0)
                path.append(args[0])
            elif args[0] == "-idirafter":
                args.pop(0)
                after.append(args[0])
            args.pop(0)
        return path + after
    
    
    def _get_flags(file):
        """Read file, return list of words.
    
        Signature: Path -> List[str]
        """
        return open(file).read().split()
    
    
    def _set_compiler_env_vars():
        """Set $CPATH and $CPLUS_INCLUDE_PATH env vars from $NIX_CFLAGS_COMPILE"""
        import os
    
        nix_cflags_compile = os.environ.get("NIX_CFLAGS_COMPILE", "").split()
        orig_cpath = os.environ.get("CPATH", "").split()
        orig_cplus_include_path = os.environ.get("CPLUS_INCLUDE_PATH", "").split()
    
        new_cpath = (
            orig_cpath
            + _buildcpath(nix_cflags_compile + _get_flags("@clang@/nix-support/libc-cflags"))
            + ["@clang@/resource-root/include"]
        )
    
        new_cplus_include_path = (
            orig_cplus_include_path
            + _buildcpath(
                nix_cflags_compile
                + _get_flags("@clang@/nix-support/libcxx-cxxflags")
                + _get_flags("@clang@/nix-support/libc-cflags")
            )
            + ["@clang@/resource-root/include"]
        )
    
        os.environ["CPATH"] = ":".join(new_cpath)
        os.environ["CPLUS_INCLUDE_PATH"] = ":".join(new_cplus_include_path)
    
    
    _set_compiler_env_vars()

    And mach-nix-overrides.nix file to apply it:

    # mach-nix overrides.
    {pkgs}: [
      (pyfinal: pyprev: {
        # Patch/wrap libclang to find system headers. Do it in postInstall to work
        # even when mach-nix package provider is "wheel".
        #
        # The clang version must be selected by the caller, for example:
        #
        #   mach-nix.mkPython {
        #     ...
        #     overridesPost = import ./this_file.nix { pkgs = pkgs // { clang = pkgs.clang_12; }; };
        #   }
        libclang = pyprev.libclang.overridePythonAttrs (old: {
          postInstall =
            (old.postInstall or "")
            + ''
              init_file=$(find "$out" -name __init__.py)
              if ! [ -f "$init_file" ]; then
                  echo "error: failed to find libclang __init__.py file to patch" >&2
                  exit 1
              fi
    
              # Set variable(s) and run substituteAll.
              export clang="${pkgs.clang}"
              substituteAll "${./libclang-inject-header-paths.py.in}" ./inject_paths.py
    
              # Inject our wrapper code.
              cat ./inject_paths.py >> "$init_file"
            '';
        });
      })
    ]
  17. added
    2.status: stale
    on Nov 12, 2022
  18. athre0z commented on Nov 27, 2022

    @athre0z
    Member

    Still relevant. python3Packages.clang and python3Packages.libclang mentioned by previous posts no longer seem to exist.

  19. removed
    2.status: stale
    on Nov 27, 2022
  20. lilyinstarlight commented on Nov 2, 2023

    @lilyinstarlight
    Member

    There's a python3Packages.libclang inspired by @WizardUli's in #261113, by the way

  21. lilyinstarlight commented on Nov 22, 2023

    @lilyinstarlight
    Member

    Can this be closed now that the python3Packages.libclang derivation from #261113 is on master, or is anything else still missing?

  22. athre0z commented on Feb 6, 2024

    @athre0z
    Member

    Not OP, but at least from my perspective this is a solved problem. Thanks for adding this! :)

  23. lilyinstarlight commented on Feb 6, 2024

    @lilyinstarlight
    Member

    Okay, I'll close this then. Anyone feel free to reopen if anything is missing :)

  24. added
    6.topic: llvm/clang
    on May 27, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    0.kind: packaging request6.topic: llvm/clang6.topic: python

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions