CFor in Haxe using Macros - for-loop

So, I love macros (yell at me).
I was trying to create a macro in Haxe, which allows me to write the traditional (C++, Java) for-loop and have the same functionality. But I am quite a beginner in Haxe...
Code:
import haxe.macro.Expr;
class Cfor {
macro public static function cfor(init: Expr, cond: Expr, post: Expr, body: Expr) {
return macro {
$init;
while ($cond) {
$body;
$post;
}
}
}
public static function main() {
trace("Traced");
cfor(var i = 0, i < 100, i++, {
var x = i * 2;
trace(x);
});
}
}
Questions:
It already works (that specific test), but it's not that close to the traditional for-loop. How to improve that?
Do you have any other improvements (style/functionality) for this code?
Is there anything target specific which I should know of about this code?
How can I see what this call to cfor expands to?

What about this?
https://gist.github.com/dpeek/7476625
The approach is different (applied to the context) but I think it is a little closer to the desired outcome.
I don't see any potential target specific issues with your code.

Related

How to suppress Kotlin unused parameter warning in all test classes?

In parameterized tests I use hint parameter to clarify test case naming. From the static analyzer point of view this parameter is never used, so this warning from kotlin-maven-plugin appears in the build log:
[WARNING] /Users/test/TestSizeCreation.kt: (42, 10) Parameter 'hint' is never used
How to suppress such warnings globally in all tests?
Example of test with hint:
#ParameterizedTest(name = "Size {index}: {0}")
#MethodSource("invalidAges")
fun shouldFailToCreateAge(hint: String, sizeCandidate: Int) {
assertThatThrownBy { Size(sizeCandidate) }
.isInstanceOf(InvalidInput::class.java)
.hasMessageStartingWith("Could not recognize size: ")
}
companion object {
#JvmStatic
fun invalidAges(): Stream<Arguments> =
Stream.of(
arguments("negative", -5),
arguments("zero", 0),
arguments("too much", 1000)
)
}
Two possible options (there may be more):
The first is to annotate the parameter as being unused, like this:
#Suppress("UNUSED_PARAMETER") either at the function or parameter level.
The second option is to use a lambda inside your test to execute the actual code, and then use an underscore to ignore the first parameter, like this:
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.Arguments
import org.junit.jupiter.params.provider.Arguments.arguments
import org.junit.jupiter.params.provider.MethodSource
import java.util.stream.Stream
class Stack {
#ParameterizedTest(name = "Size {index}: {0}")
#MethodSource("invalidAges")
fun shouldFailToCreateAge(hint: String, sizeCandidate: Int) {
process(hint, sizeCandidate) { _, size ->
println("add your test using size here $size")
}
}
private fun process(hint: String, sizeCandidate: Int, block: (String, Int) -> Unit) {
block(hint, sizeCandidate)
}
companion object {
#JvmStatic
fun invalidAges(): Stream<Arguments> =
Stream.of(
arguments("negative", -5),
arguments("zero", 0),
arguments("too much", 1000)
)
}
}
I ended up using this function introduced only in the src/test context:
// this function used only to avoid "Parameter is never used" warning
// on intentionally unused parameters
fun Any?.touch() = Unit
This how it looks in a test method:
#ParameterizedTest(name = "Size {index}: {0}")
#MethodSource("invalidAges")
fun shouldFailToCreateAge(hint: String, sizeCandidate: Int) {
hint.touch()
assertThatThrownBy { Size(sizeCandidate) }
.isInstanceOf(InvalidInput::class.java)
.hasMessageStartingWith("Could not recognize size: ")
}
Why:
The #Suppress("UNUSED_PARAMETER") is intended strictly for special situations in rare cases. And would be inappropriate to put it in all Parameterized tests making it noisy. It also could cause missing real cases of unused parameters, helping garbage code appear.
The touch method clearly shows intention. And it looks like a minimal evil.

VS2012 complains when using +[]{} sorcery

