semexprs.nim 123 KB

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