Getting the literal value of a parameter to a sweet.js macro - sweet.js

I've got a macro defined and I'm trying to test one of the values passed as a parameter to determine how to emit code. However, I keep getting errors thrown when I try to use the value. Here is a simple test that illustrates the problem:
let Test = macro {
case {
_ ($arg1,$arg2,$arg3)
} => {
if ($arg1 ==1) {
return #{
f($arg1,$arg2,$arg3)
}
} else {
return #{
g($arg1,$arg2,$arg3)
}
}
}
}
Test(1,2,3)
The error I get is:
ReferenceError: $arg1 is not defined
I've taken various stabs by calling makeIdent, syntaxUnwrap, etc. without any luck. How can I test the value passed?
Update: After playing around with some things I discovered that I can use this construct to get the value:
#{$arg1}[0].token.value
But then I found this page which suggested that at one point token.value.raw was used instead of token.value, which further suggests that since I'm not going through the official documented API I may be accessing undocumented internals which are subject to change.

Related

'identifier undefined' in C++11 for-loop with USTRUCT

I am implementing logging functionality in Unreal Engine 4.27 (in C++). A key part of my code is a function that is called once per game-tick. This function is responsible for iterating over an array of actors that I would like to log data for, checking whether a new log entry should be written at this point in time and calling the necessary functions to do that.
I am iterating over elements of a TArray of UStructs: LogObject->LoggingInfo = TArray<FActorLoggingInformation>. This array is defined as a UProperty of LogObject. In the loop I have to change the values of the elements so I want to work with the original items and "label" the current item as "ActorLoggingInfo". I have seen this done generally in cpp and also with TArrays. And yet my code does not work, there is no error message, but ActorLoggingInfo is undefined, thus the if-condition is never met.
This is the for-loop:
for (FActorLoggingInformation& ActorLoggingInfo : LogObject->LoggingInfo) {
if (ActorLoggingInfo.LogNextTick == true) {
ActorLoggingInfo.LogNextTick = false;
...
}
...
}
This is the definition of FActorLoggingInformation:
USTRUCT(BlueprintType)
struct FActorLoggingInformation
{
GENERATED_BODY()
public:
FActorLoggingInformation()
{
}
FActorLoggingInformation(int32 LogTimer, AActor* Actor, FString LogName)
{
this->LogTimer = LogTimer;
this->LogNextTick = false;
...
}
// Specifies Logging Frequency in ms
UPROPERTY(BlueprintReadOnly, VisibleAnywhere)
int32 LogTimer;
bool LogNextTick;
...
};
This is the debugger at run-time:
Additional Notes:
1. Something that consistently works for me is omitting the &, using:
for (FActorLoggingInformation ActorLoggingInfo : LogObject->LoggingInfo)
However, this is creating useless duplicates on a per-tick basis and complicates applying changes to the original objects from within in the for-loop, so it is not a viable option.
2. I have also tried auto& instead of FActorLoggingInformation& as used in the examples above, but I encountered the same issue, so I thought it would be best to be as explicit as possible.
I would be very thankful if you had any ideas how I can fix this :)
Thanks in advance!
Thanks to Avi Berger for helping me find my problem!
In fact, ActorLoggingInfo was actually never undefined and the code within the body of the if-clause was also executed (it just didn't do what it was intended to do).
When stepping through the code in the debugger it never showed the steps within the if-body and ActorLoggingInfo was shown as undefined so when no logs were written, I assumed it was something to do with that instead of my output function not working properly. So lesson learnt, do not blindly trust the debugger :)

Using Lua from C++, Fails to open standard libs with Nil error

I've been writing Lua integration into a game project, and frustratingly, every time I try and use lua_pcall, I get the error "attempting to call nil value."
When I try to look up the error, most of the examples are of people who have forgotten to use pcall after loading their lua file, or some error down the line. But for me, it's as soon as I even attempt to load the lua standard libs. I don't understand what's going wrong with so little code to show for it. Other things I've tried are skipping openLibs and going straight to loading my file with doFile, but even in that case, anything I do at all will result in a nil error.
Any help is greatly appreciated.
EDIT:
Thanks to some help I determined that I didn't need to do a pcall for luaL_openlibs, but as I wrote above, trying to run any function at all results in errors. In this case, it can't find "init" in the global lua namespace
c++
void LuaScriptingInterface::init()
{
m_luaState = std::shared_ptr<lua_State>(luaL_newstate());
luaL_openlibs(m_luaState.get());
if (luaL_dostring(m_luaState.get(), m_script.c_str())) // script below
{
const char* errStr = lua_tostring(m_luaState.get(), -1);
ASSERT(false, errStr ); // not hitting this case
}
lua_getglobal(m_luaState.get(), "init");
if (!lua_isfunction(m_luaState.get(), -1))
{
ASSERT(false); // hit this case! Why can't we find "init"?
}
}
lua
init function ()
end
update function (dt)
end
It doesn't do anything yet of course, but I expect it should at least be able to find the function.
Hilariously the issue was in my FileReader code, there was an omitted newline character

