Why does this simple annotation example is not rejected in Static Code Analysis? - sal

I'm using SAL to make sure that all code paths that create an object X should call X::work() before destroying it.
#include <sal.h>
class X {
bool worked = false;
public:
_Post_satisfies_(!worked)
X() : worked(false) {}
_Post_satisfies_(worked)
void work() {
worked = true;
}
_Pre_satisfies_(worked)
~X() {
}
};
int main() {
X x;
X y; // Does not call work() but still passes the test anyway
x.work();
}
When I remove x.work(), then there goes an error as intended:
warning C28020: The expression 'this->worked' is not true at this call.
But soon as I add work() for one object x, the other one y also seems to pass the test. Is there some problem in my annotation?

Related

std::list<int> predicate call to function: Error C3867 function call missing argument list

I am using std::list's predicate to update the list based on predicate. But calling in the OnInitDialog() throws compilation error. My code is as follows:
The below is .h:
class CDlgWindow : public CDialog
{
private:
bool single_digit (const int &value);
int _days;
}
The below is .cpp:
CDlgWindow::CDlgWindow(CWnd* pParent, CString strInfo, int days) //ctor
{
_days = days;
//_strInfo = strInfo
}
bool CDlgWindow::single_digit(const int& value)
{
return (value >= _days);
}
BOOL CDlgWindow::OnInitDialog()
{
CDialog::OnInitDialog();
CenterWindow();
.
.
.
int numArr[] = {10,20,30,40};
int size = sizeof(numArr)/sizeof(numArr[0]);
std::list<int> numList (numArr, numArr+size);
numList.remove_if(single_digit); //Error C3867 here!
.
.
}
Complete error message:
Error C3867 function call missing argument list, use '&CDlgWindow::single_digit' to create a pointer to member.
I am trying to understand the functors concept. As I checked in C++11, we have lambdas for easier implementation. Please guide me to understand more on this issue. Thanks!
std::list's remove_if member needs a unary predicate (p) that operates on values (v). The expression p(v) must be valid. Which it isn't if p is a non-static class member (see repro).
There are two options:
Make the predicate (single_digit) a static class member:
class CDlgWindow : public CDialog
{
private:
static bool single_digit (const int &value);
// ...
}
Make the predicate a free function:
bool single_digit(int const& value) {
static int days_ = ...;
return (value >= days_);
}
If you go with option 1 you will have to make _days static as well, since a static member function cannot access non-static instance data. If _days is a compile-time constant, make sure to mark it const as well. That'll open up some compiler optimizations.
This is all hoping that things haven't significantly changed between C++98 and C++11. It's hard to find a C++98 compiler to verify this.

How to do Groovy method signatures with Python-style kwargs AND default values?

