pragmas.nim 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386
  1. #
  2. #
  3. # The Nim Compiler
  4. # (c) Copyright 2015 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. # This module implements semantic checking for pragmas
  10. import
  11. condsyms, ast, astalgo, idents, semdata, msgs, renderer,
  12. wordrecg, ropes, options, extccomp, magicsys, trees,
  13. types, lookups, lineinfos, pathutils, linter, modulepaths
  14. from sigmatch import trySuggestPragmas
  15. import std/[os, math, strutils]
  16. when defined(nimPreviewSlimSystem):
  17. import std/assertions
  18. from ic / ic import addCompilerProc
  19. const
  20. FirstCallConv* = wNimcall
  21. LastCallConv* = wNoconv
  22. const
  23. declPragmas = {wImportc, wImportObjC, wImportCpp, wImportJs, wExportc, wExportCpp,
  24. wExportNims, wExtern, wDeprecated, wNodecl, wError, wUsed}
  25. ## common pragmas for declarations, to a good approximation
  26. procPragmas* = declPragmas + {FirstCallConv..LastCallConv,
  27. wMagic, wNoSideEffect, wSideEffect, wNoreturn, wNosinks, wDynlib, wHeader,
  28. wCompilerProc, wNonReloadable, wCore, wProcVar, wVarargs, wCompileTime,
  29. wBorrow, wImportCompilerProc, wThread,
  30. wAsmNoStackFrame, wDiscardable, wNoInit, wCodegenDecl,
  31. wGensym, wInject, wRaises, wEffectsOf, wTags, wForbids, wLocks, wDelegator, wGcSafe,
  32. wConstructor, wLiftLocals, wStackTrace, wLineTrace, wNoDestroy,
  33. wRequires, wEnsures, wEnforceNoRaises, wSystemRaisesDefect, wVirtual, wQuirky, wMember}
  34. converterPragmas* = procPragmas
  35. methodPragmas* = procPragmas+{wBase}-{wImportCpp}
  36. templatePragmas* = {wDeprecated, wError, wGensym, wInject, wDirty,
  37. wDelegator, wExportNims, wUsed, wPragma, wRedefine, wCallsite}
  38. macroPragmas* = declPragmas + {FirstCallConv..LastCallConv,
  39. wMagic, wNoSideEffect, wCompilerProc, wNonReloadable, wCore,
  40. wDiscardable, wGensym, wInject, wDelegator}
  41. iteratorPragmas* = declPragmas + {FirstCallConv..LastCallConv, wNoSideEffect, wSideEffect,
  42. wMagic, wBorrow,
  43. wDiscardable, wGensym, wInject, wRaises, wEffectsOf,
  44. wTags, wForbids, wLocks, wGcSafe, wRequires, wEnsures}
  45. exprPragmas* = {wLine, wLocks, wNoRewrite, wGcSafe, wNoSideEffect}
  46. stmtPragmas* = {
  47. wHint, wWarning, wError,
  48. wFatal, wDefine, wUndef, wCompile, wLink, wLinksys, wPure, wPush, wPop,
  49. wPassl, wPassc, wLocalPassc,
  50. wDeadCodeElimUnused, # deprecated, always on
  51. wDeprecated,
  52. wPragma, wEmit, wUnroll,
  53. wLinearScanEnd, wPatterns, wTrMacros, wEffects, wNoForward, wReorder, wComputedGoto,
  54. wExperimental, wDoctype, wThis, wUsed, wInvariant, wAssume, wAssert}
  55. stmtPragmasTopLevel* = {wChecks, wObjChecks, wFieldChecks, wRangeChecks,
  56. wBoundChecks, wOverflowChecks, wNilChecks, wStaticBoundchecks,
  57. wStyleChecks, wAssertions,
  58. wWarnings, wHints,
  59. wLineDir, wStackTrace, wLineTrace, wOptimization,
  60. wFloatChecks, wInfChecks, wNanChecks}
  61. lambdaPragmas* = {FirstCallConv..LastCallConv,
  62. wNoSideEffect, wSideEffect, wNoreturn, wNosinks, wDynlib, wHeader,
  63. wThread, wAsmNoStackFrame,
  64. wRaises, wLocks, wTags, wForbids, wRequires, wEnsures, wEffectsOf,
  65. wGcSafe, wCodegenDecl, wNoInit, wCompileTime}
  66. typePragmas* = declPragmas + {wMagic, wAcyclic,
  67. wPure, wHeader, wCompilerProc, wCore, wFinal, wSize, wShallow,
  68. wIncompleteStruct, wCompleteStruct, wByCopy, wByRef,
  69. wInheritable, wGensym, wInject, wRequiresInit, wUnchecked, wUnion, wPacked,
  70. wCppNonPod, wBorrow, wGcSafe, wPartial, wExplain, wPackage, wCodegenDecl,
  71. wSendable, wNoInit}
  72. fieldPragmas* = declPragmas + {wGuard, wBitsize, wCursor,
  73. wRequiresInit, wNoalias, wAlign, wNoInit} - {wExportNims, wNodecl} # why exclude these?
  74. varPragmas* = declPragmas + {wVolatile, wRegister, wThreadVar,
  75. wMagic, wHeader, wCompilerProc, wCore, wDynlib,
  76. wNoInit, wCompileTime, wGlobal,
  77. wGensym, wInject, wCodegenDecl,
  78. wGuard, wGoto, wCursor, wNoalias, wAlign}
  79. constPragmas* = declPragmas + {wHeader, wMagic,
  80. wGensym, wInject,
  81. wIntDefine, wStrDefine, wBoolDefine, wDefine,
  82. wCompilerProc, wCore}
  83. paramPragmas* = {wNoalias, wInject, wGensym, wByRef, wByCopy, wCodegenDecl}
  84. letPragmas* = varPragmas
  85. procTypePragmas* = {FirstCallConv..LastCallConv, wVarargs, wNoSideEffect,
  86. wThread, wRaises, wEffectsOf, wLocks, wTags, wForbids, wGcSafe,
  87. wRequires, wEnsures}
  88. forVarPragmas* = {wInject, wGensym}
  89. allRoutinePragmas* = methodPragmas + iteratorPragmas + lambdaPragmas
  90. enumFieldPragmas* = {wDeprecated}
  91. proc getPragmaVal*(procAst: PNode; name: TSpecialWord): PNode =
  92. result = nil
  93. let p = procAst[pragmasPos]
  94. if p.kind == nkEmpty: return nil
  95. for it in p:
  96. if it.kind in nkPragmaCallKinds and it.len == 2 and it[0].kind == nkIdent and
  97. it[0].ident.id == ord(name):
  98. return it[1]
  99. proc pragma*(c: PContext, sym: PSym, n: PNode, validPragmas: TSpecialWords;
  100. isStatement: bool = false)
  101. proc recordPragma(c: PContext; n: PNode; args: varargs[string]) =
  102. var recorded = newNodeI(nkReplayAction, n.info)
  103. for i in 0..args.high:
  104. recorded.add newStrNode(args[i], n.info)
  105. addPragmaComputation(c, recorded)
  106. const
  107. errStringLiteralExpected = "string literal expected"
  108. errIntLiteralExpected = "integer literal expected"
  109. proc invalidPragma*(c: PContext; n: PNode) =
  110. localError(c.config, n.info, "invalid pragma: " & renderTree(n, {renderNoComments}))
  111. proc illegalCustomPragma*(c: PContext, n: PNode, s: PSym) =
  112. var msg = "cannot attach a custom pragma to '" & s.name.s & "'"
  113. if s != nil:
  114. msg.add("; custom pragmas are not supported for ")
  115. case s.kind
  116. of skForVar: msg.add("`for` loop variables")
  117. of skEnumField: msg.add("enum fields")
  118. of skModule: msg.add("modules")
  119. else: msg.add("symbol kind " & $s.kind)
  120. localError(c.config, n.info, msg)
  121. proc pragmaProposition(c: PContext, n: PNode) =
  122. if n.kind notin nkPragmaCallKinds or n.len != 2:
  123. localError(c.config, n.info, "proposition expected")
  124. else:
  125. n[1] = c.semExpr(c, n[1])
  126. proc pragmaEnsures(c: PContext, n: PNode) =
  127. if n.kind notin nkPragmaCallKinds or n.len != 2:
  128. localError(c.config, n.info, "proposition expected")
  129. else:
  130. openScope(c)
  131. let o = getCurrOwner(c)
  132. if o.kind in routineKinds and o.typ != nil and o.typ.returnType != nil:
  133. var s = newSym(skResult, getIdent(c.cache, "result"), c.idgen, o, n.info)
  134. s.typ = o.typ.returnType
  135. incl(s.flags, sfUsed)
  136. addDecl(c, s)
  137. n[1] = c.semExpr(c, n[1])
  138. closeScope(c)
  139. proc setExternName(c: PContext; s: PSym, extname: string, info: TLineInfo) =
  140. # special cases to improve performance:
  141. if extname == "$1":
  142. s.loc.r = rope(s.name.s)
  143. elif '$' notin extname:
  144. s.loc.r = rope(extname)
  145. else:
  146. try:
  147. s.loc.r = rope(extname % s.name.s)
  148. except ValueError:
  149. localError(c.config, info, "invalid extern name: '" & extname & "'. (Forgot to escape '$'?)")
  150. when hasFFI:
  151. s.cname = $s.loc.r
  152. proc makeExternImport(c: PContext; s: PSym, extname: string, info: TLineInfo) =
  153. setExternName(c, s, extname, info)
  154. incl(s.flags, sfImportc)
  155. excl(s.flags, sfForward)
  156. proc makeExternExport(c: PContext; s: PSym, extname: string, info: TLineInfo) =
  157. setExternName(c, s, extname, info)
  158. incl(s.flags, sfExportc)
  159. proc processImportCompilerProc(c: PContext; s: PSym, extname: string, info: TLineInfo) =
  160. setExternName(c, s, extname, info)
  161. incl(s.flags, sfImportc)
  162. excl(s.flags, sfForward)
  163. incl(s.loc.flags, lfImportCompilerProc)
  164. proc processImportCpp(c: PContext; s: PSym, extname: string, info: TLineInfo) =
  165. setExternName(c, s, extname, info)
  166. incl(s.flags, sfImportc)
  167. incl(s.flags, sfInfixCall)
  168. excl(s.flags, sfForward)
  169. if c.config.backend == backendC:
  170. let m = s.getModule()
  171. incl(m.flags, sfCompileToCpp)
  172. incl c.config.globalOptions, optMixedMode
  173. proc processImportObjC(c: PContext; s: PSym, extname: string, info: TLineInfo) =
  174. setExternName(c, s, extname, info)
  175. incl(s.flags, sfImportc)
  176. incl(s.flags, sfNamedParamCall)
  177. excl(s.flags, sfForward)
  178. let m = s.getModule()
  179. incl(m.flags, sfCompileToObjc)
  180. proc newEmptyStrNode(c: PContext; n: PNode, strVal: string = ""): PNode {.noinline.} =
  181. result = newNodeIT(nkStrLit, n.info, getSysType(c.graph, n.info, tyString))
  182. result.strVal = strVal
  183. proc getStrLitNode(c: PContext, n: PNode): PNode =
  184. if n.kind notin nkPragmaCallKinds or n.len != 2:
  185. localError(c.config, n.info, errStringLiteralExpected)
  186. # error correction:
  187. result = newEmptyStrNode(c, n)
  188. else:
  189. n[1] = c.semConstExpr(c, n[1])
  190. case n[1].kind
  191. of nkStrLit, nkRStrLit, nkTripleStrLit: result = n[1]
  192. else:
  193. localError(c.config, n.info, errStringLiteralExpected)
  194. # error correction:
  195. result = newEmptyStrNode(c, n)
  196. proc expectStrLit(c: PContext, n: PNode): string =
  197. result = getStrLitNode(c, n).strVal
  198. proc expectIntLit(c: PContext, n: PNode): int =
  199. result = 0
  200. if n.kind notin nkPragmaCallKinds or n.len != 2:
  201. localError(c.config, n.info, errIntLiteralExpected)
  202. else:
  203. n[1] = c.semConstExpr(c, n[1])
  204. case n[1].kind
  205. of nkIntLit..nkInt64Lit: result = int(n[1].intVal)
  206. else: localError(c.config, n.info, errIntLiteralExpected)
  207. proc getOptionalStr(c: PContext, n: PNode, defaultStr: string): string =
  208. if n.kind in nkPragmaCallKinds: result = expectStrLit(c, n)
  209. else: result = defaultStr
  210. proc processVirtual(c: PContext, n: PNode, s: PSym, flag: TSymFlag) =
  211. s.constraint = newEmptyStrNode(c, n, getOptionalStr(c, n, "$1"))
  212. s.constraint.strVal = s.constraint.strVal % s.name.s
  213. s.flags.incl {flag, sfInfixCall, sfExportc, sfMangleCpp}
  214. s.typ.callConv = ccNoConvention
  215. incl c.config.globalOptions, optMixedMode
  216. proc processCodegenDecl(c: PContext, n: PNode, sym: PSym) =
  217. sym.constraint = getStrLitNode(c, n)
  218. sym.flags.incl sfCodegenDecl
  219. proc processMagic(c: PContext, n: PNode, s: PSym) =
  220. #if sfSystemModule notin c.module.flags:
  221. # liMessage(n.info, errMagicOnlyInSystem)
  222. if n.kind notin nkPragmaCallKinds or n.len != 2:
  223. localError(c.config, n.info, errStringLiteralExpected)
  224. return
  225. var v: string
  226. if n[1].kind == nkIdent: v = n[1].ident.s
  227. else: v = expectStrLit(c, n)
  228. for m in TMagic:
  229. if substr($m, 1) == v:
  230. s.magic = m
  231. break
  232. if s.magic == mNone: message(c.config, n.info, warnUnknownMagic, v)
  233. proc wordToCallConv(sw: TSpecialWord): TCallingConvention =
  234. # this assumes that the order of special words and calling conventions is
  235. # the same
  236. TCallingConvention(ord(ccNimCall) + ord(sw) - ord(wNimcall))
  237. proc isTurnedOn(c: PContext, n: PNode): bool =
  238. result = false
  239. if n.kind in nkPragmaCallKinds and n.len == 2:
  240. let x = c.semConstBoolExpr(c, n[1])
  241. n[1] = x
  242. if x.kind == nkIntLit: return x.intVal != 0
  243. localError(c.config, n.info, "'on' or 'off' expected")
  244. proc onOff(c: PContext, n: PNode, op: TOptions, resOptions: var TOptions) =
  245. if isTurnedOn(c, n): resOptions.incl op
  246. else: resOptions.excl op
  247. proc pragmaNoForward*(c: PContext, n: PNode; flag=sfNoForward) =
  248. if isTurnedOn(c, n):
  249. incl(c.module.flags, flag)
  250. c.features.incl codeReordering
  251. else:
  252. excl(c.module.flags, flag)
  253. # c.features.excl codeReordering
  254. # deprecated as of 0.18.1
  255. message(c.config, n.info, warnDeprecated,
  256. "use {.experimental: \"codeReordering\".} instead; " &
  257. (if flag == sfNoForward: "{.noForward.}" else: "{.reorder.}") & " is deprecated")
  258. proc pragmaAsm*(c: PContext, n: PNode): char =
  259. ## Checks asm pragmas and get's the asm subschar (default: '`').
  260. result = '\0'
  261. if n != nil:
  262. for i in 0..<n.len:
  263. let it = n[i]
  264. if it.kind in nkPragmaCallKinds and it.len == 2 and it[0].kind == nkIdent:
  265. case whichKeyword(it[0].ident)
  266. of wSubsChar:
  267. if it[1].kind == nkCharLit: result = chr(int(it[1].intVal))
  268. else: invalidPragma(c, it)
  269. of wAsmSyntax:
  270. let s = expectStrLit(c, it)
  271. if s notin ["gcc", "vcc"]: invalidPragma(c, it)
  272. else: invalidPragma(c, it)
  273. else:
  274. invalidPragma(c, it)
  275. proc processCallConv(c: PContext, n: PNode) =
  276. if n.kind in nkPragmaCallKinds and n.len == 2 and n[1].kind == nkIdent:
  277. let sw = whichKeyword(n[1].ident)
  278. case sw
  279. of FirstCallConv..LastCallConv:
  280. c.optionStack[^1].defaultCC = wordToCallConv(sw)
  281. else: localError(c.config, n.info, "calling convention expected")
  282. else:
  283. localError(c.config, n.info, "calling convention expected")
  284. proc getLib(c: PContext, kind: TLibKind, path: PNode): PLib =
  285. for it in c.libs:
  286. if it.kind == kind and trees.exprStructuralEquivalent(it.path, path):
  287. return it
  288. result = newLib(kind)
  289. result.path = path
  290. c.libs.add result
  291. if path.kind in {nkStrLit..nkTripleStrLit}:
  292. result.isOverridden = options.isDynlibOverride(c.config, path.strVal)
  293. proc expectDynlibNode(c: PContext, n: PNode): PNode =
  294. if n.kind notin nkPragmaCallKinds or n.len != 2:
  295. localError(c.config, n.info, errStringLiteralExpected)
  296. # error correction:
  297. result = newEmptyStrNode(c, n)
  298. else:
  299. # For the OpenGL wrapper we support:
  300. # {.dynlib: myGetProcAddr(...).}
  301. result = c.semExpr(c, n[1])
  302. if result.kind == nkSym and result.sym.kind == skConst:
  303. result = c.semConstExpr(c, result) # fold const
  304. if result.typ == nil or result.typ.kind notin {tyPointer, tyString, tyProc}:
  305. localError(c.config, n.info, errStringLiteralExpected)
  306. result = newEmptyStrNode(c, n)
  307. proc processDynLib(c: PContext, n: PNode, sym: PSym) =
  308. if (sym == nil) or (sym.kind == skModule):
  309. let lib = getLib(c, libDynamic, expectDynlibNode(c, n))
  310. if not lib.isOverridden:
  311. c.optionStack[^1].dynlib = lib
  312. else:
  313. if n.kind in nkPragmaCallKinds:
  314. var lib = getLib(c, libDynamic, expectDynlibNode(c, n))
  315. if not lib.isOverridden:
  316. addToLib(lib, sym)
  317. incl(sym.loc.flags, lfDynamicLib)
  318. else:
  319. incl(sym.loc.flags, lfExportLib)
  320. # since we'll be loading the dynlib symbols dynamically, we must use
  321. # a calling convention that doesn't introduce custom name mangling
  322. # cdecl is the default - the user can override this explicitly
  323. if sym.kind in routineKinds and sym.typ != nil and
  324. tfExplicitCallConv notin sym.typ.flags:
  325. sym.typ.callConv = ccCDecl
  326. proc processNote(c: PContext, n: PNode) =
  327. template handleNote(enumVals, notes) =
  328. let x = findStr(enumVals.a, enumVals.b, n[0][1].ident.s, errUnknown)
  329. if x != errUnknown:
  330. nk = TNoteKind(x)
  331. let x = c.semConstBoolExpr(c, n[1])
  332. n[1] = x
  333. if x.kind == nkIntLit and x.intVal != 0: incl(notes, nk)
  334. else: excl(notes, nk)
  335. else:
  336. invalidPragma(c, n)
  337. if n.kind in nkPragmaCallKinds and n.len == 2 and
  338. n[0].kind == nkBracketExpr and
  339. n[0].len == 2 and
  340. n[0][1].kind == nkIdent and n[0][0].kind == nkIdent:
  341. var nk: TNoteKind
  342. case whichKeyword(n[0][0].ident)
  343. of wHint: handleNote(hintMin .. hintMax, c.config.notes)
  344. of wWarning: handleNote(warnMin .. warnMax, c.config.notes)
  345. of wWarningAsError: handleNote(warnMin .. warnMax, c.config.warningAsErrors)
  346. of wHintAsError: handleNote(hintMin .. hintMax, c.config.warningAsErrors)
  347. else: invalidPragma(c, n)
  348. else: invalidPragma(c, n)
  349. proc pragmaToOptions*(w: TSpecialWord): TOptions {.inline.} =
  350. case w
  351. of wChecks: ChecksOptions
  352. of wObjChecks: {optObjCheck}
  353. of wFieldChecks: {optFieldCheck}
  354. of wRangeChecks: {optRangeCheck}
  355. of wBoundChecks: {optBoundsCheck}
  356. of wOverflowChecks: {optOverflowCheck}
  357. of wFloatChecks: {optNaNCheck, optInfCheck}
  358. of wNanChecks: {optNaNCheck}
  359. of wInfChecks: {optInfCheck}
  360. of wStaticBoundchecks: {optStaticBoundsCheck}
  361. of wStyleChecks: {optStyleCheck}
  362. of wAssertions: {optAssert}
  363. of wWarnings: {optWarns}
  364. of wHints: {optHints}
  365. of wLineDir: {optLineDir}
  366. of wStackTrace: {optStackTrace}
  367. of wLineTrace: {optLineTrace}
  368. of wDebugger: {optNone}
  369. of wProfiler: {optProfiler, optMemTracker}
  370. of wMemTracker: {optMemTracker}
  371. of wByRef: {optByRef}
  372. of wImplicitStatic: {optImplicitStatic}
  373. of wPatterns, wTrMacros: {optTrMacros}
  374. of wSinkInference: {optSinkInference}
  375. of wQuirky: {optQuirky}
  376. else: {}
  377. proc processExperimental(c: PContext; n: PNode) =
  378. if n.kind notin nkPragmaCallKinds or n.len != 2:
  379. c.features.incl oldExperimentalFeatures
  380. else:
  381. n[1] = c.semConstExpr(c, n[1])
  382. case n[1].kind
  383. of nkStrLit, nkRStrLit, nkTripleStrLit:
  384. try:
  385. let feature = parseEnum[Feature](n[1].strVal)
  386. c.features.incl feature
  387. if feature == codeReordering:
  388. if not isTopLevel(c):
  389. localError(c.config, n.info,
  390. "Code reordering experimental pragma only valid at toplevel")
  391. c.module.flags.incl sfReorder
  392. except ValueError:
  393. localError(c.config, n[1].info, "unknown experimental feature")
  394. else:
  395. localError(c.config, n.info, errStringLiteralExpected)
  396. proc tryProcessOption(c: PContext, n: PNode, resOptions: var TOptions): bool =
  397. result = true
  398. if n.kind notin nkPragmaCallKinds or n.len != 2: result = false
  399. elif n[0].kind == nkBracketExpr: processNote(c, n)
  400. elif n[0].kind != nkIdent: result = false
  401. else:
  402. let sw = whichKeyword(n[0].ident)
  403. if sw == wExperimental:
  404. processExperimental(c, n)
  405. return true
  406. let opts = pragmaToOptions(sw)
  407. if opts != {}:
  408. onOff(c, n, opts, resOptions)
  409. else:
  410. case sw
  411. of wCallconv: processCallConv(c, n)
  412. of wDynlib: processDynLib(c, n, nil)
  413. of wOptimization:
  414. if n[1].kind != nkIdent:
  415. invalidPragma(c, n)
  416. else:
  417. case n[1].ident.s.normalize
  418. of "speed":
  419. incl(resOptions, optOptimizeSpeed)
  420. excl(resOptions, optOptimizeSize)
  421. of "size":
  422. excl(resOptions, optOptimizeSpeed)
  423. incl(resOptions, optOptimizeSize)
  424. of "none":
  425. excl(resOptions, optOptimizeSpeed)
  426. excl(resOptions, optOptimizeSize)
  427. else: localError(c.config, n.info, "'none', 'speed' or 'size' expected")
  428. else: result = false
  429. proc processOption(c: PContext, n: PNode, resOptions: var TOptions) =
  430. if not tryProcessOption(c, n, resOptions):
  431. # calling conventions (boring...):
  432. localError(c.config, n.info, "option expected")
  433. proc processPush(c: PContext, n: PNode, start: int) =
  434. if n[start-1].kind in nkPragmaCallKinds:
  435. localError(c.config, n.info, "'push' cannot have arguments")
  436. var x = pushOptionEntry(c)
  437. for i in start..<n.len:
  438. if not tryProcessOption(c, n[i], c.config.options):
  439. # simply store it somewhere:
  440. if x.otherPragmas.isNil:
  441. x.otherPragmas = newNodeI(nkPragma, n.info)
  442. x.otherPragmas.add n[i]
  443. #localError(c.config, n.info, errOptionExpected)
  444. # If stacktrace is disabled globally we should not enable it
  445. if optStackTrace notin c.optionStack[0].options:
  446. c.config.options.excl(optStackTrace)
  447. when defined(debugOptions):
  448. echo c.config $ n.info, " PUSH config is now ", c.config.options
  449. proc processPop(c: PContext, n: PNode) =
  450. if c.optionStack.len <= 1:
  451. localError(c.config, n.info, "{.pop.} without a corresponding {.push.}")
  452. else:
  453. popOptionEntry(c)
  454. when defined(debugOptions):
  455. echo c.config $ n.info, " POP config is now ", c.config.options
  456. proc processDefineConst(c: PContext, n: PNode, sym: PSym, kind: TMagic) =
  457. sym.magic = kind
  458. if n.kind in nkPragmaCallKinds and n.len == 2:
  459. # could also use TLib
  460. n[1] = getStrLitNode(c, n)
  461. proc processDefine(c: PContext, n: PNode, sym: PSym) =
  462. if sym != nil and sym.kind == skConst:
  463. processDefineConst(c, n, sym, mGenericDefine)
  464. elif (n.kind in nkPragmaCallKinds and n.len == 2) and (n[1].kind == nkIdent):
  465. defineSymbol(c.config.symbols, n[1].ident.s)
  466. else:
  467. invalidPragma(c, n)
  468. proc processUndef(c: PContext, n: PNode) =
  469. if (n.kind in nkPragmaCallKinds and n.len == 2) and (n[1].kind == nkIdent):
  470. undefSymbol(c.config.symbols, n[1].ident.s)
  471. else:
  472. invalidPragma(c, n)
  473. proc relativeFile(c: PContext; n: PNode; ext=""): AbsoluteFile =
  474. var s = expectStrLit(c, n)
  475. if ext.len > 0 and splitFile(s).ext == "":
  476. s = addFileExt(s, ext)
  477. result = AbsoluteFile parentDir(toFullPath(c.config, n.info)) / s
  478. if not fileExists(result):
  479. if isAbsolute(s): result = AbsoluteFile s
  480. else:
  481. result = findFile(c.config, s)
  482. if result.isEmpty: result = AbsoluteFile s
  483. proc processCompile(c: PContext, n: PNode) =
  484. ## This pragma can take two forms. The first is a simple file input:
  485. ## {.compile: "file.c".}
  486. ## The second is a tuple where the second arg is the output name strutils formatter:
  487. ## {.compile: ("file.c", "$1.o").}
  488. proc docompile(c: PContext; it: PNode; src, dest: AbsoluteFile; customArgs: string) =
  489. var cf = Cfile(nimname: splitFile(src).name,
  490. cname: src, obj: dest, flags: {CfileFlag.External},
  491. customArgs: customArgs)
  492. if not fileExists(src):
  493. localError(c.config, n.info, "cannot find: " & src.string)
  494. else:
  495. extccomp.addExternalFileToCompile(c.config, cf)
  496. recordPragma(c, it, "compile", src.string, dest.string, customArgs)
  497. proc getStrLit(c: PContext, n: PNode; i: int): string =
  498. n[i] = c.semConstExpr(c, n[i])
  499. case n[i].kind
  500. of nkStrLit, nkRStrLit, nkTripleStrLit:
  501. when defined(gcArc) or defined(gcOrc) or defined(gcAtomicArc):
  502. result = n[i].strVal
  503. else:
  504. shallowCopy(result, n[i].strVal)
  505. else:
  506. localError(c.config, n.info, errStringLiteralExpected)
  507. result = ""
  508. let it = if n.kind in nkPragmaCallKinds and n.len == 2: n[1] else: n
  509. if it.kind in {nkPar, nkTupleConstr} and it.len == 2:
  510. let s = getStrLit(c, it, 0)
  511. let dest = getStrLit(c, it, 1)
  512. var found = parentDir(toFullPath(c.config, n.info)) / s
  513. for f in os.walkFiles(found):
  514. let obj = completeCfilePath(c.config, AbsoluteFile(dest % extractFilename(f)))
  515. docompile(c, it, AbsoluteFile f, obj, "")
  516. else:
  517. var s = ""
  518. var customArgs = ""
  519. if n.kind in nkCallKinds:
  520. s = getStrLit(c, n, 1)
  521. if n.len <= 3:
  522. customArgs = getStrLit(c, n, 2)
  523. else:
  524. localError(c.config, n.info, "'.compile' pragma takes up 2 arguments")
  525. else:
  526. s = expectStrLit(c, n)
  527. var found = AbsoluteFile(parentDir(toFullPath(c.config, n.info)) / s)
  528. if not fileExists(found):
  529. if isAbsolute(s): found = AbsoluteFile s
  530. else:
  531. found = findFile(c.config, s)
  532. if found.isEmpty: found = AbsoluteFile s
  533. let mangled = completeCfilePath(c.config, mangleModuleName(c.config, found).AbsoluteFile)
  534. let obj = toObjFile(c.config, mangled)
  535. docompile(c, it, found, obj, customArgs)
  536. proc processLink(c: PContext, n: PNode) =
  537. let found = relativeFile(c, n, CC[c.config.cCompiler].objExt)
  538. extccomp.addExternalFileToLink(c.config, found)
  539. recordPragma(c, n, "link", found.string)
  540. proc semAsmOrEmit*(con: PContext, n: PNode, marker: char): PNode =
  541. case n[1].kind
  542. of nkStrLit, nkRStrLit, nkTripleStrLit:
  543. result = newNodeI(if n.kind == nkAsmStmt: nkAsmStmt else: nkArgList, n.info)
  544. if n.kind == nkAsmStmt: result.add n[0] # save asm pragmas for NIR
  545. var str = n[1].strVal
  546. if str == "":
  547. localError(con.config, n.info, "empty 'asm' statement")
  548. return
  549. # now parse the string literal and substitute symbols:
  550. var a = 0
  551. while true:
  552. var b = strutils.find(str, marker, a)
  553. var sub = if b < 0: substr(str, a) else: substr(str, a, b - 1)
  554. if sub != "": result.add newStrNode(nkStrLit, sub)
  555. if b < 0: break
  556. var c = strutils.find(str, marker, b + 1)
  557. if c < 0: sub = substr(str, b + 1)
  558. else: sub = substr(str, b + 1, c - 1)
  559. if sub != "":
  560. var amb = false
  561. var e = searchInScopes(con, getIdent(con.cache, sub), amb)
  562. # XXX what to do here if 'amb' is true?
  563. if e != nil:
  564. incl(e.flags, sfUsed)
  565. result.add newSymNode(e)
  566. else:
  567. result.add newStrNode(nkStrLit, sub)
  568. else:
  569. # an empty '``' produces a single '`'
  570. result.add newStrNode(nkStrLit, $marker)
  571. if c < 0: break
  572. a = c + 1
  573. else:
  574. illFormedAstLocal(n, con.config)
  575. result = newNodeI(nkAsmStmt, n.info)
  576. if n.kind == nkAsmStmt: result.add n[0]
  577. proc pragmaEmit(c: PContext, n: PNode) =
  578. if n.kind notin nkPragmaCallKinds or n.len != 2:
  579. localError(c.config, n.info, errStringLiteralExpected)
  580. else:
  581. let n1 = n[1]
  582. if n1.kind == nkBracket:
  583. var b = newNodeI(nkBracket, n1.info, n1.len)
  584. for i in 0..<n1.len:
  585. b[i] = c.semExprWithType(c, n1[i], {efTypeAllowed})
  586. n[1] = b
  587. else:
  588. n[1] = c.semConstExpr(c, n1)
  589. case n[1].kind
  590. of nkStrLit, nkRStrLit, nkTripleStrLit:
  591. n[1] = semAsmOrEmit(c, n, '`')
  592. else:
  593. localError(c.config, n.info, errStringLiteralExpected)
  594. proc noVal(c: PContext; n: PNode) =
  595. if n.kind in nkPragmaCallKinds and n.len > 1: invalidPragma(c, n)
  596. proc pragmaUnroll(c: PContext, n: PNode) =
  597. if c.p.nestedLoopCounter <= 0:
  598. invalidPragma(c, n)
  599. elif n.kind in nkPragmaCallKinds and n.len == 2:
  600. var unrollFactor = expectIntLit(c, n)
  601. if unrollFactor <% 32:
  602. n[1] = newIntNode(nkIntLit, unrollFactor)
  603. else:
  604. invalidPragma(c, n)
  605. proc pragmaLine(c: PContext, n: PNode) =
  606. if n.kind in nkPragmaCallKinds and n.len == 2:
  607. n[1] = c.semConstExpr(c, n[1])
  608. let a = n[1]
  609. if a.kind in {nkPar, nkTupleConstr}:
  610. # unpack the tuple
  611. var x = a[0]
  612. var y = a[1]
  613. if x.kind == nkExprColonExpr: x = x[1]
  614. if y.kind == nkExprColonExpr: y = y[1]
  615. if x.kind != nkStrLit:
  616. localError(c.config, n.info, errStringLiteralExpected)
  617. elif y.kind != nkIntLit:
  618. localError(c.config, n.info, errIntLiteralExpected)
  619. else:
  620. n.info.fileIndex = fileInfoIdx(c.config, AbsoluteFile(x.strVal))
  621. n.info.line = uint16(y.intVal)
  622. else:
  623. localError(c.config, n.info, "tuple expected")
  624. else:
  625. # sensible default:
  626. n.info = getInfoContext(c.config, -1)
  627. proc processPragma(c: PContext, n: PNode, i: int) =
  628. ## Create and add a new custom pragma `{.pragma: name.}` node to the module's context.
  629. let it = n[i]
  630. if it.kind notin nkPragmaCallKinds and it.safeLen == 2:
  631. invalidPragma(c, n)
  632. return
  633. elif it.safeLen != 2 or it[0].kind != nkIdent or it[1].kind != nkIdent:
  634. invalidPragma(c, n)
  635. return
  636. var userPragma = newSym(skTemplate, it[1].ident, c.idgen, c.module, it.info, c.config.options)
  637. styleCheckDef(c, userPragma)
  638. userPragma.ast = newTreeI(nkPragma, n.info, n.sons[i+1..^1])
  639. strTableAdd(c.userPragmas, userPragma)
  640. proc pragmaRaisesOrTags(c: PContext, n: PNode) =
  641. proc processExc(c: PContext, x: PNode) =
  642. if c.hasUnresolvedArgs(c, x):
  643. x.typ = makeTypeFromExpr(c, x)
  644. else:
  645. var t = skipTypes(c.semTypeNode(c, x, nil), skipPtrs)
  646. if t.kind notin {tyObject, tyOr}:
  647. localError(c.config, x.info, errGenerated, "invalid type for raises/tags list")
  648. x.typ = t
  649. if n.kind in nkPragmaCallKinds and n.len == 2:
  650. let it = n[1]
  651. if it.kind notin {nkCurly, nkBracket}:
  652. processExc(c, it)
  653. else:
  654. for e in items(it): processExc(c, e)
  655. else:
  656. invalidPragma(c, n)
  657. proc pragmaLockStmt(c: PContext; it: PNode) =
  658. if it.kind notin nkPragmaCallKinds or it.len != 2:
  659. invalidPragma(c, it)
  660. else:
  661. let n = it[1]
  662. if n.kind != nkBracket:
  663. localError(c.config, n.info, errGenerated, "locks pragma takes a list of expressions")
  664. else:
  665. for i in 0..<n.len:
  666. n[i] = c.semExpr(c, n[i])
  667. proc typeBorrow(c: PContext; sym: PSym, n: PNode) =
  668. if n.kind in nkPragmaCallKinds and n.len == 2:
  669. let it = n[1]
  670. if it.kind != nkAccQuoted:
  671. localError(c.config, n.info, "a type can only borrow `.` for now")
  672. incl(sym.typ.flags, tfBorrowDot)
  673. proc markCompilerProc(c: PContext; s: PSym) =
  674. # minor hack ahead: FlowVar is the only generic .compilerproc type which
  675. # should not have an external name set:
  676. if s.kind != skType or s.name.s != "FlowVar":
  677. makeExternExport(c, s, "$1", s.info)
  678. incl(s.flags, sfCompilerProc)
  679. incl(s.flags, sfUsed)
  680. registerCompilerProc(c.graph, s)
  681. if c.config.symbolFiles != disabledSf:
  682. addCompilerProc(c.encoder, c.packedRepr, s)
  683. proc deprecatedStmt(c: PContext; outerPragma: PNode) =
  684. let pragma = outerPragma[1]
  685. if pragma.kind in {nkStrLit..nkTripleStrLit}:
  686. incl(c.module.flags, sfDeprecated)
  687. c.module.constraint = getStrLitNode(c, outerPragma)
  688. return
  689. if pragma.kind != nkBracket:
  690. localError(c.config, pragma.info, "list of key:value pairs expected"); return
  691. message(c.config, pragma.info, warnDeprecated,
  692. "deprecated statement is now a no-op, use regular deprecated pragma")
  693. proc pragmaGuard(c: PContext; it: PNode; kind: TSymKind): PSym =
  694. if it.kind notin nkPragmaCallKinds or it.len != 2:
  695. invalidPragma(c, it); return
  696. let n = it[1]
  697. if n.kind == nkSym:
  698. result = n.sym
  699. elif kind == skField:
  700. # First check if the guard is a global variable:
  701. result = qualifiedLookUp(c, n, {})
  702. if result.isNil or result.kind notin {skLet, skVar} or
  703. sfGlobal notin result.flags:
  704. # We return a dummy symbol; later passes over the type will repair it.
  705. # Generic instantiation needs to know about this too. But we're lazy
  706. # and perform the lookup on demand instead.
  707. result = newSym(skUnknown, considerQuotedIdent(c, n), c.idgen, nil, n.info,
  708. c.config.options)
  709. else:
  710. result = qualifiedLookUp(c, n, {checkUndeclared})
  711. proc semCustomPragma(c: PContext, n: PNode, sym: PSym): PNode =
  712. var callNode: PNode
  713. if n.kind in {nkIdent, nkSym}:
  714. # pragma -> pragma()
  715. callNode = newTree(nkCall, n)
  716. elif n.kind == nkExprColonExpr:
  717. # pragma: arg -> pragma(arg)
  718. callNode = newTree(nkCall, n[0], n[1])
  719. elif n.kind in nkPragmaCallKinds:
  720. callNode = n
  721. else:
  722. invalidPragma(c, n)
  723. return n
  724. trySuggestPragmas(c, callNode[0])
  725. let r = c.semOverloadedCall(c, callNode, n, {skTemplate}, {efNoUndeclared})
  726. if r.isNil or sfCustomPragma notin r[0].sym.flags:
  727. invalidPragma(c, n)
  728. return n
  729. # we have a valid custom pragma
  730. if sym != nil and sym.kind in {skEnumField, skForVar, skModule}:
  731. illegalCustomPragma(c, n, sym)
  732. return n
  733. result = r
  734. # Transform the nkCall node back to its original form if possible
  735. if n.kind == nkIdent and r.len == 1:
  736. # pragma() -> pragma
  737. result = result[0]
  738. elif n.kind == nkExprColonExpr and r.len == 2:
  739. # pragma(arg) -> pragma: arg
  740. result.transitionSonsKind(n.kind)
  741. proc processEffectsOf(c: PContext, n: PNode; owner: PSym) =
  742. proc processParam(c: PContext; n: PNode) =
  743. let r = c.semExpr(c, n)
  744. if r.kind == nkSym and r.sym.kind == skParam:
  745. if r.sym.owner == owner:
  746. incl r.sym.flags, sfEffectsDelayed
  747. else:
  748. localError(c.config, n.info, errGenerated, "parameter cannot be declared as .effectsOf")
  749. else:
  750. localError(c.config, n.info, errGenerated, "parameter name expected")
  751. if n.kind notin nkPragmaCallKinds or n.len != 2:
  752. localError(c.config, n.info, errGenerated, "parameter name expected")
  753. else:
  754. let it = n[1]
  755. if it.kind in {nkCurly, nkBracket}:
  756. for x in items(it): processParam(c, x)
  757. else:
  758. processParam(c, it)
  759. proc singlePragma(c: PContext, sym: PSym, n: PNode, i: var int,
  760. validPragmas: TSpecialWords,
  761. comesFromPush, isStatement: bool): bool =
  762. result = false
  763. var it = n[i]
  764. let keyDeep = it.kind in nkPragmaCallKinds and it.len > 1
  765. var key = if keyDeep: it[0] else: it
  766. if key.kind == nkBracketExpr:
  767. processNote(c, it)
  768. return
  769. elif key.kind == nkCast:
  770. if comesFromPush:
  771. localError(c.config, n.info, "a 'cast' pragma cannot be pushed")
  772. elif not isStatement:
  773. localError(c.config, n.info, "'cast' pragma only allowed in a statement context")
  774. case whichPragma(key[1])
  775. of wRaises, wTags, wForbids: pragmaRaisesOrTags(c, key[1])
  776. else: discard
  777. return
  778. elif key.kind notin nkIdentKinds:
  779. n[i] = semCustomPragma(c, it, sym)
  780. return
  781. let ident = considerQuotedIdent(c, key)
  782. var userPragma = strTableGet(c.userPragmas, ident)
  783. if userPragma != nil:
  784. styleCheckUse(c, key.info, userPragma)
  785. # number of pragmas increase/decrease with user pragma expansion
  786. inc c.instCounter
  787. if c.instCounter > 100:
  788. globalError(c.config, it.info, "recursive dependency: " & userPragma.name.s)
  789. if keyDeep:
  790. localError(c.config, it.info, "user pragma cannot have arguments")
  791. pragma(c, sym, userPragma.ast, validPragmas, isStatement)
  792. n.sons[i..i] = userPragma.ast.sons # expand user pragma with its content
  793. i.inc(userPragma.ast.len - 1) # inc by -1 is ok, user pragmas was empty
  794. dec c.instCounter
  795. else:
  796. let k = whichKeyword(ident)
  797. if k in validPragmas:
  798. checkPragmaUse(c, key.info, k, ident.s, (if sym != nil: sym else: c.module))
  799. case k
  800. of wExportc, wExportCpp:
  801. makeExternExport(c, sym, getOptionalStr(c, it, "$1"), it.info)
  802. if k == wExportCpp:
  803. if c.config.backend != backendCpp:
  804. localError(c.config, it.info, "exportcpp requires `cpp` backend, got: " & $c.config.backend)
  805. else:
  806. incl(sym.flags, sfMangleCpp)
  807. incl(sym.flags, sfUsed) # avoid wrong hints
  808. of wImportc:
  809. let name = getOptionalStr(c, it, "$1")
  810. cppDefine(c.config, name)
  811. recordPragma(c, it, "cppdefine", name)
  812. makeExternImport(c, sym, name, it.info)
  813. of wImportCompilerProc:
  814. let name = getOptionalStr(c, it, "$1")
  815. cppDefine(c.config, name)
  816. recordPragma(c, it, "cppdefine", name)
  817. processImportCompilerProc(c, sym, name, it.info)
  818. of wExtern: setExternName(c, sym, expectStrLit(c, it), it.info)
  819. of wDirty:
  820. if sym.kind == skTemplate: incl(sym.flags, sfDirty)
  821. else: invalidPragma(c, it)
  822. of wRedefine:
  823. if sym.kind == skTemplate: incl(sym.flags, sfTemplateRedefinition)
  824. else: invalidPragma(c, it)
  825. of wCallsite:
  826. if sym.kind == skTemplate: incl(sym.flags, sfCallsite)
  827. else: invalidPragma(c, it)
  828. of wImportCpp:
  829. processImportCpp(c, sym, getOptionalStr(c, it, "$1"), it.info)
  830. of wCppNonPod:
  831. incl(sym.flags, sfCppNonPod)
  832. of wImportJs:
  833. if c.config.backend != backendJs:
  834. localError(c.config, it.info, "`importjs` pragma requires the JavaScript target")
  835. let name = getOptionalStr(c, it, "$1")
  836. incl(sym.flags, sfImportc)
  837. incl(sym.flags, sfInfixCall)
  838. if sym.kind in skProcKinds and {'(', '#', '@'} notin name:
  839. localError(c.config, n.info, "`importjs` for routines requires a pattern")
  840. setExternName(c, sym, name, it.info)
  841. of wImportObjC:
  842. processImportObjC(c, sym, getOptionalStr(c, it, "$1"), it.info)
  843. of wSize:
  844. if sym.typ == nil: invalidPragma(c, it)
  845. var size = expectIntLit(c, it)
  846. case size
  847. of 1, 2, 4:
  848. sym.typ.size = size
  849. sym.typ.align = int16 size
  850. of 8:
  851. sym.typ.size = 8
  852. sym.typ.align = floatInt64Align(c.config)
  853. else:
  854. localError(c.config, it.info, "size may only be 1, 2, 4 or 8")
  855. of wAlign:
  856. let alignment = expectIntLit(c, it)
  857. if isPowerOfTwo(alignment) and alignment > 0:
  858. sym.alignment = max(sym.alignment, alignment)
  859. else:
  860. localError(c.config, it.info, "power of two expected")
  861. of wNodecl:
  862. noVal(c, it)
  863. incl(sym.loc.flags, lfNoDecl)
  864. of wPure, wAsmNoStackFrame:
  865. noVal(c, it)
  866. if sym != nil:
  867. if k == wPure and sym.kind in routineKinds: invalidPragma(c, it)
  868. else: incl(sym.flags, sfPure)
  869. of wVolatile:
  870. noVal(c, it)
  871. incl(sym.flags, sfVolatile)
  872. of wCursor:
  873. noVal(c, it)
  874. incl(sym.flags, sfCursor)
  875. of wRegister:
  876. noVal(c, it)
  877. incl(sym.flags, sfRegister)
  878. of wNoalias:
  879. noVal(c, it)
  880. incl(sym.flags, sfNoalias)
  881. of wEffectsOf:
  882. processEffectsOf(c, it, sym)
  883. of wThreadVar:
  884. noVal(c, it)
  885. incl(sym.flags, {sfThread, sfGlobal})
  886. of wDeadCodeElimUnused:
  887. warningDeprecated(c.config, n.info, "'{.deadcodeelim: on.}' is deprecated, now a noop") # deprecated, dead code elim always on
  888. of wNoForward: pragmaNoForward(c, it)
  889. of wReorder: pragmaNoForward(c, it, flag = sfReorder)
  890. of wMagic: processMagic(c, it, sym)
  891. of wCompileTime:
  892. noVal(c, it)
  893. if comesFromPush:
  894. if sym.kind in {skProc, skFunc}:
  895. incl(sym.flags, sfCompileTime)
  896. else:
  897. incl(sym.flags, sfCompileTime)
  898. #incl(sym.loc.flags, lfNoDecl)
  899. of wGlobal:
  900. noVal(c, it)
  901. incl(sym.flags, sfGlobal)
  902. incl(sym.flags, sfPure)
  903. of wConstructor:
  904. incl(sym.flags, sfConstructor)
  905. if sfImportc notin sym.flags:
  906. sym.constraint = newEmptyStrNode(c, it, getOptionalStr(c, it, ""))
  907. sym.constraint.strVal = sym.constraint.strVal
  908. sym.flags.incl {sfExportc, sfMangleCpp}
  909. sym.typ.callConv = ccNoConvention
  910. of wHeader:
  911. var lib = getLib(c, libHeader, getStrLitNode(c, it))
  912. addToLib(lib, sym)
  913. incl(sym.flags, sfImportc)
  914. incl(sym.loc.flags, lfHeader)
  915. incl(sym.loc.flags, lfNoDecl)
  916. # implies nodecl, because otherwise header would not make sense
  917. if sym.loc.r == "": sym.loc.r = rope(sym.name.s)
  918. of wNoSideEffect:
  919. noVal(c, it)
  920. if sym != nil:
  921. incl(sym.flags, sfNoSideEffect)
  922. if sym.typ != nil: incl(sym.typ.flags, tfNoSideEffect)
  923. of wSideEffect:
  924. noVal(c, it)
  925. incl(sym.flags, sfSideEffect)
  926. of wNoreturn:
  927. noVal(c, it)
  928. # Disable the 'noreturn' annotation when in the "Quirky Exceptions" mode!
  929. if c.config.exc != excQuirky:
  930. incl(sym.flags, sfNoReturn)
  931. if sym.typ.returnType != nil:
  932. localError(c.config, sym.ast[paramsPos][0].info,
  933. ".noreturn with return type not allowed")
  934. of wNoDestroy:
  935. noVal(c, it)
  936. incl(sym.flags, sfGeneratedOp)
  937. of wNosinks:
  938. noVal(c, it)
  939. incl(sym.flags, sfWasForwarded)
  940. of wDynlib:
  941. processDynLib(c, it, sym)
  942. of wCompilerProc, wCore:
  943. noVal(c, it) # compilerproc may not get a string!
  944. cppDefine(c.graph.config, sym.name.s)
  945. recordPragma(c, it, "cppdefine", sym.name.s)
  946. if sfFromGeneric notin sym.flags: markCompilerProc(c, sym)
  947. of wNonReloadable:
  948. sym.flags.incl sfNonReloadable
  949. of wProcVar:
  950. # old procvar annotation, no longer needed
  951. noVal(c, it)
  952. of wExplain:
  953. sym.flags.incl sfExplain
  954. of wDeprecated:
  955. if sym != nil and sym.kind in routineKinds + {skType, skVar, skLet, skConst}:
  956. if it.kind in nkPragmaCallKinds: discard getStrLitNode(c, it)
  957. incl(sym.flags, sfDeprecated)
  958. elif sym != nil and sym.kind != skModule:
  959. # We don't support the extra annotation field
  960. if it.kind in nkPragmaCallKinds:
  961. localError(c.config, it.info, "annotation to deprecated not supported here")
  962. incl(sym.flags, sfDeprecated)
  963. # At this point we're quite sure this is a statement and applies to the
  964. # whole module
  965. elif it.kind in nkPragmaCallKinds: deprecatedStmt(c, it)
  966. else: incl(c.module.flags, sfDeprecated)
  967. of wVarargs:
  968. noVal(c, it)
  969. if sym.typ == nil: invalidPragma(c, it)
  970. else: incl(sym.typ.flags, tfVarargs)
  971. of wBorrow:
  972. if sym.kind == skType:
  973. typeBorrow(c, sym, it)
  974. else:
  975. noVal(c, it)
  976. incl(sym.flags, sfBorrow)
  977. of wFinal:
  978. noVal(c, it)
  979. if sym.typ == nil: invalidPragma(c, it)
  980. else: incl(sym.typ.flags, tfFinal)
  981. of wInheritable:
  982. noVal(c, it)
  983. if sym.typ == nil or tfFinal in sym.typ.flags: invalidPragma(c, it)
  984. else: incl(sym.typ.flags, tfInheritable)
  985. of wPackage:
  986. noVal(c, it)
  987. if sym.typ == nil: invalidPragma(c, it)
  988. else: incl(sym.flags, sfForward)
  989. of wAcyclic:
  990. noVal(c, it)
  991. if sym.typ == nil: invalidPragma(c, it)
  992. else: incl(sym.typ.flags, tfAcyclic)
  993. of wShallow:
  994. noVal(c, it)
  995. if sym.typ == nil: invalidPragma(c, it)
  996. else: incl(sym.typ.flags, tfShallow)
  997. of wThread:
  998. noVal(c, it)
  999. incl(sym.flags, sfThread)
  1000. if sym.typ != nil:
  1001. incl(sym.typ.flags, tfThread)
  1002. if sym.typ.callConv == ccClosure: sym.typ.callConv = ccNimCall
  1003. of wSendable:
  1004. noVal(c, it)
  1005. if sym != nil and sym.typ != nil:
  1006. incl(sym.typ.flags, tfSendable)
  1007. else:
  1008. invalidPragma(c, it)
  1009. of wGcSafe:
  1010. noVal(c, it)
  1011. if sym != nil:
  1012. if sym.kind != skType: incl(sym.flags, sfThread)
  1013. if sym.typ != nil: incl(sym.typ.flags, tfGcSafe)
  1014. else: invalidPragma(c, it)
  1015. else:
  1016. discard "no checking if used as a code block"
  1017. of wPacked:
  1018. noVal(c, it)
  1019. if sym.typ == nil: invalidPragma(c, it)
  1020. else: incl(sym.typ.flags, tfPacked)
  1021. of wHint:
  1022. let s = expectStrLit(c, it)
  1023. recordPragma(c, it, "hint", s)
  1024. message(c.config, it.info, hintUser, s)
  1025. of wWarning:
  1026. let s = expectStrLit(c, it)
  1027. recordPragma(c, it, "warning", s)
  1028. message(c.config, it.info, warnUser, s)
  1029. of wError:
  1030. if sym != nil and (sym.isRoutine or sym.kind == skType) and not isStatement:
  1031. # This is subtle but correct: the error *statement* is only
  1032. # allowed when 'wUsed' is not in validPragmas. Here this is the easiest way to
  1033. # distinguish properly between
  1034. # ``proc p() {.error}`` and ``proc p() = {.error: "msg".}``
  1035. if it.kind in nkPragmaCallKinds: discard getStrLitNode(c, it)
  1036. incl(sym.flags, sfError)
  1037. excl(sym.flags, sfForward)
  1038. else:
  1039. let s = expectStrLit(c, it)
  1040. recordPragma(c, it, "error", s)
  1041. localError(c.config, it.info, errUser, s)
  1042. of wFatal: fatal(c.config, it.info, expectStrLit(c, it))
  1043. of wDefine: processDefine(c, it, sym)
  1044. of wUndef: processUndef(c, it)
  1045. of wCompile:
  1046. let m = sym.getModule()
  1047. incl(m.flags, sfUsed)
  1048. processCompile(c, it)
  1049. of wLink: processLink(c, it)
  1050. of wPassl:
  1051. let m = sym.getModule()
  1052. incl(m.flags, sfUsed)
  1053. let s = expectStrLit(c, it)
  1054. extccomp.addLinkOption(c.config, s)
  1055. recordPragma(c, it, "passl", s)
  1056. of wPassc:
  1057. let m = sym.getModule()
  1058. incl(m.flags, sfUsed)
  1059. let s = expectStrLit(c, it)
  1060. extccomp.addCompileOption(c.config, s)
  1061. recordPragma(c, it, "passc", s)
  1062. of wLocalPassc:
  1063. assert sym != nil and sym.kind == skModule
  1064. let s = expectStrLit(c, it)
  1065. appendToModule(sym, n)
  1066. extccomp.addLocalCompileOption(c.config, s, toFullPathConsiderDirty(c.config, sym.info.fileIndex))
  1067. recordPragma(c, it, "localpassl", s)
  1068. of wPush:
  1069. processPush(c, n, i + 1)
  1070. result = true
  1071. of wPop:
  1072. processPop(c, it)
  1073. result = true
  1074. of wPragma:
  1075. if not sym.isNil and sym.kind == skTemplate:
  1076. sym.flags.incl sfCustomPragma
  1077. else:
  1078. processPragma(c, n, i)
  1079. result = true
  1080. of wDiscardable:
  1081. noVal(c, it)
  1082. if sym != nil: incl(sym.flags, sfDiscardable)
  1083. of wNoInit:
  1084. noVal(c, it)
  1085. if sym != nil: incl(sym.flags, sfNoInit)
  1086. of wCodegenDecl: processCodegenDecl(c, it, sym)
  1087. of wChecks, wObjChecks, wFieldChecks, wRangeChecks, wBoundChecks,
  1088. wOverflowChecks, wNilChecks, wAssertions, wWarnings, wHints,
  1089. wLineDir, wOptimization, wStaticBoundchecks, wStyleChecks,
  1090. wCallconv, wDebugger, wProfiler,
  1091. wFloatChecks, wNanChecks, wInfChecks, wPatterns, wTrMacros:
  1092. processOption(c, it, c.config.options)
  1093. of wStackTrace, wLineTrace:
  1094. if sym.kind in {skProc, skMethod, skConverter}:
  1095. processOption(c, it, sym.options)
  1096. else:
  1097. processOption(c, it, c.config.options)
  1098. of FirstCallConv..LastCallConv:
  1099. assert(sym != nil)
  1100. if sym.typ == nil: invalidPragma(c, it)
  1101. else:
  1102. sym.typ.callConv = wordToCallConv(k)
  1103. sym.typ.flags.incl tfExplicitCallConv
  1104. of wEmit: pragmaEmit(c, it)
  1105. of wUnroll: pragmaUnroll(c, it)
  1106. of wLinearScanEnd, wComputedGoto: noVal(c, it)
  1107. of wEffects:
  1108. # is later processed in effect analysis:
  1109. noVal(c, it)
  1110. of wIncompleteStruct:
  1111. noVal(c, it)
  1112. if sym.typ == nil: invalidPragma(c, it)
  1113. else: incl(sym.typ.flags, tfIncompleteStruct)
  1114. of wCompleteStruct:
  1115. noVal(c, it)
  1116. if sym.typ == nil: invalidPragma(c, it)
  1117. else: incl(sym.typ.flags, tfCompleteStruct)
  1118. of wUnchecked:
  1119. noVal(c, it)
  1120. if sym.typ == nil or sym.typ.kind notin {tyArray, tyUncheckedArray}:
  1121. invalidPragma(c, it)
  1122. else:
  1123. sym.typ.kind = tyUncheckedArray
  1124. of wUnion:
  1125. if c.config.backend == backendJs:
  1126. localError(c.config, it.info, "`{.union.}` is not implemented for js backend.")
  1127. else:
  1128. noVal(c, it)
  1129. if sym.typ == nil: invalidPragma(c, it)
  1130. else: incl(sym.typ.flags, tfUnion)
  1131. of wRequiresInit:
  1132. noVal(c, it)
  1133. if sym.kind == skField:
  1134. sym.flags.incl sfRequiresInit
  1135. elif sym.typ != nil:
  1136. incl(sym.typ.flags, tfNeedsFullInit)
  1137. else:
  1138. invalidPragma(c, it)
  1139. of wByRef:
  1140. noVal(c, it)
  1141. if sym != nil and sym.kind == skParam:
  1142. sym.options.incl optByRef
  1143. elif sym == nil or sym.typ == nil:
  1144. processOption(c, it, c.config.options)
  1145. else:
  1146. incl(sym.typ.flags, tfByRef)
  1147. of wByCopy:
  1148. noVal(c, it)
  1149. if sym.kind == skParam:
  1150. incl(sym.flags, sfByCopy)
  1151. elif sym.kind != skType or sym.typ == nil: invalidPragma(c, it)
  1152. else: incl(sym.typ.flags, tfByCopy)
  1153. of wPartial:
  1154. noVal(c, it)
  1155. if sym.kind != skType or sym.typ == nil: invalidPragma(c, it)
  1156. else:
  1157. incl(sym.typ.flags, tfPartial)
  1158. of wInject, wGensym:
  1159. # We check for errors, but do nothing with these pragmas otherwise
  1160. # as they are handled directly in 'evalTemplate'.
  1161. noVal(c, it)
  1162. if sym == nil: invalidPragma(c, it)
  1163. of wLine: pragmaLine(c, it)
  1164. of wRaises, wTags, wForbids: pragmaRaisesOrTags(c, it)
  1165. of wLocks:
  1166. if sym == nil: pragmaLockStmt(c, it)
  1167. elif sym.typ == nil: invalidPragma(c, it)
  1168. else: warningDeprecated(c.config, n.info, "'Lock levels' are deprecated, now a noop")
  1169. of wBitsize:
  1170. if sym == nil or sym.kind != skField:
  1171. invalidPragma(c, it)
  1172. else:
  1173. sym.bitsize = expectIntLit(c, it)
  1174. if sym.bitsize <= 0:
  1175. localError(c.config, it.info, "bitsize needs to be positive")
  1176. of wGuard:
  1177. if sym == nil or sym.kind notin {skVar, skLet, skField}:
  1178. invalidPragma(c, it)
  1179. else:
  1180. sym.guard = pragmaGuard(c, it, sym.kind)
  1181. of wGoto:
  1182. if sym == nil or sym.kind notin {skVar, skLet}:
  1183. invalidPragma(c, it)
  1184. else:
  1185. sym.flags.incl sfGoto
  1186. of wExportNims:
  1187. if sym == nil: invalidPragma(c, it)
  1188. else: magicsys.registerNimScriptSymbol(c.graph, sym)
  1189. of wExperimental:
  1190. if not isTopLevel(c):
  1191. localError(c.config, n.info, "'experimental' pragma only valid as toplevel statement or in a 'push' environment")
  1192. processExperimental(c, it)
  1193. of wDoctype:
  1194. if not isTopLevel(c):
  1195. localError(c.config, n.info, "\"doctype\" pragma only valid as top-level statement")
  1196. of wNoRewrite:
  1197. noVal(c, it)
  1198. of wBase:
  1199. noVal(c, it)
  1200. sym.flags.incl sfBase
  1201. of wIntDefine:
  1202. processDefineConst(c, n, sym, mIntDefine)
  1203. of wStrDefine:
  1204. processDefineConst(c, n, sym, mStrDefine)
  1205. of wBoolDefine:
  1206. processDefineConst(c, n, sym, mBoolDefine)
  1207. of wUsed:
  1208. noVal(c, it)
  1209. if sym == nil: invalidPragma(c, it)
  1210. else: sym.flags.incl sfUsed
  1211. of wLiftLocals: discard
  1212. of wRequires, wInvariant, wAssume, wAssert:
  1213. pragmaProposition(c, it)
  1214. of wEnsures:
  1215. pragmaEnsures(c, it)
  1216. of wEnforceNoRaises, wQuirky:
  1217. sym.flags.incl sfNeverRaises
  1218. of wSystemRaisesDefect:
  1219. sym.flags.incl sfSystemRaisesDefect
  1220. of wVirtual:
  1221. processVirtual(c, it, sym, sfVirtual)
  1222. of wMember:
  1223. processVirtual(c, it, sym, sfMember)
  1224. else: invalidPragma(c, it)
  1225. elif comesFromPush and whichKeyword(ident) != wInvalid:
  1226. discard "ignore the .push pragma; it doesn't apply"
  1227. else:
  1228. # semCustomPragma gives appropriate error for invalid pragmas
  1229. n[i] = semCustomPragma(c, it, sym)
  1230. proc overwriteLineInfo(n: PNode; info: TLineInfo) =
  1231. n.info = info
  1232. for i in 0..<n.safeLen:
  1233. overwriteLineInfo(n[i], info)
  1234. proc mergePragmas(n, pragmas: PNode) =
  1235. var pragmas = copyTree(pragmas)
  1236. overwriteLineInfo pragmas, n.info
  1237. if n[pragmasPos].kind == nkEmpty:
  1238. n[pragmasPos] = pragmas
  1239. else:
  1240. for p in pragmas: n[pragmasPos].add p
  1241. proc implicitPragmas*(c: PContext, sym: PSym, info: TLineInfo,
  1242. validPragmas: TSpecialWords) =
  1243. if sym != nil and sym.kind != skModule:
  1244. for it in c.optionStack:
  1245. let o = it.otherPragmas
  1246. if not o.isNil and sfFromGeneric notin sym.flags: # bug #23019
  1247. pushInfoContext(c.config, info)
  1248. var i = 0
  1249. while i < o.len:
  1250. if singlePragma(c, sym, o, i, validPragmas, true, false):
  1251. internalError(c.config, info, "implicitPragmas")
  1252. inc i
  1253. popInfoContext(c.config)
  1254. if sym.kind in routineKinds and sym.ast != nil: mergePragmas(sym.ast, o)
  1255. if lfExportLib in sym.loc.flags and sfExportc notin sym.flags:
  1256. localError(c.config, info, ".dynlib requires .exportc")
  1257. var lib = c.optionStack[^1].dynlib
  1258. if {lfDynamicLib, lfHeader} * sym.loc.flags == {} and
  1259. sfImportc in sym.flags and lib != nil:
  1260. incl(sym.loc.flags, lfDynamicLib)
  1261. addToLib(lib, sym)
  1262. if sym.loc.r == "": sym.loc.r = rope(sym.name.s)
  1263. proc hasPragma*(n: PNode, pragma: TSpecialWord): bool =
  1264. if n == nil: return false
  1265. for p in n:
  1266. var key = if p.kind in nkPragmaCallKinds and p.len > 1: p[0] else: p
  1267. if key.kind == nkIdent and whichKeyword(key.ident) == pragma:
  1268. return true
  1269. return false
  1270. proc pragmaRec(c: PContext, sym: PSym, n: PNode, validPragmas: TSpecialWords;
  1271. isStatement: bool) =
  1272. if n == nil: return
  1273. var i = 0
  1274. while i < n.len:
  1275. if singlePragma(c, sym, n, i, validPragmas, false, isStatement): break
  1276. inc i
  1277. proc pragma(c: PContext, sym: PSym, n: PNode, validPragmas: TSpecialWords;
  1278. isStatement: bool) =
  1279. if n == nil: return
  1280. pragmaRec(c, sym, n, validPragmas, isStatement)
  1281. # XXX: in the case of a callable def, this should use its info
  1282. implicitPragmas(c, sym, n.info, validPragmas)
  1283. proc pragmaCallable*(c: PContext, sym: PSym, n: PNode, validPragmas: TSpecialWords,
  1284. isStatement: bool = false) =
  1285. if n == nil: return
  1286. if n[pragmasPos].kind != nkEmpty:
  1287. pragmaRec(c, sym, n[pragmasPos], validPragmas, isStatement)