semexprs.nim 121 KB

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