semexprs.nim 121 KB

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