How to rotate a bitvector in cvc4 using c++ API - c++

I try to rotate a bitvector in cvc4 using the C++ API, but the API is a little bit confusing when it comes to operator expressions.
Using the following code (extract):
#include <iostream>
#include <cvc4/cvc4.h>
using namespace std;
using namespace CVC4;
int main() {
ExprManager em;
SmtEngine smt(&em);
smt.setLogic("QF_BV");
Type bitvector32 = em.mkBitVectorType(32);
Integer i = Integer(1, 10);
BitVector bv = BitVector(32, i);
Expr expr = em->mkConst(bv);
BitVectorRotateLeft bv_rl = BitVectorRotateLeft(1);
Expr e_bv_rl = em->mkConst(bv_rl);
Expr e_op_rl = em->operatorOf(kind::BITVECTOR_ROTATE_LEFT_OP);
Expr e_op_e = em->mkExpr(e_op_rl, e_bv_rl);
Expr e = em->mkExpr(Kind::BITVECTOR_ROTATE_LEFT, e_op_e, expr);
return 0;
}
Executing this yields:
terminate called after throwing an instance of 'CVC4::IllegalArgumentException'
what(): Illegal argument detected
CVC4::Expr CVC4::ExprManager::mkExpr(CVC4::Expr, CVC4::Expr)
`opExpr' is a bad argument; expected (opExpr.getKind() == kind::BUILTIN || kind::metaKindOf(kind) == kind::metakind::PARAMETERIZED) to hold
This Expr constructor is for parameterized kinds only
Aborted
Does anybody know how to deal with the operator construct of cvc4?

See below for the correct construction of a rotate left expression. In general, whenever you have an expression operator that is itself an expression, you apply it by simply calling mkExpr and passing the operator expression as the first argument.
int main() {
ExprManager em;
SmtEngine smt(&em);
smt.setLogic("QF_BV");
Type bitvector32 = em.mkBitVectorType(32);
BitVector bv = BitVector(32, 1U);
Expr expr = em.mkConst(bv);
BitVectorRotateLeft bv_rl = BitVectorRotateLeft(1);
Expr e_bv_rl = em.mkConst(bv_rl);
Expr e = em.mkExpr(e_bv_rl, expr);
cout << e;
return 0;
}

Related

Can I implement operator overloading for D's SumType alias?

TLDR: Is there a way make D's SumType play nice with opCmp while maintaining its functionality?
Context
I'm writing a program for which D's native SumType works almost completely. However, I would like to be able to do the following:
alias Foo = SumType!(int, string);
Foo x = 3;
Foo y = 5;
writeln(max(x, y));
However, since no ordering is natively defined for SumType, I receive the following error:
C:\D\dmd2\windows\bin\..\..\src\phobos\std\algorithm\comparison.d(1644): Error: static assert: "Invalid arguments: Cannot compare types SumType!(int, string) and SumType!(int, string) for ordering."
mwe.d(11): instantiated from here: `max!(SumType!(int, string), SumType!(int, string))`
I was able to remedy this specific issue using the following method:
import std.stdio : writeln;
import std.exception : assertThrown;
import std.algorithm.comparison : max;
import core.exception : AssertError;
import std.sumtype;
struct Foo {
SumType!(int, string) value;
this(T)(T v) {
value = v;
}
ref Atom opAssign(T)(T rhs) {
value = rhs;
return this;
}
int opCmp(Foo other) {
return match!(
(a, b) => a < b ? -1 : a == b ? 0 : 1,
(_1, _2) => assert(0, "Cannot match")
)(value, other.value);
}
}
void main() {
Foo x = 3;
Foo y = 7;
Foo z = "asdf";
assert(x < y); // comparing ints works correctly
assertThrown!AssertError(x < z); // cannot compare int and string
assert(max(x, y) == y); // D's max works
}
The Problem
While I can now use x.value.match!(...) where I used to use x.match!(...), I would like to still be able to call .match! directly on x, and also use match!(...)(x, y) instead of match!(...)(x.value, y.value). I do not like the idea of inserting hundreds of .value throughout my code just to make certain functions like max work, and would prefer if there were a more elegant solution. I tried tinkering around with defining a custom opDispatch using mixins but I couldn't get that to play nicely with the existing SumType:
struct Foo {
SumType!(int, string) value;
this(T)(T v) {
value = v;
}
ref Atom opAssign(T)(T rhs) {
value = rhs;
return this;
}
int opCmp(Foo other) {
return match!(
(a, b) => a < b ? -1 : a == b ? 0 : 1,
(_1, _2) => assert(0, "Cannot match")
)(value, other.value);
}
auto opDispatch(string name, T...)(T vals) {
return mixin("value." ~ name)(vals);
}
}
void main() {
Foo y = 7;
y.match!(
(int intValue) => writeln("Received an integer"),
(string strValue) => writeln("Received a string")
);
}
And I am unable to decode the error which results:
mwe.d(38): Error: none of the overloads of template `std.sumtype.match!(function (int intValue) #safe
{
writeln("Received an integer");
return ;
}
, function (string strValue) #safe
{
writeln("Received a string");
return ;
}
).match` are callable using argument types `!()(Foo)`
C:\D\dmd2\windows\bin\..\..\src\phobos\std\sumtype.d(1659): Candidate is: `match(SumTypes...)(auto ref SumTypes args)`
with `SumTypes = (Foo)`
must satisfy the following constraint:
` allSatisfy!(isSumType, SumTypes)`
Beyond that I am out of ideas as to how to find a less clunky solution.
I suggest giving alias this a try. Similar to class inheritance, this lets you specialize a type and let other things fall back to the original member.
import std.stdio : writeln;
import std.exception : assertThrown;
import std.algorithm.comparison : max;
import core.exception : AssertError;
import std.sumtype;
struct Foo {
SumType!(int, string) value;
this(T)(T v) {
value = v;
}
int opCmp(Foo other) {
return match!(
(a, b) => a < b ? -1 : a == b ? 0 : 1,
(_1, _2) => assert(0, "Cannot match")
)(value, other.value);
}
alias value this;
}
void main() {
Foo x = 3;
Foo y = 7;
Foo z = "asdf";
assert(x < y); // comparing ints works correctly
assertThrown!AssertError(x < z); // cannot compare int and string
assert(max(x, y) == y); // D's max works
// this will now automatically fall back to y.value.match
y.match!(
(int intValue) => writeln("Received an integer"),
(string strValue) => writeln("Received a string")
);
}
See, you still must construct your special type, but then after that, it will look up there for members. It will find the opCmp, letting it extend the type. But then for everything else, since it isn't there, it will try checking obj.value instead, falling back to the original type.
This doesn't always work, and it means it will implicitly convert too, meaning you can pass a Foo to a void thing(SumType!(int, string)) with it passing foo.value to the function, which may or may not be desirable.
But I think it is the closest thing to what you want here.
(note btw why you got an error originally is that match isn't actually a member of SumType. it is an outside free function that takes all the match lambdas as template arguments. An opDispatch could forward template arguments too - it can be done in a two-level definition - but since match is not a member anyway, it isn't quite going to solve things anyway whereas the alias this does seem to work)

C++ Expression tree traversal to change expression to NNF in place

I want to transform an expression into negation normal form. For this, I have a binary expression tree using smart pointers. The problem is that removing double negations is not working when they occur in binary expressions although the function removeDoubleNot() is called at the right time. So e.g. ¬(A∨¬B) becomes ¬A∧¬¬B instead of ¬A∧B, but it works on ¬¬B alone. I assume the mistake is in evaluate() but I could not find it yet. Maybe the recursion is wrong?
// It is assumed that all Expressions are valid
std::shared_ptr<Expression> NNF::removeDoubleNot(std::shared_ptr<Not> expr) {
// Left is a Not -> remove both Nots
if (auto node = dynamic_cast<Not *>(expr->getLeft().get()))
return node->getLeft();
return expr;
}
std::shared_ptr<Expression> NNF::applyDeMorgan(std::shared_ptr<Not> expr) {
// And
if (auto node = dynamic_cast<And *>(expr->getLeft().get())) {
auto newLeft = std::make_shared<Not>(node->getLeft());
auto newRight = std::make_shared<Not>(node->getRight());
return std::make_shared<Or>(newLeft, newRight);
}
// Or
if (auto node = dynamic_cast<Or *>(expr->getLeft().get())) {
auto newLeft = std::make_shared<Not>(node->getLeft());
auto newRight = std::make_shared<Not>(node->getRight());
return std::make_shared<And>(newLeft, newRight);
}
return expr;
}
std::shared_ptr<Expression> NNF::removeImplication(const std::shared_ptr<Implication> &expr) {
auto newLeft = std::make_shared<Not>(expr->getLeft());
auto newRight = expr->getRight();
return std::make_shared<Or>(newLeft, newRight);
}
std::shared_ptr<Expression> NNF::moveNegationInwards(const std::shared_ptr<Not> &notExpr) {
expr = applyDeMorgan(node);
if (auto node = std::dynamic_pointer_cast<Not>(expr))
expr = removeDoubleNot(node);
return expr;
}
std::shared_ptr<Expression> NNF::evaluate(std::shared_ptr<Expression> expr) {
if (expr == nullptr)
return nullptr;
// Implication
if(auto node = std::dynamic_pointer_cast<Implication>(expr)){
auto ret = removeImplication(node);
evaluate(ret->getLeft());
evaluate(ret->getRight());
return ret;
}
// Other binary than implication
if(auto node = dynamic_cast<Binary*>(expr.get())){
evaluate(node->getLeft());
evaluate(node->getRight());
return expr;
}
// Not
if(auto node = std::dynamic_pointer_cast<Not>(expr)) {
auto ret = moveNegationInwards(node);
evaluate(ret->getLeft());
evaluate(ret->getRight());
return ret;
}
return expr;
}
When you call evaluate(ret->getLeft()) you are not using the return value, thus you never change your current child expressions.
So you need to change this to:
ret->setLeft(evaluate(ret->getLeft()));
The same goes for right.
You might want to consider using [[nodiscard]] to get compiler warnings on mistakes like these.

Function overloaded by bool and enum type is not differentiated while called using multiple ternary operator in C++

Got into an interesting problem while tried to call the overloaded function using conditional operator (just to avoid multiple if else condition)
class VirtualGpio
{
typedef enum
{
OUTPUT = 0xC7,
INPUT ,
DIRINVALID
}GpioDirection;
struct pinconfig
{
struct pinmap pin;
GpioPolarity plrty;
bool IsPullupCfgValid;
bool IsTriStCfgValid;
bool IsInputFilterValid;
GpioDirection dic;
gpiolistner fptr; // Callback function pointer on event change
};
};
class factory
{
public:
VirtualGpio *GetGpiofactory(VirtualGpio::pinconfig *cfg,VirtualGpio::GpioAccessTyp acc=VirtualGpio::Pin);
private:
int setCfgSetting(VirtualGpio::pinmap * const getpin, VirtualGpio::GpioDirection const data);
int setCfgSetting(VirtualGpio::pinmap * const getpin, bool const data);
};
int factory::setCfgSetting(VirtualGpio::pinmap * const getpin, VirtualGpio::GpioDirection const data)
{
cout << "It is a Direction overloaded" << endl;
}
int factory::setCfgSetting(VirtualGpio::pinmap * const getpin, bool const data)
{
cout << "It is a bool overloaded" << endl;
}
VirtualGpio* factory::GetGpiofactory(VirtualGpio::pinconfig *cfg,VirtualGpio::GpioAccessTyp acc)
{
VirtualGpio * io = new VirtualGpio();
printf("acc : 0x%X, pin : 0x%x, port : 0x%x\n",acc, cfg->pin.pinno, cfg->pin.portno);
printf("value of expression : 0x%x\n",((acc == VirtualGpio::Pin)? cfg->dic : ((cfg->dic == VirtualGpio::INPUT)?true :false))); <= this prints the right value
if(acc == VirtualGpio::Pin)
setCfgSetting(&cfg->pin,cfg->dic);
else if(cfg->dic == VirtualGpio::INPUT)
setCfgSetting(&cfg->pin,true);
else
setCfgSetting(&cfg->pin,false);
#if 0
if(setCfgSetting(&cfg->pin, ((acc == VirtualGpio::Pin)? cfg->dic : ((cfg->dic == VirtualGpio::INPUT)?true :false))) == ERROR)
{
printf("Error Setting the IO configuration for XRA\n");
}
else
printf("Set IO config successfully\n");
#endif
return io;
}
The commented part #if 0 in GetGpiofactory() is same as the above
multiple if-else-if-else block, but if I uncomment the #if0 part to #if
1, for all the possible inputs only bool version of the overloaded
function i.e setCfgSetting(VirtualGpio::pinmap * const getpin, bool
const data) is invoked.
below is my main code.
main()
{
static struct VirtualGpio::pinconfig cfg = {
.pin = {
.location = VirtualGpio::GPIO_ON_GPIOEXP1_TCI,
.pinno = 0,
.portno = -1
},
.plrty = VirtualGpio::active_high,
.IsPullupCfgValid = true,
.IsTriStCfgValid = true,
.IsInputFilterValid = true,
.dic = VirtualGpio::OUTPUT,
.fptr = NULL
};
factory fac;
fac.GetGpiofactory(&cfg);
}
Surprised, the overloaded function works well if I don't use the ternary operator instead use multiple if-else if-else blocks. curious to understand the reason.
That is because the ternary operator always evaluates to a single type. You can't "return" different types with this operator.
When the compiler encounters such an expression he tries to figure out whether he can reduce the whole thing to one type. If that's not possible you get a compile error.
In your case there is a valid option using bool as a type. Because cfg->dic is an enum type which is implicitly convertible to bool. If you would use and enum class your code would not compile anymore showing you what your actual problem is (example).
Also I don't really see what the advantage of this kind of code is. In my opinion it makes the code much harder to read. You could reduce your ifs to just one, if you're concerned about too many of them:
if(acc == VirtualGpio::Pin)
setCfgSetting(&cfg->pin,cfg->dic);
else
setCfgSetting(&cfg->pin, cfg->dic == VirtualGpio::INPUT);

Evaluate a math expression in Qt

I'm trying to create a Qt application and I need a math expression evaluator to evaluate things like this e.g. (4+5)*2-9/3.
I included the .hpp file of this library (http://www.partow.net/programming/exprtk/) to my project in the Qt Creator and tried to launch the following example of code:
#include <cstdio>
#include <string>
#include "exprtk.hpp"
int main()
{
typedef exprtk::expression<double> expression_t;
typedef exprtk::parser<double> parser_t;
std::string expression_string = "3 + sqrt(5) + pow(3,2) + log(5)";
expression_t expression;
parser_t parser;
if (parser.compile(expression_string,expression))
{
double result = expression.value();
printf("Result: %19.15\n",result);
}
else
printf("Error in expression\n.");
return 0;
}
When I try to compile and run it I get the following output:
debug\main.o:-1: error: too many sections (62303)
What could be the problem?
Using just pure Qt you can do something like this:
QString expression_string("3 + Math.sqrt(5) + Math.pow(3,2) + Math.log(5)");
QScriptEngine expression;
double my_val=expression.evaluate(expression_string).toNumber();
you can do much more, see HERE and HERE
Actually, on my machine (Qt 5.5, Ubuntu 16.04 with g++ 5.3), the code above does not work.
Despite the answer is quite old, I put my solution in case someone finds it useful.
QScriptEngine uses the JavaScript syntax. So to make the above code work, I had to change the syntax to:
QString expression_string("3 + Math.sqrt(5) + Math.pow(3,2) + Math.log(5)");
QScriptEngine expression;
double my_val=expression.evaluate(expression_string).toNumber();
Following the request in comments, here is how to implement an arithmetic parser using boost::spirit. First, you need to download the boost tarball, don't try to just clone Spirit alone from GitHub, because it has dependencies from other boost libraries.
Boost is huge, so if you want just a subset enough for a parser, you can extract it using bcp. From boost source directory:
cd tools/build/src/engine
./build.sh
cd ../../../bcp
../build/src/engine/b2
cd ../..
dist/bin/bcp fusion/include hana/functional spirit/home/x3 /some/path
bcp will copy all dependencies. You can leave only /some/path/boost directory, because all libraries we need are header only.
Finally, here is the full code of the parser.
#include <iostream>
#include <numeric>
#include <stdexcept>
#include <string>
#include <vector>
#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/hana/functional/fix.hpp>
#include <boost/hana/functional/overload.hpp>
#include <boost/spirit/home/x3.hpp>
#include <boost/spirit/home/x3/support/ast/variant.hpp>
using namespace boost::spirit;
namespace hana = boost::hana;
// Define AST. The root is `ast::expr`, which is the first left-hand side
// operand and a list of all operations on the right-hand side. Each operand is
// a recursive `variant` that has `ast::expr` inside.
namespace ast
{
struct nil {};
struct signed_;
struct expr;
struct operand : x3::variant<
nil
, double
, x3::forward_ast<signed_>
, x3::forward_ast<expr>
>
{
using base_type::base_type;
using base_type::operator=;
};
struct signed_
{
char sign;
operand operand_;
};
struct operation
{
char operator_;
operand operand_;
};
struct expr
{
operand first;
std::vector<operation> rest;
};
} // namespace ast
// Give the grammar access to the fields of AST.
BOOST_FUSION_ADAPT_STRUCT(ast::signed_, sign, operand_)
BOOST_FUSION_ADAPT_STRUCT(ast::operation, operator_, operand_)
BOOST_FUSION_ADAPT_STRUCT(ast::expr, first, rest)
// Arithmetic expression grammar definition.
namespace ArithExpr
{
x3::rule<class expression, ast::expr > const expression("expression");
x3::rule<class term, ast::expr > const term("term");
x3::rule<class factor, ast::operand> const factor("factor");
auto const expression_def =
term
>> *(
(x3::char_('+') >> term)
| (x3::char_('-') >> term)
);
auto const term_def =
factor
>> *(
(x3::char_('*') >> factor)
| (x3::char_('/') >> factor)
);
auto const factor_def =
x3::double_
| '(' >> expression >> ')'
| (x3::char_('-') >> factor)
| (x3::char_('+') >> factor);
BOOST_SPIRIT_DEFINE(expression, term, factor);
auto calc = expression;
} // namespace ArithExpr
template <typename Iterator>
double CalcArithExpr(Iterator const &first, Iterator last) {
ast::expr expr;
// Build AST.
if (!x3::phrase_parse(first, last, ArithExpr::calc, x3::ascii::space, expr)) {
throw std::runtime_error("Cannot parse arithmetic expression");
}
// Parse the AST and calculate the result.
// hana::fix allows recursive lambda call
auto astEval = hana::fix([](auto self, auto expr) -> double {
// hana::overload calls a lambda corresponding to the type in the variant
return hana::overload(
[](ast::nil) -> double {
BOOST_ASSERT(0);
return 0;
},
[](double x) -> double { return x; },
[&](ast::signed_ const &x) -> double {
double rhs = boost::apply_visitor(self, x.operand_);
switch (x.sign) {
case '-': return -rhs;
case '+': return +rhs;
}
BOOST_ASSERT(0);
return 0;
},
[&](ast::expr const &x) -> double {
return std::accumulate(
x.rest.begin(), x.rest.end(),
// evaluate recursively left-hand side
boost::apply_visitor(self, x.first),
[&](double lhs, const ast::operation &op) -> double {
// evaluate recursively right-hand side
double rhs = boost::apply_visitor(self, op.operand_);
switch (op.operator_) {
case '+': return lhs + rhs;
case '-': return lhs - rhs;
case '*': return lhs * rhs;
case '/': return lhs / rhs;
}
BOOST_ASSERT(0);
return 0;
}
);
}
)(expr);
});
return astEval(expr);
}
int main(int argc, char *argv[]) {
auto expr = std::string{"-(4.5 + 5e-1) * 2.22 - 9.1 / 3.45"};
std::cout << CalcArithExpr(expr.begin(), expr.end()) << std::endl;
}
It calculates -(4.5 + 5e-1) * 2.22 - 9.1 / 3.45 and outputs -13.7377.
Update
Here are instructions how to build bcp and copy selected headers on Windows. Though, without any guarantee. In Linux everything just works, on Windows it is always jumps over some hoops, and the direction of jumps are always unpredictable.
This being said, open PowerShell command line. There
Import-Module 'C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\Common7\Tools\Microsoft.VisualStudio.DevShell.dll'
Install-Module VSSetup -Scope CurrentUser
Get-VSSetupInstance
Substitute 2019 above with your version of VS. You have to do it only once for your PowerShell. The rest is every time you need to build bcp. Get-VSSetupInstance above will print information about the instances of Visual Studio you have on your machine. Write down InstanceId that you would like to use. Now change to the boost directory in the PowerShell, and:
Enter-VsDevShell InstanceId -DevCmdArguments '-arch=x64' -SkipAutomaticLocation
Where InstanceId is the ID you got from Get-VSSetupInstance. Then from the same command prompt
cd tools\build\src\engine
& .\build.bat
cd ..\..\..\bcp
..\build\src\engine\b2 address-model=64
cd ..\..
dist\bin\bcp fusion\include hana\functional spirit\home\x3 X:\some\path\boost

error: c++ [map] does not name a type

I've written the following as part of a text command parser for a text adventure game.
I'm attempting to associate a string input by a user to an item in an enum class. The following is in my header file:
#include <iostream>
#include <map>
#include <string>
using namespace std;
enum class Noun
{
// Interrogation subjects
name, // ask the subject his name
base, // where is the base?
attack, // when will the attack be?
invalid
};
map < string, Noun > knownNouns;
knownNouns["name"] = Noun::name;
knownNouns["base"] = Noun::base;
knownNouns["attack"] = Noun::attack;
Noun parseNoun(string &noun)
{
auto n = knownNouns.find(noun);
if ( n == knownNouns.end() ) {
return Noun::invalid;
}
return n->second;
When I put this through the compiler, I get the following:
nouns.h:46:1: error: 'knownNouns' does not name a type
knownNouns["name"] = Noun::name;
^
nouns.h:47:1: error: 'knownNouns' does not name a type
knownNouns["base"] = Noun::base;
^
nouns.h:48:1: error: 'knownNouns' does not name a type
knownNouns["attack"] = Noun::attack;
^
nouns.h: In function 'Noun parseNoun(std::string&)':
nouns.h:52:10: error: 'n' does not name a type
auto n = knownNouns.find(noun);
^
nouns.h:53:10: error: 'n' was not declared in this scope
if ( n == knownNouns.end() ) {
^
nouns.h:54:16: error: 'Noun' is not a class or namespace
return Noun::invalid;
^
nouns.h:56:12: error: 'n' was not declared in this scope
return n->second;
^
This is my first time attempting to use maps and enums, and I'm not sure what it is I did wrong. I'm also not terribly familiar with the use of auto vars, so that's a bit of cargo-cult programming on my part. I'm hoping I understood its implementation and the error will clear once I resolve the type definition problem I'm having.
edit: That's embarassing. I copy pasted a mistake that I had already corrected. the code still does not compile when (i.e., the same issue occurs when)
map < string, Noun > knownNouns;
knownNouns["name"] = Verb::name;
knownNouns["base"] = Verb::base;
knownNouns["attack"] = Verb::attack;
is corrected as
map < string, Noun > knownNouns;
knownNouns["name"] = Noun::name;
knownNouns["base"] = Noun::base;
knownNouns["attack"] = Noun::attack;
You can't place non-declaration constructs directly in namespace scope.
A C++ translation unit is a sequence of declarations.
Non-declaration statements such as assignments must be inside function bodies.
Fixed code:
#include <iostream>
#include <map>
#include <string>
using namespace std;
enum class Noun
{
// Interrogation subjects
name, // ask the subject his name
base, // where is the base?
attack, // when will the attack be?
invalid
};
map< string, Noun > knownNouns =
{
{ "name", Noun::name },
{ "base", Noun::base },
{ "attack", Noun::attack }
};
auto parseNoun( string const& noun )
-> Noun
{
// auto n = knownNouns.find(noun);
// if ( n == knownNouns.end() ) {
// return Noun::invalid;
// }
// return n->second;
return Noun::invalid;
}
Here knownNouns is initialized. It's not an assignment, even if the = looks very much like an assignment.
You may not initialize map entries statically like:
knownNouns["name"] = Verb::name;
knownNouns["base"] = Verb::base;
knownNouns["attack"] = Verb::attack;