I might be asking too much, but Groovy seems super flexible, so here goes...
I would like a method in a class to be defined like so:
class Foo {
Boolean y = SomeOtherClass.DEFAULT_Y
Boolean z = SomeOtherClass.DEFAULT_Z
void bar(String x = SomeOtherClass.DEFAULT_X,
Integer y = this.y, Boolean z = this.z) {
// ...
}
}
And to be able to provide only certain arguments like so:
def f = new Foo(y: 16)
f.bar(z: true) // <-- This line throws groovy.lang.MissingMethodException!
I am trying to provide an API that is both flexible and type safe, which is the problem. The given code is not flexible in that I would have to pass in (and know as the user of the API) the default value for x in order to call the method. Here are some challenges for the solution I want:
Type safety is a must--no void bar(Map) signatures unless the keys can somehow be made type safe. I realize with this I could do the type checking in the method body, but I'm trying to avoid that level of redundancy as I have many of this "kind" of method to write.
I could use a class for each method signature--something like:
class BarArgs {
String x = SomeOtherClass.DEFAULT_X
String y
String z
}
And define it like:
void bar(BarArgs barArgs) {
// ...
}
And call it using my desired way using the map constructor: f.bar(z: true), but my problem lies in the object's default on y. There's no way to handle that (that I know of) without having to specify it when calling the method as in: f.bar(y: f.y, z: true). This is fine for my little sample, but I'm looking at 20-30 optional parameters on some methods.
Any suggestions (or questions if needed) are welcome! Thank you for taking a look.
Interesting question. I've interpreted your requirements like this
The class should have a set of default properties.
Each method should have a set of default arguments.
The method defaults override the class defaults.
Each method can have additional arguments, not existing on the class.
The method arguments should not modify the class instance.
Provided arguments needs to be checked for type.
I was not sure about number 5 since it is not explicitly specified, but it
looked like that was what you wanted.
As far as I know, there is nothing built-in in groovy to support all this,
but there are several ways to make it work in a "simple-to-use" manner.
One way that comes to mind is to create specialized argument classes, but
only use maps as the arguments in the methods. With a simple super-class
or trait to verify and set the properties, it is a one-liner to get the
actual arguments for each method.
Here is a trait and some examples that can be used as a starting point:
trait DefaultArgs {
void setArgs(Map args, DefaultArgs defaultArgs) {
if (defaultArgs) {
setArgs(defaultArgs.toArgsMap())
}
setArgs(args)
}
void setArgs(Map args) {
MetaClass thisMetaClass = getMetaClass()
args.each { name, value ->
assert name instanceof String
MetaProperty metaProperty = thisMetaClass.getMetaProperty(name)
assert name && metaProperty != null
if (value != null) {
assert metaProperty.type.isAssignableFrom(value.class)
}
thisMetaClass.setProperty(this, name, value)
}
}
Map toArgsMap() {
def properties = getProperties()
properties.remove('class')
return properties
}
}
With this trait is it easy to create specialized argument classes.
#ToString(includePackage = false, includeNames = true)
class FooArgs implements DefaultArgs {
String a = 'a'
Boolean b = true
Integer i = 42
FooArgs(Map args = [:], DefaultArgs defaultArgs = null) {
setArgs(args, defaultArgs)
}
}
#ToString(includePackage = false, includeNames = true, includeSuper = true)
class BarArgs extends FooArgs {
Long l = 10
BarArgs(Map args = [:], FooArgs defaultArgs = null) {
setArgs(args, defaultArgs)
}
}
And a class that uses these arguments:
class Foo {
FooArgs defaultArgs
Foo(Map args = [:]) {
defaultArgs = new FooArgs(args)
}
void foo(Map args = [:]) {
FooArgs fooArgs = new FooArgs(args, defaultArgs)
println fooArgs
}
void bar(Map args = [:]) {
BarArgs barArgs = new BarArgs(args, defaultArgs)
println barArgs
}
}
Finally, a simple test script; output of method invocations in comments
def foo = new Foo()
foo.foo() // FooArgs(a:a, b:true, i:42)
foo.foo(a:'A') // FooArgs(a:A, b:true, i:42)
foo.bar() // BarArgs(l:10, super:FooArgs(a:a, b:true, i:42))
foo.bar(i:1000, a:'H') // BarArgs(l:10, super:FooArgs(a:H, b:true, i:1000))
foo.bar(l:50L) // BarArgs(l:50, super:FooArgs(a:a, b:true, i:42))
def foo2 = new Foo(i:16)
foo2.foo() // FooArgs(a:a, b:true, i:16)
foo2.foo(a:'A') // FooArgs(a:A, b:true, i:16)
foo2.bar() // BarArgs(l:10, super:FooArgs(a:a, b:true, i:16))
foo2.bar(i:1000, a:'H') // BarArgs(l:10, super:FooArgs(a:H, b:true, i:1000))
foo2.bar(l:50L) // BarArgs(l:50, super:FooArgs(a:a, b:true, i:16))
def verifyError(Class thrownClass, Closure closure) {
try {
closure()
assert "Expected thrown: $thrownClass" && false
} catch (Throwable e) {
assert e.class == thrownClass
}
}
// Test exceptions on wrong type
verifyError(PowerAssertionError) { foo.foo(a:5) }
verifyError(PowerAssertionError) { foo.foo(b:'true') }
verifyError(PowerAssertionError) { foo.bar(i:10L) } // long instead of integer
verifyError(PowerAssertionError) { foo.bar(l:10) } // integer instead of long
// Test exceptions on missing properties
verifyError(PowerAssertionError) { foo.foo(nonExisting: 'hello') }
verifyError(PowerAssertionError) { foo.bar(nonExisting: 'hello') }
verifyError(PowerAssertionError) { foo.foo(l: 50L) } // 'l' does not exist on foo

accessing an element in a range in D

