semexprs.nim 121 KB

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