linter.nim 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  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 the style checker.
  10. import
  11. strutils, os, intsets, strtabs
  12. import options, ast, astalgo, msgs, semdata, ropes, idents,
  13. lineinfos, pathutils
  14. const
  15. Letters* = {'a'..'z', 'A'..'Z', '0'..'9', '\x80'..'\xFF', '_'}
  16. proc identLen*(line: string, start: int): int =
  17. while start+result < line.len and line[start+result] in Letters:
  18. inc result
  19. type
  20. StyleCheck* {.pure.} = enum None, Warn, Auto
  21. var
  22. gOverWrite* = true
  23. gStyleCheck*: StyleCheck
  24. gCheckExtern*, gOnlyMainfile*: bool
  25. proc overwriteFiles*(conf: ConfigRef) =
  26. let doStrip = options.getConfigVar(conf, "pretty.strip").normalize == "on"
  27. for i in 0 .. high(conf.m.fileInfos):
  28. if conf.m.fileInfos[i].dirty and
  29. (not gOnlyMainfile or FileIndex(i) == conf.projectMainIdx):
  30. let newFile = if gOverWrite: conf.m.fileInfos[i].fullpath
  31. else: conf.m.fileInfos[i].fullpath.changeFileExt(".pretty.nim")
  32. try:
  33. var f = open(newFile.string, fmWrite)
  34. for line in conf.m.fileInfos[i].lines:
  35. if doStrip:
  36. f.write line.strip(leading = false, trailing = true)
  37. else:
  38. f.write line
  39. f.write(conf.m.fileInfos[i], "\L")
  40. f.close
  41. except IOError:
  42. rawMessage(conf, errGenerated, "cannot open file: " & newFile.string)
  43. proc `=~`(s: string, a: openArray[string]): bool =
  44. for x in a:
  45. if s.startsWith(x): return true
  46. proc beautifyName(s: string, k: TSymKind): string =
  47. # minimal set of rules here for transition:
  48. # GC_ is allowed
  49. let allUpper = allCharsInSet(s, {'A'..'Z', '0'..'9', '_'})
  50. if allUpper and k in {skConst, skEnumField, skType}: return s
  51. result = newStringOfCap(s.len)
  52. var i = 0
  53. case k
  54. of skType, skGenericParam:
  55. # Types should start with a capital unless builtins like 'int' etc.:
  56. if s =~ ["int", "uint", "cint", "cuint", "clong", "cstring", "string",
  57. "char", "byte", "bool", "openArray", "seq", "array", "void",
  58. "pointer", "float", "csize", "cdouble", "cchar", "cschar",
  59. "cshort", "cu", "nil", "typedesc", "auto", "any",
  60. "range", "openarray", "varargs", "set", "cfloat", "ref", "ptr",
  61. "untyped", "typed", "static", "sink", "lent", "type"]:
  62. result.add s[i]
  63. else:
  64. result.add toUpperAscii(s[i])
  65. of skConst, skEnumField:
  66. # for 'const' we keep how it's spelt; either upper case or lower case:
  67. result.add s[0]
  68. else:
  69. # as a special rule, don't transform 'L' to 'l'
  70. if s.len == 1 and s[0] == 'L': result.add 'L'
  71. elif '_' in s: result.add(s[i])
  72. else: result.add toLowerAscii(s[0])
  73. inc i
  74. while i < s.len:
  75. if s[i] == '_':
  76. if i > 0 and s[i-1] in {'A'..'Z'}:
  77. # don't skip '_' as it's essential for e.g. 'GC_disable'
  78. result.add('_')
  79. inc i
  80. result.add s[i]
  81. else:
  82. inc i
  83. result.add toUpperAscii(s[i])
  84. elif allUpper:
  85. result.add toLowerAscii(s[i])
  86. else:
  87. result.add s[i]
  88. inc i
  89. proc differ*(line: string, a, b: int, x: string): bool =
  90. let y = line[a..b]
  91. result = cmpIgnoreStyle(y, x) == 0 and y != x
  92. proc replaceInFile(conf: ConfigRef; info: TLineInfo; newName: string) =
  93. let line = conf.m.fileInfos[info.fileIndex.int].lines[info.line.int-1]
  94. var first = min(info.col.int, line.len)
  95. if first < 0: return
  96. #inc first, skipIgnoreCase(line, "proc ", first)
  97. while first > 0 and line[first-1] in Letters: dec first
  98. if first < 0: return
  99. if line[first] == '`': inc first
  100. let last = first+identLen(line, first)-1
  101. if differ(line, first, last, newName):
  102. # last-first+1 != newName.len or
  103. var x = line.substr(0, first-1) & newName & line.substr(last+1)
  104. system.shallowCopy(conf.m.fileInfos[info.fileIndex.int].lines[info.line.int-1], x)
  105. conf.m.fileInfos[info.fileIndex.int].dirty = true
  106. proc lintReport(conf: ConfigRef; info: TLineInfo, beau: string) =
  107. if optStyleError in conf.globalOptions:
  108. localError(conf, info, "name should be: '$1'" % beau)
  109. else:
  110. message(conf, info, hintName, beau)
  111. proc checkStyle(conf: ConfigRef; cache: IdentCache; info: TLineInfo, s: string, k: TSymKind; sym: PSym) =
  112. let beau = beautifyName(s, k)
  113. if s != beau:
  114. if gStyleCheck == StyleCheck.Auto:
  115. sym.name = getIdent(cache, beau)
  116. replaceInFile(conf, info, beau)
  117. else:
  118. lintReport(conf, info, beau)
  119. proc styleCheckDefImpl(conf: ConfigRef; cache: IdentCache; info: TLineInfo; s: PSym; k: TSymKind) =
  120. # operators stay as they are:
  121. if k in {skResult, skTemp} or s.name.s[0] notin Letters: return
  122. if k in {skType, skGenericParam} and sfAnon in s.flags: return
  123. if {sfImportc, sfExportc} * s.flags == {} or gCheckExtern:
  124. checkStyle(conf, cache, info, s.name.s, k, s)
  125. proc nep1CheckDefImpl(conf: ConfigRef; info: TLineInfo; s: PSym; k: TSymKind) =
  126. # operators stay as they are:
  127. if k in {skResult, skTemp} or s.name.s[0] notin Letters: return
  128. if k in {skType, skGenericParam} and sfAnon in s.flags: return
  129. if s.typ != nil and s.typ.kind == tyTypeDesc: return
  130. if {sfImportc, sfExportc} * s.flags != {}: return
  131. let beau = beautifyName(s.name.s, k)
  132. if s.name.s != beau:
  133. lintReport(conf, info, beau)
  134. template styleCheckDef*(conf: ConfigRef; info: TLineInfo; s: PSym; k: TSymKind) =
  135. if {optStyleHint, optStyleError} * conf.globalOptions != {}:
  136. nep1CheckDefImpl(conf, info, s, k)
  137. when defined(nimfix):
  138. if gStyleCheck != StyleCheck.None: styleCheckDefImpl(conf, cache, info, s, k)
  139. template styleCheckDef*(conf: ConfigRef; info: TLineInfo; s: PSym) =
  140. styleCheckDef(conf, info, s, s.kind)
  141. template styleCheckDef*(conf: ConfigRef; s: PSym) =
  142. styleCheckDef(conf, s.info, s, s.kind)
  143. proc styleCheckUseImpl(conf: ConfigRef; info: TLineInfo; s: PSym) =
  144. if info.fileIndex.int < 0: return
  145. # we simply convert it to what it looks like in the definition
  146. # for consistency
  147. # operators stay as they are:
  148. if s.kind in {skResult, skTemp} or s.name.s[0] notin Letters:
  149. return
  150. if s.kind in {skType, skGenericParam} and sfAnon in s.flags: return
  151. let newName = s.name.s
  152. replaceInFile(conf, info, newName)
  153. #if newName == "File": writeStackTrace()
  154. template styleCheckUse*(info: TLineInfo; s: PSym) =
  155. when defined(nimfix):
  156. if gStyleCheck != StyleCheck.None: styleCheckUseImpl(conf, info, s)