类型相等性
Nim对大多数类型使用结构类型等价。 仅对于对象,枚举和不同类型使用名称等价。 伪代码中 的以下算法确定类型相等:
- proc typeEqualsAux(a, b: PType,
- s: var HashSet[(PType, PType)]): bool =
- if (a,b) in s: return true
- incl(s, (a,b))
- if a.kind == b.kind:
- case a.kind
- of int, intXX, float, floatXX, char, string, cstring, pointer,
- bool, nil, void:
- # 叶类型: 类型等价; 不做更多检查
- result = true
- of ref, ptr, var, set, seq, openarray:
- result = typeEqualsAux(a.baseType, b.baseType, s)
- of range:
- result = typeEqualsAux(a.baseType, b.baseType, s) and
- (a.rangeA == b.rangeA) and (a.rangeB == b.rangeB)
- of array:
- result = typeEqualsAux(a.baseType, b.baseType, s) and
- typeEqualsAux(a.indexType, b.indexType, s)
- of tuple:
- if a.tupleLen == b.tupleLen:
- for i in 0..a.tupleLen-1:
- if not typeEqualsAux(a[i], b[i], s): return false
- result = true
- of object, enum, distinct:
- result = a == b
- of proc:
- result = typeEqualsAux(a.parameterTuple, b.parameterTuple, s) and
- typeEqualsAux(a.resultType, b.resultType, s) and
- a.callingConvention == b.callingConvention
- proc typeEquals(a, b: PType): bool =
- var s: HashSet[(PType, PType)] = {}
- result = typeEqualsAux(a, b, s)
由于类型可以是有环图,因此上述算法需要辅助集合 s 来检测这种情况