类型相等性

Nim对大多数类型使用结构类型等价。 仅对于对象,枚举和不同类型使用名称等价。 伪代码中 的以下算法确定类型相等:

  1. proc typeEqualsAux(a, b: PType,
  2. s: var HashSet[(PType, PType)]): bool =
  3. if (a,b) in s: return true
  4. incl(s, (a,b))
  5. if a.kind == b.kind:
  6. case a.kind
  7. of int, intXX, float, floatXX, char, string, cstring, pointer,
  8. bool, nil, void:
  9. # 叶类型: 类型等价; 不做更多检查
  10. result = true
  11. of ref, ptr, var, set, seq, openarray:
  12. result = typeEqualsAux(a.baseType, b.baseType, s)
  13. of range:
  14. result = typeEqualsAux(a.baseType, b.baseType, s) and
  15. (a.rangeA == b.rangeA) and (a.rangeB == b.rangeB)
  16. of array:
  17. result = typeEqualsAux(a.baseType, b.baseType, s) and
  18. typeEqualsAux(a.indexType, b.indexType, s)
  19. of tuple:
  20. if a.tupleLen == b.tupleLen:
  21. for i in 0..a.tupleLen-1:
  22. if not typeEqualsAux(a[i], b[i], s): return false
  23. result = true
  24. of object, enum, distinct:
  25. result = a == b
  26. of proc:
  27. result = typeEqualsAux(a.parameterTuple, b.parameterTuple, s) and
  28. typeEqualsAux(a.resultType, b.resultType, s) and
  29. a.callingConvention == b.callingConvention
  30.  
  31. proc typeEquals(a, b: PType): bool =
  32. var s: HashSet[(PType, PType)] = {}
  33. result = typeEqualsAux(a, b, s)

由于类型可以是有环图,因此上述算法需要辅助集合 s 来检测这种情况