nimpretty.nim 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. #
  2. #
  3. # The Nim Compiler
  4. # (c) Copyright 2017 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## Standard tool for pretty printing.
  10. when not defined(nimpretty):
  11. {.error: "This needs to be compiled with --define:nimPretty".}
  12. import ../compiler / [idents, llstream, ast, msgs, syntaxes, options, pathutils, layouter]
  13. import parseopt, strutils, os, sequtils
  14. const
  15. Version = "0.2"
  16. Usage = "nimpretty - Nim Pretty Printer Version " & Version & """
  17. (c) 2017 Andreas Rumpf
  18. Usage:
  19. nimpretty [options] nimfiles...
  20. Options:
  21. --out:file set the output file (default: overwrite the input file)
  22. --outDir:dir set the output dir (default: overwrite the input files)
  23. --indent:N[=0] set the number of spaces that is used for indentation
  24. --indent:0 means autodetection (default behaviour)
  25. --maxLineLen:N set the desired maximum line length (default: 80)
  26. --version show the version
  27. --help show this help
  28. """
  29. proc writeHelp() =
  30. stdout.write(Usage)
  31. stdout.flushFile()
  32. quit(0)
  33. proc writeVersion() =
  34. stdout.write(Version & "\n")
  35. stdout.flushFile()
  36. quit(0)
  37. type
  38. PrettyOptions* = object
  39. indWidth*: Natural
  40. maxLineLen*: Positive
  41. proc goodEnough(a, b: PNode): bool =
  42. if a.kind == b.kind and a.safeLen == b.safeLen:
  43. case a.kind
  44. of nkNone, nkEmpty, nkNilLit: result = true
  45. of nkIdent: result = a.ident.id == b.ident.id
  46. of nkSym: result = a.sym == b.sym
  47. of nkType: result = true
  48. of nkCharLit, nkIntLit..nkInt64Lit, nkUIntLit..nkUInt64Lit:
  49. result = a.intVal == b.intVal
  50. of nkFloatLit..nkFloat128Lit:
  51. result = a.floatVal == b.floatVal
  52. of nkStrLit, nkRStrLit, nkTripleStrLit:
  53. result = a.strVal == b.strVal
  54. else:
  55. for i in 0 ..< a.len:
  56. if not goodEnough(a[i], b[i]): return false
  57. return true
  58. elif a.kind == nkStmtList and a.len == 1:
  59. result = goodEnough(a[0], b)
  60. elif b.kind == nkStmtList and b.len == 1:
  61. result = goodEnough(a, b[0])
  62. else:
  63. result = false
  64. proc finalCheck(content: string; origAst: PNode): bool {.nimcall.} =
  65. var conf = newConfigRef()
  66. let oldErrors = conf.errorCounter
  67. var parser: Parser
  68. parser.em.indWidth = 2
  69. let fileIdx = fileInfoIdx(conf, AbsoluteFile "nimpretty_bug.nim")
  70. openParser(parser, fileIdx, llStreamOpen(content), newIdentCache(), conf)
  71. let newAst = parseAll(parser)
  72. closeParser(parser)
  73. result = conf.errorCounter == oldErrors # and goodEnough(newAst, origAst)
  74. proc prettyPrint*(infile, outfile: string, opt: PrettyOptions) =
  75. var conf = newConfigRef()
  76. let fileIdx = fileInfoIdx(conf, AbsoluteFile infile)
  77. let f = splitFile(outfile.expandTilde)
  78. conf.outFile = RelativeFile f.name & f.ext
  79. conf.outDir = toAbsoluteDir f.dir
  80. var parser: Parser
  81. parser.em.indWidth = opt.indWidth
  82. if setupParser(parser, fileIdx, newIdentCache(), conf):
  83. parser.em.maxLineLen = opt.maxLineLen
  84. let fullAst = parseAll(parser)
  85. closeParser(parser)
  86. when defined(nimpretty):
  87. closeEmitter(parser.em, fullAst, finalCheck)
  88. proc main =
  89. var outfile, outdir: string
  90. var infiles = newSeq[string]()
  91. var outfiles = newSeq[string]()
  92. var backup = false
  93. # when `on`, create a backup file of input in case
  94. # `prettyPrint` could overwrite it (note that the backup may happen even
  95. # if input is not actually overwritten, when nimpretty is a noop).
  96. # --backup was un-documented (rely on git instead).
  97. var opt = PrettyOptions(indWidth: 0, maxLineLen: 80)
  98. for kind, key, val in getopt():
  99. case kind
  100. of cmdArgument:
  101. if dirExists(key):
  102. for file in walkDirRec(key, skipSpecial = true):
  103. if file.endsWith(".nim") or file.endsWith(".nimble"):
  104. infiles.add(file)
  105. else:
  106. infiles.add(key.addFileExt(".nim"))
  107. of cmdLongOption, cmdShortOption:
  108. case normalize(key)
  109. of "help", "h": writeHelp()
  110. of "version", "v": writeVersion()
  111. of "backup": backup = parseBool(val)
  112. of "output", "o", "out": outfile = val
  113. of "outDir", "outdir": outdir = val
  114. of "indent": opt.indWidth = parseInt(val)
  115. of "maxlinelen": opt.maxLineLen = parseInt(val)
  116. else: writeHelp()
  117. of cmdEnd: assert(false) # cannot happen
  118. if infiles.len == 0:
  119. quit "[Error] no input file."
  120. if outfile.len != 0 and outdir.len != 0:
  121. quit "[Error] out and outDir cannot both be specified"
  122. if outfile.len == 0 and outdir.len == 0:
  123. outfiles = infiles
  124. elif outfile.len != 0 and infiles.len > 1:
  125. # Take the last file to maintain backwards compatibility
  126. let infile = infiles[^1]
  127. infiles = @[infile]
  128. outfiles = @[outfile]
  129. elif outfile.len != 0:
  130. outfiles = @[outfile]
  131. elif outdir.len != 0:
  132. outfiles = infiles.mapIt($(joinPath(outdir, it)))
  133. for (infile, outfile) in zip(infiles, outfiles):
  134. let (dir, _, _) = splitFile(outfile)
  135. createDir(dir)
  136. if not fileExists(outfile) or not sameFile(infile, outfile):
  137. backup = false # no backup needed since won't be over-written
  138. if backup:
  139. let infileBackup = infile & ".backup" # works with .nim or .nims
  140. echo "writing backup " & infile & " > " & infileBackup
  141. os.copyFile(source = infile, dest = infileBackup)
  142. prettyPrint(infile, outfile, opt)
  143. when isMainModule:
  144. main()