linter.nim 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  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 std/strutils
  11. from std/sugar import dup
  12. import options, ast, msgs, idents, lineinfos, wordrecg, astmsgs, semdata, packages
  13. export packages
  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. proc `=~`(s: string, a: openArray[string]): bool =
  20. for x in a:
  21. if s.startsWith(x): return true
  22. proc beautifyName(s: string, k: TSymKind): string =
  23. # minimal set of rules here for transition:
  24. # GC_ is allowed
  25. let allUpper = allCharsInSet(s, {'A'..'Z', '0'..'9', '_'})
  26. if allUpper and k in {skConst, skEnumField, skType}: return s
  27. result = newStringOfCap(s.len)
  28. var i = 0
  29. case k
  30. of skType, skGenericParam:
  31. # Types should start with a capital unless builtins like 'int' etc.:
  32. if s =~ ["int", "uint", "cint", "cuint", "clong", "cstring", "string",
  33. "char", "byte", "bool", "openArray", "seq", "array", "void",
  34. "pointer", "float", "csize", "csize_t", "cdouble", "cchar", "cschar",
  35. "cshort", "cu", "nil", "typedesc", "auto", "any",
  36. "range", "openarray", "varargs", "set", "cfloat", "ref", "ptr",
  37. "untyped", "typed", "static", "sink", "lent", "type", "owned", "iterable"]:
  38. result.add s[i]
  39. else:
  40. result.add toUpperAscii(s[i])
  41. of skConst, skEnumField:
  42. # for 'const' we keep how it's spelt; either upper case or lower case:
  43. result.add s[0]
  44. else:
  45. # as a special rule, don't transform 'L' to 'l'
  46. if s.len == 1 and s[0] == 'L': result.add 'L'
  47. elif '_' in s: result.add(s[i])
  48. else: result.add toLowerAscii(s[0])
  49. inc i
  50. while i < s.len:
  51. if s[i] == '_':
  52. if i+1 >= s.len:
  53. discard "trailing underscores should be stripped off"
  54. elif i > 0 and s[i-1] in {'A'..'Z'}:
  55. # don't skip '_' as it's essential for e.g. 'GC_disable'
  56. result.add('_')
  57. inc i
  58. result.add s[i]
  59. else:
  60. inc i
  61. result.add toUpperAscii(s[i])
  62. elif allUpper:
  63. result.add toLowerAscii(s[i])
  64. else:
  65. result.add s[i]
  66. inc i
  67. proc differ*(line: string, a, b: int, x: string): string =
  68. proc substrEq(s: string, pos, last: int, substr: string): bool =
  69. result = true
  70. for i in 0..<substr.len:
  71. if pos+i > last or s[pos+i] != substr[i]: return false
  72. result = ""
  73. if not substrEq(line, a, b, x):
  74. let y = line[a..b]
  75. if cmpIgnoreStyle(y, x) == 0:
  76. result = y
  77. proc nep1CheckDefImpl(conf: ConfigRef; info: TLineInfo; s: PSym; k: TSymKind) =
  78. let beau = beautifyName(s.name.s, k)
  79. if s.name.s != beau:
  80. lintReport(conf, info, beau, s.name.s)
  81. template styleCheckDef*(ctx: PContext; info: TLineInfo; sym: PSym; k: TSymKind) =
  82. ## Check symbol definitions adhere to NEP1 style rules.
  83. if optStyleCheck in ctx.config.options and # ignore if styleChecks are off
  84. {optStyleHint, optStyleError} * ctx.config.globalOptions != {} and # check only if hint/error is enabled
  85. hintName in ctx.config.notes and # ignore if name checks are not requested
  86. ctx.config.belongsToProjectPackage(ctx.module) and # ignore foreign packages
  87. optStyleUsages notin ctx.config.globalOptions and # ignore if requested to only check name usage
  88. sym.kind != skResult and # ignore `result`
  89. sym.kind != skTemp and # ignore temporary variables created by the compiler
  90. sym.name.s[0] in Letters and # ignore operators TODO: what about unicode symbols???
  91. k notin {skType, skGenericParam} and # ignore types and generic params
  92. (sym.typ == nil or sym.typ.kind != tyTypeDesc) and # ignore `typedesc`
  93. {sfImportc, sfExportc} * sym.flags == {} and # ignore FFI
  94. sfAnon notin sym.flags: # ignore if created by compiler
  95. nep1CheckDefImpl(ctx.config, info, sym, k)
  96. template styleCheckDef*(ctx: PContext; info: TLineInfo; s: PSym) =
  97. ## Check symbol definitions adhere to NEP1 style rules.
  98. styleCheckDef(ctx, info, s, s.kind)
  99. template styleCheckDef*(ctx: PContext; s: PSym) =
  100. ## Check symbol definitions adhere to NEP1 style rules.
  101. styleCheckDef(ctx, s.info, s, s.kind)
  102. proc differs(conf: ConfigRef; info: TLineInfo; newName: string): string =
  103. let line = sourceLine(conf, info)
  104. var first = min(info.col.int, line.len)
  105. if first < 0: return
  106. #inc first, skipIgnoreCase(line, "proc ", first)
  107. while first > 0 and line[first-1] in Letters: dec first
  108. if first < 0: return
  109. if first+1 < line.len and line[first] == '`': inc first
  110. let last = first+identLen(line, first)-1
  111. result = differ(line, first, last, newName)
  112. proc styleCheckUseImpl(conf: ConfigRef; info: TLineInfo; s: PSym) =
  113. let newName = s.name.s
  114. let badName = differs(conf, info, newName)
  115. if badName.len > 0:
  116. lintReport(conf, info, newName, badName, "".dup(addDeclaredLoc(conf, s)))
  117. template styleCheckUse*(ctx: PContext; info: TLineInfo; sym: PSym) =
  118. ## Check symbol uses match their definition's style.
  119. if {optStyleHint, optStyleError} * ctx.config.globalOptions != {} and # ignore if styleChecks are off
  120. hintName in ctx.config.notes and # ignore if name checks are not requested
  121. ctx.config.belongsToProjectPackage(ctx.module) and # ignore foreign packages
  122. sym.kind != skTemp and # ignore temporary variables created by the compiler
  123. sym.name.s[0] in Letters and # ignore operators TODO: what about unicode symbols???
  124. sfAnon notin sym.flags: # ignore temporary variables created by the compiler
  125. styleCheckUseImpl(ctx.config, info, sym)
  126. proc checkPragmaUseImpl(conf: ConfigRef; info: TLineInfo; w: TSpecialWord; pragmaName: string) =
  127. let wanted = $w
  128. if pragmaName != wanted:
  129. lintReport(conf, info, wanted, pragmaName)
  130. template checkPragmaUse*(conf: ConfigRef; info: TLineInfo; w: TSpecialWord; pragmaName: string) =
  131. if {optStyleHint, optStyleError} * conf.globalOptions != {}:
  132. checkPragmaUseImpl(conf, info, w, pragmaName)