I want automatic deduction of the arguments of a templated function which accepts a function, while using lambdas. This Example shows some of my options:
template <class T>
void foo(void (*func)(T)) {
T val;
// do something with val and func...
}
int main() {
auto pfunc0 = [] (int) { /*...*/ };
void (*pfunc1)(int) = [] (int) { /*...*/ };
auto* pfunc2 = +[] (int) { /*...*/ };
foo(pfunc0); // not ok
foo<int>(pfunc0); // ok, but redundant
foo(pfunc1); // ok, but redundant
foo(pfunc2); // ok
}
pfunc2 uses a trick I learned here: Obtaining function pointer to lambda?. So actually I should be happy with the pfunc2 case as it is concise and non repeating code, unfortunately the Visual C++ 2012 IDE complains it was erroneous code even though it compiles just fine.
Are there any workarounds or recommendations for this problem?
IDE error messages:
In the "auto* pfunc2" line: The IDE underlines 'auto' and says
Error: cannot deduce 'auto' type
also it underlines '[' where it complains
Error: more than one conversion function from "lambda[]void (int)->void" to a build-in type applies:
function "lambda[]void (int)->void::operator void (*)(int)() const"
function "lambda[]void (int)->void::operator void (*)(int)() const"
function "lambda[]void (int)->void::operator void (*)(int)() const"
This is related to this bug (closed as "by design"). VC++ supports several calling conventions on x86 and lambdas with empty capture lists provide conversions to them all. That's why there's ambiguity.
Unfortunately, there's no workaround listed that you haven't already tried.
By the way, this bug is listed as fixed in Visual C++ 2015 Update 2

How to get Unit component? Can i use addAsync for get solution?

I want to built a program which is get problems and I found that my first batches of tests involving custom components would tend to follow code:
import mx.core.Application;   
 import mx.events.FlexEvent;
 import flexunit.framework.TestCase;
