pragmas.nim 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158
  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, platform, condsyms, ast, astalgo, idents, semdata, msgs, renderer,
  12. wordrecg, ropes, options, strutils, extccomp, math, magicsys, trees,
  13. types, lookups, lineinfos, pathutils
  14. const
  15. FirstCallConv* = wNimcall
  16. LastCallConv* = wNoconv
  17. const
  18. procPragmas* = {FirstCallConv..LastCallConv, wImportc, wExportc, wNodecl,
  19. wMagic, wNosideeffect, wSideeffect, wNoreturn, wDynlib, wHeader,
  20. wCompilerProc, wCore, wProcVar, wDeprecated, wVarargs, wCompileTime, wMerge,
  21. wBorrow, wExtern, wImportCompilerProc, wThread, wImportCpp, wImportObjC,
  22. wAsmNoStackFrame, wError, wDiscardable, wNoInit, wCodegenDecl,
  23. wGensym, wInject, wRaises, wTags, wLocks, wDelegator, wGcSafe, wOverride,
  24. wConstructor, wExportNims, wUsed, wLiftLocals, wStacktrace, wLinetrace}
  25. converterPragmas* = procPragmas
  26. methodPragmas* = procPragmas+{wBase}-{wImportCpp}
  27. templatePragmas* = {wImmediate, wDeprecated, wError, wGensym, wInject, wDirty,
  28. wDelegator, wExportNims, wUsed, wPragma}
  29. macroPragmas* = {FirstCallConv..LastCallConv, wImmediate, wImportc, wExportc,
  30. wNodecl, wMagic, wNosideeffect, wCompilerProc, wCore, wDeprecated, wExtern,
  31. wImportCpp, wImportObjC, wError, wDiscardable, wGensym, wInject, wDelegator,
  32. wExportNims, wUsed}
  33. iteratorPragmas* = {FirstCallConv..LastCallConv, wNosideeffect, wSideeffect,
  34. wImportc, wExportc, wNodecl, wMagic, wDeprecated, wBorrow, wExtern,
  35. wImportCpp, wImportObjC, wError, wDiscardable, wGensym, wInject, wRaises,
  36. wTags, wLocks, wGcSafe, wExportNims, wUsed}
  37. exprPragmas* = {wLine, wLocks, wNoRewrite, wGcSafe}
  38. stmtPragmas* = {wChecks, wObjChecks, wFieldChecks, wRangechecks,
  39. wBoundchecks, wOverflowchecks, wNilchecks, wMovechecks, wAssertions,
  40. wWarnings, wHints,
  41. wLinedir, wStacktrace, wLinetrace, wOptimization, wHint, wWarning, wError,
  42. wFatal, wDefine, wUndef, wCompile, wLink, wLinksys, wPure, wPush, wPop,
  43. wBreakpoint, wWatchPoint, wPassl, wPassc,
  44. wDeadCodeElimUnused, # deprecated, always on
  45. wDeprecated,
  46. wFloatchecks, wInfChecks, wNanChecks, wPragma, wEmit, wUnroll,
  47. wLinearScanEnd, wPatterns, wEffects, wNoForward, wReorder, wComputedGoto,
  48. wInjectStmt, wDeprecated, wExperimental, wThis}
  49. lambdaPragmas* = {FirstCallConv..LastCallConv, wImportc, wExportc, wNodecl,
  50. wNosideeffect, wSideeffect, wNoreturn, wDynlib, wHeader,
  51. wDeprecated, wExtern, wThread, wImportCpp, wImportObjC, wAsmNoStackFrame,
  52. wRaises, wLocks, wTags, wGcSafe, wCodegenDecl}
  53. typePragmas* = {wImportc, wExportc, wDeprecated, wMagic, wAcyclic, wNodecl,
  54. wPure, wHeader, wCompilerProc, wCore, wFinal, wSize, wExtern, wShallow,
  55. wImportCpp, wImportObjC, wError, wIncompleteStruct, wByCopy, wByRef,
  56. wInheritable, wGensym, wInject, wRequiresInit, wUnchecked, wUnion, wPacked,
  57. wBorrow, wGcSafe, wExportNims, wPartial, wUsed, wExplain, wPackage}
  58. fieldPragmas* = {wImportc, wExportc, wDeprecated, wExtern,
  59. wImportCpp, wImportObjC, wError, wGuard, wBitsize, wUsed}
  60. varPragmas* = {wImportc, wExportc, wVolatile, wRegister, wThreadVar, wNodecl,
  61. wMagic, wHeader, wDeprecated, wCompilerProc, wCore, wDynlib, wExtern,
  62. wImportCpp, wImportObjC, wError, wNoInit, wCompileTime, wGlobal,
  63. wGensym, wInject, wCodegenDecl, wGuard, wGoto, wExportNims, wUsed}
  64. constPragmas* = {wImportc, wExportc, wHeader, wDeprecated, wMagic, wNodecl,
  65. wExtern, wImportCpp, wImportObjC, wError, wGensym, wInject, wExportNims,
  66. wIntDefine, wStrDefine, wUsed, wCompilerProc, wCore}
  67. letPragmas* = varPragmas
  68. procTypePragmas* = {FirstCallConv..LastCallConv, wVarargs, wNosideeffect,
  69. wThread, wRaises, wLocks, wTags, wGcSafe}
  70. forVarPragmas* = {wInject, wGensym}
  71. allRoutinePragmas* = methodPragmas + iteratorPragmas + lambdaPragmas
  72. proc getPragmaVal*(procAst: PNode; name: TSpecialWord): PNode =
  73. let p = procAst[pragmasPos]
  74. if p.kind == nkEmpty: return nil
  75. for it in p:
  76. if it.kind in nkPragmaCallKinds and it.len == 2 and it[0].kind == nkIdent and
  77. it[0].ident.id == ord(name):
  78. return it[1]
  79. proc pragma*(c: PContext, sym: PSym, n: PNode, validPragmas: TSpecialWords)
  80. proc recordPragma(c: PContext; n: PNode; key, val: string; val2 = "") =
  81. var recorded = newNodeI(nkCommentStmt, n.info)
  82. recorded.add newStrNode(key, n.info)
  83. recorded.add newStrNode(val, n.info)
  84. if val2.len > 0: recorded.add newStrNode(val2, n.info)
  85. c.graph.recordStmt(c.graph, c.module, recorded)
  86. const
  87. errStringLiteralExpected = "string literal expected"
  88. errIntLiteralExpected = "integer literal expected"
  89. proc invalidPragma*(c: PContext; n: PNode) =
  90. localError(c.config, n.info, "invalid pragma: " & renderTree(n, {renderNoComments}))
  91. proc illegalCustomPragma*(c: PContext, n: PNode, s: PSym) =
  92. localError(c.config, n.info, "cannot attach a custom pragma to '" & s.name.s & "'")
  93. proc pragmaAsm*(c: PContext, n: PNode): char =
  94. result = '\0'
  95. if n != nil:
  96. for i in countup(0, sonsLen(n) - 1):
  97. let it = n.sons[i]
  98. if it.kind in nkPragmaCallKinds and it.len == 2 and it.sons[0].kind == nkIdent:
  99. case whichKeyword(it.sons[0].ident)
  100. of wSubsChar:
  101. if it.sons[1].kind == nkCharLit: result = chr(int(it.sons[1].intVal))
  102. else: invalidPragma(c, it)
  103. else: invalidPragma(c, it)
  104. else:
  105. invalidPragma(c, it)
  106. proc setExternName(c: PContext; s: PSym, extname: string, info: TLineInfo) =
  107. # special cases to improve performance:
  108. if extname == "$1":
  109. s.loc.r = rope(s.name.s)
  110. elif '$' notin extname:
  111. s.loc.r = rope(extname)
  112. else:
  113. try:
  114. s.loc.r = rope(extname % s.name.s)
  115. except ValueError:
  116. localError(c.config, info, "invalid extern name: '" & extname & "'. (Forgot to escape '$'?)")
  117. if c.config.cmd == cmdPretty and '$' notin extname:
  118. # note that '{.importc.}' is transformed into '{.importc: "$1".}'
  119. s.loc.flags.incl(lfFullExternalName)
  120. proc makeExternImport(c: PContext; s: PSym, extname: string, info: TLineInfo) =
  121. setExternName(c, s, extname, info)
  122. incl(s.flags, sfImportc)
  123. excl(s.flags, sfForward)
  124. proc makeExternExport(c: PContext; s: PSym, extname: string, info: TLineInfo) =
  125. setExternName(c, s, extname, info)
  126. incl(s.flags, sfExportc)
  127. proc processImportCompilerProc(c: PContext; s: PSym, extname: string, info: TLineInfo) =
  128. setExternName(c, s, extname, info)
  129. incl(s.flags, sfImportc)
  130. excl(s.flags, sfForward)
  131. incl(s.loc.flags, lfImportCompilerProc)
  132. proc processImportCpp(c: PContext; s: PSym, extname: string, info: TLineInfo) =
  133. setExternName(c, s, extname, info)
  134. incl(s.flags, sfImportc)
  135. incl(s.flags, sfInfixCall)
  136. excl(s.flags, sfForward)
  137. if c.config.cmd == cmdCompileToC:
  138. let m = s.getModule()
  139. incl(m.flags, sfCompileToCpp)
  140. incl c.config.globalOptions, optMixedMode
  141. proc processImportObjC(c: PContext; s: PSym, extname: string, info: TLineInfo) =
  142. setExternName(c, s, extname, info)
  143. incl(s.flags, sfImportc)
  144. incl(s.flags, sfNamedParamCall)
  145. excl(s.flags, sfForward)
  146. let m = s.getModule()
  147. incl(m.flags, sfCompileToObjC)
  148. proc newEmptyStrNode(c: PContext; n: PNode): PNode {.noinline.} =
  149. result = newNodeIT(nkStrLit, n.info, getSysType(c.graph, n.info, tyString))
  150. result.strVal = ""
  151. proc getStrLitNode(c: PContext, n: PNode): PNode =
  152. if n.kind notin nkPragmaCallKinds or n.len != 2:
  153. localError(c.config, n.info, errStringLiteralExpected)
  154. # error correction:
  155. result = newEmptyStrNode(c, n)
  156. else:
  157. n.sons[1] = c.semConstExpr(c, n.sons[1])
  158. case n.sons[1].kind
  159. of nkStrLit, nkRStrLit, nkTripleStrLit: result = n.sons[1]
  160. else:
  161. localError(c.config, n.info, errStringLiteralExpected)
  162. # error correction:
  163. result = newEmptyStrNode(c, n)
  164. proc expectStrLit(c: PContext, n: PNode): string =
  165. result = getStrLitNode(c, n).strVal
  166. proc expectIntLit(c: PContext, n: PNode): int =
  167. if n.kind notin nkPragmaCallKinds or n.len != 2:
  168. localError(c.config, n.info, errIntLiteralExpected)
  169. else:
  170. n.sons[1] = c.semConstExpr(c, n.sons[1])
  171. case n.sons[1].kind
  172. of nkIntLit..nkInt64Lit: result = int(n.sons[1].intVal)
  173. else: localError(c.config, n.info, errIntLiteralExpected)
  174. proc getOptionalStr(c: PContext, n: PNode, defaultStr: string): string =
  175. if n.kind in nkPragmaCallKinds: result = expectStrLit(c, n)
  176. else: result = defaultStr
  177. proc processCodegenDecl(c: PContext, n: PNode, sym: PSym) =
  178. sym.constraint = getStrLitNode(c, n)
  179. proc processMagic(c: PContext, n: PNode, s: PSym) =
  180. #if sfSystemModule notin c.module.flags:
  181. # liMessage(n.info, errMagicOnlyInSystem)
  182. if n.kind notin nkPragmaCallKinds or n.len != 2:
  183. localError(c.config, n.info, errStringLiteralExpected)
  184. return
  185. var v: string
  186. if n.sons[1].kind == nkIdent: v = n.sons[1].ident.s
  187. else: v = expectStrLit(c, n)
  188. for m in countup(low(TMagic), high(TMagic)):
  189. if substr($m, 1) == v:
  190. s.magic = m
  191. break
  192. if s.magic == mNone: message(c.config, n.info, warnUnknownMagic, v)
  193. proc wordToCallConv(sw: TSpecialWord): TCallingConvention =
  194. # this assumes that the order of special words and calling conventions is
  195. # the same
  196. result = TCallingConvention(ord(ccDefault) + ord(sw) - ord(wNimcall))
  197. proc isTurnedOn(c: PContext, n: PNode): bool =
  198. if n.kind in nkPragmaCallKinds and n.len == 2:
  199. let x = c.semConstBoolExpr(c, n.sons[1])
  200. n.sons[1] = x
  201. if x.kind == nkIntLit: return x.intVal != 0
  202. localError(c.config, n.info, "'on' or 'off' expected")
  203. proc onOff(c: PContext, n: PNode, op: TOptions, resOptions: var TOptions) =
  204. if isTurnedOn(c, n): resOptions = resOptions + op
  205. else: resOptions = resOptions - op
  206. proc pragmaNoForward(c: PContext, n: PNode; flag=sfNoForward) =
  207. if isTurnedOn(c, n):
  208. incl(c.module.flags, flag)
  209. c.features.incl codeReordering
  210. else:
  211. excl(c.module.flags, flag)
  212. # c.features.excl codeReordering
  213. # deprecated as of 0.18.1
  214. message(c.config, n.info, warnDeprecated,
  215. "use {.experimental: \"codeReordering.\".} instead; " &
  216. (if flag == sfNoForward: "{.noForward.}" else: "{.reorder.}"))
  217. proc processCallConv(c: PContext, n: PNode) =
  218. if n.kind in nkPragmaCallKinds and n.len == 2 and n.sons[1].kind == nkIdent:
  219. let sw = whichKeyword(n.sons[1].ident)
  220. case sw
  221. of FirstCallConv..LastCallConv:
  222. c.optionStack[^1].defaultCC = wordToCallConv(sw)
  223. else: localError(c.config, n.info, "calling convention expected")
  224. else:
  225. localError(c.config, n.info, "calling convention expected")
  226. proc getLib(c: PContext, kind: TLibKind, path: PNode): PLib =
  227. for it in c.libs:
  228. if it.kind == kind and trees.exprStructuralEquivalent(it.path, path):
  229. return it
  230. result = newLib(kind)
  231. result.path = path
  232. c.libs.add result
  233. if path.kind in {nkStrLit..nkTripleStrLit}:
  234. result.isOverriden = options.isDynlibOverride(c.config, path.strVal)
  235. proc expectDynlibNode(c: PContext, n: PNode): PNode =
  236. if n.kind notin nkPragmaCallKinds or n.len != 2:
  237. localError(c.config, n.info, errStringLiteralExpected)
  238. # error correction:
  239. result = newEmptyStrNode(c, n)
  240. else:
  241. # For the OpenGL wrapper we support:
  242. # {.dynlib: myGetProcAddr(...).}
  243. result = c.semExpr(c, n.sons[1])
  244. if result.kind == nkSym and result.sym.kind == skConst:
  245. result = result.sym.ast # look it up
  246. if result.typ == nil or result.typ.kind notin {tyPointer, tyString, tyProc}:
  247. localError(c.config, n.info, errStringLiteralExpected)
  248. result = newEmptyStrNode(c, n)
  249. proc processDynLib(c: PContext, n: PNode, sym: PSym) =
  250. if (sym == nil) or (sym.kind == skModule):
  251. let lib = getLib(c, libDynamic, expectDynlibNode(c, n))
  252. if not lib.isOverriden:
  253. c.optionStack[^1].dynlib = lib
  254. else:
  255. if n.kind in nkPragmaCallKinds:
  256. var lib = getLib(c, libDynamic, expectDynlibNode(c, n))
  257. if not lib.isOverriden:
  258. addToLib(lib, sym)
  259. incl(sym.loc.flags, lfDynamicLib)
  260. else:
  261. incl(sym.loc.flags, lfExportLib)
  262. # since we'll be loading the dynlib symbols dynamically, we must use
  263. # a calling convention that doesn't introduce custom name mangling
  264. # cdecl is the default - the user can override this explicitly
  265. if sym.kind in routineKinds and sym.typ != nil and
  266. sym.typ.callConv == ccDefault:
  267. sym.typ.callConv = ccCDecl
  268. proc processNote(c: PContext, n: PNode) =
  269. if n.kind in nkPragmaCallKinds and len(n) == 2 and
  270. n[0].kind == nkBracketExpr and
  271. n[0].len == 2 and
  272. n[0][1].kind == nkIdent and n[0][0].kind == nkIdent:
  273. var nk: TNoteKind
  274. case whichKeyword(n[0][0].ident)
  275. of wHint:
  276. var x = findStr(HintsToStr, n[0][1].ident.s)
  277. if x >= 0: nk = TNoteKind(x + ord(hintMin))
  278. else: invalidPragma(c, n); return
  279. of wWarning:
  280. var x = findStr(WarningsToStr, n[0][1].ident.s)
  281. if x >= 0: nk = TNoteKind(x + ord(warnMin))
  282. else: invalidPragma(c, n); return
  283. else:
  284. invalidPragma(c, n)
  285. return
  286. let x = c.semConstBoolExpr(c, n[1])
  287. n.sons[1] = x
  288. if x.kind == nkIntLit and x.intVal != 0: incl(c.config.notes, nk)
  289. else: excl(c.config.notes, nk)
  290. else:
  291. invalidPragma(c, n)
  292. proc pragmaToOptions(w: TSpecialWord): TOptions {.inline.} =
  293. case w
  294. of wChecks: ChecksOptions
  295. of wObjChecks: {optObjCheck}
  296. of wFieldChecks: {optFieldCheck}
  297. of wRangechecks: {optRangeCheck}
  298. of wBoundchecks: {optBoundsCheck}
  299. of wOverflowchecks: {optOverflowCheck}
  300. of wNilchecks: {optNilCheck}
  301. of wFloatchecks: {optNaNCheck, optInfCheck}
  302. of wNanChecks: {optNaNCheck}
  303. of wInfChecks: {optInfCheck}
  304. of wMovechecks: {optMoveCheck}
  305. of wAssertions: {optAssert}
  306. of wWarnings: {optWarns}
  307. of wHints: {optHints}
  308. of wLinedir: {optLineDir}
  309. of wStacktrace: {optStackTrace}
  310. of wLinetrace: {optLineTrace}
  311. of wDebugger: {optEndb}
  312. of wProfiler: {optProfiler, optMemTracker}
  313. of wMemTracker: {optMemTracker}
  314. of wByRef: {optByRef}
  315. of wImplicitStatic: {optImplicitStatic}
  316. of wPatterns: {optPatterns}
  317. else: {}
  318. proc processExperimental(c: PContext; n: PNode) =
  319. if n.kind notin nkPragmaCallKinds or n.len != 2:
  320. c.features.incl oldExperimentalFeatures
  321. else:
  322. n[1] = c.semConstExpr(c, n[1])
  323. case n[1].kind
  324. of nkStrLit, nkRStrLit, nkTripleStrLit:
  325. try:
  326. let feature = parseEnum[Feature](n[1].strVal)
  327. c.features.incl feature
  328. if feature == codeReordering:
  329. if not isTopLevel(c):
  330. localError(c.config, n.info,
  331. "Code reordering experimental pragma only valid at toplevel")
  332. c.module.flags.incl sfReorder
  333. except ValueError:
  334. localError(c.config, n[1].info, "unknown experimental feature")
  335. else:
  336. localError(c.config, n.info, errStringLiteralExpected)
  337. proc tryProcessOption(c: PContext, n: PNode, resOptions: var TOptions): bool =
  338. result = true
  339. if n.kind notin nkPragmaCallKinds or n.len != 2: result = false
  340. elif n.sons[0].kind == nkBracketExpr: processNote(c, n)
  341. elif n.sons[0].kind != nkIdent: result = false
  342. else:
  343. let sw = whichKeyword(n.sons[0].ident)
  344. if sw == wExperimental:
  345. processExperimental(c, n)
  346. return true
  347. let opts = pragmaToOptions(sw)
  348. if opts != {}:
  349. onOff(c, n, opts, resOptions)
  350. else:
  351. case sw
  352. of wCallconv: processCallConv(c, n)
  353. of wDynlib: processDynLib(c, n, nil)
  354. of wOptimization:
  355. if n.sons[1].kind != nkIdent:
  356. invalidPragma(c, n)
  357. else:
  358. case n.sons[1].ident.s.normalize
  359. of "speed":
  360. incl(resOptions, optOptimizeSpeed)
  361. excl(resOptions, optOptimizeSize)
  362. of "size":
  363. excl(resOptions, optOptimizeSpeed)
  364. incl(resOptions, optOptimizeSize)
  365. of "none":
  366. excl(resOptions, optOptimizeSpeed)
  367. excl(resOptions, optOptimizeSize)
  368. else: localError(c.config, n.info, "'none', 'speed' or 'size' expected")
  369. else: result = false
  370. proc processOption(c: PContext, n: PNode, resOptions: var TOptions) =
  371. if not tryProcessOption(c, n, resOptions):
  372. # calling conventions (boring...):
  373. localError(c.config, n.info, "option expected")
  374. proc processPush(c: PContext, n: PNode, start: int) =
  375. if n.sons[start-1].kind in nkPragmaCallKinds:
  376. localError(c.config, n.info, "'push' cannot have arguments")
  377. var x = newOptionEntry(c.config)
  378. var y = c.optionStack[^1]
  379. x.options = c.config.options
  380. x.defaultCC = y.defaultCC
  381. x.dynlib = y.dynlib
  382. x.notes = c.config.notes
  383. x.features = c.features
  384. c.optionStack.add(x)
  385. for i in countup(start, sonsLen(n) - 1):
  386. if not tryProcessOption(c, n.sons[i], c.config.options):
  387. # simply store it somewhere:
  388. if x.otherPragmas.isNil:
  389. x.otherPragmas = newNodeI(nkPragma, n.info)
  390. x.otherPragmas.add n.sons[i]
  391. #localError(c.config, n.info, errOptionExpected)
  392. # If stacktrace is disabled globally we should not enable it
  393. if optStackTrace notin c.optionStack[0].options:
  394. c.config.options.excl(optStackTrace)
  395. proc processPop(c: PContext, n: PNode) =
  396. if c.optionStack.len <= 1:
  397. localError(c.config, n.info, "{.pop.} without a corresponding {.push.}")
  398. else:
  399. c.config.options = c.optionStack[^1].options
  400. c.config.notes = c.optionStack[^1].notes
  401. c.features = c.optionStack[^1].features
  402. c.optionStack.setLen(c.optionStack.len - 1)
  403. proc processDefine(c: PContext, n: PNode) =
  404. if (n.kind in nkPragmaCallKinds and n.len == 2) and (n[1].kind == nkIdent):
  405. defineSymbol(c.config.symbols, n[1].ident.s)
  406. message(c.config, n.info, warnDeprecated, "define")
  407. else:
  408. invalidPragma(c, n)
  409. proc processUndef(c: PContext, n: PNode) =
  410. if (n.kind in nkPragmaCallKinds and n.len == 2) and (n[1].kind == nkIdent):
  411. undefSymbol(c.config.symbols, n[1].ident.s)
  412. message(c.config, n.info, warnDeprecated, "undef")
  413. else:
  414. invalidPragma(c, n)
  415. proc relativeFile(c: PContext; n: PNode; ext=""): AbsoluteFile =
  416. var s = expectStrLit(c, n)
  417. if ext.len > 0 and splitFile(s).ext == "":
  418. s = addFileExt(s, ext)
  419. result = AbsoluteFile parentDir(toFullPath(c.config, n.info)) / s
  420. if not fileExists(result):
  421. if isAbsolute(s): result = AbsoluteFile s
  422. else:
  423. result = findFile(c.config, s)
  424. if result.isEmpty: result = AbsoluteFile s
  425. proc processCompile(c: PContext, n: PNode) =
  426. proc docompile(c: PContext; it: PNode; src, dest: AbsoluteFile) =
  427. var cf = Cfile(cname: src, obj: dest, flags: {CfileFlag.External})
  428. extccomp.addExternalFileToCompile(c.config, cf)
  429. recordPragma(c, it, "compile", src.string, dest.string)
  430. proc getStrLit(c: PContext, n: PNode; i: int): string =
  431. n.sons[i] = c.semConstExpr(c, n[i])
  432. case n[i].kind
  433. of nkStrLit, nkRStrLit, nkTripleStrLit:
  434. shallowCopy(result, n[i].strVal)
  435. else:
  436. localError(c.config, n.info, errStringLiteralExpected)
  437. result = ""
  438. let it = if n.kind in nkPragmaCallKinds and n.len == 2: n.sons[1] else: n
  439. if it.kind in {nkPar, nkTupleConstr} and it.len == 2:
  440. let s = getStrLit(c, it, 0)
  441. let dest = getStrLit(c, it, 1)
  442. var found = parentDir(toFullPath(c.config, n.info)) / s
  443. for f in os.walkFiles(found):
  444. let obj = completeCFilePath(c.config, AbsoluteFile(dest % extractFilename(f)))
  445. docompile(c, it, AbsoluteFile f, obj)
  446. else:
  447. let s = expectStrLit(c, n)
  448. var found = AbsoluteFile(parentDir(toFullPath(c.config, n.info)) / s)
  449. if not fileExists(found):
  450. if isAbsolute(s): found = AbsoluteFile s
  451. else:
  452. found = findFile(c.config, s)
  453. if found.isEmpty: found = AbsoluteFile s
  454. let obj = toObjFile(c.config, completeCFilePath(c.config, found, false))
  455. docompile(c, it, found, obj)
  456. proc processLink(c: PContext, n: PNode) =
  457. let found = relativeFile(c, n, CC[c.config.cCompiler].objExt)
  458. extccomp.addExternalFileToLink(c.config, found)
  459. recordPragma(c, n, "link", found.string)
  460. proc pragmaBreakpoint(c: PContext, n: PNode) =
  461. discard getOptionalStr(c, n, "")
  462. proc pragmaWatchpoint(c: PContext, n: PNode) =
  463. if n.kind in nkPragmaCallKinds and n.len == 2:
  464. n.sons[1] = c.semExpr(c, n.sons[1])
  465. else:
  466. invalidPragma(c, n)
  467. proc semAsmOrEmit*(con: PContext, n: PNode, marker: char): PNode =
  468. case n.sons[1].kind
  469. of nkStrLit, nkRStrLit, nkTripleStrLit:
  470. result = newNode(if n.kind == nkAsmStmt: nkAsmStmt else: nkArgList, n.info)
  471. var str = n.sons[1].strVal
  472. if str == "":
  473. localError(con.config, n.info, "empty 'asm' statement")
  474. return
  475. # now parse the string literal and substitute symbols:
  476. var a = 0
  477. while true:
  478. var b = strutils.find(str, marker, a)
  479. var sub = if b < 0: substr(str, a) else: substr(str, a, b - 1)
  480. if sub != "": addSon(result, newStrNode(nkStrLit, sub))
  481. if b < 0: break
  482. var c = strutils.find(str, marker, b + 1)
  483. if c < 0: sub = substr(str, b + 1)
  484. else: sub = substr(str, b + 1, c - 1)
  485. if sub != "":
  486. var e = searchInScopes(con, getIdent(con.cache, sub))
  487. if e != nil:
  488. when false:
  489. if e.kind == skStub: loadStub(e)
  490. incl(e.flags, sfUsed)
  491. addSon(result, newSymNode(e))
  492. else:
  493. addSon(result, newStrNode(nkStrLit, sub))
  494. else:
  495. # an empty '``' produces a single '`'
  496. addSon(result, newStrNode(nkStrLit, $marker))
  497. if c < 0: break
  498. a = c + 1
  499. else:
  500. illFormedAstLocal(n, con.config)
  501. result = newNode(nkAsmStmt, n.info)
  502. proc pragmaEmit(c: PContext, n: PNode) =
  503. if n.kind notin nkPragmaCallKinds or n.len != 2:
  504. localError(c.config, n.info, errStringLiteralExpected)
  505. else:
  506. let n1 = n[1]
  507. if n1.kind == nkBracket:
  508. var b = newNodeI(nkBracket, n1.info, n1.len)
  509. for i in 0..<n1.len:
  510. b.sons[i] = c.semExpr(c, n1[i])
  511. n.sons[1] = b
  512. else:
  513. n.sons[1] = c.semConstExpr(c, n1)
  514. case n.sons[1].kind
  515. of nkStrLit, nkRStrLit, nkTripleStrLit:
  516. n.sons[1] = semAsmOrEmit(c, n, '`')
  517. else:
  518. localError(c.config, n.info, errStringLiteralExpected)
  519. proc noVal(c: PContext; n: PNode) =
  520. if n.kind in nkPragmaCallKinds and n.len > 1: invalidPragma(c, n)
  521. proc pragmaUnroll(c: PContext, n: PNode) =
  522. if c.p.nestedLoopCounter <= 0:
  523. invalidPragma(c, n)
  524. elif n.kind in nkPragmaCallKinds and n.len == 2:
  525. var unrollFactor = expectIntLit(c, n)
  526. if unrollFactor <% 32:
  527. n.sons[1] = newIntNode(nkIntLit, unrollFactor)
  528. else:
  529. invalidPragma(c, n)
  530. proc pragmaLine(c: PContext, n: PNode) =
  531. if n.kind in nkPragmaCallKinds and n.len == 2:
  532. n.sons[1] = c.semConstExpr(c, n.sons[1])
  533. let a = n.sons[1]
  534. if a.kind in {nkPar, nkTupleConstr}:
  535. # unpack the tuple
  536. var x = a.sons[0]
  537. var y = a.sons[1]
  538. if x.kind == nkExprColonExpr: x = x.sons[1]
  539. if y.kind == nkExprColonExpr: y = y.sons[1]
  540. if x.kind != nkStrLit:
  541. localError(c.config, n.info, errStringLiteralExpected)
  542. elif y.kind != nkIntLit:
  543. localError(c.config, n.info, errIntLiteralExpected)
  544. else:
  545. n.info.fileIndex = fileInfoIdx(c.config, AbsoluteFile(x.strVal))
  546. n.info.line = uint16(y.intVal)
  547. else:
  548. localError(c.config, n.info, "tuple expected")
  549. else:
  550. # sensible default:
  551. n.info = getInfoContext(c.config, -1)
  552. proc processPragma(c: PContext, n: PNode, i: int) =
  553. let it = n[i]
  554. if it.kind notin nkPragmaCallKinds and it.len == 2: invalidPragma(c, n)
  555. elif it[0].kind != nkIdent: invalidPragma(c, n)
  556. elif it[1].kind != nkIdent: invalidPragma(c, n)
  557. var userPragma = newSym(skTemplate, it[1].ident, nil, it.info, c.config.options)
  558. userPragma.ast = newNode(nkPragma, n.info, n.sons[i+1..^1])
  559. strTableAdd(c.userPragmas, userPragma)
  560. proc pragmaRaisesOrTags(c: PContext, n: PNode) =
  561. proc processExc(c: PContext, x: PNode) =
  562. var t = skipTypes(c.semTypeNode(c, x, nil), skipPtrs)
  563. if t.kind != tyObject:
  564. localError(c.config, x.info, errGenerated, "invalid type for raises/tags list")
  565. x.typ = t
  566. if n.kind in nkPragmaCallKinds and n.len == 2:
  567. let it = n.sons[1]
  568. if it.kind notin {nkCurly, nkBracket}:
  569. processExc(c, it)
  570. else:
  571. for e in items(it): processExc(c, e)
  572. else:
  573. invalidPragma(c, n)
  574. proc pragmaLockStmt(c: PContext; it: PNode) =
  575. if it.kind notin nkPragmaCallKinds or it.len != 2:
  576. invalidPragma(c, it)
  577. else:
  578. let n = it[1]
  579. if n.kind != nkBracket:
  580. localError(c.config, n.info, errGenerated, "locks pragma takes a list of expressions")
  581. else:
  582. for i in 0 ..< n.len:
  583. n.sons[i] = c.semExpr(c, n.sons[i])
  584. proc pragmaLocks(c: PContext, it: PNode): TLockLevel =
  585. if it.kind notin nkPragmaCallKinds or it.len != 2:
  586. invalidPragma(c, it)
  587. else:
  588. case it[1].kind
  589. of nkStrLit, nkRStrLit, nkTripleStrLit:
  590. if it[1].strVal == "unknown":
  591. result = UnknownLockLevel
  592. else:
  593. localError(c.config, it[1].info, "invalid string literal for locks pragma (only allowed string is \"unknown\")")
  594. else:
  595. let x = expectIntLit(c, it)
  596. if x < 0 or x > MaxLockLevel:
  597. localError(c.config, it[1].info, "integer must be within 0.." & $MaxLockLevel)
  598. else:
  599. result = TLockLevel(x)
  600. proc typeBorrow(c: PContext; sym: PSym, n: PNode) =
  601. if n.kind in nkPragmaCallKinds and n.len == 2:
  602. let it = n.sons[1]
  603. if it.kind != nkAccQuoted:
  604. localError(c.config, n.info, "a type can only borrow `.` for now")
  605. incl(sym.typ.flags, tfBorrowDot)
  606. proc markCompilerProc(c: PContext; s: PSym) =
  607. # minor hack ahead: FlowVar is the only generic .compilerProc type which
  608. # should not have an external name set:
  609. if s.kind != skType or s.name.s != "FlowVar":
  610. makeExternExport(c, s, "$1", s.info)
  611. incl(s.flags, sfCompilerProc)
  612. incl(s.flags, sfUsed)
  613. registerCompilerProc(c.graph, s)
  614. proc deprecatedStmt(c: PContext; outerPragma: PNode) =
  615. let pragma = outerPragma[1]
  616. if pragma.kind in {nkStrLit..nkTripleStrLit}:
  617. incl(c.module.flags, sfDeprecated)
  618. c.module.constraint = getStrLitNode(c, outerPragma)
  619. return
  620. if pragma.kind != nkBracket:
  621. localError(c.config, pragma.info, "list of key:value pairs expected"); return
  622. for n in pragma:
  623. if n.kind in nkPragmaCallKinds and n.len == 2:
  624. let dest = qualifiedLookUp(c, n[1], {checkUndeclared})
  625. if dest == nil or dest.kind in routineKinds:
  626. localError(c.config, n.info, warnUser, "the .deprecated pragma is unreliable for routines")
  627. let src = considerQuotedIdent(c, n[0])
  628. let alias = newSym(skAlias, src, dest, n[0].info, c.config.options)
  629. incl(alias.flags, sfExported)
  630. if sfCompilerProc in dest.flags: markCompilerProc(c, alias)
  631. addInterfaceDecl(c, alias)
  632. n.sons[1] = newSymNode(dest)
  633. else:
  634. localError(c.config, n.info, "key:value pair expected")
  635. proc pragmaGuard(c: PContext; it: PNode; kind: TSymKind): PSym =
  636. if it.kind notin nkPragmaCallKinds or it.len != 2:
  637. invalidPragma(c, it); return
  638. let n = it[1]
  639. if n.kind == nkSym:
  640. result = n.sym
  641. elif kind == skField:
  642. # First check if the guard is a global variable:
  643. result = qualifiedLookUp(c, n, {})
  644. if result.isNil or result.kind notin {skLet, skVar} or
  645. sfGlobal notin result.flags:
  646. # We return a dummy symbol; later passes over the type will repair it.
  647. # Generic instantiation needs to know about this too. But we're lazy
  648. # and perform the lookup on demand instead.
  649. result = newSym(skUnknown, considerQuotedIdent(c, n), nil, n.info,
  650. c.config.options)
  651. else:
  652. result = qualifiedLookUp(c, n, {checkUndeclared})
  653. proc semCustomPragma(c: PContext, n: PNode): PNode =
  654. if n.kind == nkIdent:
  655. result = newTree(nkCall, n)
  656. elif n.kind == nkExprColonExpr:
  657. # pragma: arg -> pragma(arg)
  658. result = newTree(nkCall, n[0], n[1])
  659. elif n.kind in nkPragmaCallKinds:
  660. result = n
  661. else:
  662. invalidPragma(c, n)
  663. return n
  664. let r = c.semOverloadedCall(c, result, n, {skTemplate}, {efNoUndeclared})
  665. if r.isNil or sfCustomPragma notin r[0].sym.flags:
  666. invalidPragma(c, n)
  667. else:
  668. result = r
  669. if n.kind == nkIdent:
  670. result = result[0]
  671. elif n.kind == nkExprColonExpr:
  672. result.kind = n.kind # pragma(arg) -> pragma: arg
  673. proc singlePragma(c: PContext, sym: PSym, n: PNode, i: var int,
  674. validPragmas: TSpecialWords): bool =
  675. var it = n.sons[i]
  676. var key = if it.kind in nkPragmaCallKinds and it.len > 1: it.sons[0] else: it
  677. if key.kind == nkBracketExpr:
  678. processNote(c, it)
  679. return
  680. elif key.kind notin nkIdentKinds:
  681. n.sons[i] = semCustomPragma(c, it)
  682. return
  683. let ident = considerQuotedIdent(c, key)
  684. var userPragma = strTableGet(c.userPragmas, ident)
  685. if userPragma != nil:
  686. # number of pragmas increase/decrease with user pragma expansion
  687. inc c.instCounter
  688. if c.instCounter > 100:
  689. globalError(c.config, it.info, "recursive dependency: " & userPragma.name.s)
  690. pragma(c, sym, userPragma.ast, validPragmas)
  691. n.sons[i..i] = userPragma.ast.sons # expand user pragma with its content
  692. i.inc(userPragma.ast.len - 1) # inc by -1 is ok, user pragmas was empty
  693. dec c.instCounter
  694. else:
  695. let k = whichKeyword(ident)
  696. if k in validPragmas:
  697. case k
  698. of wExportc:
  699. makeExternExport(c, sym, getOptionalStr(c, it, "$1"), it.info)
  700. incl(sym.flags, sfUsed) # avoid wrong hints
  701. of wImportc:
  702. let name = getOptionalStr(c, it, "$1")
  703. cppDefine(c.config, name)
  704. recordPragma(c, it, "cppdefine", name)
  705. makeExternImport(c, sym, name, it.info)
  706. of wImportCompilerProc:
  707. let name = getOptionalStr(c, it, "$1")
  708. cppDefine(c.config, name)
  709. recordPragma(c, it, "cppdefine", name)
  710. processImportCompilerProc(c, sym, name, it.info)
  711. of wExtern: setExternName(c, sym, expectStrLit(c, it), it.info)
  712. of wImmediate:
  713. if sym.kind in {skTemplate, skMacro}:
  714. incl(sym.flags, sfImmediate)
  715. incl(sym.flags, sfAllUntyped)
  716. message(c.config, n.info, warnDeprecated, "use 'untyped' parameters instead; immediate")
  717. else: invalidPragma(c, it)
  718. of wDirty:
  719. if sym.kind == skTemplate: incl(sym.flags, sfDirty)
  720. else: invalidPragma(c, it)
  721. of wImportCpp:
  722. processImportCpp(c, sym, getOptionalStr(c, it, "$1"), it.info)
  723. of wImportObjC:
  724. processImportObjC(c, sym, getOptionalStr(c, it, "$1"), it.info)
  725. of wAlign:
  726. if sym.typ == nil: invalidPragma(c, it)
  727. var align = expectIntLit(c, it)
  728. if (not isPowerOfTwo(align) and align != 0) or align >% high(int16):
  729. localError(c.config, it.info, "power of two expected")
  730. else:
  731. sym.typ.align = align.int16
  732. of wSize:
  733. if sym.typ == nil: invalidPragma(c, it)
  734. var size = expectIntLit(c, it)
  735. if not isPowerOfTwo(size) or size <= 0 or size > 8:
  736. localError(c.config, it.info, "size may only be 1, 2, 4 or 8")
  737. else:
  738. sym.typ.size = size
  739. # TODO, this is not correct
  740. sym.typ.align = int16(size)
  741. of wNodecl:
  742. noVal(c, it)
  743. incl(sym.loc.flags, lfNoDecl)
  744. of wPure, wAsmNoStackFrame:
  745. noVal(c, it)
  746. if sym != nil:
  747. if k == wPure and sym.kind in routineKinds: invalidPragma(c, it)
  748. else: incl(sym.flags, sfPure)
  749. of wVolatile:
  750. noVal(c, it)
  751. incl(sym.flags, sfVolatile)
  752. of wRegister:
  753. noVal(c, it)
  754. incl(sym.flags, sfRegister)
  755. of wThreadVar:
  756. noVal(c, it)
  757. incl(sym.flags, {sfThread, sfGlobal})
  758. of wDeadCodeElimUnused: discard # deprecated, dead code elim always on
  759. of wNoForward: pragmaNoForward(c, it)
  760. of wReorder: pragmaNoForward(c, it, flag = sfReorder)
  761. of wMagic: processMagic(c, it, sym)
  762. of wCompileTime:
  763. noVal(c, it)
  764. incl(sym.flags, sfCompileTime)
  765. incl(sym.loc.flags, lfNoDecl)
  766. of wGlobal:
  767. noVal(c, it)
  768. incl(sym.flags, sfGlobal)
  769. incl(sym.flags, sfPure)
  770. of wMerge:
  771. # only supported for backwards compat, doesn't do anything anymore
  772. noVal(c, it)
  773. of wConstructor:
  774. noVal(c, it)
  775. incl(sym.flags, sfConstructor)
  776. of wHeader:
  777. var lib = getLib(c, libHeader, getStrLitNode(c, it))
  778. addToLib(lib, sym)
  779. incl(sym.flags, sfImportc)
  780. incl(sym.loc.flags, lfHeader)
  781. incl(sym.loc.flags, lfNoDecl)
  782. # implies nodecl, because otherwise header would not make sense
  783. if sym.loc.r == nil: sym.loc.r = rope(sym.name.s)
  784. of wOverride:
  785. sym.flags.incl sfOverriden
  786. of wNosideeffect:
  787. noVal(c, it)
  788. incl(sym.flags, sfNoSideEffect)
  789. if sym.typ != nil: incl(sym.typ.flags, tfNoSideEffect)
  790. of wSideeffect:
  791. noVal(c, it)
  792. incl(sym.flags, sfSideEffect)
  793. of wNoreturn:
  794. noVal(c, it)
  795. incl(sym.flags, sfNoReturn)
  796. if sym.typ[0] != nil:
  797. localError(c.config, sym.ast[paramsPos][0].info,
  798. ".noreturn with return type not allowed")
  799. of wDynlib:
  800. processDynLib(c, it, sym)
  801. of wCompilerProc, wCore:
  802. noVal(c, it) # compilerproc may not get a string!
  803. cppDefine(c.graph.config, sym.name.s)
  804. recordPragma(c, it, "cppdefine", sym.name.s)
  805. if sfFromGeneric notin sym.flags: markCompilerProc(c, sym)
  806. of wProcVar:
  807. noVal(c, it)
  808. incl(sym.flags, sfProcvar)
  809. of wExplain:
  810. sym.flags.incl sfExplain
  811. of wDeprecated:
  812. if sym != nil and sym.kind in routineKinds + {skType}:
  813. if it.kind in nkPragmaCallKinds: discard getStrLitNode(c, it)
  814. incl(sym.flags, sfDeprecated)
  815. elif sym != nil and sym.kind != skModule:
  816. # We don't support the extra annotation field
  817. if it.kind in nkPragmaCallKinds:
  818. localError(c.config, it.info, "annotation to deprecated not supported here")
  819. incl(sym.flags, sfDeprecated)
  820. # At this point we're quite sure this is a statement and applies to the
  821. # whole module
  822. elif it.kind in nkPragmaCallKinds: deprecatedStmt(c, it)
  823. else: incl(c.module.flags, sfDeprecated)
  824. of wVarargs:
  825. noVal(c, it)
  826. if sym.typ == nil: invalidPragma(c, it)
  827. else: incl(sym.typ.flags, tfVarargs)
  828. of wBorrow:
  829. if sym.kind == skType:
  830. typeBorrow(c, sym, it)
  831. else:
  832. noVal(c, it)
  833. incl(sym.flags, sfBorrow)
  834. of wFinal:
  835. noVal(c, it)
  836. if sym.typ == nil: invalidPragma(c, it)
  837. else: incl(sym.typ.flags, tfFinal)
  838. of wInheritable:
  839. noVal(c, it)
  840. if sym.typ == nil or tfFinal in sym.typ.flags: invalidPragma(c, it)
  841. else: incl(sym.typ.flags, tfInheritable)
  842. of wPackage:
  843. noVal(c, it)
  844. if sym.typ == nil: invalidPragma(c, it)
  845. else: incl(sym.flags, sfForward)
  846. of wAcyclic:
  847. noVal(c, it)
  848. if sym.typ == nil: invalidPragma(c, it)
  849. else: incl(sym.typ.flags, tfAcyclic)
  850. of wShallow:
  851. noVal(c, it)
  852. if sym.typ == nil: invalidPragma(c, it)
  853. else: incl(sym.typ.flags, tfShallow)
  854. of wThread:
  855. noVal(c, it)
  856. incl(sym.flags, sfThread)
  857. incl(sym.flags, sfProcvar)
  858. if sym.typ != nil:
  859. incl(sym.typ.flags, tfThread)
  860. if sym.typ.callConv == ccClosure: sym.typ.callConv = ccDefault
  861. of wGcSafe:
  862. noVal(c, it)
  863. if sym != nil:
  864. if sym.kind != skType: incl(sym.flags, sfThread)
  865. if sym.typ != nil: incl(sym.typ.flags, tfGcSafe)
  866. else: invalidPragma(c, it)
  867. else:
  868. discard "no checking if used as a code block"
  869. of wPacked:
  870. noVal(c, it)
  871. if sym.typ == nil: invalidPragma(c, it)
  872. else: incl(sym.typ.flags, tfPacked)
  873. of wHint:
  874. let s = expectStrLit(c, it)
  875. recordPragma(c, it, "hint", s)
  876. message(c.config, it.info, hintUser, s)
  877. of wWarning:
  878. let s = expectStrLit(c, it)
  879. recordPragma(c, it, "warning", s)
  880. message(c.config, it.info, warnUser, s)
  881. of wError:
  882. if sym != nil and (sym.isRoutine or sym.kind == skType) and wUsed in validPragmas:
  883. # This is subtle but correct: the error *statement* is only
  884. # allowed when 'wUsed' is not in validPragmas. Here this is the easiest way to
  885. # distinguish properly between
  886. # ``proc p() {.error}`` and ``proc p() = {.error: "msg".}``
  887. if it.kind in nkPragmaCallKinds: discard getStrLitNode(c, it)
  888. incl(sym.flags, sfError)
  889. excl(sym.flags, sfForward)
  890. else:
  891. let s = expectStrLit(c, it)
  892. recordPragma(c, it, "error", s)
  893. localError(c.config, it.info, errUser, s)
  894. of wFatal: fatal(c.config, it.info, errUser, expectStrLit(c, it))
  895. of wDefine: processDefine(c, it)
  896. of wUndef: processUndef(c, it)
  897. of wCompile: processCompile(c, it)
  898. of wLink: processLink(c, it)
  899. of wPassl:
  900. let s = expectStrLit(c, it)
  901. extccomp.addLinkOption(c.config, s)
  902. recordPragma(c, it, "passl", s)
  903. of wPassc:
  904. let s = expectStrLit(c, it)
  905. extccomp.addCompileOption(c.config, s)
  906. recordPragma(c, it, "passc", s)
  907. of wBreakpoint: pragmaBreakpoint(c, it)
  908. of wWatchPoint: pragmaWatchpoint(c, it)
  909. of wPush:
  910. processPush(c, n, i + 1)
  911. result = true
  912. of wPop: processPop(c, it)
  913. of wPragma:
  914. if not sym.isNil and sym.kind == skTemplate:
  915. sym.flags.incl sfCustomPragma
  916. else:
  917. processPragma(c, n, i)
  918. result = true
  919. of wDiscardable:
  920. noVal(c, it)
  921. if sym != nil: incl(sym.flags, sfDiscardable)
  922. of wNoInit:
  923. noVal(c, it)
  924. if sym != nil: incl(sym.flags, sfNoInit)
  925. of wCodegenDecl: processCodegenDecl(c, it, sym)
  926. of wChecks, wObjChecks, wFieldChecks, wRangechecks, wBoundchecks,
  927. wOverflowchecks, wNilchecks, wAssertions, wWarnings, wHints,
  928. wLinedir, wOptimization, wMovechecks, wCallconv, wDebugger, wProfiler,
  929. wFloatchecks, wNanChecks, wInfChecks, wPatterns:
  930. processOption(c, it, c.config.options)
  931. of wStacktrace, wLinetrace:
  932. if sym.kind in {skProc, skMethod, skConverter}:
  933. processOption(c, it, sym.options)
  934. else:
  935. processOption(c, it, c.config.options)
  936. of FirstCallConv..LastCallConv:
  937. assert(sym != nil)
  938. if sym.typ == nil: invalidPragma(c, it)
  939. else: sym.typ.callConv = wordToCallConv(k)
  940. of wEmit: pragmaEmit(c, it)
  941. of wUnroll: pragmaUnroll(c, it)
  942. of wLinearScanEnd, wComputedGoto: noVal(c, it)
  943. of wEffects:
  944. # is later processed in effect analysis:
  945. noVal(c, it)
  946. of wIncompleteStruct:
  947. noVal(c, it)
  948. if sym.typ == nil: invalidPragma(c, it)
  949. else: incl(sym.typ.flags, tfIncompleteStruct)
  950. of wUnchecked:
  951. noVal(c, it)
  952. if sym.typ == nil: invalidPragma(c, it)
  953. else: incl(sym.typ.flags, tfUncheckedArray)
  954. of wUnion:
  955. noVal(c, it)
  956. if sym.typ == nil: invalidPragma(c, it)
  957. else: incl(sym.typ.flags, tfUnion)
  958. of wRequiresInit:
  959. noVal(c, it)
  960. if sym.typ == nil: invalidPragma(c, it)
  961. else: incl(sym.typ.flags, tfNeedsInit)
  962. of wByRef:
  963. noVal(c, it)
  964. if sym == nil or sym.typ == nil:
  965. processOption(c, it, c.config.options)
  966. else:
  967. incl(sym.typ.flags, tfByRef)
  968. of wByCopy:
  969. noVal(c, it)
  970. if sym.kind != skType or sym.typ == nil: invalidPragma(c, it)
  971. else: incl(sym.typ.flags, tfByCopy)
  972. of wPartial:
  973. noVal(c, it)
  974. if sym.kind != skType or sym.typ == nil: invalidPragma(c, it)
  975. else:
  976. incl(sym.typ.flags, tfPartial)
  977. of wInject, wGensym:
  978. # We check for errors, but do nothing with these pragmas otherwise
  979. # as they are handled directly in 'evalTemplate'.
  980. noVal(c, it)
  981. if sym == nil: invalidPragma(c, it)
  982. of wLine: pragmaLine(c, it)
  983. of wRaises, wTags: pragmaRaisesOrTags(c, it)
  984. of wLocks:
  985. if sym == nil: pragmaLockStmt(c, it)
  986. elif sym.typ == nil: invalidPragma(c, it)
  987. else: sym.typ.lockLevel = pragmaLocks(c, it)
  988. of wBitsize:
  989. if sym == nil or sym.kind != skField:
  990. invalidPragma(c, it)
  991. else:
  992. sym.bitsize = expectIntLit(c, it)
  993. of wGuard:
  994. if sym == nil or sym.kind notin {skVar, skLet, skField}:
  995. invalidPragma(c, it)
  996. else:
  997. sym.guard = pragmaGuard(c, it, sym.kind)
  998. of wGoto:
  999. if sym == nil or sym.kind notin {skVar, skLet}:
  1000. invalidPragma(c, it)
  1001. else:
  1002. sym.flags.incl sfGoto
  1003. of wExportNims:
  1004. if sym == nil: invalidPragma(c, it)
  1005. else: magicsys.registerNimScriptSymbol(c.graph, sym)
  1006. of wInjectStmt:
  1007. if it.kind notin nkPragmaCallKinds or it.len != 2:
  1008. localError(c.config, it.info, "expression expected")
  1009. else:
  1010. it.sons[1] = c.semExpr(c, it.sons[1])
  1011. of wExperimental:
  1012. if not isTopLevel(c):
  1013. localError(c.config, n.info, "'experimental' pragma only valid as toplevel statement or in a 'push' environment")
  1014. processExperimental(c, it)
  1015. of wThis:
  1016. if it.kind in nkPragmaCallKinds and it.len == 2:
  1017. c.selfName = considerQuotedIdent(c, it[1])
  1018. message(c.config, n.info, warnDeprecated, "the '.this' pragma")
  1019. elif it.kind == nkIdent or it.len == 1:
  1020. c.selfName = getIdent(c.cache, "self")
  1021. message(c.config, n.info, warnDeprecated, "the '.this' pragma")
  1022. else:
  1023. localError(c.config, it.info, "'this' pragma is allowed to have zero or one arguments")
  1024. of wNoRewrite:
  1025. noVal(c, it)
  1026. of wBase:
  1027. noVal(c, it)
  1028. sym.flags.incl sfBase
  1029. of wIntDefine:
  1030. sym.magic = mIntDefine
  1031. of wStrDefine:
  1032. sym.magic = mStrDefine
  1033. of wUsed:
  1034. noVal(c, it)
  1035. if sym == nil: invalidPragma(c, it)
  1036. else: sym.flags.incl sfUsed
  1037. of wLiftLocals: discard
  1038. else: invalidPragma(c, it)
  1039. elif sym.kind in {skVar,skLet,skParam,skField,skProc,skFunc,skConverter,skMethod,skType}:
  1040. n.sons[i] = semCustomPragma(c, it)
  1041. else:
  1042. illegalCustomPragma(c, it, sym)
  1043. proc implicitPragmas*(c: PContext, sym: PSym, n: PNode,
  1044. validPragmas: TSpecialWords) =
  1045. if sym != nil and sym.kind != skModule:
  1046. for it in c.optionStack:
  1047. let o = it.otherPragmas
  1048. if not o.isNil:
  1049. pushInfoContext(c.config, n.info)
  1050. var i = 0
  1051. while i < o.len():
  1052. if singlePragma(c, sym, o, i, validPragmas):
  1053. internalError(c.config, n.info, "implicitPragmas")
  1054. inc i
  1055. popInfoContext(c.config)
  1056. if lfExportLib in sym.loc.flags and sfExportc notin sym.flags:
  1057. localError(c.config, n.info, ".dynlib requires .exportc")
  1058. var lib = c.optionStack[^1].dynlib
  1059. if {lfDynamicLib, lfHeader} * sym.loc.flags == {} and
  1060. sfImportc in sym.flags and lib != nil:
  1061. incl(sym.loc.flags, lfDynamicLib)
  1062. addToLib(lib, sym)
  1063. if sym.loc.r == nil: sym.loc.r = rope(sym.name.s)
  1064. proc hasPragma*(n: PNode, pragma: TSpecialWord): bool =
  1065. if n == nil: return false
  1066. for p in n:
  1067. var key = if p.kind in nkPragmaCallKinds and p.len > 1: p[0] else: p
  1068. if key.kind == nkIdent and whichKeyword(key.ident) == pragma:
  1069. return true
  1070. return false
  1071. proc pragmaRec(c: PContext, sym: PSym, n: PNode, validPragmas: TSpecialWords) =
  1072. if n == nil: return
  1073. var i = 0
  1074. while i < n.len:
  1075. if singlePragma(c, sym, n, i, validPragmas): break
  1076. inc i
  1077. proc pragma(c: PContext, sym: PSym, n: PNode, validPragmas: TSpecialWords) =
  1078. if n == nil: return
  1079. pragmaRec(c, sym, n, validPragmas)
  1080. implicitPragmas(c, sym, n, validPragmas)