semexprs.nim 125 KB

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