What are all valid ways of writing closures that return nothing and accept no parameters in Objective-C and Swift? - ios

I'm having trouble understanding closure syntax in Swift and Objective-C.
Can someone tell me all possible ways in both languages to write a closure which accepts no arguments and returns nothing?

In Objective-C language
void (^closureA)(void) = ^{ };
In Swift language
let closureB: () -> ()
let closureC: () -> Void

Since you ask for all and since C is within Objective-C's reach and since you specify no parameters, this also gets the job done.
void ( * f ) ( void ); // C function pointer
Above is purely academic and below for amusement, but with that you can do the following!
// Void block to void function pointer
void ( ^ block ) ( void ) = ^ {
NSLog ( #"You have been warned" );
};
void * p = & block;
long * q = ( long * )( * ( long * ) p );
long * r = q + 2; // Try 0, 1, 2 [crash crash voila!]
void ( * f ) ( void ) = ( void ( * )( void ) )( * r );
// You have been warned
f ();
This is extremely dangerous (and entertaining) but does illustrate the equivalence between the void block and function pointer.

Related

How to disable auto group codo in one line for a short function?

int compare (const void * a, const void * b) {
return ( *(int*)a - *(int*)b );
}
The above code is indented like this by the following command. I'd like to keep its original style (if it is one line, the output is one line, if the input is three lines, the output should be three lines.) Is there a way to do so with clang-format?
$ clang-format -style='{IndentWidth: 8, UseTab: Always, SpaceBeforeParens: Never, IndentCaseLabels: true }'
int compare(const void *a, const void *b) { return (*(int *)a - *(int *)b); }
Given input.cpp:
int compare (const void * a, const void * b) { return ( *(int*)a - *(int*)b ); }
This is the result of using AllowShortFunctionsOnASingleLine: None:
% clang-format -style='{AllowShortFunctionsOnASingleLine: None}' input.cpp
int compare(const void *a, const void *b) {
return (*(int *)a - *(int *)b);
}
% clang-format --version
7.0.1

Is there an equivalent of std::bind in Dart like there is for C++?

Suppose I have something like this
void funct(int a ,int b)
{
std::cout << a+b ;//3+2=5
}
in C++ we could bind a value to parameter to b so the callback will only have to pass in one parameter. Can we do this in dart ?
int main()
{
auto f = std::bind(&funct,std::placeholders::_1,2); //pass b=2
f(3);
}
As mentioned in the comment below your question, you can accomplish this with a closure:
void funct(int a, int b) {
print(a + b);
}
void main() {
var f = (b) => funct(2, b);
f(3);
}

How to use this API "xTaskCreate" to create multiple tasks?

I have read in link, This xTaskCreate FreeRTOS API is used to create a task. Using this API we can create more number of tasks:
/* Task to be created. */
/* Task to be created. */
void vTaskCode( void * pvParameters )
{
/* The parameter value is expected to be 1 as 1 is passed in the
pvParameters value in the call to xTaskCreate() below.
configASSERT( ( ( uint32_t ) pvParameters ) == 1 );
for( ;; )
{
/* Task code goes here. */
}
}
I have seen this program example. I want to create two tasks. First task blink led1, second task blink led2.
I don't understand how to write program for two tasks.
to create the second task just call xTaskCreate twice, like below:
void vTaskLedGreen( void * pvParameters )
{
/* The parameter value is expected to be 1 as 1 is passed in the
pvParameters value in the call to xTaskCreate() below.
configASSERT( ( ( uint32_t ) pvParameters ) == 1 );
for( ;; )
{
vTaskDelay(pdMS_TO_TICKS(1000));
GreenLedOff();
vTaskDelay(pdMS_TO_TICKS(1000));
GreenLedOn();
}
}
void vTaskLedRed( void * pvParameters )
{
/* The parameter value is expected to be 1 as 1 is passed in the
pvParameters value in the call to xTaskCreate() below.
configASSERT( ( ( uint32_t ) pvParameters ) == 1 );
for( ;; )
{
vTaskDelay(pdMS_TO_TICKS(1000));
RedLedOff();
vTaskDelay(pdMS_TO_TICKS(1000));
RedLedOn();
}
}
/* Function that creates a task. */
void main( void )
{
BaseType_t xReturned;
TaskHandle_t xHandle = NULL;
xReturned = xTaskCreate(
vTaskLedRed, /* Function that implements the task. */
"RedLed", /* Text name for the task. */
STACK_SIZE, /* Stack size in words, not bytes. */
( void * ) 1, /* Parameter passed into the task. */
tskIDLE_PRIORITY,/* Priority at which the task is created. */
&xHandle ); /* Used to pass out the created task's handle. */
if( xReturned != pdPASS )
{
ErrorHandler();
}
xReturned = xTaskCreate(
vTaskLedGreen, /* Function that implements the task. */
"GreenLed", /* Text name for the task. */
STACK_SIZE, /* Stack size in words, not bytes. */
( void * ) 1, /* Parameter passed into the task. */
tskIDLE_PRIORITY,/* Priority at which the task is created. */
&xHandle ); /* Used to pass out the created task's handle. */
if( xReturned != pdPASS )
{
ErrorHandler();
}
// Start the real time scheduler.
vTaskStartScheduler();
}

What can be done by void functions in MQL4?

A question by an MQL4 newbie.
What are the limits of what a void function can do in MQL4?.
I mean what can be done by a void function code and what can not be done?.
"void" only means that there is no return value from such function. So "returning a value" can not be done by a void function.
Hope that help....
you can put everything in a void function that you can put in a double, int, string, bool, ... function. What changes is what type of variable the function returns.
For instance, the following int function returns the sum of two values.
int sum( int a, int b )
{
return( a + b );
}
you could turn this function into a void function and instead of returning the value, you can print the value to the console.
void printsum( int a, int b )
{
Print( a + b );
}
In your follow up answer you ask about creating a void function that does something to a moving average. The following void function will accept different periods as input and print the MA. The function can't directly return the value of anything ( unless you use global variables / pass variables by reference ), but it can still accept values and do stuff based on those values.
void PrintMA( int period )
{
Print( iMA( NULL, 0, period, 8, MODE_SMMA, PRICE_MEDIAN, 1 ) );
}
The int function in your follow up answer only ever returns 0, so you could swap it to a void function and remove return(0) and it will work as before. Just change the function name first as start is a function name you should avoid using.
If you read the compile log, you'll be able to see why your above answer won't compile.
The only thing a void function(...) cannot do is to ever participate in an MQL4 assignment statement, i.e.:
someVariable = aVoidDeclaredFUNCTION();
Except this, one can do literally everything imaginable.
How that can be useful?
void aVoidDeclaredFUNCTION( const int thisParameterWillNeverChangeItsVALUE,
int &thisParameterWillBeAbleToChangeVALUE
){...}
Using a technique to pass by-Value, resp. to pass by-reference ( &passVariableByREF ) , even a void function(...) can process and "return"-results, if it is not enough to cause some actions in the void function(...){...} body, per-se.
"Void" just means the function doesn't return anything. These are useful for segmenting any stand alone sections of code (to make the code more organized for example, or to prevent repeating code... etc).
See this short video (not made by me) on the topic: Void Functions

How to keep track of a variable with Clang's static analyzer?

Suppose I'm working with the following C snippet:
void inc(int *num) {*num++;}
void dec(int *num) {*num--;}
void f(int var) {
inc(&var);
dec(&var);
}
By using a static analyzer, I want to be able to tell if the value of var didn't change during the function's execution. I know I have to keep its state on my own (that's the point of writing a Clang checker), but I'm having troubles getting a unique reference of this variable.
For example: if I use the following API
void MySimpleChecker::checkPostCall(const CallEvent &Call,
CheckerContext &C) const {
SymbolRef MyArg = Call.getArgSVal(0).getAsSymbol();
}
I'd expect it to return a pointer to this symbol's representation in my checker's context. However, I always get 0 into MyArg by using it this way. This happens for both inc and dec functions in the pre and post callbacks.
What am I missing here? What concepts did I get wrong?
Note: I'm currently reading the Clang CFE Internals Manual and I've read the excellent How to Write a Checker in 24 Hours material. I still couldn't find my answer so far.
Interpretation of question
Specifically, you want to count the calls to inc and dec applied to each variable and report when they do not balance for some path in a function.
Generally, you want to know how to associate an abstract value, here a number, with a program variable, and be able to update and query that value along each execution path.
High-level answer
Whereas the tutorial checker SimpleStreamChecker.cpp associates an abstract value with the value stored in a variable, here we want associate an abstract value with the variable itself. That is what IteratorChecker.cpp does when tracking containers, so I based my solution on it.
Within the static analyzer's abstract state, each variable is represented by a MemRegion object. So the first step is to make a map where MemRegion is the key:
REGISTER_MAP_WITH_PROGRAMSTATE(TrackVarMap, MemRegion const *, int)
Next, when we have an SVal that corresponds to a pointer to a variable, we can use SVal::getAsRegion to get the corresponding MemRegion. For instance, given a CallEvent, call, with a first argument that is a pointer, we can do:
if (MemRegion const *region = call.getArgSVal(0).getAsRegion()) {
to get the region that the pointer points at.
Then, we can access our map using that region as its key:
state = state->set<TrackVarMap>(region, newValue);
Finally, in checkDeadSymbols, we use SymbolReaper::isLiveRegion to detect when a region (variable) is going out of scope:
const TrackVarMapTy &Map = state->get<TrackVarMap>();
for (auto const &I : Map) {
MemRegion const *region = I.first;
int delta = I.second;
if (SymReaper.isLiveRegion(region) || (delta==0))
continue; // Not dead, or unchanged; skip.
Complete example
To demonstrate, here is a complete checker that reports unbalanced use of inc and dec:
// TrackVarChecker.cpp
// https://stackoverflow.com/questions/23448540/how-to-keep-track-of-a-variable-with-clangs-static-analyzer
#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
#include "clang/StaticAnalyzer/Core/Checker.h"
#include "clang/StaticAnalyzer/Core/CheckerManager.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
using namespace clang;
using namespace ento;
namespace {
class TrackVarChecker
: public Checker< check::PostCall,
check::DeadSymbols >
{
mutable IdentifierInfo *II_inc, *II_dec;
mutable std::unique_ptr<BuiltinBug> BT_modified;
public:
TrackVarChecker() : II_inc(nullptr), II_dec(nullptr) {}
void checkPostCall(CallEvent const &Call, CheckerContext &C) const;
void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
};
} // end anonymous namespace
// Map from memory region corresponding to a variable (that is, the
// variable itself, not its current value) to the difference between its
// current and original value.
REGISTER_MAP_WITH_PROGRAMSTATE(TrackVarMap, MemRegion const *, int)
void TrackVarChecker::checkPostCall(CallEvent const &call, CheckerContext &C) const
{
const FunctionDecl *FD = dyn_cast<FunctionDecl>(call.getDecl());
if (!FD || FD->getKind() != Decl::Function) {
return;
}
ASTContext &Ctx = C.getASTContext();
if (!II_inc) {
II_inc = &Ctx.Idents.get("inc");
}
if (!II_dec) {
II_dec = &Ctx.Idents.get("dec");
}
if (FD->getIdentifier() == II_inc || FD->getIdentifier() == II_dec) {
// We expect the argument to be a pointer. Get the memory region
// that the pointer points at.
if (MemRegion const *region = call.getArgSVal(0).getAsRegion()) {
// Increment the associated value, creating it first if needed.
ProgramStateRef state = C.getState();
int delta = (FD->getIdentifier() == II_inc)? +1 : -1;
int const *curp = state->get<TrackVarMap>(region);
int newValue = (curp? *curp : 0) + delta;
state = state->set<TrackVarMap>(region, newValue);
C.addTransition(state);
}
}
}
void TrackVarChecker::checkDeadSymbols(
SymbolReaper &SymReaper, CheckerContext &C) const
{
ProgramStateRef state = C.getState();
const TrackVarMapTy &Map = state->get<TrackVarMap>();
for (auto const &I : Map) {
// Check for a memory region (variable) going out of scope that has
// a non-zero delta.
MemRegion const *region = I.first;
int delta = I.second;
if (SymReaper.isLiveRegion(region) || (delta==0)) {
continue; // Not dead, or unchanged; skip.
}
//llvm::errs() << region << " dead with delta " << delta << "\n";
if (ExplodedNode *N = C.generateNonFatalErrorNode()) {
if (!BT_modified) {
BT_modified.reset(
new BuiltinBug(this, "Delta not zero",
"Variable changed from its original value."));
}
C.emitReport(llvm::make_unique<BugReport>(
*BT_modified, BT_modified->getDescription(), N));
}
}
}
void ento::registerTrackVarChecker(CheckerManager &mgr) {
mgr.registerChecker<TrackVarChecker>();
}
bool ento::shouldRegisterTrackVarChecker(const LangOptions &LO) {
return true;
}
To hook this in to the rest of Clang, add entries to:
clang/include/clang/StaticAnalyzer/Checkers/Checkers.td and
clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt
Example input to test it:
// trackvar.c
// Test for TrackVarChecker.
// The behavior of these functions is hardcoded in the checker.
void inc(int *num);
void dec(int *num);
void call_inc(int var) {
inc(&var);
} // reported
void call_inc_dec(int var) {
inc(&var);
dec(&var);
} // NOT reported
void if_inc(int var) {
if (var > 2) {
inc(&var);
}
} // reported
void indirect_inc(int val) {
int *p = &val;
inc(p);
} // reported
Sample run:
$ gcc -E -o trackvar.i trackvar.c
$ ~/bld/llvm-project/build/bin/clang -cc1 -analyze -analyzer-checker=alpha.core.TrackVar trackvar.i
trackvar.c:10:1: warning: Variable changed from its original value
}
^
trackvar.c:21:1: warning: Variable changed from its original value
}
^
trackvar.c:26:1: warning: Variable changed from its original value
}
^
3 warnings generated.
I think you missed the check that this call event is a call to your function inc/dec. You should have something like
void MySimpleChecker::checkPostCall(const CallEvent &Call,
CheckerContext &C) const {
const IdentifierInfo* callee = Call.getCalleeIdentifier();
if (callee->getName().str() == "inc" || callee->getName().str() == "dec")
SymbolRef MyArg = Call.getArgSVal(0).getAsSymbol();
}

Resources