nimfind.nim 7.7 KB

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