semexprs.nim 137 KB

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