public class CustomComponentTest extends TestCase {
private var component:CustomComponent;
public function testSomeAspect() : void {
component = new CustomComponent();
component.addEventListener(FlexEvent.CREATION_COMPLETE,
addAsync(verifySomeAspect, 5000));
component.height = 0;
component.width = 0;
Application.application.addChild(component);
}
public function verifySomeAspect(event:FlexEvent) : void {}
override public function tearDown() : void {
 try {
if (component) {
Application.application.removeChild(component);
component = null;
}
} catch (e:Error) {
 }
}
First, you need to make sure the component has been fully initialized before you can reliably verify anything about it, and in Flex this happens asynchronously after it has been added to the display list. So you need to setup a callback (using FlexUnit's addAsync function) to be notified when that's happened.
Lately i've been just manually calling the methods that the runtime would call for you in the necessary places, so now my tests tend to look more like this:
import flexunit.framework.TestCase;
public class CustomComponentTest extends TestCase {
public function testSomeAspect() : void {
var component:CustomComponent = new CustomComponent();
 component.initialize();
component.validateProperties();
}
This is much easier to follow, but it kinda feels like I'm cheating a little either way. The first case is slamming it into the current Application (which would be the unit test runner shell app), and the latter isn't a "real" environment.I was wondering how other people would handle this sort of situation?
I can agree that the second version is shorter, but I'm not sure that I think it's easier to follow. The test does a lot of things that you wouldn't normally do, whereas the first example is more true to how you would use the component outside the test environment.
Also, in the second form you have to make sure that you do exactly what the framework would do, miss one step and your test isn't relevant, and each test must repeat this code. Seems to me it's better to test it in a situation that is as close to the real thing as possible.
You could have a look at dpUint's sequences, they made component testing a little more declarative:
public function testLogin():void {
var passThroughData:Object = new Object();
passThroughData.username = "myuser1";
passThroughData.password = "somepsswd";
var sequence:SequenceRunner = new SequenceRunner(this);
sequence.addStep(new SequenceSetter(form.usernameTI,
{text:passThroughData.username}));
sequence.addStep(new SequenceWaiter(form.usernameTI,
FlexEvent.VALUE_COMMIT, 100));
sequence.addStep(new SequenceSetter(form.passwordTI,
{text:passThroughData.password}));
sequence.addStep(new SequenceWaiter(form.passwordTI, FlexEvent.VALUE_COMMIT, 100));
sequence.addStep(new SequenceEventDispatcher(form.loginBtn,
new MouseEvent("click", true, false)));
sequence.addStep(new SequenceWaiter(form, "loginRequested", 100));
sequence.addAssertHandler(handleLoginEvent, passThroughData);
sequence.run();}

Code Brain "Teaser" -- but not really

I'm just curious to see what you guys think about this. I heard a bunch of answers passed around the office and I want to see if you guys can have possibly a better one.
Question:
You have two functions outlined below:
function one()
{
A();
B();
C();
}
function two()
{
A();
D();
C();
}
How would you re-write this (anything counts, you could create classes, variables, other methods, anything), to reduce code duplication?
Each of the methods called changes variables that the other functions need to use. Methods A() B() and C() are already defined.
Not all languages will support this approach, and the syntax of passing a function may vary between those that do, but the concept would be:
function one()
{
refactored(B);
}
function two()
{
refactored(D);
}
function refactored(middleMan)
{
A();
middleMan();
C();
}
There is no code duplication here. It looks fine.
Each of the methods called changes variables that the other functions need to use.
I would start by refactoring the entire class to use proper OOP.
There are a number of ways to refactor that code; which I would use depends on the specific application, as it may mean that I need to reconsider things at a higher level, e.g. redefine classes, or at worst review the entire application design because the duplication means I missed some key relationship.
If your functions one() and two() are really three-liners as in the example, I wouldn't rewrite anything. You would loose readability and make the code much harder to understand for the next guy.
If the calls to A() and C() are actually larger blocks of code...
- define a base class with abstract method X() and a concrete
function any()
{
A();
X();
C();
}
define a class One where X() is implemented by B()
define a class Two where X() is implemented by D()
Here's one option.
function (triggerA, triggerB, triggerC, triggerD)
{
A(triggerA);
B(triggerB);
C(triggerC);
D(triggerD);
}
This way you're only calling one function to do it all, and skips whatever you don't need/want to do.
If you have closures, lambdas etc. available, you could write
function one()
{
three(B)
}
function two()
{
three(D);
}
function three(middle)
{
A();
middle();
C();
}
You could (but probably shouldn't) make a class where A() is the constructor and C() is the destructor, and have one() and two() be methods of the class calling B() and D() respectively.
I said you probably shouldn't because OOP should be used to write code that makes sense and not for obscure optimization reasons.
In C++ this is usually accomplished with RAII if the context makes sense... this pattern is usually A() = some init function, C() = some de-init function. There's usually also a context associated that's being initialized or destroyed as well.
class bar
{
bar() {
A();
}
~bar() {
C();
}
};
void one()
{
bar barvar;
B();
}
void two()
{
bar barvar;
D();
}

How to take advantage of an auto-property when refactoring this .Net 1.1 sample?

I see a lot of legacy .Net 1.1-style code at work like in example below, which I would like to shrink with the help of an auto-property. This will help many classes shrink by 30-40%, which I think would be good.
public int MyIntThingy
{
get
{
return _myIntThingy;
}
set
{
_myIntThingy = value;
}
} private int _myIntThingy = -1;
This would become:
public int MyIntThingy
{
get;
set;
}
And the only question is - where do I set MyIntThingy = -1;?
If I wrote the class from the start, then I would have a better idea, but I did not. An obvious answer would be: put it in the constructor. Trouble is: there are many constructors in this class. Watching the initialization to -1 in the debugger, I see it happen (I believe) before the constructor gets called. It is almost as if I need to use a static constructor as described here:
http://www.c-sharpcorner.com/uploadfile/cupadhyay/staticconstructors11092005061428am/staticconstructors.aspx
except that my variables are not static. Java's static initializer comes to mind, but again - my variables are not static. http://www.glenmccl.com/tip_003.htm
I want to make stylistic but not functional changes to this class. As crappy as it is, it has been tested and working for a few years now. breaking the functionality would be bad. So ... I am looking for shorter, sweeter, cuter, and yet EQUIVALENT code. Let me know if you have questions.
I'm afraid that you have no option.
If you want to use an auto-property with an initial value that differs from the type's default value then you'll need to set the initial value in the constructor(s).
If you just need a stylistic, non-breaking change, consider changing the format a little:
public int MyIntThingy
{
get { return _myIntThingy; }
set { _myIntThingy = value; }
}
private int _myIntThingy = -1;
Isn't that prettier?
And consider using auto-properties for future code only. It sounds too risky to use them on existing code, unless there are no default values.

Resources