nimfind.nim 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. #
  2. #
  3. # The Nim Compiler
  4. # (c) Copyright 2018 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## Nimfind is a tool that helps to give editors IDE like capabilities.
  10. when not defined(nimcore):
  11. {.error: "nimcore MUST be defined for Nim's core tooling".}
  12. when not defined(nimfind):
  13. {.error: "nimfind MUST be defined for Nim's nimfind tool".}
  14. const Usage = """
  15. Nimfind - Tool to find declarations or usages for Nim symbols
  16. Usage:
  17. nimfind [options] file.nim:line:col
  18. Options:
  19. --help, -h show this help
  20. --rebuild rebuild the index
  21. --project:file.nim use file.nim as the entry point
  22. In addition, all command line options of Nim that do not affect code generation
  23. are supported.
  24. """
  25. import strutils, os, parseopt
  26. import "../compiler" / [options, commands, modules, sem,
  27. passes, passaux, msgs, ast,
  28. idents, modulegraphs, lineinfos, cmdlinehelper,
  29. pathutils]
  30. import db_sqlite
  31. proc createDb(db: DbConn) =
  32. db.exec(sql"""
  33. create table if not exists filenames(
  34. id integer primary key,
  35. fullpath varchar(8000) not null
  36. );
  37. """)
  38. db.exec sql"create index if not exists FilenameIx on filenames(fullpath);"
  39. # every sym can have potentially 2 different definitions due to forward
  40. # declarations.
  41. db.exec(sql"""
  42. create table if not exists syms(
  43. id integer primary key,
  44. nimid integer not null,
  45. name varchar(256) not null,
  46. defline integer not null,
  47. defcol integer not null,
  48. deffile integer not null,
  49. deflineB integer not null default 0,
  50. defcolB integer not null default 0,
  51. deffileB integer not null default 0,
  52. foreign key (deffile) references filenames(id),
  53. foreign key (deffileB) references filenames(id)
  54. );
  55. """)
  56. db.exec(sql"""
  57. create table if not exists usages(
  58. id integer primary key,
  59. nimid integer not null,
  60. line integer not null,
  61. col integer not null,
  62. colB integer not null,
  63. file integer not null,
  64. foreign key (file) references filenames(id),
  65. foreign key (nimid) references syms(nimid)
  66. );
  67. """)
  68. db.exec sql"create index if not exists UsagesIx on usages(file, line);"
  69. proc toDbFileId*(db: DbConn; conf: ConfigRef; fileIdx: FileIndex): int =
  70. if fileIdx == FileIndex(-1): return -1
  71. let fullpath = toFullPath(conf, fileIdx)
  72. let row = db.getRow(sql"select id from filenames where fullpath = ?", fullpath)
  73. let id = row[0]
  74. if id.len == 0:
  75. result = int db.insertID(sql"insert into filenames(fullpath) values (?)",
  76. fullpath)
  77. else:
  78. result = parseInt(id)
  79. type
  80. FinderRef = ref object of RootObj
  81. db: DbConn
  82. proc writeDef(graph: ModuleGraph; s: PSym; info: TLineInfo) =
  83. let f = FinderRef(graph.backend)
  84. f.db.exec(sql"""insert into syms(nimid, name, defline, defcol, deffile) values (?, ?, ?, ?, ?)""",
  85. s.id, s.name.s, info.line, info.col,
  86. toDbFileId(f.db, graph.config, info.fileIndex))
  87. proc writeDefResolveForward(graph: ModuleGraph; s: PSym; info: TLineInfo) =
  88. let f = FinderRef(graph.backend)
  89. f.db.exec(sql"""update syms set deflineB = ?, defcolB = ?, deffileB = ?
  90. where nimid = ?""", info.line, info.col,
  91. toDbFileId(f.db, graph.config, info.fileIndex), s.id)
  92. proc writeUsage(graph: ModuleGraph; s: PSym; info: TLineInfo) =
  93. let f = FinderRef(graph.backend)
  94. f.db.exec(sql"""insert into usages(nimid, line, col, colB, file) values (?, ?, ?, ?, ?)""",
  95. s.id, info.line, info.col, info.col + s.name.s.len - 1,
  96. toDbFileId(f.db, graph.config, info.fileIndex))
  97. proc performSearch(conf: ConfigRef; dbfile: AbsoluteFile) =
  98. var db = open(connection=string dbfile, user="nim", password="",
  99. database="nim")
  100. let pos = conf.m.trackPos
  101. let fid = toDbFileId(db, conf, pos.fileIndex)
  102. let known = toFullPath(conf, pos.fileIndex)
  103. let nimids = db.getRow(sql"""select distinct nimid from usages where line = ? and file = ? and ? between col and colB""",
  104. pos.line, fid, pos.col)
  105. if nimids.len > 0:
  106. var idSet = ""
  107. for id in nimids:
  108. if idSet.len > 0: idSet.add ", "
  109. idSet.add id
  110. var outputLater = ""
  111. for r in db.rows(sql"""select line, col, filenames.fullpath from usages
  112. inner join filenames on filenames.id = file
  113. where nimid in (?)""", idSet):
  114. let line = parseInt(r[0])
  115. let col = parseInt(r[1])
  116. let file = r[2]
  117. if file == known and line == pos.line.int:
  118. # output the line we already know last:
  119. outputLater.add file & ":" & $line & ":" & $(col+1) & "\n"
  120. else:
  121. echo file, ":", line, ":", col+1
  122. if outputLater.len > 0: stdout.write outputLater
  123. close(db)
  124. proc setupDb(g: ModuleGraph; dbfile: AbsoluteFile) =
  125. var f = FinderRef()
  126. removeFile(dbfile)
  127. f.db = open(connection=string dbfile, user="nim", password="",
  128. database="nim")
  129. createDb(f.db)
  130. f.db.exec(sql"pragma journal_mode=off")
  131. # This MUST be turned off, otherwise it's way too slow even for testing purposes:
  132. f.db.exec(sql"pragma SYNCHRONOUS=off")
  133. f.db.exec(sql"pragma LOCKING_MODE=exclusive")
  134. g.backend = f
  135. proc mainCommand(graph: ModuleGraph) =
  136. let conf = graph.config
  137. let dbfile = getNimcacheDir(conf) / RelativeFile"nimfind.db"
  138. if not fileExists(dbfile) or optForceFullMake in conf.globalOptions:
  139. clearPasses(graph)
  140. registerPass graph, verbosePass
  141. registerPass graph, semPass
  142. conf.cmd = cmdIdeTools
  143. wantMainModule(conf)
  144. setupDb(graph, dbfile)
  145. graph.onDefinition = writeUsage # writeDef
  146. graph.onDefinitionResolveForward = writeUsage # writeDefResolveForward
  147. graph.onUsage = writeUsage
  148. if not fileExists(conf.projectFull):
  149. quit "cannot find file: " & conf.projectFull.string
  150. add(conf.searchPaths, conf.libpath)
  151. # do not stop after the first error:
  152. conf.errorMax = high(int)
  153. try:
  154. compileProject(graph)
  155. finally:
  156. close(FinderRef(graph.backend).db)
  157. performSearch(conf, dbfile)
  158. proc processCmdLine*(pass: TCmdLinePass, cmd: string; conf: ConfigRef) =
  159. var p = parseopt.initOptParser(cmd)
  160. while true:
  161. parseopt.next(p)
  162. case p.kind
  163. of cmdEnd: break
  164. of cmdLongOption, cmdShortOption:
  165. case p.key.normalize
  166. of "help", "h":
  167. stdout.writeLine(Usage)
  168. quit()
  169. of "project":
  170. conf.projectName = p.val
  171. of "rebuild":
  172. incl conf.globalOptions, optForceFullMake
  173. else: processSwitch(pass, p, conf)
  174. of cmdArgument:
  175. let info = p.key.split(':')
  176. if info.len == 3:
  177. let (dir, file, ext) = info[0].splitFile()
  178. conf.projectName = findProjectNimFile(conf, dir)
  179. if conf.projectName.len == 0: conf.projectName = info[0]
  180. try:
  181. conf.m.trackPos = newLineInfo(conf, AbsoluteFile info[0],
  182. parseInt(info[1]), parseInt(info[2])-1)
  183. except ValueError:
  184. quit "invalid command line"
  185. else:
  186. quit "invalid command line"
  187. proc handleCmdLine(cache: IdentCache; conf: ConfigRef) =
  188. let self = NimProg(
  189. suggestMode: true,
  190. processCmdLine: processCmdLine,
  191. mainCommand: mainCommand
  192. )
  193. self.initDefinesProg(conf, "nimfind")
  194. if paramCount() == 0:
  195. stdout.writeLine(Usage)
  196. return
  197. self.processCmdLineAndProjectPath(conf)
  198. # Find Nim's prefix dir.
  199. let binaryPath = findExe("nim")
  200. if binaryPath == "":
  201. raise newException(IOError,
  202. "Cannot find Nim standard library: Nim compiler not in PATH")
  203. conf.prefixDir = AbsoluteDir binaryPath.splitPath().head.parentDir()
  204. if not dirExists(conf.prefixDir / RelativeDir"lib"):
  205. conf.prefixDir = AbsoluteDir""
  206. discard self.loadConfigsAndRunMainCommand(cache, conf)
  207. handleCmdLine(newIdentCache(), newConfigRef())