sigmatch.nim 91 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604
  1. #
  2. #
  3. # The Nim Compiler
  4. # (c) Copyright 2013 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## This module implements the signature matching for resolving
  10. ## the call to overloaded procs, generic procs and operators.
  11. import
  12. intsets, ast, astalgo, semdata, types, msgs, renderer, lookups, semtypinst,
  13. magicsys, condsyms, idents, lexer, options, parampatterns, strutils, trees,
  14. linter, lineinfos
  15. when defined(booting) or defined(nimsuggest):
  16. import docgen
  17. type
  18. TCandidateState* = enum
  19. csEmpty, csMatch, csNoMatch
  20. CandidateError* = object
  21. sym*: PSym
  22. unmatchedVarParam*, firstMismatch*: int
  23. diagnostics*: seq[string]
  24. enabled*: bool
  25. CandidateErrors* = seq[CandidateError]
  26. TCandidate* = object
  27. c*: PContext
  28. exactMatches*: int # also misused to prefer iters over procs
  29. genericMatches: int # also misused to prefer constraints
  30. subtypeMatches: int
  31. intConvMatches: int # conversions to int are not as expensive
  32. convMatches: int
  33. state*: TCandidateState
  34. callee*: PType # may not be nil!
  35. calleeSym*: PSym # may be nil
  36. calleeScope*: int # scope depth:
  37. # is this a top-level symbol or a nested proc?
  38. call*: PNode # modified call
  39. bindings*: TIdTable # maps types to types
  40. magic*: TMagic # magic of operation
  41. baseTypeMatch: bool # needed for conversions from T to openarray[T]
  42. # for example
  43. fauxMatch*: TTypeKind # the match was successful only due to the use
  44. # of error or wildcard (unknown) types.
  45. # this is used to prevent instantiations.
  46. genericConverter*: bool # true if a generic converter needs to
  47. # be instantiated
  48. coerceDistincts*: bool # this is an explicit coercion that can strip away
  49. # a distrinct type
  50. typedescMatched*: bool
  51. isNoCall*: bool # misused for generic type instantiations C[T]
  52. mutabilityProblem*: uint8 # tyVar mismatch
  53. inferredTypes: seq[PType] # inferred types during the current signature
  54. # matching. they will be reset if the matching
  55. # is not successful. may replace the bindings
  56. # table in the future.
  57. diagnostics*: seq[string] # \
  58. # when diagnosticsEnabled, the matching process
  59. # will collect extra diagnostics that will be
  60. # displayed to the user.
  61. # triggered when overload resolution fails
  62. # or when the explain pragma is used. may be
  63. # triggered with an idetools command in the
  64. # future.
  65. inheritancePenalty: int # to prefer closest father object type
  66. firstMismatch*: int # position of the first type mismatch for
  67. # better error messages
  68. diagnosticsEnabled*: bool
  69. TTypeRelFlag* = enum
  70. trDontBind
  71. trNoCovariance
  72. TTypeRelFlags* = set[TTypeRelFlag]
  73. TTypeRelation* = enum # order is important!
  74. isNone, isConvertible,
  75. isIntConv,
  76. isSubtype,
  77. isSubrange, # subrange of the wanted type; no type conversion
  78. # but apart from that counts as ``isSubtype``
  79. isBothMetaConvertible # generic proc parameter was matched against
  80. # generic type, e.g., map(mySeq, x=>x+1),
  81. # maybe recoverable by rerun if the parameter is
  82. # the proc's return value
  83. isInferred, # generic proc was matched against a concrete type
  84. isInferredConvertible, # same as above, but requiring proc CC conversion
  85. isGeneric,
  86. isFromIntLit, # conversion *from* int literal; proven safe
  87. isEqual
  88. const
  89. isNilConversion = isConvertible # maybe 'isIntConv' fits better?
  90. proc markUsed*(conf: ConfigRef; info: TLineInfo, s: PSym; usageSym: var PSym)
  91. template hasFauxMatch*(c: TCandidate): bool = c.fauxMatch != tyNone
  92. proc initCandidateAux(ctx: PContext,
  93. c: var TCandidate, callee: PType) {.inline.} =
  94. c.c = ctx
  95. c.exactMatches = 0
  96. c.subtypeMatches = 0
  97. c.convMatches = 0
  98. c.intConvMatches = 0
  99. c.genericMatches = 0
  100. c.state = csEmpty
  101. c.callee = callee
  102. c.call = nil
  103. c.baseTypeMatch = false
  104. c.genericConverter = false
  105. c.inheritancePenalty = 0
  106. proc initCandidate*(ctx: PContext, c: var TCandidate, callee: PType) =
  107. initCandidateAux(ctx, c, callee)
  108. c.calleeSym = nil
  109. initIdTable(c.bindings)
  110. proc put(c: var TCandidate, key, val: PType) {.inline.} =
  111. idTablePut(c.bindings, key, val.skipIntLit)
  112. proc initCandidate*(ctx: PContext, c: var TCandidate, callee: PSym,
  113. binding: PNode, calleeScope = -1,
  114. diagnosticsEnabled = false) =
  115. initCandidateAux(ctx, c, callee.typ)
  116. c.calleeSym = callee
  117. if callee.kind in skProcKinds and calleeScope == -1:
  118. if callee.originatingModule == ctx.module:
  119. c.calleeScope = 2
  120. var owner = callee
  121. while true:
  122. owner = owner.skipGenericOwner
  123. if owner.kind == skModule: break
  124. inc c.calleeScope
  125. else:
  126. c.calleeScope = 1
  127. else:
  128. c.calleeScope = calleeScope
  129. c.diagnostics = @[] # if diagnosticsEnabled: @[] else: nil
  130. c.diagnosticsEnabled = diagnosticsEnabled
  131. c.magic = c.calleeSym.magic
  132. initIdTable(c.bindings)
  133. if binding != nil and callee.kind in routineKinds:
  134. var typeParams = callee.ast[genericParamsPos]
  135. for i in 1..min(sonsLen(typeParams), sonsLen(binding)-1):
  136. var formalTypeParam = typeParams.sons[i-1].typ
  137. var bound = binding[i].typ
  138. if bound != nil:
  139. if formalTypeParam.kind == tyTypeDesc:
  140. if bound.kind != tyTypeDesc:
  141. bound = makeTypeDesc(ctx, bound)
  142. else:
  143. bound = bound.skipTypes({tyTypeDesc})
  144. put(c, formalTypeParam, bound)
  145. proc newCandidate*(ctx: PContext, callee: PSym,
  146. binding: PNode, calleeScope = -1): TCandidate =
  147. initCandidate(ctx, result, callee, binding, calleeScope)
  148. proc newCandidate*(ctx: PContext, callee: PType): TCandidate =
  149. initCandidate(ctx, result, callee)
  150. proc copyCandidate(a: var TCandidate, b: TCandidate) =
  151. a.c = b.c
  152. a.exactMatches = b.exactMatches
  153. a.subtypeMatches = b.subtypeMatches
  154. a.convMatches = b.convMatches
  155. a.intConvMatches = b.intConvMatches
  156. a.genericMatches = b.genericMatches
  157. a.state = b.state
  158. a.callee = b.callee
  159. a.calleeSym = b.calleeSym
  160. a.call = copyTree(b.call)
  161. a.baseTypeMatch = b.baseTypeMatch
  162. copyIdTable(a.bindings, b.bindings)
  163. proc sumGeneric(t: PType): int =
  164. var t = t
  165. var isvar = 1
  166. while true:
  167. case t.kind
  168. of tyGenericInst, tyArray, tyRef, tyPtr, tyDistinct,
  169. tyOpenArray, tyVarargs, tySet, tyRange, tySequence, tyGenericBody,
  170. tyLent:
  171. t = t.lastSon
  172. inc result
  173. of tyOr:
  174. var maxBranch = 0
  175. for branch in t.sons:
  176. let branchSum = branch.sumGeneric
  177. if branchSum > maxBranch: maxBranch = branchSum
  178. inc result, maxBranch + 1
  179. break
  180. of tyVar:
  181. t = t.sons[0]
  182. inc result
  183. inc isvar
  184. of tyTypeDesc:
  185. t = t.lastSon
  186. if t.kind == tyEmpty: break
  187. inc result
  188. of tyGenericInvocation, tyTuple, tyProc, tyAnd:
  189. result += ord(t.kind in {tyGenericInvocation, tyAnd})
  190. for i in 0 ..< t.len:
  191. if t.sons[i] != nil:
  192. result += t.sons[i].sumGeneric
  193. break
  194. of tyStatic:
  195. return t.sons[0].sumGeneric + 1
  196. of tyGenericParam, tyExpr, tyStmt: break
  197. of tyAlias, tySink: t = t.lastSon
  198. of tyBool, tyChar, tyEnum, tyObject, tyPointer,
  199. tyString, tyCString, tyInt..tyInt64, tyFloat..tyFloat128,
  200. tyUInt..tyUInt64, tyCompositeTypeClass:
  201. return isvar
  202. else:
  203. return 0
  204. #var ggDebug: bool
  205. proc complexDisambiguation(a, b: PType): int =
  206. # 'a' matches better if *every* argument matches better or equal than 'b'.
  207. var winner = 0
  208. for i in 1 ..< min(a.len, b.len):
  209. let x = a.sons[i].sumGeneric
  210. let y = b.sons[i].sumGeneric
  211. #if ggDebug:
  212. #echo "came herA ", typeToString(a.sons[i]), " ", x
  213. #echo "came herB ", typeToString(b.sons[i]), " ", y
  214. if x != y:
  215. if winner == 0:
  216. if x > y: winner = 1
  217. else: winner = -1
  218. elif x > y:
  219. if winner != 1:
  220. # contradiction
  221. return 0
  222. else:
  223. if winner != -1:
  224. return 0
  225. result = winner
  226. when false:
  227. var x, y: int
  228. for i in 1 ..< a.len: x += a.sons[i].sumGeneric
  229. for i in 1 ..< b.len: y += b.sons[i].sumGeneric
  230. result = x - y
  231. proc writeMatches*(c: TCandidate) =
  232. echo "Candidate '", c.calleeSym.name.s, "' at ", c.c.config $ c.calleeSym.info
  233. echo " exact matches: ", c.exactMatches
  234. echo " generic matches: ", c.genericMatches
  235. echo " subtype matches: ", c.subtypeMatches
  236. echo " intconv matches: ", c.intConvMatches
  237. echo " conv matches: ", c.convMatches
  238. echo " inheritance: ", c.inheritancePenalty
  239. proc cmpCandidates*(a, b: TCandidate): int =
  240. result = a.exactMatches - b.exactMatches
  241. if result != 0: return
  242. result = a.genericMatches - b.genericMatches
  243. if result != 0: return
  244. result = a.subtypeMatches - b.subtypeMatches
  245. if result != 0: return
  246. result = a.intConvMatches - b.intConvMatches
  247. if result != 0: return
  248. result = a.convMatches - b.convMatches
  249. if result != 0: return
  250. # the other way round because of other semantics:
  251. result = b.inheritancePenalty - a.inheritancePenalty
  252. if result != 0: return
  253. # prefer more specialized generic over more general generic:
  254. result = complexDisambiguation(a.callee, b.callee)
  255. # only as a last resort, consider scoping:
  256. if result != 0: return
  257. result = a.calleeScope - b.calleeScope
  258. proc argTypeToString(arg: PNode; prefer: TPreferedDesc): string =
  259. if arg.kind in nkSymChoices:
  260. result = typeToString(arg[0].typ, prefer)
  261. for i in 1 ..< arg.len:
  262. result.add(" | ")
  263. result.add typeToString(arg[i].typ, prefer)
  264. elif arg.typ == nil:
  265. result = "void"
  266. else:
  267. result = arg.typ.typeToString(prefer)
  268. proc describeArgs*(c: PContext, n: PNode, startIdx = 1;
  269. prefer: TPreferedDesc = preferName): string =
  270. result = ""
  271. for i in countup(startIdx, n.len - 1):
  272. var arg = n.sons[i]
  273. if n.sons[i].kind == nkExprEqExpr:
  274. add(result, renderTree(n.sons[i].sons[0]))
  275. add(result, ": ")
  276. if arg.typ.isNil and arg.kind notin {nkStmtList, nkDo}:
  277. # XXX we really need to 'tryExpr' here!
  278. arg = c.semOperand(c, n.sons[i].sons[1])
  279. n.sons[i].typ = arg.typ
  280. n.sons[i].sons[1] = arg
  281. else:
  282. if arg.typ.isNil and arg.kind notin {nkStmtList, nkDo, nkElse,
  283. nkOfBranch, nkElifBranch,
  284. nkExceptBranch}:
  285. arg = c.semOperand(c, n.sons[i])
  286. n.sons[i] = arg
  287. if arg.typ != nil and arg.typ.kind == tyError: return
  288. add(result, argTypeToString(arg, prefer))
  289. if i != sonsLen(n) - 1: add(result, ", ")
  290. proc typeRelImpl*(c: var TCandidate, f, aOrig: PType,
  291. flags: TTypeRelFlags = {}): TTypeRelation
  292. const traceTypeRel = false
  293. when traceTypeRel:
  294. var nextTypeRel = 0
  295. template typeRel*(c: var TCandidate, f, aOrig: PType,
  296. flags: TTypeRelFlags = {}): TTypeRelation =
  297. when traceTypeRel:
  298. var enteringAt = nextTypeRel
  299. if mdbg:
  300. inc nextTypeRel
  301. echo "----- TYPE REL ", enteringAt
  302. debug f
  303. debug aOrig
  304. # writeStackTrace()
  305. let r = typeRelImpl(c, f, aOrig, flags)
  306. when traceTypeRel:
  307. if enteringAt != nextTypeRel:
  308. echo "----- TYPE REL ", enteringAt, " RESULT: ", r
  309. r
  310. proc concreteType(c: TCandidate, t: PType): PType =
  311. case t.kind
  312. of tyNil:
  313. result = nil # what should it be?
  314. of tyTypeDesc:
  315. if c.isNoCall: result = t
  316. else: result = nil
  317. of tySequence, tySet:
  318. if t.sons[0].kind == tyEmpty: result = nil
  319. else: result = t
  320. of tyGenericParam, tyAnything:
  321. result = t
  322. while true:
  323. result = PType(idTableGet(c.bindings, t))
  324. if result == nil:
  325. break # it's ok, no match
  326. # example code that triggers it:
  327. # proc sort[T](cmp: proc(a, b: T): int = cmp)
  328. if result.kind != tyGenericParam: break
  329. of tyGenericInvocation:
  330. result = t
  331. doAssert(false, "cannot resolve type: " & typeToString(t))
  332. else:
  333. result = t # Note: empty is valid here
  334. proc handleRange(f, a: PType, min, max: TTypeKind): TTypeRelation =
  335. if a.kind == f.kind:
  336. result = isEqual
  337. else:
  338. let ab = skipTypes(a, {tyRange})
  339. let k = ab.kind
  340. if k == f.kind: result = isSubrange
  341. elif k == tyInt and f.kind in {tyRange, tyInt8..tyInt64,
  342. tyUInt..tyUInt64} and
  343. isIntLit(ab) and ab.n.intVal >= firstOrd(nil, f) and
  344. ab.n.intVal <= lastOrd(nil, f):
  345. # passing 'nil' to firstOrd/lastOrd here as type checking rules should
  346. # not depent on the target integer size configurations!
  347. # integer literal in the proper range; we want ``i16 + 4`` to stay an
  348. # ``int16`` operation so we declare the ``4`` pseudo-equal to int16
  349. result = isFromIntLit
  350. elif f.kind == tyInt and k in {tyInt8..tyInt32}:
  351. result = isIntConv
  352. elif k >= min and k <= max:
  353. result = isConvertible
  354. elif a.kind == tyRange and a.sons[0].kind in {tyInt..tyInt64,
  355. tyUInt8..tyUInt32} and
  356. a.n[0].intVal >= firstOrd(nil, f) and
  357. a.n[1].intVal <= lastOrd(nil, f):
  358. # passing 'nil' to firstOrd/lastOrd here as type checking rules should
  359. # not depent on the target integer size configurations!
  360. result = isConvertible
  361. else: result = isNone
  362. #elif f.kind == tyInt and k in {tyInt..tyInt32}: result = isIntConv
  363. #elif f.kind == tyUInt and k in {tyUInt..tyUInt32}: result = isIntConv
  364. proc isConvertibleToRange(f, a: PType): bool =
  365. # be less picky for tyRange, as that it is used for array indexing:
  366. if f.kind in {tyInt..tyInt64, tyUInt..tyUInt64} and
  367. a.kind in {tyInt..tyInt64, tyUInt..tyUInt64}:
  368. case f.kind
  369. of tyInt, tyInt64: result = true
  370. of tyInt8: result = a.kind in {tyInt8, tyInt}
  371. of tyInt16: result = a.kind in {tyInt8, tyInt16, tyInt}
  372. of tyInt32: result = a.kind in {tyInt8, tyInt16, tyInt32, tyInt}
  373. of tyUInt, tyUInt64: result = true
  374. of tyUInt8: result = a.kind in {tyUInt8, tyUInt}
  375. of tyUInt16: result = a.kind in {tyUInt8, tyUInt16, tyUInt}
  376. of tyUInt32: result = a.kind in {tyUInt8, tyUInt16, tyUInt32, tyUInt}
  377. else: result = false
  378. elif f.kind in {tyFloat..tyFloat128} and
  379. a.kind in {tyFloat..tyFloat128}:
  380. result = true
  381. proc handleFloatRange(f, a: PType): TTypeRelation =
  382. if a.kind == f.kind:
  383. result = isEqual
  384. else:
  385. let ab = skipTypes(a, {tyRange})
  386. var k = ab.kind
  387. if k == f.kind: result = isSubrange
  388. elif isFloatLit(ab): result = isFromIntLit
  389. elif isIntLit(ab): result = isConvertible
  390. elif k >= tyFloat and k <= tyFloat128:
  391. # conversion to "float32" is not as good:
  392. if f.kind == tyFloat32: result = isConvertible
  393. else: result = isIntConv
  394. else: result = isNone
  395. proc genericParamPut(c: var TCandidate; last, fGenericOrigin: PType) =
  396. if fGenericOrigin != nil and last.kind == tyGenericInst and
  397. last.len-1 == fGenericOrigin.len:
  398. for i in countup(1, sonsLen(fGenericOrigin) - 1):
  399. let x = PType(idTableGet(c.bindings, fGenericOrigin.sons[i]))
  400. if x == nil:
  401. put(c, fGenericOrigin.sons[i], last.sons[i])
  402. proc isObjectSubtype(c: var TCandidate; a, f, fGenericOrigin: PType): int =
  403. var t = a
  404. assert t.kind == tyObject
  405. var depth = 0
  406. var last = a
  407. while t != nil and not sameObjectTypes(f, t):
  408. assert t.kind == tyObject
  409. t = t.sons[0]
  410. if t == nil: break
  411. last = t
  412. t = skipTypes(t, skipPtrs)
  413. inc depth
  414. if t != nil:
  415. genericParamPut(c, last, fGenericOrigin)
  416. result = depth
  417. else:
  418. result = -1
  419. type
  420. SkippedPtr = enum skippedNone, skippedRef, skippedPtr
  421. proc skipToObject(t: PType; skipped: var SkippedPtr): PType =
  422. var r = t
  423. # we're allowed to skip one level of ptr/ref:
  424. var ptrs = 0
  425. while r != nil:
  426. case r.kind
  427. of tyGenericInvocation:
  428. r = r.sons[0]
  429. of tyRef:
  430. inc ptrs
  431. skipped = skippedRef
  432. r = r.lastSon
  433. of tyPtr:
  434. inc ptrs
  435. skipped = skippedPtr
  436. r = r.lastSon
  437. of tyGenericBody, tyGenericInst, tyAlias, tySink:
  438. r = r.lastSon
  439. else:
  440. break
  441. if r.kind == tyObject and ptrs <= 1: result = r
  442. proc isGenericSubtype(c: var TCandidate; a, f: PType, d: var int, fGenericOrigin: PType = nil): bool =
  443. assert f.kind in {tyGenericInst, tyGenericInvocation, tyGenericBody}
  444. var askip = skippedNone
  445. var fskip = skippedNone
  446. var t = a.skipToObject(askip)
  447. let r = f.skipToObject(fskip)
  448. if r == nil: return false
  449. var depth = 0
  450. var last = a
  451. # XXX sameObjectType can return false here. Need to investigate
  452. # why that is but sameObjectType does way too much work here anyway.
  453. while t != nil and r.sym != t.sym and askip == fskip:
  454. t = t.sons[0]
  455. if t == nil: break
  456. last = t
  457. t = t.skipToObject(askip)
  458. inc depth
  459. if t != nil and askip == fskip:
  460. genericParamPut(c, last, fGenericOrigin)
  461. d = depth
  462. result = true
  463. proc minRel(a, b: TTypeRelation): TTypeRelation =
  464. if a <= b: result = a
  465. else: result = b
  466. proc recordRel(c: var TCandidate, f, a: PType): TTypeRelation =
  467. result = isNone
  468. if sameType(f, a):
  469. result = isEqual
  470. elif sonsLen(a) == sonsLen(f):
  471. result = isEqual
  472. let firstField = if f.kind == tyTuple: 0
  473. else: 1
  474. for i in countup(firstField, sonsLen(f) - 1):
  475. var m = typeRel(c, f.sons[i], a.sons[i])
  476. if m < isSubtype: return isNone
  477. result = minRel(result, m)
  478. if f.n != nil and a.n != nil:
  479. for i in countup(0, sonsLen(f.n) - 1):
  480. # check field names:
  481. if f.n.sons[i].kind != nkSym: return isNone
  482. elif a.n.sons[i].kind != nkSym: return isNone
  483. else:
  484. var x = f.n.sons[i].sym
  485. var y = a.n.sons[i].sym
  486. if f.kind == tyObject and typeRel(c, x.typ, y.typ) < isSubtype:
  487. return isNone
  488. if x.name.id != y.name.id: return isNone
  489. proc allowsNil(f: PType): TTypeRelation {.inline.} =
  490. result = if tfNotNil notin f.flags: isSubtype else: isNone
  491. proc allowsNilDeprecated(c: TCandidate, f: PType): TTypeRelation =
  492. if optNilSeqs in c.c.config.options:
  493. result = allowsNil(f)
  494. else:
  495. result = isNone
  496. proc inconsistentVarTypes(f, a: PType): bool {.inline.} =
  497. result = f.kind != a.kind and (f.kind in {tyVar, tyLent} or a.kind in {tyVar, tyLent})
  498. proc procParamTypeRel(c: var TCandidate, f, a: PType): TTypeRelation =
  499. ## For example we have:
  500. ## .. code-block:: nim
  501. ## proc myMap[T,S](sIn: seq[T], f: proc(x: T): S): seq[S] = ...
  502. ## proc innerProc[Q,W](q: Q): W = ...
  503. ## And we want to match: myMap(@[1,2,3], innerProc)
  504. ## This proc (procParamTypeRel) will do the following steps in
  505. ## three different calls:
  506. ## - matches f=T to a=Q. Since f is metatype, we resolve it
  507. ## to int (which is already known at this point). So in this case
  508. ## Q=int mapping will be saved to c.bindings.
  509. ## - matches f=S to a=W. Both of these metatypes are unknown, so we
  510. ## return with isBothMetaConvertible to ask for rerun.
  511. ## - matches f=S to a=W. At this point the return type of innerProc
  512. ## is known (we get it from c.bindings). We can use that value
  513. ## to match with f, and save back to c.bindings.
  514. var
  515. f = f
  516. a = a
  517. if a.isMetaType:
  518. let aResolved = PType(idTableGet(c.bindings, a))
  519. if aResolved != nil:
  520. a = aResolved
  521. if a.isMetaType:
  522. if f.isMetaType:
  523. # We are matching a generic proc (as proc param)
  524. # to another generic type appearing in the proc
  525. # signature. There is a change that the target
  526. # type is already fully-determined, so we are
  527. # going to try resolve it
  528. if c.call != nil:
  529. f = generateTypeInstance(c.c, c.bindings, c.call.info, f)
  530. else:
  531. f = nil
  532. if f == nil or f.isMetaType:
  533. # no luck resolving the type, so the inference fails
  534. return isBothMetaConvertible
  535. # Note that this typeRel call will save a's resolved type into c.bindings
  536. let reverseRel = typeRel(c, a, f)
  537. if reverseRel >= isGeneric:
  538. result = isInferred
  539. #inc c.genericMatches
  540. else:
  541. # Note that this typeRel call will save f's resolved type into c.bindings
  542. # if f is metatype.
  543. result = typeRel(c, f, a)
  544. if result <= isSubtype or inconsistentVarTypes(f, a):
  545. result = isNone
  546. #if result == isEqual:
  547. # inc c.exactMatches
  548. proc procTypeRel(c: var TCandidate, f, a: PType): TTypeRelation =
  549. case a.kind
  550. of tyProc:
  551. if sonsLen(f) != sonsLen(a): return
  552. result = isEqual # start with maximum; also correct for no
  553. # params at all
  554. template checkParam(f, a) =
  555. result = minRel(result, procParamTypeRel(c, f, a))
  556. if result == isNone: return
  557. # Note: We have to do unification for the parameters before the
  558. # return type!
  559. for i in 1 ..< f.sonsLen:
  560. checkParam(f.sons[i], a.sons[i])
  561. if f.sons[0] != nil:
  562. if a.sons[0] != nil:
  563. checkParam(f.sons[0], a.sons[0])
  564. else:
  565. return isNone
  566. elif a.sons[0] != nil:
  567. return isNone
  568. if tfNoSideEffect in f.flags and tfNoSideEffect notin a.flags:
  569. return isNone
  570. elif tfThread in f.flags and a.flags * {tfThread, tfNoSideEffect} == {} and
  571. optThreadAnalysis in c.c.config.globalOptions:
  572. # noSideEffect implies ``tfThread``!
  573. return isNone
  574. elif f.flags * {tfIterator} != a.flags * {tfIterator}:
  575. return isNone
  576. elif f.callConv != a.callConv:
  577. # valid to pass a 'nimcall' thingie to 'closure':
  578. if f.callConv == ccClosure and a.callConv == ccDefault:
  579. result = if result == isInferred: isInferredConvertible
  580. elif result == isBothMetaConvertible: isBothMetaConvertible
  581. else: isConvertible
  582. else:
  583. return isNone
  584. when useEffectSystem:
  585. if compatibleEffects(f, a) != efCompat: return isNone
  586. of tyNil:
  587. result = f.allowsNil
  588. else: discard
  589. proc typeRangeRel(f, a: PType): TTypeRelation {.noinline.} =
  590. template checkRange[T](a0, a1, f0, f1: T): TTypeRelation =
  591. if a0 == f0 and a1 == f1:
  592. isEqual
  593. elif a0 >= f0 and a1 <= f1:
  594. isConvertible
  595. elif a0 <= f1 and f0 <= a1:
  596. # X..Y and C..D overlap iff (X <= D and C <= Y)
  597. isConvertible
  598. else:
  599. isNone
  600. if f.isOrdinalType:
  601. checkRange(firstOrd(nil, a), lastOrd(nil, a), firstOrd(nil, f), lastOrd(nil, f))
  602. else:
  603. checkRange(firstFloat(a), lastFloat(a), firstFloat(f), lastFloat(f))
  604. proc matchUserTypeClass*(m: var TCandidate; ff, a: PType): PType =
  605. var
  606. c = m.c
  607. typeClass = ff.skipTypes({tyUserTypeClassInst})
  608. body = typeClass.n[3]
  609. matchedConceptContext: TMatchedConcept
  610. prevMatchedConcept = c.matchedConcept
  611. prevCandidateType = typeClass[0][0]
  612. if prevMatchedConcept != nil:
  613. matchedConceptContext.prev = prevMatchedConcept
  614. matchedConceptContext.depth = prevMatchedConcept.depth + 1
  615. if prevMatchedConcept.depth > 4:
  616. localError(m.c.graph.config, body.info, $body & " too nested for type matching")
  617. return nil
  618. openScope(c)
  619. matchedConceptContext.candidateType = a
  620. typeClass[0].sons[0] = a
  621. c.matchedConcept = addr(matchedConceptContext)
  622. defer:
  623. c.matchedConcept = prevMatchedConcept
  624. typeClass[0].sons[0] = prevCandidateType
  625. closeScope(c)
  626. var typeParams: seq[(PSym, PType)]
  627. if ff.kind == tyUserTypeClassInst:
  628. for i in 1 ..< (ff.len - 1):
  629. var
  630. typeParamName = ff.base.sons[i-1].sym.name
  631. typ = ff.sons[i]
  632. param: PSym
  633. alreadyBound = PType(idTableGet(m.bindings, typ))
  634. if alreadyBound != nil: typ = alreadyBound
  635. template paramSym(kind): untyped =
  636. newSym(kind, typeParamName, typeClass.sym, typeClass.sym.info, {})
  637. block addTypeParam:
  638. for prev in typeParams:
  639. if prev[1].id == typ.id:
  640. param = paramSym prev[0].kind
  641. param.typ = prev[0].typ
  642. break addTypeParam
  643. case typ.kind
  644. of tyStatic:
  645. param = paramSym skConst
  646. param.typ = typ.exactReplica
  647. if typ.n == nil:
  648. param.typ.flags.incl tfInferrableStatic
  649. else:
  650. param.ast = typ.n
  651. of tyUnknown:
  652. param = paramSym skVar
  653. param.typ = typ.exactReplica
  654. else:
  655. param = paramSym skType
  656. param.typ = if typ.isMetaType:
  657. c.newTypeWithSons(tyInferred, @[typ])
  658. else:
  659. makeTypeDesc(c, typ)
  660. typeParams.safeAdd((param, typ))
  661. addDecl(c, param)
  662. var
  663. oldWriteHook: type(m.c.config.writelnHook)
  664. diagnostics: seq[string]
  665. errorPrefix: string
  666. flags: TExprFlags = {}
  667. collectDiagnostics = m.diagnosticsEnabled or
  668. sfExplain in typeClass.sym.flags
  669. if collectDiagnostics:
  670. oldWriteHook = m.c.config.writelnHook
  671. # XXX: we can't write to m.diagnostics directly, because
  672. # Nim doesn't support capturing var params in closures
  673. diagnostics = @[]
  674. flags = {efExplain}
  675. m.c.config.writelnHook = proc (s: string) =
  676. if errorPrefix.len == 0: errorPrefix = typeClass.sym.name.s & ":"
  677. let msg = s.replace("Error:", errorPrefix)
  678. if oldWriteHook != nil: oldWriteHook msg
  679. diagnostics.add msg
  680. var checkedBody = c.semTryExpr(c, body.copyTree, flags)
  681. if collectDiagnostics:
  682. m.c.config.writelnHook = oldWriteHook
  683. for msg in diagnostics:
  684. m.diagnostics.safeAdd msg
  685. m.diagnosticsEnabled = true
  686. if checkedBody == nil: return nil
  687. # The inferrable type params have been identified during the semTryExpr above.
  688. # We need to put them in the current sigmatch's binding table in order for them
  689. # to be resolvable while matching the rest of the parameters
  690. for p in typeParams:
  691. put(m, p[1], p[0].typ)
  692. if ff.kind == tyUserTypeClassInst:
  693. result = generateTypeInstance(c, m.bindings, typeClass.sym.info, ff)
  694. else:
  695. result = copyType(ff, ff.owner, true)
  696. result.n = checkedBody
  697. proc shouldSkipDistinct(m: TCandidate; rules: PNode, callIdent: PIdent): bool =
  698. # XXX This is bad as 'considerQuotedIdent' can produce an error!
  699. if rules.kind == nkWith:
  700. for r in rules:
  701. if considerQuotedIdent(m.c, r) == callIdent: return true
  702. return false
  703. else:
  704. for r in rules:
  705. if considerQuotedIdent(m.c, r) == callIdent: return false
  706. return true
  707. proc maybeSkipDistinct(m: TCandidate; t: PType, callee: PSym): PType =
  708. if t != nil and t.kind == tyDistinct and t.n != nil and
  709. shouldSkipDistinct(m, t.n, callee.name):
  710. result = t.base
  711. else:
  712. result = t
  713. proc tryResolvingStaticExpr(c: var TCandidate, n: PNode,
  714. allowUnresolved = false): PNode =
  715. # Consider this example:
  716. # type Value[N: static[int]] = object
  717. # proc foo[N](a: Value[N], r: range[0..(N-1)])
  718. # Here, N-1 will be initially nkStaticExpr that can be evaluated only after
  719. # N is bound to a concrete value during the matching of the first param.
  720. # This proc is used to evaluate such static expressions.
  721. let instantiated = replaceTypesInBody(c.c, c.bindings, n, nil,
  722. allowMetaTypes = allowUnresolved)
  723. result = c.c.semExpr(c.c, instantiated)
  724. proc inferStaticParam*(c: var TCandidate, lhs: PNode, rhs: BiggestInt): bool =
  725. # This is a simple integer arithimetic equation solver,
  726. # capable of deriving the value of a static parameter in
  727. # expressions such as (N + 5) / 2 = rhs
  728. #
  729. # Preconditions:
  730. #
  731. # * The input of this proc must be semantized
  732. # - all templates should be expanded
  733. # - aby constant folding possible should already be performed
  734. #
  735. # * There must be exactly one unresolved static parameter
  736. #
  737. # Result:
  738. #
  739. # The proc will return true if the static types was successfully
  740. # inferred. The result will be bound to the original static type
  741. # in the TCandidate.
  742. #
  743. if lhs.kind in nkCallKinds and lhs[0].kind == nkSym:
  744. case lhs[0].sym.magic
  745. of mUnaryLt:
  746. return inferStaticParam(c, lhs[1], rhs + 1)
  747. of mAddI, mAddU, mInc, mSucc:
  748. if lhs[1].kind == nkIntLit:
  749. return inferStaticParam(c, lhs[2], rhs - lhs[1].intVal)
  750. elif lhs[2].kind == nkIntLit:
  751. return inferStaticParam(c, lhs[1], rhs - lhs[2].intVal)
  752. of mDec, mSubI, mSubU, mPred:
  753. if lhs[1].kind == nkIntLit:
  754. return inferStaticParam(c, lhs[2], lhs[1].intVal - rhs)
  755. elif lhs[2].kind == nkIntLit:
  756. return inferStaticParam(c, lhs[1], rhs + lhs[2].intVal)
  757. of mMulI, mMulU:
  758. if lhs[1].kind == nkIntLit:
  759. if rhs mod lhs[1].intVal == 0:
  760. return inferStaticParam(c, lhs[2], rhs div lhs[1].intVal)
  761. elif lhs[2].kind == nkIntLit:
  762. if rhs mod lhs[2].intVal == 0:
  763. return inferStaticParam(c, lhs[1], rhs div lhs[2].intVal)
  764. of mDivI, mDivU:
  765. if lhs[1].kind == nkIntLit:
  766. if lhs[1].intVal mod rhs == 0:
  767. return inferStaticParam(c, lhs[2], lhs[1].intVal div rhs)
  768. elif lhs[2].kind == nkIntLit:
  769. return inferStaticParam(c, lhs[1], lhs[2].intVal * rhs)
  770. of mShlI:
  771. if lhs[2].kind == nkIntLit:
  772. return inferStaticParam(c, lhs[1], rhs shr lhs[2].intVal)
  773. of mShrI:
  774. if lhs[2].kind == nkIntLit:
  775. return inferStaticParam(c, lhs[1], rhs shl lhs[2].intVal)
  776. of mAshrI:
  777. if lhs[2].kind == nkIntLit:
  778. return inferStaticParam(c, lhs[1], ashr(rhs, lhs[2].intVal))
  779. of mUnaryMinusI:
  780. return inferStaticParam(c, lhs[1], -rhs)
  781. of mUnaryPlusI, mToInt, mToBiggestInt:
  782. return inferStaticParam(c, lhs[1], rhs)
  783. else: discard
  784. elif lhs.kind == nkSym and lhs.typ.kind == tyStatic and lhs.typ.n == nil:
  785. var inferred = newTypeWithSons(c.c, tyStatic, lhs.typ.sons)
  786. inferred.n = newIntNode(nkIntLit, rhs)
  787. put(c, lhs.typ, inferred)
  788. if c.c.matchedConcept != nil:
  789. # inside concepts, binding is currently done with
  790. # direct mutation of the involved types:
  791. lhs.typ.n = inferred.n
  792. return true
  793. return false
  794. proc failureToInferStaticParam(conf: ConfigRef; n: PNode) =
  795. let staticParam = n.findUnresolvedStatic
  796. let name = if staticParam != nil: staticParam.sym.name.s
  797. else: "unknown"
  798. localError(conf, n.info, "cannot infer the value of the static param '" & name & "'")
  799. proc inferStaticsInRange(c: var TCandidate,
  800. inferred, concrete: PType): TTypeRelation =
  801. let lowerBound = tryResolvingStaticExpr(c, inferred.n[0],
  802. allowUnresolved = true)
  803. let upperBound = tryResolvingStaticExpr(c, inferred.n[1],
  804. allowUnresolved = true)
  805. template doInferStatic(e: PNode, r: BiggestInt) =
  806. var exp = e
  807. var rhs = r
  808. if inferStaticParam(c, exp, rhs):
  809. return isGeneric
  810. else:
  811. failureToInferStaticParam(c.c.config, exp)
  812. if lowerBound.kind == nkIntLit:
  813. if upperBound.kind == nkIntLit:
  814. if lengthOrd(c.c.config, concrete) == upperBound.intVal - lowerBound.intVal + 1:
  815. return isGeneric
  816. else:
  817. return isNone
  818. doInferStatic(upperBound, lengthOrd(c.c.config, concrete) + lowerBound.intVal - 1)
  819. elif upperBound.kind == nkIntLit:
  820. doInferStatic(lowerBound, upperBound.intVal + 1 - lengthOrd(c.c.config, concrete))
  821. template subtypeCheck() =
  822. if result <= isSubrange and f.lastSon.skipTypes(abstractInst).kind in {tyRef, tyPtr, tyVar, tyLent}:
  823. result = isNone
  824. proc isCovariantPtr(c: var TCandidate, f, a: PType): bool =
  825. # this proc is always called for a pair of matching types
  826. assert f.kind == a.kind
  827. template baseTypesCheck(lhs, rhs: PType): bool =
  828. lhs.kind notin {tyPtr, tyRef, tyVar, tyLent} and
  829. typeRel(c, lhs, rhs, {trNoCovariance}) == isSubtype
  830. case f.kind
  831. of tyRef, tyPtr:
  832. return baseTypesCheck(f.base, a.base)
  833. of tyGenericInst:
  834. let body = f.base
  835. return body == a.base and
  836. a.sonsLen == 3 and
  837. tfWeakCovariant notin body.sons[0].flags and
  838. baseTypesCheck(f.sons[1], a.sons[1])
  839. else:
  840. return false
  841. when false:
  842. proc maxNumericType(prev, candidate: PType): PType =
  843. let c = candidate.skipTypes({tyRange})
  844. template greater(s) =
  845. if c.kind in s: result = c
  846. case prev.kind
  847. of tyInt: greater({tyInt64})
  848. of tyInt8: greater({tyInt, tyInt16, tyInt32, tyInt64})
  849. of tyInt16: greater({tyInt, tyInt32, tyInt64})
  850. of tyInt32: greater({tyInt64})
  851. of tyUInt: greater({tyUInt64})
  852. of tyUInt8: greater({tyUInt, tyUInt16, tyUInt32, tyUInt64})
  853. of tyUInt16: greater({tyUInt, tyUInt32, tyUInt64})
  854. of tyUInt32: greater({tyUInt64})
  855. of tyFloat32: greater({tyFloat64, tyFloat128})
  856. of tyFloat64: greater({tyFloat128})
  857. else: discard
  858. proc typeRelImpl(c: var TCandidate, f, aOrig: PType,
  859. flags: TTypeRelFlags = {}): TTypeRelation =
  860. # typeRel can be used to establish various relationships between types:
  861. #
  862. # 1) When used with concrete types, it will check for type equivalence
  863. # or a subtype relationship.
  864. #
  865. # 2) When used with a concrete type against a type class (such as generic
  866. # signature of a proc), it will check whether the concrete type is a member
  867. # of the designated type class.
  868. #
  869. # 3) When used with two type classes, it will check whether the types
  870. # matching the first type class are a strict subset of the types matching
  871. # the other. This allows us to compare the signatures of generic procs in
  872. # order to give preferrence to the most specific one:
  873. #
  874. # seq[seq[any]] is a strict subset of seq[any] and hence more specific.
  875. result = isNone
  876. assert(f != nil)
  877. if f.kind == tyExpr:
  878. if aOrig != nil: put(c, f, aOrig)
  879. return isGeneric
  880. assert(aOrig != nil)
  881. var
  882. useTypeLoweringRuleInTypeClass = c.c.matchedConcept != nil and
  883. not c.isNoCall and
  884. f.kind != tyTypeDesc and
  885. tfExplicit notin aOrig.flags and
  886. tfConceptMatchedTypeSym notin aOrig.flags
  887. aOrig = if useTypeLoweringRuleInTypeClass:
  888. aOrig.skipTypes({tyTypeDesc})
  889. else:
  890. aOrig
  891. if aOrig.kind == tyInferred:
  892. let prev = aOrig.previouslyInferred
  893. if prev != nil:
  894. return typeRel(c, f, prev)
  895. else:
  896. var candidate = f
  897. case f.kind
  898. of tyGenericParam:
  899. var prev = PType(idTableGet(c.bindings, f))
  900. if prev != nil: candidate = prev
  901. of tyFromExpr:
  902. let computedType = tryResolvingStaticExpr(c, f.n).typ
  903. case computedType.kind
  904. of tyTypeDesc:
  905. candidate = computedType.base
  906. of tyStatic:
  907. candidate = computedType
  908. else:
  909. # XXX What is this non-sense? Error reporting in signature matching?
  910. discard "localError(f.n.info, errTypeExpected)"
  911. else:
  912. discard
  913. result = typeRel(c, aOrig.base, candidate)
  914. if result != isNone:
  915. c.inferredTypes.safeAdd aOrig
  916. aOrig.sons.add candidate
  917. result = isEqual
  918. return
  919. template doBind: bool = trDontBind notin flags
  920. # var and static arguments match regular modifier-free types
  921. var a = maybeSkipDistinct(c, aOrig.skipTypes({tyStatic, tyVar, tyLent}), c.calleeSym)
  922. # XXX: Theoretically, maybeSkipDistinct could be called before we even
  923. # start the param matching process. This could be done in `prepareOperand`
  924. # for example, but unfortunately `prepareOperand` is not called in certain
  925. # situation when nkDotExpr are rotated to nkDotCalls
  926. if aOrig.kind in {tyAlias, tySink}:
  927. return typeRel(c, f, lastSon(aOrig))
  928. if a.kind == tyGenericInst and
  929. skipTypes(f, {tyVar, tyLent}).kind notin {
  930. tyGenericBody, tyGenericInvocation,
  931. tyGenericInst, tyGenericParam} + tyTypeClasses:
  932. return typeRel(c, f, lastSon(a))
  933. if a.isResolvedUserTypeClass:
  934. return typeRel(c, f, a.lastSon)
  935. template bindingRet(res) =
  936. if doBind:
  937. let bound = aOrig.skipTypes({tyRange}).skipIntLit
  938. put(c, f, bound)
  939. return res
  940. template considerPreviousT(body: untyped) =
  941. var prev = PType(idTableGet(c.bindings, f))
  942. if prev == nil: body
  943. else: return typeRel(c, prev, a)
  944. case a.kind
  945. of tyOr:
  946. # XXX: deal with the current dual meaning of tyGenericParam
  947. c.typedescMatched = true
  948. # seq[int|string] vs seq[number]
  949. # both int and string must match against number
  950. # but ensure that '[T: A|A]' matches as good as '[T: A]' (bug #2219):
  951. result = isGeneric
  952. for branch in a.sons:
  953. let x = typeRel(c, f, branch, flags + {trDontBind})
  954. if x == isNone: return isNone
  955. if x < result: result = x
  956. return
  957. of tyAnd:
  958. # XXX: deal with the current dual meaning of tyGenericParam
  959. c.typedescMatched = true
  960. # seq[Sortable and Iterable] vs seq[Sortable]
  961. # only one match is enough
  962. for branch in a.sons:
  963. let x = typeRel(c, f, branch, flags + {trDontBind})
  964. if x != isNone:
  965. return if x >= isGeneric: isGeneric else: x
  966. return isNone
  967. of tyNot:
  968. case f.kind
  969. of tyNot:
  970. # seq[!int] vs seq[!number]
  971. # seq[float] matches the first, but not the second
  972. # we must turn the problem around:
  973. # is number a subset of int?
  974. return typeRel(c, a.lastSon, f.lastSon)
  975. else:
  976. # negative type classes are essentially infinite,
  977. # so only the `any` type class is their superset
  978. return if f.kind == tyAnything: isGeneric
  979. else: isNone
  980. of tyAnything:
  981. if f.kind == tyAnything: return isGeneric
  982. else: return isNone
  983. of tyUserTypeClass, tyUserTypeClassInst:
  984. if c.c.matchedConcept != nil and c.c.matchedConcept.depth <= 4:
  985. # consider this: 'var g: Node' *within* a concept where 'Node'
  986. # is a concept too (tgraph)
  987. inc c.c.matchedConcept.depth
  988. let x = typeRel(c, a, f, flags + {trDontBind})
  989. if x >= isGeneric:
  990. return isGeneric
  991. else: discard
  992. case f.kind
  993. of tyEnum:
  994. if a.kind == f.kind and sameEnumTypes(f, a): result = isEqual
  995. elif sameEnumTypes(f, skipTypes(a, {tyRange})): result = isSubtype
  996. of tyBool, tyChar:
  997. if a.kind == f.kind: result = isEqual
  998. elif skipTypes(a, {tyRange}).kind == f.kind: result = isSubtype
  999. of tyRange:
  1000. if a.kind == f.kind:
  1001. if f.base.kind == tyNone: return isGeneric
  1002. result = typeRel(c, base(f), base(a))
  1003. # bugfix: accept integer conversions here
  1004. #if result < isGeneric: result = isNone
  1005. if result notin {isNone, isGeneric}:
  1006. # resolve any late-bound static expressions
  1007. # that may appear in the range:
  1008. for i in 0..1:
  1009. if f.n[i].kind == nkStaticExpr:
  1010. f.n.sons[i] = tryResolvingStaticExpr(c, f.n[i])
  1011. result = typeRangeRel(f, a)
  1012. else:
  1013. if skipTypes(f, {tyRange}).kind == a.kind:
  1014. result = isIntConv
  1015. elif isConvertibleToRange(skipTypes(f, {tyRange}), a):
  1016. result = isConvertible # a convertible to f
  1017. of tyInt: result = handleRange(f, a, tyInt8, tyInt32)
  1018. of tyInt8: result = handleRange(f, a, tyInt8, tyInt8)
  1019. of tyInt16: result = handleRange(f, a, tyInt8, tyInt16)
  1020. of tyInt32: result = handleRange(f, a, tyInt8, tyInt32)
  1021. of tyInt64: result = handleRange(f, a, tyInt, tyInt64)
  1022. of tyUInt: result = handleRange(f, a, tyUInt8, tyUInt32)
  1023. of tyUInt8: result = handleRange(f, a, tyUInt8, tyUInt8)
  1024. of tyUInt16: result = handleRange(f, a, tyUInt8, tyUInt16)
  1025. of tyUInt32: result = handleRange(f, a, tyUInt8, tyUInt32)
  1026. of tyUInt64: result = handleRange(f, a, tyUInt, tyUInt64)
  1027. of tyFloat: result = handleFloatRange(f, a)
  1028. of tyFloat32: result = handleFloatRange(f, a)
  1029. of tyFloat64: result = handleFloatRange(f, a)
  1030. of tyFloat128: result = handleFloatRange(f, a)
  1031. of tyVar, tyLent:
  1032. if aOrig.kind == f.kind: result = typeRel(c, f.base, aOrig.base)
  1033. else: result = typeRel(c, f.base, aOrig, flags + {trNoCovariance})
  1034. subtypeCheck()
  1035. of tyArray:
  1036. case a.kind
  1037. of tyArray:
  1038. var fRange = f.sons[0]
  1039. var aRange = a.sons[0]
  1040. if fRange.kind == tyGenericParam:
  1041. var prev = PType(idTableGet(c.bindings, fRange))
  1042. if prev == nil:
  1043. put(c, fRange, a.sons[0])
  1044. fRange = a
  1045. else:
  1046. fRange = prev
  1047. let ff = f.sons[1].skipTypes({tyTypeDesc})
  1048. # This typeDesc rule is wrong, see bug #7331
  1049. let aa = a.sons[1] #.skipTypes({tyTypeDesc})
  1050. if f.sons[0].kind != tyGenericParam and aa.kind == tyEmpty:
  1051. result = isGeneric
  1052. else:
  1053. result = typeRel(c, ff, aa)
  1054. if result < isGeneric:
  1055. if nimEnableCovariance and
  1056. trNoCovariance notin flags and
  1057. ff.kind == aa.kind and
  1058. isCovariantPtr(c, ff, aa):
  1059. result = isSubtype
  1060. else:
  1061. return isNone
  1062. if fRange.rangeHasUnresolvedStatic:
  1063. return inferStaticsInRange(c, fRange, a)
  1064. elif c.c.matchedConcept != nil and aRange.rangeHasUnresolvedStatic:
  1065. return inferStaticsInRange(c, aRange, f)
  1066. else:
  1067. if lengthOrd(c.c.config, fRange) != lengthOrd(c.c.config, aRange):
  1068. result = isNone
  1069. else: discard
  1070. of tyOpenArray, tyVarargs:
  1071. # varargs[expr] is special too but handled earlier. So we only need to
  1072. # handle varargs[stmt] which is the same as varargs[typed]:
  1073. if f.kind == tyVarargs:
  1074. if tfVarargs in a.flags:
  1075. return typeRel(c, f.base, a.lastSon)
  1076. if tfOldSchoolExprStmt in f.sons[0].flags:
  1077. if f.sons[0].kind == tyExpr: return
  1078. elif f.sons[0].kind == tyStmt: return
  1079. template matchArrayOrSeq(aBase: PType) =
  1080. let ff = f.base
  1081. let aa = aBase
  1082. let baseRel = typeRel(c, ff, aa)
  1083. if baseRel >= isGeneric:
  1084. result = isConvertible
  1085. elif nimEnableCovariance and
  1086. trNoCovariance notin flags and
  1087. ff.kind == aa.kind and
  1088. isCovariantPtr(c, ff, aa):
  1089. result = isConvertible
  1090. case a.kind
  1091. of tyOpenArray, tyVarargs:
  1092. result = typeRel(c, base(f), base(a))
  1093. if result < isGeneric: result = isNone
  1094. of tyArray:
  1095. if (f.sons[0].kind != tyGenericParam) and (a.sons[1].kind == tyEmpty):
  1096. return isSubtype
  1097. matchArrayOrSeq(a.sons[1])
  1098. of tySequence:
  1099. if (f.sons[0].kind != tyGenericParam) and (a.sons[0].kind == tyEmpty):
  1100. return isConvertible
  1101. matchArrayOrSeq(a.sons[0])
  1102. of tyString:
  1103. if f.kind == tyOpenArray:
  1104. if f.sons[0].kind == tyChar:
  1105. result = isConvertible
  1106. elif f.sons[0].kind == tyGenericParam and a.len > 0 and
  1107. typeRel(c, base(f), base(a)) >= isGeneric:
  1108. result = isConvertible
  1109. else: discard
  1110. of tySequence:
  1111. case a.kind
  1112. of tySequence:
  1113. if (f.sons[0].kind != tyGenericParam) and (a.sons[0].kind == tyEmpty):
  1114. result = isSubtype
  1115. else:
  1116. let ff = f.sons[0]
  1117. let aa = a.sons[0]
  1118. result = typeRel(c, ff, aa)
  1119. if result < isGeneric:
  1120. if nimEnableCovariance and
  1121. trNoCovariance notin flags and
  1122. ff.kind == aa.kind and
  1123. isCovariantPtr(c, ff, aa):
  1124. result = isSubtype
  1125. else:
  1126. result = isNone
  1127. elif tfNotNil in f.flags and tfNotNil notin a.flags:
  1128. result = isNilConversion
  1129. of tyNil: result = allowsNilDeprecated(c, f)
  1130. else: discard
  1131. of tyOrdinal:
  1132. if isOrdinalType(a):
  1133. var x = if a.kind == tyOrdinal: a.sons[0] else: a
  1134. if f.sons[0].kind == tyNone:
  1135. result = isGeneric
  1136. else:
  1137. result = typeRel(c, f.sons[0], x)
  1138. if result < isGeneric: result = isNone
  1139. elif a.kind == tyGenericParam:
  1140. result = isGeneric
  1141. of tyForward:
  1142. #internalError("forward type in typeRel()")
  1143. result = isNone
  1144. of tyNil:
  1145. if a.kind == f.kind: result = isEqual
  1146. of tyTuple:
  1147. if a.kind == tyTuple: result = recordRel(c, f, a)
  1148. of tyObject:
  1149. if a.kind == tyObject:
  1150. if sameObjectTypes(f, a):
  1151. result = isEqual
  1152. # elif tfHasMeta in f.flags: result = recordRel(c, f, a)
  1153. else:
  1154. var depth = isObjectSubtype(c, a, f, nil)
  1155. if depth > 0:
  1156. inc(c.inheritancePenalty, depth)
  1157. result = isSubtype
  1158. of tyDistinct:
  1159. if a.kind == tyDistinct:
  1160. if sameDistinctTypes(f, a): result = isEqual
  1161. elif f.base.kind == tyAnything: result = isGeneric
  1162. elif c.coerceDistincts: result = typeRel(c, f.base, a)
  1163. elif a.kind == tyNil and f.base.kind in NilableTypes:
  1164. result = f.allowsNil
  1165. elif c.coerceDistincts: result = typeRel(c, f.base, a)
  1166. of tySet:
  1167. if a.kind == tySet:
  1168. if f.sons[0].kind != tyGenericParam and a.sons[0].kind == tyEmpty:
  1169. result = isSubtype
  1170. else:
  1171. result = typeRel(c, f.sons[0], a.sons[0])
  1172. if result <= isConvertible:
  1173. result = isNone # BUGFIX!
  1174. of tyPtr, tyRef:
  1175. if a.kind == f.kind:
  1176. # ptr[R, T] can be passed to ptr[T], but not the other way round:
  1177. if a.len < f.len: return isNone
  1178. for i in 0..f.len-2:
  1179. if typeRel(c, f.sons[i], a.sons[i]) == isNone: return isNone
  1180. result = typeRel(c, f.lastSon, a.lastSon, flags + {trNoCovariance})
  1181. subtypeCheck()
  1182. if result <= isConvertible: result = isNone
  1183. elif tfNotNil in f.flags and tfNotNil notin a.flags:
  1184. result = isNilConversion
  1185. elif a.kind == tyNil: result = f.allowsNil
  1186. else: discard
  1187. of tyProc:
  1188. result = procTypeRel(c, f, a)
  1189. if result != isNone and tfNotNil in f.flags and tfNotNil notin a.flags:
  1190. result = isNilConversion
  1191. of tyPointer:
  1192. case a.kind
  1193. of tyPointer:
  1194. if tfNotNil in f.flags and tfNotNil notin a.flags:
  1195. result = isNilConversion
  1196. else:
  1197. result = isEqual
  1198. of tyNil: result = f.allowsNil
  1199. of tyProc:
  1200. if a.callConv != ccClosure: result = isConvertible
  1201. of tyPtr:
  1202. # 'pointer' is NOT compatible to regionized pointers
  1203. # so 'dealloc(regionPtr)' fails:
  1204. if a.len == 1: result = isConvertible
  1205. of tyCString: result = isConvertible
  1206. else: discard
  1207. of tyString:
  1208. case a.kind
  1209. of tyString:
  1210. if tfNotNil in f.flags and tfNotNil notin a.flags:
  1211. result = isNilConversion
  1212. else:
  1213. result = isEqual
  1214. of tyNil: result = allowsNilDeprecated(c, f)
  1215. else: discard
  1216. of tyCString:
  1217. # conversion from string to cstring is automatic:
  1218. case a.kind
  1219. of tyCString:
  1220. if tfNotNil in f.flags and tfNotNil notin a.flags:
  1221. result = isNilConversion
  1222. else:
  1223. result = isEqual
  1224. of tyNil: result = f.allowsNil
  1225. of tyString: result = isConvertible
  1226. of tyPtr:
  1227. # ptr[Tag, char] is not convertible to 'cstring' for now:
  1228. if a.len == 1:
  1229. let pointsTo = a.sons[0].skipTypes(abstractInst)
  1230. if pointsTo.kind == tyChar: result = isConvertible
  1231. elif pointsTo.kind == tyArray and firstOrd(nil, pointsTo.sons[0]) == 0 and
  1232. skipTypes(pointsTo.sons[0], {tyRange}).kind in {tyInt..tyInt64} and
  1233. pointsTo.sons[1].kind == tyChar:
  1234. result = isConvertible
  1235. else: discard
  1236. of tyEmpty, tyVoid:
  1237. if a.kind == f.kind: result = isEqual
  1238. of tyAlias, tySink:
  1239. result = typeRel(c, lastSon(f), a)
  1240. of tyGenericInst:
  1241. var prev = PType(idTableGet(c.bindings, f))
  1242. var f = if prev == nil: f else: prev
  1243. let roota = a.skipGenericAlias
  1244. let rootf = f.skipGenericAlias
  1245. var m = c
  1246. if a.kind == tyGenericInst:
  1247. if roota.base == rootf.base:
  1248. let nextFlags = flags + {trNoCovariance}
  1249. var hasCovariance = false
  1250. for i in 1 .. rootf.sonsLen-2:
  1251. let ff = rootf.sons[i]
  1252. let aa = roota.sons[i]
  1253. result = typeRel(c, ff, aa, nextFlags)
  1254. if result notin {isEqual, isGeneric}:
  1255. if trNoCovariance notin flags and ff.kind == aa.kind:
  1256. let paramFlags = rootf.base.sons[i-1].flags
  1257. hasCovariance =
  1258. if tfCovariant in paramFlags:
  1259. if tfWeakCovariant in paramFlags:
  1260. isCovariantPtr(c, ff, aa)
  1261. else:
  1262. ff.kind notin {tyRef, tyPtr} and result == isSubtype
  1263. else:
  1264. tfContravariant in paramFlags and
  1265. typeRel(c, aa, ff) == isSubtype
  1266. if hasCovariance:
  1267. continue
  1268. return isNone
  1269. if prev == nil: put(c, f, a)
  1270. result = isGeneric
  1271. else:
  1272. let fKind = rootf.lastSon.kind
  1273. if fKind in {tyAnd, tyOr}:
  1274. result = typeRel(c, lastSon(f), a)
  1275. if result != isNone: put(c, f, a)
  1276. return
  1277. var aAsObject = roota.lastSon
  1278. if fKind in {tyRef, tyPtr}:
  1279. if aAsObject.kind == tyObject:
  1280. # bug #7600, tyObject cannot be passed
  1281. # as argument to tyRef/tyPtr
  1282. return isNone
  1283. elif aAsObject.kind == fKind:
  1284. aAsObject = aAsObject.base
  1285. if aAsObject.kind == tyObject:
  1286. let baseType = aAsObject.base
  1287. if baseType != nil:
  1288. c.inheritancePenalty += 1
  1289. return typeRel(c, f, baseType)
  1290. result = isNone
  1291. else:
  1292. result = typeRel(c, lastSon(f), a)
  1293. if result != isNone and a.kind != tyNil:
  1294. put(c, f, a)
  1295. of tyGenericBody:
  1296. considerPreviousT:
  1297. if a == f or a.kind == tyGenericInst and a.sons[0] == f:
  1298. bindingRet isGeneric
  1299. let ff = lastSon(f)
  1300. if ff != nil:
  1301. result = typeRel(c, ff, a)
  1302. of tyGenericInvocation:
  1303. var x = a.skipGenericAlias
  1304. # XXX: This is very hacky. It should be moved back into liftTypeParam
  1305. if x.kind in {tyGenericInst, tyArray} and
  1306. c.calleeSym != nil and
  1307. c.calleeSym.kind in {skProc, skFunc} and c.call != nil:
  1308. let inst = prepareMetatypeForSigmatch(c.c, c.bindings, c.call.info, f)
  1309. return typeRel(c, inst, a)
  1310. var depth = 0
  1311. if x.kind == tyGenericInvocation or f.sons[0].kind != tyGenericBody:
  1312. #InternalError("typeRel: tyGenericInvocation -> tyGenericInvocation")
  1313. # simply no match for now:
  1314. discard
  1315. elif x.kind == tyGenericInst and
  1316. ((f.sons[0] == x.sons[0]) or isGenericSubType(c, x, f, depth)) and
  1317. (sonsLen(x) - 1 == sonsLen(f)):
  1318. for i in countup(1, sonsLen(f) - 1):
  1319. if x.sons[i].kind == tyGenericParam:
  1320. internalError(c.c.graph.config, "wrong instantiated type!")
  1321. elif typeRel(c, f.sons[i], x.sons[i]) <= isSubtype:
  1322. # Workaround for regression #4589
  1323. if f.sons[i].kind != tyTypeDesc: return
  1324. c.inheritancePenalty += depth
  1325. result = isGeneric
  1326. else:
  1327. let genericBody = f.sons[0]
  1328. var askip = skippedNone
  1329. var fskip = skippedNone
  1330. let aobj = x.skipToObject(askip)
  1331. let fobj = genericBody.lastSon.skipToObject(fskip)
  1332. var depth = -1
  1333. if fobj != nil and aobj != nil and askip == fskip:
  1334. depth = isObjectSubtype(c, aobj, fobj, f)
  1335. result = typeRel(c, genericBody, x)
  1336. if result != isNone:
  1337. # see tests/generics/tgeneric3.nim for an example that triggers this
  1338. # piece of code:
  1339. #
  1340. # proc internalFind[T,D](n: PNode[T,D], key: T): ref TItem[T,D]
  1341. # proc internalPut[T,D](ANode: ref TNode[T,D], Akey: T, Avalue: D,
  1342. # Oldvalue: var D): ref TNode[T,D]
  1343. # var root = internalPut[int, int](nil, 312, 312, oldvalue)
  1344. # var it1 = internalFind(root, 312) # cannot instantiate: 'D'
  1345. #
  1346. # we steal the generic parameters from the tyGenericBody:
  1347. for i in countup(1, sonsLen(f) - 1):
  1348. let x = PType(idTableGet(c.bindings, genericBody.sons[i-1]))
  1349. if x == nil:
  1350. discard "maybe fine (for eg. a==tyNil)"
  1351. elif x.kind in {tyGenericInvocation, tyGenericParam}:
  1352. internalError(c.c.graph.config, "wrong instantiated type!")
  1353. else:
  1354. put(c, f.sons[i], x)
  1355. if result == isNone:
  1356. # Here object inheriting from generic/specialized generic object
  1357. # crossing path with metatypes/aliases, so we need to separate them
  1358. # by checking sym.id
  1359. let genericSubtype = isGenericSubType(c, x, f, depth, f)
  1360. if not (genericSubtype and aobj.sym.id != fobj.sym.id) and aOrig.kind != tyGenericBody:
  1361. depth = -1
  1362. if depth >= 0:
  1363. c.inheritancePenalty += depth
  1364. # bug #4863: We still need to bind generic alias crap, so
  1365. # we cannot return immediately:
  1366. result = if depth == 0: isGeneric else: isSubtype
  1367. of tyAnd:
  1368. considerPreviousT:
  1369. result = isEqual
  1370. for branch in f.sons:
  1371. let x = typeRel(c, branch, aOrig)
  1372. if x < isSubtype: return isNone
  1373. # 'and' implies minimum matching result:
  1374. if x < result: result = x
  1375. if result > isGeneric: result = isGeneric
  1376. bindingRet result
  1377. of tyOr:
  1378. considerPreviousT:
  1379. result = isNone
  1380. let oldInheritancePenalty = c.inheritancePenalty
  1381. var maxInheritance = 0
  1382. for branch in f.sons:
  1383. c.inheritancePenalty = 0
  1384. let x = typeRel(c, branch, aOrig)
  1385. maxInheritance = max(maxInheritance, c.inheritancePenalty)
  1386. # 'or' implies maximum matching result:
  1387. if x > result: result = x
  1388. if result >= isSubtype:
  1389. if result > isGeneric: result = isGeneric
  1390. bindingRet result
  1391. else:
  1392. result = isNone
  1393. c.inheritancePenalty = oldInheritancePenalty + maxInheritance
  1394. of tyNot:
  1395. considerPreviousT:
  1396. for branch in f.sons:
  1397. if typeRel(c, branch, aOrig) != isNone:
  1398. return isNone
  1399. bindingRet isGeneric
  1400. of tyAnything:
  1401. considerPreviousT:
  1402. var concrete = concreteType(c, a)
  1403. if concrete != nil and doBind:
  1404. put(c, f, concrete)
  1405. return isGeneric
  1406. of tyBuiltInTypeClass:
  1407. considerPreviousT:
  1408. let targetKind = f.sons[0].kind
  1409. let effectiveArgType = a.skipTypes({tyRange, tyGenericInst,
  1410. tyBuiltInTypeClass, tyAlias, tySink})
  1411. let typeClassMatches = targetKind == effectiveArgType.kind and
  1412. not effectiveArgType.isEmptyContainer
  1413. if typeClassMatches or
  1414. (targetKind in {tyProc, tyPointer} and effectiveArgType.kind == tyNil):
  1415. put(c, f, a)
  1416. return isGeneric
  1417. else:
  1418. return isNone
  1419. of tyUserTypeClassInst, tyUserTypeClass:
  1420. if f.isResolvedUserTypeClass:
  1421. result = typeRel(c, f.lastSon, a)
  1422. else:
  1423. considerPreviousT:
  1424. if aOrig == f: return isEqual
  1425. var matched = matchUserTypeClass(c, f, aOrig)
  1426. if matched != nil:
  1427. bindConcreteTypeToUserTypeClass(matched, a)
  1428. if doBind: put(c, f, matched)
  1429. result = isGeneric
  1430. else:
  1431. result = isNone
  1432. of tyCompositeTypeClass:
  1433. considerPreviousT:
  1434. let roota = a.skipGenericAlias
  1435. let rootf = f.lastSon.skipGenericAlias
  1436. if a.kind == tyGenericInst and roota.base == rootf.base:
  1437. for i in 1 .. rootf.sonsLen-2:
  1438. let ff = rootf.sons[i]
  1439. let aa = roota.sons[i]
  1440. result = typeRel(c, ff, aa)
  1441. if result == isNone: return
  1442. if ff.kind == tyRange and result != isEqual: return isNone
  1443. else:
  1444. result = typeRel(c, rootf.lastSon, a)
  1445. if result != isNone:
  1446. put(c, f, a)
  1447. result = isGeneric
  1448. of tyGenericParam:
  1449. var x = PType(idTableGet(c.bindings, f))
  1450. if x == nil:
  1451. if c.callee.kind == tyGenericBody and
  1452. f.kind == tyGenericParam and not c.typedescMatched:
  1453. # XXX: The fact that generic types currently use tyGenericParam for
  1454. # their parameters is really a misnomer. tyGenericParam means "match
  1455. # any value" and what we need is "match any type", which can be encoded
  1456. # by a tyTypeDesc params. Unfortunately, this requires more substantial
  1457. # changes in semtypinst and elsewhere.
  1458. if tfWildcard in a.flags:
  1459. result = isGeneric
  1460. elif a.kind == tyTypeDesc:
  1461. if f.sonsLen == 0:
  1462. result = isGeneric
  1463. else:
  1464. internalAssert c.c.graph.config, a.len > 0
  1465. c.typedescMatched = true
  1466. var aa = a
  1467. while aa.kind in {tyTypeDesc, tyGenericParam} and aa.len > 0:
  1468. aa = lastSon(aa)
  1469. if aa.kind == tyGenericParam:
  1470. return isGeneric
  1471. result = typeRel(c, f.base, aa)
  1472. if result > isGeneric: result = isGeneric
  1473. else:
  1474. result = isNone
  1475. else:
  1476. if f.sonsLen > 0 and f.sons[0].kind != tyNone:
  1477. let oldInheritancePenalty = c.inheritancePenalty
  1478. result = typeRel(c, f.lastSon, a, flags + {trDontBind})
  1479. if doBind and result notin {isNone, isGeneric}:
  1480. let concrete = concreteType(c, a)
  1481. if concrete == nil: return isNone
  1482. put(c, f, concrete)
  1483. # bug #6526
  1484. if result in {isEqual, isSubtype}:
  1485. # 'T: Class' is a *better* match than just 'T'
  1486. # but 'T: Subclass' is even better:
  1487. c.inheritancePenalty = oldInheritancePenalty - c.inheritancePenalty -
  1488. 100 * ord(result == isEqual)
  1489. result = isGeneric
  1490. else:
  1491. result = isGeneric
  1492. if result == isGeneric:
  1493. var concrete = a
  1494. if tfWildcard in a.flags:
  1495. a.sym.kind = skType
  1496. a.flags.excl tfWildcard
  1497. else:
  1498. concrete = concreteType(c, a)
  1499. if concrete == nil:
  1500. return isNone
  1501. if doBind:
  1502. put(c, f, concrete)
  1503. elif result > isGeneric:
  1504. result = isGeneric
  1505. elif a.kind == tyEmpty:
  1506. result = isGeneric
  1507. elif x.kind == tyGenericParam:
  1508. result = isGeneric
  1509. else:
  1510. # Special type binding rule for numeric types.
  1511. # See section "Generic type inference for numeric types" of the
  1512. # manual for further details:
  1513. when false:
  1514. let rebinding = maxNumericType(x.skipTypes({tyRange}), a)
  1515. if rebinding != nil:
  1516. put(c, f, rebinding)
  1517. result = isGeneric
  1518. else:
  1519. discard
  1520. result = typeRel(c, x, a) # check if it fits
  1521. if result > isGeneric: result = isGeneric
  1522. of tyStatic:
  1523. let prev = PType(idTableGet(c.bindings, f))
  1524. if prev == nil:
  1525. if aOrig.kind == tyStatic:
  1526. if f.base.kind != tyNone:
  1527. result = typeRel(c, f.base, a)
  1528. if result != isNone and f.n != nil:
  1529. if not exprStructuralEquivalent(f.n, aOrig.n):
  1530. result = isNone
  1531. else:
  1532. result = isGeneric
  1533. if result != isNone: put(c, f, aOrig)
  1534. elif aOrig.n != nil and aOrig.n.typ != nil:
  1535. result = if f.base.kind != tyNone: typeRel(c, f.lastSon, aOrig.n.typ)
  1536. else: isGeneric
  1537. if result != isNone:
  1538. var boundType = newTypeWithSons(c.c, tyStatic, @[aOrig.n.typ])
  1539. boundType.n = aOrig.n
  1540. put(c, f, boundType)
  1541. else:
  1542. result = isNone
  1543. elif prev.kind == tyStatic:
  1544. if aOrig.kind == tyStatic:
  1545. result = typeRel(c, prev.lastSon, a)
  1546. if result != isNone and prev.n != nil:
  1547. if not exprStructuralEquivalent(prev.n, aOrig.n):
  1548. result = isNone
  1549. else: result = isNone
  1550. else:
  1551. # XXX endless recursion?
  1552. #result = typeRel(c, prev, aOrig)
  1553. result = isNone
  1554. of tyInferred:
  1555. let prev = f.previouslyInferred
  1556. if prev != nil:
  1557. result = typeRel(c, prev, a)
  1558. else:
  1559. result = typeRel(c, f.base, a)
  1560. if result != isNone:
  1561. c.inferredTypes.safeAdd f
  1562. f.sons.add a
  1563. of tyTypeDesc:
  1564. var prev = PType(idTableGet(c.bindings, f))
  1565. if prev == nil:
  1566. # proc foo(T: typedesc, x: T)
  1567. # when `f` is an unresolved typedesc, `a` could be any
  1568. # type, so we should not perform this check earlier
  1569. if a.kind != tyTypeDesc:
  1570. if a.kind == tyGenericParam and tfWildcard in a.flags:
  1571. # TODO: prevent `a` from matching as a wildcard again
  1572. result = isGeneric
  1573. else:
  1574. result = isNone
  1575. elif f.base.kind == tyNone:
  1576. result = isGeneric
  1577. else:
  1578. result = typeRel(c, f.base, a.base)
  1579. if result != isNone:
  1580. put(c, f, a)
  1581. else:
  1582. if tfUnresolved in f.flags:
  1583. result = typeRel(c, prev.base, a)
  1584. elif a.kind == tyTypeDesc:
  1585. result = typeRel(c, prev.base, a.base)
  1586. else:
  1587. result = isNone
  1588. of tyStmt:
  1589. if aOrig != nil and tfOldSchoolExprStmt notin f.flags:
  1590. put(c, f, aOrig)
  1591. result = isGeneric
  1592. of tyProxy:
  1593. result = isEqual
  1594. of tyFromExpr:
  1595. # fix the expression, so it contains the already instantiated types
  1596. if f.n == nil or f.n.kind == nkEmpty: return isGeneric
  1597. let reevaluated = tryResolvingStaticExpr(c, f.n)
  1598. case reevaluated.typ.kind
  1599. of tyTypeDesc:
  1600. result = typeRel(c, a, reevaluated.typ.base)
  1601. of tyStatic:
  1602. result = typeRel(c, a, reevaluated.typ.base)
  1603. if result != isNone and reevaluated.typ.n != nil:
  1604. if not exprStructuralEquivalent(aOrig.n, reevaluated.typ.n):
  1605. result = isNone
  1606. else:
  1607. localError(c.c.graph.config, f.n.info, "type expected")
  1608. result = isNone
  1609. of tyNone:
  1610. if a.kind == tyNone: result = isEqual
  1611. else:
  1612. internalError c.c.graph.config, " unknown type kind " & $f.kind
  1613. proc cmpTypes*(c: PContext, f, a: PType): TTypeRelation =
  1614. var m: TCandidate
  1615. initCandidate(c, m, f)
  1616. result = typeRel(m, f, a)
  1617. proc getInstantiatedType(c: PContext, arg: PNode, m: TCandidate,
  1618. f: PType): PType =
  1619. result = PType(idTableGet(m.bindings, f))
  1620. if result == nil:
  1621. result = generateTypeInstance(c, m.bindings, arg, f)
  1622. if result == nil:
  1623. internalError(c.graph.config, arg.info, "getInstantiatedType")
  1624. result = errorType(c)
  1625. proc implicitConv(kind: TNodeKind, f: PType, arg: PNode, m: TCandidate,
  1626. c: PContext): PNode =
  1627. result = newNodeI(kind, arg.info)
  1628. if containsGenericType(f):
  1629. if not m.hasFauxMatch:
  1630. result.typ = getInstantiatedType(c, arg, m, f)
  1631. else:
  1632. result.typ = errorType(c)
  1633. else:
  1634. result.typ = f
  1635. if result.typ == nil: internalError(c.graph.config, arg.info, "implicitConv")
  1636. addSon(result, c.graph.emptyNode)
  1637. addSon(result, arg)
  1638. proc userConvMatch(c: PContext, m: var TCandidate, f, a: PType,
  1639. arg: PNode): PNode =
  1640. result = nil
  1641. for i in countup(0, len(c.converters) - 1):
  1642. var src = c.converters[i].typ.sons[1]
  1643. var dest = c.converters[i].typ.sons[0]
  1644. # for generic type converters we need to check 'src <- a' before
  1645. # 'f <- dest' in order to not break the unification:
  1646. # see tests/tgenericconverter:
  1647. let srca = typeRel(m, src, a)
  1648. if srca notin {isEqual, isGeneric, isSubtype}: continue
  1649. let constraint = c.converters[i].typ.n[1].sym.constraint
  1650. if not constraint.isNil and not matchNodeKinds(constraint, arg):
  1651. continue
  1652. let destIsGeneric = containsGenericType(dest)
  1653. if destIsGeneric:
  1654. dest = generateTypeInstance(c, m.bindings, arg, dest)
  1655. let fdest = typeRel(m, f, dest)
  1656. if fdest in {isEqual, isGeneric}:
  1657. markUsed(c.config, arg.info, c.converters[i], c.graph.usageSym)
  1658. var s = newSymNode(c.converters[i])
  1659. s.typ = c.converters[i].typ
  1660. s.info = arg.info
  1661. result = newNodeIT(nkHiddenCallConv, arg.info, dest)
  1662. addSon(result, s)
  1663. var param: PNode = nil
  1664. if srca == isSubtype:
  1665. param = implicitConv(nkHiddenSubConv, src, copyTree(arg), m, c)
  1666. else:
  1667. param = copyTree(arg)
  1668. addSon(result, param)
  1669. inc(m.convMatches)
  1670. m.genericConverter = srca == isGeneric or destIsGeneric
  1671. return result
  1672. proc localConvMatch(c: PContext, m: var TCandidate, f, a: PType,
  1673. arg: PNode): PNode =
  1674. # arg.typ can be nil in 'suggest':
  1675. if isNil(arg.typ): return nil
  1676. # sem'checking for 'echo' needs to be re-entrant:
  1677. # XXX we will revisit this issue after 0.10.2 is released
  1678. if f == arg.typ and arg.kind == nkHiddenStdConv: return arg
  1679. var call = newNodeI(nkCall, arg.info)
  1680. call.add(f.n.copyTree)
  1681. call.add(arg.copyTree)
  1682. result = c.semExpr(c, call)
  1683. if result != nil:
  1684. if result.typ == nil: return nil
  1685. # resulting type must be consistent with the other arguments:
  1686. var r = typeRel(m, f.sons[0], result.typ)
  1687. if r < isGeneric: return nil
  1688. if result.kind == nkCall: result.kind = nkHiddenCallConv
  1689. inc(m.convMatches)
  1690. if r == isGeneric:
  1691. result.typ = getInstantiatedType(c, arg, m, base(f))
  1692. m.baseTypeMatch = true
  1693. proc incMatches(m: var TCandidate; r: TTypeRelation; convMatch = 1) =
  1694. case r
  1695. of isConvertible, isIntConv: inc(m.convMatches, convMatch)
  1696. of isSubtype, isSubrange: inc(m.subtypeMatches)
  1697. of isGeneric, isInferred, isBothMetaConvertible: inc(m.genericMatches)
  1698. of isFromIntLit: inc(m.intConvMatches, 256)
  1699. of isInferredConvertible:
  1700. inc(m.convMatches)
  1701. of isEqual: inc(m.exactMatches)
  1702. of isNone: discard
  1703. template matchesVoidProc(t: PType): bool =
  1704. (t.kind == tyProc and t.len == 1 and t.sons[0] == nil) or
  1705. (t.kind == tyBuiltInTypeClass and t.sons[0].kind == tyProc)
  1706. proc paramTypesMatchAux(m: var TCandidate, f, a: PType,
  1707. argSemantized, argOrig: PNode): PNode =
  1708. var
  1709. fMaybeStatic = f.skipTypes({tyDistinct})
  1710. arg = argSemantized
  1711. a = a
  1712. c = m.c
  1713. if tfHasStatic in fMaybeStatic.flags:
  1714. # XXX: When implicit statics are the default
  1715. # this will be done earlier - we just have to
  1716. # make sure that static types enter here
  1717. # XXX: weaken tyGenericParam and call it tyGenericPlaceholder
  1718. # and finally start using tyTypedesc for generic types properly.
  1719. if a.kind == tyGenericParam and tfWildcard in a.flags:
  1720. a.assignType(f)
  1721. # put(m.bindings, f, a)
  1722. return argSemantized
  1723. if a.kind == tyStatic:
  1724. if m.callee.kind == tyGenericBody and
  1725. a.n == nil and
  1726. tfGenericTypeParam notin a.flags:
  1727. return newNodeIT(nkType, argOrig.info, makeTypeFromExpr(c, arg))
  1728. else:
  1729. var evaluated = c.semTryConstExpr(c, arg)
  1730. if evaluated != nil:
  1731. arg.typ = newTypeS(tyStatic, c)
  1732. arg.typ.sons = @[evaluated.typ]
  1733. arg.typ.n = evaluated
  1734. a = arg.typ
  1735. else:
  1736. if m.callee.kind == tyGenericBody:
  1737. if f.kind == tyStatic and typeRel(m, f.base, a) != isNone:
  1738. result = makeStaticExpr(m.c, arg)
  1739. result.typ.flags.incl tfUnresolved
  1740. result.typ.n = arg
  1741. return
  1742. let oldInheritancePenalty = m.inheritancePenalty
  1743. var r = typeRel(m, f, a)
  1744. # This special typing rule for macros and templates is not documented
  1745. # anywhere and breaks symmetry. It's hard to get rid of though, my
  1746. # custom seqs example fails to compile without this:
  1747. if r != isNone and m.calleeSym != nil and
  1748. m.calleeSym.kind in {skMacro, skTemplate}:
  1749. # XXX: duplicating this is ugly, but we cannot (!) move this
  1750. # directly into typeRel using return-like templates
  1751. incMatches(m, r)
  1752. if f.kind == tyStmt:
  1753. return arg
  1754. elif f.kind == tyTypeDesc:
  1755. return arg
  1756. elif f.kind == tyStatic and arg.typ.n != nil:
  1757. return arg.typ.n
  1758. else:
  1759. return argSemantized # argOrig
  1760. # If r == isBothMetaConvertible then we rerun typeRel.
  1761. # bothMetaCounter is for safety to avoid any infinite loop,
  1762. # I don't have any example when it is needed.
  1763. # lastBindingsLenth is used to check whether m.bindings remains the same,
  1764. # because in that case there is no point in continuing.
  1765. var bothMetaCounter = 0
  1766. var lastBindingsLength = -1
  1767. while r == isBothMetaConvertible and
  1768. lastBindingsLength != m.bindings.counter and
  1769. bothMetaCounter < 100:
  1770. lastBindingsLength = m.bindings.counter
  1771. inc(bothMetaCounter)
  1772. if arg.kind in {nkProcDef, nkFuncDef, nkIteratorDef} + nkLambdaKinds:
  1773. result = c.semInferredLambda(c, m.bindings, arg)
  1774. elif arg.kind != nkSym:
  1775. return nil
  1776. else:
  1777. let inferred = c.semGenerateInstance(c, arg.sym, m.bindings, arg.info)
  1778. result = newSymNode(inferred, arg.info)
  1779. inc(m.convMatches)
  1780. arg = result
  1781. r = typeRel(m, f, arg.typ)
  1782. case r
  1783. of isConvertible:
  1784. inc(m.convMatches)
  1785. result = implicitConv(nkHiddenStdConv, f, arg, m, c)
  1786. of isIntConv:
  1787. # I'm too lazy to introduce another ``*matches`` field, so we conflate
  1788. # ``isIntConv`` and ``isIntLit`` here:
  1789. inc(m.intConvMatches)
  1790. result = implicitConv(nkHiddenStdConv, f, arg, m, c)
  1791. of isSubtype:
  1792. inc(m.subtypeMatches)
  1793. if f.kind == tyTypeDesc:
  1794. result = arg
  1795. else:
  1796. result = implicitConv(nkHiddenSubConv, f, arg, m, c)
  1797. of isSubrange:
  1798. inc(m.subtypeMatches)
  1799. if f.kind == tyVar:
  1800. result = arg
  1801. else:
  1802. result = implicitConv(nkHiddenStdConv, f, arg, m, c)
  1803. of isInferred, isInferredConvertible:
  1804. if arg.kind in {nkProcDef, nkFuncDef, nkIteratorDef} + nkLambdaKinds:
  1805. result = c.semInferredLambda(c, m.bindings, arg)
  1806. elif arg.kind != nkSym:
  1807. return nil
  1808. else:
  1809. let inferred = c.semGenerateInstance(c, arg.sym, m.bindings, arg.info)
  1810. result = newSymNode(inferred, arg.info)
  1811. if r == isInferredConvertible:
  1812. inc(m.convMatches)
  1813. result = implicitConv(nkHiddenStdConv, f, result, m, c)
  1814. else:
  1815. inc(m.genericMatches)
  1816. of isGeneric:
  1817. inc(m.genericMatches)
  1818. if arg.typ == nil:
  1819. result = arg
  1820. elif skipTypes(arg.typ, abstractVar-{tyTypeDesc}).kind == tyTuple or
  1821. m.inheritancePenalty > oldInheritancePenalty:
  1822. result = implicitConv(nkHiddenSubConv, f, arg, m, c)
  1823. elif arg.typ.isEmptyContainer:
  1824. result = arg.copyTree
  1825. result.typ = getInstantiatedType(c, arg, m, f)
  1826. else:
  1827. result = arg
  1828. of isBothMetaConvertible:
  1829. # This is the result for the 101th time.
  1830. result = nil
  1831. of isFromIntLit:
  1832. # too lazy to introduce another ``*matches`` field, so we conflate
  1833. # ``isIntConv`` and ``isIntLit`` here:
  1834. inc(m.intConvMatches, 256)
  1835. result = implicitConv(nkHiddenStdConv, f, arg, m, c)
  1836. of isEqual:
  1837. inc(m.exactMatches)
  1838. result = arg
  1839. if skipTypes(f, abstractVar-{tyTypeDesc}).kind in {tyTuple}:
  1840. result = implicitConv(nkHiddenSubConv, f, arg, m, c)
  1841. of isNone:
  1842. # do not do this in ``typeRel`` as it then can't infer T in ``ref T``:
  1843. if a.kind in {tyProxy, tyUnknown}:
  1844. inc(m.genericMatches)
  1845. m.fauxMatch = a.kind
  1846. return arg
  1847. elif a.kind == tyVoid and f.matchesVoidProc and argOrig.kind == nkStmtList:
  1848. # lift do blocks without params to lambdas
  1849. let p = c.graph
  1850. let lifted = c.semExpr(c, newProcNode(nkDo, argOrig.info, body = argOrig,
  1851. params = p.emptyNode, name = p.emptyNode, pattern = p.emptyNode,
  1852. genericParams = p.emptyNode, pragmas = p.emptyNode, exceptions = p.emptyNode), {})
  1853. if f.kind == tyBuiltInTypeClass:
  1854. inc m.genericMatches
  1855. put(m, f, lifted.typ)
  1856. inc m.convMatches
  1857. return implicitConv(nkHiddenStdConv, f, lifted, m, c)
  1858. result = userConvMatch(c, m, f, a, arg)
  1859. # check for a base type match, which supports varargs[T] without []
  1860. # constructor in a call:
  1861. if result == nil and f.kind == tyVarargs:
  1862. if f.n != nil:
  1863. result = localConvMatch(c, m, f, a, arg)
  1864. else:
  1865. r = typeRel(m, base(f), a)
  1866. if r >= isGeneric:
  1867. inc(m.convMatches)
  1868. result = copyTree(arg)
  1869. if r == isGeneric:
  1870. result.typ = getInstantiatedType(c, arg, m, base(f))
  1871. m.baseTypeMatch = true
  1872. # bug #4799, varargs accepting subtype relation object
  1873. elif r == isSubtype:
  1874. inc(m.subtypeMatches)
  1875. if f.kind == tyTypeDesc:
  1876. result = arg
  1877. else:
  1878. result = implicitConv(nkHiddenSubConv, f, arg, m, c)
  1879. m.baseTypeMatch = true
  1880. else:
  1881. result = userConvMatch(c, m, base(f), a, arg)
  1882. if result != nil: m.baseTypeMatch = true
  1883. proc paramTypesMatch*(m: var TCandidate, f, a: PType,
  1884. arg, argOrig: PNode): PNode =
  1885. if arg == nil or arg.kind notin nkSymChoices:
  1886. result = paramTypesMatchAux(m, f, a, arg, argOrig)
  1887. else:
  1888. # CAUTION: The order depends on the used hashing scheme. Thus it is
  1889. # incorrect to simply use the first fitting match. However, to implement
  1890. # this correctly is inefficient. We have to copy `m` here to be able to
  1891. # roll back the side effects of the unification algorithm.
  1892. let c = m.c
  1893. var x, y, z: TCandidate
  1894. initCandidate(c, x, m.callee)
  1895. initCandidate(c, y, m.callee)
  1896. initCandidate(c, z, m.callee)
  1897. x.calleeSym = m.calleeSym
  1898. y.calleeSym = m.calleeSym
  1899. z.calleeSym = m.calleeSym
  1900. var best = -1
  1901. for i in 0 ..< arg.len:
  1902. if arg.sons[i].sym.kind in {skProc, skFunc, skMethod, skConverter,
  1903. skIterator, skMacro, skTemplate}:
  1904. copyCandidate(z, m)
  1905. z.callee = arg.sons[i].typ
  1906. if tfUnresolved in z.callee.flags: continue
  1907. z.calleeSym = arg.sons[i].sym
  1908. #if arg.sons[i].sym.name.s == "cmp":
  1909. # ggDebug = true
  1910. # echo "CALLLEEEEEEEE A ", typeToString(z.callee)
  1911. # XXX this is still all wrong: (T, T) should be 2 generic matches
  1912. # and (int, int) 2 exact matches, etc. Essentially you cannot call
  1913. # typeRel here and expect things to work!
  1914. let r = typeRel(z, f, arg.sons[i].typ)
  1915. incMatches(z, r, 2)
  1916. #if arg.sons[i].sym.name.s == "cmp": # and arg.info.line == 606:
  1917. # echo "M ", r, " ", arg.info, " ", typeToString(arg.sons[i].sym.typ)
  1918. # writeMatches(z)
  1919. if r != isNone:
  1920. z.state = csMatch
  1921. case x.state
  1922. of csEmpty, csNoMatch:
  1923. x = z
  1924. best = i
  1925. of csMatch:
  1926. let cmp = cmpCandidates(x, z)
  1927. if cmp < 0:
  1928. best = i
  1929. x = z
  1930. elif cmp == 0:
  1931. y = z # z is as good as x
  1932. if x.state == csEmpty:
  1933. result = nil
  1934. elif y.state == csMatch and cmpCandidates(x, y) == 0:
  1935. if x.state != csMatch:
  1936. internalError(m.c.graph.config, arg.info, "x.state is not csMatch")
  1937. # ambiguous: more than one symbol fits!
  1938. # See tsymchoice_for_expr as an example. 'f.kind == tyExpr' should match
  1939. # anyway:
  1940. if f.kind in {tyExpr, tyStmt}: result = arg
  1941. else: result = nil
  1942. else:
  1943. # only one valid interpretation found:
  1944. markUsed(m.c.config, arg.info, arg.sons[best].sym, m.c.graph.usageSym)
  1945. styleCheckUse(arg.info, arg.sons[best].sym)
  1946. result = paramTypesMatchAux(m, f, arg.sons[best].typ, arg.sons[best],
  1947. argOrig)
  1948. when false:
  1949. if m.calleeSym != nil and m.calleeSym.name.s == "[]":
  1950. echo m.c.config $ arg.info, " for ", m.calleeSym.name.s, " ", m.c.config $ m.calleeSym.info
  1951. writeMatches(m)
  1952. proc setSon(father: PNode, at: int, son: PNode) =
  1953. let oldLen = father.len
  1954. if oldLen <= at:
  1955. setLen(father.sons, at + 1)
  1956. father.sons[at] = son
  1957. # insert potential 'void' parameters:
  1958. #for i in oldLen ..< at:
  1959. # father.sons[i] = newNodeIT(nkEmpty, son.info, getSysType(tyVoid))
  1960. # we are allowed to modify the calling node in the 'prepare*' procs:
  1961. proc prepareOperand(c: PContext; formal: PType; a: PNode): PNode =
  1962. if formal.kind == tyExpr and formal.len != 1:
  1963. # {tyTypeDesc, tyExpr, tyStmt, tyProxy}:
  1964. # a.typ == nil is valid
  1965. result = a
  1966. elif a.typ.isNil:
  1967. # XXX This is unsound! 'formal' can differ from overloaded routine to
  1968. # overloaded routine!
  1969. let flags = {efDetermineType, efAllowStmt}
  1970. #if formal.kind == tyIter: {efDetermineType, efWantIterator}
  1971. #else: {efDetermineType, efAllowStmt}
  1972. #elif formal.kind == tyStmt: {efDetermineType, efWantStmt}
  1973. #else: {efDetermineType}
  1974. result = c.semOperand(c, a, flags)
  1975. else:
  1976. result = a
  1977. considerGenSyms(c, result)
  1978. proc prepareOperand(c: PContext; a: PNode): PNode =
  1979. if a.typ.isNil:
  1980. result = c.semOperand(c, a, {efDetermineType})
  1981. else:
  1982. result = a
  1983. considerGenSyms(c, result)
  1984. proc prepareNamedParam(a: PNode; c: PContext) =
  1985. if a.sons[0].kind != nkIdent:
  1986. var info = a.sons[0].info
  1987. a.sons[0] = newIdentNode(considerQuotedIdent(c, a.sons[0]), info)
  1988. proc arrayConstr(c: PContext, n: PNode): PType =
  1989. result = newTypeS(tyArray, c)
  1990. rawAddSon(result, makeRangeType(c, 0, 0, n.info))
  1991. addSonSkipIntLit(result, skipTypes(n.typ,
  1992. {tyGenericInst, tyVar, tyLent, tyOrdinal}))
  1993. proc arrayConstr(c: PContext, info: TLineInfo): PType =
  1994. result = newTypeS(tyArray, c)
  1995. rawAddSon(result, makeRangeType(c, 0, -1, info))
  1996. rawAddSon(result, newTypeS(tyEmpty, c)) # needs an empty basetype!
  1997. proc incrIndexType(t: PType) =
  1998. assert t.kind == tyArray
  1999. inc t.sons[0].n.sons[1].intVal
  2000. template isVarargsUntyped(x): untyped =
  2001. x.kind == tyVarargs and x.sons[0].kind == tyExpr and
  2002. tfOldSchoolExprStmt notin x.sons[0].flags
  2003. proc matchesAux(c: PContext, n, nOrig: PNode,
  2004. m: var TCandidate, marker: var IntSet) =
  2005. template checkConstraint(n: untyped) {.dirty.} =
  2006. if not formal.constraint.isNil:
  2007. if matchNodeKinds(formal.constraint, n):
  2008. # better match over other routines with no such restriction:
  2009. inc(m.genericMatches, 100)
  2010. else:
  2011. m.state = csNoMatch
  2012. return
  2013. if formal.typ.kind == tyVar:
  2014. if not n.isLValue:
  2015. m.state = csNoMatch
  2016. m.mutabilityProblem = uint8(f-1)
  2017. return
  2018. var
  2019. # iterates over formal parameters
  2020. f = if m.callee.kind != tyGenericBody: 1
  2021. else: 0
  2022. # iterates over the actual given arguments
  2023. a = 1
  2024. m.state = csMatch # until proven otherwise
  2025. m.call = newNodeI(n.kind, n.info)
  2026. m.call.typ = base(m.callee) # may be nil
  2027. var formalLen = m.callee.n.len
  2028. addSon(m.call, copyTree(n.sons[0]))
  2029. var container: PNode = nil # constructed container
  2030. var formal: PSym = if formalLen > 1: m.callee.n.sons[1].sym else: nil
  2031. while a < n.len:
  2032. if a >= formalLen-1 and f < formalLen and m.callee.n[f].typ.isVarargsUntyped:
  2033. formal = m.callee.n.sons[f].sym
  2034. incl(marker, formal.position)
  2035. if n.sons[a].kind == nkHiddenStdConv:
  2036. doAssert n.sons[a].sons[0].kind == nkEmpty and
  2037. n.sons[a].sons[1].kind == nkArgList and
  2038. n.sons[a].sons[1].len == 0
  2039. # Steal the container and pass it along
  2040. setSon(m.call, formal.position + 1, n.sons[a].sons[1])
  2041. else:
  2042. if container.isNil:
  2043. container = newNodeIT(nkArgList, n.sons[a].info, arrayConstr(c, n.info))
  2044. setSon(m.call, formal.position + 1, container)
  2045. else:
  2046. incrIndexType(container.typ)
  2047. addSon(container, n.sons[a])
  2048. elif n.sons[a].kind == nkExprEqExpr:
  2049. # named param
  2050. # check if m.callee has such a param:
  2051. prepareNamedParam(n.sons[a], c)
  2052. if n.sons[a].sons[0].kind != nkIdent:
  2053. localError(c.config, n.sons[a].info, "named parameter has to be an identifier")
  2054. m.state = csNoMatch
  2055. m.firstMismatch = -a
  2056. return
  2057. formal = getSymFromList(m.callee.n, n.sons[a].sons[0].ident, 1)
  2058. if formal == nil:
  2059. # no error message!
  2060. m.state = csNoMatch
  2061. m.firstMismatch = -a
  2062. return
  2063. if containsOrIncl(marker, formal.position):
  2064. # already in namedParams, so no match
  2065. # we used to produce 'errCannotBindXTwice' here but see
  2066. # bug #3836 of why that is not sound (other overload with
  2067. # different parameter names could match later on):
  2068. when false: localError(n.sons[a].info, errCannotBindXTwice, formal.name.s)
  2069. m.state = csNoMatch
  2070. return
  2071. m.baseTypeMatch = false
  2072. m.typedescMatched = false
  2073. n.sons[a].sons[1] = prepareOperand(c, formal.typ, n.sons[a].sons[1])
  2074. n.sons[a].typ = n.sons[a].sons[1].typ
  2075. var arg = paramTypesMatch(m, formal.typ, n.sons[a].typ,
  2076. n.sons[a].sons[1], n.sons[a].sons[1])
  2077. if arg == nil:
  2078. m.state = csNoMatch
  2079. m.firstMismatch = a
  2080. return
  2081. checkConstraint(n.sons[a].sons[1])
  2082. if m.baseTypeMatch:
  2083. #assert(container == nil)
  2084. container = newNodeIT(nkBracket, n.sons[a].info, arrayConstr(c, arg))
  2085. addSon(container, arg)
  2086. setSon(m.call, formal.position + 1, container)
  2087. if f != formalLen - 1: container = nil
  2088. else:
  2089. setSon(m.call, formal.position + 1, arg)
  2090. inc f
  2091. else:
  2092. # unnamed param
  2093. if f >= formalLen:
  2094. # too many arguments?
  2095. if tfVarargs in m.callee.flags:
  2096. # is ok... but don't increment any counters...
  2097. # we have no formal here to snoop at:
  2098. n.sons[a] = prepareOperand(c, n.sons[a])
  2099. if skipTypes(n.sons[a].typ, abstractVar-{tyTypeDesc}).kind==tyString:
  2100. addSon(m.call, implicitConv(nkHiddenStdConv,
  2101. getSysType(c.graph, n.sons[a].info, tyCString),
  2102. copyTree(n.sons[a]), m, c))
  2103. else:
  2104. addSon(m.call, copyTree(n.sons[a]))
  2105. elif formal != nil and formal.typ.kind == tyVarargs:
  2106. # beware of the side-effects in 'prepareOperand'! So only do it for
  2107. # varargs matching. See tests/metatype/tstatic_overloading.
  2108. m.baseTypeMatch = false
  2109. m.typedescMatched = false
  2110. incl(marker, formal.position)
  2111. n.sons[a] = prepareOperand(c, formal.typ, n.sons[a])
  2112. var arg = paramTypesMatch(m, formal.typ, n.sons[a].typ,
  2113. n.sons[a], nOrig.sons[a])
  2114. if arg != nil and m.baseTypeMatch and container != nil:
  2115. addSon(container, arg)
  2116. incrIndexType(container.typ)
  2117. checkConstraint(n.sons[a])
  2118. else:
  2119. m.state = csNoMatch
  2120. return
  2121. else:
  2122. m.state = csNoMatch
  2123. return
  2124. else:
  2125. if m.callee.n.sons[f].kind != nkSym:
  2126. internalError(c.config, n.sons[a].info, "matches")
  2127. return
  2128. formal = m.callee.n.sons[f].sym
  2129. if containsOrIncl(marker, formal.position) and container.isNil:
  2130. # already in namedParams: (see above remark)
  2131. when false: localError(n.sons[a].info, errCannotBindXTwice, formal.name.s)
  2132. m.state = csNoMatch
  2133. return
  2134. if formal.typ.isVarargsUntyped:
  2135. if container.isNil:
  2136. container = newNodeIT(nkArgList, n.sons[a].info, arrayConstr(c, n.info))
  2137. setSon(m.call, formal.position + 1, container)
  2138. else:
  2139. incrIndexType(container.typ)
  2140. addSon(container, n.sons[a])
  2141. else:
  2142. m.baseTypeMatch = false
  2143. m.typedescMatched = false
  2144. n.sons[a] = prepareOperand(c, formal.typ, n.sons[a])
  2145. var arg = paramTypesMatch(m, formal.typ, n.sons[a].typ,
  2146. n.sons[a], nOrig.sons[a])
  2147. if arg == nil:
  2148. m.state = csNoMatch
  2149. m.firstMismatch = f
  2150. return
  2151. if m.baseTypeMatch:
  2152. assert formal.typ.kind == tyVarargs
  2153. #assert(container == nil)
  2154. if container.isNil:
  2155. container = newNodeIT(nkBracket, n.sons[a].info, arrayConstr(c, arg))
  2156. container.typ.flags.incl tfVarargs
  2157. else:
  2158. incrIndexType(container.typ)
  2159. addSon(container, arg)
  2160. setSon(m.call, formal.position + 1,
  2161. implicitConv(nkHiddenStdConv, formal.typ, container, m, c))
  2162. #if f != formalLen - 1: container = nil
  2163. # pick the formal from the end, so that 'x, y, varargs, z' works:
  2164. f = max(f, formalLen - n.len + a + 1)
  2165. elif formal.typ.kind != tyVarargs or container == nil:
  2166. setSon(m.call, formal.position + 1, arg)
  2167. inc(f)
  2168. container = nil
  2169. else:
  2170. # we end up here if the argument can be converted into the varargs
  2171. # formal (eg. seq[T] -> varargs[T]) but we have already instantiated
  2172. # a container
  2173. assert arg.kind == nkHiddenStdConv
  2174. localError(c.config, n.sons[a].info, "cannot convert $1 to $2" % [
  2175. typeToString(n.sons[a].typ), typeToString(formal.typ) ])
  2176. m.state = csNoMatch
  2177. return
  2178. checkConstraint(n.sons[a])
  2179. inc(a)
  2180. proc semFinishOperands*(c: PContext, n: PNode) =
  2181. # this needs to be called to ensure that after overloading resolution every
  2182. # argument has been sem'checked:
  2183. for i in 1 ..< n.len:
  2184. n.sons[i] = prepareOperand(c, n.sons[i])
  2185. proc partialMatch*(c: PContext, n, nOrig: PNode, m: var TCandidate) =
  2186. # for 'suggest' support:
  2187. var marker = initIntSet()
  2188. matchesAux(c, n, nOrig, m, marker)
  2189. proc matches*(c: PContext, n, nOrig: PNode, m: var TCandidate) =
  2190. if m.magic in {mArrGet, mArrPut}:
  2191. m.state = csMatch
  2192. m.call = n
  2193. # Note the following doesn't work as it would produce ambiguities.
  2194. # Instead we patch system.nim, see bug #8049.
  2195. when false:
  2196. inc m.genericMatches
  2197. inc m.exactMatches
  2198. return
  2199. var marker = initIntSet()
  2200. matchesAux(c, n, nOrig, m, marker)
  2201. if m.state == csNoMatch: return
  2202. # check that every formal parameter got a value:
  2203. var f = 1
  2204. while f < sonsLen(m.callee.n):
  2205. var formal = m.callee.n.sons[f].sym
  2206. if not containsOrIncl(marker, formal.position):
  2207. if formal.ast == nil:
  2208. if formal.typ.kind == tyVarargs:
  2209. # For consistency with what happens in `matchesAux` select the
  2210. # container node kind accordingly
  2211. let cnKind = if formal.typ.isVarargsUntyped: nkArgList else: nkBracket
  2212. var container = newNodeIT(cnKind, n.info, arrayConstr(c, n.info))
  2213. setSon(m.call, formal.position + 1,
  2214. implicitConv(nkHiddenStdConv, formal.typ, container, m, c))
  2215. else:
  2216. # no default value
  2217. m.state = csNoMatch
  2218. m.firstMismatch = f
  2219. break
  2220. else:
  2221. if formal.ast.kind == nkEmpty:
  2222. # The default param value is set to empty in `instantiateProcType`
  2223. # when the type of the default expression doesn't match the type
  2224. # of the instantiated proc param:
  2225. localError(c.config, m.call.info,
  2226. ("The default parameter '$1' has incompatible type " &
  2227. "with the explicitly requested proc instantiation") %
  2228. formal.name.s)
  2229. if nfDefaultRefsParam in formal.ast.flags:
  2230. m.call.flags.incl nfDefaultRefsParam
  2231. var def = copyTree(formal.ast)
  2232. if def.kind == nkNilLit:
  2233. def = implicitConv(nkHiddenStdConv, formal.typ, def, m, c)
  2234. if {tfImplicitTypeParam, tfGenericTypeParam} * formal.typ.flags != {}:
  2235. put(m, formal.typ, def.typ)
  2236. def.flags.incl nfDefaultParam
  2237. setSon(m.call, formal.position + 1, def)
  2238. inc(f)
  2239. # forget all inferred types if the overload matching failed
  2240. if m.state == csNoMatch:
  2241. for t in m.inferredTypes:
  2242. if t.sonsLen > 1: t.sons.setLen 1
  2243. proc argtypeMatches*(c: PContext, f, a: PType, fromHlo = false): bool =
  2244. var m: TCandidate
  2245. initCandidate(c, m, f)
  2246. let res = paramTypesMatch(m, f, a, c.graph.emptyNode, nil)
  2247. #instantiateGenericConverters(c, res, m)
  2248. # XXX this is used by patterns.nim too; I think it's better to not
  2249. # instantiate generic converters for that
  2250. if not fromHlo:
  2251. res != nil
  2252. else:
  2253. # pattern templates do not allow for conversions except from int literal
  2254. res != nil and m.convMatches == 0 and m.intConvMatches in [0, 256]
  2255. proc instTypeBoundOp*(c: PContext; dc: PSym; t: PType; info: TLineInfo;
  2256. op: TTypeAttachedOp; col: int): PSym {.procvar.} =
  2257. var m: TCandidate
  2258. initCandidate(c, m, dc.typ)
  2259. if col >= dc.typ.len:
  2260. localError(c.config, info, "cannot instantiate: '" & dc.name.s & "'")
  2261. return nil
  2262. var f = dc.typ.sons[col]
  2263. if op == attachedDeepCopy:
  2264. if f.kind in {tyRef, tyPtr}: f = f.lastSon
  2265. else:
  2266. if f.kind == tyVar: f = f.lastSon
  2267. if typeRel(m, f, t) == isNone:
  2268. localError(c.config, info, "cannot instantiate: '" & dc.name.s & "'")
  2269. else:
  2270. result = c.semGenerateInstance(c, dc, m.bindings, info)
  2271. if op == attachedDeepCopy:
  2272. assert sfFromGeneric in result.flags
  2273. include suggest
  2274. when not declared(tests):
  2275. template tests(s: untyped) = discard
  2276. tests:
  2277. var dummyOwner = newSym(skModule, getIdent("test_module"), nil, UnknownLineInfo())
  2278. proc `|` (t1, t2: PType): PType =
  2279. result = newType(tyOr, dummyOwner)
  2280. result.rawAddSon(t1)
  2281. result.rawAddSon(t2)
  2282. proc `&` (t1, t2: PType): PType =
  2283. result = newType(tyAnd, dummyOwner)
  2284. result.rawAddSon(t1)
  2285. result.rawAddSon(t2)
  2286. proc `!` (t: PType): PType =
  2287. result = newType(tyNot, dummyOwner)
  2288. result.rawAddSon(t)
  2289. proc seq(t: PType): PType =
  2290. result = newType(tySequence, dummyOwner)
  2291. result.rawAddSon(t)
  2292. proc array(x: int, t: PType): PType =
  2293. result = newType(tyArray, dummyOwner)
  2294. var n = newNodeI(nkRange, UnknownLineInfo())
  2295. addSon(n, newIntNode(nkIntLit, 0))
  2296. addSon(n, newIntNode(nkIntLit, x))
  2297. let range = newType(tyRange, dummyOwner)
  2298. result.rawAddSon(range)
  2299. result.rawAddSon(t)
  2300. suite "type classes":
  2301. let
  2302. int = newType(tyInt, dummyOwner)
  2303. float = newType(tyFloat, dummyOwner)
  2304. string = newType(tyString, dummyOwner)
  2305. ordinal = newType(tyOrdinal, dummyOwner)
  2306. any = newType(tyAnything, dummyOwner)
  2307. number = int | float
  2308. var TFoo = newType(tyObject, dummyOwner)
  2309. TFoo.sym = newSym(skType, getIdent"TFoo", dummyOwner, UnknownLineInfo())
  2310. var T1 = newType(tyGenericParam, dummyOwner)
  2311. T1.sym = newSym(skType, getIdent"T1", dummyOwner, UnknownLineInfo())
  2312. T1.sym.position = 0
  2313. var T2 = newType(tyGenericParam, dummyOwner)
  2314. T2.sym = newSym(skType, getIdent"T2", dummyOwner, UnknownLineInfo())
  2315. T2.sym.position = 1
  2316. setup:
  2317. var c: TCandidate
  2318. initCandidate(nil, c, nil)
  2319. template yes(x, y) =
  2320. test astToStr(x) & " is " & astToStr(y):
  2321. check typeRel(c, y, x) == isGeneric
  2322. template no(x, y) =
  2323. test astToStr(x) & " is not " & astToStr(y):
  2324. check typeRel(c, y, x) == isNone
  2325. yes seq(any), array(10, int) | seq(any)
  2326. # Sure, seq[any] is directly included
  2327. yes seq(int), seq(any)
  2328. yes seq(int), seq(number)
  2329. # Sure, the int sequence is certainly
  2330. # part of the number sequences (and all sequences)
  2331. no seq(any), seq(float)
  2332. # Nope, seq[any] includes types that are not seq[float] (e.g. seq[int])
  2333. yes seq(int|string), seq(any)
  2334. # Sure
  2335. yes seq(int&string), seq(any)
  2336. # Again
  2337. yes seq(int&string), seq(int)
  2338. # A bit more complicated
  2339. # seq[int&string] is not a real type, but it's analogous to
  2340. # seq[Sortable and Iterable], which is certainly a subset of seq[Sortable]
  2341. no seq(int|string), seq(int|float)
  2342. # Nope, seq[string] is not included in not included in
  2343. # the seq[int|float] set
  2344. no seq(!(int|string)), seq(string)
  2345. # A sequence that is neither seq[int] or seq[string]
  2346. # is obviously not seq[string]
  2347. no seq(!int), seq(number)
  2348. # Now your head should start to hurt a bit
  2349. # A sequence that is not seq[int] is not necessarily a number sequence
  2350. # it could well be seq[string] for example
  2351. yes seq(!(int|string)), seq(!string)
  2352. # all sequnece types besides seq[int] and seq[string]
  2353. # are subset of all sequence types that are not seq[string]
  2354. no seq(!(int|string)), seq(!(string|TFoo))
  2355. # Nope, seq[TFoo] is included in the first set, but not in the second
  2356. no seq(!string), seq(!number)
  2357. # Nope, seq[int] in included in the first set, but not in the second
  2358. yes seq(!number), seq(any)
  2359. yes seq(!int), seq(any)
  2360. no seq(any), seq(!any)
  2361. no seq(!int), seq(!any)
  2362. yes int, ordinal
  2363. no string, ordinal