semexprs.nim 119 KB

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