pragmas.nim 49 KB

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