.NET Profiler enter/leave function hooks does not get called in case of exception

I am building a .Net Profiler for some custom requirement.
I want to hook at Enter and Leave for some specific methods. To achieve this, I have tried below two approaches.
IL Rewrite - I am able to inject the custom code at both the places. It is successfully getting injected and calling the custom code. I am also able to get the input arguments, 'this' and return value. Injecting at the Enter is not much difficult. However, it's complex to inject at Leave as there could be return at multiple places in a method. I have to inject the code at every place where return statement is written.
It's bit complex but somewhat doable. But, if there any exception, the execution is not reaching to return statement and hence my injected code is not getting invoked.
Subscribe to Enter/Leave through SetEnterLeaveFunctionHooks2 in ICorProfilerInfo2 as per the sample code given here.
In both the cases, hook at the Leave is not getting invoked in case of exception in the method.
How to handle this? I want a return value in all the scenarios. In case of an exception, I should know there is an exception; I will consider as 'No return value'. Probably, I may need exception details as well.
Below is a sample method. I want to hook at Enter and Leave for GetString method. It has multiple returns. I am able to capture the return value in a normal scenario. But in case of exception, execution stops immediately and due to that the hook at return is not getting invoked.
public int GetInt()
{
//int retVal = 10;
int retVal = 1010;
//throw new Exception("test");
return retVal;
}
public string GetString()
{
var retunValue = "Return string ";
if (GetInt() > 100)
{
retunValue += " inside IF > 100";
return retunValue;
}
return retunValue + " at last return";
}
To get the exception notification when using IL re-writing, you need to inject a try-finally or try-catch-throw. Since the ret instruction is not valid within a try block, you will need to replace them with a leave instruction that branches to an instruction after the inserted exception handler and return from there.
Another option is to include COR_PRF_MONITOR_EXCEPTIONS in your call to SetEventMask and listen on the ExceptionUnwindFunctionEnter and ExceptionUnwindFunctionLeave callbacks. These callbacks don't include the thrown exception however. You could track the exception from ExceptionThrown, but this may be misleading when an exception leaves a filter block as the runtime will treat it as returning false and continue with the previous exception, but IIRC, there is no callback to indicate when this happens.

Setting up setCharging for Linea Pro device in Swift

I want to set up the Linea Pro to charge the phone if the phone's battery gets low and I'm having a tough time mainly because all the examples are shown in objective-C still and not in Swift.
The manual says:
#param enabled TRUE to enable charging, FALSE to disable/stop it
#param error pointer to NSError object, where error information is stored in case function fails. You can pass nil if you don't want that information
#return TRUE if function succeeded, FALSE otherwise
*/
and the code provided is the following:
-(BOOL)setCharging:(BOOL)enabled error:(NSError **)error;
So in Swift I first tried this:
self.scanner.setCharging = true
but that gives me the following error:
Cannot assign to property: 'setCharging' is a method
So I tried this:
self.scanner.setCharging(true)
which gives me this error:
Call can throw, but it is not marked with 'try' and the error is not handled
Interesting because apparently I have to build it in a function called "setCharging" I think, but I have no idea what and how it wants me to set up the try and catch to, and quite frankly where am I opposed to get this information from?
I think it should be along these lines or something, but I'm not clear on the specifics :
func setCharging(_ enabled: Bool) throws -> Bool {
do {
try
//something goes here I'm not sure what
} catch {
//and then maybe something here on that to do with error
print("some error")
}
}
The answer was provided to me by the manufacturer. It is unnecessary to create a function with the same name as the API, APIs can be called anywhere in the code with the exception of handling error. So in this case I just have this directly in my code not in a function and it just works. (Since I have my scanner.connect code inside a viewWillAppear block, the code to start charging was too early to be called in there, so I placed it inside of a viewDidAppear block).
The following is the code:
do{
try self.scanner.setCharging(true)
}catch let error as NSError{
NSLog("Operation \(error as Error)")
}

Exception handling aware of execution flow

