sigmatch.nim 92 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625
  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, tyUncheckedArray,
  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.add((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.add 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.add 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 tyUncheckedArray:
  1071. if a.kind == tyUncheckedArray:
  1072. result = typeRel(c, base(f), base(a))
  1073. if result < isGeneric: result = isNone
  1074. else: discard
  1075. of tyOpenArray, tyVarargs:
  1076. # varargs[expr] is special too but handled earlier. So we only need to
  1077. # handle varargs[stmt] which is the same as varargs[typed]:
  1078. if f.kind == tyVarargs:
  1079. if tfVarargs in a.flags:
  1080. return typeRel(c, f.base, a.lastSon)
  1081. if tfOldSchoolExprStmt in f.sons[0].flags:
  1082. if f.sons[0].kind == tyExpr: return
  1083. elif f.sons[0].kind == tyStmt: return
  1084. template matchArrayOrSeq(aBase: PType) =
  1085. let ff = f.base
  1086. let aa = aBase
  1087. let baseRel = typeRel(c, ff, aa)
  1088. if baseRel >= isGeneric:
  1089. result = isConvertible
  1090. elif nimEnableCovariance and
  1091. trNoCovariance notin flags and
  1092. ff.kind == aa.kind and
  1093. isCovariantPtr(c, ff, aa):
  1094. result = isConvertible
  1095. case a.kind
  1096. of tyOpenArray, tyVarargs:
  1097. result = typeRel(c, base(f), base(a))
  1098. if result < isGeneric: result = isNone
  1099. of tyArray:
  1100. if (f.sons[0].kind != tyGenericParam) and (a.sons[1].kind == tyEmpty):
  1101. return isSubtype
  1102. matchArrayOrSeq(a.sons[1])
  1103. of tySequence:
  1104. if (f.sons[0].kind != tyGenericParam) and (a.sons[0].kind == tyEmpty):
  1105. return isConvertible
  1106. matchArrayOrSeq(a.sons[0])
  1107. of tyString:
  1108. if f.kind == tyOpenArray:
  1109. if f.sons[0].kind == tyChar:
  1110. result = isConvertible
  1111. elif f.sons[0].kind == tyGenericParam and a.len > 0 and
  1112. typeRel(c, base(f), base(a)) >= isGeneric:
  1113. result = isConvertible
  1114. else: discard
  1115. of tySequence:
  1116. case a.kind
  1117. of tySequence:
  1118. if (f.sons[0].kind != tyGenericParam) and (a.sons[0].kind == tyEmpty):
  1119. result = isSubtype
  1120. else:
  1121. let ff = f.sons[0]
  1122. let aa = a.sons[0]
  1123. result = typeRel(c, ff, aa)
  1124. if result < isGeneric:
  1125. if nimEnableCovariance and
  1126. trNoCovariance notin flags and
  1127. ff.kind == aa.kind and
  1128. isCovariantPtr(c, ff, aa):
  1129. result = isSubtype
  1130. else:
  1131. result = isNone
  1132. elif tfNotNil in f.flags and tfNotNil notin a.flags:
  1133. result = isNilConversion
  1134. of tyNil: result = allowsNilDeprecated(c, f)
  1135. else: discard
  1136. of tyOrdinal:
  1137. if isOrdinalType(a):
  1138. var x = if a.kind == tyOrdinal: a.sons[0] else: a
  1139. if f.sons[0].kind == tyNone:
  1140. result = isGeneric
  1141. else:
  1142. result = typeRel(c, f.sons[0], x)
  1143. if result < isGeneric: result = isNone
  1144. elif a.kind == tyGenericParam:
  1145. result = isGeneric
  1146. of tyForward:
  1147. #internalError("forward type in typeRel()")
  1148. result = isNone
  1149. of tyNil:
  1150. if a.kind == f.kind: result = isEqual
  1151. of tyTuple:
  1152. if a.kind == tyTuple: result = recordRel(c, f, a)
  1153. of tyObject:
  1154. if a.kind == tyObject:
  1155. if sameObjectTypes(f, a):
  1156. result = isEqual
  1157. # elif tfHasMeta in f.flags: result = recordRel(c, f, a)
  1158. else:
  1159. var depth = isObjectSubtype(c, a, f, nil)
  1160. if depth > 0:
  1161. inc(c.inheritancePenalty, depth)
  1162. result = isSubtype
  1163. of tyDistinct:
  1164. if a.kind == tyDistinct:
  1165. if sameDistinctTypes(f, a): result = isEqual
  1166. #elif f.base.kind == tyAnything: result = isGeneric # issue 4435
  1167. elif c.coerceDistincts: result = typeRel(c, f.base, a)
  1168. elif a.kind == tyNil and f.base.kind in NilableTypes:
  1169. result = f.allowsNil
  1170. elif c.coerceDistincts: result = typeRel(c, f.base, a)
  1171. of tySet:
  1172. if a.kind == tySet:
  1173. if f.sons[0].kind != tyGenericParam and a.sons[0].kind == tyEmpty:
  1174. result = isSubtype
  1175. else:
  1176. result = typeRel(c, f.sons[0], a.sons[0])
  1177. if result <= isConvertible:
  1178. result = isNone # BUGFIX!
  1179. of tyPtr, tyRef:
  1180. if a.kind == f.kind:
  1181. # ptr[R, T] can be passed to ptr[T], but not the other way round:
  1182. if a.len < f.len: return isNone
  1183. for i in 0..f.len-2:
  1184. if typeRel(c, f.sons[i], a.sons[i]) == isNone: return isNone
  1185. result = typeRel(c, f.lastSon, a.lastSon, flags + {trNoCovariance})
  1186. subtypeCheck()
  1187. if result <= isConvertible: result = isNone
  1188. elif tfNotNil in f.flags and tfNotNil notin a.flags:
  1189. result = isNilConversion
  1190. elif a.kind == tyNil: result = f.allowsNil
  1191. else: discard
  1192. of tyProc:
  1193. result = procTypeRel(c, f, a)
  1194. if result != isNone and tfNotNil in f.flags and tfNotNil notin a.flags:
  1195. result = isNilConversion
  1196. of tyPointer:
  1197. case a.kind
  1198. of tyPointer:
  1199. if tfNotNil in f.flags and tfNotNil notin a.flags:
  1200. result = isNilConversion
  1201. else:
  1202. result = isEqual
  1203. of tyNil: result = f.allowsNil
  1204. of tyProc:
  1205. if a.callConv != ccClosure: result = isConvertible
  1206. of tyPtr:
  1207. # 'pointer' is NOT compatible to regionized pointers
  1208. # so 'dealloc(regionPtr)' fails:
  1209. if a.len == 1: result = isConvertible
  1210. of tyCString: result = isConvertible
  1211. else: discard
  1212. of tyString:
  1213. case a.kind
  1214. of tyString:
  1215. if tfNotNil in f.flags and tfNotNil notin a.flags:
  1216. result = isNilConversion
  1217. else:
  1218. result = isEqual
  1219. of tyNil: result = allowsNilDeprecated(c, f)
  1220. else: discard
  1221. of tyCString:
  1222. # conversion from string to cstring is automatic:
  1223. case a.kind
  1224. of tyCString:
  1225. if tfNotNil in f.flags and tfNotNil notin a.flags:
  1226. result = isNilConversion
  1227. else:
  1228. result = isEqual
  1229. of tyNil: result = f.allowsNil
  1230. of tyString: result = isConvertible
  1231. of tyPtr:
  1232. # ptr[Tag, char] is not convertible to 'cstring' for now:
  1233. if a.len == 1:
  1234. let pointsTo = a.sons[0].skipTypes(abstractInst)
  1235. if pointsTo.kind == tyChar: result = isConvertible
  1236. elif pointsTo.kind == tyUncheckedArray and pointsTo.sons[0].kind == tyChar:
  1237. result = isConvertible
  1238. elif pointsTo.kind == tyArray and firstOrd(nil, pointsTo.sons[0]) == 0 and
  1239. skipTypes(pointsTo.sons[0], {tyRange}).kind in {tyInt..tyInt64} and
  1240. pointsTo.sons[1].kind == tyChar:
  1241. result = isConvertible
  1242. else: discard
  1243. of tyEmpty, tyVoid:
  1244. if a.kind == f.kind: result = isEqual
  1245. of tyAlias, tySink:
  1246. result = typeRel(c, lastSon(f), a)
  1247. of tyGenericInst:
  1248. var prev = PType(idTableGet(c.bindings, f))
  1249. let origF = f
  1250. var f = if prev == nil: f else: prev
  1251. let roota = a.skipGenericAlias
  1252. let rootf = f.skipGenericAlias
  1253. var m = c
  1254. if a.kind == tyGenericInst:
  1255. if roota.base == rootf.base:
  1256. let nextFlags = flags + {trNoCovariance}
  1257. var hasCovariance = false
  1258. for i in 1 .. rootf.sonsLen-2:
  1259. let ff = rootf.sons[i]
  1260. let aa = roota.sons[i]
  1261. result = typeRel(c, ff, aa, nextFlags)
  1262. if result notin {isEqual, isGeneric}:
  1263. if trNoCovariance notin flags and ff.kind == aa.kind:
  1264. let paramFlags = rootf.base.sons[i-1].flags
  1265. hasCovariance =
  1266. if tfCovariant in paramFlags:
  1267. if tfWeakCovariant in paramFlags:
  1268. isCovariantPtr(c, ff, aa)
  1269. else:
  1270. ff.kind notin {tyRef, tyPtr} and result == isSubtype
  1271. else:
  1272. tfContravariant in paramFlags and
  1273. typeRel(c, aa, ff) == isSubtype
  1274. if hasCovariance:
  1275. continue
  1276. return isNone
  1277. if prev == nil: put(c, f, a)
  1278. result = isGeneric
  1279. else:
  1280. let fKind = rootf.lastSon.kind
  1281. if fKind in {tyAnd, tyOr}:
  1282. result = typeRel(c, lastSon(f), a)
  1283. if result != isNone: put(c, f, a)
  1284. return
  1285. var aAsObject = roota.lastSon
  1286. if fKind in {tyRef, tyPtr}:
  1287. if aAsObject.kind == tyObject:
  1288. # bug #7600, tyObject cannot be passed
  1289. # as argument to tyRef/tyPtr
  1290. return isNone
  1291. elif aAsObject.kind == fKind:
  1292. aAsObject = aAsObject.base
  1293. if aAsObject.kind == tyObject:
  1294. let baseType = aAsObject.base
  1295. if baseType != nil:
  1296. c.inheritancePenalty += 1
  1297. return typeRel(c, f, baseType)
  1298. result = isNone
  1299. else:
  1300. assert lastSon(origF) != nil
  1301. result = typeRel(c, lastSon(origF), a)
  1302. if result != isNone and a.kind != tyNil:
  1303. put(c, f, a)
  1304. of tyGenericBody:
  1305. considerPreviousT:
  1306. if a == f or a.kind == tyGenericInst and a.sons[0] == f:
  1307. bindingRet isGeneric
  1308. let ff = lastSon(f)
  1309. if ff != nil:
  1310. result = typeRel(c, ff, a)
  1311. of tyGenericInvocation:
  1312. var x = a.skipGenericAlias
  1313. # XXX: This is very hacky. It should be moved back into liftTypeParam
  1314. if x.kind in {tyGenericInst, tyArray} and
  1315. c.calleeSym != nil and
  1316. c.calleeSym.kind in {skProc, skFunc} and c.call != nil:
  1317. let inst = prepareMetatypeForSigmatch(c.c, c.bindings, c.call.info, f)
  1318. return typeRel(c, inst, a)
  1319. var depth = 0
  1320. if x.kind == tyGenericInvocation or f.sons[0].kind != tyGenericBody:
  1321. #InternalError("typeRel: tyGenericInvocation -> tyGenericInvocation")
  1322. # simply no match for now:
  1323. discard
  1324. elif x.kind == tyGenericInst and
  1325. ((f.sons[0] == x.sons[0]) or isGenericSubType(c, x, f, depth)) and
  1326. (sonsLen(x) - 1 == sonsLen(f)):
  1327. for i in countup(1, sonsLen(f) - 1):
  1328. if x.sons[i].kind == tyGenericParam:
  1329. internalError(c.c.graph.config, "wrong instantiated type!")
  1330. elif typeRel(c, f.sons[i], x.sons[i]) <= isSubtype:
  1331. # Workaround for regression #4589
  1332. if f.sons[i].kind != tyTypeDesc: return
  1333. c.inheritancePenalty += depth
  1334. result = isGeneric
  1335. else:
  1336. let genericBody = f.sons[0]
  1337. var askip = skippedNone
  1338. var fskip = skippedNone
  1339. let aobj = x.skipToObject(askip)
  1340. let fobj = genericBody.lastSon.skipToObject(fskip)
  1341. var depth = -1
  1342. if fobj != nil and aobj != nil and askip == fskip:
  1343. depth = isObjectSubtype(c, aobj, fobj, f)
  1344. result = typeRel(c, genericBody, x)
  1345. if result != isNone:
  1346. # see tests/generics/tgeneric3.nim for an example that triggers this
  1347. # piece of code:
  1348. #
  1349. # proc internalFind[T,D](n: PNode[T,D], key: T): ref TItem[T,D]
  1350. # proc internalPut[T,D](ANode: ref TNode[T,D], Akey: T, Avalue: D,
  1351. # Oldvalue: var D): ref TNode[T,D]
  1352. # var root = internalPut[int, int](nil, 312, 312, oldvalue)
  1353. # var it1 = internalFind(root, 312) # cannot instantiate: 'D'
  1354. #
  1355. # we steal the generic parameters from the tyGenericBody:
  1356. for i in countup(1, sonsLen(f) - 1):
  1357. let x = PType(idTableGet(c.bindings, genericBody.sons[i-1]))
  1358. if x == nil:
  1359. discard "maybe fine (for eg. a==tyNil)"
  1360. elif x.kind in {tyGenericInvocation, tyGenericParam}:
  1361. internalError(c.c.graph.config, "wrong instantiated type!")
  1362. else:
  1363. put(c, f.sons[i], x)
  1364. if result == isNone:
  1365. # Here object inheriting from generic/specialized generic object
  1366. # crossing path with metatypes/aliases, so we need to separate them
  1367. # by checking sym.id
  1368. let genericSubtype = isGenericSubType(c, x, f, depth, f)
  1369. if not (genericSubtype and aobj.sym.id != fobj.sym.id) and aOrig.kind != tyGenericBody:
  1370. depth = -1
  1371. if depth >= 0:
  1372. c.inheritancePenalty += depth
  1373. # bug #4863: We still need to bind generic alias crap, so
  1374. # we cannot return immediately:
  1375. result = if depth == 0: isGeneric else: isSubtype
  1376. of tyAnd:
  1377. considerPreviousT:
  1378. result = isEqual
  1379. for branch in f.sons:
  1380. let x = typeRel(c, branch, aOrig)
  1381. if x < isSubtype: return isNone
  1382. # 'and' implies minimum matching result:
  1383. if x < result: result = x
  1384. if result > isGeneric: result = isGeneric
  1385. bindingRet result
  1386. of tyOr:
  1387. considerPreviousT:
  1388. result = isNone
  1389. let oldInheritancePenalty = c.inheritancePenalty
  1390. var maxInheritance = 0
  1391. for branch in f.sons:
  1392. c.inheritancePenalty = 0
  1393. let x = typeRel(c, branch, aOrig)
  1394. maxInheritance = max(maxInheritance, c.inheritancePenalty)
  1395. # 'or' implies maximum matching result:
  1396. if x > result: result = x
  1397. if result >= isSubtype:
  1398. if result > isGeneric: result = isGeneric
  1399. bindingRet result
  1400. else:
  1401. result = isNone
  1402. c.inheritancePenalty = oldInheritancePenalty + maxInheritance
  1403. of tyNot:
  1404. considerPreviousT:
  1405. for branch in f.sons:
  1406. if typeRel(c, branch, aOrig) != isNone:
  1407. return isNone
  1408. bindingRet isGeneric
  1409. of tyAnything:
  1410. considerPreviousT:
  1411. var concrete = concreteType(c, a)
  1412. if concrete != nil and doBind:
  1413. put(c, f, concrete)
  1414. return isGeneric
  1415. of tyBuiltInTypeClass:
  1416. considerPreviousT:
  1417. let targetKind = f.sons[0].kind
  1418. let effectiveArgType = a.skipTypes({tyRange, tyGenericInst,
  1419. tyBuiltInTypeClass, tyAlias, tySink})
  1420. let typeClassMatches = targetKind == effectiveArgType.kind and
  1421. not effectiveArgType.isEmptyContainer
  1422. if typeClassMatches or
  1423. (targetKind in {tyProc, tyPointer} and effectiveArgType.kind == tyNil):
  1424. put(c, f, a)
  1425. return isGeneric
  1426. else:
  1427. return isNone
  1428. of tyUserTypeClassInst, tyUserTypeClass:
  1429. if f.isResolvedUserTypeClass:
  1430. result = typeRel(c, f.lastSon, a)
  1431. else:
  1432. considerPreviousT:
  1433. if aOrig == f: return isEqual
  1434. var matched = matchUserTypeClass(c, f, aOrig)
  1435. if matched != nil:
  1436. bindConcreteTypeToUserTypeClass(matched, a)
  1437. if doBind: put(c, f, matched)
  1438. result = isGeneric
  1439. else:
  1440. result = isNone
  1441. of tyCompositeTypeClass:
  1442. considerPreviousT:
  1443. let roota = a.skipGenericAlias
  1444. let rootf = f.lastSon.skipGenericAlias
  1445. if a.kind == tyGenericInst and roota.base == rootf.base:
  1446. for i in 1 .. rootf.sonsLen-2:
  1447. let ff = rootf.sons[i]
  1448. let aa = roota.sons[i]
  1449. result = typeRel(c, ff, aa)
  1450. if result == isNone: return
  1451. if ff.kind == tyRange and result != isEqual: return isNone
  1452. else:
  1453. result = typeRel(c, rootf.lastSon, a)
  1454. if result != isNone:
  1455. put(c, f, a)
  1456. result = isGeneric
  1457. of tyGenericParam:
  1458. var x = PType(idTableGet(c.bindings, f))
  1459. if x == nil:
  1460. if c.callee.kind == tyGenericBody and
  1461. f.kind == tyGenericParam and not c.typedescMatched:
  1462. # XXX: The fact that generic types currently use tyGenericParam for
  1463. # their parameters is really a misnomer. tyGenericParam means "match
  1464. # any value" and what we need is "match any type", which can be encoded
  1465. # by a tyTypeDesc params. Unfortunately, this requires more substantial
  1466. # changes in semtypinst and elsewhere.
  1467. if tfWildcard in a.flags:
  1468. result = isGeneric
  1469. elif a.kind == tyTypeDesc:
  1470. if f.sonsLen == 0:
  1471. result = isGeneric
  1472. else:
  1473. internalAssert c.c.graph.config, a.len > 0
  1474. c.typedescMatched = true
  1475. var aa = a
  1476. while aa.kind in {tyTypeDesc, tyGenericParam} and aa.len > 0:
  1477. aa = lastSon(aa)
  1478. if aa.kind == tyGenericParam:
  1479. return isGeneric
  1480. result = typeRel(c, f.base, aa)
  1481. if result > isGeneric: result = isGeneric
  1482. else:
  1483. result = isNone
  1484. else:
  1485. if f.sonsLen > 0 and f.sons[0].kind != tyNone:
  1486. let oldInheritancePenalty = c.inheritancePenalty
  1487. result = typeRel(c, f.lastSon, a, flags + {trDontBind})
  1488. if doBind and result notin {isNone, isGeneric}:
  1489. let concrete = concreteType(c, a)
  1490. if concrete == nil: return isNone
  1491. put(c, f, concrete)
  1492. # bug #6526
  1493. if result in {isEqual, isSubtype}:
  1494. # 'T: Class' is a *better* match than just 'T'
  1495. # but 'T: Subclass' is even better:
  1496. c.inheritancePenalty = oldInheritancePenalty - c.inheritancePenalty -
  1497. 100 * ord(result == isEqual)
  1498. result = isGeneric
  1499. else:
  1500. result = isGeneric
  1501. if result == isGeneric:
  1502. var concrete = a
  1503. if tfWildcard in a.flags:
  1504. a.sym.kind = skType
  1505. a.flags.excl tfWildcard
  1506. else:
  1507. concrete = concreteType(c, a)
  1508. if concrete == nil:
  1509. return isNone
  1510. if doBind:
  1511. put(c, f, concrete)
  1512. elif result > isGeneric:
  1513. result = isGeneric
  1514. elif a.kind == tyEmpty:
  1515. result = isGeneric
  1516. elif x.kind == tyGenericParam:
  1517. result = isGeneric
  1518. else:
  1519. # Special type binding rule for numeric types.
  1520. # See section "Generic type inference for numeric types" of the
  1521. # manual for further details:
  1522. when false:
  1523. let rebinding = maxNumericType(x.skipTypes({tyRange}), a)
  1524. if rebinding != nil:
  1525. put(c, f, rebinding)
  1526. result = isGeneric
  1527. else:
  1528. discard
  1529. result = typeRel(c, x, a) # check if it fits
  1530. if result > isGeneric: result = isGeneric
  1531. of tyStatic:
  1532. let prev = PType(idTableGet(c.bindings, f))
  1533. if prev == nil:
  1534. if aOrig.kind == tyStatic:
  1535. if f.base.kind != tyNone:
  1536. result = typeRel(c, f.base, a)
  1537. if result != isNone and f.n != nil:
  1538. if not exprStructuralEquivalent(f.n, aOrig.n):
  1539. result = isNone
  1540. else:
  1541. result = isGeneric
  1542. if result != isNone: put(c, f, aOrig)
  1543. elif aOrig.n != nil and aOrig.n.typ != nil:
  1544. result = if f.base.kind != tyNone: typeRel(c, f.lastSon, aOrig.n.typ)
  1545. else: isGeneric
  1546. if result != isNone:
  1547. var boundType = newTypeWithSons(c.c, tyStatic, @[aOrig.n.typ])
  1548. boundType.n = aOrig.n
  1549. put(c, f, boundType)
  1550. else:
  1551. result = isNone
  1552. elif prev.kind == tyStatic:
  1553. if aOrig.kind == tyStatic:
  1554. result = typeRel(c, prev.lastSon, a)
  1555. if result != isNone and prev.n != nil:
  1556. if not exprStructuralEquivalent(prev.n, aOrig.n):
  1557. result = isNone
  1558. else: result = isNone
  1559. else:
  1560. # XXX endless recursion?
  1561. #result = typeRel(c, prev, aOrig)
  1562. result = isNone
  1563. of tyInferred:
  1564. let prev = f.previouslyInferred
  1565. if prev != nil:
  1566. result = typeRel(c, prev, a)
  1567. else:
  1568. result = typeRel(c, f.base, a)
  1569. if result != isNone:
  1570. c.inferredTypes.add f
  1571. f.sons.add a
  1572. of tyTypeDesc:
  1573. var prev = PType(idTableGet(c.bindings, f))
  1574. if prev == nil:
  1575. # proc foo(T: typedesc, x: T)
  1576. # when `f` is an unresolved typedesc, `a` could be any
  1577. # type, so we should not perform this check earlier
  1578. if a.kind != tyTypeDesc:
  1579. if a.kind == tyGenericParam and tfWildcard in a.flags:
  1580. # TODO: prevent `a` from matching as a wildcard again
  1581. result = isGeneric
  1582. else:
  1583. result = isNone
  1584. elif f.base.kind == tyNone:
  1585. result = isGeneric
  1586. else:
  1587. result = typeRel(c, f.base, a.base)
  1588. if result != isNone:
  1589. put(c, f, a)
  1590. else:
  1591. if tfUnresolved in f.flags:
  1592. result = typeRel(c, prev.base, a)
  1593. elif a.kind == tyTypeDesc:
  1594. result = typeRel(c, prev.base, a.base)
  1595. else:
  1596. result = isNone
  1597. of tyStmt:
  1598. if aOrig != nil and tfOldSchoolExprStmt notin f.flags:
  1599. put(c, f, aOrig)
  1600. result = isGeneric
  1601. of tyProxy:
  1602. result = isEqual
  1603. of tyFromExpr:
  1604. # fix the expression, so it contains the already instantiated types
  1605. if f.n == nil or f.n.kind == nkEmpty: return isGeneric
  1606. let reevaluated = tryResolvingStaticExpr(c, f.n)
  1607. case reevaluated.typ.kind
  1608. of tyTypeDesc:
  1609. result = typeRel(c, a, reevaluated.typ.base)
  1610. of tyStatic:
  1611. result = typeRel(c, a, reevaluated.typ.base)
  1612. if result != isNone and reevaluated.typ.n != nil:
  1613. if not exprStructuralEquivalent(aOrig.n, reevaluated.typ.n):
  1614. result = isNone
  1615. else:
  1616. localError(c.c.graph.config, f.n.info, "type expected")
  1617. result = isNone
  1618. of tyNone:
  1619. if a.kind == tyNone: result = isEqual
  1620. else:
  1621. internalError c.c.graph.config, " unknown type kind " & $f.kind
  1622. proc cmpTypes*(c: PContext, f, a: PType): TTypeRelation =
  1623. var m: TCandidate
  1624. initCandidate(c, m, f)
  1625. result = typeRel(m, f, a)
  1626. proc getInstantiatedType(c: PContext, arg: PNode, m: TCandidate,
  1627. f: PType): PType =
  1628. result = PType(idTableGet(m.bindings, f))
  1629. if result == nil:
  1630. result = generateTypeInstance(c, m.bindings, arg, f)
  1631. if result == nil:
  1632. internalError(c.graph.config, arg.info, "getInstantiatedType")
  1633. result = errorType(c)
  1634. proc implicitConv(kind: TNodeKind, f: PType, arg: PNode, m: TCandidate,
  1635. c: PContext): PNode =
  1636. result = newNodeI(kind, arg.info)
  1637. if containsGenericType(f):
  1638. if not m.hasFauxMatch:
  1639. result.typ = getInstantiatedType(c, arg, m, f)
  1640. else:
  1641. result.typ = errorType(c)
  1642. else:
  1643. result.typ = f
  1644. if result.typ == nil: internalError(c.graph.config, arg.info, "implicitConv")
  1645. addSon(result, c.graph.emptyNode)
  1646. addSon(result, arg)
  1647. proc userConvMatch(c: PContext, m: var TCandidate, f, a: PType,
  1648. arg: PNode): PNode =
  1649. result = nil
  1650. for i in countup(0, len(c.converters) - 1):
  1651. var src = c.converters[i].typ.sons[1]
  1652. var dest = c.converters[i].typ.sons[0]
  1653. # for generic type converters we need to check 'src <- a' before
  1654. # 'f <- dest' in order to not break the unification:
  1655. # see tests/tgenericconverter:
  1656. let srca = typeRel(m, src, a)
  1657. if srca notin {isEqual, isGeneric, isSubtype}: continue
  1658. # What's done below matches the logic in ``matchesAux``
  1659. let constraint = c.converters[i].typ.n[1].sym.constraint
  1660. if not constraint.isNil and not matchNodeKinds(constraint, arg):
  1661. continue
  1662. if src.kind in {tyVar, tyLent} and not arg.isLValue:
  1663. continue
  1664. let destIsGeneric = containsGenericType(dest)
  1665. if destIsGeneric:
  1666. dest = generateTypeInstance(c, m.bindings, arg, dest)
  1667. let fdest = typeRel(m, f, dest)
  1668. if fdest in {isEqual, isGeneric}:
  1669. markUsed(c.config, arg.info, c.converters[i], c.graph.usageSym)
  1670. var s = newSymNode(c.converters[i])
  1671. s.typ = c.converters[i].typ
  1672. s.info = arg.info
  1673. result = newNodeIT(nkHiddenCallConv, arg.info, dest)
  1674. addSon(result, s)
  1675. # We build the call expression by ourselves in order to avoid passing this
  1676. # expression trough the semantic check phase once again so let's make sure
  1677. # it is correct
  1678. var param: PNode = nil
  1679. if srca == isSubtype:
  1680. param = implicitConv(nkHiddenSubConv, src, copyTree(arg), m, c)
  1681. elif src.kind == tyVar:
  1682. # Analyse the converter return type
  1683. param = newNodeIT(nkHiddenAddr, arg.info, s.typ[1])
  1684. param.addSon(copyTree(arg))
  1685. else:
  1686. param = copyTree(arg)
  1687. addSon(result, param)
  1688. inc(m.convMatches)
  1689. m.genericConverter = srca == isGeneric or destIsGeneric
  1690. return result
  1691. proc localConvMatch(c: PContext, m: var TCandidate, f, a: PType,
  1692. arg: PNode): PNode =
  1693. # arg.typ can be nil in 'suggest':
  1694. if isNil(arg.typ): return nil
  1695. # sem'checking for 'echo' needs to be re-entrant:
  1696. # XXX we will revisit this issue after 0.10.2 is released
  1697. if f == arg.typ and arg.kind == nkHiddenStdConv: return arg
  1698. var call = newNodeI(nkCall, arg.info)
  1699. call.add(f.n.copyTree)
  1700. call.add(arg.copyTree)
  1701. result = c.semExpr(c, call)
  1702. if result != nil:
  1703. if result.typ == nil: return nil
  1704. # resulting type must be consistent with the other arguments:
  1705. var r = typeRel(m, f.sons[0], result.typ)
  1706. if r < isGeneric: return nil
  1707. if result.kind == nkCall: result.kind = nkHiddenCallConv
  1708. inc(m.convMatches)
  1709. if r == isGeneric:
  1710. result.typ = getInstantiatedType(c, arg, m, base(f))
  1711. m.baseTypeMatch = true
  1712. proc incMatches(m: var TCandidate; r: TTypeRelation; convMatch = 1) =
  1713. case r
  1714. of isConvertible, isIntConv: inc(m.convMatches, convMatch)
  1715. of isSubtype, isSubrange: inc(m.subtypeMatches)
  1716. of isGeneric, isInferred, isBothMetaConvertible: inc(m.genericMatches)
  1717. of isFromIntLit: inc(m.intConvMatches, 256)
  1718. of isInferredConvertible:
  1719. inc(m.convMatches)
  1720. of isEqual: inc(m.exactMatches)
  1721. of isNone: discard
  1722. template matchesVoidProc(t: PType): bool =
  1723. (t.kind == tyProc and t.len == 1 and t.sons[0] == nil) or
  1724. (t.kind == tyBuiltInTypeClass and t.sons[0].kind == tyProc)
  1725. proc paramTypesMatchAux(m: var TCandidate, f, a: PType,
  1726. argSemantized, argOrig: PNode): PNode =
  1727. var
  1728. fMaybeStatic = f.skipTypes({tyDistinct})
  1729. arg = argSemantized
  1730. a = a
  1731. c = m.c
  1732. if tfHasStatic in fMaybeStatic.flags:
  1733. # XXX: When implicit statics are the default
  1734. # this will be done earlier - we just have to
  1735. # make sure that static types enter here
  1736. # XXX: weaken tyGenericParam and call it tyGenericPlaceholder
  1737. # and finally start using tyTypedesc for generic types properly.
  1738. if a.kind == tyGenericParam and tfWildcard in a.flags:
  1739. a.assignType(f)
  1740. # put(m.bindings, f, a)
  1741. return argSemantized
  1742. if a.kind == tyStatic:
  1743. if m.callee.kind == tyGenericBody and
  1744. a.n == nil and
  1745. tfGenericTypeParam notin a.flags:
  1746. return newNodeIT(nkType, argOrig.info, makeTypeFromExpr(c, arg))
  1747. else:
  1748. var evaluated = c.semTryConstExpr(c, arg)
  1749. if evaluated != nil:
  1750. # Don't build the type in-place because `evaluated` and `arg` may point
  1751. # to the same object and we'd end up creating recursive types (#9255)
  1752. let typ = newTypeS(tyStatic, c)
  1753. typ.sons = @[evaluated.typ]
  1754. typ.n = evaluated
  1755. arg.typ = typ
  1756. a = typ
  1757. else:
  1758. if m.callee.kind == tyGenericBody:
  1759. if f.kind == tyStatic and typeRel(m, f.base, a) != isNone:
  1760. result = makeStaticExpr(m.c, arg)
  1761. result.typ.flags.incl tfUnresolved
  1762. result.typ.n = arg
  1763. return
  1764. let oldInheritancePenalty = m.inheritancePenalty
  1765. var r = typeRel(m, f, a)
  1766. # This special typing rule for macros and templates is not documented
  1767. # anywhere and breaks symmetry. It's hard to get rid of though, my
  1768. # custom seqs example fails to compile without this:
  1769. if r != isNone and m.calleeSym != nil and
  1770. m.calleeSym.kind in {skMacro, skTemplate}:
  1771. # XXX: duplicating this is ugly, but we cannot (!) move this
  1772. # directly into typeRel using return-like templates
  1773. incMatches(m, r)
  1774. if f.kind == tyStmt:
  1775. return arg
  1776. elif f.kind == tyTypeDesc:
  1777. return arg
  1778. elif f.kind == tyStatic and arg.typ.n != nil:
  1779. return arg.typ.n
  1780. else:
  1781. return argSemantized # argOrig
  1782. # If r == isBothMetaConvertible then we rerun typeRel.
  1783. # bothMetaCounter is for safety to avoid any infinite loop,
  1784. # I don't have any example when it is needed.
  1785. # lastBindingsLenth is used to check whether m.bindings remains the same,
  1786. # because in that case there is no point in continuing.
  1787. var bothMetaCounter = 0
  1788. var lastBindingsLength = -1
  1789. while r == isBothMetaConvertible and
  1790. lastBindingsLength != m.bindings.counter and
  1791. bothMetaCounter < 100:
  1792. lastBindingsLength = m.bindings.counter
  1793. inc(bothMetaCounter)
  1794. if arg.kind in {nkProcDef, nkFuncDef, nkIteratorDef} + nkLambdaKinds:
  1795. result = c.semInferredLambda(c, m.bindings, arg)
  1796. elif arg.kind != nkSym:
  1797. return nil
  1798. else:
  1799. let inferred = c.semGenerateInstance(c, arg.sym, m.bindings, arg.info)
  1800. result = newSymNode(inferred, arg.info)
  1801. inc(m.convMatches)
  1802. arg = result
  1803. r = typeRel(m, f, arg.typ)
  1804. case r
  1805. of isConvertible:
  1806. inc(m.convMatches)
  1807. result = implicitConv(nkHiddenStdConv, f, arg, m, c)
  1808. of isIntConv:
  1809. # I'm too lazy to introduce another ``*matches`` field, so we conflate
  1810. # ``isIntConv`` and ``isIntLit`` here:
  1811. inc(m.intConvMatches)
  1812. result = implicitConv(nkHiddenStdConv, f, arg, m, c)
  1813. of isSubtype:
  1814. inc(m.subtypeMatches)
  1815. if f.kind == tyTypeDesc:
  1816. result = arg
  1817. else:
  1818. result = implicitConv(nkHiddenSubConv, f, arg, m, c)
  1819. of isSubrange:
  1820. inc(m.subtypeMatches)
  1821. if f.kind == tyVar:
  1822. result = arg
  1823. else:
  1824. result = implicitConv(nkHiddenStdConv, f, arg, m, c)
  1825. of isInferred, isInferredConvertible:
  1826. if arg.kind in {nkProcDef, nkFuncDef, nkIteratorDef} + nkLambdaKinds:
  1827. result = c.semInferredLambda(c, m.bindings, arg)
  1828. elif arg.kind != nkSym:
  1829. return nil
  1830. else:
  1831. let inferred = c.semGenerateInstance(c, arg.sym, m.bindings, arg.info)
  1832. result = newSymNode(inferred, arg.info)
  1833. if r == isInferredConvertible:
  1834. inc(m.convMatches)
  1835. result = implicitConv(nkHiddenStdConv, f, result, m, c)
  1836. else:
  1837. inc(m.genericMatches)
  1838. of isGeneric:
  1839. inc(m.genericMatches)
  1840. if arg.typ == nil:
  1841. result = arg
  1842. elif skipTypes(arg.typ, abstractVar-{tyTypeDesc}).kind == tyTuple or
  1843. m.inheritancePenalty > oldInheritancePenalty:
  1844. result = implicitConv(nkHiddenSubConv, f, arg, m, c)
  1845. elif arg.typ.isEmptyContainer:
  1846. result = arg.copyTree
  1847. result.typ = getInstantiatedType(c, arg, m, f)
  1848. else:
  1849. result = arg
  1850. of isBothMetaConvertible:
  1851. # This is the result for the 101th time.
  1852. result = nil
  1853. of isFromIntLit:
  1854. # too lazy to introduce another ``*matches`` field, so we conflate
  1855. # ``isIntConv`` and ``isIntLit`` here:
  1856. inc(m.intConvMatches, 256)
  1857. result = implicitConv(nkHiddenStdConv, f, arg, m, c)
  1858. of isEqual:
  1859. inc(m.exactMatches)
  1860. result = arg
  1861. if skipTypes(f, abstractVar-{tyTypeDesc}).kind in {tyTuple}:
  1862. result = implicitConv(nkHiddenSubConv, f, arg, m, c)
  1863. of isNone:
  1864. # do not do this in ``typeRel`` as it then can't infer T in ``ref T``:
  1865. if a.kind in {tyProxy, tyUnknown}:
  1866. inc(m.genericMatches)
  1867. m.fauxMatch = a.kind
  1868. return arg
  1869. elif a.kind == tyVoid and f.matchesVoidProc and argOrig.kind == nkStmtList:
  1870. # lift do blocks without params to lambdas
  1871. let p = c.graph
  1872. let lifted = c.semExpr(c, newProcNode(nkDo, argOrig.info, body = argOrig,
  1873. params = p.emptyNode, name = p.emptyNode, pattern = p.emptyNode,
  1874. genericParams = p.emptyNode, pragmas = p.emptyNode, exceptions = p.emptyNode), {})
  1875. if f.kind == tyBuiltInTypeClass:
  1876. inc m.genericMatches
  1877. put(m, f, lifted.typ)
  1878. inc m.convMatches
  1879. return implicitConv(nkHiddenStdConv, f, lifted, m, c)
  1880. result = userConvMatch(c, m, f, a, arg)
  1881. # check for a base type match, which supports varargs[T] without []
  1882. # constructor in a call:
  1883. if result == nil and f.kind == tyVarargs:
  1884. if f.n != nil:
  1885. result = localConvMatch(c, m, f, a, arg)
  1886. else:
  1887. r = typeRel(m, base(f), a)
  1888. if r >= isGeneric:
  1889. inc(m.convMatches)
  1890. result = copyTree(arg)
  1891. if r == isGeneric:
  1892. result.typ = getInstantiatedType(c, arg, m, base(f))
  1893. m.baseTypeMatch = true
  1894. # bug #4799, varargs accepting subtype relation object
  1895. elif r == isSubtype:
  1896. inc(m.subtypeMatches)
  1897. if f.kind == tyTypeDesc:
  1898. result = arg
  1899. else:
  1900. result = implicitConv(nkHiddenSubConv, f, arg, m, c)
  1901. m.baseTypeMatch = true
  1902. else:
  1903. result = userConvMatch(c, m, base(f), a, arg)
  1904. if result != nil: m.baseTypeMatch = true
  1905. proc paramTypesMatch*(m: var TCandidate, f, a: PType,
  1906. arg, argOrig: PNode): PNode =
  1907. if arg == nil or arg.kind notin nkSymChoices:
  1908. result = paramTypesMatchAux(m, f, a, arg, argOrig)
  1909. else:
  1910. # CAUTION: The order depends on the used hashing scheme. Thus it is
  1911. # incorrect to simply use the first fitting match. However, to implement
  1912. # this correctly is inefficient. We have to copy `m` here to be able to
  1913. # roll back the side effects of the unification algorithm.
  1914. let c = m.c
  1915. var x, y, z: TCandidate
  1916. initCandidate(c, x, m.callee)
  1917. initCandidate(c, y, m.callee)
  1918. initCandidate(c, z, m.callee)
  1919. x.calleeSym = m.calleeSym
  1920. y.calleeSym = m.calleeSym
  1921. z.calleeSym = m.calleeSym
  1922. var best = -1
  1923. for i in 0 ..< arg.len:
  1924. if arg.sons[i].sym.kind in {skProc, skFunc, skMethod, skConverter,
  1925. skIterator, skMacro, skTemplate}:
  1926. copyCandidate(z, m)
  1927. z.callee = arg.sons[i].typ
  1928. if tfUnresolved in z.callee.flags: continue
  1929. z.calleeSym = arg.sons[i].sym
  1930. #if arg.sons[i].sym.name.s == "cmp":
  1931. # ggDebug = true
  1932. # echo "CALLLEEEEEEEE A ", typeToString(z.callee)
  1933. # XXX this is still all wrong: (T, T) should be 2 generic matches
  1934. # and (int, int) 2 exact matches, etc. Essentially you cannot call
  1935. # typeRel here and expect things to work!
  1936. let r = typeRel(z, f, arg.sons[i].typ)
  1937. incMatches(z, r, 2)
  1938. #if arg.sons[i].sym.name.s == "cmp": # and arg.info.line == 606:
  1939. # echo "M ", r, " ", arg.info, " ", typeToString(arg.sons[i].sym.typ)
  1940. # writeMatches(z)
  1941. if r != isNone:
  1942. z.state = csMatch
  1943. case x.state
  1944. of csEmpty, csNoMatch:
  1945. x = z
  1946. best = i
  1947. of csMatch:
  1948. let cmp = cmpCandidates(x, z)
  1949. if cmp < 0:
  1950. best = i
  1951. x = z
  1952. elif cmp == 0:
  1953. y = z # z is as good as x
  1954. if x.state == csEmpty:
  1955. result = nil
  1956. elif y.state == csMatch and cmpCandidates(x, y) == 0:
  1957. if x.state != csMatch:
  1958. internalError(m.c.graph.config, arg.info, "x.state is not csMatch")
  1959. # ambiguous: more than one symbol fits!
  1960. # See tsymchoice_for_expr as an example. 'f.kind == tyExpr' should match
  1961. # anyway:
  1962. if f.kind in {tyExpr, tyStmt}: result = arg
  1963. else: result = nil
  1964. else:
  1965. # only one valid interpretation found:
  1966. markUsed(m.c.config, arg.info, arg.sons[best].sym, m.c.graph.usageSym)
  1967. styleCheckUse(arg.info, arg.sons[best].sym)
  1968. result = paramTypesMatchAux(m, f, arg.sons[best].typ, arg.sons[best],
  1969. argOrig)
  1970. when false:
  1971. if m.calleeSym != nil and m.calleeSym.name.s == "[]":
  1972. echo m.c.config $ arg.info, " for ", m.calleeSym.name.s, " ", m.c.config $ m.calleeSym.info
  1973. writeMatches(m)
  1974. proc setSon(father: PNode, at: int, son: PNode) =
  1975. let oldLen = father.len
  1976. if oldLen <= at:
  1977. setLen(father.sons, at + 1)
  1978. father.sons[at] = son
  1979. # insert potential 'void' parameters:
  1980. #for i in oldLen ..< at:
  1981. # father.sons[i] = newNodeIT(nkEmpty, son.info, getSysType(tyVoid))
  1982. # we are allowed to modify the calling node in the 'prepare*' procs:
  1983. proc prepareOperand(c: PContext; formal: PType; a: PNode): PNode =
  1984. if formal.kind == tyExpr and formal.len != 1:
  1985. # {tyTypeDesc, tyExpr, tyStmt, tyProxy}:
  1986. # a.typ == nil is valid
  1987. result = a
  1988. elif a.typ.isNil:
  1989. # XXX This is unsound! 'formal' can differ from overloaded routine to
  1990. # overloaded routine!
  1991. let flags = {efDetermineType, efAllowStmt}
  1992. #if formal.kind == tyIter: {efDetermineType, efWantIterator}
  1993. #else: {efDetermineType, efAllowStmt}
  1994. #elif formal.kind == tyStmt: {efDetermineType, efWantStmt}
  1995. #else: {efDetermineType}
  1996. result = c.semOperand(c, a, flags)
  1997. else:
  1998. result = a
  1999. considerGenSyms(c, result)
  2000. proc prepareOperand(c: PContext; a: PNode): PNode =
  2001. if a.typ.isNil:
  2002. result = c.semOperand(c, a, {efDetermineType})
  2003. else:
  2004. result = a
  2005. considerGenSyms(c, result)
  2006. proc prepareNamedParam(a: PNode; c: PContext) =
  2007. if a.sons[0].kind != nkIdent:
  2008. var info = a.sons[0].info
  2009. a.sons[0] = newIdentNode(considerQuotedIdent(c, a.sons[0]), info)
  2010. proc arrayConstr(c: PContext, n: PNode): PType =
  2011. result = newTypeS(tyArray, c)
  2012. rawAddSon(result, makeRangeType(c, 0, 0, n.info))
  2013. addSonSkipIntLit(result, skipTypes(n.typ,
  2014. {tyGenericInst, tyVar, tyLent, tyOrdinal}))
  2015. proc arrayConstr(c: PContext, info: TLineInfo): PType =
  2016. result = newTypeS(tyArray, c)
  2017. rawAddSon(result, makeRangeType(c, 0, -1, info))
  2018. rawAddSon(result, newTypeS(tyEmpty, c)) # needs an empty basetype!
  2019. proc incrIndexType(t: PType) =
  2020. assert t.kind == tyArray
  2021. inc t.sons[0].n.sons[1].intVal
  2022. template isVarargsUntyped(x): untyped =
  2023. x.kind == tyVarargs and x.sons[0].kind == tyExpr and
  2024. tfOldSchoolExprStmt notin x.sons[0].flags
  2025. proc matchesAux(c: PContext, n, nOrig: PNode,
  2026. m: var TCandidate, marker: var IntSet) =
  2027. template checkConstraint(n: untyped) {.dirty.} =
  2028. if not formal.constraint.isNil:
  2029. if matchNodeKinds(formal.constraint, n):
  2030. # better match over other routines with no such restriction:
  2031. inc(m.genericMatches, 100)
  2032. else:
  2033. m.state = csNoMatch
  2034. return
  2035. if formal.typ.kind == tyVar:
  2036. if not n.isLValue:
  2037. m.state = csNoMatch
  2038. m.mutabilityProblem = uint8(f-1)
  2039. return
  2040. var
  2041. # iterates over formal parameters
  2042. f = if m.callee.kind != tyGenericBody: 1
  2043. else: 0
  2044. # iterates over the actual given arguments
  2045. a = 1
  2046. m.state = csMatch # until proven otherwise
  2047. m.call = newNodeI(n.kind, n.info)
  2048. m.call.typ = base(m.callee) # may be nil
  2049. var formalLen = m.callee.n.len
  2050. addSon(m.call, copyTree(n.sons[0]))
  2051. var container: PNode = nil # constructed container
  2052. var formal: PSym = if formalLen > 1: m.callee.n.sons[1].sym else: nil
  2053. while a < n.len:
  2054. if a >= formalLen-1 and f < formalLen and m.callee.n[f].typ.isVarargsUntyped:
  2055. formal = m.callee.n.sons[f].sym
  2056. incl(marker, formal.position)
  2057. if n.sons[a].kind == nkHiddenStdConv:
  2058. doAssert n.sons[a].sons[0].kind == nkEmpty and
  2059. n.sons[a].sons[1].kind == nkArgList and
  2060. n.sons[a].sons[1].len == 0
  2061. # Steal the container and pass it along
  2062. setSon(m.call, formal.position + 1, n.sons[a].sons[1])
  2063. else:
  2064. if container.isNil:
  2065. container = newNodeIT(nkArgList, n.sons[a].info, arrayConstr(c, n.info))
  2066. setSon(m.call, formal.position + 1, container)
  2067. else:
  2068. incrIndexType(container.typ)
  2069. addSon(container, n.sons[a])
  2070. elif n.sons[a].kind == nkExprEqExpr:
  2071. # named param
  2072. # check if m.callee has such a param:
  2073. prepareNamedParam(n.sons[a], c)
  2074. if n.sons[a].sons[0].kind != nkIdent:
  2075. localError(c.config, n.sons[a].info, "named parameter has to be an identifier")
  2076. m.state = csNoMatch
  2077. m.firstMismatch = -a
  2078. return
  2079. formal = getSymFromList(m.callee.n, n.sons[a].sons[0].ident, 1)
  2080. if formal == nil:
  2081. # no error message!
  2082. m.state = csNoMatch
  2083. m.firstMismatch = -a
  2084. return
  2085. if containsOrIncl(marker, formal.position):
  2086. # already in namedParams, so no match
  2087. # we used to produce 'errCannotBindXTwice' here but see
  2088. # bug #3836 of why that is not sound (other overload with
  2089. # different parameter names could match later on):
  2090. when false: localError(n.sons[a].info, errCannotBindXTwice, formal.name.s)
  2091. m.state = csNoMatch
  2092. return
  2093. m.baseTypeMatch = false
  2094. m.typedescMatched = false
  2095. n.sons[a].sons[1] = prepareOperand(c, formal.typ, n.sons[a].sons[1])
  2096. n.sons[a].typ = n.sons[a].sons[1].typ
  2097. var arg = paramTypesMatch(m, formal.typ, n.sons[a].typ,
  2098. n.sons[a].sons[1], n.sons[a].sons[1])
  2099. if arg == nil:
  2100. m.state = csNoMatch
  2101. m.firstMismatch = a
  2102. return
  2103. checkConstraint(n.sons[a].sons[1])
  2104. if m.baseTypeMatch:
  2105. #assert(container == nil)
  2106. container = newNodeIT(nkBracket, n.sons[a].info, arrayConstr(c, arg))
  2107. addSon(container, arg)
  2108. setSon(m.call, formal.position + 1, container)
  2109. if f != formalLen - 1: container = nil
  2110. else:
  2111. setSon(m.call, formal.position + 1, arg)
  2112. inc f
  2113. else:
  2114. # unnamed param
  2115. if f >= formalLen:
  2116. # too many arguments?
  2117. if tfVarargs in m.callee.flags:
  2118. # is ok... but don't increment any counters...
  2119. # we have no formal here to snoop at:
  2120. n.sons[a] = prepareOperand(c, n.sons[a])
  2121. if skipTypes(n.sons[a].typ, abstractVar-{tyTypeDesc}).kind==tyString:
  2122. addSon(m.call, implicitConv(nkHiddenStdConv,
  2123. getSysType(c.graph, n.sons[a].info, tyCString),
  2124. copyTree(n.sons[a]), m, c))
  2125. else:
  2126. addSon(m.call, copyTree(n.sons[a]))
  2127. elif formal != nil and formal.typ.kind == tyVarargs:
  2128. # beware of the side-effects in 'prepareOperand'! So only do it for
  2129. # varargs matching. See tests/metatype/tstatic_overloading.
  2130. m.baseTypeMatch = false
  2131. m.typedescMatched = false
  2132. incl(marker, formal.position)
  2133. n.sons[a] = prepareOperand(c, formal.typ, n.sons[a])
  2134. var arg = paramTypesMatch(m, formal.typ, n.sons[a].typ,
  2135. n.sons[a], nOrig.sons[a])
  2136. if arg != nil and m.baseTypeMatch and container != nil:
  2137. addSon(container, arg)
  2138. incrIndexType(container.typ)
  2139. checkConstraint(n.sons[a])
  2140. else:
  2141. m.state = csNoMatch
  2142. return
  2143. else:
  2144. m.state = csNoMatch
  2145. return
  2146. else:
  2147. if m.callee.n.sons[f].kind != nkSym:
  2148. internalError(c.config, n.sons[a].info, "matches")
  2149. return
  2150. formal = m.callee.n.sons[f].sym
  2151. if containsOrIncl(marker, formal.position) and container.isNil:
  2152. # already in namedParams: (see above remark)
  2153. when false: localError(n.sons[a].info, errCannotBindXTwice, formal.name.s)
  2154. m.state = csNoMatch
  2155. return
  2156. if formal.typ.isVarargsUntyped:
  2157. if container.isNil:
  2158. container = newNodeIT(nkArgList, n.sons[a].info, arrayConstr(c, n.info))
  2159. setSon(m.call, formal.position + 1, container)
  2160. else:
  2161. incrIndexType(container.typ)
  2162. addSon(container, n.sons[a])
  2163. else:
  2164. m.baseTypeMatch = false
  2165. m.typedescMatched = false
  2166. n.sons[a] = prepareOperand(c, formal.typ, n.sons[a])
  2167. var arg = paramTypesMatch(m, formal.typ, n.sons[a].typ,
  2168. n.sons[a], nOrig.sons[a])
  2169. if arg == nil:
  2170. m.state = csNoMatch
  2171. m.firstMismatch = f
  2172. return
  2173. if m.baseTypeMatch:
  2174. assert formal.typ.kind == tyVarargs
  2175. #assert(container == nil)
  2176. if container.isNil:
  2177. container = newNodeIT(nkBracket, n.sons[a].info, arrayConstr(c, arg))
  2178. container.typ.flags.incl tfVarargs
  2179. else:
  2180. incrIndexType(container.typ)
  2181. addSon(container, arg)
  2182. setSon(m.call, formal.position + 1,
  2183. implicitConv(nkHiddenStdConv, formal.typ, container, m, c))
  2184. #if f != formalLen - 1: container = nil
  2185. # pick the formal from the end, so that 'x, y, varargs, z' works:
  2186. f = max(f, formalLen - n.len + a + 1)
  2187. elif formal.typ.kind != tyVarargs or container == nil:
  2188. setSon(m.call, formal.position + 1, arg)
  2189. inc(f)
  2190. container = nil
  2191. else:
  2192. # we end up here if the argument can be converted into the varargs
  2193. # formal (eg. seq[T] -> varargs[T]) but we have already instantiated
  2194. # a container
  2195. assert arg.kind == nkHiddenStdConv
  2196. localError(c.config, n.sons[a].info, "cannot convert $1 to $2" % [
  2197. typeToString(n.sons[a].typ), typeToString(formal.typ) ])
  2198. m.state = csNoMatch
  2199. return
  2200. checkConstraint(n.sons[a])
  2201. inc(a)
  2202. proc semFinishOperands*(c: PContext, n: PNode) =
  2203. # this needs to be called to ensure that after overloading resolution every
  2204. # argument has been sem'checked:
  2205. for i in 1 ..< n.len:
  2206. n.sons[i] = prepareOperand(c, n.sons[i])
  2207. proc partialMatch*(c: PContext, n, nOrig: PNode, m: var TCandidate) =
  2208. # for 'suggest' support:
  2209. var marker = initIntSet()
  2210. matchesAux(c, n, nOrig, m, marker)
  2211. proc matches*(c: PContext, n, nOrig: PNode, m: var TCandidate) =
  2212. if m.magic in {mArrGet, mArrPut}:
  2213. m.state = csMatch
  2214. m.call = n
  2215. # Note the following doesn't work as it would produce ambiguities.
  2216. # Instead we patch system.nim, see bug #8049.
  2217. when false:
  2218. inc m.genericMatches
  2219. inc m.exactMatches
  2220. return
  2221. var marker = initIntSet()
  2222. matchesAux(c, n, nOrig, m, marker)
  2223. if m.state == csNoMatch: return
  2224. # check that every formal parameter got a value:
  2225. var f = 1
  2226. while f < sonsLen(m.callee.n):
  2227. var formal = m.callee.n.sons[f].sym
  2228. if not containsOrIncl(marker, formal.position):
  2229. if formal.ast == nil:
  2230. if formal.typ.kind == tyVarargs:
  2231. # For consistency with what happens in `matchesAux` select the
  2232. # container node kind accordingly
  2233. let cnKind = if formal.typ.isVarargsUntyped: nkArgList else: nkBracket
  2234. var container = newNodeIT(cnKind, n.info, arrayConstr(c, n.info))
  2235. setSon(m.call, formal.position + 1,
  2236. implicitConv(nkHiddenStdConv, formal.typ, container, m, c))
  2237. else:
  2238. # no default value
  2239. m.state = csNoMatch
  2240. m.firstMismatch = f
  2241. break
  2242. else:
  2243. if formal.ast.kind == nkEmpty:
  2244. # The default param value is set to empty in `instantiateProcType`
  2245. # when the type of the default expression doesn't match the type
  2246. # of the instantiated proc param:
  2247. localError(c.config, m.call.info,
  2248. ("The default parameter '$1' has incompatible type " &
  2249. "with the explicitly requested proc instantiation") %
  2250. formal.name.s)
  2251. if nfDefaultRefsParam in formal.ast.flags:
  2252. m.call.flags.incl nfDefaultRefsParam
  2253. var def = copyTree(formal.ast)
  2254. if def.kind == nkNilLit:
  2255. def = implicitConv(nkHiddenStdConv, formal.typ, def, m, c)
  2256. if {tfImplicitTypeParam, tfGenericTypeParam} * formal.typ.flags != {}:
  2257. put(m, formal.typ, def.typ)
  2258. def.flags.incl nfDefaultParam
  2259. setSon(m.call, formal.position + 1, def)
  2260. inc(f)
  2261. # forget all inferred types if the overload matching failed
  2262. if m.state == csNoMatch:
  2263. for t in m.inferredTypes:
  2264. if t.sonsLen > 1: t.sons.setLen 1
  2265. proc argtypeMatches*(c: PContext, f, a: PType, fromHlo = false): bool =
  2266. var m: TCandidate
  2267. initCandidate(c, m, f)
  2268. let res = paramTypesMatch(m, f, a, c.graph.emptyNode, nil)
  2269. #instantiateGenericConverters(c, res, m)
  2270. # XXX this is used by patterns.nim too; I think it's better to not
  2271. # instantiate generic converters for that
  2272. if not fromHlo:
  2273. res != nil
  2274. else:
  2275. # pattern templates do not allow for conversions except from int literal
  2276. res != nil and m.convMatches == 0 and m.intConvMatches in [0, 256]
  2277. proc instTypeBoundOp*(c: PContext; dc: PSym; t: PType; info: TLineInfo;
  2278. op: TTypeAttachedOp; col: int): PSym {.procvar.} =
  2279. var m: TCandidate
  2280. initCandidate(c, m, dc.typ)
  2281. if col >= dc.typ.len:
  2282. localError(c.config, info, "cannot instantiate: '" & dc.name.s & "'")
  2283. return nil
  2284. var f = dc.typ.sons[col]
  2285. if op == attachedDeepCopy:
  2286. if f.kind in {tyRef, tyPtr}: f = f.lastSon
  2287. else:
  2288. if f.kind == tyVar: f = f.lastSon
  2289. if typeRel(m, f, t) == isNone:
  2290. localError(c.config, info, "cannot instantiate: '" & dc.name.s & "'")
  2291. else:
  2292. result = c.semGenerateInstance(c, dc, m.bindings, info)
  2293. if op == attachedDeepCopy:
  2294. assert sfFromGeneric in result.flags
  2295. include suggest
  2296. when not declared(tests):
  2297. template tests(s: untyped) = discard
  2298. tests:
  2299. var dummyOwner = newSym(skModule, getIdent("test_module"), nil, UnknownLineInfo())
  2300. proc `|` (t1, t2: PType): PType =
  2301. result = newType(tyOr, dummyOwner)
  2302. result.rawAddSon(t1)
  2303. result.rawAddSon(t2)
  2304. proc `&` (t1, t2: PType): PType =
  2305. result = newType(tyAnd, dummyOwner)
  2306. result.rawAddSon(t1)
  2307. result.rawAddSon(t2)
  2308. proc `!` (t: PType): PType =
  2309. result = newType(tyNot, dummyOwner)
  2310. result.rawAddSon(t)
  2311. proc seq(t: PType): PType =
  2312. result = newType(tySequence, dummyOwner)
  2313. result.rawAddSon(t)
  2314. proc array(x: int, t: PType): PType =
  2315. result = newType(tyArray, dummyOwner)
  2316. var n = newNodeI(nkRange, UnknownLineInfo())
  2317. addSon(n, newIntNode(nkIntLit, 0))
  2318. addSon(n, newIntNode(nkIntLit, x))
  2319. let range = newType(tyRange, dummyOwner)
  2320. result.rawAddSon(range)
  2321. result.rawAddSon(t)
  2322. suite "type classes":
  2323. let
  2324. int = newType(tyInt, dummyOwner)
  2325. float = newType(tyFloat, dummyOwner)
  2326. string = newType(tyString, dummyOwner)
  2327. ordinal = newType(tyOrdinal, dummyOwner)
  2328. any = newType(tyAnything, dummyOwner)
  2329. number = int | float
  2330. var TFoo = newType(tyObject, dummyOwner)
  2331. TFoo.sym = newSym(skType, getIdent"TFoo", dummyOwner, UnknownLineInfo())
  2332. var T1 = newType(tyGenericParam, dummyOwner)
  2333. T1.sym = newSym(skType, getIdent"T1", dummyOwner, UnknownLineInfo())
  2334. T1.sym.position = 0
  2335. var T2 = newType(tyGenericParam, dummyOwner)
  2336. T2.sym = newSym(skType, getIdent"T2", dummyOwner, UnknownLineInfo())
  2337. T2.sym.position = 1
  2338. setup:
  2339. var c: TCandidate
  2340. initCandidate(nil, c, nil)
  2341. template yes(x, y) =
  2342. test astToStr(x) & " is " & astToStr(y):
  2343. check typeRel(c, y, x) == isGeneric
  2344. template no(x, y) =
  2345. test astToStr(x) & " is not " & astToStr(y):
  2346. check typeRel(c, y, x) == isNone
  2347. yes seq(any), array(10, int) | seq(any)
  2348. # Sure, seq[any] is directly included
  2349. yes seq(int), seq(any)
  2350. yes seq(int), seq(number)
  2351. # Sure, the int sequence is certainly
  2352. # part of the number sequences (and all sequences)
  2353. no seq(any), seq(float)
  2354. # Nope, seq[any] includes types that are not seq[float] (e.g. seq[int])
  2355. yes seq(int|string), seq(any)
  2356. # Sure
  2357. yes seq(int&string), seq(any)
  2358. # Again
  2359. yes seq(int&string), seq(int)
  2360. # A bit more complicated
  2361. # seq[int&string] is not a real type, but it's analogous to
  2362. # seq[Sortable and Iterable], which is certainly a subset of seq[Sortable]
  2363. no seq(int|string), seq(int|float)
  2364. # Nope, seq[string] is not included in not included in
  2365. # the seq[int|float] set
  2366. no seq(!(int|string)), seq(string)
  2367. # A sequence that is neither seq[int] or seq[string]
  2368. # is obviously not seq[string]
  2369. no seq(!int), seq(number)
  2370. # Now your head should start to hurt a bit
  2371. # A sequence that is not seq[int] is not necessarily a number sequence
  2372. # it could well be seq[string] for example
  2373. yes seq(!(int|string)), seq(!string)
  2374. # all sequnece types besides seq[int] and seq[string]
  2375. # are subset of all sequence types that are not seq[string]
  2376. no seq(!(int|string)), seq(!(string|TFoo))
  2377. # Nope, seq[TFoo] is included in the first set, but not in the second
  2378. no seq(!string), seq(!number)
  2379. # Nope, seq[int] in included in the first set, but not in the second
  2380. yes seq(!number), seq(any)
  2381. yes seq(!int), seq(any)
  2382. no seq(any), seq(!any)
  2383. no seq(!int), seq(!any)
  2384. yes int, ordinal
  2385. no string, ordinal