I am writing my first D program, and trying to understand how to implement an associative array. The issue that keeps coming up is that if i create an array like:
import std.stdio;
import std.string;
import std.array;
void main(string[] args) {
int[string] arr = ["first" : 1, "second" : 2];
}
everything compiles fine. but if i try and move arr outside of main--into a struct, i get an error saying: Error: non-constant expression.
this throws the error:
import std.stdio;
import std.string;
import std.array;
struct foo {
int[string] arr = ["first" : 1, "second" : 2];
}
void main(string[] args)
{ /* do stuff with foo */ }
I'm sure this is a super simple fix, but this is my first attempt at D.
This limitation comes from the fact that symbols in D modules are not ordered but exist "in parallel". Which is generally a good thing because:
compiler can possibly do semantic analysis in parallel
you don't need explicit forward declarations (like in C) to use symbol declared later in the module
With that in mind, consider this code (global scope):
int x;
int foo() { return ++x; }
int y1 = foo();
int y2 = foo();
If using run-time code was allowed for initializers, values of y1 and y2 would depend on order of evaluation which is not defined in general - all globals are "equal".
But for local function variables there is no such problem - they are placed on stack and thus order of evaluation is perfectly defined (it is in lexical order):
void foo()
{
int x;
int foo() { return ++x; }
int y1 = foo(); // will always be 1
int y2 = foo(); // will always be 2
}
Because of that compiler restricts you to only compile-time constants when using initializer syntax for globals or struct fields. Constructors (including module constructors) are still OK though:
int[int] x;
static this()
{
x = [ 1 : 1, 2 : 2 ];
}
AA literal may look like a proper constant but it actually needs to allocate memory from run-time heap. D is smart enough to accept some of such entities (even some classes) and put them in fixed binary memory section but AA may be extended so proper dynamic heap is necessary.
Also please note that struct in D can't have default constructor:
struct foo
{
int[string] arr;
// this won't work:
this() { this.arr = ["first" : 1, "second" : 2]; }
}
// need class instead
class boo
{
int[string] arr;
// fine:
this() { this.arr = ["first" : 1, "second" : 2]; }
}
Something like this will work.
struct Foo{
int[string] arr;
}
void main(){
Foo foo = Foo(["first" : 1, "second" : 2]);
}

Is it possible to have different signature?

I have the following code :
class Test {
static function main() {
trace("Haxe is great!");
var api:Api = new Api();
api.doAdd(1,1);
}
}
class Api {
public function new(){}
public function doAdd( x : Int, y : Int ) {
trace( x + y );
}
public function doAdd( x : Int, y : Int , z : Int) {
trace( x + y + z);
}
}
Here is a link to a try Haxe code
If I try to compile this code, I get an error : ```Duplicate class field declaration : doAdd````
My question is, is there anyway to have two methods with differents signatures in haxe ?
On the Java and C# targets, the following works:
#:overload
public function doAdd(x:Int, y:Int) {
trace(x + y);
}
#:overload
public function doAdd(x:Int, y:Int, z:Int) {
trace(x + y + z);
}
On other targets, the syntax for #:overload is a bit different and only works for externs as far as I understand it. There's an example in this thread.

haxe "should be int" error

Haxe seems to assume that certain things must be Int. In the following function,
class Main {
static function main() {
function mult_s<T,A>(s:T,x:A):A { return cast s*x; }
var bb = mult_s(1.1,2.2);
}
}
I got (with Haxe 3.01):
Main.hx:xx: characters 48-49 : mult_s.T should be Int
Main.hx:xx: characters 50-51 : mult_s.A should be Int
Can anyone please explain why T and A should be Int instead of Float?
A more puzzling example is this:
class Main {
public static function min<T:(Int,Float)>(t:T, t2:T):T { return t < t2 ? t : t2; }
static function main() {
var a = min(1.1,2.2); //compile error
var b = min(1,2); //ok
}
}
I can't see why t<t2 implies that either t or t2 is Int. But Haxe seems prefer Int: min is fine if called with Int's but fails if called with Float's. Is this reasonable?
Thanks,
min<T:(Int,Float)> means T should be both Int and Float. See the constraints section of Haxe Manual.
Given Int can be converted to Float implicitly, you can safely remove the constraint of Int. i.e. the following will works:
http://try.haxe.org/#420bC
class Test {
public static function min<T:Float>(t:T, t2:T):T { return t < t2 ? t : t2; }
static function main() {
var a = min(1.1,2.2); //ok
$type(a); //Float
trace(a); //1.1
var b = min(1,2); //ok
$type(b); //Int
trace(b); //1
}
}

Resources