semexprs.nim 124 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286
  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 does the semantic checking for expressions
  10. # included from sem.nim
  11. when defined(nimCompilerStacktraceHints):
  12. import std/stackframes
  13. const
  14. errExprXHasNoType = "expression '$1' has no type (or is ambiguous)"
  15. errXExpectsTypeOrValue = "'$1' expects a type or value"
  16. errVarForOutParamNeededX = "for a 'var' type a variable needs to be passed; but '$1' is immutable"
  17. errXStackEscape = "address of '$1' may not escape its stack frame"
  18. errExprHasNoAddress = "expression has no address"
  19. errCannotInterpretNodeX = "cannot evaluate '$1'"
  20. errNamedExprExpected = "named expression expected"
  21. errNamedExprNotAllowed = "named expression not allowed here"
  22. errFieldInitTwice = "field initialized twice: '$1'"
  23. errUndeclaredFieldX = "undeclared field: '$1'"
  24. proc semTemplateExpr(c: PContext, n: PNode, s: PSym,
  25. flags: TExprFlags = {}; expectedType: PType = nil): PNode =
  26. rememberExpansion(c, n.info, s)
  27. let info = getCallLineInfo(n)
  28. markUsed(c, info, s)
  29. onUse(info, s)
  30. # Note: This is n.info on purpose. It prevents template from creating an info
  31. # context when called from an another template
  32. pushInfoContext(c.config, n.info, s.detailedInfo)
  33. result = evalTemplate(n, s, getCurrOwner(c), c.config, c.cache,
  34. c.templInstCounter, c.idgen, efFromHlo in flags)
  35. if efNoSemCheck notin flags:
  36. result = semAfterMacroCall(c, n, result, s, flags, expectedType)
  37. popInfoContext(c.config)
  38. # XXX: A more elaborate line info rewrite might be needed
  39. result.info = info
  40. proc semFieldAccess(c: PContext, n: PNode, flags: TExprFlags = {}): PNode
  41. template rejectEmptyNode(n: PNode) =
  42. # No matter what a nkEmpty node is not what we want here
  43. if n.kind == nkEmpty: illFormedAst(n, c.config)
  44. proc semOperand(c: PContext, n: PNode, flags: TExprFlags = {}): PNode =
  45. rejectEmptyNode(n)
  46. # same as 'semExprWithType' but doesn't check for proc vars
  47. result = semExpr(c, n, flags + {efOperand})
  48. if result.typ != nil:
  49. # XXX tyGenericInst here?
  50. if result.typ.kind == tyProc and hasUnresolvedParams(result, {efOperand}):
  51. #and tfUnresolved in result.typ.flags:
  52. localError(c.config, n.info, errProcHasNoConcreteType % n.renderTree)
  53. if result.typ.kind in {tyVar, tyLent}: result = newDeref(result)
  54. elif {efWantStmt, efAllowStmt} * flags != {}:
  55. result.typ = newTypeS(tyVoid, c)
  56. else:
  57. localError(c.config, n.info, errExprXHasNoType %
  58. renderTree(result, {renderNoComments}))
  59. result.typ = errorType(c)
  60. proc semExprCheck(c: PContext, n: PNode, flags: TExprFlags, expectedType: PType = nil): PNode =
  61. rejectEmptyNode(n)
  62. result = semExpr(c, n, flags+{efWantValue}, expectedType)
  63. let
  64. isEmpty = result.kind == nkEmpty
  65. isTypeError = result.typ != nil and result.typ.kind == tyError
  66. if isEmpty or isTypeError:
  67. # bug #12741, redundant error messages are the lesser evil here:
  68. localError(c.config, n.info, errExprXHasNoType %
  69. renderTree(result, {renderNoComments}))
  70. if isEmpty:
  71. # do not produce another redundant error message:
  72. result = errorNode(c, n)
  73. proc ambiguousSymChoice(c: PContext, orig, n: PNode): PNode =
  74. let first = n[0].sym
  75. if first.kind == skEnumField:
  76. # choose the first resolved enum field, i.e. the latest in scope
  77. # to mirror behavior before overloadable enums
  78. if hintAmbiguousEnum in c.config.notes:
  79. var err = "ambiguous enum field '" & first.name.s &
  80. "' assumed to be of type " & typeToString(first.typ) &
  81. " -- use one of the following:\n"
  82. for child in n:
  83. let candidate = child.sym
  84. err.add " " & candidate.owner.name.s & "." & candidate.name.s & "\n"
  85. message(c.config, orig.info, hintAmbiguousEnum, err)
  86. result = n[0]
  87. else:
  88. var err = "ambiguous identifier '" & first.name.s &
  89. "' -- use one of the following:\n"
  90. for child in n:
  91. let candidate = child.sym
  92. err.add " " & candidate.owner.name.s & "." & candidate.name.s
  93. err.add ": " & typeToString(candidate.typ) & "\n"
  94. localError(c.config, orig.info, err)
  95. n.typ = errorType(c)
  96. result = n
  97. proc semExprWithType(c: PContext, n: PNode, flags: TExprFlags = {}, expectedType: PType = nil): PNode =
  98. result = semExprCheck(c, n, flags, expectedType)
  99. if result.typ == nil and efInTypeof in flags:
  100. result.typ = c.voidType
  101. elif (result.typ == nil or result.typ.kind == tyNone) and
  102. efTypeAllowed in flags and
  103. result.kind == nkClosedSymChoice and result.len > 0:
  104. result = ambiguousSymChoice(c, n, result)
  105. elif result.typ == nil or result.typ == c.enforceVoidContext:
  106. localError(c.config, n.info, errExprXHasNoType %
  107. renderTree(result, {renderNoComments}))
  108. result.typ = errorType(c)
  109. elif result.typ.kind == tyError:
  110. # associates the type error to the current owner
  111. result.typ = errorType(c)
  112. else:
  113. if result.typ.kind in {tyVar, tyLent}: result = newDeref(result)
  114. proc semExprNoDeref(c: PContext, n: PNode, flags: TExprFlags = {}): PNode =
  115. result = semExprCheck(c, n, flags)
  116. if result.typ == nil:
  117. localError(c.config, n.info, errExprXHasNoType %
  118. renderTree(result, {renderNoComments}))
  119. result.typ = errorType(c)
  120. proc semSymGenericInstantiation(c: PContext, n: PNode, s: PSym): PNode =
  121. result = symChoice(c, n, s, scClosed)
  122. proc inlineConst(c: PContext, n: PNode, s: PSym): PNode {.inline.} =
  123. result = copyTree(s.astdef)
  124. if result.isNil:
  125. localError(c.config, n.info, "constant of type '" & typeToString(s.typ) & "' has no value")
  126. result = newSymNode(s)
  127. else:
  128. result.typ = s.typ
  129. result.info = n.info
  130. type
  131. TConvStatus = enum
  132. convOK,
  133. convNotNeedeed,
  134. convNotLegal,
  135. convNotInRange
  136. proc checkConversionBetweenObjects(castDest, src: PType; pointers: int): TConvStatus =
  137. let diff = inheritanceDiff(castDest, src)
  138. return if diff == high(int) or (pointers > 1 and diff != 0):
  139. convNotLegal
  140. else:
  141. convOK
  142. const
  143. IntegralTypes = {tyBool, tyEnum, tyChar, tyInt..tyUInt64}
  144. proc checkConvertible(c: PContext, targetTyp: PType, src: PNode): TConvStatus =
  145. let srcTyp = src.typ.skipTypes({tyStatic})
  146. result = convOK
  147. if sameType(targetTyp, srcTyp) and targetTyp.sym == srcTyp.sym:
  148. # don't annoy conversions that may be needed on another processor:
  149. if targetTyp.kind notin IntegralTypes+{tyRange}:
  150. result = convNotNeedeed
  151. return
  152. var d = skipTypes(targetTyp, abstractVar)
  153. var s = srcTyp
  154. if s.kind in tyUserTypeClasses and s.isResolvedUserTypeClass:
  155. s = s.lastSon
  156. s = skipTypes(s, abstractVar-{tyTypeDesc, tyOwned})
  157. if s.kind == tyOwned and d.kind != tyOwned:
  158. s = s.lastSon
  159. var pointers = 0
  160. while (d != nil) and (d.kind in {tyPtr, tyRef, tyOwned}):
  161. if s.kind == tyOwned and d.kind != tyOwned:
  162. s = s.lastSon
  163. elif d.kind != s.kind:
  164. break
  165. else:
  166. d = d.lastSon
  167. s = s.lastSon
  168. inc pointers
  169. let targetBaseTyp = skipTypes(targetTyp, abstractVarRange)
  170. let srcBaseTyp = skipTypes(srcTyp, abstractVarRange-{tyTypeDesc})
  171. if d == nil:
  172. result = convNotLegal
  173. elif d.skipTypes(abstractInst).kind == tyObject and s.skipTypes(abstractInst).kind == tyObject:
  174. result = checkConversionBetweenObjects(d.skipTypes(abstractInst), s.skipTypes(abstractInst), pointers)
  175. elif (targetBaseTyp.kind in IntegralTypes) and
  176. (srcBaseTyp.kind in IntegralTypes):
  177. if targetTyp.kind == tyEnum and srcBaseTyp.kind == tyEnum:
  178. message(c.config, src.info, warnSuspiciousEnumConv, "suspicious code: enum to enum conversion")
  179. # `elif` would be incorrect here
  180. if targetTyp.kind == tyBool:
  181. discard "convOk"
  182. elif targetTyp.isOrdinalType:
  183. if src.kind in nkCharLit..nkUInt64Lit and
  184. src.getInt notin firstOrd(c.config, targetTyp)..lastOrd(c.config, targetTyp):
  185. result = convNotInRange
  186. elif src.kind in nkFloatLit..nkFloat64Lit and
  187. (classify(src.floatVal) in {fcNan, fcNegInf, fcInf} or
  188. src.floatVal.int64 notin firstOrd(c.config, targetTyp)..lastOrd(c.config, targetTyp)):
  189. result = convNotInRange
  190. elif targetBaseTyp.kind in tyFloat..tyFloat64:
  191. if src.kind in nkFloatLit..nkFloat64Lit and
  192. not floatRangeCheck(src.floatVal, targetTyp):
  193. result = convNotInRange
  194. elif src.kind in nkCharLit..nkUInt64Lit and
  195. not floatRangeCheck(src.intVal.float, targetTyp):
  196. result = convNotInRange
  197. else:
  198. # we use d, s here to speed up that operation a bit:
  199. case cmpTypes(c, d, s)
  200. of isNone, isGeneric:
  201. if not compareTypes(targetTyp.skipTypes(abstractVar), srcTyp.skipTypes({tyOwned}), dcEqIgnoreDistinct):
  202. result = convNotLegal
  203. else:
  204. discard
  205. proc isCastable(c: PContext; dst, src: PType, info: TLineInfo): bool =
  206. ## Checks whether the source type can be cast to the destination type.
  207. ## Casting is very unrestrictive; casts are allowed as long as
  208. ## dst.size >= src.size, and typeAllowed(dst, skParam)
  209. #const
  210. # castableTypeKinds = {tyInt, tyPtr, tyRef, tyCstring, tyString,
  211. # tySequence, tyPointer, tyNil, tyOpenArray,
  212. # tyProc, tySet, tyEnum, tyBool, tyChar}
  213. let src = src.skipTypes(tyUserTypeClasses)
  214. if skipTypes(dst, abstractInst-{tyOpenArray}).kind == tyOpenArray:
  215. return false
  216. if skipTypes(src, abstractInst-{tyTypeDesc}).kind == tyTypeDesc:
  217. return false
  218. if skipTypes(dst, abstractInst).kind == tyBuiltInTypeClass:
  219. return false
  220. let conf = c.config
  221. if conf.selectedGC in {gcArc, gcOrc}:
  222. let d = skipTypes(dst, abstractInst)
  223. let s = skipTypes(src, abstractInst)
  224. if d.kind == tyRef and s.kind == tyRef and s[0].isFinal != d[0].isFinal:
  225. return false
  226. elif d.kind in IntegralTypes and s.kind in {tyString, tySequence}:
  227. return false
  228. var dstSize, srcSize: BiggestInt
  229. dstSize = computeSize(conf, dst)
  230. srcSize = computeSize(conf, src)
  231. if dstSize == -3 or srcSize == -3: # szUnknownSize
  232. # The Nim compiler can't detect if it's legal or not.
  233. # Just assume the programmer knows what he is doing.
  234. return true
  235. if dstSize < 0:
  236. return false
  237. elif srcSize < 0:
  238. return false
  239. elif typeAllowed(dst, skParam, c, {taIsCastable}) != nil:
  240. return false
  241. elif dst.kind == tyProc and dst.callConv == ccClosure:
  242. return src.kind == tyProc and src.callConv == ccClosure
  243. else:
  244. result = (dstSize >= srcSize) or
  245. (skipTypes(dst, abstractInst).kind in IntegralTypes) or
  246. (skipTypes(src, abstractInst-{tyTypeDesc}).kind in IntegralTypes)
  247. if result and (dstSize > srcSize):
  248. var warnMsg = "target type is larger than source type"
  249. warnMsg.add("\n target type: '$1' ($2)" % [$dst, if dstSize == 1: "1 byte" else: $dstSize & " bytes"])
  250. warnMsg.add("\n source type: '$1' ($2)" % [$src, if srcSize == 1: "1 byte" else: $srcSize & " bytes"])
  251. message(conf, info, warnCastSizes, warnMsg)
  252. if result and src.kind == tyNil:
  253. return dst.size <= conf.target.ptrSize
  254. proc isSymChoice(n: PNode): bool {.inline.} =
  255. result = n.kind in nkSymChoices
  256. proc maybeLiftType(t: var PType, c: PContext, info: TLineInfo) =
  257. # XXX: liftParamType started to perform addDecl
  258. # we could do that instead in semTypeNode by snooping for added
  259. # gnrc. params, then it won't be necessary to open a new scope here
  260. openScope(c)
  261. var lifted = liftParamType(c, skType, newNodeI(nkArgList, info),
  262. t, ":anon", info)
  263. closeScope(c)
  264. if lifted != nil: t = lifted
  265. proc isOwnedSym(c: PContext; n: PNode): bool =
  266. let s = qualifiedLookUp(c, n, {})
  267. result = s != nil and sfSystemModule in s.owner.flags and s.name.s == "owned"
  268. proc semConv(c: PContext, n: PNode; expectedType: PType = nil): PNode =
  269. if n.len != 2:
  270. localError(c.config, n.info, "a type conversion takes exactly one argument")
  271. return n
  272. result = newNodeI(nkConv, n.info)
  273. var targetType = semTypeNode(c, n[0], nil)
  274. case targetType.skipTypes({tyDistinct}).kind
  275. of tyTypeDesc:
  276. internalAssert c.config, targetType.len > 0
  277. if targetType.base.kind == tyNone:
  278. return semTypeOf(c, n)
  279. else:
  280. targetType = targetType.base
  281. of tyStatic:
  282. var evaluated = semStaticExpr(c, n[1], expectedType)
  283. if evaluated.kind == nkType or evaluated.typ.kind == tyTypeDesc:
  284. result = n
  285. result.typ = c.makeTypeDesc semStaticType(c, evaluated, nil)
  286. return
  287. elif targetType.base.kind == tyNone:
  288. return evaluated
  289. else:
  290. targetType = targetType.base
  291. of tyAnything, tyUntyped, tyTyped:
  292. localError(c.config, n.info, "illegal type conversion to '$1'" % typeToString(targetType))
  293. else: discard
  294. maybeLiftType(targetType, c, n[0].info)
  295. if targetType.kind in {tySink, tyLent} or isOwnedSym(c, n[0]):
  296. let baseType = semTypeNode(c, n[1], nil).skipTypes({tyTypeDesc})
  297. let t = newTypeS(targetType.kind, c)
  298. if targetType.kind == tyOwned:
  299. t.flags.incl tfHasOwned
  300. t.rawAddSonNoPropagationOfTypeFlags baseType
  301. result = newNodeI(nkType, n.info)
  302. result.typ = makeTypeDesc(c, t)
  303. return
  304. result.add copyTree(n[0])
  305. # special case to make MyObject(x = 3) produce a nicer error message:
  306. if n[1].kind == nkExprEqExpr and
  307. targetType.skipTypes(abstractPtrs).kind == tyObject:
  308. localError(c.config, n.info, "object construction uses ':', not '='")
  309. var op = semExprWithType(c, n[1])
  310. if targetType.kind != tyGenericParam and targetType.isMetaType:
  311. let final = inferWithMetatype(c, targetType, op, true)
  312. result.add final
  313. result.typ = final.typ
  314. return
  315. result.typ = targetType
  316. # XXX op is overwritten later on, this is likely added too early
  317. # here or needs to be overwritten too then.
  318. result.add op
  319. if targetType.kind == tyGenericParam:
  320. result.typ = makeTypeFromExpr(c, copyTree(result))
  321. return result
  322. if not isSymChoice(op):
  323. let status = checkConvertible(c, result.typ, op)
  324. case status
  325. of convOK:
  326. # handle SomeProcType(SomeGenericProc)
  327. if op.kind == nkSym and op.sym.isGenericRoutine:
  328. result[1] = fitNode(c, result.typ, result[1], result.info)
  329. elif op.kind in {nkPar, nkTupleConstr} and targetType.kind == tyTuple:
  330. op = fitNode(c, targetType, op, result.info)
  331. of convNotNeedeed:
  332. message(c.config, n.info, hintConvFromXtoItselfNotNeeded, result.typ.typeToString)
  333. of convNotLegal:
  334. result = fitNode(c, result.typ, result[1], result.info)
  335. if result == nil:
  336. localError(c.config, n.info, "illegal conversion from '$1' to '$2'" %
  337. [op.typ.typeToString, result.typ.typeToString])
  338. of convNotInRange:
  339. let value =
  340. if op.kind in {nkCharLit..nkUInt64Lit}: $op.getInt else: $op.getFloat
  341. localError(c.config, n.info, errGenerated, value & " can't be converted to " &
  342. result.typ.typeToString)
  343. else:
  344. for i in 0..<op.len:
  345. let it = op[i]
  346. let status = checkConvertible(c, result.typ, it)
  347. if status in {convOK, convNotNeedeed}:
  348. markUsed(c, n.info, it.sym)
  349. onUse(n.info, it.sym)
  350. markIndirect(c, it.sym)
  351. return it
  352. errorUseQualifier(c, n.info, op[0].sym)
  353. proc semCast(c: PContext, n: PNode): PNode =
  354. ## Semantically analyze a casting ("cast[type](param)")
  355. checkSonsLen(n, 2, c.config)
  356. let targetType = semTypeNode(c, n[0], nil)
  357. let castedExpr = semExprWithType(c, n[1])
  358. if castedExpr.kind == nkClosedSymChoice:
  359. errorUseQualifier(c, n[1].info, castedExpr)
  360. if targetType == nil:
  361. localError(c.config, n.info, "Invalid usage of cast, cast requires a type to convert to, e.g., cast[int](0d).")
  362. if tfHasMeta in targetType.flags:
  363. localError(c.config, n[0].info, "cannot cast to a non concrete type: '$1'" % $targetType)
  364. if not isCastable(c, targetType, castedExpr.typ, n.info):
  365. localError(c.config, n.info, "expression cannot be cast to '$1'" % $targetType)
  366. result = newNodeI(nkCast, n.info)
  367. result.typ = targetType
  368. result.add copyTree(n[0])
  369. result.add castedExpr
  370. proc semLowHigh(c: PContext, n: PNode, m: TMagic): PNode =
  371. const
  372. opToStr: array[mLow..mHigh, string] = ["low", "high"]
  373. if n.len != 2:
  374. localError(c.config, n.info, errXExpectsTypeOrValue % opToStr[m])
  375. else:
  376. n[1] = semExprWithType(c, n[1], {efDetermineType})
  377. var typ = skipTypes(n[1].typ, abstractVarRange + {tyTypeDesc, tyUserTypeClassInst})
  378. case typ.kind
  379. of tySequence, tyString, tyCstring, tyOpenArray, tyVarargs:
  380. n.typ = getSysType(c.graph, n.info, tyInt)
  381. of tyArray:
  382. n.typ = typ[0] # indextype
  383. if n.typ.kind == tyRange and emptyRange(n.typ.n[0], n.typ.n[1]): #Invalid range
  384. n.typ = getSysType(c.graph, n.info, tyInt)
  385. of tyInt..tyInt64, tyChar, tyBool, tyEnum, tyUInt..tyUInt64, tyFloat..tyFloat64:
  386. n.typ = n[1].typ.skipTypes({tyTypeDesc})
  387. of tyGenericParam:
  388. # prepare this for resolving in semtypinst:
  389. # we must use copyTree here in order to avoid creating a cycle
  390. # that could easily turn into an infinite recursion in semtypinst
  391. n.typ = makeTypeFromExpr(c, n.copyTree)
  392. else:
  393. localError(c.config, n.info, "invalid argument for: " & opToStr[m])
  394. result = n
  395. proc fixupStaticType(c: PContext, n: PNode) =
  396. # This proc can be applied to evaluated expressions to assign
  397. # them a static type.
  398. #
  399. # XXX: with implicit static, this should not be necessary,
  400. # because the output type of operations such as `semConstExpr`
  401. # should be a static type (as well as the type of any other
  402. # expression that can be implicitly evaluated). For now, we
  403. # apply this measure only in code that is enlightened to work
  404. # with static types.
  405. if n.typ.kind != tyStatic:
  406. n.typ = newTypeWithSons(getCurrOwner(c), tyStatic, @[n.typ], c.idgen)
  407. n.typ.n = n # XXX: cycles like the one here look dangerous.
  408. # Consider using `n.copyTree`
  409. proc isOpImpl(c: PContext, n: PNode, flags: TExprFlags): PNode =
  410. internalAssert c.config,
  411. n.len == 3 and
  412. n[1].typ != nil and
  413. n[2].kind in {nkStrLit..nkTripleStrLit, nkType}
  414. var
  415. res = false
  416. t1 = n[1].typ
  417. t2 = n[2].typ
  418. if t1.kind == tyTypeDesc and t2.kind != tyTypeDesc:
  419. t1 = t1.base
  420. if n[2].kind in {nkStrLit..nkTripleStrLit}:
  421. case n[2].strVal.normalize
  422. of "closure":
  423. let t = skipTypes(t1, abstractRange)
  424. res = t.kind == tyProc and
  425. t.callConv == ccClosure
  426. of "iterator":
  427. # holdover from when `is iterator` didn't work
  428. let t = skipTypes(t1, abstractRange)
  429. res = t.kind == tyProc and
  430. t.callConv == ccClosure and
  431. tfIterator in t.flags
  432. else:
  433. res = false
  434. else:
  435. if t1.skipTypes({tyGenericInst, tyAlias, tySink, tyDistinct}).kind != tyGenericBody:
  436. maybeLiftType(t2, c, n.info)
  437. else:
  438. #[
  439. for this case:
  440. type Foo = object[T]
  441. Foo is Foo
  442. ]#
  443. discard
  444. var m = newCandidate(c, t2)
  445. if efExplain in flags:
  446. m.diagnostics = @[]
  447. m.diagnosticsEnabled = true
  448. res = typeRel(m, t2, t1) >= isSubtype # isNone
  449. # `res = sameType(t1, t2)` would be wrong, e.g. for `int is (int|float)`
  450. result = newIntNode(nkIntLit, ord(res))
  451. result.typ = n.typ
  452. proc semIs(c: PContext, n: PNode, flags: TExprFlags): PNode =
  453. if n.len != 3:
  454. localError(c.config, n.info, "'is' operator takes 2 arguments")
  455. let boolType = getSysType(c.graph, n.info, tyBool)
  456. result = n
  457. n.typ = boolType
  458. var liftLhs = true
  459. n[1] = semExprWithType(c, n[1], {efDetermineType, efWantIterator})
  460. if n[2].kind notin {nkStrLit..nkTripleStrLit}:
  461. let t2 = semTypeNode(c, n[2], nil)
  462. n[2] = newNodeIT(nkType, n[2].info, t2)
  463. if t2.kind == tyStatic:
  464. let evaluated = tryConstExpr(c, n[1])
  465. if evaluated != nil:
  466. c.fixupStaticType(evaluated)
  467. n[1] = evaluated
  468. else:
  469. result = newIntNode(nkIntLit, 0)
  470. result.typ = boolType
  471. return
  472. elif t2.kind == tyTypeDesc and
  473. (t2.base.kind == tyNone or tfExplicit in t2.flags):
  474. # When the right-hand side is an explicit type, we must
  475. # not allow regular values to be matched against the type:
  476. liftLhs = false
  477. else:
  478. n[2] = semExpr(c, n[2])
  479. var lhsType = n[1].typ
  480. if lhsType.kind != tyTypeDesc:
  481. if liftLhs:
  482. n[1] = makeTypeSymNode(c, lhsType, n[1].info)
  483. lhsType = n[1].typ
  484. else:
  485. if lhsType.base.kind == tyNone or
  486. (c.inGenericContext > 0 and lhsType.base.containsGenericType):
  487. # BUGFIX: don't evaluate this too early: ``T is void``
  488. return
  489. result = isOpImpl(c, n, flags)
  490. proc semOpAux(c: PContext, n: PNode) =
  491. const flags = {efDetermineType}
  492. for i in 1..<n.len:
  493. var a = n[i]
  494. if a.kind == nkExprEqExpr and a.len == 2:
  495. let info = a[0].info
  496. a[0] = newIdentNode(considerQuotedIdent(c, a[0], a), info)
  497. a[1] = semExprWithType(c, a[1], flags)
  498. a.typ = a[1].typ
  499. else:
  500. n[i] = semExprWithType(c, a, flags)
  501. proc overloadedCallOpr(c: PContext, n: PNode): PNode =
  502. # quick check if there is *any* () operator overloaded:
  503. var par = getIdent(c.cache, "()")
  504. var amb = false
  505. if searchInScopes(c, par, amb) == nil:
  506. result = nil
  507. else:
  508. result = newNodeI(nkCall, n.info)
  509. result.add newIdentNode(par, n.info)
  510. for i in 0..<n.len: result.add n[i]
  511. result = semExpr(c, result, flags = {efNoUndeclared})
  512. proc changeType(c: PContext; n: PNode, newType: PType, check: bool) =
  513. case n.kind
  514. of nkCurly, nkBracket:
  515. for i in 0..<n.len:
  516. changeType(c, n[i], elemType(newType), check)
  517. of nkPar, nkTupleConstr:
  518. let tup = newType.skipTypes({tyGenericInst, tyAlias, tySink, tyDistinct})
  519. if tup.kind != tyTuple:
  520. if tup.kind == tyObject: return
  521. globalError(c.config, n.info, "no tuple type for constructor")
  522. elif n.len > 0 and n[0].kind == nkExprColonExpr:
  523. # named tuple?
  524. for i in 0..<n.len:
  525. var m = n[i][0]
  526. if m.kind != nkSym:
  527. globalError(c.config, m.info, "invalid tuple constructor")
  528. return
  529. if tup.n != nil:
  530. var f = getSymFromList(tup.n, m.sym.name)
  531. if f == nil:
  532. globalError(c.config, m.info, "unknown identifier: " & m.sym.name.s)
  533. return
  534. changeType(c, n[i][1], f.typ, check)
  535. else:
  536. changeType(c, n[i][1], tup[i], check)
  537. else:
  538. for i in 0..<n.len:
  539. changeType(c, n[i], tup[i], check)
  540. when false:
  541. var m = n[i]
  542. var a = newNodeIT(nkExprColonExpr, m.info, newType[i])
  543. a.add newSymNode(newType.n[i].sym)
  544. a.add m
  545. changeType(m, tup[i], check)
  546. of nkCharLit..nkUInt64Lit:
  547. if check and n.kind != nkUInt64Lit and not sameType(n.typ, newType):
  548. let value = n.intVal
  549. if value < firstOrd(c.config, newType) or value > lastOrd(c.config, newType):
  550. localError(c.config, n.info, "cannot convert " & $value &
  551. " to " & typeToString(newType))
  552. of nkFloatLit..nkFloat64Lit:
  553. if check and not floatRangeCheck(n.floatVal, newType):
  554. localError(c.config, n.info, errFloatToString % [$n.floatVal, typeToString(newType)])
  555. else: discard
  556. n.typ = newType
  557. proc arrayConstrType(c: PContext, n: PNode): PType =
  558. var typ = newTypeS(tyArray, c)
  559. rawAddSon(typ, nil) # index type
  560. if n.len == 0:
  561. rawAddSon(typ, newTypeS(tyEmpty, c)) # needs an empty basetype!
  562. else:
  563. var t = skipTypes(n[0].typ, {tyGenericInst, tyVar, tyLent, tyOrdinal, tyAlias, tySink})
  564. addSonSkipIntLit(typ, t, c.idgen)
  565. typ[0] = makeRangeType(c, 0, n.len - 1, n.info)
  566. result = typ
  567. proc semArrayConstr(c: PContext, n: PNode, flags: TExprFlags; expectedType: PType = nil): PNode =
  568. result = newNodeI(nkBracket, n.info)
  569. result.typ = newTypeS(tyArray, c)
  570. var expectedElementType, expectedIndexType: PType = nil
  571. if expectedType != nil:
  572. let expected = expectedType.skipTypes(abstractRange-{tyDistinct})
  573. case expected.kind
  574. of tyArray:
  575. expectedIndexType = expected[0]
  576. expectedElementType = expected[1]
  577. of tyOpenArray:
  578. expectedElementType = expected[0]
  579. else: discard
  580. rawAddSon(result.typ, nil) # index type
  581. var
  582. firstIndex, lastIndex: Int128
  583. indexType = getSysType(c.graph, n.info, tyInt)
  584. lastValidIndex = lastOrd(c.config, indexType)
  585. if n.len == 0:
  586. rawAddSon(result.typ,
  587. if expectedElementType != nil and
  588. typeAllowed(expectedElementType, skLet, c) == nil:
  589. expectedElementType
  590. else:
  591. newTypeS(tyEmpty, c)) # needs an empty basetype!
  592. lastIndex = toInt128(-1)
  593. else:
  594. var x = n[0]
  595. if x.kind == nkExprColonExpr and x.len == 2:
  596. var idx = semConstExpr(c, x[0], expectedIndexType)
  597. if not isOrdinalType(idx.typ):
  598. localError(c.config, idx.info, "expected ordinal value for array " &
  599. "index, got '$1'" % renderTree(idx))
  600. else:
  601. firstIndex = getOrdValue(idx)
  602. lastIndex = firstIndex
  603. indexType = idx.typ
  604. lastValidIndex = lastOrd(c.config, indexType)
  605. x = x[1]
  606. let yy = semExprWithType(c, x, {efTypeAllowed}, expectedElementType)
  607. var typ = yy.typ
  608. if expectedElementType == nil:
  609. expectedElementType = typ
  610. result.add yy
  611. #var typ = skipTypes(result[0].typ, {tyGenericInst, tyVar, tyLent, tyOrdinal})
  612. for i in 1..<n.len:
  613. if lastIndex == lastValidIndex:
  614. let validIndex = makeRangeType(c, toInt64(firstIndex), toInt64(lastValidIndex), n.info,
  615. indexType)
  616. localError(c.config, n.info, "size of array exceeds range of index " &
  617. "type '$1' by $2 elements" % [typeToString(validIndex), $(n.len-i)])
  618. x = n[i]
  619. if x.kind == nkExprColonExpr and x.len == 2:
  620. var idx = semConstExpr(c, x[0], indexType)
  621. idx = fitNode(c, indexType, idx, x.info)
  622. if lastIndex+1 != getOrdValue(idx):
  623. localError(c.config, x.info, "invalid order in array constructor")
  624. x = x[1]
  625. let xx = semExprWithType(c, x, {efTypeAllowed}, expectedElementType)
  626. result.add xx
  627. typ = commonType(c, typ, xx.typ)
  628. #n[i] = semExprWithType(c, x, {})
  629. #result.add fitNode(c, typ, n[i])
  630. inc(lastIndex)
  631. addSonSkipIntLit(result.typ, typ, c.idgen)
  632. for i in 0..<result.len:
  633. result[i] = fitNode(c, typ, result[i], result[i].info)
  634. result.typ[0] = makeRangeType(c, toInt64(firstIndex), toInt64(lastIndex), n.info,
  635. indexType)
  636. proc fixAbstractType(c: PContext, n: PNode) =
  637. for i in 1..<n.len:
  638. let it = n[i]
  639. if it == nil:
  640. localError(c.config, n.info, "'$1' has nil child at index $2" % [renderTree(n, {renderNoComments}), $i])
  641. return
  642. # do not get rid of nkHiddenSubConv for OpenArrays, the codegen needs it:
  643. if it.kind == nkHiddenSubConv and
  644. skipTypes(it.typ, abstractVar).kind notin {tyOpenArray, tyVarargs}:
  645. if skipTypes(it[1].typ, abstractVar).kind in
  646. {tyNil, tyTuple, tySet} or it[1].isArrayConstr:
  647. var s = skipTypes(it.typ, abstractVar + tyUserTypeClasses)
  648. if s.kind != tyUntyped:
  649. changeType(c, it[1], s, check=true)
  650. n[i] = it[1]
  651. proc isAssignable(c: PContext, n: PNode): TAssignableResult =
  652. result = parampatterns.isAssignable(c.p.owner, n)
  653. proc isUnresolvedSym(s: PSym): bool =
  654. result = s.kind == skGenericParam
  655. if not result and s.typ != nil:
  656. result = tfInferrableStatic in s.typ.flags or
  657. (s.kind == skParam and s.typ.isMetaType) or
  658. (s.kind == skType and
  659. s.typ.flags * {tfGenericTypeParam, tfImplicitTypeParam} != {})
  660. proc hasUnresolvedArgs(c: PContext, n: PNode): bool =
  661. # Checks whether an expression depends on generic parameters that
  662. # don't have bound values yet. E.g. this could happen in situations
  663. # such as:
  664. # type Slot[T] = array[T.size, byte]
  665. # proc foo[T](x: default(T))
  666. #
  667. # Both static parameter and type parameters can be unresolved.
  668. case n.kind
  669. of nkSym:
  670. return isUnresolvedSym(n.sym)
  671. of nkIdent, nkAccQuoted:
  672. let ident = considerQuotedIdent(c, n)
  673. var amb = false
  674. let sym = searchInScopes(c, ident, amb)
  675. if sym != nil:
  676. return isUnresolvedSym(sym)
  677. else:
  678. return false
  679. else:
  680. for i in 0..<n.safeLen:
  681. if hasUnresolvedArgs(c, n[i]): return true
  682. return false
  683. proc newHiddenAddrTaken(c: PContext, n: PNode, isOutParam: bool): PNode =
  684. if n.kind == nkHiddenDeref and not (c.config.backend == backendCpp or
  685. sfCompileToCpp in c.module.flags):
  686. checkSonsLen(n, 1, c.config)
  687. result = n[0]
  688. else:
  689. result = newNodeIT(nkHiddenAddr, n.info, makeVarType(c, n.typ))
  690. result.add n
  691. let aa = isAssignable(c, n)
  692. let sym = getRoot(n)
  693. if aa notin {arLValue, arLocalLValue}:
  694. if aa == arDiscriminant and c.inUncheckedAssignSection > 0:
  695. discard "allow access within a cast(unsafeAssign) section"
  696. elif strictDefs in c.features and aa == arAddressableConst and
  697. sym != nil and sym.kind == skLet and isOutParam:
  698. discard "allow let varaibles to be passed to out parameters"
  699. else:
  700. localError(c.config, n.info, errVarForOutParamNeededX % renderNotLValue(n))
  701. proc analyseIfAddressTaken(c: PContext, n: PNode, isOutParam: bool): PNode =
  702. result = n
  703. case n.kind
  704. of nkSym:
  705. # n.sym.typ can be nil in 'check' mode ...
  706. if n.sym.typ != nil and
  707. skipTypes(n.sym.typ, abstractInst-{tyTypeDesc}).kind notin {tyVar, tyLent}:
  708. incl(n.sym.flags, sfAddrTaken)
  709. result = newHiddenAddrTaken(c, n, isOutParam)
  710. of nkDotExpr:
  711. checkSonsLen(n, 2, c.config)
  712. if n[1].kind != nkSym:
  713. internalError(c.config, n.info, "analyseIfAddressTaken")
  714. return
  715. if skipTypes(n[1].sym.typ, abstractInst-{tyTypeDesc}).kind notin {tyVar, tyLent}:
  716. incl(n[1].sym.flags, sfAddrTaken)
  717. result = newHiddenAddrTaken(c, n, isOutParam)
  718. of nkBracketExpr:
  719. checkMinSonsLen(n, 1, c.config)
  720. if skipTypes(n[0].typ, abstractInst-{tyTypeDesc}).kind notin {tyVar, tyLent}:
  721. if n[0].kind == nkSym: incl(n[0].sym.flags, sfAddrTaken)
  722. result = newHiddenAddrTaken(c, n, isOutParam)
  723. else:
  724. result = newHiddenAddrTaken(c, n, isOutParam)
  725. proc analyseIfAddressTakenInCall(c: PContext, n: PNode, isConverter = false) =
  726. checkMinSonsLen(n, 1, c.config)
  727. const
  728. FakeVarParams = {mNew, mNewFinalize, mInc, ast.mDec, mIncl, mExcl,
  729. mSetLengthStr, mSetLengthSeq, mAppendStrCh, mAppendStrStr, mSwap,
  730. mAppendSeqElem, mNewSeq, mReset, mShallowCopy, mDeepCopy, mMove,
  731. mWasMoved}
  732. template checkIfConverterCalled(c: PContext, n: PNode) =
  733. ## Checks if there is a converter call which wouldn't be checked otherwise
  734. # Call can sometimes be wrapped in a deref
  735. let node = if n.kind == nkHiddenDeref: n[0] else: n
  736. if node.kind == nkHiddenCallConv:
  737. analyseIfAddressTakenInCall(c, node, true)
  738. # get the real type of the callee
  739. # it may be a proc var with a generic alias type, so we skip over them
  740. var t = n[0].typ.skipTypes({tyGenericInst, tyAlias, tySink})
  741. if n[0].kind == nkSym and n[0].sym.magic in FakeVarParams:
  742. # BUGFIX: check for L-Value still needs to be done for the arguments!
  743. # note sometimes this is eval'ed twice so we check for nkHiddenAddr here:
  744. for i in 1..<n.len:
  745. if i < t.len and t[i] != nil and
  746. skipTypes(t[i], abstractInst-{tyTypeDesc}).kind in {tyVar}:
  747. let it = n[i]
  748. let aa = isAssignable(c, it)
  749. if aa notin {arLValue, arLocalLValue}:
  750. if it.kind != nkHiddenAddr:
  751. if aa == arDiscriminant and c.inUncheckedAssignSection > 0:
  752. discard "allow access within a cast(unsafeAssign) section"
  753. else:
  754. localError(c.config, it.info, errVarForOutParamNeededX % $it)
  755. # Make sure to still check arguments for converters
  756. c.checkIfConverterCalled(n[i])
  757. # bug #5113: disallow newSeq(result) where result is a 'var T':
  758. if n[0].sym.magic in {mNew, mNewFinalize, mNewSeq}:
  759. var arg = n[1] #.skipAddr
  760. if arg.kind == nkHiddenDeref: arg = arg[0]
  761. if arg.kind == nkSym and arg.sym.kind == skResult and
  762. arg.typ.skipTypes(abstractInst).kind in {tyVar, tyLent}:
  763. localError(c.config, n.info, errXStackEscape % renderTree(n[1], {renderNoComments}))
  764. return
  765. for i in 1..<n.len:
  766. let n = if n.kind == nkHiddenDeref: n[0] else: n
  767. c.checkIfConverterCalled(n[i])
  768. if i < t.len and
  769. skipTypes(t[i], abstractInst-{tyTypeDesc}).kind in {tyVar}:
  770. # Converters wrap var parameters in nkHiddenAddr but they haven't been analysed yet.
  771. # So we need to make sure we are checking them still when in a converter call
  772. if n[i].kind != nkHiddenAddr or isConverter:
  773. n[i] = analyseIfAddressTaken(c, n[i].skipAddr(), isOutParam(skipTypes(t[i], abstractInst-{tyTypeDesc})))
  774. include semmagic
  775. proc evalAtCompileTime(c: PContext, n: PNode): PNode =
  776. result = n
  777. if n.kind notin nkCallKinds or n[0].kind != nkSym: return
  778. var callee = n[0].sym
  779. # workaround for bug #537 (overly aggressive inlining leading to
  780. # wrong NimNode semantics):
  781. if n.typ != nil and tfTriggersCompileTime in n.typ.flags: return
  782. # constant folding that is necessary for correctness of semantic pass:
  783. if callee.magic != mNone and callee.magic in ctfeWhitelist and n.typ != nil:
  784. var call = newNodeIT(nkCall, n.info, n.typ)
  785. call.add(n[0])
  786. var allConst = true
  787. for i in 1..<n.len:
  788. var a = getConstExpr(c.module, n[i], c.idgen, c.graph)
  789. if a == nil:
  790. allConst = false
  791. a = n[i]
  792. if a.kind == nkHiddenStdConv: a = a[1]
  793. call.add(a)
  794. if allConst:
  795. result = semfold.getConstExpr(c.module, call, c.idgen, c.graph)
  796. if result.isNil: result = n
  797. else: return result
  798. block maybeLabelAsStatic:
  799. # XXX: temporary work-around needed for tlateboundstatic.
  800. # This is certainly not correct, but it will get the job
  801. # done until we have a more robust infrastructure for
  802. # implicit statics.
  803. if n.len > 1:
  804. for i in 1..<n.len:
  805. # see bug #2113, it's possible that n[i].typ for errornous code:
  806. if n[i].typ.isNil or n[i].typ.kind != tyStatic or
  807. tfUnresolved notin n[i].typ.flags:
  808. break maybeLabelAsStatic
  809. n.typ = newTypeWithSons(c, tyStatic, @[n.typ])
  810. n.typ.flags.incl tfUnresolved
  811. # optimization pass: not necessary for correctness of the semantic pass
  812. if callee.kind == skConst or
  813. {sfNoSideEffect, sfCompileTime} * callee.flags != {} and
  814. {sfForward, sfImportc} * callee.flags == {} and n.typ != nil:
  815. if callee.kind != skConst and
  816. sfCompileTime notin callee.flags and
  817. optImplicitStatic notin c.config.options: return
  818. if callee.magic notin ctfeWhitelist: return
  819. if callee.kind notin {skProc, skFunc, skConverter, skConst} or callee.isGenericRoutine:
  820. return
  821. if n.typ != nil and typeAllowed(n.typ, skConst, c) != nil: return
  822. var call = newNodeIT(nkCall, n.info, n.typ)
  823. call.add(n[0])
  824. for i in 1..<n.len:
  825. let a = getConstExpr(c.module, n[i], c.idgen, c.graph)
  826. if a == nil: return n
  827. call.add(a)
  828. #echo "NOW evaluating at compile time: ", call.renderTree
  829. if c.inStaticContext == 0 or sfNoSideEffect in callee.flags:
  830. if sfCompileTime in callee.flags:
  831. result = evalStaticExpr(c.module, c.idgen, c.graph, call, c.p.owner)
  832. if result.isNil:
  833. localError(c.config, n.info, errCannotInterpretNodeX % renderTree(call))
  834. else: result = fixupTypeAfterEval(c, result, n)
  835. else:
  836. result = evalConstExpr(c.module, c.idgen, c.graph, call)
  837. if result.isNil: result = n
  838. else: result = fixupTypeAfterEval(c, result, n)
  839. else:
  840. result = n
  841. #if result != n:
  842. # echo "SUCCESS evaluated at compile time: ", call.renderTree
  843. proc semStaticExpr(c: PContext, n: PNode; expectedType: PType = nil): PNode =
  844. inc c.inStaticContext
  845. openScope(c)
  846. let a = semExprWithType(c, n, expectedType = expectedType)
  847. closeScope(c)
  848. dec c.inStaticContext
  849. if a.findUnresolvedStatic != nil: return a
  850. result = evalStaticExpr(c.module, c.idgen, c.graph, a, c.p.owner)
  851. if result.isNil:
  852. localError(c.config, n.info, errCannotInterpretNodeX % renderTree(n))
  853. result = c.graph.emptyNode
  854. else:
  855. result = fixupTypeAfterEval(c, result, a)
  856. proc semOverloadedCallAnalyseEffects(c: PContext, n: PNode, nOrig: PNode,
  857. flags: TExprFlags): PNode =
  858. if flags*{efInTypeof, efWantIterator, efWantIterable} != {}:
  859. # consider: 'for x in pReturningArray()' --> we don't want the restriction
  860. # to 'skIterator' anymore; skIterator is preferred in sigmatch already
  861. # for typeof support.
  862. # for ``typeof(countup(1,3))``, see ``tests/ttoseq``.
  863. result = semOverloadedCall(c, n, nOrig,
  864. {skProc, skFunc, skMethod, skConverter, skMacro, skTemplate, skIterator}, flags)
  865. else:
  866. result = semOverloadedCall(c, n, nOrig,
  867. {skProc, skFunc, skMethod, skConverter, skMacro, skTemplate}, flags)
  868. if result != nil:
  869. if result[0].kind != nkSym:
  870. internalError(c.config, "semOverloadedCallAnalyseEffects")
  871. return
  872. let callee = result[0].sym
  873. case callee.kind
  874. of skMacro, skTemplate: discard
  875. else:
  876. if callee.kind == skIterator and callee.id == c.p.owner.id and
  877. not isClosureIterator(c.p.owner.typ):
  878. localError(c.config, n.info, errRecursiveDependencyIteratorX % callee.name.s)
  879. # error correction, prevents endless for loop elimination in transf.
  880. # See bug #2051:
  881. result[0] = newSymNode(errorSym(c, n))
  882. elif callee.kind == skIterator:
  883. if efWantIterable in flags:
  884. let typ = newTypeS(tyIterable, c)
  885. rawAddSon(typ, result.typ)
  886. result.typ = typ
  887. proc resolveIndirectCall(c: PContext; n, nOrig: PNode;
  888. t: PType): TCandidate =
  889. initCandidate(c, result, t)
  890. matches(c, n, nOrig, result)
  891. proc bracketedMacro(n: PNode): PSym =
  892. if n.len >= 1 and n[0].kind == nkSym:
  893. result = n[0].sym
  894. if result.kind notin {skMacro, skTemplate}:
  895. result = nil
  896. proc setGenericParams(c: PContext, n: PNode) =
  897. for i in 1..<n.len:
  898. n[i].typ = semTypeNode(c, n[i], nil)
  899. proc afterCallActions(c: PContext; n, orig: PNode, flags: TExprFlags; expectedType: PType = nil): PNode =
  900. if efNoSemCheck notin flags and n.typ != nil and n.typ.kind == tyError:
  901. return errorNode(c, n)
  902. result = n
  903. when defined(nimsuggest):
  904. if c.config.expandProgress:
  905. if c.config.expandLevels == 0:
  906. return n
  907. else:
  908. c.config.expandLevels -= 1
  909. let callee = result[0].sym
  910. case callee.kind
  911. of skMacro: result = semMacroExpr(c, result, orig, callee, flags, expectedType)
  912. of skTemplate: result = semTemplateExpr(c, result, callee, flags, expectedType)
  913. else:
  914. semFinishOperands(c, result)
  915. activate(c, result)
  916. fixAbstractType(c, result)
  917. analyseIfAddressTakenInCall(c, result)
  918. if callee.magic != mNone:
  919. result = magicsAfterOverloadResolution(c, result, flags, expectedType)
  920. when false:
  921. if result.typ != nil and
  922. not (result.typ.kind == tySequence and result.typ[0].kind == tyEmpty):
  923. liftTypeBoundOps(c, result.typ, n.info)
  924. #result = patchResolvedTypeBoundOp(c, result)
  925. if c.matchedConcept == nil:
  926. result = evalAtCompileTime(c, result)
  927. proc semIndirectOp(c: PContext, n: PNode, flags: TExprFlags; expectedType: PType = nil): PNode =
  928. result = nil
  929. checkMinSonsLen(n, 1, c.config)
  930. var prc = n[0]
  931. if n[0].kind == nkDotExpr:
  932. checkSonsLen(n[0], 2, c.config)
  933. let n0 = semFieldAccess(c, n[0], {efIsDotCall})
  934. if n0.kind == nkDotCall:
  935. # it is a static call!
  936. result = n0
  937. result.transitionSonsKind(nkCall)
  938. result.flags.incl nfExplicitCall
  939. for i in 1..<n.len: result.add n[i]
  940. return semExpr(c, result, flags)
  941. else:
  942. n[0] = n0
  943. else:
  944. n[0] = semExpr(c, n[0], {efInCall})
  945. let t = n[0].typ
  946. if t != nil and t.kind in {tyVar, tyLent}:
  947. n[0] = newDeref(n[0])
  948. elif n[0].kind == nkBracketExpr:
  949. let s = bracketedMacro(n[0])
  950. if s != nil:
  951. setGenericParams(c, n[0])
  952. return semDirectOp(c, n, flags, expectedType)
  953. elif isSymChoice(n[0]):
  954. # overloaded generic procs e.g. newSeq[int] can end up here
  955. return semDirectOp(c, n, flags, expectedType)
  956. var t: PType = nil
  957. if n[0].typ != nil:
  958. t = skipTypes(n[0].typ, abstractInst+{tyOwned}-{tyTypeDesc, tyDistinct})
  959. if t != nil and t.kind == tyTypeDesc:
  960. if n.len == 1: return semObjConstr(c, n, flags, expectedType)
  961. return semConv(c, n)
  962. let nOrig = n.copyTree
  963. semOpAux(c, n)
  964. if t != nil and t.kind == tyProc:
  965. # This is a proc variable, apply normal overload resolution
  966. let m = resolveIndirectCall(c, n, nOrig, t)
  967. if m.state != csMatch:
  968. if c.config.m.errorOutputs == {}:
  969. # speed up error generation:
  970. globalError(c.config, n.info, "type mismatch")
  971. return c.graph.emptyNode
  972. else:
  973. var hasErrorType = false
  974. var msg = "type mismatch: got <"
  975. for i in 1..<n.len:
  976. if i > 1: msg.add(", ")
  977. let nt = n[i].typ
  978. msg.add(typeToString(nt))
  979. if nt.kind == tyError:
  980. hasErrorType = true
  981. break
  982. if not hasErrorType:
  983. let typ = n[0].typ
  984. msg.add(">\nbut expected one of:\n" &
  985. typeToString(typ))
  986. # prefer notin preferToResolveSymbols
  987. # t.sym != nil
  988. # sfAnon notin t.sym.flags
  989. # t.kind != tySequence(It is tyProc)
  990. if typ.sym != nil and sfAnon notin typ.sym.flags and
  991. typ.kind == tyProc:
  992. # when can `typ.sym != nil` ever happen?
  993. msg.add(" = " & typeToString(typ, preferDesc))
  994. msg.addDeclaredLocMaybe(c.config, typ)
  995. localError(c.config, n.info, msg)
  996. return errorNode(c, n)
  997. result = nil
  998. else:
  999. result = m.call
  1000. instGenericConvertersSons(c, result, m)
  1001. else:
  1002. result = overloadedCallOpr(c, n) # this uses efNoUndeclared
  1003. # Now that nkSym does not imply an iteration over the proc/iterator space,
  1004. # the old ``prc`` (which is likely an nkIdent) has to be restored:
  1005. if result == nil or result.kind == nkEmpty:
  1006. # XXX: hmm, what kind of symbols will end up here?
  1007. # do we really need to try the overload resolution?
  1008. n[0] = prc
  1009. nOrig[0] = prc
  1010. n.flags.incl nfExprCall
  1011. result = semOverloadedCallAnalyseEffects(c, n, nOrig, flags)
  1012. if result == nil: return errorNode(c, n)
  1013. elif result.kind notin nkCallKinds:
  1014. # the semExpr() in overloadedCallOpr can even break this condition!
  1015. # See bug #904 of how to trigger it:
  1016. return result
  1017. #result = afterCallActions(c, result, nOrig, flags)
  1018. if result[0].kind == nkSym:
  1019. result = afterCallActions(c, result, nOrig, flags, expectedType)
  1020. else:
  1021. fixAbstractType(c, result)
  1022. analyseIfAddressTakenInCall(c, result)
  1023. proc semDirectOp(c: PContext, n: PNode, flags: TExprFlags; expectedType: PType = nil): PNode =
  1024. # this seems to be a hotspot in the compiler!
  1025. let nOrig = n.copyTree
  1026. #semLazyOpAux(c, n)
  1027. result = semOverloadedCallAnalyseEffects(c, n, nOrig, flags)
  1028. if result != nil: result = afterCallActions(c, result, nOrig, flags, expectedType)
  1029. else: result = errorNode(c, n)
  1030. proc buildEchoStmt(c: PContext, n: PNode): PNode =
  1031. # we MUST not check 'n' for semantics again here! But for now we give up:
  1032. result = newNodeI(nkCall, n.info)
  1033. let e = systemModuleSym(c.graph, getIdent(c.cache, "echo"))
  1034. if e != nil:
  1035. result.add(newSymNode(e))
  1036. else:
  1037. result.add localErrorNode(c, n, "system needs: echo")
  1038. result.add(n)
  1039. result.add(newStrNode(nkStrLit, ": " & n.typ.typeToString))
  1040. result = semExpr(c, result)
  1041. proc semExprNoType(c: PContext, n: PNode): PNode =
  1042. let isPush = c.config.hasHint(hintExtendedContext)
  1043. if isPush: pushInfoContext(c.config, n.info)
  1044. result = semExpr(c, n, {efWantStmt})
  1045. discardCheck(c, result, {})
  1046. if isPush: popInfoContext(c.config)
  1047. proc isTypeExpr(n: PNode): bool =
  1048. case n.kind
  1049. of nkType, nkTypeOfExpr: result = true
  1050. of nkSym: result = n.sym.kind == skType
  1051. else: result = false
  1052. proc createSetType(c: PContext; baseType: PType): PType =
  1053. assert baseType != nil
  1054. result = newTypeS(tySet, c)
  1055. rawAddSon(result, baseType)
  1056. proc lookupInRecordAndBuildCheck(c: PContext, n, r: PNode, field: PIdent,
  1057. check: var PNode): PSym =
  1058. # transform in a node that contains the runtime check for the
  1059. # field, if it is in a case-part...
  1060. result = nil
  1061. case r.kind
  1062. of nkRecList:
  1063. for i in 0..<r.len:
  1064. result = lookupInRecordAndBuildCheck(c, n, r[i], field, check)
  1065. if result != nil: return
  1066. of nkRecCase:
  1067. checkMinSonsLen(r, 2, c.config)
  1068. if (r[0].kind != nkSym): illFormedAst(r, c.config)
  1069. result = lookupInRecordAndBuildCheck(c, n, r[0], field, check)
  1070. if result != nil: return
  1071. let setType = createSetType(c, r[0].typ)
  1072. var s = newNodeIT(nkCurly, r.info, setType)
  1073. for i in 1..<r.len:
  1074. var it = r[i]
  1075. case it.kind
  1076. of nkOfBranch:
  1077. result = lookupInRecordAndBuildCheck(c, n, lastSon(it), field, check)
  1078. if result == nil:
  1079. for j in 0..<it.len-1: s.add copyTree(it[j])
  1080. else:
  1081. if check == nil:
  1082. check = newNodeI(nkCheckedFieldExpr, n.info)
  1083. check.add c.graph.emptyNode # make space for access node
  1084. s = newNodeIT(nkCurly, n.info, setType)
  1085. for j in 0..<it.len - 1: s.add copyTree(it[j])
  1086. var inExpr = newNodeIT(nkCall, n.info, getSysType(c.graph, n.info, tyBool))
  1087. inExpr.add newSymNode(getSysMagic(c.graph, n.info, "contains", mInSet), n.info)
  1088. inExpr.add s
  1089. inExpr.add copyTree(r[0])
  1090. check.add inExpr
  1091. #check.add semExpr(c, inExpr)
  1092. return
  1093. of nkElse:
  1094. result = lookupInRecordAndBuildCheck(c, n, lastSon(it), field, check)
  1095. if result != nil:
  1096. if check == nil:
  1097. check = newNodeI(nkCheckedFieldExpr, n.info)
  1098. check.add c.graph.emptyNode # make space for access node
  1099. var inExpr = newNodeIT(nkCall, n.info, getSysType(c.graph, n.info, tyBool))
  1100. inExpr.add newSymNode(getSysMagic(c.graph, n.info, "contains", mInSet), n.info)
  1101. inExpr.add s
  1102. inExpr.add copyTree(r[0])
  1103. var notExpr = newNodeIT(nkCall, n.info, getSysType(c.graph, n.info, tyBool))
  1104. notExpr.add newSymNode(getSysMagic(c.graph, n.info, "not", mNot), n.info)
  1105. notExpr.add inExpr
  1106. check.add notExpr
  1107. return
  1108. else: illFormedAst(it, c.config)
  1109. of nkSym:
  1110. if r.sym.name.id == field.id: result = r.sym
  1111. else: illFormedAst(n, c.config)
  1112. const
  1113. tyTypeParamsHolders = {tyGenericInst, tyCompositeTypeClass}
  1114. tyDotOpTransparent = {tyVar, tyLent, tyPtr, tyRef, tyOwned, tyAlias, tySink}
  1115. proc readTypeParameter(c: PContext, typ: PType,
  1116. paramName: PIdent, info: TLineInfo): PNode =
  1117. # Note: This function will return emptyNode when attempting to read
  1118. # a static type parameter that is not yet resolved (e.g. this may
  1119. # happen in proc signatures such as `proc(x: T): array[T.sizeParam, U]`
  1120. if typ.kind in {tyUserTypeClass, tyUserTypeClassInst}:
  1121. for statement in typ.n:
  1122. case statement.kind
  1123. of nkTypeSection:
  1124. for def in statement:
  1125. if def[0].sym.name.id == paramName.id:
  1126. # XXX: Instead of lifting the section type to a typedesc
  1127. # here, we could try doing it earlier in semTypeSection.
  1128. # This seems semantically correct and then we'll be able
  1129. # to return the section symbol directly here
  1130. let foundType = makeTypeDesc(c, def[2].typ)
  1131. return newSymNode(copySym(def[0].sym, nextSymId c.idgen).linkTo(foundType), info)
  1132. of nkConstSection:
  1133. for def in statement:
  1134. if def[0].sym.name.id == paramName.id:
  1135. return def[2]
  1136. else:
  1137. discard
  1138. if typ.kind != tyUserTypeClass:
  1139. let ty = if typ.kind == tyCompositeTypeClass: typ[1].skipGenericAlias
  1140. else: typ.skipGenericAlias
  1141. let tbody = ty[0]
  1142. for s in 0..<tbody.len-1:
  1143. let tParam = tbody[s]
  1144. if tParam.sym.name.id == paramName.id:
  1145. let rawTyp = ty[s + 1]
  1146. if rawTyp.kind == tyStatic:
  1147. if rawTyp.n != nil:
  1148. return rawTyp.n
  1149. else:
  1150. return c.graph.emptyNode
  1151. else:
  1152. let foundTyp = makeTypeDesc(c, rawTyp)
  1153. return newSymNode(copySym(tParam.sym, nextSymId c.idgen).linkTo(foundTyp), info)
  1154. return nil
  1155. proc semSym(c: PContext, n: PNode, sym: PSym, flags: TExprFlags): PNode =
  1156. let s = getGenSym(c, sym)
  1157. case s.kind
  1158. of skConst:
  1159. if n.kind != nkDotExpr: # dotExpr is already checked by builtinFieldAccess
  1160. markUsed(c, n.info, s)
  1161. onUse(n.info, s)
  1162. let typ = skipTypes(s.typ, abstractInst-{tyTypeDesc})
  1163. case typ.kind
  1164. of tyNil, tyChar, tyInt..tyInt64, tyFloat..tyFloat128,
  1165. tyTuple, tySet, tyUInt..tyUInt64:
  1166. if s.magic == mNone: result = inlineConst(c, n, s)
  1167. else: result = newSymNode(s, n.info)
  1168. of tyArray, tySequence:
  1169. # Consider::
  1170. # const x = []
  1171. # proc p(a: openarray[int])
  1172. # proc q(a: openarray[char])
  1173. # p(x)
  1174. # q(x)
  1175. #
  1176. # It is clear that ``[]`` means two totally different things. Thus, we
  1177. # copy `x`'s AST into each context, so that the type fixup phase can
  1178. # deal with two different ``[]``.
  1179. if s.astdef.safeLen == 0: result = inlineConst(c, n, s)
  1180. else: result = newSymNode(s, n.info)
  1181. of tyStatic:
  1182. if typ.n != nil:
  1183. result = typ.n
  1184. result.typ = typ.base
  1185. else:
  1186. result = newSymNode(s, n.info)
  1187. else:
  1188. result = newSymNode(s, n.info)
  1189. of skMacro, skTemplate:
  1190. if efNoEvaluateGeneric in flags and s.ast[genericParamsPos].len > 0 or
  1191. (n.kind notin nkCallKinds and s.requiredParams > 0) or
  1192. sfCustomPragma in sym.flags:
  1193. let info = getCallLineInfo(n)
  1194. markUsed(c, info, s)
  1195. onUse(info, s)
  1196. result = symChoice(c, n, s, scClosed)
  1197. else:
  1198. case s.kind
  1199. of skMacro: result = semMacroExpr(c, n, n, s, flags)
  1200. of skTemplate: result = semTemplateExpr(c, n, s, flags)
  1201. else: discard # unreachable
  1202. of skParam:
  1203. markUsed(c, n.info, s)
  1204. onUse(n.info, s)
  1205. if s.typ != nil and s.typ.kind == tyStatic and s.typ.n != nil:
  1206. # XXX see the hack in sigmatch.nim ...
  1207. return s.typ.n
  1208. elif sfGenSym in s.flags:
  1209. # the owner should have been set by now by addParamOrResult
  1210. internalAssert c.config, s.owner != nil
  1211. result = newSymNode(s, n.info)
  1212. of skVar, skLet, skResult, skForVar:
  1213. if s.magic == mNimvm:
  1214. localError(c.config, n.info, "illegal context for 'nimvm' magic")
  1215. if n.kind != nkDotExpr: # dotExpr is already checked by builtinFieldAccess
  1216. markUsed(c, n.info, s)
  1217. onUse(n.info, s)
  1218. result = newSymNode(s, n.info)
  1219. # We cannot check for access to outer vars for example because it's still
  1220. # not sure the symbol really ends up being used:
  1221. # var len = 0 # but won't be called
  1222. # genericThatUsesLen(x) # marked as taking a closure?
  1223. if hasWarn(c.config, warnResultUsed):
  1224. message(c.config, n.info, warnResultUsed)
  1225. of skGenericParam:
  1226. onUse(n.info, s)
  1227. if s.typ.kind == tyStatic:
  1228. result = newSymNode(s, n.info)
  1229. result.typ = s.typ
  1230. elif s.ast != nil:
  1231. result = semExpr(c, s.ast)
  1232. else:
  1233. n.typ = s.typ
  1234. return n
  1235. of skType:
  1236. if n.kind != nkDotExpr: # dotExpr is already checked by builtinFieldAccess
  1237. markUsed(c, n.info, s)
  1238. onUse(n.info, s)
  1239. if s.typ.kind == tyStatic and s.typ.base.kind != tyNone and s.typ.n != nil:
  1240. return s.typ.n
  1241. result = newSymNode(s, n.info)
  1242. result.typ = makeTypeDesc(c, s.typ)
  1243. of skField:
  1244. # old code, not sure if it's live code:
  1245. markUsed(c, n.info, s)
  1246. onUse(n.info, s)
  1247. result = newSymNode(s, n.info)
  1248. of skModule:
  1249. # make sure type is None and not nil for discard checking
  1250. if efWantStmt in flags: s.typ = newTypeS(tyNone, c)
  1251. markUsed(c, n.info, s)
  1252. onUse(n.info, s)
  1253. result = newSymNode(s, n.info)
  1254. else:
  1255. let info = getCallLineInfo(n)
  1256. #if efInCall notin flags:
  1257. markUsed(c, info, s)
  1258. onUse(info, s)
  1259. result = newSymNode(s, info)
  1260. proc tryReadingGenericParam(c: PContext, n: PNode, i: PIdent, t: PType): PNode =
  1261. case t.kind
  1262. of tyTypeParamsHolders:
  1263. result = readTypeParameter(c, t, i, n.info)
  1264. if result == c.graph.emptyNode:
  1265. result = n
  1266. n.typ = makeTypeFromExpr(c, n.copyTree)
  1267. of tyUserTypeClasses:
  1268. if t.isResolvedUserTypeClass:
  1269. result = readTypeParameter(c, t, i, n.info)
  1270. else:
  1271. n.typ = makeTypeFromExpr(c, copyTree(n))
  1272. result = n
  1273. of tyGenericParam, tyAnything:
  1274. n.typ = makeTypeFromExpr(c, copyTree(n))
  1275. result = n
  1276. else:
  1277. discard
  1278. proc tryReadingTypeField(c: PContext, n: PNode, i: PIdent, ty: PType): PNode =
  1279. var ty = ty.skipTypes(tyDotOpTransparent)
  1280. case ty.kind
  1281. of tyEnum:
  1282. # look up if the identifier belongs to the enum:
  1283. var f = PSym(nil)
  1284. while ty != nil:
  1285. f = getSymFromList(ty.n, i)
  1286. if f != nil: break
  1287. ty = ty.sons[0] # enum inheritance
  1288. if f != nil:
  1289. result = newSymNode(f)
  1290. result.info = n.info
  1291. result.typ = ty
  1292. markUsed(c, n.info, f)
  1293. onUse(n.info, f)
  1294. of tyObject, tyTuple:
  1295. if ty.n != nil and ty.n.kind == nkRecList:
  1296. let field = lookupInRecord(ty.n, i)
  1297. if field != nil:
  1298. n.typ = makeTypeDesc(c, field.typ)
  1299. result = n
  1300. of tyGenericInst:
  1301. result = tryReadingTypeField(c, n, i, ty.lastSon)
  1302. if result == nil:
  1303. result = tryReadingGenericParam(c, n, i, ty)
  1304. else:
  1305. result = tryReadingGenericParam(c, n, i, ty)
  1306. proc builtinFieldAccess(c: PContext; n: PNode; flags: var TExprFlags): PNode =
  1307. ## returns nil if it's not a built-in field access
  1308. checkSonsLen(n, 2, c.config)
  1309. # tests/bind/tbindoverload.nim wants an early exit here, but seems to
  1310. # work without now. template/tsymchoicefield doesn't like an early exit
  1311. # here at all!
  1312. #if isSymChoice(n[1]): return
  1313. when defined(nimsuggest):
  1314. if c.config.cmd == cmdIdeTools:
  1315. suggestExpr(c, n)
  1316. if exactEquals(c.config.m.trackPos, n[1].info): suggestExprNoCheck(c, n)
  1317. var s = qualifiedLookUp(c, n, {checkAmbiguity, checkUndeclared, checkModule})
  1318. if s != nil:
  1319. if s.kind in OverloadableSyms:
  1320. result = symChoice(c, n, s, scClosed)
  1321. if result.kind == nkSym: result = semSym(c, n, s, flags)
  1322. else:
  1323. markUsed(c, n[1].info, s)
  1324. result = semSym(c, n, s, flags)
  1325. onUse(n[1].info, s)
  1326. return
  1327. n[0] = semExprWithType(c, n[0], flags+{efDetermineType, efWantIterable})
  1328. #restoreOldStyleType(n[0])
  1329. var i = considerQuotedIdent(c, n[1], n)
  1330. var ty = n[0].typ
  1331. var f: PSym = nil
  1332. result = nil
  1333. if ty.kind == tyTypeDesc:
  1334. if ty.base.kind == tyNone:
  1335. # This is a still unresolved typedesc parameter.
  1336. # If this is a regular proc, then all bets are off and we must return
  1337. # tyFromExpr, but when this happen in a macro this is not a built-in
  1338. # field access and we leave the compiler to compile a normal call:
  1339. if getCurrOwner(c).kind != skMacro:
  1340. n.typ = makeTypeFromExpr(c, n.copyTree)
  1341. flags.incl efCannotBeDotCall
  1342. return n
  1343. else:
  1344. return nil
  1345. else:
  1346. flags.incl efCannotBeDotCall
  1347. return tryReadingTypeField(c, n, i, ty.base)
  1348. elif isTypeExpr(n.sons[0]):
  1349. flags.incl efCannotBeDotCall
  1350. return tryReadingTypeField(c, n, i, ty)
  1351. elif ty.kind == tyError:
  1352. # a type error doesn't have any builtin fields
  1353. return nil
  1354. if ty.kind in tyUserTypeClasses and ty.isResolvedUserTypeClass:
  1355. ty = ty.lastSon
  1356. ty = skipTypes(ty, {tyGenericInst, tyVar, tyLent, tyPtr, tyRef, tyOwned, tyAlias, tySink, tyStatic})
  1357. while tfBorrowDot in ty.flags: ty = ty.skipTypes({tyDistinct, tyGenericInst, tyAlias})
  1358. var check: PNode = nil
  1359. if ty.kind == tyObject:
  1360. while true:
  1361. check = nil
  1362. f = lookupInRecordAndBuildCheck(c, n, ty.n, i, check)
  1363. if f != nil: break
  1364. if ty[0] == nil: break
  1365. ty = skipTypes(ty[0], skipPtrs)
  1366. if f != nil:
  1367. let visibilityCheckNeeded =
  1368. if n[1].kind == nkSym and n[1].sym == f:
  1369. false # field lookup was done already, likely by hygienic template or bindSym
  1370. else: true
  1371. if not visibilityCheckNeeded or fieldVisible(c, f):
  1372. # is the access to a public field or in the same module or in a friend?
  1373. markUsed(c, n[1].info, f)
  1374. onUse(n[1].info, f)
  1375. let info = n[1].info
  1376. n[0] = makeDeref(n[0])
  1377. n[1] = newSymNode(f) # we now have the correct field
  1378. n[1].info = info # preserve the original info
  1379. n.typ = f.typ
  1380. if check == nil:
  1381. result = n
  1382. else:
  1383. check[0] = n
  1384. check.typ = n.typ
  1385. result = check
  1386. elif ty.kind == tyTuple and ty.n != nil:
  1387. f = getSymFromList(ty.n, i)
  1388. if f != nil:
  1389. markUsed(c, n[1].info, f)
  1390. onUse(n[1].info, f)
  1391. n[0] = makeDeref(n[0])
  1392. n[1] = newSymNode(f)
  1393. n.typ = f.typ
  1394. result = n
  1395. # we didn't find any field, let's look for a generic param
  1396. if result == nil:
  1397. let t = n[0].typ.skipTypes(tyDotOpTransparent)
  1398. result = tryReadingGenericParam(c, n, i, t)
  1399. flags.incl efCannotBeDotCall
  1400. proc dotTransformation(c: PContext, n: PNode): PNode =
  1401. if isSymChoice(n[1]):
  1402. result = newNodeI(nkDotCall, n.info)
  1403. result.add n[1]
  1404. result.add copyTree(n[0])
  1405. else:
  1406. var i = considerQuotedIdent(c, n[1], n)
  1407. result = newNodeI(nkDotCall, n.info)
  1408. result.flags.incl nfDotField
  1409. result.add newIdentNode(i, n[1].info)
  1410. result.add copyTree(n[0])
  1411. proc semFieldAccess(c: PContext, n: PNode, flags: TExprFlags): PNode =
  1412. # this is difficult, because the '.' is used in many different contexts
  1413. # in Nim. We first allow types in the semantic checking.
  1414. var f = flags - {efIsDotCall}
  1415. result = builtinFieldAccess(c, n, f)
  1416. if result == nil or ((result.typ == nil or result.typ.skipTypes(abstractInst).kind != tyProc) and
  1417. efIsDotCall in flags and callOperator notin c.features and
  1418. efCannotBeDotCall notin f):
  1419. result = dotTransformation(c, n)
  1420. proc buildOverloadedSubscripts(n: PNode, ident: PIdent): PNode =
  1421. result = newNodeI(nkCall, n.info)
  1422. result.add(newIdentNode(ident, n.info))
  1423. for s in n: result.add s
  1424. proc semDeref(c: PContext, n: PNode): PNode =
  1425. checkSonsLen(n, 1, c.config)
  1426. n[0] = semExprWithType(c, n[0])
  1427. let a = getConstExpr(c.module, n[0], c.idgen, c.graph)
  1428. if a != nil:
  1429. if a.kind == nkNilLit:
  1430. localError(c.config, n.info, "nil dereference is not allowed")
  1431. n[0] = a
  1432. result = n
  1433. var t = skipTypes(n[0].typ, {tyGenericInst, tyVar, tyLent, tyAlias, tySink, tyOwned})
  1434. case t.kind
  1435. of tyRef, tyPtr: n.typ = t.lastSon
  1436. else: result = nil
  1437. #GlobalError(n[0].info, errCircumNeedsPointer)
  1438. proc maybeInstantiateGeneric(c: PContext, n: PNode, s: PSym): PNode =
  1439. ## Instantiates generic if not lacking implicit generics,
  1440. ## otherwise returns n.
  1441. let
  1442. neededGenParams = s.ast[genericParamsPos].len
  1443. heldGenParams = n.len - 1
  1444. var implicitParams = 0
  1445. for x in s.ast[genericParamsPos]:
  1446. if tfImplicitTypeParam in x.typ.flags:
  1447. inc implicitParams
  1448. if heldGenParams != neededGenParams and implicitParams + heldGenParams == neededGenParams:
  1449. # This is an implicit + explicit generic procedure without all args passed,
  1450. # kicking back the sem'd symbol fixes #17212
  1451. # Uncertain the hackiness of this solution.
  1452. result = n
  1453. else:
  1454. result = explicitGenericInstantiation(c, n, s)
  1455. if result == n:
  1456. n[0] = copyTree(result[0])
  1457. else:
  1458. n[0] = result
  1459. proc semSubscript(c: PContext, n: PNode, flags: TExprFlags): PNode =
  1460. ## returns nil if not a built-in subscript operator; also called for the
  1461. ## checking of assignments
  1462. if n.len == 1:
  1463. let x = semDeref(c, n)
  1464. if x == nil: return nil
  1465. result = newNodeIT(nkDerefExpr, x.info, x.typ)
  1466. result.add(x[0])
  1467. return
  1468. checkMinSonsLen(n, 2, c.config)
  1469. # make sure we don't evaluate generic macros/templates
  1470. n[0] = semExprWithType(c, n[0],
  1471. {efNoEvaluateGeneric})
  1472. var arr = skipTypes(n[0].typ, {tyGenericInst, tyUserTypeClassInst, tyOwned,
  1473. tyVar, tyLent, tyPtr, tyRef, tyAlias, tySink})
  1474. if arr.kind == tyStatic:
  1475. if arr.base.kind == tyNone:
  1476. result = n
  1477. result.typ = semStaticType(c, n[1], nil)
  1478. return
  1479. elif arr.n != nil:
  1480. return semSubscript(c, arr.n, flags)
  1481. else:
  1482. arr = arr.base
  1483. case arr.kind
  1484. of tyArray, tyOpenArray, tyVarargs, tySequence, tyString, tyCstring,
  1485. tyUncheckedArray:
  1486. if n.len != 2: return nil
  1487. n[0] = makeDeref(n[0])
  1488. for i in 1..<n.len:
  1489. n[i] = semExprWithType(c, n[i],
  1490. flags*{efInTypeof, efDetermineType})
  1491. # Arrays index type is dictated by the range's type
  1492. if arr.kind == tyArray:
  1493. var indexType = arr[0]
  1494. var arg = indexTypesMatch(c, indexType, n[1].typ, n[1])
  1495. if arg != nil:
  1496. n[1] = arg
  1497. result = n
  1498. result.typ = elemType(arr)
  1499. # Other types have a bit more of leeway
  1500. elif n[1].typ.skipTypes(abstractRange-{tyDistinct}).kind in
  1501. {tyInt..tyInt64, tyUInt..tyUInt64}:
  1502. result = n
  1503. result.typ = elemType(arr)
  1504. of tyTypeDesc:
  1505. # The result so far is a tyTypeDesc bound
  1506. # a tyGenericBody. The line below will substitute
  1507. # it with the instantiated type.
  1508. result = n
  1509. result.typ = makeTypeDesc(c, semTypeNode(c, n, nil))
  1510. #result = symNodeFromType(c, semTypeNode(c, n, nil), n.info)
  1511. of tyTuple:
  1512. if n.len != 2: return nil
  1513. n[0] = makeDeref(n[0])
  1514. # [] operator for tuples requires constant expression:
  1515. n[1] = semConstExpr(c, n[1])
  1516. if skipTypes(n[1].typ, {tyGenericInst, tyRange, tyOrdinal, tyAlias, tySink}).kind in
  1517. {tyInt..tyInt64}:
  1518. let idx = getOrdValue(n[1])
  1519. if idx >= 0 and idx < arr.len: n.typ = arr[toInt(idx)]
  1520. else: localError(c.config, n.info, "invalid index value for tuple subscript")
  1521. result = n
  1522. else:
  1523. result = nil
  1524. else:
  1525. let s = if n[0].kind == nkSym: n[0].sym
  1526. elif n[0].kind in nkSymChoices: n[0][0].sym
  1527. else: nil
  1528. if s != nil:
  1529. case s.kind
  1530. of skProc, skFunc, skMethod, skConverter, skIterator:
  1531. # type parameters: partial generic specialization
  1532. n[0] = semSymGenericInstantiation(c, n[0], s)
  1533. result = maybeInstantiateGeneric(c, n, s)
  1534. of skMacro, skTemplate:
  1535. if efInCall in flags:
  1536. # We are processing macroOrTmpl[] in macroOrTmpl[](...) call.
  1537. # Return as is, so it can be transformed into complete macro or
  1538. # template call in semIndirectOp caller.
  1539. result = n
  1540. else:
  1541. # We are processing macroOrTmpl[] not in call. Transform it to the
  1542. # macro or template call with generic arguments here.
  1543. n.transitionSonsKind(nkCall)
  1544. case s.kind
  1545. of skMacro: result = semMacroExpr(c, n, n, s, flags)
  1546. of skTemplate: result = semTemplateExpr(c, n, s, flags)
  1547. else: discard
  1548. of skType:
  1549. result = symNodeFromType(c, semTypeNode(c, n, nil), n.info)
  1550. else:
  1551. discard
  1552. proc semArrayAccess(c: PContext, n: PNode, flags: TExprFlags; expectedType: PType = nil): PNode =
  1553. result = semSubscript(c, n, flags)
  1554. if result == nil:
  1555. # overloaded [] operator:
  1556. result = semExpr(c, buildOverloadedSubscripts(n, getIdent(c.cache, "[]")), flags, expectedType)
  1557. proc propertyWriteAccess(c: PContext, n, nOrig, a: PNode): PNode =
  1558. var id = considerQuotedIdent(c, a[1], a)
  1559. var setterId = newIdentNode(getIdent(c.cache, id.s & '='), n.info)
  1560. # a[0] is already checked for semantics, that does ``builtinFieldAccess``
  1561. # this is ugly. XXX Semantic checking should use the ``nfSem`` flag for
  1562. # nodes?
  1563. let aOrig = nOrig[0]
  1564. result = newTreeI(nkCall, n.info, setterId, a[0], semExprWithType(c, n[1]))
  1565. result.flags.incl nfDotSetter
  1566. let orig = newTreeI(nkCall, n.info, setterId, aOrig[0], nOrig[1])
  1567. result = semOverloadedCallAnalyseEffects(c, result, orig, {})
  1568. if result != nil:
  1569. result = afterCallActions(c, result, nOrig, {})
  1570. #fixAbstractType(c, result)
  1571. #analyseIfAddressTakenInCall(c, result)
  1572. proc takeImplicitAddr(c: PContext, n: PNode; isLent: bool): PNode =
  1573. # See RFC #7373, calls returning 'var T' are assumed to
  1574. # return a view into the first argument (if there is one):
  1575. let root = exprRoot(n)
  1576. if root != nil and root.owner == c.p.owner:
  1577. template url: string = "var_t_return.html".createDocLink
  1578. if root.kind in {skLet, skVar, skTemp} and sfGlobal notin root.flags:
  1579. localError(c.config, n.info, "'$1' escapes its stack frame; context: '$2'; see $3" % [
  1580. root.name.s, renderTree(n, {renderNoComments}), url])
  1581. elif root.kind == skParam and root.position != 0:
  1582. localError(c.config, n.info, "'$1' is not the first parameter; context: '$2'; see $3" % [
  1583. root.name.s, renderTree(n, {renderNoComments}), url])
  1584. case n.kind
  1585. of nkHiddenAddr, nkAddr: return n
  1586. of nkDerefExpr: return n[0]
  1587. of nkBracketExpr:
  1588. if n.len == 1: return n[0]
  1589. of nkHiddenDeref:
  1590. # issue #13848
  1591. # `proc fun(a: var int): var int = a`
  1592. discard
  1593. else: discard
  1594. let valid = isAssignable(c, n)
  1595. if valid != arLValue:
  1596. if valid in {arAddressableConst, arLentValue} and isLent:
  1597. discard "ok"
  1598. elif valid == arLocalLValue:
  1599. localError(c.config, n.info, errXStackEscape % renderTree(n, {renderNoComments}))
  1600. else:
  1601. localError(c.config, n.info, errExprHasNoAddress)
  1602. result = newNodeIT(nkHiddenAddr, n.info, if n.typ.kind in {tyVar, tyLent}: n.typ else: makePtrType(c, n.typ))
  1603. result.add(n)
  1604. proc asgnToResultVar(c: PContext, n, le, ri: PNode) {.inline.} =
  1605. if le.kind == nkHiddenDeref:
  1606. var x = le[0]
  1607. if x.kind == nkSym:
  1608. if x.sym.kind == skResult and (x.typ.kind in {tyVar, tyLent} or classifyViewType(x.typ) != noView):
  1609. n[0] = x # 'result[]' --> 'result'
  1610. n[1] = takeImplicitAddr(c, ri, x.typ.kind == tyLent)
  1611. x.typ.flags.incl tfVarIsPtr
  1612. #echo x.info, " setting it for this type ", typeToString(x.typ), " ", n.info
  1613. elif sfGlobal in x.sym.flags:
  1614. x.typ.flags.incl tfVarIsPtr
  1615. proc borrowCheck(c: PContext, n, le, ri: PNode) =
  1616. const
  1617. PathKinds0 = {nkDotExpr, nkCheckedFieldExpr,
  1618. nkBracketExpr, nkAddr, nkHiddenAddr,
  1619. nkObjDownConv, nkObjUpConv}
  1620. PathKinds1 = {nkHiddenStdConv, nkHiddenSubConv}
  1621. proc getRoot(n: PNode; followDeref: bool): PNode =
  1622. result = n
  1623. while true:
  1624. case result.kind
  1625. of nkDerefExpr, nkHiddenDeref:
  1626. if followDeref: result = result[0]
  1627. else: break
  1628. of PathKinds0:
  1629. result = result[0]
  1630. of PathKinds1:
  1631. result = result[1]
  1632. else: break
  1633. proc scopedLifetime(c: PContext; ri: PNode): bool {.inline.} =
  1634. let n = getRoot(ri, followDeref = false)
  1635. result = (ri.kind in nkCallKinds+{nkObjConstr}) or
  1636. (n.kind == nkSym and n.sym.owner == c.p.owner and n.sym.kind != skResult)
  1637. proc escapes(c: PContext; le: PNode): bool {.inline.} =
  1638. # param[].foo[] = self definitely escapes, we don't need to
  1639. # care about pointer derefs:
  1640. let n = getRoot(le, followDeref = true)
  1641. result = n.kind == nkSym and n.sym.kind == skParam
  1642. # Special typing rule: do not allow to pass 'owned T' to 'T' in 'result = x':
  1643. const absInst = abstractInst - {tyOwned}
  1644. if ri.typ != nil and ri.typ.skipTypes(absInst).kind == tyOwned and
  1645. le.typ != nil and le.typ.skipTypes(absInst).kind != tyOwned and
  1646. scopedLifetime(c, ri):
  1647. if le.kind == nkSym and le.sym.kind == skResult:
  1648. localError(c.config, n.info, "cannot return an owned pointer as an unowned pointer; " &
  1649. "use 'owned(" & typeToString(le.typ) & ")' as the return type")
  1650. elif escapes(c, le):
  1651. localError(c.config, n.info,
  1652. "assignment produces a dangling ref: the unowned ref lives longer than the owned ref")
  1653. template resultTypeIsInferrable(typ: PType): untyped =
  1654. typ.isMetaType and typ.kind != tyTypeDesc
  1655. proc goodLineInfo(arg: PNode): TLineInfo =
  1656. if arg.kind == nkStmtListExpr and arg.len > 0:
  1657. goodLineInfo(arg[^1])
  1658. else:
  1659. arg.info
  1660. proc semAsgn(c: PContext, n: PNode; mode=asgnNormal): PNode =
  1661. checkSonsLen(n, 2, c.config)
  1662. var a = n[0]
  1663. case a.kind
  1664. of nkDotExpr:
  1665. # r.f = x
  1666. # --> `f=` (r, x)
  1667. let nOrig = n.copyTree
  1668. var flags = {efLValue}
  1669. a = builtinFieldAccess(c, a, flags)
  1670. if a == nil:
  1671. a = propertyWriteAccess(c, n, nOrig, n[0])
  1672. if a != nil: return a
  1673. # we try without the '='; proc that return 'var' or macros are still
  1674. # possible:
  1675. a = dotTransformation(c, n[0])
  1676. if a.kind == nkDotCall:
  1677. a.transitionSonsKind(nkCall)
  1678. a = semExprWithType(c, a, {efLValue})
  1679. of nkBracketExpr:
  1680. # a[i] = x
  1681. # --> `[]=`(a, i, x)
  1682. a = semSubscript(c, a, {efLValue})
  1683. if a == nil:
  1684. result = buildOverloadedSubscripts(n[0], getIdent(c.cache, "[]="))
  1685. result.add(n[1])
  1686. if mode == noOverloadedSubscript:
  1687. bracketNotFoundError(c, result)
  1688. return n
  1689. else:
  1690. result = semExprNoType(c, result)
  1691. return result
  1692. of nkCurlyExpr:
  1693. # a{i} = x --> `{}=`(a, i, x)
  1694. result = buildOverloadedSubscripts(n[0], getIdent(c.cache, "{}="))
  1695. result.add(n[1])
  1696. return semExprNoType(c, result)
  1697. of nkPar, nkTupleConstr:
  1698. if a.len >= 2 or a.kind == nkTupleConstr:
  1699. # unfortunately we need to rewrite ``(x, y) = foo()`` already here so
  1700. # that overloading of the assignment operator still works. Usually we
  1701. # prefer to do these rewritings in transf.nim:
  1702. return semStmt(c, lowerTupleUnpackingForAsgn(c.graph, n, c.idgen, c.p.owner), {})
  1703. else:
  1704. a = semExprWithType(c, a, {efLValue})
  1705. else:
  1706. a = semExprWithType(c, a, {efLValue})
  1707. n[0] = a
  1708. # a = b # both are vars, means: a[] = b[]
  1709. # a = b # b no 'var T' means: a = addr(b)
  1710. var le = a.typ
  1711. let assignable = isAssignable(c, a)
  1712. let root = getRoot(a)
  1713. let useStrictDefLet = root != nil and root.kind == skLet and
  1714. assignable == arAddressableConst and
  1715. strictDefs in c.features and isLocalSym(root)
  1716. if le == nil:
  1717. localError(c.config, a.info, "expression has no type")
  1718. elif (skipTypes(le, {tyGenericInst, tyAlias, tySink}).kind notin {tyVar} and
  1719. assignable in {arNone, arLentValue, arAddressableConst} and not useStrictDefLet
  1720. ) or (skipTypes(le, abstractVar).kind in {tyOpenArray, tyVarargs} and views notin c.features):
  1721. # Direct assignment to a discriminant is allowed!
  1722. localError(c.config, a.info, errXCannotBeAssignedTo %
  1723. renderTree(a, {renderNoComments}))
  1724. else:
  1725. let lhs = n[0]
  1726. let rhs = semExprWithType(c, n[1], {efTypeAllowed}, le)
  1727. if lhs.kind == nkSym and lhs.sym.kind == skResult:
  1728. n.typ = c.enforceVoidContext
  1729. if c.p.owner.kind != skMacro and resultTypeIsInferrable(lhs.sym.typ):
  1730. var rhsTyp = rhs.typ
  1731. if rhsTyp.kind in tyUserTypeClasses and rhsTyp.isResolvedUserTypeClass:
  1732. rhsTyp = rhsTyp.lastSon
  1733. if lhs.sym.typ.kind == tyAnything:
  1734. rhsTyp = rhsTyp.skipIntLit(c.idgen)
  1735. if cmpTypes(c, lhs.typ, rhsTyp) in {isGeneric, isEqual}:
  1736. internalAssert c.config, c.p.resultSym != nil
  1737. # Make sure the type is valid for the result variable
  1738. typeAllowedCheck(c, n.info, rhsTyp, skResult)
  1739. lhs.typ = rhsTyp
  1740. c.p.resultSym.typ = rhsTyp
  1741. c.p.owner.typ[0] = rhsTyp
  1742. else:
  1743. typeMismatch(c.config, n.info, lhs.typ, rhsTyp, rhs)
  1744. borrowCheck(c, n, lhs, rhs)
  1745. n[1] = fitNode(c, le, rhs, goodLineInfo(n[1]))
  1746. when false: liftTypeBoundOps(c, lhs.typ, lhs.info)
  1747. fixAbstractType(c, n)
  1748. asgnToResultVar(c, n, n[0], n[1])
  1749. result = n
  1750. proc semReturn(c: PContext, n: PNode): PNode =
  1751. result = n
  1752. checkSonsLen(n, 1, c.config)
  1753. if c.p.owner.kind in {skConverter, skMethod, skProc, skFunc, skMacro} or
  1754. (not c.p.owner.typ.isNil and isClosureIterator(c.p.owner.typ)):
  1755. if n[0].kind != nkEmpty:
  1756. if n[0].kind == nkAsgn and n[0][0].kind == nkSym and c.p.resultSym == n[0][0].sym:
  1757. discard "return is already transformed"
  1758. elif c.p.resultSym != nil:
  1759. # transform ``return expr`` to ``result = expr; return``
  1760. var a = newNodeI(nkAsgn, n[0].info)
  1761. a.add newSymNode(c.p.resultSym)
  1762. a.add n[0]
  1763. n[0] = a
  1764. else:
  1765. localError(c.config, n.info, errNoReturnTypeDeclared)
  1766. return
  1767. result[0] = semAsgn(c, n[0])
  1768. # optimize away ``result = result``:
  1769. if result[0][1].kind == nkSym and result[0][1].sym == c.p.resultSym:
  1770. result[0] = c.graph.emptyNode
  1771. else:
  1772. localError(c.config, n.info, "'return' not allowed here")
  1773. proc semProcBody(c: PContext, n: PNode; expectedType: PType = nil): PNode =
  1774. when defined(nimsuggest):
  1775. if c.graph.config.expandDone():
  1776. return n
  1777. openScope(c)
  1778. result = semExpr(c, n, expectedType = expectedType)
  1779. if c.p.resultSym != nil and not isEmptyType(result.typ):
  1780. if result.kind == nkNilLit:
  1781. # or ImplicitlyDiscardable(result):
  1782. # new semantic: 'result = x' triggers the void context
  1783. result.typ = nil
  1784. elif result.kind == nkStmtListExpr and result.typ.kind == tyNil:
  1785. # to keep backwards compatibility bodies like:
  1786. # nil
  1787. # # comment
  1788. # are not expressions:
  1789. fixNilType(c, result)
  1790. else:
  1791. var a = newNodeI(nkAsgn, n.info, 2)
  1792. a[0] = newSymNode(c.p.resultSym)
  1793. a[1] = result
  1794. result = semAsgn(c, a)
  1795. else:
  1796. discardCheck(c, result, {})
  1797. if c.p.owner.kind notin {skMacro, skTemplate} and
  1798. c.p.resultSym != nil and c.p.resultSym.typ.isMetaType:
  1799. if isEmptyType(result.typ):
  1800. # we inferred a 'void' return type:
  1801. c.p.resultSym.typ = errorType(c)
  1802. c.p.owner.typ[0] = nil
  1803. else:
  1804. localError(c.config, c.p.resultSym.info, errCannotInferReturnType %
  1805. c.p.owner.name.s)
  1806. if isIterator(c.p.owner.typ) and c.p.owner.typ[0] != nil and
  1807. c.p.owner.typ[0].kind == tyAnything:
  1808. localError(c.config, c.p.owner.info, errCannotInferReturnType %
  1809. c.p.owner.name.s)
  1810. closeScope(c)
  1811. proc semYieldVarResult(c: PContext, n: PNode, restype: PType) =
  1812. var t = skipTypes(restype, {tyGenericInst, tyAlias, tySink})
  1813. case t.kind
  1814. of tyVar, tyLent:
  1815. t.flags.incl tfVarIsPtr # bugfix for #4048, #4910, #6892
  1816. if n[0].kind in {nkHiddenStdConv, nkHiddenSubConv}:
  1817. n[0] = n[0][1]
  1818. n[0] = takeImplicitAddr(c, n[0], t.kind == tyLent)
  1819. of tyTuple:
  1820. for i in 0..<t.len:
  1821. let e = skipTypes(t[i], {tyGenericInst, tyAlias, tySink})
  1822. if e.kind in {tyVar, tyLent}:
  1823. e.flags.incl tfVarIsPtr # bugfix for #4048, #4910, #6892
  1824. let tupleConstr = if n[0].kind in {nkHiddenStdConv, nkHiddenSubConv}: n[0][1] else: n[0]
  1825. if tupleConstr.kind in {nkPar, nkTupleConstr}:
  1826. if tupleConstr[i].kind == nkExprColonExpr:
  1827. tupleConstr[i][1] = takeImplicitAddr(c, tupleConstr[i][1], e.kind == tyLent)
  1828. else:
  1829. tupleConstr[i] = takeImplicitAddr(c, tupleConstr[i], e.kind == tyLent)
  1830. else:
  1831. localError(c.config, n[0].info, errXExpected, "tuple constructor")
  1832. elif e.kind == tyEmpty:
  1833. localError(c.config, n[0].info, errTypeExpected)
  1834. else:
  1835. when false:
  1836. # XXX investigate what we really need here.
  1837. if isViewType(t):
  1838. n[0] = takeImplicitAddr(c, n[0], false)
  1839. proc semYield(c: PContext, n: PNode): PNode =
  1840. result = n
  1841. checkSonsLen(n, 1, c.config)
  1842. if c.p.owner == nil or c.p.owner.kind != skIterator:
  1843. localError(c.config, n.info, errYieldNotAllowedHere)
  1844. elif n[0].kind != nkEmpty:
  1845. n[0] = semExprWithType(c, n[0]) # check for type compatibility:
  1846. var iterType = c.p.owner.typ
  1847. let restype = iterType[0]
  1848. if restype != nil:
  1849. if restype.kind != tyUntyped:
  1850. n[0] = fitNode(c, restype, n[0], n.info)
  1851. if n[0].typ == nil: internalError(c.config, n.info, "semYield")
  1852. if resultTypeIsInferrable(restype):
  1853. let inferred = n[0].typ
  1854. iterType[0] = inferred
  1855. if c.p.resultSym != nil:
  1856. c.p.resultSym.typ = inferred
  1857. semYieldVarResult(c, n, restype)
  1858. else:
  1859. localError(c.config, n.info, errCannotReturnExpr)
  1860. elif c.p.owner.typ[0] != nil:
  1861. localError(c.config, n.info, errGenerated, "yield statement must yield a value")
  1862. proc considerQuotedIdentOrDot(c: PContext, n: PNode, origin: PNode = nil): PIdent =
  1863. if n.kind == nkDotExpr:
  1864. let a = considerQuotedIdentOrDot(c, n[0], origin).s
  1865. let b = considerQuotedIdentOrDot(c, n[1], origin).s
  1866. var s = newStringOfCap(a.len + b.len + 1)
  1867. s.add(a)
  1868. s.add('.')
  1869. s.add(b)
  1870. result = getIdent(c.cache, s)
  1871. else:
  1872. result = considerQuotedIdent(c, n, origin)
  1873. proc semDefined(c: PContext, n: PNode): PNode =
  1874. checkSonsLen(n, 2, c.config)
  1875. # we replace this node by a 'true' or 'false' node:
  1876. result = newIntNode(nkIntLit, 0)
  1877. result.intVal = ord isDefined(c.config, considerQuotedIdentOrDot(c, n[1], n).s)
  1878. result.info = n.info
  1879. result.typ = getSysType(c.graph, n.info, tyBool)
  1880. proc lookUpForDeclared(c: PContext, n: PNode, onlyCurrentScope: bool): PSym =
  1881. case n.kind
  1882. of nkIdent, nkAccQuoted:
  1883. var amb = false
  1884. let ident = considerQuotedIdent(c, n)
  1885. result = if onlyCurrentScope:
  1886. localSearchInScope(c, ident)
  1887. else:
  1888. searchInScopes(c, ident, amb)
  1889. of nkDotExpr:
  1890. result = nil
  1891. if onlyCurrentScope: return
  1892. checkSonsLen(n, 2, c.config)
  1893. var m = lookUpForDeclared(c, n[0], onlyCurrentScope)
  1894. if m != nil and m.kind == skModule:
  1895. let ident = considerQuotedIdent(c, n[1], n)
  1896. if m == c.module:
  1897. result = strTableGet(c.topLevelScope.symbols, ident)
  1898. else:
  1899. result = someSym(c.graph, m, ident)
  1900. of nkSym:
  1901. result = n.sym
  1902. of nkOpenSymChoice, nkClosedSymChoice:
  1903. result = n[0].sym
  1904. else:
  1905. localError(c.config, n.info, "identifier expected, but got: " & renderTree(n))
  1906. result = nil
  1907. proc semDeclared(c: PContext, n: PNode, onlyCurrentScope: bool): PNode =
  1908. checkSonsLen(n, 2, c.config)
  1909. # we replace this node by a 'true' or 'false' node:
  1910. result = newIntNode(nkIntLit, 0)
  1911. result.intVal = ord lookUpForDeclared(c, n[1], onlyCurrentScope) != nil
  1912. result.info = n.info
  1913. result.typ = getSysType(c.graph, n.info, tyBool)
  1914. proc expectMacroOrTemplateCall(c: PContext, n: PNode): PSym =
  1915. ## The argument to the proc should be nkCall(...) or similar
  1916. ## Returns the macro/template symbol
  1917. if isCallExpr(n):
  1918. var expandedSym = qualifiedLookUp(c, n[0], {checkUndeclared})
  1919. if expandedSym == nil:
  1920. errorUndeclaredIdentifier(c, n.info, n[0].renderTree)
  1921. return errorSym(c, n[0])
  1922. if expandedSym.kind notin {skMacro, skTemplate}:
  1923. localError(c.config, n.info, "'$1' is not a macro or template" % expandedSym.name.s)
  1924. return errorSym(c, n[0])
  1925. result = expandedSym
  1926. else:
  1927. localError(c.config, n.info, "'$1' is not a macro or template" % n.renderTree)
  1928. result = errorSym(c, n)
  1929. proc expectString(c: PContext, n: PNode): string =
  1930. var n = semConstExpr(c, n)
  1931. if n.kind in nkStrKinds:
  1932. return n.strVal
  1933. else:
  1934. localError(c.config, n.info, errStringLiteralExpected)
  1935. proc newAnonSym(c: PContext; kind: TSymKind, info: TLineInfo): PSym =
  1936. result = newSym(kind, c.cache.idAnon, nextSymId c.idgen, getCurrOwner(c), info)
  1937. proc semExpandToAst(c: PContext, n: PNode): PNode =
  1938. let macroCall = n[1]
  1939. when false:
  1940. let expandedSym = expectMacroOrTemplateCall(c, macroCall)
  1941. if expandedSym.kind == skError: return n
  1942. macroCall[0] = newSymNode(expandedSym, macroCall.info)
  1943. markUsed(c, n.info, expandedSym)
  1944. onUse(n.info, expandedSym)
  1945. if isCallExpr(macroCall):
  1946. for i in 1..<macroCall.len:
  1947. #if macroCall[0].typ[i].kind != tyUntyped:
  1948. macroCall[i] = semExprWithType(c, macroCall[i], {})
  1949. # performing overloading resolution here produces too serious regressions:
  1950. let headSymbol = macroCall[0]
  1951. var cands = 0
  1952. var cand: PSym = nil
  1953. var o: TOverloadIter
  1954. var symx = initOverloadIter(o, c, headSymbol)
  1955. while symx != nil:
  1956. if symx.kind in {skTemplate, skMacro} and symx.typ.len == macroCall.len:
  1957. cand = symx
  1958. inc cands
  1959. symx = nextOverloadIter(o, c, headSymbol)
  1960. if cands == 0:
  1961. localError(c.config, n.info, "expected a template that takes " & $(macroCall.len-1) & " arguments")
  1962. elif cands >= 2:
  1963. localError(c.config, n.info, "ambiguous symbol in 'getAst' context: " & $macroCall)
  1964. else:
  1965. let info = macroCall[0].info
  1966. macroCall[0] = newSymNode(cand, info)
  1967. markUsed(c, info, cand)
  1968. onUse(info, cand)
  1969. # we just perform overloading resolution here:
  1970. #n[1] = semOverloadedCall(c, macroCall, macroCall, {skTemplate, skMacro})
  1971. else:
  1972. localError(c.config, n.info, "getAst takes a call, but got " & n.renderTree)
  1973. # Preserve the magic symbol in order to be handled in evals.nim
  1974. internalAssert c.config, n[0].sym.magic == mExpandToAst
  1975. #n.typ = getSysSym("NimNode").typ # expandedSym.getReturnType
  1976. if n.kind == nkStmtList and n.len == 1: result = n[0]
  1977. else: result = n
  1978. result.typ = sysTypeFromName(c.graph, n.info, "NimNode")
  1979. proc semExpandToAst(c: PContext, n: PNode, magicSym: PSym,
  1980. flags: TExprFlags = {}): PNode =
  1981. if n.len == 2:
  1982. n[0] = newSymNode(magicSym, n.info)
  1983. result = semExpandToAst(c, n)
  1984. else:
  1985. result = semDirectOp(c, n, flags)
  1986. proc processQuotations(c: PContext; n: var PNode, op: string,
  1987. quotes: var seq[PNode],
  1988. ids: var seq[PNode]) =
  1989. template returnQuote(q) =
  1990. quotes.add q
  1991. n = newIdentNode(getIdent(c.cache, $quotes.len), n.info)
  1992. ids.add n
  1993. return
  1994. template handlePrefixOp(prefixed) =
  1995. if prefixed[0].kind == nkIdent:
  1996. let examinedOp = prefixed[0].ident.s
  1997. if examinedOp == op:
  1998. returnQuote prefixed[1]
  1999. elif examinedOp.startsWith(op):
  2000. prefixed[0] = newIdentNode(getIdent(c.cache, examinedOp.substr(op.len)), prefixed.info)
  2001. if n.kind == nkPrefix:
  2002. checkSonsLen(n, 2, c.config)
  2003. handlePrefixOp(n)
  2004. elif n.kind == nkAccQuoted:
  2005. if op == "``":
  2006. returnQuote n[0]
  2007. else: # [bug #7589](https://github.com/nim-lang/Nim/issues/7589)
  2008. if n.len == 2 and n[0].ident.s == op:
  2009. var tempNode = nkPrefix.newTree()
  2010. tempNode.newSons(2)
  2011. tempNode[0] = n[0]
  2012. tempNode[1] = n[1]
  2013. handlePrefixOp(tempNode)
  2014. elif n.kind == nkIdent:
  2015. if n.ident.s == "result":
  2016. n = ids[0]
  2017. for i in 0..<n.safeLen:
  2018. processQuotations(c, n[i], op, quotes, ids)
  2019. proc semQuoteAst(c: PContext, n: PNode): PNode =
  2020. if n.len != 2 and n.len != 3:
  2021. localError(c.config, n.info, "'quote' expects 1 or 2 arguments")
  2022. return n
  2023. # We transform the do block into a template with a param for
  2024. # each interpolation. We'll pass this template to getAst.
  2025. var
  2026. quotedBlock = n[^1]
  2027. op = if n.len == 3: expectString(c, n[1]) else: "``"
  2028. quotes = newSeq[PNode](2)
  2029. # the quotes will be added to a nkCall statement
  2030. # leave some room for the callee symbol and the result symbol
  2031. ids = newSeq[PNode](1)
  2032. # this will store the generated param names
  2033. # leave some room for the result symbol
  2034. if quotedBlock.kind != nkStmtList:
  2035. localError(c.config, n.info, errXExpected, "block")
  2036. # This adds a default first field to pass the result symbol
  2037. ids[0] = newAnonSym(c, skParam, n.info).newSymNode
  2038. processQuotations(c, quotedBlock, op, quotes, ids)
  2039. let dummyTemplateSym = newAnonSym(c, skTemplate, n.info)
  2040. incl(dummyTemplateSym.flags, sfTemplateRedefinition)
  2041. var dummyTemplate = newProcNode(
  2042. nkTemplateDef, quotedBlock.info, body = quotedBlock,
  2043. params = c.graph.emptyNode,
  2044. name = dummyTemplateSym.newSymNode,
  2045. pattern = c.graph.emptyNode, genericParams = c.graph.emptyNode,
  2046. pragmas = c.graph.emptyNode, exceptions = c.graph.emptyNode)
  2047. if ids.len > 0:
  2048. dummyTemplate[paramsPos] = newNodeI(nkFormalParams, n.info)
  2049. dummyTemplate[paramsPos].add getSysSym(c.graph, n.info, "untyped").newSymNode # return type
  2050. dummyTemplate[paramsPos].add newTreeI(nkIdentDefs, n.info, ids[0], getSysSym(c.graph, n.info, "typed").newSymNode, c.graph.emptyNode)
  2051. for i in 1..<ids.len:
  2052. let typ = semExprWithType(c, quotes[i+1], {}).typ
  2053. if tfTriggersCompileTime notin typ.flags and typ.kind != tyTypeDesc:
  2054. dummyTemplate[paramsPos].add newTreeI(nkIdentDefs, n.info, ids[i], newNodeIT(nkType, n.info, typ), c.graph.emptyNode)
  2055. else:
  2056. dummyTemplate[paramsPos].add newTreeI(nkIdentDefs, n.info, ids[i], getSysSym(c.graph, n.info, "typed").newSymNode, c.graph.emptyNode)
  2057. var tmpl = semTemplateDef(c, dummyTemplate)
  2058. quotes[0] = tmpl[namePos]
  2059. # This adds a call to newIdentNode("result") as the first argument to the template call
  2060. let identNodeSym = getCompilerProc(c.graph, "newIdentNode")
  2061. # so that new Nim compilers can compile old macros.nim versions, we check for 'nil'
  2062. # here and provide the old fallback solution:
  2063. let identNode = if identNodeSym == nil:
  2064. newIdentNode(getIdent(c.cache, "newIdentNode"), n.info)
  2065. else:
  2066. identNodeSym.newSymNode
  2067. quotes[1] = newTreeI(nkCall, n.info, identNode, newStrNode(nkStrLit, "result"))
  2068. result = newTreeI(nkCall, n.info,
  2069. createMagic(c.graph, c.idgen, "getAst", mExpandToAst).newSymNode,
  2070. newTreeI(nkCall, n.info, quotes))
  2071. result = semExpandToAst(c, result)
  2072. proc tryExpr(c: PContext, n: PNode, flags: TExprFlags = {}): PNode =
  2073. # watch out, hacks ahead:
  2074. when defined(nimsuggest):
  2075. # Remove the error hook so nimsuggest doesn't report errors there
  2076. let tempHook = c.graph.config.structuredErrorHook
  2077. c.graph.config.structuredErrorHook = nil
  2078. let oldErrorCount = c.config.errorCounter
  2079. let oldErrorMax = c.config.errorMax
  2080. let oldCompilesId = c.compilesContextId
  2081. # if this is a nested 'when compiles', do not increase the ID so that
  2082. # generic instantiations can still be cached for this level.
  2083. if c.compilesContextId == 0:
  2084. inc c.compilesContextIdGenerator
  2085. c.compilesContextId = c.compilesContextIdGenerator
  2086. c.config.errorMax = high(int) # `setErrorMaxHighMaybe` not appropriate here
  2087. # open a scope for temporary symbol inclusions:
  2088. let oldScope = c.currentScope
  2089. openScope(c)
  2090. let oldOwnerLen = c.graph.owners.len
  2091. let oldGenerics = c.generics
  2092. let oldErrorOutputs = c.config.m.errorOutputs
  2093. if efExplain notin flags: c.config.m.errorOutputs = {}
  2094. let oldContextLen = msgs.getInfoContextLen(c.config)
  2095. let oldInGenericContext = c.inGenericContext
  2096. let oldInUnrolledContext = c.inUnrolledContext
  2097. let oldInGenericInst = c.inGenericInst
  2098. let oldInStaticContext = c.inStaticContext
  2099. let oldProcCon = c.p
  2100. c.generics = @[]
  2101. var err: string
  2102. try:
  2103. result = semExpr(c, n, flags)
  2104. if result != nil and efNoSem2Check notin flags:
  2105. trackStmt(c, c.module, result, isTopLevel = false)
  2106. if c.config.errorCounter != oldErrorCount:
  2107. result = nil
  2108. except ERecoverableError:
  2109. discard
  2110. # undo symbol table changes (as far as it's possible):
  2111. c.compilesContextId = oldCompilesId
  2112. c.generics = oldGenerics
  2113. c.inGenericContext = oldInGenericContext
  2114. c.inUnrolledContext = oldInUnrolledContext
  2115. c.inGenericInst = oldInGenericInst
  2116. c.inStaticContext = oldInStaticContext
  2117. c.p = oldProcCon
  2118. msgs.setInfoContextLen(c.config, oldContextLen)
  2119. setLen(c.graph.owners, oldOwnerLen)
  2120. c.currentScope = oldScope
  2121. c.config.m.errorOutputs = oldErrorOutputs
  2122. c.config.errorCounter = oldErrorCount
  2123. c.config.errorMax = oldErrorMax
  2124. when defined(nimsuggest):
  2125. # Restore the error hook
  2126. c.graph.config.structuredErrorHook = tempHook
  2127. proc semCompiles(c: PContext, n: PNode, flags: TExprFlags): PNode =
  2128. # we replace this node by a 'true' or 'false' node:
  2129. if n.len != 2: return semDirectOp(c, n, flags)
  2130. result = newIntNode(nkIntLit, ord(tryExpr(c, n[1], flags) != nil))
  2131. result.info = n.info
  2132. result.typ = getSysType(c.graph, n.info, tyBool)
  2133. proc semShallowCopy(c: PContext, n: PNode, flags: TExprFlags): PNode =
  2134. if n.len == 3:
  2135. # XXX ugh this is really a hack: shallowCopy() can be overloaded only
  2136. # with procs that take not 2 parameters:
  2137. result = newNodeI(nkFastAsgn, n.info)
  2138. result.add(n[1])
  2139. result.add(n[2])
  2140. result = semAsgn(c, result)
  2141. else:
  2142. result = semDirectOp(c, n, flags)
  2143. proc createFlowVar(c: PContext; t: PType; info: TLineInfo): PType =
  2144. result = newType(tyGenericInvocation, nextTypeId c.idgen, c.module)
  2145. addSonSkipIntLit(result, magicsys.getCompilerProc(c.graph, "FlowVar").typ, c.idgen)
  2146. addSonSkipIntLit(result, t, c.idgen)
  2147. result = instGenericContainer(c, info, result, allowMetaTypes = false)
  2148. proc instantiateCreateFlowVarCall(c: PContext; t: PType;
  2149. info: TLineInfo): PSym =
  2150. let sym = magicsys.getCompilerProc(c.graph, "nimCreateFlowVar")
  2151. if sym == nil:
  2152. localError(c.config, info, "system needs: nimCreateFlowVar")
  2153. var bindings: TIdTable
  2154. initIdTable(bindings)
  2155. bindings.idTablePut(sym.ast[genericParamsPos][0].typ, t)
  2156. result = c.semGenerateInstance(c, sym, bindings, info)
  2157. # since it's an instantiation, we unmark it as a compilerproc. Otherwise
  2158. # codegen would fail:
  2159. if sfCompilerProc in result.flags:
  2160. result.flags.excl {sfCompilerProc, sfExportc, sfImportc}
  2161. result.loc.r = ""
  2162. proc setMs(n: PNode, s: PSym): PNode =
  2163. result = n
  2164. n[0] = newSymNode(s)
  2165. n[0].info = n.info
  2166. proc semSizeof(c: PContext, n: PNode): PNode =
  2167. if n.len != 2:
  2168. localError(c.config, n.info, errXExpectsTypeOrValue % "sizeof")
  2169. else:
  2170. n[1] = semExprWithType(c, n[1], {efDetermineType})
  2171. #restoreOldStyleType(n[1])
  2172. n.typ = getSysType(c.graph, n.info, tyInt)
  2173. result = foldSizeOf(c.config, n, n)
  2174. proc semMagic(c: PContext, n: PNode, s: PSym, flags: TExprFlags; expectedType: PType = nil): PNode =
  2175. # this is a hotspot in the compiler!
  2176. result = n
  2177. case s.magic # magics that need special treatment
  2178. of mAddr:
  2179. markUsed(c, n.info, s)
  2180. checkSonsLen(n, 2, c.config)
  2181. result[0] = newSymNode(s, n[0].info)
  2182. result[1] = semAddrArg(c, n[1])
  2183. result.typ = makePtrType(c, result[1].typ)
  2184. of mTypeOf:
  2185. markUsed(c, n.info, s)
  2186. result = semTypeOf(c, n)
  2187. of mDefined:
  2188. markUsed(c, n.info, s)
  2189. result = semDefined(c, setMs(n, s))
  2190. of mDeclared:
  2191. markUsed(c, n.info, s)
  2192. result = semDeclared(c, setMs(n, s), false)
  2193. of mDeclaredInScope:
  2194. markUsed(c, n.info, s)
  2195. result = semDeclared(c, setMs(n, s), true)
  2196. of mCompiles:
  2197. markUsed(c, n.info, s)
  2198. result = semCompiles(c, setMs(n, s), flags)
  2199. of mIs:
  2200. markUsed(c, n.info, s)
  2201. result = semIs(c, setMs(n, s), flags)
  2202. of mShallowCopy:
  2203. markUsed(c, n.info, s)
  2204. result = semShallowCopy(c, n, flags)
  2205. of mExpandToAst:
  2206. markUsed(c, n.info, s)
  2207. result = semExpandToAst(c, n, s, flags)
  2208. of mQuoteAst:
  2209. markUsed(c, n.info, s)
  2210. result = semQuoteAst(c, n)
  2211. of mAstToStr:
  2212. markUsed(c, n.info, s)
  2213. checkSonsLen(n, 2, c.config)
  2214. result = newStrNodeT(renderTree(n[1], {renderNoComments}), n, c.graph)
  2215. result.typ = getSysType(c.graph, n.info, tyString)
  2216. of mParallel:
  2217. markUsed(c, n.info, s)
  2218. if parallel notin c.features:
  2219. localError(c.config, n.info, "use the {.experimental.} pragma to enable 'parallel'")
  2220. result = setMs(n, s)
  2221. var x = n.lastSon
  2222. if x.kind == nkDo: x = x[bodyPos]
  2223. inc c.inParallelStmt
  2224. result[1] = semStmt(c, x, {})
  2225. dec c.inParallelStmt
  2226. of mSpawn:
  2227. markUsed(c, n.info, s)
  2228. when defined(leanCompiler):
  2229. result = localErrorNode(c, n, "compiler was built without 'spawn' support")
  2230. else:
  2231. result = setMs(n, s)
  2232. for i in 1..<n.len:
  2233. result[i] = semExpr(c, n[i])
  2234. if n.len > 1 and n[1].kind notin nkCallKinds:
  2235. return localErrorNode(c, n, n[1].info, "'spawn' takes a call expression; got: " & $n[1])
  2236. let typ = result[^1].typ
  2237. if not typ.isEmptyType:
  2238. if spawnResult(typ, c.inParallelStmt > 0) == srFlowVar:
  2239. result.typ = createFlowVar(c, typ, n.info)
  2240. else:
  2241. result.typ = typ
  2242. result.add instantiateCreateFlowVarCall(c, typ, n.info).newSymNode
  2243. else:
  2244. result.add c.graph.emptyNode
  2245. of mProcCall:
  2246. markUsed(c, n.info, s)
  2247. result = setMs(n, s)
  2248. result[1] = semExpr(c, n[1])
  2249. result.typ = n[1].typ
  2250. of mPlugin:
  2251. markUsed(c, n.info, s)
  2252. # semDirectOp with conditional 'afterCallActions':
  2253. let nOrig = n.copyTree
  2254. #semLazyOpAux(c, n)
  2255. result = semOverloadedCallAnalyseEffects(c, n, nOrig, flags)
  2256. if result == nil:
  2257. result = errorNode(c, n)
  2258. else:
  2259. let callee = result[0].sym
  2260. if callee.magic == mNone:
  2261. semFinishOperands(c, result)
  2262. activate(c, result)
  2263. fixAbstractType(c, result)
  2264. analyseIfAddressTakenInCall(c, result)
  2265. if callee.magic != mNone:
  2266. result = magicsAfterOverloadResolution(c, result, flags)
  2267. of mRunnableExamples:
  2268. markUsed(c, n.info, s)
  2269. if c.config.cmd in cmdDocLike and n.len >= 2 and n.lastSon.kind == nkStmtList:
  2270. when false:
  2271. # some of this dead code was moved to `prepareExamples`
  2272. if sfMainModule in c.module.flags:
  2273. let inp = toFullPath(c.config, c.module.info)
  2274. if c.runnableExamples == nil:
  2275. c.runnableExamples = newTree(nkStmtList,
  2276. newTree(nkImportStmt, newStrNode(nkStrLit, expandFilename(inp))))
  2277. let imports = newTree(nkStmtList)
  2278. var savedLastSon = copyTree n.lastSon
  2279. extractImports(savedLastSon, imports)
  2280. for imp in imports: c.runnableExamples.add imp
  2281. c.runnableExamples.add newTree(nkBlockStmt, c.graph.emptyNode, copyTree savedLastSon)
  2282. result = setMs(n, s)
  2283. else:
  2284. result = c.graph.emptyNode
  2285. of mSizeOf:
  2286. markUsed(c, n.info, s)
  2287. result = semSizeof(c, setMs(n, s))
  2288. of mArrToSeq, mOpenArrayToSeq:
  2289. if expectedType != nil and (
  2290. let expected = expectedType.skipTypes(abstractRange-{tyDistinct});
  2291. expected.kind in {tySequence, tyOpenArray}):
  2292. # seq type inference
  2293. var arrayType = newType(tyOpenArray, nextTypeId(c.idgen), expected.owner)
  2294. arrayType.rawAddSon(expected[0])
  2295. if n[0].kind == nkSym and sfFromGeneric in n[0].sym.flags:
  2296. # may have been resolved to `@`[empty] at some point,
  2297. # reset to `@` to deal with this
  2298. n[0] = newSymNode(n[0].sym.owner, n[0].info)
  2299. n[1] = semExpr(c, n[1], flags, arrayType)
  2300. result = semDirectOp(c, n, flags, expectedType)
  2301. else:
  2302. result = semDirectOp(c, n, flags, expectedType)
  2303. proc semWhen(c: PContext, n: PNode, semCheck = true): PNode =
  2304. # If semCheck is set to false, ``when`` will return the verbatim AST of
  2305. # the correct branch. Otherwise the AST will be passed through semStmt.
  2306. result = nil
  2307. template setResult(e: untyped) =
  2308. if semCheck: result = semExpr(c, e) # do not open a new scope!
  2309. else: result = e
  2310. # Check if the node is "when nimvm"
  2311. # when nimvm:
  2312. # ...
  2313. # else:
  2314. # ...
  2315. var whenNimvm = false
  2316. var typ = commonTypeBegin
  2317. if n.len in 1..2 and n[0].kind == nkElifBranch and (
  2318. n.len == 1 or n[1].kind == nkElse):
  2319. let exprNode = n[0][0]
  2320. if exprNode.kind == nkIdent:
  2321. whenNimvm = lookUp(c, exprNode).magic == mNimvm
  2322. elif exprNode.kind == nkSym:
  2323. whenNimvm = exprNode.sym.magic == mNimvm
  2324. if whenNimvm: n.flags.incl nfLL
  2325. for i in 0..<n.len:
  2326. var it = n[i]
  2327. case it.kind
  2328. of nkElifBranch, nkElifExpr:
  2329. checkSonsLen(it, 2, c.config)
  2330. if whenNimvm:
  2331. if semCheck:
  2332. it[1] = semExpr(c, it[1])
  2333. typ = commonType(c, typ, it[1].typ)
  2334. result = n # when nimvm is not elimited until codegen
  2335. else:
  2336. let e = forceBool(c, semConstExpr(c, it[0]))
  2337. if e.kind != nkIntLit:
  2338. # can happen for cascading errors, assume false
  2339. # InternalError(n.info, "semWhen")
  2340. discard
  2341. elif e.intVal != 0 and result == nil:
  2342. setResult(it[1])
  2343. return # we're not in nimvm and we already have a result
  2344. of nkElse, nkElseExpr:
  2345. checkSonsLen(it, 1, c.config)
  2346. if result == nil or whenNimvm:
  2347. if semCheck:
  2348. it[0] = semExpr(c, it[0])
  2349. typ = commonType(c, typ, it[0].typ)
  2350. if result == nil:
  2351. result = it[0]
  2352. else: illFormedAst(n, c.config)
  2353. if result == nil:
  2354. result = newNodeI(nkEmpty, n.info)
  2355. if whenNimvm:
  2356. result.typ = typ
  2357. if n.len == 1:
  2358. result.add(newTree(nkElse, newNode(nkStmtList)))
  2359. proc semSetConstr(c: PContext, n: PNode, expectedType: PType = nil): PNode =
  2360. result = newNodeI(nkCurly, n.info)
  2361. result.typ = newTypeS(tySet, c)
  2362. result.typ.flags.incl tfIsConstructor
  2363. var expectedElementType: PType = nil
  2364. if expectedType != nil and (
  2365. let expected = expectedType.skipTypes(abstractRange-{tyDistinct});
  2366. expected.kind == tySet):
  2367. expectedElementType = expected[0]
  2368. if n.len == 0:
  2369. rawAddSon(result.typ,
  2370. if expectedElementType != nil and
  2371. typeAllowed(expectedElementType, skLet, c) == nil:
  2372. expectedElementType
  2373. else:
  2374. newTypeS(tyEmpty, c))
  2375. else:
  2376. # only semantic checking for all elements, later type checking:
  2377. var typ: PType = nil
  2378. for i in 0..<n.len:
  2379. let doSetType = typ == nil
  2380. if isRange(n[i]):
  2381. checkSonsLen(n[i], 3, c.config)
  2382. n[i][1] = semExprWithType(c, n[i][1], {efTypeAllowed}, expectedElementType)
  2383. n[i][2] = semExprWithType(c, n[i][2], {efTypeAllowed}, expectedElementType)
  2384. if doSetType:
  2385. typ = skipTypes(n[i][1].typ,
  2386. {tyGenericInst, tyVar, tyLent, tyOrdinal, tyAlias, tySink})
  2387. n[i].typ = n[i][2].typ # range node needs type too
  2388. elif n[i].kind == nkRange:
  2389. # already semchecked
  2390. if doSetType:
  2391. typ = skipTypes(n[i][0].typ,
  2392. {tyGenericInst, tyVar, tyLent, tyOrdinal, tyAlias, tySink})
  2393. else:
  2394. n[i] = semExprWithType(c, n[i], {efTypeAllowed}, expectedElementType)
  2395. if doSetType:
  2396. typ = skipTypes(n[i].typ, {tyGenericInst, tyVar, tyLent, tyOrdinal, tyAlias, tySink})
  2397. if doSetType:
  2398. if not isOrdinalType(typ, allowEnumWithHoles=true):
  2399. localError(c.config, n.info, errOrdinalTypeExpected % typeToString(typ, preferDesc))
  2400. typ = makeRangeType(c, 0, MaxSetElements-1, n.info)
  2401. elif isIntLit(typ):
  2402. # set of int literal, use a default range smaller than the max range
  2403. typ = makeRangeType(c, 0, DefaultSetElements-1, n.info)
  2404. elif lengthOrd(c.config, typ) > MaxSetElements:
  2405. message(c.config, n.info, warnAboveMaxSizeSet, "type '" &
  2406. typeToString(typ, preferDesc) & "' is too big to be a `set` element, " &
  2407. "assuming a range of 0.." & $(MaxSetElements - 1) &
  2408. ", explicitly write this range to get rid of warning")
  2409. typ = makeRangeType(c, 0, MaxSetElements-1, n.info)
  2410. if expectedElementType == nil:
  2411. expectedElementType = typ
  2412. addSonSkipIntLit(result.typ, typ, c.idgen)
  2413. for i in 0..<n.len:
  2414. var m: PNode
  2415. let info = n[i].info
  2416. if isRange(n[i]):
  2417. m = newNodeI(nkRange, info)
  2418. m.add fitNode(c, typ, n[i][1], info)
  2419. m.add fitNode(c, typ, n[i][2], info)
  2420. elif n[i].kind == nkRange: m = n[i] # already semchecked
  2421. else:
  2422. m = fitNode(c, typ, n[i], info)
  2423. result.add m
  2424. proc semTableConstr(c: PContext, n: PNode; expectedType: PType = nil): PNode =
  2425. # we simply transform ``{key: value, key2, key3: value}`` to
  2426. # ``[(key, value), (key2, value2), (key3, value2)]``
  2427. result = newNodeI(nkBracket, n.info)
  2428. var lastKey = 0
  2429. for i in 0..<n.len:
  2430. var x = n[i]
  2431. if x.kind == nkExprColonExpr and x.len == 2:
  2432. for j in lastKey..<i:
  2433. var pair = newNodeI(nkTupleConstr, x.info)
  2434. pair.add(n[j])
  2435. pair.add(x[1])
  2436. result.add(pair)
  2437. var pair = newNodeI(nkTupleConstr, x.info)
  2438. pair.add(x[0])
  2439. pair.add(x[1])
  2440. result.add(pair)
  2441. lastKey = i+1
  2442. if lastKey != n.len: illFormedAst(n, c.config)
  2443. result = semExpr(c, result, expectedType = expectedType)
  2444. type
  2445. TParKind = enum
  2446. paNone, paSingle, paTupleFields, paTuplePositions
  2447. proc checkPar(c: PContext; n: PNode): TParKind =
  2448. if n.len == 0:
  2449. result = paTuplePositions # ()
  2450. elif n.len == 1:
  2451. if n[0].kind == nkExprColonExpr: result = paTupleFields
  2452. elif n.kind == nkTupleConstr: result = paTuplePositions
  2453. else: result = paSingle # (expr)
  2454. else:
  2455. if n[0].kind == nkExprColonExpr: result = paTupleFields
  2456. else: result = paTuplePositions
  2457. for i in 0..<n.len:
  2458. if result == paTupleFields:
  2459. if (n[i].kind != nkExprColonExpr) or
  2460. n[i][0].kind notin {nkSym, nkIdent, nkAccQuoted}:
  2461. localError(c.config, n[i].info, errNamedExprExpected)
  2462. return paNone
  2463. else:
  2464. if n[i].kind == nkExprColonExpr:
  2465. localError(c.config, n[i].info, errNamedExprNotAllowed)
  2466. return paNone
  2467. proc semTupleFieldsConstr(c: PContext, n: PNode, flags: TExprFlags; expectedType: PType = nil): PNode =
  2468. result = newNodeI(nkTupleConstr, n.info)
  2469. var expected: PType = nil
  2470. if expectedType != nil:
  2471. expected = expectedType.skipTypes(abstractRange-{tyDistinct})
  2472. if not (expected.kind == tyTuple and expected.len == n.len):
  2473. expected = nil
  2474. var typ = newTypeS(tyTuple, c)
  2475. typ.n = newNodeI(nkRecList, n.info) # nkIdentDefs
  2476. var ids = initIntSet()
  2477. for i in 0..<n.len:
  2478. if n[i].kind != nkExprColonExpr:
  2479. illFormedAst(n[i], c.config)
  2480. let id = considerQuotedIdent(c, n[i][0])
  2481. if containsOrIncl(ids, id.id):
  2482. localError(c.config, n[i].info, errFieldInitTwice % id.s)
  2483. # can check if field name matches expected type here
  2484. let expectedElemType = if expected != nil: expected[i] else: nil
  2485. n[i][1] = semExprWithType(c, n[i][1], {}, expectedElemType)
  2486. if n[i][1].typ.kind == tyTypeDesc:
  2487. localError(c.config, n[i][1].info, "typedesc not allowed as tuple field.")
  2488. n[i][1].typ = errorType(c)
  2489. var f = newSymS(skField, n[i][0], c)
  2490. f.typ = skipIntLit(n[i][1].typ, c.idgen)
  2491. f.position = i
  2492. rawAddSon(typ, f.typ)
  2493. typ.n.add newSymNode(f)
  2494. n[i][0] = newSymNode(f)
  2495. result.add n[i]
  2496. result.typ = typ
  2497. proc semTuplePositionsConstr(c: PContext, n: PNode, flags: TExprFlags; expectedType: PType = nil): PNode =
  2498. result = n # we don't modify n, but compute the type:
  2499. result.transitionSonsKind(nkTupleConstr)
  2500. var expected: PType = nil
  2501. if expectedType != nil:
  2502. expected = expectedType.skipTypes(abstractRange-{tyDistinct})
  2503. if not (expected.kind == tyTuple and expected.len == n.len):
  2504. expected = nil
  2505. var typ = newTypeS(tyTuple, c) # leave typ.n nil!
  2506. for i in 0..<n.len:
  2507. let expectedElemType = if expected != nil: expected[i] else: nil
  2508. n[i] = semExprWithType(c, n[i], {}, expectedElemType)
  2509. addSonSkipIntLit(typ, n[i].typ, c.idgen)
  2510. result.typ = typ
  2511. include semobjconstr
  2512. proc semBlock(c: PContext, n: PNode; flags: TExprFlags; expectedType: PType = nil): PNode =
  2513. result = n
  2514. inc(c.p.nestedBlockCounter)
  2515. let oldBreakInLoop = c.p.breakInLoop
  2516. c.p.breakInLoop = false
  2517. checkSonsLen(n, 2, c.config)
  2518. openScope(c) # BUGFIX: label is in the scope of block!
  2519. if n[0].kind != nkEmpty:
  2520. var labl = newSymG(skLabel, n[0], c)
  2521. if sfGenSym notin labl.flags:
  2522. addDecl(c, labl)
  2523. elif labl.owner == nil:
  2524. labl.owner = c.p.owner
  2525. n[0] = newSymNode(labl, n[0].info)
  2526. suggestSym(c.graph, n[0].info, labl, c.graph.usageSym)
  2527. styleCheckDef(c, labl)
  2528. onDef(n[0].info, labl)
  2529. n[1] = semExpr(c, n[1], flags, expectedType)
  2530. n.typ = n[1].typ
  2531. if isEmptyType(n.typ): n.transitionSonsKind(nkBlockStmt)
  2532. else: n.transitionSonsKind(nkBlockExpr)
  2533. closeScope(c)
  2534. c.p.breakInLoop = oldBreakInLoop
  2535. dec(c.p.nestedBlockCounter)
  2536. proc semExportExcept(c: PContext, n: PNode): PNode =
  2537. let moduleName = semExpr(c, n[0])
  2538. if moduleName.kind != nkSym or moduleName.sym.kind != skModule:
  2539. localError(c.config, n.info, "The export/except syntax expects a module name")
  2540. return n
  2541. let exceptSet = readExceptSet(c, n)
  2542. let exported = moduleName.sym
  2543. result = newNodeI(nkExportStmt, n.info)
  2544. reexportSym(c, exported)
  2545. for s in allSyms(c.graph, exported):
  2546. if s.kind in ExportableSymKinds+{skModule} and
  2547. s.name.id notin exceptSet and sfError notin s.flags:
  2548. reexportSym(c, s)
  2549. result.add newSymNode(s, n.info)
  2550. markUsed(c, n.info, exported)
  2551. proc semExport(c: PContext, n: PNode): PNode =
  2552. proc specialSyms(c: PContext; s: PSym) {.inline.} =
  2553. if s.kind == skConverter: addConverter(c, LazySym(sym: s))
  2554. elif s.kind == skType and s.typ != nil and s.typ.kind == tyEnum and sfPure in s.flags:
  2555. addPureEnum(c, LazySym(sym: s))
  2556. result = newNodeI(nkExportStmt, n.info)
  2557. for i in 0..<n.len:
  2558. let a = n[i]
  2559. var o: TOverloadIter
  2560. var s = initOverloadIter(o, c, a)
  2561. if s == nil:
  2562. localError(c.config, a.info, errGenerated, "cannot export: " & renderTree(a))
  2563. elif s.kind == skModule:
  2564. # forward everything from that module:
  2565. reexportSym(c, s)
  2566. for it in allSyms(c.graph, s):
  2567. if it.kind in ExportableSymKinds+{skModule}:
  2568. reexportSym(c, it)
  2569. result.add newSymNode(it, a.info)
  2570. specialSyms(c, it)
  2571. markUsed(c, n.info, s)
  2572. else:
  2573. while s != nil:
  2574. if s.kind == skEnumField:
  2575. localError(c.config, a.info, errGenerated, "cannot export: " & renderTree(a) &
  2576. "; enum field cannot be exported individually")
  2577. if s.kind in ExportableSymKinds+{skModule} and sfError notin s.flags:
  2578. result.add(newSymNode(s, a.info))
  2579. reexportSym(c, s)
  2580. markUsed(c, n.info, s)
  2581. specialSyms(c, s)
  2582. if s.kind == skType and sfPure notin s.flags:
  2583. var etyp = s.typ
  2584. if etyp.kind in {tyBool, tyEnum}:
  2585. for j in 0..<etyp.n.len:
  2586. var e = etyp.n[j].sym
  2587. if e.kind != skEnumField:
  2588. internalError(c.config, s.info, "rawImportSymbol")
  2589. reexportSym(c, e)
  2590. s = nextOverloadIter(o, c, a)
  2591. proc semTupleConstr(c: PContext, n: PNode, flags: TExprFlags; expectedType: PType = nil): PNode =
  2592. var tupexp = semTuplePositionsConstr(c, n, flags, expectedType)
  2593. var isTupleType: bool
  2594. if tupexp.len > 0: # don't interpret () as type
  2595. isTupleType = tupexp[0].typ.kind == tyTypeDesc
  2596. # check if either everything or nothing is tyTypeDesc
  2597. for i in 1..<tupexp.len:
  2598. if isTupleType != (tupexp[i].typ.kind == tyTypeDesc):
  2599. return localErrorNode(c, n, tupexp[i].info, "Mixing types and values in tuples is not allowed.")
  2600. if isTupleType: # expressions as ``(int, string)`` are reinterpret as type expressions
  2601. result = n
  2602. var typ = semTypeNode(c, n, nil).skipTypes({tyTypeDesc})
  2603. result.typ = makeTypeDesc(c, typ)
  2604. else:
  2605. result = tupexp
  2606. proc shouldBeBracketExpr(n: PNode): bool =
  2607. assert n.kind in nkCallKinds
  2608. let a = n[0]
  2609. if a.kind in nkCallKinds:
  2610. let b = a[0]
  2611. if b.kind in nkSymChoices:
  2612. for i in 0..<b.len:
  2613. if b[i].kind == nkSym and b[i].sym.magic == mArrGet:
  2614. let be = newNodeI(nkBracketExpr, n.info)
  2615. for i in 1..<a.len: be.add(a[i])
  2616. n[0] = be
  2617. return true
  2618. proc asBracketExpr(c: PContext; n: PNode): PNode =
  2619. proc isGeneric(c: PContext; n: PNode): bool =
  2620. if n.kind in {nkIdent, nkAccQuoted}:
  2621. let s = qualifiedLookUp(c, n, {})
  2622. result = s != nil and isGenericRoutineStrict(s)
  2623. assert n.kind in nkCallKinds
  2624. if n.len > 1 and isGeneric(c, n[1]):
  2625. let b = n[0]
  2626. if b.kind in nkSymChoices:
  2627. for i in 0..<b.len:
  2628. if b[i].kind == nkSym and b[i].sym.magic == mArrGet:
  2629. result = newNodeI(nkBracketExpr, n.info)
  2630. for i in 1..<n.len: result.add(n[i])
  2631. return result
  2632. return nil
  2633. proc hoistParamsUsedInDefault(c: PContext, call, letSection, defExpr: var PNode) =
  2634. # This takes care of complicated signatures such as:
  2635. # proc foo(a: int, b = a)
  2636. # proc bar(a: int, b: int, c = a + b)
  2637. #
  2638. # The recursion may confuse you. It performs two duties:
  2639. #
  2640. # 1) extracting all referenced params from default expressions
  2641. # into a let section preceding the call
  2642. #
  2643. # 2) replacing the "references" within the default expression
  2644. # with these extracted skLet symbols.
  2645. #
  2646. # The first duty is carried out directly in the code here, while the second
  2647. # duty is activated by returning a non-nil value. The caller is responsible
  2648. # for replacing the input to the function with the returned non-nil value.
  2649. # (which is the hoisted symbol)
  2650. if defExpr.kind == nkSym and defExpr.sym.kind == skParam and defExpr.sym.owner == call[0].sym:
  2651. let paramPos = defExpr.sym.position + 1
  2652. if call[paramPos].kind != nkSym:
  2653. let hoistedVarSym = newSym(skLet, getIdent(c.graph.cache, genPrefix), nextSymId c.idgen,
  2654. c.p.owner, letSection.info, c.p.owner.options)
  2655. hoistedVarSym.typ = call[paramPos].typ
  2656. letSection.add newTreeI(nkIdentDefs, letSection.info,
  2657. newSymNode(hoistedVarSym),
  2658. newNodeI(nkEmpty, letSection.info),
  2659. call[paramPos])
  2660. call[paramPos] = newSymNode(hoistedVarSym) # Refer the original arg to its hoisted sym
  2661. # arg we refer to is a sym, wether introduced by hoisting or not doesn't matter, we simply reuse it
  2662. defExpr = call[paramPos]
  2663. else:
  2664. for i in 0..<defExpr.safeLen:
  2665. hoistParamsUsedInDefault(c, call, letSection, defExpr[i])
  2666. proc getNilType(c: PContext): PType =
  2667. result = c.nilTypeCache
  2668. if result == nil:
  2669. result = newTypeS(tyNil, c)
  2670. result.size = c.config.target.ptrSize
  2671. result.align = c.config.target.ptrSize.int16
  2672. c.nilTypeCache = result
  2673. proc enumFieldSymChoice(c: PContext, n: PNode, s: PSym): PNode =
  2674. var o: TOverloadIter
  2675. var i = 0
  2676. var a = initOverloadIter(o, c, n)
  2677. while a != nil:
  2678. if a.kind == skEnumField:
  2679. inc(i)
  2680. if i > 1: break
  2681. a = nextOverloadIter(o, c, n)
  2682. let info = getCallLineInfo(n)
  2683. if i <= 1:
  2684. if sfGenSym notin s.flags:
  2685. result = newSymNode(s, info)
  2686. markUsed(c, info, s)
  2687. onUse(info, s)
  2688. else:
  2689. result = n
  2690. else:
  2691. result = newNodeIT(nkClosedSymChoice, info, newTypeS(tyNone, c))
  2692. a = initOverloadIter(o, c, n)
  2693. while a != nil:
  2694. if a.kind == skEnumField:
  2695. incl(a.flags, sfUsed)
  2696. markOwnerModuleAsUsed(c, a)
  2697. result.add newSymNode(a, info)
  2698. onUse(info, a)
  2699. a = nextOverloadIter(o, c, n)
  2700. proc semPragmaStmt(c: PContext; n: PNode) =
  2701. if c.p.owner.kind == skModule:
  2702. pragma(c, c.p.owner, n, stmtPragmas+stmtPragmasTopLevel, true)
  2703. else:
  2704. pragma(c, c.p.owner, n, stmtPragmas, true)
  2705. proc semExpr(c: PContext, n: PNode, flags: TExprFlags = {}, expectedType: PType = nil): PNode =
  2706. when defined(nimCompilerStacktraceHints):
  2707. setFrameMsg c.config$n.info & " " & $n.kind
  2708. when false: # see `tdebugutils`
  2709. if isCompilerDebug():
  2710. echo (">", c.config$n.info, n, flags, n.kind)
  2711. defer:
  2712. if isCompilerDebug():
  2713. echo ("<", c.config$n.info, n, ?.result.typ)
  2714. template directLiteral(typeKind: TTypeKind) =
  2715. if result.typ == nil:
  2716. if expectedType != nil and (
  2717. let expected = expectedType.skipTypes(abstractRange-{tyDistinct});
  2718. expected.kind == typeKind):
  2719. result.typ = expected
  2720. changeType(c, result, expectedType, check=true)
  2721. else:
  2722. result.typ = getSysType(c.graph, n.info, typeKind)
  2723. result = n
  2724. when defined(nimsuggest):
  2725. var expandStarted = false
  2726. if c.config.ideCmd == ideExpand and not c.config.expandProgress and
  2727. ((n.kind in {nkFuncDef, nkProcDef, nkIteratorDef, nkTemplateDef, nkMethodDef, nkConverterDef} and
  2728. n.info.exactEquals(c.config.expandPosition)) or
  2729. (n.kind in {nkCall, nkCommand} and
  2730. n[0].info.exactEquals(c.config.expandPosition))):
  2731. expandStarted = true
  2732. c.config.expandProgress = true
  2733. if c.config.expandLevels == 0:
  2734. c.config.expandNodeResult = $n
  2735. suggestQuit()
  2736. if c.config.cmd == cmdIdeTools: suggestExpr(c, n)
  2737. if nfSem in n.flags: return
  2738. case n.kind
  2739. of nkIdent, nkAccQuoted:
  2740. var s: PSym
  2741. if expectedType != nil and (
  2742. let expected = expectedType.skipTypes(abstractRange-{tyDistinct});
  2743. expected.kind == tyEnum):
  2744. let nameId = considerQuotedIdent(c, n).id
  2745. for f in expected.n:
  2746. if f.kind == nkSym and f.sym.name.id == nameId:
  2747. s = f.sym
  2748. break
  2749. if s == nil:
  2750. let checks = if efNoEvaluateGeneric in flags:
  2751. {checkUndeclared, checkPureEnumFields}
  2752. elif efInCall in flags:
  2753. {checkUndeclared, checkModule, checkPureEnumFields}
  2754. else:
  2755. {checkUndeclared, checkModule, checkAmbiguity, checkPureEnumFields}
  2756. s = qualifiedLookUp(c, n, checks)
  2757. if c.matchedConcept == nil: semCaptureSym(s, c.p.owner)
  2758. case s.kind
  2759. of skProc, skFunc, skMethod, skConverter, skIterator:
  2760. #performProcvarCheck(c, n, s)
  2761. result = symChoice(c, n, s, scClosed)
  2762. if result.kind == nkSym:
  2763. markIndirect(c, result.sym)
  2764. # if isGenericRoutine(result.sym):
  2765. # localError(c.config, n.info, errInstantiateXExplicitly, s.name.s)
  2766. # "procs literals" are 'owned'
  2767. if optOwnedRefs in c.config.globalOptions:
  2768. result.typ = makeVarType(c, result.typ, tyOwned)
  2769. of skEnumField:
  2770. result = enumFieldSymChoice(c, n, s)
  2771. else:
  2772. result = semSym(c, n, s, flags)
  2773. if expectedType != nil and isSymChoice(result):
  2774. result = fitNode(c, expectedType, result, n.info)
  2775. if result.kind == nkSym:
  2776. result = semSym(c, result, result.sym, flags)
  2777. of nkSym:
  2778. # because of the changed symbol binding, this does not mean that we
  2779. # don't have to check the symbol for semantics here again!
  2780. result = semSym(c, n, n.sym, flags)
  2781. of nkEmpty, nkNone, nkCommentStmt, nkType:
  2782. discard
  2783. of nkNilLit:
  2784. if result.typ == nil:
  2785. result.typ = getNilType(c)
  2786. if expectedType != nil:
  2787. var m = newCandidate(c, result.typ)
  2788. if typeRel(m, expectedType, result.typ) >= isSubtype:
  2789. result.typ = expectedType
  2790. # or: result = fitNode(c, expectedType, result, n.info)
  2791. of nkIntLit:
  2792. if result.typ == nil:
  2793. if expectedType != nil and (
  2794. let expected = expectedType.skipTypes(abstractRange-{tyDistinct});
  2795. expected.kind in {tyInt..tyInt64,
  2796. tyUInt..tyUInt64,
  2797. tyFloat..tyFloat128}):
  2798. result.typ = expected
  2799. if expected.kind in {tyFloat..tyFloat128}:
  2800. n.transitionIntToFloatKind(nkFloatLit)
  2801. changeType(c, result, expectedType, check=true)
  2802. else:
  2803. setIntLitType(c, result)
  2804. of nkInt8Lit: directLiteral(tyInt8)
  2805. of nkInt16Lit: directLiteral(tyInt16)
  2806. of nkInt32Lit: directLiteral(tyInt32)
  2807. of nkInt64Lit: directLiteral(tyInt64)
  2808. of nkUIntLit: directLiteral(tyUInt)
  2809. of nkUInt8Lit: directLiteral(tyUInt8)
  2810. of nkUInt16Lit: directLiteral(tyUInt16)
  2811. of nkUInt32Lit: directLiteral(tyUInt32)
  2812. of nkUInt64Lit: directLiteral(tyUInt64)
  2813. of nkFloatLit:
  2814. if result.typ == nil:
  2815. if expectedType != nil and (
  2816. let expected = expectedType.skipTypes(abstractRange-{tyDistinct});
  2817. expected.kind in {tyFloat..tyFloat128}):
  2818. result.typ = expected
  2819. changeType(c, result, expectedType, check=true)
  2820. else:
  2821. result.typ = getSysType(c.graph, n.info, tyFloat64)
  2822. of nkFloat32Lit: directLiteral(tyFloat32)
  2823. of nkFloat64Lit: directLiteral(tyFloat64)
  2824. of nkFloat128Lit: directLiteral(tyFloat128)
  2825. of nkStrLit..nkTripleStrLit:
  2826. if result.typ == nil:
  2827. if expectedType != nil and (
  2828. let expected = expectedType.skipTypes(abstractRange-{tyDistinct});
  2829. expected.kind in {tyString, tyCstring}):
  2830. result.typ = expectedType
  2831. else:
  2832. result.typ = getSysType(c.graph, n.info, tyString)
  2833. of nkCharLit: directLiteral(tyChar)
  2834. of nkDotExpr:
  2835. result = semFieldAccess(c, n, flags)
  2836. if result.kind == nkDotCall:
  2837. result.transitionSonsKind(nkCall)
  2838. result = semExpr(c, result, flags)
  2839. of nkBind:
  2840. message(c.config, n.info, warnDeprecated, "bind is deprecated")
  2841. result = semExpr(c, n[0], flags, expectedType)
  2842. of nkTypeOfExpr..nkTupleClassTy, nkStaticTy, nkRefTy..nkEnumTy:
  2843. if c.matchedConcept != nil and n.len == 1:
  2844. let modifier = n.modifierTypeKindOfNode
  2845. if modifier != tyNone:
  2846. var baseType = semExpr(c, n[0]).typ.skipTypes({tyTypeDesc})
  2847. result.typ = c.makeTypeDesc(c.newTypeWithSons(modifier, @[baseType]))
  2848. return
  2849. var typ = semTypeNode(c, n, nil).skipTypes({tyTypeDesc})
  2850. result.typ = makeTypeDesc(c, typ)
  2851. of nkStmtListType:
  2852. let typ = semTypeNode(c, n, nil)
  2853. result.typ = makeTypeDesc(c, typ)
  2854. of nkCall, nkInfix, nkPrefix, nkPostfix, nkCommand, nkCallStrLit:
  2855. # check if it is an expression macro:
  2856. checkMinSonsLen(n, 1, c.config)
  2857. #when defined(nimsuggest):
  2858. # if gIdeCmd == ideCon and c.config.m.trackPos == n.info: suggestExprNoCheck(c, n)
  2859. let mode = if nfDotField in n.flags: {} else: {checkUndeclared}
  2860. c.isAmbiguous = false
  2861. var s = qualifiedLookUp(c, n[0], mode)
  2862. if s != nil:
  2863. #if c.config.cmd == cmdNimfix and n[0].kind == nkDotExpr:
  2864. # pretty.checkUse(n[0][1].info, s)
  2865. case s.kind
  2866. of skMacro, skTemplate:
  2867. result = semDirectOp(c, n, flags, expectedType)
  2868. of skType:
  2869. # XXX think about this more (``set`` procs)
  2870. let ambig = c.isAmbiguous
  2871. if not (n[0].kind in {nkClosedSymChoice, nkOpenSymChoice, nkIdent} and ambig) and n.len == 2:
  2872. result = semConv(c, n, expectedType)
  2873. elif ambig and n.len == 1:
  2874. errorUseQualifier(c, n.info, s)
  2875. elif n.len == 1:
  2876. result = semObjConstr(c, n, flags, expectedType)
  2877. elif s.magic == mNone: result = semDirectOp(c, n, flags, expectedType)
  2878. else: result = semMagic(c, n, s, flags, expectedType)
  2879. of skProc, skFunc, skMethod, skConverter, skIterator:
  2880. if s.magic == mNone: result = semDirectOp(c, n, flags)
  2881. else: result = semMagic(c, n, s, flags, expectedType)
  2882. else:
  2883. #liMessage(n.info, warnUser, renderTree(n));
  2884. result = semIndirectOp(c, n, flags, expectedType)
  2885. elif (n[0].kind == nkBracketExpr or shouldBeBracketExpr(n)) and
  2886. isSymChoice(n[0][0]):
  2887. # indirectOp can deal with explicit instantiations; the fixes
  2888. # the 'newSeq[T](x)' bug
  2889. setGenericParams(c, n[0])
  2890. result = semDirectOp(c, n, flags, expectedType)
  2891. elif nfDotField in n.flags:
  2892. result = semDirectOp(c, n, flags, expectedType)
  2893. elif isSymChoice(n[0]):
  2894. let b = asBracketExpr(c, n)
  2895. if b != nil:
  2896. result = semExpr(c, b, flags, expectedType)
  2897. else:
  2898. result = semDirectOp(c, n, flags, expectedType)
  2899. else:
  2900. result = semIndirectOp(c, n, flags, expectedType)
  2901. if nfDefaultRefsParam in result.flags:
  2902. result = result.copyTree #XXX: Figure out what causes default param nodes to be shared.. (sigmatch bug?)
  2903. # We've found a default value that references another param.
  2904. # See the notes in `hoistParamsUsedInDefault` for more details.
  2905. var hoistedParams = newNodeI(nkLetSection, result.info)
  2906. for i in 1..<result.len:
  2907. hoistParamsUsedInDefault(c, result, hoistedParams, result[i])
  2908. result = newTreeIT(nkStmtListExpr, result.info, result.typ, hoistedParams, result)
  2909. of nkWhen:
  2910. if efWantStmt in flags:
  2911. result = semWhen(c, n, true)
  2912. else:
  2913. result = semWhen(c, n, false)
  2914. if result == n:
  2915. # This is a "when nimvm" stmt.
  2916. result = semWhen(c, n, true)
  2917. else:
  2918. result = semExpr(c, result, flags, expectedType)
  2919. of nkBracketExpr:
  2920. checkMinSonsLen(n, 1, c.config)
  2921. result = semArrayAccess(c, n, flags, expectedType)
  2922. of nkCurlyExpr:
  2923. result = semExpr(c, buildOverloadedSubscripts(n, getIdent(c.cache, "{}")), flags, expectedType)
  2924. of nkPragmaExpr:
  2925. var
  2926. pragma = n[1]
  2927. pragmaName = considerQuotedIdent(c, pragma[0])
  2928. flags = flags
  2929. finalNodeFlags: TNodeFlags = {}
  2930. case whichKeyword(pragmaName)
  2931. of wExplain:
  2932. flags.incl efExplain
  2933. of wExecuteOnReload:
  2934. finalNodeFlags.incl nfExecuteOnReload
  2935. else:
  2936. # what other pragmas are allowed for expressions? `likely`, `unlikely`
  2937. invalidPragma(c, n)
  2938. result = semExpr(c, n[0], flags)
  2939. result.flags.incl finalNodeFlags
  2940. of nkPar, nkTupleConstr:
  2941. case checkPar(c, n)
  2942. of paNone: result = errorNode(c, n)
  2943. of paTuplePositions: result = semTupleConstr(c, n, flags, expectedType)
  2944. of paTupleFields: result = semTupleFieldsConstr(c, n, flags, expectedType)
  2945. of paSingle: result = semExpr(c, n[0], flags, expectedType)
  2946. of nkCurly: result = semSetConstr(c, n, expectedType)
  2947. of nkBracket:
  2948. result = semArrayConstr(c, n, flags, expectedType)
  2949. of nkObjConstr: result = semObjConstr(c, n, flags, expectedType)
  2950. of nkLambdaKinds: result = semProcAux(c, n, skProc, lambdaPragmas, flags)
  2951. of nkDerefExpr: result = semDeref(c, n)
  2952. of nkAddr:
  2953. result = n
  2954. checkSonsLen(n, 1, c.config)
  2955. result[0] = semAddrArg(c, n[0])
  2956. result.typ = makePtrType(c, result[0].typ)
  2957. of nkHiddenAddr, nkHiddenDeref:
  2958. checkSonsLen(n, 1, c.config)
  2959. n[0] = semExpr(c, n[0], flags, expectedType)
  2960. of nkCast: result = semCast(c, n)
  2961. of nkIfExpr, nkIfStmt: result = semIf(c, n, flags, expectedType)
  2962. of nkHiddenStdConv, nkHiddenSubConv, nkConv, nkHiddenCallConv:
  2963. checkSonsLen(n, 2, c.config)
  2964. considerGenSyms(c, n)
  2965. of nkStringToCString, nkCStringToString, nkObjDownConv, nkObjUpConv:
  2966. checkSonsLen(n, 1, c.config)
  2967. considerGenSyms(c, n)
  2968. of nkChckRangeF, nkChckRange64, nkChckRange:
  2969. checkSonsLen(n, 3, c.config)
  2970. considerGenSyms(c, n)
  2971. of nkCheckedFieldExpr:
  2972. checkMinSonsLen(n, 2, c.config)
  2973. considerGenSyms(c, n)
  2974. of nkTableConstr:
  2975. result = semTableConstr(c, n, expectedType)
  2976. of nkClosedSymChoice, nkOpenSymChoice:
  2977. # handling of sym choices is context dependent
  2978. # the node is left intact for now
  2979. discard
  2980. of nkStaticExpr: result = semStaticExpr(c, n[0], expectedType)
  2981. of nkAsgn, nkFastAsgn: result = semAsgn(c, n)
  2982. of nkBlockStmt, nkBlockExpr: result = semBlock(c, n, flags, expectedType)
  2983. of nkStmtList, nkStmtListExpr: result = semStmtList(c, n, flags, expectedType)
  2984. of nkRaiseStmt: result = semRaise(c, n)
  2985. of nkVarSection: result = semVarOrLet(c, n, skVar)
  2986. of nkLetSection: result = semVarOrLet(c, n, skLet)
  2987. of nkConstSection: result = semConst(c, n)
  2988. of nkTypeSection: result = semTypeSection(c, n)
  2989. of nkDiscardStmt: result = semDiscard(c, n)
  2990. of nkWhileStmt: result = semWhile(c, n, flags)
  2991. of nkTryStmt, nkHiddenTryStmt: result = semTry(c, n, flags, expectedType)
  2992. of nkBreakStmt, nkContinueStmt: result = semBreakOrContinue(c, n)
  2993. of nkForStmt, nkParForStmt: result = semFor(c, n, flags)
  2994. of nkCaseStmt: result = semCase(c, n, flags, expectedType)
  2995. of nkReturnStmt: result = semReturn(c, n)
  2996. of nkUsingStmt: result = semUsing(c, n)
  2997. of nkAsmStmt: result = semAsm(c, n)
  2998. of nkYieldStmt: result = semYield(c, n)
  2999. of nkPragma: semPragmaStmt(c, n)
  3000. of nkIteratorDef: result = semIterator(c, n)
  3001. of nkProcDef: result = semProc(c, n)
  3002. of nkFuncDef: result = semFunc(c, n)
  3003. of nkMethodDef: result = semMethod(c, n)
  3004. of nkConverterDef: result = semConverterDef(c, n)
  3005. of nkMacroDef: result = semMacroDef(c, n)
  3006. of nkTemplateDef: result = semTemplateDef(c, n)
  3007. of nkImportStmt:
  3008. # this particular way allows 'import' in a 'compiles' context so that
  3009. # template canImport(x): bool =
  3010. # compiles:
  3011. # import x
  3012. #
  3013. # works:
  3014. if c.currentScope.depthLevel > 2 + c.compilesContextId:
  3015. localError(c.config, n.info, errXOnlyAtModuleScope % "import")
  3016. result = evalImport(c, n)
  3017. of nkImportExceptStmt:
  3018. if not isTopLevel(c): localError(c.config, n.info, errXOnlyAtModuleScope % "import")
  3019. result = evalImportExcept(c, n)
  3020. of nkFromStmt:
  3021. if not isTopLevel(c): localError(c.config, n.info, errXOnlyAtModuleScope % "from")
  3022. result = evalFrom(c, n)
  3023. of nkIncludeStmt:
  3024. #if not isTopLevel(c): localError(c.config, n.info, errXOnlyAtModuleScope % "include")
  3025. result = evalInclude(c, n)
  3026. of nkExportStmt:
  3027. if not isTopLevel(c): localError(c.config, n.info, errXOnlyAtModuleScope % "export")
  3028. result = semExport(c, n)
  3029. of nkExportExceptStmt:
  3030. if not isTopLevel(c): localError(c.config, n.info, errXOnlyAtModuleScope % "export")
  3031. result = semExportExcept(c, n)
  3032. of nkPragmaBlock:
  3033. result = semPragmaBlock(c, n, expectedType)
  3034. of nkStaticStmt:
  3035. result = semStaticStmt(c, n)
  3036. of nkDefer:
  3037. if c.currentScope == c.topLevelScope:
  3038. localError(c.config, n.info, "defer statement not supported at top level")
  3039. n[0] = semExpr(c, n[0])
  3040. if not n[0].typ.isEmptyType and not implicitlyDiscardable(n[0]):
  3041. localError(c.config, n.info, "'defer' takes a 'void' expression")
  3042. #localError(c.config, n.info, errGenerated, "'defer' not allowed in this context")
  3043. of nkGotoState, nkState:
  3044. if n.len != 1 and n.len != 2: illFormedAst(n, c.config)
  3045. for i in 0..<n.len:
  3046. n[i] = semExpr(c, n[i])
  3047. of nkComesFrom: discard "ignore the comes from information for now"
  3048. of nkMixinStmt: discard
  3049. of nkBindStmt:
  3050. if c.p != nil:
  3051. if n.len > 0 and n[0].kind == nkSym:
  3052. c.p.localBindStmts.add n
  3053. else:
  3054. localError(c.config, n.info, "invalid context for 'bind' statement: " &
  3055. renderTree(n, {renderNoComments}))
  3056. else:
  3057. localError(c.config, n.info, "invalid expression: " &
  3058. renderTree(n, {renderNoComments}))
  3059. if result != nil: incl(result.flags, nfSem)
  3060. when defined(nimsuggest):
  3061. if expandStarted:
  3062. c.config.expandNodeResult = $result
  3063. suggestQuit()