semexprs.nim 121 KB

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