Segfault when importing Swift enumeration with String.Index associated value from framework - xcode

I'm experimenting with Swift frameworks. I've discovered some strange behavior. Look at the following enumeration from my framework:
public enum Sobchak {
case Walter(String.Index)
}
In my framework, this compiles without a problem. Unit tests using it work fine. But if I create another project, reference my framework, and then create a declaration using the enumeration above, the compiler actually crashes with a segmentation fault. (It also kills SourceKitService completely.) The problem appears to be related to String.Index (which is actually a struct, not a type alias). If I take it out, everything works. If I use a simple type like Int or String, no problem. I can even use type aliases, e.g.:
public enum Sobchack {
case Walter(Array<Int>.Element)
}
This compiles just fine. (Of course, anyone saying Array<Int>.Element instead of just Int should be quietly shown the door.)
Anyone have any insight on this? String.Index is definitely the culprit. I can't reproduce this problem with any other type.

Related

Using instances of generic types as return value type in a Hyperledger chain code written in GO

In my project, I am using a wrapper structure, that is defined similar to this:
type Wrapper[T any] struct {
Foo int
Data T
}
Additionally, my chain code offers a method with the following signature
func(contract *MyContract) DoSomething() *Wrapper[mypkg.Bar]
where Bar is a simple structure defined - for example - like this:
package mypkg
struct Bar {
Foo string
Bar string
}
Anyhow, if I try to deploy my chaincode, I get the following error:
Error compiling schema for MyContract[DoSomething]. Return schema invalid. Object has no key 'Wrapper[[]<part of module name>'
Strangely, the part with Wrapper[[]<part of module name> is cropped. So only part of the module name is showing, and, as you can see, the bracketing is wrong: The second closing bracket is missing (so that is not a mistake made by me). The name of my module is the link to the GitHub repository.
I have tried to manually replace the generic type T in Wrapper with Bar by creating the structure
type WrapperBar struct {
Foo int
Data Bar
}
If I now adapt the function signature to
func(contract *MyContract) DoSomething() *WrapperBar
it works just fine. Unfortunately, I am using the structure Wrapper several times with different
type instantiations. So although creating all the types manually would be a workaround, it is obviously not a very elegant one.
Is there another workaround so that I can still use my generic Wrapper structure?
I am currently using go in version 1.18 and fabric-contract-api-go in version v1.1.1.
The Go contract-api at this time doesn't support Go Generics, the only workarounds I can suggest are the one that you have tried noted in this question or to write your chaincode without using the contract API, there is an example here https://github.com/hyperledger/fabric-samples/tree/main/chaincode/marbles02/go of an implementation that doesn't use the contract-api.
Your implemention will have to do more work in your chaincode such as providing your own method dispatching, validating and unmarshalling the input data
You could raise an issue at https://github.com/hyperledger/fabric-contract-api-go and ideally also contribute a PR that addresses this issue as I can't say when or if this would ever be supported.

Hint or infer the return type for RSpec let() implementing FactoryGirl create()

Using RubyMine, in an rspec test, is there a way to let RubyMine know the type of the created object (for auto-completion and 'cannot find ' warning suppression?
eg:
# #yieldreturn [Tibbees::Tibbee]
let!(:tibbee) {
create(:tibbee,
canonical_vendible: article_vendible,
owner: tibbee_user)
}
RubyMine doesn't seem to recognise #yieldreturn (and I'm not sure if that's correct anyhow) and I've had no luck with #type and #return.
The
let!(:tibbee) { create(...) || Tibbees::Tibbee.new }
cludge works, but yuk. Any advice greatly appreciated. Perhaps there's even a way to let the factories take care of it, but that seems 'too deep' an abstraction to be likely to be picked up by RubyMine?
Not an immediate solution, but:
While google on this, I came across https://github.com/JetBrains/ruby-type-inference which holds great promise for the future, that is probably relevant to anyone with an interest in this question.
From the README:
ruby-type-inference project is a completely new approach to tackle the problems Ruby dynamic nature by providing more reliable symbol resolution and type inference.
In answer to some questions I asked them:
We are going to make the plugin working and publicly available with 2017.3 release though it will definitely be in "beta" since several problems are yet to be solved even on the theoretical side. For everything to work real properly we have to rework our type system on IDE side which is most likely not going to be completed in 2017.
It might be run at the moment, however ... the results are more of experimental value ... [and] it will be difficult to use it on a daily basis.
This is an old request, but updating for future reference with discussion at https://youtrack.jetbrains.com/issue/RUBY-19907:
As of today (RubyMine 2021.2.3, Build #RM-212.5457.52) Rubymine can now introspect the correct type for FactoryBot create within a let, so that:
let(:name) { create(:some_model)} now has the type inferred correct from the factory.
However it would still be useful to be able to annotate a let that can't be introspected (maybe it's not calling FactoryBot).
But the suggestion of #yieldreturn seems wrong - that's for methods that take a block. But it would be nice if you could annotate let(:whatever){} with #return tag. Compare https://rubydoc.info/gems/yard/file/docs/Tags.md#yieldreturn with https://rubydoc.info/gems/yard/file/docs/Tags.md#return

Should I always use the override contextual keyword?

I know that the override contextual keyword was introduced to write safer code (by checking for a virtual function with the same signature) but I don't feel good about it, because it seems to be redundant for me to write override every time I want to override a virtual function.
Is it a bad practice to not use override contextual keyword for 99% of cases? Why/when should I have to use it (a compiler warning is not enough when we are hiding a virtual function mistakenly)?
EDIT: In other words; what is the advantage of using the override contextual keyword in C++11 while we always had a compiler warning if we were hiding a virtual function mistakenly in C++03 (without using override contextual keyword)?
The override keyword is totally useful and I would recommend using it all the time.
If you misspell your virtual function it will compile fine but at runtime the program will call the wrong function. It will call the base class function rather than your override.
It can be a really difficult bug to find:
#include <iostream>
class Base
{
public:
virtual ~Base() {}
virtual int func()
{
// do stuff for bases
return 3;
}
};
class Derived
: public Base
{
public:
virtual int finc() // WHOOPS MISSPELLED, override would prevent this
{
// do stuff for deriveds
return 8;
}
};
int main()
{
Base* base = new Derived;
std::cout << base->func() << std::endl;
delete base;
}
Annotations are what you call contextual keywords, they serve as clarification, to make sure anyone who reads the code realizes it is a function that overrides a function in a superclass or a interface.
The compiler can also give a warning if the originally overridden feature was removed, in which case you might want to think about removing your function as well.
As far as I know, nothing bad happens if you ommit anotations. It's neither right nor wrong. Like you stated correctly already: annotations are introduced to write safer code.
However: They won't change your code in any functional way.
If you work as a single programmer on your own project it might not matter wheter you use them or not. It is however good practice to stick to one style (i.e. either you use it, or you don't use it. Anything inbetween like sometimes using it and sometimes not only causes confusion)
If you work in a Team you should discuss the topic with your teammates and decide wheter you all use it or not.
What is the advantage of using override contextual keyword in C++11 while we always had a compiler warning if we were hiding a virtual function mistakenly
Nearly none!?
But:
It depends on how much warnings will be accepted by your build rules. If you say, every warning MUST be fixed, you will get the same result UNTIL you are using a compiler which give you the warning.
We have decided to always use override and remove virtual on overriding methods. So the "overhead" is zero and the code is portable in the meaning of "give an error" on misuse.
I personally like this new feature, because it makes the language clearer. If you say this is an override, it will be checked! And if we want to add a new method with different signature, we will NOT get a false positive warning, which is important in your scenario!

An alternative to TaskEx.FromResult on a platform where it's not available

I am converting a portable class library to use a different profile (78). Most of the changes were related to reflection API, and now I have few last lines that don't compile, all of them are using TaskEx.FromResult.
TaskEx.FromResult is handy when a method returns Task, and a value of T needs to be wrapped and returned from the method, e.g.:
public Task<int> ReturnTaskOfInt()
{
return TaskEx.FromResult(42);
}
Unfortunately TaskEx is not available for some PCL profiles. Perhaps it shouldn't be hard to write a replacement for it, and I will appreciate an advise.
Oops, it was damn easy. TaskEx.FromResult is not available, but Task.FromResult is there.

How good idea is it to use code contracts in Visual Studio 2010 Professional (ie. no static checking) for class libraries?

I create class libraries, some which are used by others around the world, and now that I'm starting to use Visual Studio 2010 I'm wondering how good idea it is for me to switch to using code contracts, instead of regular old-style if-statements.
ie. instead of this:
if (fileName == null)
throw new ArgumentNullException("fileName");
use this:
Contract.Requires(fileName != null);
The reason I'm asking is that I know that the static checker is not available to me, so I'm a bit nervous about some assumptions that I make, that the compiler cannot verify. This might lead to the class library not compiling for someone that downloads it, when they have the static checker. This, coupled with the fact that I cannot even reproduce the problem, would make it tiresome to fix, and I would gather that it doesn't speak volumes to the quality of my class library if it seemingly doesn't even compile out of the box.
So I have a few questions:
Is the static checker on by default if you have access to it? Or is there a setting I need to switch on in the class library (and since I don't have the static checker, I won't)
Are my fears unwarranted? Is the above scenario a real problem?
Any advice would be welcome.
Edit: Let me clarify what I mean.
Let's say I have the following method in a class:
public void LogToFile(string fileName, string message)
{
Contracts.Requires(fileName != null);
// log to the file here
}
and then I have this code:
public void Log(string message)
{
var targetProvider = IoC.Resolve<IFileLogTargetProvider>();
var fileName = targetProvider.GetTargetFileName();
LogToFile(fileName, message);
}
Now, here, IoC kicks in, resolves some "random" class, that provides me with a filename. Let's say that for this library, there is no possible way that I can get back a class that won't give me a non-null filename, however, due to the nature of the IoC call, the static analysis is unable to verify this, and thus might assume that a possible value could be null.
Hence, the static analysis might conclude that there is a risk of the LogToFile method being called with a null argument, and thus fail to build.
I understand that I can add assumptions to the code, saying that the compiler should take it as given that the fileName I get back from that method will never be null, but if I don't have the static analyzer (VS2010 Professional), the above code would compile for me, and thus I might leave this as a sleeping bug for someone with Ultimate to find. In other words, there would be no compile-time warning that there might be a problem here, so I might release the library as-is.
So is this a real scenario and problem?
When both your LogToFile and Log methods are part of your library, it is possible that your Log method will not compile, once you turn on the static checker. This of course will also happen when you supply code to others that compile your code using the static checker. However, as far as I know, your client's static checker will not validate the internals of the assembly you ship. It will statically check their own code against the public API of your assembly. So as long as you just ship the DLL, you'd be okay.
Of course there is a change of shipping a library that has a very annoying API for users that actually have the static checker enabled, so I think it is advisable to only ship your library with the contract definitions, if you tested the usability of the API both with and without the static checker.
Please be warned about changing the existing if (cond) throw ex calls to Contracts.Requires(cond) calls for public API calls that you have already shipped in a previous release. Note that the Requires method throws a different exception (a RequiresViolationException if I recall correctly) than what you'd normally throw (a ArgumentException). In that situation, use the Contract.Requires overload. This way your API interface stays unchanged.
First, the static checker is really (as I understand it) only available in the ultimate/academic editions - so unless everyone in your organization uses it they may not be warned if they are potentially violating an invariant.
Second, while the static analysis is impressive it cannot always find all paths that may lead to violation of the invariant. However, the good news here is that the Requires contract is retained at runtime - it is processed in an IL-transformation step - so the check exists at both compile time and runtime. In this way it is equivalent (but superior) to a regular if() check.
You can read more about the runtime rewriting that code contract compilation performs here, you can also read the detailed manual here.
EDIT: Based on what I can glean from the manual, I suspect the situation you describe is indeed possible. However, I thought that these would be warninings rather than compilation errors - and you can suppress them using System.Diagnostics.CodeAnalysis.SuppressMessage(). Consumers of your code who have the static verifier can also mark specific cases to be ignored - but that could certainly be inconvenient if there are a lot of them. I will try to find some time later today to put together a definitive test of your scenario (I don't have access to the static verifier at the moment).
There's an excellent blog here that is almost exclusively dedicated to code contracts which (if you haven't yet seen) may have some content that interests you.
No; the static analyzer will never prevent compilation from succeeding (unless it crashes!).
The static analyzer will warn you about unproven pre-/post-conditions, but doesn't stop compilation.

Resources