semexprs.nim 118 KB

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