semexprs.nim 107 KB

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