Compiler generated by GetHashCode ()

I am working on writing a compiler for a .net language, and one of the things I would like to do is automatically generate the GetHashCode method, but I have a few questions:

  • Is it possible that the compiler knows enough about the type (s) to do the reasonable work of implementing the method?
  • Should I do this for value types, reference types, or both?
  • What is a reasonable GetHashCode algorithm for a compiler for generation that includes support for null properties, etc.?
  • Was this done in another language / compiler that I can look at?
  • If this is not possible or is it really a bad idea, why?

thanks

+3
source share
1 answer

See what the C # compiler does for anonymous types. Basically this is the same hash like me:

public override int GetHashCode() { int hash = 17; hash = 31 * hash + field1.GetHashCode(); hash = 31 * hash + field2.GetHashCode(); // etc return hash; } 

(Of course, you need an incorrect check).

I think it's a good idea to do this (and override equality) for immutable types, but usually not for mutable types. In any case, value types should always be immutable - reference types can go anyway. Does your language have any built-in concept of immutability? Of course, this will go wrong if your type is "shallow immutable", but contains mutable types that override GetHashCode to indicate the current state of the object. In any case, these types will be painful.

In general, I believe that in many cases it is reasonable to auto-generate equalities and hash codes - indeed, I would like this to be part of C # 5 for named types too: I want an easy way to name types that would otherwise have those same functions as anonymous types.

+2
source

Source: https://habr.com/ru/post/896208/


All Articles