pragmas.nim 50 KB

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