semexprs.nim 105 KB

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