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

Build Type 1 binding features #567

Merged
merged 14 commits into from
Sep 22, 2022
166 changes: 166 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -48,3 +48,169 @@ test/int/*.interpreter

*.dSYM
.envrc

# Created by https://www.toptal.com/developers/gitignore/api/python
# Edit at https://www.toptal.com/developers/gitignore?templates=python

### Python ###
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
.pybuilder/
target/

# Jupyter Notebook
.ipynb_checkpoints

# IPython
profile_default/
ipython_config.py

# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version

# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock

# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock

# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
# in version control.
# https://pdm.fming.dev/#use-with-ide
.pdm.toml

# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/

# Celery stuff
celerybeat-schedule
celerybeat.pid

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
.dmypy.json
dmypy.json

# Pyre type checker
.pyre/

# pytype static type analyzer
.pytype/

# Cython debug symbols
cython_debug/

# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/

# End of https://www.toptal.com/developers/gitignore/api/python
100 changes: 94 additions & 6 deletions bindings/python/ast.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
#include <pybind11/stl.h>

#include <sstream>
#include <tuple>

#include "runtime.h"

Expand All @@ -14,15 +15,49 @@ namespace py = pybind11;
using namespace kllvm;
using namespace kllvm::parser;

// Metaprogramming support for the adapter function between AST print() methods
// and Python's __repr__.
namespace detail {

template <typename T>
struct type_identity {
using type = T;
};

template <typename T, typename... Args>
struct print_repr_adapter_st {
print_repr_adapter_st(type_identity<T>, Args &&...args)
: args_(std::forward<Args>(args)...) { }

std::string operator()(T &node) {
auto ss = std::stringstream{};

std::apply(
[&](auto &&...args) { return node.print(args...); },
std::tuple_cat(
std::tuple{std::ref(ss)}, std::forward<decltype(args_)>(args_)));

return ss.str();
}

private:
std::tuple<Args...> args_;
};

template <typename T, typename... Args>
print_repr_adapter_st(type_identity<T>, Args &&...)
-> print_repr_adapter_st<T, Args...>;

} // namespace detail

/**
* Adapt an AST node's print method to return a string for use with Python's
* __repr__ method.
*/
template <typename T>
std::string print_repr_adapter(T &node) {
auto ss = std::stringstream{};
node.print(ss);
return ss.str();
template <typename T, typename... Args>
auto print_repr_adapter(Args &&...args) {
return ::detail::print_repr_adapter_st(
::detail::type_identity<T>{}, std::forward<Args>(args)...);
}

void bind_ast(py::module_ &m) {
Expand Down Expand Up @@ -57,7 +92,7 @@ void bind_ast(py::module_ &m) {
= py::class_<KORESort, std::shared_ptr<KORESort>>(ast, "Sort")
.def_property_readonly("is_concrete", &KORESort::isConcrete)
.def("substitute", &KORESort::substitute)
.def("__repr__", print_repr_adapter<KORESort>)
.def("__repr__", print_repr_adapter<KORESort>())
.def(
"__hash__",
[](KORESort const &sort) { return HashSort{}(sort); })
Expand All @@ -75,8 +110,61 @@ void bind_ast(py::module_ &m) {
py::arg("cat") = ValueType{SortCategory::Uncomputed, 0})
.def("add_argument", &KORECompositeSort::addArgument)
.def_property_readonly("name", &KORECompositeSort::getName);

/* Symbols */

py::class_<KORESymbol>(ast, "Symbol")
.def(py::init(&KORESymbol::Create))
.def("__repr__", print_repr_adapter<KORESymbol>())
.def("add_formal_argument", &KORESymbol::addFormalArgument)
.def(py::self == py::self)
.def(py::self != py::self);

py::class_<KOREVariable>(ast, "Variable")
.def(py::init(&KOREVariable::Create))
.def("__repr__", print_repr_adapter<KOREVariable>())
.def_property_readonly("name", &KOREVariable::getName);

/* Patterns */

auto pattern_base
= py::class_<KOREPattern, std::shared_ptr<KOREPattern>>(ast, "Pattern")
.def(py::init(&KOREPattern::load))
.def("__repr__", print_repr_adapter<KOREPattern>())
.def("substitute", &KOREPattern::substitute);

py::class_<KORECompositePattern, std::shared_ptr<KORECompositePattern>>(
ast, "CompositePattern", pattern_base)
.def(py::init(py::overload_cast<std::string const &>(
&KORECompositePattern::Create)))
.def(py::init(
py::overload_cast<KORESymbol *>(&KORECompositePattern::Create)))
.def("add_argument", &KORECompositePattern::addArgument);

py::class_<KOREVariablePattern, std::shared_ptr<KOREVariablePattern>>(
ast, "VariablePattern", pattern_base)
.def(py::init(&KOREVariablePattern::Create))
.def_property_readonly("name", &KOREVariablePattern::getName)
.def_property_readonly("sort", &KOREVariablePattern::getSort);

py::class_<KOREStringPattern, std::shared_ptr<KOREStringPattern>>(
ast, "StringPattern", pattern_base)
.def(py::init(&KOREStringPattern::Create))
.def_property_readonly("contents", &KOREStringPattern::getContents);
}

void bind_parser(py::module_ &mod) {
auto parser = mod.def_submodule("parser", "KORE Parser");

py::class_<KOREParser, std::unique_ptr<KOREParser>>(parser, "Parser")
.def(py::init<std::string>())
.def_static("from_string", &KOREParser::from_string)
.def("pattern", [](KOREParser &parser) {
return std::shared_ptr(parser.pattern());
});
}

PYBIND11_MODULE(_kllvm, m) {
bind_ast(m);
bind_parser(m);
}
2 changes: 1 addition & 1 deletion include/kllvm/parser/KOREParser.h
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ class KOREParser {
: scanner(KOREScanner(filename))
, loc(location(filename)) { }

static KOREParser from_string(std::string text);
static std::unique_ptr<KOREParser> from_string(std::string text);

ptr<KOREDefinition> definition(void);
ptr<KOREPattern> pattern(void);
Expand Down
4 changes: 2 additions & 2 deletions lib/parser/KOREParser.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
namespace kllvm {
namespace parser {

KOREParser KOREParser::from_string(std::string text) {
std::unique_ptr<KOREParser> KOREParser::from_string(std::string text) {
char temp_file_name[] = "tmp.parse.XXXXXX";

if (mkstemp(temp_file_name) == -1) {
Expand All @@ -21,7 +21,7 @@ KOREParser KOREParser::from_string(std::string text) {
os << text;
os.close();

auto parser = KOREParser(temp_file_name);
auto parser = std::make_unique<KOREParser>(temp_file_name);
std::remove(temp_file_name);
return parser;
}
Expand Down
3 changes: 2 additions & 1 deletion nix/overlay.nix
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,8 @@ let
buildPhase = ''
runHook preBuild

LIT_USE_NIX=1 lit -v test
BINDINGS_INSTALL_PATH=${llvm-backend}/bindings/python \
LIT_USE_NIX=1 lit -v test

runHook postBuild
'';
Expand Down
2 changes: 1 addition & 1 deletion runtime/util/ConfigurationSerializer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,7 @@ cached_symbol_sort_list(std::string const &symbol) {
std::string, std::pair<std::string, std::vector<sptr<KORESort>>>>{};

if (cache.find(symbol) == cache.end()) {
cache[symbol] = KOREParser::from_string(symbol).symbol_sort_list();
cache[symbol] = KOREParser::from_string(symbol)->symbol_sort_list();
}

return cache.at(symbol);
Expand Down
Loading