semexprs.nim 131 KB

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