Initial version, pending windows
This commit is contained in:
@@ -27,7 +27,7 @@ BreakBeforeTernaryOperators: true
|
||||
BreakConstructorInitializers: AfterColon
|
||||
BreakInheritanceList: AfterColon
|
||||
BreakStringLiterals: false
|
||||
ColumnLimit: 90
|
||||
ColumnLimit: 98
|
||||
CompactNamespaces: false
|
||||
ConstructorInitializerAllOnOneLineOrOnePerLine: true
|
||||
ConstructorInitializerIndentWidth: 4
|
||||
@@ -65,7 +65,7 @@ PointerAlignment: Left
|
||||
ReferenceAlignment: Left # New in v13. int &name ==> int& name
|
||||
ReflowComments: false
|
||||
SeparateDefinitionBlocks: Always # New in v14.
|
||||
SortIncludes: true
|
||||
SortIncludes: false
|
||||
SortUsingDeclarations: true
|
||||
SpaceAfterCStyleCast: false
|
||||
SpaceAfterLogicalNot: false
|
||||
@@ -7,5 +7,4 @@ insert_final_newline = true
|
||||
[{*.lua,*.rockspec,.luacov}]
|
||||
indent_style = space
|
||||
indent_size = 3
|
||||
call_parentheses = nosingletable
|
||||
max_line_length = 98
|
||||
max_line_length = 105
|
||||
|
||||
37
.github/workflows/busted.yml
vendored
Normal file
37
.github/workflows/busted.yml
vendored
Normal file
@@ -0,0 +1,37 @@
|
||||
name: Busted
|
||||
|
||||
on: [push, pull_request]
|
||||
|
||||
jobs:
|
||||
busted:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
lua_version: ["luajit-openresty", "luajit-2.1.0-beta3", "luajit-git"]
|
||||
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
- name: Setup ‘lua’
|
||||
uses: jkl1337/gh-actions-lua@master
|
||||
with:
|
||||
luaVersion: ${{ matrix.lua_version }}
|
||||
- name: Setup ‘luarocks’
|
||||
uses: jkl1337/gh-actions-luarocks@master
|
||||
- name: Setup dependencies
|
||||
run: |
|
||||
luarocks install busted
|
||||
luarocks install luacov-coveralls
|
||||
- name: Build C library
|
||||
run: |
|
||||
luarocks make --no-install
|
||||
- name: Run busted tests
|
||||
run: busted -c -v
|
||||
- name: Report test coverage
|
||||
if: success()
|
||||
continue-on-error: true
|
||||
run: luacov-coveralls -e .luarocks -e spec
|
||||
env:
|
||||
COVERALLS_REPO_TOKEN: ${{ github.token }}
|
||||
3
.gitignore
vendored
3
.gitignore
vendored
@@ -2,6 +2,9 @@
|
||||
/lua
|
||||
/lua_modules
|
||||
/.luarocks
|
||||
*.pch
|
||||
*.gch
|
||||
*.so
|
||||
*.o
|
||||
.cache/
|
||||
compile_commands.json
|
||||
|
||||
@@ -8,6 +8,6 @@
|
||||
"lua_modules/share/lua/5.1/?.lua",
|
||||
"lua_modules/share/lua/5.1/?/init.lua"
|
||||
],
|
||||
"workspace.library": ["lua_modules/share/lua/5.1"],
|
||||
"workspace.library": ["${3rd}/busted/library", "${3rd}/luassert/library"],
|
||||
"workspace.checkThirdParty": false
|
||||
}
|
||||
|
||||
7
LICENSE
Normal file
7
LICENSE
Normal file
@@ -0,0 +1,7 @@
|
||||
Copyright 2024 John Luebs
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
93
Makefile
Normal file
93
Makefile
Normal file
@@ -0,0 +1,93 @@
|
||||
-include config.mk
|
||||
|
||||
CC := $(CROSS)gcc
|
||||
CP := cp
|
||||
RM := rm
|
||||
LIBFLAG := -shared
|
||||
LIB_EXT := so
|
||||
LUA_INCDIR := /usr/include
|
||||
|
||||
SRCDIR := .
|
||||
|
||||
OPTFLAG := -O2
|
||||
CCFLAGS += $(OPTFLAG) -fPIC -Wall -fvisibility=hidden -Wformat=2 -Wconversion -Wimplicit-fallthrough
|
||||
|
||||
SANITIZE_FLAGS := -fstrict-flex-arrays -fsanitize=undefined -fsanitize=address
|
||||
LTO_FLAGS := -flto=auto
|
||||
|
||||
ifdef SANITIZE
|
||||
CCFLAGS += $(SANITIZE_FLAGS)
|
||||
endif
|
||||
ifdef LTO
|
||||
CCFLAGS += $(LTO_FLAGS)
|
||||
endif
|
||||
|
||||
override CPPFLAGS += -I$(SRCDIR) -I$(SRCDIR)/kiwi -I$(LUA_INCDIR)
|
||||
override CXXFLAGS += -std=c++14 -fno-rtti $(CCFLAGS)
|
||||
override CFLAGS += -std=c99 $(CCFLAGS)
|
||||
|
||||
ifneq ($(filter %gcc,$(CC)),)
|
||||
CXX := $(patsubst %gcc,%g++,$(CC))
|
||||
PCH := ljkiwi.hpp.gch
|
||||
else
|
||||
ifneq ($(filter %clang,$(CC)),)
|
||||
CXX := $(patsubst %clang,%clang++,$(CC))
|
||||
override CXXFLAGS += -pedantic -Wno-c99-extensions
|
||||
PCH := ljkiwi.hpp.pch
|
||||
endif
|
||||
endif
|
||||
|
||||
ifdef LUA
|
||||
LUA_VERSION ?= $(lastword $(shell $(LUA) -e "print(_VERSION)"))
|
||||
endif
|
||||
|
||||
ifndef LUA_VERSION
|
||||
LJKIWI_CKIWI := 1
|
||||
else
|
||||
ifeq ($(LUA_VERSION),5.1)
|
||||
LJKIWI_CKIWI := 1
|
||||
endif
|
||||
endif
|
||||
|
||||
KIWI_LIB := AssocVector.h constraint.h debug.h errors.h expression.h kiwi.h maptype.h \
|
||||
row.h shareddata.h solver.h solverimpl.h strength.h symbol.h symbolics.h term.h \
|
||||
util.h variable.h version.h
|
||||
|
||||
OBJS := luakiwi.o
|
||||
ifdef LJKIWI_CKIWI
|
||||
OBJS += ckiwi.o
|
||||
endif
|
||||
|
||||
vpath %.cpp $(SRCDIR)/ckiwi $(SRCDIR)/luakiwi
|
||||
vpath %.h $(SRCDIR)/ckiwi $(SRCDIR)/luakiwi $(SRCDIR)/kiwi/kiwi
|
||||
|
||||
all: ljkiwi.$(LIB_EXT)
|
||||
|
||||
install:
|
||||
$(CP) -f ljkiwi.$(LIB_EXT) $(INST_LIBDIR)/ljkiwi.$(LIB_EXT)
|
||||
$(CP) -f kiwi.lua $(INST_LUADIR)/kiwi.lua
|
||||
|
||||
clean:
|
||||
$(RM) -f ljkiwi.$(LIB_EXT) $(OBJS) $(PCH)
|
||||
|
||||
|
||||
ljkiwi.hpp.gch: $(KIWI_LIB)
|
||||
ckiwi.o: $(PCH) ckiwi.cpp ckiwi.h $(KIWI_LIB)
|
||||
luakiwi.o: $(PCH) luakiwi-int.h luacompat.h $(KIWI_LIB)
|
||||
|
||||
ljkiwi.$(LIB_EXT): $(OBJS)
|
||||
$(CXX) $(CCFLAGS) $(LIBFLAG) -o $@ $(OBJS)
|
||||
|
||||
%.hpp.gch: %.hpp
|
||||
$(CXX) $(CPPFLAGS) $(CXXFLAGS) -x c++-header -o $@ $<
|
||||
|
||||
%.hpp.pch: %.hpp
|
||||
$(CXX) $(CPPFLAGS) $(CXXFLAGS) -x c++-header -o $@ $<
|
||||
|
||||
%.o: %.c
|
||||
$(CC) $(CPPFLAGS) $(CFLAGS) -c -o $@ $<
|
||||
|
||||
%.o: %.cpp
|
||||
$(CXX) $(CPPFLAGS) $(CXXFLAGS) -c -o $@ $<
|
||||
|
||||
.PHONY: all install clean
|
||||
94
README.md
Normal file
94
README.md
Normal file
@@ -0,0 +1,94 @@
|
||||
ljkiwi - Free LuaJIT FFI and Lua C API kiwi (Cassowary derived) constraint solver.
|
||||
|
||||
[](https://github.com/jkl1337/ljkiwi/actions/workflows/busted.yml)
|
||||
[](https://coveralls.io/github/jkl1337/ljkiwi?branch=master)
|
||||
[](https://luarocks.org/modules/jkl/kiwi)
|
||||
|
||||
# Introduction
|
||||
|
||||
Kiwi is a reasonably efficient C++ implementation of the Cassowary constraint solving algorithm. It is an implementation of the algorithm as described in the paper ["The Cassowary Linear Arithmetic Constraint Solving Algorithm"](http://www.cs.washington.edu/research/constraints/cassowary/techreports/cassowaryTR.pdf) by Greg J. Badros and Alan Borning. The Kiwi implementation is not based on the original C++ implementation, but is a ground-up reimplementation with performance 10x to 500x faster in typical use.
|
||||
Cassowary constraint solving is a technique that is particularly well suited to user interface layout. It is the algorithm Apple uses for iOS and OS X Auto Layout.
|
||||
|
||||
There are a few Lua implementations or attempts. The SILE typesetting system has a pure Lua implementation of the original Cassowary code, which appears to be correct but is quite slow. There are two extant Lua ports of Kiwi, one that is based on a C rewrite of Kiwi. However testing of these was not encouraging with either segfaults or incorrect results.
|
||||
Since the C++ Kiwi library is well tested and widely used it was simpler to provide a LuaJIT FFI wrapper. There is also a Lua C API binding with support for 5.1 through 5.4.
|
||||
This package has no dependencies other than a supported C++14 compiler to compile the included Kiwi library and a small C wrapper.
|
||||
|
||||
The Lua API has a pure Lua expression builder. There is of course some overhead to this, however in most cases expression building is infrequent and the underlying structures can be reused.
|
||||
|
||||
The wrapper is quite close to the Kiwi C++/Python port with a few naming changes.
|
||||
|
||||
## Example
|
||||
|
||||
```lua
|
||||
local kiwi = require("kiwi")
|
||||
local Var = kiwi.Var
|
||||
|
||||
local Button = setmetatable({}, {
|
||||
__call = function(_, identifier)
|
||||
return setmetatable({
|
||||
left = Var(identifier .. " left"),
|
||||
width = Var(identifier .. " width"),
|
||||
}, {
|
||||
__tostring = function(self)
|
||||
return "Button(" .. self.left:value() .. ", " .. self.width:value() .. ")"
|
||||
end,
|
||||
})
|
||||
end,
|
||||
})
|
||||
|
||||
local b1 = Button("b1")
|
||||
local b2 = Button("b2")
|
||||
|
||||
local left_edge = Var("left")
|
||||
local right_edge = Var("width")
|
||||
|
||||
local STRONG = kiwi.Strength.STRONG
|
||||
|
||||
-- stylua: ignore start
|
||||
local constraints = {
|
||||
left_edge :eq(0.0),
|
||||
-- two buttons are the same width
|
||||
b1.width :eq(b2.width),
|
||||
-- button1 starts 50 from the left margin
|
||||
b1.left :eq(left_edge + 50),
|
||||
-- button2 ends 50 from the right margin
|
||||
right_edge :eq(b2.left + b2.width + 50),
|
||||
-- button2 starts at least 100 from the end of button1. This is the "elastic" constraint
|
||||
b2.left :ge(b1.left + b1.width + 100),
|
||||
-- button1 has a minimum width of 87
|
||||
b1.width :ge(87),
|
||||
-- button1 has a preferred width of 87
|
||||
b1.width :eq(87, STRONG),
|
||||
-- button2 has minimum width of 113
|
||||
b2.width :ge(113),
|
||||
-- button2 has a preferred width of 113
|
||||
b2.width :eq(113, STRONG),
|
||||
}
|
||||
-- stylua: ignore end
|
||||
|
||||
local solver = kiwi.Solver()
|
||||
|
||||
for _, c in ipairs(constraints) do
|
||||
solver:add_constraint(c)
|
||||
end
|
||||
|
||||
solver:update_vars()
|
||||
|
||||
print(b1) -- Button(50, 113)
|
||||
print(b2) -- Button(263, 113)
|
||||
print(left_edge:value()) -- 0
|
||||
print(right_edge:value()) -- 426
|
||||
|
||||
solver:add_edit_var(right_edge, STRONG)
|
||||
solver:suggest_value(right_edge, 500)
|
||||
solver:update_vars()
|
||||
print(b1) -- Button(50, 113)
|
||||
print(b2) -- Button(337, 113)
|
||||
print(right_edge:value()) -- 500
|
||||
|
||||
```
|
||||
|
||||
In addition to the expression builder there is a convenience constraints submodule with: `pair_ratio`, `pair`, and `single` to allow efficient construction of the most common simple expression types for GUI layout.
|
||||
|
||||
## Documentation
|
||||
WIP - However the API is fully annotated and will work with lua-language-server. Documentation can also be generated with lua-language-server.
|
||||
366
ckiwi/ckiwi.cpp
Normal file
366
ckiwi/ckiwi.cpp
Normal file
@@ -0,0 +1,366 @@
|
||||
#include "ljkiwi.hpp"
|
||||
#include "ckiwi.h"
|
||||
|
||||
#include <kiwi/kiwi.h>
|
||||
|
||||
#include <cstdlib>
|
||||
#include <climits>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
|
||||
#if defined(__GNUC__) && !defined(LJKIWI_NO_BUILTIN)
|
||||
#define lk_likely(x) (__builtin_expect(((x) != 0), 1))
|
||||
#define lk_unlikely(x) (__builtin_expect(((x) != 0), 0))
|
||||
#else
|
||||
#define lk_likely(x) (x)
|
||||
#define lk_unlikely(x) (x)
|
||||
#endif
|
||||
|
||||
namespace {
|
||||
|
||||
using namespace kiwi;
|
||||
|
||||
const KiwiErr* new_error(const KiwiErr* base, const std::exception& ex) {
|
||||
if (!std::strcmp(ex.what(), base->message))
|
||||
return base;
|
||||
|
||||
const auto msg_n = std::strlen(ex.what()) + 1;
|
||||
|
||||
auto* mem = static_cast<char*>(std::malloc(sizeof(KiwiErr) + msg_n));
|
||||
if (!mem) {
|
||||
return base;
|
||||
}
|
||||
|
||||
const auto* err = new (mem) KiwiErr {base->kind, mem + sizeof(KiwiErr), true};
|
||||
std::memcpy(const_cast<char*>(err->message), ex.what(), msg_n);
|
||||
return err;
|
||||
}
|
||||
|
||||
static const constexpr KiwiErr kKiwiErrUnhandledCxxException {
|
||||
KiwiErrUnknown,
|
||||
"An unhandled C++ exception occurred."};
|
||||
|
||||
static const constexpr KiwiErr kKiwiErrNullObjectArg0 {
|
||||
KiwiErrNullObject,
|
||||
"null object passed as argument #0 (self)"};
|
||||
|
||||
static const constexpr KiwiErr kKiwiErrNullObjectArg1 {
|
||||
KiwiErrNullObject,
|
||||
"null object passed as argument #1"};
|
||||
|
||||
template<typename F>
|
||||
const KiwiErr* wrap_err(F&& f) {
|
||||
try {
|
||||
f();
|
||||
} catch (const UnsatisfiableConstraint& ex) {
|
||||
static const constexpr KiwiErr err {
|
||||
KiwiErrUnsatisfiableConstraint,
|
||||
"The constraint cannot be satisfied."};
|
||||
return &err;
|
||||
} catch (const UnknownConstraint& ex) {
|
||||
static const constexpr KiwiErr err {
|
||||
KiwiErrUnknownConstraint,
|
||||
"The constraint has not been added to the solver."};
|
||||
return &err;
|
||||
|
||||
} catch (const DuplicateConstraint& ex) {
|
||||
static const constexpr KiwiErr err {
|
||||
KiwiErrDuplicateConstraint,
|
||||
"The constraint has already been added to the solver."};
|
||||
return &err;
|
||||
|
||||
} catch (const UnknownEditVariable& ex) {
|
||||
static const constexpr KiwiErr err {
|
||||
KiwiErrUnknownEditVariable,
|
||||
"The edit variable has not been added to the solver."};
|
||||
return &err;
|
||||
|
||||
} catch (const DuplicateEditVariable& ex) {
|
||||
static const constexpr KiwiErr err {
|
||||
KiwiErrDuplicateEditVariable,
|
||||
"The edit variable has already been added to the solver."};
|
||||
return &err;
|
||||
|
||||
} catch (const BadRequiredStrength& ex) {
|
||||
static const constexpr KiwiErr err {
|
||||
KiwiErrBadRequiredStrength,
|
||||
"A required strength cannot be used in this context."};
|
||||
return &err;
|
||||
|
||||
} catch (const InternalSolverError& ex) {
|
||||
static const constexpr KiwiErr base {
|
||||
KiwiErrInternalSolverError,
|
||||
"An internal solver error occurred."};
|
||||
return new_error(&base, ex);
|
||||
} catch (std::bad_alloc&) {
|
||||
static const constexpr KiwiErr err {KiwiErrAlloc, "A memory allocation failed."};
|
||||
return &err;
|
||||
} catch (const std::exception& ex) {
|
||||
return new_error(&kKiwiErrUnhandledCxxException, ex);
|
||||
} catch (...) {
|
||||
return &kKiwiErrUnhandledCxxException;
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
template<typename P, typename R, typename F>
|
||||
const KiwiErr* wrap_err(P self, F&& f) {
|
||||
if (lk_unlikely(!self)) {
|
||||
return &kKiwiErrNullObjectArg0;
|
||||
}
|
||||
return wrap_err([&]() { f(self->solver); });
|
||||
}
|
||||
|
||||
template<typename P, typename R, typename F>
|
||||
const KiwiErr* wrap_err(P* self, R* item, F&& f) {
|
||||
if (lk_unlikely(!self)) {
|
||||
return &kKiwiErrNullObjectArg0;
|
||||
} else if (lk_unlikely(!item)) {
|
||||
return &kKiwiErrNullObjectArg1;
|
||||
}
|
||||
return wrap_err([&]() { f(self->solver, item); });
|
||||
}
|
||||
|
||||
template<typename T, typename... Args>
|
||||
T* make_unmanaged(Args... args) {
|
||||
auto* o = new T(std::forward<Args>(args)...);
|
||||
o->m_refcount = 1;
|
||||
return o;
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
void release_unmanaged(T* p) {
|
||||
if (lk_likely(p)) {
|
||||
if (--p->m_refcount == 0)
|
||||
delete p;
|
||||
}
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
T* retain_unmanaged(T* p) {
|
||||
if (lk_likely(p))
|
||||
p->m_refcount++;
|
||||
return p;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
extern "C" {
|
||||
|
||||
KiwiVar* kiwi_var_construct(const char* name) {
|
||||
return make_unmanaged<VariableData>(lk_likely(name) ? name : "");
|
||||
}
|
||||
|
||||
void kiwi_var_release(KiwiVar* var) {
|
||||
release_unmanaged(var);
|
||||
}
|
||||
|
||||
void kiwi_var_retain(KiwiVar* var) {
|
||||
retain_unmanaged(var);
|
||||
}
|
||||
|
||||
const char* kiwi_var_name(const KiwiVar* var) {
|
||||
return lk_likely(var) ? var->name().c_str() : "(<null>)";
|
||||
}
|
||||
|
||||
void kiwi_var_set_name(KiwiVar* var, const char* name) {
|
||||
if (lk_likely(var && name))
|
||||
var->setName(name);
|
||||
}
|
||||
|
||||
double kiwi_var_value(const KiwiVar* var) {
|
||||
return lk_likely(var) ? var->value() : std::numeric_limits<double>::quiet_NaN();
|
||||
}
|
||||
|
||||
void kiwi_var_set_value(KiwiVar* var, double value) {
|
||||
if (lk_likely(var))
|
||||
var->setValue(value);
|
||||
}
|
||||
|
||||
void kiwi_expression_retain(KiwiExpression* expr) {
|
||||
if (lk_unlikely(!expr))
|
||||
return;
|
||||
for (auto* t = expr->terms_; t != expr->terms_ + expr->term_count; ++t) {
|
||||
retain_unmanaged(t->var);
|
||||
}
|
||||
}
|
||||
|
||||
void kiwi_expression_destroy(KiwiExpression* expr) {
|
||||
if (lk_unlikely(!expr))
|
||||
return;
|
||||
|
||||
if (expr->owner) {
|
||||
release_unmanaged(expr->owner);
|
||||
} else {
|
||||
for (auto* t = expr->terms_; t != expr->terms_ + expr->term_count; ++t) {
|
||||
release_unmanaged(t->var);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
KiwiConstraint* kiwi_constraint_construct(
|
||||
const KiwiExpression* lhs,
|
||||
const KiwiExpression* rhs,
|
||||
enum KiwiRelOp op,
|
||||
double strength
|
||||
) {
|
||||
if (strength < 0.0) {
|
||||
strength = kiwi::strength::required;
|
||||
}
|
||||
|
||||
std::vector<Term> terms;
|
||||
terms.reserve(static_cast<std::size_t>(
|
||||
(lhs && lhs->term_count > 0 ? lhs->term_count : 0)
|
||||
+ (rhs && rhs->term_count > 0 ? rhs->term_count : 0)
|
||||
));
|
||||
|
||||
if (lhs) {
|
||||
for (int i = 0; i < lhs->term_count; ++i) {
|
||||
const auto& t = lhs->terms_[i];
|
||||
if (t.var)
|
||||
terms.emplace_back(Variable(t.var), t.coefficient);
|
||||
}
|
||||
}
|
||||
if (rhs) {
|
||||
for (int i = 0; i < rhs->term_count; ++i) {
|
||||
const auto& t = rhs->terms_[i];
|
||||
if (t.var)
|
||||
terms.emplace_back(Variable(t.var), -t.coefficient);
|
||||
}
|
||||
}
|
||||
|
||||
return make_unmanaged<ConstraintData>(
|
||||
Expression(std::move(terms), (lhs ? lhs->constant : 0.0) - (rhs ? rhs->constant : 0.0)),
|
||||
static_cast<RelationalOperator>(op),
|
||||
strength
|
||||
);
|
||||
}
|
||||
|
||||
void kiwi_constraint_release(KiwiConstraint* c) {
|
||||
release_unmanaged(c);
|
||||
}
|
||||
|
||||
void kiwi_constraint_retain(KiwiConstraint* c) {
|
||||
retain_unmanaged(c);
|
||||
}
|
||||
|
||||
double kiwi_constraint_strength(const KiwiConstraint* c) {
|
||||
return lk_likely(c) ? c->strength() : std::numeric_limits<double>::quiet_NaN();
|
||||
}
|
||||
|
||||
enum KiwiRelOp kiwi_constraint_op(const KiwiConstraint* c) {
|
||||
return lk_likely(c) ? static_cast<KiwiRelOp>(c->op()) : KiwiRelOp::KIWI_OP_EQ;
|
||||
}
|
||||
|
||||
bool kiwi_constraint_violated(const KiwiConstraint* c) {
|
||||
return lk_likely(c) ? c->violated() : false;
|
||||
}
|
||||
|
||||
int kiwi_constraint_expression(KiwiConstraint* c, KiwiExpression* out, int out_size) {
|
||||
if (lk_unlikely(!c))
|
||||
return 0;
|
||||
|
||||
const auto& expr = c->expression();
|
||||
const auto& terms = expr.terms();
|
||||
int n = terms.size() < INT_MAX ? static_cast<int>(terms.size()) : INT_MAX;
|
||||
if (!out || out_size < n)
|
||||
return n;
|
||||
|
||||
for (int i = 0; i < n; ++i) {
|
||||
const auto& t = terms[static_cast<std::size_t>(i)];
|
||||
out->terms_[i].var = const_cast<Variable&>(t.variable()).ptr();
|
||||
out->terms_[i].coefficient = t.coefficient();
|
||||
}
|
||||
out->constant = expr.constant();
|
||||
out->term_count = n;
|
||||
out->owner = retain_unmanaged(c);
|
||||
|
||||
return n;
|
||||
}
|
||||
|
||||
struct KiwiSolver {
|
||||
unsigned error_mask;
|
||||
Solver solver;
|
||||
};
|
||||
|
||||
KiwiSolver* kiwi_solver_construct(unsigned error_mask) {
|
||||
return new KiwiSolver {error_mask};
|
||||
}
|
||||
|
||||
void kiwi_solver_destroy(KiwiSolver* s) {
|
||||
if (lk_likely(s))
|
||||
delete s;
|
||||
}
|
||||
|
||||
unsigned kiwi_solver_get_error_mask(const KiwiSolver* s) {
|
||||
return lk_likely(s) ? s->error_mask : 0;
|
||||
}
|
||||
|
||||
void kiwi_solver_set_error_mask(KiwiSolver* s, unsigned mask) {
|
||||
if (lk_likely(s))
|
||||
s->error_mask = mask;
|
||||
}
|
||||
|
||||
const KiwiErr* kiwi_solver_add_constraint(KiwiSolver* s, KiwiConstraint* constraint) {
|
||||
return wrap_err(s, constraint, [](auto&& s, auto&& c) { s.addConstraint(Constraint(c)); });
|
||||
}
|
||||
|
||||
const KiwiErr* kiwi_solver_remove_constraint(KiwiSolver* s, KiwiConstraint* constraint) {
|
||||
return wrap_err(s, constraint, [](auto&& s, auto&& c) { s.removeConstraint(Constraint(c)); });
|
||||
}
|
||||
|
||||
bool kiwi_solver_has_constraint(const KiwiSolver* s, KiwiConstraint* constraint) {
|
||||
if (lk_unlikely(!s || !constraint))
|
||||
return 0;
|
||||
return s->solver.hasConstraint(Constraint(constraint));
|
||||
}
|
||||
|
||||
const KiwiErr* kiwi_solver_add_edit_var(KiwiSolver* s, KiwiVar* var, double strength) {
|
||||
return wrap_err(s, var, [strength](auto& s, auto&& v) {
|
||||
s.addEditVariable(Variable(v), strength);
|
||||
});
|
||||
}
|
||||
|
||||
const KiwiErr* kiwi_solver_remove_edit_var(KiwiSolver* s, KiwiVar* var) {
|
||||
return wrap_err(s, var, [](auto&& s, auto&& v) { s.removeEditVariable(Variable(v)); });
|
||||
}
|
||||
|
||||
bool kiwi_solver_has_edit_var(const KiwiSolver* s, KiwiVar* var) {
|
||||
if (lk_unlikely(!s || !var))
|
||||
return 0;
|
||||
return s->solver.hasEditVariable(Variable(var));
|
||||
}
|
||||
|
||||
const KiwiErr* kiwi_solver_suggest_value(KiwiSolver* s, KiwiVar* var, double value) {
|
||||
return wrap_err(s, var, [value](auto&& s, auto&& v) { s.suggestValue(Variable(v), value); });
|
||||
}
|
||||
|
||||
void kiwi_solver_update_vars(KiwiSolver* s) {
|
||||
if (lk_likely(s))
|
||||
s->solver.updateVariables();
|
||||
}
|
||||
|
||||
void kiwi_solver_reset(KiwiSolver* s) {
|
||||
if (lk_likely(s))
|
||||
s->solver.reset();
|
||||
}
|
||||
|
||||
void kiwi_solver_dump(const KiwiSolver* s) {
|
||||
if (lk_likely(s))
|
||||
s->solver.dump();
|
||||
}
|
||||
|
||||
char* kiwi_solver_dumps(const KiwiSolver* s) {
|
||||
if (lk_unlikely(!s))
|
||||
return nullptr;
|
||||
|
||||
const auto& str = s->solver.dumps();
|
||||
const auto buf_size = str.size() + 1;
|
||||
auto* buf = static_cast<char*>(std::malloc(buf_size));
|
||||
if (!buf)
|
||||
return nullptr;
|
||||
std::memcpy(buf, str.c_str(), str.size() + 1);
|
||||
return buf;
|
||||
}
|
||||
|
||||
} // extern "C"
|
||||
133
ckiwi/ckiwi.h
Normal file
133
ckiwi/ckiwi.h
Normal file
@@ -0,0 +1,133 @@
|
||||
#ifndef LJKIWI_CKIWI_H_
|
||||
#define LJKIWI_CKIWI_H_
|
||||
|
||||
#if !defined(_MSC_VER) || _MSC_VER >= 1900
|
||||
#undef LJKIWI_USE_FAM_1
|
||||
#else
|
||||
#define LJKIWI_USE_FAM_1
|
||||
#endif
|
||||
|
||||
#ifdef __cplusplus
|
||||
|
||||
namespace kiwi {
|
||||
class VariableData;
|
||||
class Constraint;
|
||||
} // namespace kiwi
|
||||
|
||||
typedef kiwi::VariableData KiwiVar;
|
||||
typedef kiwi::ConstraintData KiwiConstraint;
|
||||
|
||||
extern "C" {
|
||||
|
||||
#else
|
||||
typedef struct KiwiVar KiwiVar;
|
||||
typedef struct KiwiConstraint KiwiConstraint;
|
||||
|
||||
#endif
|
||||
|
||||
#if __GNUC__
|
||||
#pragma GCC visibility push(default)
|
||||
#define LJKIWI_DATA_EXPORT __attribute__((visibility("default")))
|
||||
#endif
|
||||
|
||||
// LuaJIT start
|
||||
enum KiwiErrKind {
|
||||
KiwiErrNone,
|
||||
KiwiErrUnsatisfiableConstraint = 1,
|
||||
KiwiErrUnknownConstraint,
|
||||
KiwiErrDuplicateConstraint,
|
||||
KiwiErrUnknownEditVariable,
|
||||
KiwiErrDuplicateEditVariable,
|
||||
KiwiErrBadRequiredStrength,
|
||||
KiwiErrInternalSolverError,
|
||||
KiwiErrAlloc,
|
||||
KiwiErrNullObject,
|
||||
KiwiErrUnknown,
|
||||
};
|
||||
|
||||
enum KiwiRelOp { KIWI_OP_LE, KIWI_OP_GE, KIWI_OP_EQ };
|
||||
|
||||
typedef struct KiwiTerm {
|
||||
KiwiVar* var;
|
||||
double coefficient;
|
||||
} KiwiTerm;
|
||||
|
||||
typedef struct KiwiExpression {
|
||||
double constant;
|
||||
int term_count;
|
||||
KiwiConstraint* owner;
|
||||
|
||||
#if defined(LJKIWI_LUAJIT_DEF)
|
||||
KiwiTerm terms_[?];
|
||||
#elif defined(LJKIWI_USE_FAM_1)
|
||||
KiwiTerm terms_[1]; // LuaJIT: struct KiwiTerm terms_[?];
|
||||
#else
|
||||
KiwiTerm terms_[];
|
||||
#endif
|
||||
|
||||
} KiwiExpression;
|
||||
|
||||
typedef struct KiwiErr {
|
||||
enum KiwiErrKind kind;
|
||||
const char* message;
|
||||
bool must_free;
|
||||
} KiwiErr;
|
||||
|
||||
struct KiwiSolver;
|
||||
|
||||
KiwiVar* kiwi_var_construct(const char* name);
|
||||
void kiwi_var_release(KiwiVar* var);
|
||||
void kiwi_var_retain(KiwiVar* var);
|
||||
|
||||
const char* kiwi_var_name(const KiwiVar* var);
|
||||
void kiwi_var_set_name(KiwiVar* var, const char* name);
|
||||
double kiwi_var_value(const KiwiVar* var);
|
||||
void kiwi_var_set_value(KiwiVar* var, double value);
|
||||
|
||||
void kiwi_expression_retain(KiwiExpression* expr);
|
||||
void kiwi_expression_destroy(KiwiExpression* expr);
|
||||
|
||||
KiwiConstraint* kiwi_constraint_construct(
|
||||
const KiwiExpression* lhs,
|
||||
const KiwiExpression* rhs,
|
||||
enum KiwiRelOp op,
|
||||
double strength
|
||||
);
|
||||
void kiwi_constraint_release(KiwiConstraint* c);
|
||||
void kiwi_constraint_retain(KiwiConstraint* c);
|
||||
|
||||
double kiwi_constraint_strength(const KiwiConstraint* c);
|
||||
enum KiwiRelOp kiwi_constraint_op(const KiwiConstraint* c);
|
||||
bool kiwi_constraint_violated(const KiwiConstraint* c);
|
||||
int kiwi_constraint_expression(KiwiConstraint* c, KiwiExpression* out, int out_size);
|
||||
|
||||
KiwiSolver* kiwi_solver_construct(unsigned error_mask);
|
||||
void kiwi_solver_destroy(KiwiSolver* s);
|
||||
unsigned kiwi_solver_get_error_mask(const KiwiSolver* s);
|
||||
void kiwi_solver_set_error_mask(KiwiSolver* s, unsigned mask);
|
||||
|
||||
const KiwiErr* kiwi_solver_add_constraint(KiwiSolver* s, KiwiConstraint* constraint);
|
||||
const KiwiErr* kiwi_solver_remove_constraint(KiwiSolver* s, KiwiConstraint* constraint);
|
||||
bool kiwi_solver_has_constraint(const KiwiSolver* s, KiwiConstraint* constraint);
|
||||
const KiwiErr* kiwi_solver_add_edit_var(KiwiSolver* s, KiwiVar* var, double strength);
|
||||
const KiwiErr* kiwi_solver_remove_edit_var(KiwiSolver* s, KiwiVar* var);
|
||||
bool kiwi_solver_has_edit_var(const KiwiSolver* s, KiwiVar* var);
|
||||
const KiwiErr* kiwi_solver_suggest_value(KiwiSolver* s, KiwiVar* var, double value);
|
||||
void kiwi_solver_update_vars(KiwiSolver* sp);
|
||||
void kiwi_solver_reset(KiwiSolver* sp);
|
||||
void kiwi_solver_dump(const KiwiSolver* sp);
|
||||
char* kiwi_solver_dumps(const KiwiSolver* sp);
|
||||
// LuaJIT end
|
||||
|
||||
#if __GNUC__
|
||||
#pragma GCC visibility pop
|
||||
#endif
|
||||
|
||||
#ifdef __cplusplus
|
||||
} // extern "C"
|
||||
#endif
|
||||
|
||||
// Local Variables:
|
||||
// mode: c++
|
||||
// End:
|
||||
#endif // LJKIWI_CKIWI_H_
|
||||
36
kiwi-scm-1.rockspec
Normal file
36
kiwi-scm-1.rockspec
Normal file
@@ -0,0 +1,36 @@
|
||||
rockspec_format = "3.0"
|
||||
package = "kiwi"
|
||||
version = "scm-1"
|
||||
source = {
|
||||
url = "git+https://github.com/jkl1337/ljkiwi",
|
||||
}
|
||||
description = {
|
||||
summary = "LuaJIT FFI and Lua binding for the Kiwi constraint solver.",
|
||||
detailed = [[
|
||||
kiwi is a LuaJIT FFI and Lua binding for the Kiwi constraint solver. Kiwi is a fast
|
||||
implementation of the Cassowary constraint solving algorithm. kiwi provides
|
||||
reasonably efficient bindings using the LuaJIT FFI and convential Lua C bindings.]],
|
||||
license = "MIT",
|
||||
issues_url = "https://github.com/jkl1337/ljkiwi/issues",
|
||||
maintainer = "John Luebs",
|
||||
}
|
||||
dependencies = {
|
||||
"lua >= 5.1",
|
||||
}
|
||||
|
||||
build = {
|
||||
type = "make",
|
||||
build_variables = {
|
||||
LUA = "$(LUA)",
|
||||
CFLAGS = "$(CFLAGS)",
|
||||
LUA_INCDIR = "$(LUA_INCDIR)",
|
||||
LIBFLAG = "$(LIBFLAG)",
|
||||
LIB_EXT = "$(LIB_EXTENSION)",
|
||||
OBJ_EXT = "$(OBJ_EXTENSION)",
|
||||
},
|
||||
install_variables = {
|
||||
INST_LIBDIR = "$(LIBDIR)",
|
||||
INST_LUADIR = "$(LUADIR)",
|
||||
LIB_EXT = "$(LIB_EXTENSION)",
|
||||
},
|
||||
}
|
||||
@@ -145,7 +145,7 @@ public:
|
||||
/* Dump a representation of the solver internals to stdout.
|
||||
|
||||
*/
|
||||
void dump()
|
||||
void dump() const
|
||||
{
|
||||
debug::dump( m_impl );
|
||||
}
|
||||
@@ -153,7 +153,7 @@ public:
|
||||
/* Dump a representation of the solver internals to a stream.
|
||||
|
||||
*/
|
||||
void dump( std::ostream& out )
|
||||
void dump( std::ostream& out ) const
|
||||
{
|
||||
debug::dump( m_impl, out );
|
||||
}
|
||||
@@ -161,7 +161,7 @@ public:
|
||||
/* Dump a representation of the solver internals to a string.
|
||||
|
||||
*/
|
||||
std::string dumps()
|
||||
std::string dumps() const
|
||||
{
|
||||
return debug::dumps( m_impl );
|
||||
}
|
||||
|
||||
@@ -64,7 +64,7 @@ public:
|
||||
void setValue(double value) { m_data->setValue(value); }
|
||||
|
||||
// operator== is used for symbolics
|
||||
bool equals(const Variable &other)
|
||||
bool equals(const Variable &other) const
|
||||
{
|
||||
return m_data == other.m_data;
|
||||
}
|
||||
|
||||
1
ljkiwi.hpp
Normal file
1
ljkiwi.hpp
Normal file
@@ -0,0 +1 @@
|
||||
#include <kiwi/kiwi.h>
|
||||
155
luakiwi/luacompat.h
Normal file
155
luakiwi/luacompat.h
Normal file
@@ -0,0 +1,155 @@
|
||||
#ifndef LJKIWI_LUACOMPAT_H_
|
||||
#define LJKIWI_LUACOMPAT_H_
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif // __cplusplus
|
||||
|
||||
#include <lauxlib.h>
|
||||
#include <lua.h>
|
||||
#include <lualib.h>
|
||||
|
||||
#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM == 501 && defined(__GNUC__)
|
||||
#define LJKIWI_LJ_COMPAT_ATTR __attribute__((weak, visibility("default")))
|
||||
#else
|
||||
#define LJKIWI_LJ_COMPAT_ATTR static
|
||||
#endif
|
||||
|
||||
#if !defined(LUA_VERSION_NUM) || LUA_VERSION_NUM == 501
|
||||
|
||||
#define LUA_OPADD 0
|
||||
#define LUA_OPSUB 1
|
||||
#define LUA_OPMUL 2
|
||||
#define LUA_OPDIV 3
|
||||
#define LUA_OPMOD 4
|
||||
#define LUA_OPPOW 5
|
||||
#define LUA_OPUNM 6
|
||||
|
||||
static int lua_absindex(lua_State* L, int i) {
|
||||
if (i < 0 && i > LUA_REGISTRYINDEX)
|
||||
i += lua_gettop(L) + 1;
|
||||
return i;
|
||||
}
|
||||
|
||||
LJKIWI_LJ_COMPAT_ATTR lua_Number lua_tonumberx(lua_State* L, int i, int* isnum) {
|
||||
lua_Number n = lua_tonumber(L, i);
|
||||
if (isnum != NULL) {
|
||||
*isnum = (n != 0 || lua_isnumber(L, i));
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
LJKIWI_LJ_COMPAT_ATTR lua_Integer lua_tointegerx(lua_State* L, int i, int* isnum) {
|
||||
int ok = 0;
|
||||
lua_Number n = lua_tonumberx(L, i, &ok);
|
||||
if (ok) {
|
||||
if (n == (lua_Integer)n) {
|
||||
if (isnum)
|
||||
*isnum = 1;
|
||||
return (lua_Integer)n;
|
||||
}
|
||||
}
|
||||
if (isnum)
|
||||
*isnum = 0;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static const char* luaL_tolstring(lua_State* L, int idx, size_t* len) {
|
||||
if (!luaL_callmeta(L, idx, "__tostring")) {
|
||||
int t = lua_type(L, idx), tt = 0;
|
||||
char const* name = NULL;
|
||||
switch (t) {
|
||||
case LUA_TNIL:
|
||||
lua_pushliteral(L, "nil");
|
||||
break;
|
||||
case LUA_TSTRING:
|
||||
case LUA_TNUMBER:
|
||||
lua_pushvalue(L, idx);
|
||||
break;
|
||||
case LUA_TBOOLEAN:
|
||||
if (lua_toboolean(L, idx))
|
||||
lua_pushliteral(L, "true");
|
||||
else
|
||||
lua_pushliteral(L, "false");
|
||||
break;
|
||||
default:
|
||||
tt = luaL_getmetafield(L, idx, "__name");
|
||||
name = (tt == LUA_TSTRING) ? lua_tostring(L, -1) : lua_typename(L, t);
|
||||
lua_pushfstring(L, "%s: %p", name, lua_topointer(L, idx));
|
||||
if (tt != LUA_TNIL)
|
||||
lua_replace(L, -2);
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
if (!lua_isstring(L, -1))
|
||||
luaL_error(L, "'__tostring' must return a string");
|
||||
}
|
||||
return lua_tolstring(L, -1, len);
|
||||
}
|
||||
|
||||
#endif /* LUA_VERSION_NUM == 501 */
|
||||
|
||||
#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM <= 502
|
||||
|
||||
static void compat_reverse(lua_State* L, int a, int b) {
|
||||
for (; a < b; ++a, --b) {
|
||||
lua_pushvalue(L, a);
|
||||
lua_pushvalue(L, b);
|
||||
lua_replace(L, a);
|
||||
lua_replace(L, b);
|
||||
}
|
||||
}
|
||||
|
||||
static void lua_rotate(lua_State* L, int idx, int n) {
|
||||
int n_elems = 0;
|
||||
idx = lua_absindex(L, idx);
|
||||
n_elems = lua_gettop(L) - idx + 1;
|
||||
if (n < 0)
|
||||
n += n_elems;
|
||||
if (n > 0 && n < n_elems) {
|
||||
luaL_checkstack(L, 2, "not enough stack slots available");
|
||||
n = n_elems - n;
|
||||
compat_reverse(L, idx, idx + n - 1);
|
||||
compat_reverse(L, idx + n, idx + n_elems - 1);
|
||||
compat_reverse(L, idx, idx + n_elems - 1);
|
||||
}
|
||||
}
|
||||
|
||||
static int lua_geti(lua_State* L, int index, lua_Integer i) {
|
||||
index = lua_absindex(L, index);
|
||||
lua_pushinteger(L, i);
|
||||
lua_gettable(L, index);
|
||||
return lua_type(L, -1);
|
||||
}
|
||||
|
||||
#endif /* LUA_VERSION_NUM <= 502 */
|
||||
|
||||
#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM <= 503
|
||||
static int luaL_typeerror(lua_State* L, int arg, const char* tname) {
|
||||
const char* msg;
|
||||
const char* typearg; /* name for the type of the actual argument */
|
||||
if (luaL_getmetafield(L, arg, "__name") == LUA_TSTRING)
|
||||
typearg = lua_tostring(L, -1); /* use the given type name */
|
||||
else if (lua_type(L, arg) == LUA_TLIGHTUSERDATA)
|
||||
typearg = "light userdata"; /* special name for messages */
|
||||
else
|
||||
typearg = luaL_typename(L, arg); /* standard name */
|
||||
msg = lua_pushfstring(L, "%s expected, got %s", tname, typearg);
|
||||
return luaL_argerror(L, arg, msg);
|
||||
}
|
||||
|
||||
#endif /* LUA_VERSION_NUM <= 503 */
|
||||
|
||||
#if !defined(luaL_newlibtable)
|
||||
#define luaL_newlibtable(L, l) lua_createtable(L, 0, sizeof(l) / sizeof((l)[0]) - 1)
|
||||
#endif
|
||||
|
||||
#if !defined(luaL_checkversion)
|
||||
#define luaL_checkversion(L) ((void)0)
|
||||
#endif
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif // __cplusplus
|
||||
|
||||
#endif // LJKIWI_LUACOMPAT_H_
|
||||
301
luakiwi/luakiwi-int.h
Normal file
301
luakiwi/luakiwi-int.h
Normal file
@@ -0,0 +1,301 @@
|
||||
#ifndef LUAKIWI_INT_H_
|
||||
#define LUAKIWI_INT_H_
|
||||
|
||||
#include <kiwi/kiwi.h>
|
||||
|
||||
#include <cstring>
|
||||
#include <new>
|
||||
|
||||
#include "luacompat.h"
|
||||
|
||||
#if defined(__GNUC__) && !defined(LJKIWI_NO_BUILTIN)
|
||||
#define lk_likely(x) (__builtin_expect(((x) != 0), 1))
|
||||
#define lk_unlikely(x) (__builtin_expect(((x) != 0), 0))
|
||||
#else
|
||||
#define lk_likely(x) (x)
|
||||
#define lk_unlikely(x) (x)
|
||||
#endif
|
||||
|
||||
namespace {
|
||||
|
||||
using namespace kiwi;
|
||||
|
||||
// Lua 5.1 compatibility for missing lua_arith.
|
||||
inline void compat_arith_unm(lua_State* L) {
|
||||
#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM == 501
|
||||
int isnum;
|
||||
lua_Number n = lua_tonumberx(L, -1, &isnum);
|
||||
if (isnum) {
|
||||
lua_pop(L, 1);
|
||||
lua_pushnumber(L, -n);
|
||||
} else {
|
||||
if (!luaL_callmeta(L, -1, "__unm"))
|
||||
luaL_error(L, "attempt to perform arithmetic on a %s value", luaL_typename(L, -1));
|
||||
lua_replace(L, -2);
|
||||
}
|
||||
#else
|
||||
lua_arith(L, LUA_OPUNM);
|
||||
#endif
|
||||
}
|
||||
|
||||
// This version supports placeholders.
|
||||
inline void setfuncs(lua_State* L, const luaL_Reg* l, int nup) {
|
||||
luaL_checkstack(L, nup, "too many upvalues");
|
||||
for (; l->name != NULL; l++) { /* fill the table with given functions */
|
||||
if (l->func == NULL) /* place holder? */
|
||||
lua_pushboolean(L, 0);
|
||||
else {
|
||||
for (int i = 0; i < nup; i++) /* copy upvalues to the top */
|
||||
lua_pushvalue(L, -nup);
|
||||
lua_pushcclosure(L, l->func, nup); /* closure with those upvalues */
|
||||
}
|
||||
lua_setfield(L, -(nup + 2), l->name);
|
||||
}
|
||||
lua_pop(L, nup); /* remove upvalues */
|
||||
}
|
||||
|
||||
template<typename T, std::size_t N>
|
||||
constexpr int array_count(T (&)[N]) {
|
||||
return static_cast<int>(N);
|
||||
}
|
||||
|
||||
inline void newlib(lua_State* L, const luaL_Reg* l) {
|
||||
lua_newtable(L);
|
||||
setfuncs(L, l, 0);
|
||||
}
|
||||
|
||||
enum KiwiErrKind {
|
||||
KiwiErrNone,
|
||||
KiwiErrUnsatisfiableConstraint = 1,
|
||||
KiwiErrUnknownConstraint,
|
||||
KiwiErrDuplicateConstraint,
|
||||
KiwiErrUnknownEditVariable,
|
||||
KiwiErrDuplicateEditVariable,
|
||||
KiwiErrBadRequiredStrength,
|
||||
KiwiErrInternalSolverError,
|
||||
KiwiErrAlloc,
|
||||
KiwiErrNullObject,
|
||||
KiwiErrUnknown,
|
||||
};
|
||||
|
||||
struct KiwiTerm {
|
||||
VariableData* var;
|
||||
double coefficient;
|
||||
};
|
||||
|
||||
struct KiwiExpression {
|
||||
double constant;
|
||||
int term_count;
|
||||
ConstraintData* owner;
|
||||
|
||||
#if !defined(_MSC_VER) || _MSC_VER >= 1900
|
||||
KiwiTerm terms[];
|
||||
|
||||
static constexpr std::size_t sz(int count) {
|
||||
return sizeof(KiwiExpression) + sizeof(KiwiTerm) * (count > 0 ? count : 0);
|
||||
}
|
||||
#else
|
||||
KiwiTerm terms[1];
|
||||
|
||||
static constexpr std::size_t sz(int count) {
|
||||
return sizeof(KiwiExpression) + sizeof(KiwiTerm) * (count > 1 ? count - 1 : 0);
|
||||
}
|
||||
#endif
|
||||
|
||||
KiwiExpression() = delete;
|
||||
KiwiExpression(const KiwiExpression&) = delete;
|
||||
KiwiExpression& operator=(const KiwiExpression&) = delete;
|
||||
~KiwiExpression() = delete;
|
||||
};
|
||||
|
||||
// This mechanism was initially designed for LuaJIT FFI.
|
||||
struct KiwiErr {
|
||||
enum KiwiErrKind kind;
|
||||
const char* message;
|
||||
bool must_delete;
|
||||
};
|
||||
|
||||
struct KiwiSolver {
|
||||
unsigned error_mask;
|
||||
Solver solver;
|
||||
};
|
||||
|
||||
inline const KiwiErr* new_error(const KiwiErr* base, const std::exception& ex) {
|
||||
if (!std::strcmp(ex.what(), base->message))
|
||||
return base;
|
||||
|
||||
const auto msg_n = std::strlen(ex.what()) + 1;
|
||||
|
||||
auto* mem = static_cast<char*>(::operator new(sizeof(KiwiErr) + msg_n, std::nothrow));
|
||||
if (!mem) {
|
||||
return base;
|
||||
}
|
||||
auto* msg = mem + sizeof(KiwiErr);
|
||||
std::memcpy(msg, ex.what(), msg_n);
|
||||
return new (mem) KiwiErr {base->kind, msg, true};
|
||||
}
|
||||
|
||||
template<typename F>
|
||||
inline const KiwiErr* wrap_err(F&& f) {
|
||||
static const constexpr KiwiErr kKiwiErrUnhandledCxxException {
|
||||
KiwiErrUnknown,
|
||||
"An unhandled C++ exception occurred."};
|
||||
|
||||
try {
|
||||
f();
|
||||
} catch (const UnsatisfiableConstraint&) {
|
||||
static const constexpr KiwiErr err {
|
||||
KiwiErrUnsatisfiableConstraint,
|
||||
"The constraint cannot be satisfied."};
|
||||
return &err;
|
||||
} catch (const UnknownConstraint&) {
|
||||
static const constexpr KiwiErr err {
|
||||
KiwiErrUnknownConstraint,
|
||||
"The constraint has not been added to the solver."};
|
||||
return &err;
|
||||
|
||||
} catch (const DuplicateConstraint&) {
|
||||
static const constexpr KiwiErr err {
|
||||
KiwiErrDuplicateConstraint,
|
||||
"The constraint has already been added to the solver."};
|
||||
return &err;
|
||||
|
||||
} catch (const UnknownEditVariable&) {
|
||||
static const constexpr KiwiErr err {
|
||||
KiwiErrUnknownEditVariable,
|
||||
"The edit variable has not been added to the solver."};
|
||||
return &err;
|
||||
|
||||
} catch (const DuplicateEditVariable&) {
|
||||
static const constexpr KiwiErr err {
|
||||
KiwiErrDuplicateEditVariable,
|
||||
"The edit variable has already been added to the solver."};
|
||||
return &err;
|
||||
|
||||
} catch (const BadRequiredStrength&) {
|
||||
static const constexpr KiwiErr err {
|
||||
KiwiErrBadRequiredStrength,
|
||||
"A required strength cannot be used in this context."};
|
||||
return &err;
|
||||
|
||||
} catch (const InternalSolverError& ex) {
|
||||
static const constexpr KiwiErr base {
|
||||
KiwiErrInternalSolverError,
|
||||
"An internal solver error occurred."};
|
||||
return new_error(&base, ex);
|
||||
} catch (std::bad_alloc&) {
|
||||
static const constexpr KiwiErr err {KiwiErrAlloc, "A memory allocation failed."};
|
||||
return &err;
|
||||
} catch (const std::exception& ex) {
|
||||
return new_error(&kKiwiErrUnhandledCxxException, ex);
|
||||
} catch (...) {
|
||||
return &kKiwiErrUnhandledCxxException;
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
template<typename P, typename R, typename F>
|
||||
inline const KiwiErr* wrap_err(P&& s, F&& f) {
|
||||
return wrap_err([&]() { f(s); });
|
||||
}
|
||||
|
||||
template<typename P, typename R, typename F>
|
||||
inline const KiwiErr* wrap_err(P&& s, R&& ref, F&& f) {
|
||||
return wrap_err([&]() { f(s, ref); });
|
||||
}
|
||||
|
||||
template<typename T, typename... Args>
|
||||
inline T* make_unmanaged(Args... args) {
|
||||
auto* o = new T(std::forward<Args>(args)...);
|
||||
o->m_refcount = 1;
|
||||
return o;
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
inline void release_unmanaged(T* p) {
|
||||
if (lk_likely(p)) {
|
||||
if (--p->m_refcount == 0)
|
||||
delete p;
|
||||
}
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
inline T* retain_unmanaged(T* p) {
|
||||
if (lk_likely(p))
|
||||
p->m_refcount++;
|
||||
return p;
|
||||
}
|
||||
|
||||
inline ConstraintData* kiwi_constraint_new(
|
||||
const KiwiExpression* lhs,
|
||||
const KiwiExpression* rhs,
|
||||
RelationalOperator op,
|
||||
double strength
|
||||
) {
|
||||
if (strength < 0.0) {
|
||||
strength = kiwi::strength::required;
|
||||
}
|
||||
|
||||
std::vector<Term> terms;
|
||||
terms.reserve(static_cast<std::size_t>(
|
||||
(lhs && lhs->term_count > 0 ? lhs->term_count : 0)
|
||||
+ (rhs && rhs->term_count > 0 ? rhs->term_count : 0)
|
||||
));
|
||||
|
||||
if (lhs) {
|
||||
for (int i = 0; i < lhs->term_count; ++i) {
|
||||
const auto& t = lhs->terms[i];
|
||||
terms.emplace_back(Variable(t.var), t.coefficient);
|
||||
}
|
||||
}
|
||||
if (rhs) {
|
||||
for (int i = 0; i < rhs->term_count; ++i) {
|
||||
const auto& t = rhs->terms[i];
|
||||
terms.emplace_back(Variable(t.var), -t.coefficient);
|
||||
}
|
||||
}
|
||||
|
||||
return make_unmanaged<ConstraintData>(
|
||||
Expression(std::move(terms), (lhs ? lhs->constant : 0.0) - (rhs ? rhs->constant : 0.0)),
|
||||
static_cast<RelationalOperator>(op),
|
||||
strength
|
||||
);
|
||||
}
|
||||
|
||||
inline const KiwiErr* kiwi_solver_add_constraint(Solver& s, ConstraintData* constraint) {
|
||||
return wrap_err(s, constraint, [](auto&& solver, auto&& c) {
|
||||
solver.addConstraint(Constraint(c));
|
||||
});
|
||||
}
|
||||
|
||||
inline const KiwiErr* kiwi_solver_remove_constraint(Solver& s, ConstraintData* constraint) {
|
||||
return wrap_err(s, constraint, [](auto&& solver, auto&& c) {
|
||||
solver.removeConstraint(Constraint(c));
|
||||
});
|
||||
}
|
||||
|
||||
inline const KiwiErr* kiwi_solver_add_edit_var(Solver& s, VariableData* var, double strength) {
|
||||
return wrap_err(s, var, [strength](auto&& solver, auto&& v) {
|
||||
solver.addEditVariable(Variable(v), strength);
|
||||
});
|
||||
}
|
||||
|
||||
inline const KiwiErr* kiwi_solver_remove_edit_var(Solver& s, VariableData* var) {
|
||||
return wrap_err(s, var, [](auto&& solver, auto&& v) {
|
||||
solver.removeEditVariable(Variable(v));
|
||||
});
|
||||
}
|
||||
|
||||
inline const KiwiErr* kiwi_solver_suggest_value(Solver& s, VariableData* var, double value) {
|
||||
return wrap_err(s, var, [value](auto&& solver, auto&& v) {
|
||||
solver.suggestValue(Variable(v), value);
|
||||
});
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
// Local Variables:
|
||||
// mode: c++
|
||||
// End:
|
||||
|
||||
#endif // LUAKIWI_INT_H_
|
||||
1688
luakiwi/luakiwi.cpp
Normal file
1688
luakiwi/luakiwi.cpp
Normal file
File diff suppressed because it is too large
Load Diff
125
spec/constraint_spec.lua
Normal file
125
spec/constraint_spec.lua
Normal file
@@ -0,0 +1,125 @@
|
||||
expose("module", function()
|
||||
require("kiwi")
|
||||
end)
|
||||
|
||||
describe("Constraint", function()
|
||||
local kiwi = require("kiwi")
|
||||
local LUA_VERSION = tonumber(_VERSION:match("%d+%.%d+"))
|
||||
|
||||
describe("construction", function()
|
||||
local v, lhs
|
||||
before_each(function()
|
||||
v = kiwi.Var("foo")
|
||||
lhs = v + 1
|
||||
end)
|
||||
|
||||
it("has correct type", function()
|
||||
assert.True(kiwi.is_constraint(kiwi.Constraint()))
|
||||
assert.False(kiwi.is_constraint(v))
|
||||
end)
|
||||
|
||||
it("default op and strength", function()
|
||||
local c = kiwi.Constraint(lhs)
|
||||
assert.equal("EQ", c:op())
|
||||
assert.equal(kiwi.strength.REQUIRED, c:strength())
|
||||
end)
|
||||
|
||||
it("configure op", function()
|
||||
local c = kiwi.Constraint(lhs, nil, "LE")
|
||||
assert.equal("LE", c:op())
|
||||
end)
|
||||
it("configure strength", function()
|
||||
local c = kiwi.Constraint(lhs, nil, "GE", kiwi.strength.STRONG)
|
||||
assert.equal(kiwi.strength.STRONG, c:strength())
|
||||
end)
|
||||
|
||||
-- TODO: standardize formatting
|
||||
it("formats well", function()
|
||||
local c = kiwi.Constraint(lhs)
|
||||
if LUA_VERSION <= 5.2 then
|
||||
assert.equal("1 foo + 1 == 0 | required", tostring(c))
|
||||
else
|
||||
assert.equal("1.0 foo + 1.0 == 0 | required", tostring(c))
|
||||
end
|
||||
|
||||
c = kiwi.Constraint(lhs * 2, nil, "GE", kiwi.strength.STRONG)
|
||||
if LUA_VERSION <= 5.2 then
|
||||
assert.equal("2 foo + 2 >= 0 | strong", tostring(c))
|
||||
else
|
||||
assert.equal("2.0 foo + 2.0 >= 0 | strong", tostring(c))
|
||||
end
|
||||
|
||||
c = kiwi.Constraint(lhs / 2, nil, "LE", kiwi.strength.MEDIUM)
|
||||
assert.equal("0.5 foo + 0.5 <= 0 | medium", tostring(c))
|
||||
|
||||
c = kiwi.Constraint(lhs, kiwi.Expression(3), "GE", kiwi.strength.WEAK)
|
||||
if LUA_VERSION <= 5.2 then
|
||||
assert.equal("1 foo + -2 >= 0 | weak", tostring(c))
|
||||
else
|
||||
assert.equal("1.0 foo + -2.0 >= 0 | weak", tostring(c))
|
||||
end
|
||||
end)
|
||||
|
||||
it("rejects invalid args", function()
|
||||
assert.error(function()
|
||||
local _ = kiwi.Constraint(1)
|
||||
end)
|
||||
assert.error(function()
|
||||
local _ = kiwi.Constraint(lhs, 1)
|
||||
end)
|
||||
assert.error(function()
|
||||
local _ = kiwi.Constraint("")
|
||||
end)
|
||||
assert.error(function()
|
||||
local _ = kiwi.Constraint(lhs, "")
|
||||
end)
|
||||
assert.error(function()
|
||||
local _ = kiwi.Constraint(lhs, nil, "foo")
|
||||
end)
|
||||
assert.error(function()
|
||||
local _ = kiwi.Constraint(lhs, nil, "LE", "foo")
|
||||
end)
|
||||
end)
|
||||
it("combines lhs and rhs", function()
|
||||
local v2 = kiwi.Var("bar")
|
||||
local rhs = kiwi.Expression(3, 5 * v2, 3 * v)
|
||||
local c = kiwi.Constraint(lhs, rhs)
|
||||
|
||||
local e = c:expression()
|
||||
local t = e:terms()
|
||||
assert.equal(2, #t)
|
||||
if t[1].var ~= v then
|
||||
t[1], t[2] = t[2], t[1]
|
||||
end
|
||||
assert.equal(v, t[1].var)
|
||||
assert.equal(-2.0, t[1].coefficient)
|
||||
assert.equal(v2, t[2].var)
|
||||
assert.equal(-5.0, t[2].coefficient)
|
||||
assert.equal(-2.0, e.constant)
|
||||
end)
|
||||
end)
|
||||
|
||||
describe("method", function()
|
||||
local c, v
|
||||
|
||||
before_each(function()
|
||||
v = kiwi.Var("foo")
|
||||
c = kiwi.Constraint(2 * v + 1)
|
||||
end)
|
||||
|
||||
it("violated", function()
|
||||
assert.True(c:violated())
|
||||
v:set(-0.5)
|
||||
assert.False(c:violated())
|
||||
end)
|
||||
|
||||
it("add/remove constraint", function()
|
||||
local s = kiwi.Solver()
|
||||
c:add_to(s)
|
||||
assert.True(s:has_constraint(c))
|
||||
|
||||
c:remove_from(s)
|
||||
assert.False(s:has_constraint(c))
|
||||
end)
|
||||
end)
|
||||
end)
|
||||
335
spec/solver_spec.lua
Normal file
335
spec/solver_spec.lua
Normal file
@@ -0,0 +1,335 @@
|
||||
expose("module", function()
|
||||
require("kiwi")
|
||||
end)
|
||||
|
||||
describe("solver", function()
|
||||
local kiwi = require("kiwi")
|
||||
---@type kiwi.Solver
|
||||
local solver
|
||||
|
||||
before_each(function()
|
||||
solver = kiwi.Solver()
|
||||
end)
|
||||
|
||||
it("should create a solver", function()
|
||||
assert.True(kiwi.is_solver(solver))
|
||||
assert.False(kiwi.is_solver(kiwi.Term(kiwi.Var("v1"))))
|
||||
end)
|
||||
|
||||
describe("edit variables", function()
|
||||
local v1, v2, v3
|
||||
before_each(function()
|
||||
v1 = kiwi.Var("foo")
|
||||
v2 = kiwi.Var("bar")
|
||||
v3 = kiwi.Var("baz")
|
||||
end)
|
||||
|
||||
describe("add_edit_var", function()
|
||||
it("should add a variable", function()
|
||||
solver:add_edit_var(v1, kiwi.strength.STRONG)
|
||||
assert.True(solver:has_edit_var(v1))
|
||||
end)
|
||||
|
||||
it("should return the argument", function()
|
||||
assert.equal(v1, solver:add_edit_var(v1, kiwi.strength.STRONG))
|
||||
end)
|
||||
|
||||
it("should error on incorrect type", function()
|
||||
assert.error(function()
|
||||
solver:add_edit_var("", kiwi.strength.STRONG) ---@diagnostic disable-line: param-type-mismatch
|
||||
end)
|
||||
assert.error(function()
|
||||
solver:add_edit_var(v1, "") ---@diagnostic disable-line: param-type-mismatch
|
||||
end)
|
||||
end)
|
||||
|
||||
it("should require a strength argument", function()
|
||||
assert.error(function()
|
||||
solver:add_edit_var(v1) ---@diagnostic disable-line: missing-parameter
|
||||
end)
|
||||
end)
|
||||
|
||||
it("should error on duplicate variable", function()
|
||||
solver:add_edit_var(v1, kiwi.strength.STRONG)
|
||||
local _, err = pcall(function()
|
||||
return solver:add_edit_var(v1, kiwi.strength.STRONG)
|
||||
end)
|
||||
assert.True(kiwi.is_error(err))
|
||||
assert.True(kiwi.is_solver(err.solver))
|
||||
assert.equal(v1, err.item)
|
||||
assert.equal("KiwiErrDuplicateEditVariable", err.kind)
|
||||
assert.equal("The edit variable has already been added to the solver.", err.message)
|
||||
end)
|
||||
|
||||
it("should error on invalid strength", function()
|
||||
local _, err = pcall(function()
|
||||
return solver:add_edit_var(v1, kiwi.strength.REQUIRED)
|
||||
end)
|
||||
assert.True(kiwi.is_error(err))
|
||||
assert.True(kiwi.is_solver(err.solver))
|
||||
assert.equal(v1, err.item)
|
||||
assert.equal("KiwiErrBadRequiredStrength", err.kind)
|
||||
assert.equal("A required strength cannot be used in this context.", err.message)
|
||||
end)
|
||||
|
||||
it("should return errors for duplicate variables", function()
|
||||
solver:set_error_mask({ "KiwiErrDuplicateEditVariable", "KiwiErrBadRequiredStrength" })
|
||||
local ret, err = solver:add_edit_var(v1, kiwi.strength.STRONG)
|
||||
assert.Nil(err)
|
||||
|
||||
ret, err = solver:add_edit_var(v1, kiwi.strength.STRONG)
|
||||
|
||||
assert.equal(v1, ret)
|
||||
assert.True(kiwi.is_error(err))
|
||||
---@diagnostic disable: need-check-nil
|
||||
assert.True(kiwi.is_solver(err.solver))
|
||||
assert.equal(v1, err.item)
|
||||
assert.equal("KiwiErrDuplicateEditVariable", err.kind)
|
||||
assert.equal("The edit variable has already been added to the solver.", err.message)
|
||||
---@diagnostic enable: need-check-nil
|
||||
end)
|
||||
|
||||
it("should return errors for invalid strength", function()
|
||||
solver:set_error_mask({ "KiwiErrDuplicateEditVariable", "KiwiErrBadRequiredStrength" })
|
||||
|
||||
---@diagnostic disable: need-check-nil
|
||||
local ret, err = solver:add_edit_var(v2, kiwi.strength.REQUIRED)
|
||||
assert.equal(v2, ret)
|
||||
assert.True(kiwi.is_error(err))
|
||||
assert.True(kiwi.is_solver(err.solver))
|
||||
assert.equal(v2, err.item)
|
||||
assert.equal("KiwiErrBadRequiredStrength", err.kind)
|
||||
assert.equal("A required strength cannot be used in this context.", err.message)
|
||||
---@diagnostic enable: need-check-nil
|
||||
end)
|
||||
|
||||
it("tolerates a nil self", function()
|
||||
assert.error(function()
|
||||
kiwi.Solver.add_edit_var(nil, v1, kiwi.strength.STRONG) ---@diagnostic disable-line: param-type-mismatch
|
||||
end)
|
||||
end)
|
||||
|
||||
it("tolerates a nil var", function()
|
||||
assert.error(function()
|
||||
solver:add_edit_var(nil, kiwi.strength.STRONG) ---@diagnostic disable-line: param-type-mismatch
|
||||
end)
|
||||
end)
|
||||
end)
|
||||
|
||||
describe("add_edit_vars", function()
|
||||
it("should add variables", function()
|
||||
solver:add_edit_vars({ v1, v2 }, kiwi.strength.STRONG)
|
||||
assert.True(solver:has_edit_var(v1))
|
||||
assert.True(solver:has_edit_var(v2))
|
||||
assert.False(solver:has_edit_var(v3))
|
||||
end)
|
||||
|
||||
it("should return the argument", function()
|
||||
local arg = { v1, v2, v3 }
|
||||
assert.equal(arg, solver:add_edit_vars(arg, kiwi.strength.STRONG))
|
||||
end)
|
||||
|
||||
it("should error on incorrect type", function()
|
||||
assert.error(function()
|
||||
solver:add_edit_vars(v1, kiwi.strength.STRONG) ---@diagnostic disable-line: param-type-mismatch
|
||||
end)
|
||||
assert.error(function()
|
||||
solver:add_edit_vars("", kiwi.strength.STRONG) ---@diagnostic disable-line: param-type-mismatch
|
||||
end)
|
||||
assert.error(function()
|
||||
solver:add_edit_vars(v1, "") ---@diagnostic disable-line: param-type-mismatch
|
||||
end)
|
||||
end)
|
||||
|
||||
it("should require a strength argument", function()
|
||||
assert.error(function()
|
||||
solver:add_edit_vars({ v1, v2 }) ---@diagnostic disable-line: missing-parameter
|
||||
end)
|
||||
end)
|
||||
|
||||
it("should error on duplicate variable", function()
|
||||
local _, err = pcall(function()
|
||||
return solver:add_edit_vars({ v1, v2, v3, v2, v3 }, kiwi.strength.STRONG)
|
||||
end)
|
||||
assert.True(kiwi.is_error(err))
|
||||
assert.True(kiwi.is_solver(err.solver))
|
||||
assert.equal(v2, err.item)
|
||||
assert.equal("KiwiErrDuplicateEditVariable", err.kind)
|
||||
assert.equal("The edit variable has already been added to the solver.", err.message)
|
||||
end)
|
||||
|
||||
it("should error on invalid strength", function()
|
||||
local _, err = pcall(function()
|
||||
return solver:add_edit_vars({ v1, v2 }, kiwi.strength.REQUIRED)
|
||||
end)
|
||||
assert.True(kiwi.is_error(err))
|
||||
assert.True(kiwi.is_solver(err.solver))
|
||||
assert.equal(v1, err.item)
|
||||
assert.equal("KiwiErrBadRequiredStrength", err.kind)
|
||||
assert.equal("A required strength cannot be used in this context.", err.message)
|
||||
end)
|
||||
|
||||
it("should return errors for duplicate variables", function()
|
||||
solver:set_error_mask({ "KiwiErrDuplicateEditVariable", "KiwiErrBadRequiredStrength" })
|
||||
local ret, err = solver:add_edit_vars({ v1, v2, v3 }, kiwi.strength.STRONG)
|
||||
assert.Nil(err)
|
||||
|
||||
local arg = { v1, v2, v3 }
|
||||
ret, err = solver:add_edit_vars(arg, kiwi.strength.STRONG)
|
||||
assert.equal(arg, ret)
|
||||
assert.True(kiwi.is_error(err))
|
||||
---@diagnostic disable: need-check-nil
|
||||
assert.True(kiwi.is_solver(err.solver))
|
||||
assert.equal(v1, err.item)
|
||||
assert.equal("KiwiErrDuplicateEditVariable", err.kind)
|
||||
assert.equal("The edit variable has already been added to the solver.", err.message)
|
||||
---@diagnostic enable: need-check-nil
|
||||
end)
|
||||
|
||||
it("should return errors for invalid strength", function()
|
||||
solver:set_error_mask({ "KiwiErrDuplicateEditVariable", "KiwiErrBadRequiredStrength" })
|
||||
arg = { v2, v3 }
|
||||
local ret, err = solver:add_edit_vars(arg, kiwi.strength.REQUIRED)
|
||||
assert.equal(arg, ret)
|
||||
assert.True(kiwi.is_error(err))
|
||||
---@diagnostic disable: need-check-nil
|
||||
assert.True(kiwi.is_solver(err.solver))
|
||||
assert.equal(v2, err.item)
|
||||
assert.equal("KiwiErrBadRequiredStrength", err.kind)
|
||||
assert.equal("A required strength cannot be used in this context.", err.message)
|
||||
---@diagnostic enable: need-check-nil
|
||||
end)
|
||||
|
||||
it("tolerates a nil self", function()
|
||||
assert.has_error(function()
|
||||
kiwi.Solver.add_edit_vars(nil, { v1, v2 }, kiwi.strength.STRONG) ---@diagnostic disable-line: param-type-mismatch
|
||||
end)
|
||||
end)
|
||||
end)
|
||||
|
||||
describe("remove_edit_var", function()
|
||||
it("should remove a variable", function()
|
||||
solver:add_edit_vars({ v1, v2, v3 }, kiwi.strength.STRONG)
|
||||
assert.True(solver:has_edit_var(v2))
|
||||
solver:remove_edit_var(v2)
|
||||
assert.True(solver:has_edit_var(v1))
|
||||
assert.False(solver:has_edit_var(v2))
|
||||
assert.True(solver:has_edit_var(v3))
|
||||
end)
|
||||
|
||||
it("should return the argument", function()
|
||||
solver:add_edit_var(v1, kiwi.strength.STRONG)
|
||||
assert.equal(v1, solver:remove_edit_var(v1))
|
||||
end)
|
||||
|
||||
it("should error on incorrect type", function()
|
||||
assert.error(function()
|
||||
solver:remove_edit_var("") ---@diagnostic disable-line: param-type-mismatch
|
||||
end)
|
||||
assert.error(function()
|
||||
solver:remove_edit_var({ v1 }) ---@diagnostic disable-line: param-type-mismatch
|
||||
end)
|
||||
end)
|
||||
|
||||
it("should error on unknown variable", function()
|
||||
solver:add_edit_var(v1, kiwi.strength.STRONG)
|
||||
local _, err = pcall(function()
|
||||
return solver:remove_edit_var(v2)
|
||||
end)
|
||||
assert.True(kiwi.is_error(err))
|
||||
assert.True(kiwi.is_solver(err.solver))
|
||||
assert.equal(v2, err.item)
|
||||
assert.equal("KiwiErrUnknownEditVariable", err.kind)
|
||||
assert.equal("The edit variable has not been added to the solver.", err.message)
|
||||
end)
|
||||
|
||||
it("should return errors if requested", function()
|
||||
solver:set_error_mask({ "KiwiErrDuplicateEditVariable", "KiwiErrUnknownEditVariable" })
|
||||
|
||||
local ret, err = solver:remove_edit_var(v1)
|
||||
|
||||
assert.equal(v1, ret)
|
||||
assert.True(kiwi.is_error(err))
|
||||
---@diagnostic disable: need-check-nil
|
||||
assert.True(kiwi.is_solver(err.solver))
|
||||
assert.equal(v1, err.item)
|
||||
assert.equal("KiwiErrUnknownEditVariable", err.kind)
|
||||
assert.equal("The edit variable has not been added to the solver.", err.message)
|
||||
---@diagnostic enable: need-check-nil
|
||||
end)
|
||||
|
||||
it("tolerates a nil self", function()
|
||||
assert.has_error(function()
|
||||
kiwi.Solver.remove_edit_var(nil, v1) ---@diagnostic disable-line: param-type-mismatch
|
||||
end)
|
||||
end)
|
||||
|
||||
it("tolerates a nil var", function()
|
||||
assert.has_error(function()
|
||||
solver:remove_edit_var(nil) ---@diagnostic disable-line: param-type-mismatch
|
||||
end)
|
||||
end)
|
||||
end)
|
||||
|
||||
describe("remove_edit_vars", function()
|
||||
it("should remove variables", function()
|
||||
solver:add_edit_vars({ v1, v2, v3 }, kiwi.strength.STRONG)
|
||||
assert.True(solver:has_edit_var(v2))
|
||||
assert.True(solver:has_edit_var(v3))
|
||||
|
||||
solver:remove_edit_vars({ v2, v3 })
|
||||
assert.False(solver:has_edit_var(v2))
|
||||
assert.False(solver:has_edit_var(v3))
|
||||
end)
|
||||
|
||||
it("should return the argument", function()
|
||||
local arg = { v1, v2, v3 }
|
||||
solver:add_edit_vars(arg, kiwi.strength.STRONG)
|
||||
assert.equal(arg, solver:remove_edit_vars(arg))
|
||||
end)
|
||||
|
||||
it("should error on incorrect type", function()
|
||||
assert.error(function()
|
||||
solver:remove_edit_vars(v1) ---@diagnostic disable-line: param-type-mismatch
|
||||
end)
|
||||
assert.error(function()
|
||||
solver:remove_edit_vars("") ---@diagnostic disable-line: param-type-mismatch
|
||||
end)
|
||||
end)
|
||||
|
||||
it("should error on unknown variables", function()
|
||||
local _, err = pcall(function()
|
||||
return solver:remove_edit_vars({ v2, v1 })
|
||||
end)
|
||||
assert.True(kiwi.is_error(err))
|
||||
assert.True(kiwi.is_solver(err.solver))
|
||||
assert.equal(v2, err.item)
|
||||
assert.equal("KiwiErrUnknownEditVariable", err.kind)
|
||||
assert.equal("The edit variable has not been added to the solver.", err.message)
|
||||
end)
|
||||
|
||||
it("should return errors for unknown variables", function()
|
||||
solver:set_error_mask({ "KiwiErrDuplicateEditVariable", "KiwiErrUnknownEditVariable" })
|
||||
local ret, err = solver:add_edit_vars({ v1, v2 }, kiwi.strength.STRONG)
|
||||
assert.Nil(err)
|
||||
|
||||
local arg = { v1, v2, v3 }
|
||||
ret, err = solver:remove_edit_vars(arg)
|
||||
assert.equal(arg, ret)
|
||||
assert.True(kiwi.is_error(err))
|
||||
---@diagnostic disable: need-check-nil
|
||||
assert.True(kiwi.is_solver(err.solver))
|
||||
assert.equal(v3, err.item)
|
||||
assert.equal("KiwiErrUnknownEditVariable", err.kind)
|
||||
assert.equal("The edit variable has not been added to the solver.", err.message)
|
||||
---@diagnostic enable: need-check-nil
|
||||
end)
|
||||
|
||||
it("tolerates a nil self", function()
|
||||
assert.has_error(function()
|
||||
kiwi.Solver.remove_edit_vars(nil, { v1, v2 }) ---@diagnostic disable-line: param-type-mismatch
|
||||
end)
|
||||
end)
|
||||
end)
|
||||
end)
|
||||
end)
|
||||
186
spec/var_spec.lua
Normal file
186
spec/var_spec.lua
Normal file
@@ -0,0 +1,186 @@
|
||||
expose("module", function()
|
||||
require("kiwi")
|
||||
end)
|
||||
|
||||
describe("Var", function()
|
||||
local kiwi = require("kiwi")
|
||||
|
||||
it("construction", function()
|
||||
assert.True(kiwi.is_var(kiwi.Var()))
|
||||
assert.False(kiwi.is_var(kiwi.Constraint()))
|
||||
|
||||
assert.error(function()
|
||||
kiwi.Var({})
|
||||
end)
|
||||
end)
|
||||
|
||||
describe("method", function()
|
||||
local v
|
||||
|
||||
before_each(function()
|
||||
v = kiwi.Var("goo")
|
||||
end)
|
||||
|
||||
it("has settable name", function()
|
||||
assert.equal("goo", v:name())
|
||||
v:set_name("Δ")
|
||||
assert.equal("Δ", v:name())
|
||||
assert.error(function()
|
||||
v:set_name({})
|
||||
end)
|
||||
end)
|
||||
|
||||
it("has a initial value of 0.0", function()
|
||||
assert.equal(0.0, v:value())
|
||||
end)
|
||||
|
||||
it("has a settable value", function()
|
||||
v:set(47.0)
|
||||
assert.equal(47.0, v:value())
|
||||
end)
|
||||
|
||||
it("neg", function()
|
||||
local neg = -v --[[@as kiwi.Term]]
|
||||
assert.True(kiwi.is_term(neg))
|
||||
assert.equal(v, neg.var)
|
||||
assert.equal(-1.0, neg.coefficient)
|
||||
end)
|
||||
|
||||
describe("bin op", function()
|
||||
local v2
|
||||
before_each(function()
|
||||
v2 = kiwi.Var("foo")
|
||||
end)
|
||||
|
||||
it("mul", function()
|
||||
for _, prod in ipairs({ v * 2.0, 2 * v }) do
|
||||
assert.True(kiwi.is_term(prod))
|
||||
assert.equal(v, prod.var)
|
||||
assert.equal(2.0, prod.coefficient)
|
||||
end
|
||||
|
||||
assert.error(function()
|
||||
local _ = v * v2
|
||||
end)
|
||||
end)
|
||||
|
||||
it("div", function()
|
||||
local quot = v / 2.0
|
||||
assert.True(kiwi.is_term(quot))
|
||||
assert.equal(v, quot.var)
|
||||
assert.equal(0.5, quot.coefficient)
|
||||
|
||||
assert.error(function()
|
||||
local _ = v / v2
|
||||
end)
|
||||
end)
|
||||
|
||||
it("add", function()
|
||||
for _, sum in ipairs({ v + 2.0, 2 + v }) do
|
||||
assert.True(kiwi.is_expression(sum))
|
||||
assert.equal(2.0, sum.constant)
|
||||
|
||||
local terms = sum:terms()
|
||||
assert.equal(1, #terms)
|
||||
assert.equal(1.0, terms[1].coefficient)
|
||||
assert.equal(v, terms[1].var)
|
||||
end
|
||||
|
||||
local sum = v + v2
|
||||
assert.True(kiwi.is_expression(sum))
|
||||
assert.equal(0, sum.constant)
|
||||
local terms = sum:terms()
|
||||
assert.equal(2, #terms)
|
||||
assert.equal(v, terms[1].var)
|
||||
assert.equal(1.0, terms[1].coefficient)
|
||||
assert.equal(v2, terms[2].var)
|
||||
assert.equal(1.0, terms[2].coefficient)
|
||||
|
||||
assert.error(function()
|
||||
local _ = v + "foo"
|
||||
end)
|
||||
assert.error(function()
|
||||
local _ = v + {}
|
||||
end)
|
||||
end)
|
||||
|
||||
it("sub", function()
|
||||
local constants = { -2, 2 }
|
||||
for i, diff in ipairs({ v - 2.0, 2 - v }) do
|
||||
local constant = constants[i]
|
||||
assert.True(kiwi.is_expression(diff))
|
||||
assert.equal(constant, diff.constant)
|
||||
|
||||
local terms = diff:terms()
|
||||
assert.equal(1, #terms)
|
||||
assert.equal(v, terms[1].var)
|
||||
assert.equal(constant < 0 and 1 or -1, terms[1].coefficient)
|
||||
end
|
||||
|
||||
local diff = v - v2
|
||||
assert.True(kiwi.is_expression(diff))
|
||||
assert.equal(0, diff.constant)
|
||||
local terms = diff:terms()
|
||||
assert.equal(2, #terms)
|
||||
assert.equal(v, terms[1].var)
|
||||
assert.equal(1.0, terms[1].coefficient)
|
||||
assert.equal(v2, terms[2].var)
|
||||
assert.equal(-1.0, terms[2].coefficient)
|
||||
|
||||
assert.error(function()
|
||||
local _ = v - "foo"
|
||||
end)
|
||||
assert.error(function()
|
||||
local _ = v - {}
|
||||
end)
|
||||
end)
|
||||
|
||||
it("constraint var op expr", function()
|
||||
local ops = { "LE", "EQ", "GE" }
|
||||
for i, meth in ipairs({ "le", "eq", "ge" }) do
|
||||
local c = v[meth](v, v2 + 1)
|
||||
assert.True(kiwi.is_constraint(c))
|
||||
|
||||
local e = c:expression()
|
||||
local t = e:terms()
|
||||
assert.equal(2, #t)
|
||||
|
||||
-- order can be randomized due to use of map
|
||||
if t[1].var ~= v then
|
||||
t[1], t[2] = t[2], t[1]
|
||||
end
|
||||
assert.equal(v, t[1].var)
|
||||
assert.equal(1.0, t[1].coefficient)
|
||||
assert.equal(v2, t[2].var)
|
||||
assert.equal(-1.0, t[2].coefficient)
|
||||
|
||||
assert.equal(-1, e.constant)
|
||||
assert.equal(ops[i], c:op())
|
||||
assert.equal(kiwi.strength.REQUIRED, c:strength())
|
||||
end
|
||||
end)
|
||||
|
||||
it("constraint var op var", function()
|
||||
for i, meth in ipairs({ "le", "eq", "ge" }) do
|
||||
local c = v[meth](v, v2)
|
||||
assert.True(kiwi.is_constraint(c))
|
||||
|
||||
local e = c:expression()
|
||||
local t = e:terms()
|
||||
assert.equal(2, #t)
|
||||
|
||||
-- order can be randomized due to use of map
|
||||
if t[1].var ~= v then
|
||||
t[1], t[2] = t[2], t[1]
|
||||
end
|
||||
assert.equal(v, t[1].var)
|
||||
assert.equal(1.0, t[1].coefficient)
|
||||
assert.equal(v2, t[2].var)
|
||||
assert.equal(-1.0, t[2].coefficient)
|
||||
|
||||
assert.equal(0, e.constant)
|
||||
end
|
||||
end)
|
||||
end)
|
||||
end)
|
||||
end)
|
||||
Reference in New Issue
Block a user