Edit:
For personn interested in a cleaner way to implemenent that, have a look to that answer.
In my job I often need to use third-made API to access remote system.
For instance to create a request and send it to the remote system:
#include "external_lib.h"
void SendRequest(UserRequest user_request)
{
try
{
external_lib::Request my_request;
my_request.SetPrice(user_request.price);
my_request.SetVolume(user_request.quantity);
my_request.SetVisibleVolume(user_request.quantity);
my_request.SetReference(user_request.instrument);
my_request.SetUserID(user_request.user_name);
my_request.SetUserPassword(user_request.user_name);
// Meny other member affectations ...
}
catch(external_lib::out_of_range_error& e)
{
// Price , volume ????
}
catch(external_lib::error_t& e)
{
// Here I need to tell the user what was going wrong
}
}
Each lib's setter do checks the values that the end user has provided, and may thow an exception when the user does not comply with remote system needs. For instance a specific user may be disallowed to send a too big volume. That's an example, and actually many times users tries does not comply: no long valid instrument, the prices is out of the limit, etc, etc.
Conseqently, our end user need an explicit error message to tell him what to modify in its request to get a second chance to compose a valid request. I have to provide hiim such hints
Whatever , external lib's exceptions (mostly) never specifies which field is the source
of aborting the request.
What is the best way, according to you, to handle those exceptions?
My first try at handling those exceptions was to "wrap" the Request class with mine. Each setters are then wrapped in a method which does only one thing : a try/catch block. The catch block then throws a new exceptions of mine : my_out_of_range_volume, or my_out_of_range_price depending on the setter. For instance SetVolume() will be wrapped this way:
My_Request::SetVolume(const int volume)
{
try
{
m_Request.SetVolume(volume);
}
catch(external_lib::out_range_error& e)
{
throw my_out_of_range_volume(volume, e);
}
}
What do you think of it? What do you think about the exception handling overhead it implies? ... :/
Well the question is open, I need new idea to get rid of that lib constraints!
If there really are a lot of methods you need to call, you could cut down on the code using a reflection library, by creating just one method to do the calling and exception handling, and passing in the name of the method/property to call/set as an argument. You'd still have the same amount of try/catch calls, but the code would be simpler and you'd already know the name of the method that failed.
Alternatively, depending on the type of exception object that they throw back, it may contain stack information or you could use another library to walk the stack trace to get the name of the last method that it failed on. This depends on the platform you're using.
I always prefer a wrapper whenever I'm using third party library.
It allows me to define my own exception handling mechanism avoiding users of my class to know about external library.
Also, if later the third party changes the exception handling to return codes then my users need not be affected.
But rather than throwing the exception back to my users I would implement the error codes. Something like this:
class MyRequest
{
enum RequestErrorCode
{
PRICE_OUT_OF_LIMIT,
VOLUME_OUT_OF_LIMIT,
...
...
...
};
bool SetPrice(const int price , RequestErrorCode& ErrorCode_out);
...
private:
external_lib::Request mRequest;
};
bool MyRequest::SetPrice(const int price , RequestErrorCode& ErrorCode_out)
{
bool bReturn = true;
try
{
bReturn = mRequest.SetPrice(price);
}
catch(external_lib::out_of_range_error& e)
{
ErrorCode_out = PRICE_OUT_OF_LIMIT;
bReturn = false;
}
return bReturn;
}
bool SendRequest(UserRequest user_request)
{
MyRequest my_request;
MyRequest::RequestErrorCode anErrorCode;
bool bReturn = my_request.SetPrice(user_request.price, anErrorCode);
if( false == bReturn)
{
//Get the error code and process
//ex:PRICE_OUT_OF_LIMIT
}
}
I think in this case I might dare a macro. Something like (not tested, backslashes omitted):
#define SET( ins, setfun, value, msg )
try {
ins.setfun( value );
}
catch( external::error & ) {
throw my_explanation( msg, value );
}
and in use:
Instrument i;
SET( i, SetExpiry, "01-01-2010", "Invalid expiry date" );
SET( i, SetPeriod, 6, "Period out of range" );
You get the idea.
Although this is not really the answer you are looking for, but i think that your external lib, or you usage of it, somehow abuses exceptions. An exception should not be used to alter the general process flow. If it is the general case, that the input does not match the specification, than it is up to your app to valid the parameter before passing it to the external lib. Exceptions should only be thrown if an "exceptional" case occurrs, and i think whenever it comes to doing something with user input, you usually have to deal with everything and not rely on 'the user has to provide the correct data, otherwise we handle it with exceptions'.
nevertheless, an alternative to Neil's suggestions could be using boost::lambda, if you want to avoid macros.
In your first version, you could report the number of operations that succeeded provided the SetXXX functions return some value. You could also keep a counter (which increases after every SetXXX call in that try block) to note what all calls succeeded and based on that counter value, return an appropriate error message.
The major problem with validating each and every step is, in a real-time system -- you are probably introducing too much latency.
Otherwise, your second option looks like the only way. Now, if you have to write a wrapper for every library function and why not add the validation logic, if you can, instead of making the actual call to the said library? This IMO, is more efficient.