semexprs.nim 126 KB

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