semexprs.nim 133 KB

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