semexprs.nim 123 KB

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