filters.nim 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. #
  2. #
  3. # The Nim Compiler
  4. # (c) Copyright 2012 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. # This module implements Nim's simple filters and helpers for filters.
  10. import
  11. llstream, os, wordrecg, idents, strutils, ast, astalgo, msgs, options,
  12. renderer
  13. proc invalidPragma(n: PNode) =
  14. localError(n.info, errXNotAllowedHere, renderTree(n, {renderNoComments}))
  15. proc getArg(n: PNode, name: string, pos: int): PNode =
  16. result = nil
  17. if n.kind in {nkEmpty..nkNilLit}: return
  18. for i in countup(1, sonsLen(n) - 1):
  19. if n.sons[i].kind == nkExprEqExpr:
  20. if n.sons[i].sons[0].kind != nkIdent: invalidPragma(n)
  21. if cmpIgnoreStyle(n.sons[i].sons[0].ident.s, name) == 0:
  22. return n.sons[i].sons[1]
  23. elif i == pos:
  24. return n.sons[i]
  25. proc charArg*(n: PNode, name: string, pos: int, default: char): char =
  26. var x = getArg(n, name, pos)
  27. if x == nil: result = default
  28. elif x.kind == nkCharLit: result = chr(int(x.intVal))
  29. else: invalidPragma(n)
  30. proc strArg*(n: PNode, name: string, pos: int, default: string): string =
  31. var x = getArg(n, name, pos)
  32. if x == nil: result = default
  33. elif x.kind in {nkStrLit..nkTripleStrLit}: result = x.strVal
  34. else: invalidPragma(n)
  35. proc boolArg*(n: PNode, name: string, pos: int, default: bool): bool =
  36. var x = getArg(n, name, pos)
  37. if x == nil: result = default
  38. elif x.kind == nkIdent and cmpIgnoreStyle(x.ident.s, "true") == 0: result = true
  39. elif x.kind == nkIdent and cmpIgnoreStyle(x.ident.s, "false") == 0: result = false
  40. else: invalidPragma(n)
  41. proc filterStrip*(stdin: PLLStream, filename: string, call: PNode): PLLStream =
  42. var pattern = strArg(call, "startswith", 1, "")
  43. var leading = boolArg(call, "leading", 2, true)
  44. var trailing = boolArg(call, "trailing", 3, true)
  45. result = llStreamOpen("")
  46. var line = newStringOfCap(80)
  47. while llStreamReadLine(stdin, line):
  48. var stripped = strip(line, leading, trailing)
  49. if len(pattern) == 0 or startsWith(stripped, pattern):
  50. llStreamWriteln(result, stripped)
  51. else:
  52. llStreamWriteln(result, line)
  53. llStreamClose(stdin)
  54. proc filterReplace*(stdin: PLLStream, filename: string, call: PNode): PLLStream =
  55. var sub = strArg(call, "sub", 1, "")
  56. if len(sub) == 0: invalidPragma(call)
  57. var by = strArg(call, "by", 2, "")
  58. result = llStreamOpen("")
  59. var line = newStringOfCap(80)
  60. while llStreamReadLine(stdin, line):
  61. llStreamWriteln(result, replace(line, sub, by))
  62. llStreamClose(stdin)