semexprs.nim 137 KB

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