semexprs.nim 136 KB

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