Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

First attempt to bind constants #155

Open
wants to merge 9 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions source/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@ add_clang_executable(binder
enum.hpp
enum.cpp

const.hpp
const.cpp

function.hpp
function.cpp

Expand Down
10 changes: 10 additions & 0 deletions source/binder.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@

#include <context.hpp>
#include <enum.hpp>
#include <const.hpp>
#include <function.hpp>
#include <class.hpp>
#include <util.hpp>
Expand Down Expand Up @@ -208,6 +209,15 @@ class BinderVisitor : public RecursiveASTVisitor<BinderVisitor>

return true;
}
virtual bool VisitVarDecl(VarDecl *V) {
if( !V->getType().isConstQualified() ) return true;
if( !V->hasInit() ) return true;
if( V->getType().getTypePtr()->isArrayType()) return true;
if( V->isCXXInstanceMember() or V->isCXXClassMember() ) return true;
binder::BinderOP b = std::make_shared<binder::ConstBinder>( V );
context.add(b);
return true;
}

void generate(void) {
context.generate( Config::get() );
Expand Down
114 changes: 114 additions & 0 deletions source/const.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
// -*- mode:c++;tab-width:2;indent-tabs-mode:t;show-trailing-whitespace:t;rm-trailing-spaces:t -*-
// vi: set ts=2 noet:
//
// Copyright (c) 2021 Sergey Lyskov <[email protected]>
//
// All rights reserved. Use of this source code is governed by a
// MIT license that can be found in the LICENSE file.

/// @file binder/const.cpp
/// @brief Binding generation for C++ constants
/// @author Sergey Lyskov, Andrii Verbytskyi


#include <const.hpp>

#include <type.hpp>
#include <util.hpp>

#include <fmt/format.h>

#include <clang/AST/ASTContext.h>

using namespace llvm;
using namespace clang;
#include <iostream>
using std::string;
using std::vector;

using namespace fmt::literals;

namespace binder {

/// check if generator can create binding
bool is_bindable(VarDecl const *E)
{
if ( !E->getType().isConstQualified() ) return false;
if ( !E->hasInit() ) return false;
if ( E->getType().getTypePtr()->isArrayType()) return false;
if( E->isCXXInstanceMember() or E->isCXXClassMember() ) return false;
if( E->isCXXInstanceMember() ) return false;
if ( standard_name( E->getType().getCanonicalType().getAsString() ) == "const std::string" ) return true;
if (E->getType().getTypePtr()->isRealFloatingType() ) return true;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

could you please fix formatting here so it consistent? Sorry: i am pedantic...

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OK.

if (E->getType().getTypePtr()->isIntegerType() ) return true;
if (E->getType().getTypePtr()->isBooleanType() ) return true;
return false;
}

// Generate binding for given function: py::enum_<MyEnum>(module, "MyEnum")...
std::string bind_const(std::string const & module, VarDecl const *E)
{
string r=" ";
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we need to use \t instead of just space to keep indentation correct

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OK.

clang::Expr const* init = E->getInit();
if (init){
string name { E->getNameAsString() };
std::string type = E->getType().getCanonicalType().getAsString();
std::string pytype = "";
bool pytype_set = false;
//This is a list of types that can bi binded with pybind, see https://pybind11.readthedocs.io/en/stable/advanced/pycpp/object.html*/
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

could you please fix indentation here and remove */ at the line end?

if ( !pytype_set and standard_name( type ) == "const std::string" ) { pytype_set=true; pytype="str";}
if ( !pytype_set and E->getType().getTypePtr()->isRealFloatingType() ) { pytype_set=true; pytype="float_"; }
if ( !pytype_set and E->getType().getTypePtr()->isIntegerType() ) { pytype_set=true; pytype="int_"; }
if ( !pytype_set and E->getType().getTypePtr()->isBooleanType() ) { pytype_set=true; pytype="bool_"; }
if (pytype_set) {
std::string rhs;
llvm::raw_string_ostream rso(rhs);
clang::LangOptions lang_opts;
lang_opts.CPlusPlus = true;
clang::PrintingPolicy Policy(lang_opts);
init->printPretty(rso, NULL, Policy);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please replace NULL with 0 here

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OK.

r = "\t{}.attr(\"{}\") = pybind11::{}({})\n"_format( module, name, pytype, rhs);
}
}
r.pop_back();
return r;
}


/// Generate string id that uniquly identify C++ binding object. For functions this is function prototype and for classes forward declaration.
string ConstBinder::id() const
{
return E->getQualifiedNameAsString();
}


/// check if generator can create binding
bool ConstBinder::bindable() const
{
return is_bindable(E);
}

/// check if user requested binding for the given declaration
void ConstBinder::request_bindings_and_skipping(Config const &config)
{
if( config.is_namespace_binding_requested( namespace_from_named_decl(E) ) ) Binder::request_bindings();
}


/// extract include needed for this generator and add it to includes vector
void ConstBinder::add_relevant_includes(IncludeSet &includes) const
{
}
Comment on lines +98 to +101
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why this function is empty, was this just an oversight or we can not deduce includes for some reason? Can we just do binder::add_relevant_includes(E, includes, 0);?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

My understanding was that once only the standard types are used, no extra includes are needed.
And the std::string is included anyway.


/// generate binding code for this object and all its dependencies
void ConstBinder::bind(Context &context)
{
if( is_binded() ) return;

string const module_variable_name = context.module_variable_name( namespace_from_named_decl(E) );

code() = "\t" + generate_comment_for_declaration(E);
code() += bind_const(module_variable_name, E) + ";\n\n";
}

} // namespace binder
63 changes: 63 additions & 0 deletions source/const.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
// -*- mode:c++;tab-width:2;indent-tabs-mode:t;show-trailing-whitespace:t;rm-trailing-spaces:t -*-
// vi: set ts=2 noet:
//
// Copyright (c) 2021 Sergey Lyskov <[email protected]>
//
// All rights reserved. Use of this source code is governed by a
// MIT license that can be found in the LICENSE file.

/// @file binder/const.hpp
/// @brief Binding generation for C++ constant expressions
/// @author Sergey Lyskov, Andrii Verbytskyi


#ifndef _INCLUDED_const_hpp_
#define _INCLUDED_const_hpp_

#include <context.hpp>

#include <clang/AST/Decl.h>

#include <string>

namespace binder {

/// check if generator can create binding
bool is_bindable(clang::VarDecl const *E);


// Generate binding for given function
std::string bind_const(std::string const & module, clang::VarDecl const *E);


class ConstBinder : public Binder
{
public:
ConstBinder(clang::VarDecl const *e) : E(e) {}

/// Generate string id that uniquly identify C++ binding object. For functions this is function prototype and for classes forward declaration.
string id() const override;
// return Clang AST NamedDecl pointer to original declaration used to create this Binder
clang::NamedDecl const * named_decl() const override { return E; };

/// check if generator can create binding
bool bindable() const override;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sorry, pedantic: indentation here is broken

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OK.


/// check if user requested binding for the given declaration
virtual void request_bindings_and_skipping(Config const &) override;

/// extract include needed for this generator and add it to includes vector
void add_relevant_includes(IncludeSet &includes) const override;

/// generate binding code for this object and all its dependencies
void bind(Context &) override;


private:
clang::VarDecl const *E;
};


} // namespace binder

#endif // _INCLUDED_const_hpp_
1 change: 1 addition & 0 deletions test/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@ set( binder_tests
T42.stl.names.multimap
T42.stl.names.multiset
T50.namespace_binder
T60.const
)
if (pybind11_VERSION VERSION_LESS 2.5.99)
message(STATUS "pybind11 version ${pybind11_VERSION} is less than 2.5.99. Some tests will be disabled." )
Expand Down
48 changes: 48 additions & 0 deletions test/T60.const.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
// -*- mode:c++;tab-width:2;indent-tabs-mode:t;show-trailing-whitespace:t;rm-trailing-spaces:t -*-
// vi: set ts=2 noet:
//
// Copyright (c) 2016 Sergey Lyskov <[email protected]>
//
// All rights reserved. Use of this source code is governed by a
// MIT license that can be found in the LICENSE file.

/// @file binder/test/T00.basic.hpp
/// @brief Binder self-test file. Basic functionality.
/// @author Sergey Lyskov

#ifndef _INCLUDED_T60_basic_hpp_
#define _INCLUDED_T60_basic_hpp_
#include <string>
#include <vector>

const int global_int=1;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here and below: could you please fix the const placement here and below to match the rest of source code? Thanks,

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OK.

const long global_long=2;

const unsigned int global_unsigned_int=3;
const unsigned long global_unsigned_long=4;

const float global_float=5.0;
const double global_double=6.0;

const std::string global_string1="Some test string";

const std::string global_string2=std::string("Some test string");


const double expression_global_double=8.0+1.0/5.0;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I see that this will be bound verbatim below as pybind11::float_(8. + 1. / 5.) which is problematic. Consider this: let's say we binding constant for some deep-nested namespace that depend on some other constants like this:

namespace TEST {
int const A = 1;
int const B = A+1
...

if binding code for this will be generate as A+1 then result will not compile because expression should really be `TEST::A +``
My recommendation would be to disable bindings for expression unless we can somehow evaluate them (this might be possible though since LLVM have required code)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, that is a problematic part.

we can somehow evaluate them

Eh, it is safer not to evaluate them. Just imagine a code

#ifdef MYFLAG
int const a=5;
#else
int const a=6;
#endif

and then somewhere binding the constants like

int const i_want_to_bind_it   mya = 100 * a;

In case the evaluation would be turned on, one would have to regenerate the binding code each time the 'a' is updated or the MYFLAG is changed.

What could make more sense is to transform the RHS from the "raw" code into a canonical representation. I will have to look how to do that (LLVM should be able to do that, or am I wrong?).


const double array_global_double[5]={1.0,2.0,3.0,4.0,5.0}; //This should not appear in bindings so far.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

here and below: could you please add _not_binded suffix to all names thats should not be bound? That will make test script to raise alarm before compilation/linking failure which will be more readable for developers. Thanks,

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OK.


const std::vector<double> vector_global_double{1.0,2.0,3.0,4.0,5.0}; //This should not appear in bindings so far.

int foo_char(char *) { return 0; }
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

could you please elaborate why do we need this function here, what do we test with it?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is just to test that other parts are working fine.


namespace foo
{
const double foonamespaced_global_double=7.0;

int foonamespaced_foo_char(char *) { return 0; }
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

could you please elaborate why do we need this function here, what do we test with it?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a test again.


}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we add some user defined data types here? If they can not be bound that totally fine but i want to make sure that Binder is always generate compilable code. Thanks,

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The constants can be bound using the special types like "float_", so I custom types cannot use it, as far as I understand.


#endif // _INCLUDED_T60_basic_hpp_
119 changes: 119 additions & 0 deletions test/T60.const.ref
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
// File: T60_const.cpp
#include <T60.const.hpp> // foo_char

#include <pybind11/pybind11.h>
#include <functional>
#include <string>

#ifndef BINDER_PYBIND11_TYPE_CASTER
#define BINDER_PYBIND11_TYPE_CASTER
PYBIND11_DECLARE_HOLDER_TYPE(T, std::shared_ptr<T>)
PYBIND11_DECLARE_HOLDER_TYPE(T, T*)
PYBIND11_MAKE_OPAQUE(std::shared_ptr<void>)
#endif

void bind_T60_const(std::function< pybind11::module &(std::string const &namespace_) > &M)
{
// global_int file:T60.const.hpp line:18
M("").attr("global_int") = pybind11::int_(1);

// global_long file:T60.const.hpp line:19
M("").attr("global_long") = pybind11::int_(2);

// global_unsigned_int file:T60.const.hpp line:21
M("").attr("global_unsigned_int") = pybind11::int_(3);

// global_unsigned_long file:T60.const.hpp line:22
M("").attr("global_unsigned_long") = pybind11::int_(4);

// global_float file:T60.const.hpp line:24
M("").attr("global_float") = pybind11::float_(5.);

// global_double file:T60.const.hpp line:25
M("").attr("global_double") = pybind11::float_(6.);

// global_string1 file:T60.const.hpp line:27
M("").attr("global_string1") = pybind11::str("Some test string");

// global_string2 file:T60.const.hpp line:29
M("").attr("global_string2") = pybind11::str(std::string("Some test string"));

// expression_global_double file:T60.const.hpp line:32
M("").attr("expression_global_double") = pybind11::float_(8. + 1. / 5.);

// foo_char(char *) file:T60.const.hpp line:38
M("").def("foo_char", (int (*)(char *)) &foo_char, "C++: foo_char(char *) --> int", pybind11::arg(""));

}


// File: T60_const_1.cpp
#include <T60.const.hpp> // foo::foonamespaced_foo_char

#include <pybind11/pybind11.h>
#include <functional>
#include <string>

#ifndef BINDER_PYBIND11_TYPE_CASTER
#define BINDER_PYBIND11_TYPE_CASTER
PYBIND11_DECLARE_HOLDER_TYPE(T, std::shared_ptr<T>)
PYBIND11_DECLARE_HOLDER_TYPE(T, T*)
PYBIND11_MAKE_OPAQUE(std::shared_ptr<void>)
#endif

void bind_T60_const_1(std::function< pybind11::module &(std::string const &namespace_) > &M)
{
// foo::foonamespaced_global_double file:T60.const.hpp line:42
M("foo").attr("foonamespaced_global_double") = pybind11::float_(7.);

// foo::foonamespaced_foo_char(char *) file:T60.const.hpp line:44
M("foo").def("foonamespaced_foo_char", (int (*)(char *)) &foo::foonamespaced_foo_char, "C++: foo::foonamespaced_foo_char(char *) --> int", pybind11::arg(""));

}


#include <map>
#include <memory>
#include <stdexcept>
#include <functional>
#include <string>

#include <pybind11/pybind11.h>

typedef std::function< pybind11::module & (std::string const &) > ModuleGetter;

void bind_T60_const(std::function< pybind11::module &(std::string const &namespace_) > &M);
void bind_T60_const_1(std::function< pybind11::module &(std::string const &namespace_) > &M);


PYBIND11_MODULE(T60_const, root_module) {
root_module.doc() = "T60_const module";

std::map <std::string, pybind11::module> modules;
ModuleGetter M = [&](std::string const &namespace_) -> pybind11::module & {
auto it = modules.find(namespace_);
if( it == modules.end() ) throw std::runtime_error("Attempt to access pybind11::module for namespace " + namespace_ + " before it was created!!!");
return it->second;
};

modules[""] = root_module;

std::vector< std::pair<std::string, std::string> > sub_modules {
{"", "foo"},
};
for(auto &p : sub_modules ) modules[p.first.size() ? p.first+"::"+p.second : p.second] = modules[p.first].def_submodule(p.second.c_str(), ("Bindings for " + p.first + "::" + p.second + " namespace").c_str() );

//pybind11::class_<std::shared_ptr<void>>(M(""), "_encapsulated_data_");

bind_T60_const(M);
bind_T60_const_1(M);

}

// Source list file: /home/andriish/Projects/binder/test//T60_const.sources
// T60_const.cpp
// T60_const.cpp
// T60_const_1.cpp

// Modules list file: /home/andriish/Projects/binder/test//T60_const.modules
// foo
Loading