semexprs.nim 119 KB

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