From 6e8ed8c6fa8ea43ad2cc2c44008ab7a76984030b Mon Sep 17 00:00:00 2001 From: Andreas Rumpf Date: Wed, 14 Nov 2018 16:04:45 +0100 Subject: added first version of a nimfind tool for the poor souls that don't have a good nimsuggest integretation --- tools/nimfind.nim | 228 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 228 insertions(+) create mode 100644 tools/nimfind.nim (limited to 'tools') diff --git a/tools/nimfind.nim b/tools/nimfind.nim new file mode 100644 index 000000000..097ee599c --- /dev/null +++ b/tools/nimfind.nim @@ -0,0 +1,228 @@ +# +# +# The Nim Compiler +# (c) Copyright 2018 Andreas Rumpf +# +# See the file "copying.txt", included in this +# distribution, for details about the copyright. +# + +## Nimfind is a tool that helps to give editors IDE like capabilities. + +when not defined(nimcore): + {.error: "nimcore MUST be defined for Nim's core tooling".} +when not defined(nimfind): + {.error: "nimfind MUST be defined for Nim's nimfind tool".} + +const Usage = """ +Nimfind - Tool to find declarations or usages for Nim symbols +Usage: + nimfind [options] file.nim:line:col + +Options: + --help, -h show this help + --rebuild rebuild the index + --project:file.nim use file.nim as the entry point + +In addition, all command line options of Nim that do not affect code generation +are supported. +""" + +import strutils, os, parseopt, parseutils + +import "../compiler" / [options, commands, modules, sem, + passes, passaux, msgs, nimconf, + extccomp, condsyms, + ast, scriptconfig, + idents, modulegraphs, vm, prefixmatches, lineinfos, cmdlinehelper, + pathutils] + +import db_sqlite + +proc createDb(db: DbConn) = + db.exec(sql""" + create table if not exists filenames( + id integer primary key, + fullpath varchar(8000) not null + ); + """) + db.exec sql"create index if not exists FilenameIx on filenames(fullpath);" + + # every sym can have potentially 2 different definitions due to forward + # declarations. + db.exec(sql""" + create table if not exists syms( + id integer primary key, + nimid integer not null, + name varchar(256) not null, + defline integer not null, + defcol integer not null, + deffile integer not null, + deflineB integer not null default 0, + defcolB integer not null default 0, + deffileB integer not null default 0, + foreign key (deffile) references filenames(id), + foreign key (deffileB) references filenames(id) + ); + """) + + db.exec(sql""" + create table if not exists usages( + id integer primary key, + nimid integer not null, + line integer not null, + col integer not null, + file integer not null, + foreign key (file) references filenames(id), + foreign key (nimid) references syms(nimid) + ); + """) + +proc toDbFileId*(db: DbConn; conf: ConfigRef; fileIdx: FileIndex): int = + if fileIdx == FileIndex(-1): return -1 + let fullpath = toFullPath(conf, fileIdx) + let row = db.getRow(sql"select id from filenames where fullpath = ?", fullpath) + let id = row[0] + if id.len == 0: + result = int db.insertID(sql"insert into filenames(fullpath) values (?)", + fullpath) + else: + result = parseInt(id) + +type + FinderRef = ref object of RootObj + db: DbConn + +proc writeDef(graph: ModuleGraph; s: PSym; info: TLineInfo) = + let f = FinderRef(graph.backend) + f.db.exec(sql"""insert into syms(nimid, name, defline, defcol, deffile) values (?, ?, ?, ?, ?)""", + s.id, s.name.s, info.line, info.col, + toDbFileId(f.db, graph.config, info.fileIndex)) + +proc writeDefResolveForward(graph: ModuleGraph; s: PSym; info: TLineInfo) = + let f = FinderRef(graph.backend) + f.db.exec(sql"""update syms set deflineB = ?, defcolB = ?, deffileB = ? + where nimid = ?""", info.line, info.col, + toDbFileId(f.db, graph.config, info.fileIndex), s.id) + +proc writeUsage(graph: ModuleGraph; s: PSym; info: TLineInfo) = + let f = FinderRef(graph.backend) + f.db.exec(sql"""insert into usages(nimid, line, col, file) values (?, ?, ?, ?)""", + s.id, info.line, info.col, + toDbFileId(f.db, graph.config, info.fileIndex)) + +proc performSearch(conf: ConfigRef; dbfile: AbsoluteFile) = + var db = open(connection=string dbfile, user="nim", password="", + database="nim") + let pos = conf.m.trackPos + let fid = toDbFileId(db, conf, pos.fileIndex) + var row = db.getRow(sql"""select max(col) from usages where line = ? and file = ? and ? >= col""", + pos.line, fid, pos.col) + if row.len > 0: + let known = toFullPath(conf, pos.fileIndex) + let nimid = db.getRow(sql"""select nimid from usages where line = ? and file = ? and col = ?""", + pos.line, fid, row[0]) + for r in db.rows(sql"""select line, col, filenames.fullpath from usages + inner join filenames on filenames.id = file + where nimid = ?""", nimid): + let line = parseInt(r[0]) + let col = parseInt(r[1]) + let file = r[2] + if file == known and line == pos.line.int: + discard "don't output the line we already know" + else: + echo file, ":", line, ":", col+1 + close(db) + +proc setupDb(g: ModuleGraph; dbfile: AbsoluteFile) = + var f = FinderRef() + removeFile(dbfile) + f.db = open(connection=string dbfile, user="nim", password="", + database="nim") + createDb(f.db) + f.db.exec(sql"pragma journal_mode=off") + # This MUST be turned off, otherwise it's way too slow even for testing purposes: + f.db.exec(sql"pragma SYNCHRONOUS=off") + f.db.exec(sql"pragma LOCKING_MODE=exclusive") + g.backend = f + +proc mainCommand(graph: ModuleGraph) = + let conf = graph.config + let dbfile = getNimcacheDir(conf) / RelativeFile"nimfind.db" + if not fileExists(dbfile) or optForceFullMake in conf.globalOptions: + clearPasses(graph) + registerPass graph, verbosePass + registerPass graph, semPass + conf.cmd = cmdIdeTools + wantMainModule(conf) + setupDb(graph, dbfile) + + graph.onDefinition = writeUsage # writeDef + graph.onDefinitionResolveForward = writeUsage # writeDefResolveForward + graph.onUsage = writeUsage + + if not fileExists(conf.projectFull): + quit "cannot find file: " & conf.projectFull.string + add(conf.searchPaths, conf.libpath) + # do not stop after the first error: + conf.errorMax = high(int) + compileProject(graph) + close(FinderRef(graph.backend).db) + performSearch(conf, dbfile) + +proc processCmdLine*(pass: TCmdLinePass, cmd: string; conf: ConfigRef) = + var p = parseopt.initOptParser(cmd) + while true: + parseopt.next(p) + case p.kind + of cmdEnd: break + of cmdLongoption, cmdShortOption: + case p.key.normalize + of "help", "h": + stdout.writeline(Usage) + quit() + of "project": + conf.projectName = p.val + of "rebuild": + incl conf.globalOptions, optForceFullMake + else: processSwitch(pass, p, conf) + of cmdArgument: + let info = p.key.split(':') + if info.len == 3: + let (dir, file, ext) = info[0].splitFile() + conf.projectName = findProjectNimFile(conf, dir) + if conf.projectName.len == 0: conf.projectName = info[0] + try: + conf.m.trackPos = newLineInfo(conf, AbsoluteFile info[0], + parseInt(info[1]), parseInt(info[2])) + except ValueError: + quit "invalid command line" + else: + quit "invalid command line" + +proc handleCmdLine(cache: IdentCache; conf: ConfigRef) = + let self = NimProg( + suggestMode: true, + processCmdLine: processCmdLine, + mainCommand: mainCommand + ) + self.initDefinesProg(conf, "nimfind") + + if paramCount() == 0: + stdout.writeline(Usage) + return + + self.processCmdLineAndProjectPath(conf) + + # Find Nim's prefix dir. + let binaryPath = findExe("nim") + if binaryPath == "": + raise newException(IOError, + "Cannot find Nim standard library: Nim compiler not in PATH") + conf.prefixDir = AbsoluteDir binaryPath.splitPath().head.parentDir() + if not dirExists(conf.prefixDir / RelativeDir"lib"): + conf.prefixDir = AbsoluteDir"" + + discard self.loadConfigsAndRunMainCommand(cache, conf) + +handleCmdline(newIdentCache(), newConfigRef()) -- cgit 1.4.1-2-gfad0 commit/main.c?id=a7d89e0e08570dd6991ca544aa2e059f88ebf2b2'>a7d89e0e ^
a4ca6291 ^
a7d89e0e ^
f9737251 ^











a7d89e0e ^
17488ca3 ^
9b177a9e ^
17488ca3 ^
9b55f2de ^
a4cadf78 ^
7c908780 ^
9b177a9e ^
0fbaa6f5 ^
6b852a2f ^
fc5bfb7d ^
ca1dcdda ^







17b4e45c ^



a4ca6291 ^
a4cadf78 ^

581f58e4 ^
7c908780 ^
a2726b6a ^




7c908780 ^
279737ba ^
a2726b6a ^
6bad38c2 ^
f2159559 ^
5e99a791 ^






e0dfe483 ^

a2726b6a ^
7c908780 ^
034a9858 ^
b8207207 ^
75cfe388 ^
46e938b6 ^
4f19ea26 ^
7c908780 ^

6bad38c2 ^
a2726b6a ^

72d96a92 ^
7c908780 ^

7c908780 ^

c9ed5834 ^
98bc1abb ^
72d96a92 ^
7c908780 ^
72d96a92 ^
453fcae2 ^

7c908780 ^
9b177a9e ^

a4ca6291 ^
6b852a2f ^
a4ca6291 ^
6b852a2f ^

a4ca6291 ^
6b852a2f ^

13088e0a ^

3adc399d ^
14c8f53f ^
7c908780 ^


0115d71e ^


651d5aaa ^
2b88e2f1 ^
2b88e2f1 ^
e434b1bb ^
651d5aaa ^




9b177a9e ^
a2726b6a ^
ca1dcdda ^
0115d71e ^



9b177a9e ^
a2726b6a ^
ca1dcdda ^
2490c3ed ^



249701fe ^





9b177a9e ^
bd928f0f ^




9b177a9e ^
7f3fca2b ^
17b4e45c ^
2783c84a ^



697db019 ^
791b13cb ^
1e60d17d ^
791b13cb ^
1e60d17d ^

0cff1112 ^





7c908780 ^
72d96a92 ^

b8207207 ^

d18ec23d ^

c9fcd018 ^



4f19ea26 ^
5d9c7ffd ^


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
  
         
                                 
  
                                                            
                                                               
  
                                    
  
                                                                      



                                                                       
                                                                 




                                                                    
                                                                        
  











                                                                                
   
 
                   
 
                   
                 
 
                       
                       
      
 







                    



                                   
                        

                             
 
                                




                                 
 
   
                           
 
                                                                     






                                                       

     
                                     
                                                                                             
                                                                                                           
                                                                                                                        
                                                                                                               
                                                                                        
                                                                                          

                
 

                            
 

                                                              

                                                                 
                                       
                            
                 
     
 

                                   
                          

                                                         
                                                                                                               
     
                                                                     

                
                                                                  

         

                                                                                   
                                                                                   
                                                                                                        


                                                                                        


                                        
 
                                              
 
                                  




                                                                
                  
                                                 
                                                                   



                                           
                    
                                                 
                                                                     



                                           





                                             
             




                                         
                  
                                                                       
                                                                  



                                              
               
                                                  
     
                                                   

      





                                          
                 

     

                                                                                  

                                                    



                         
                       


             
/*
 * main.c
 * vim: expandtab:ts=4:sts=4:sw=4
 *
 * Copyright (C) 2012 - 2019 James Booth <boothj5@gmail.com>
 * Copyright (C) 2019 - 2023 Michael Vetter <jubalh@iodoru.org>
 *
 * This file is part of Profani-tty.
 *
 * Profani-tty is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Profani-tty is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Profani-tty.  If not, see <https://www.gnu.org/licenses/>.
 *
 * In addition, as a special exception, the copyright holders give permission to
 * link the code of portions of this program with the OpenSSL library under
 * certain conditions as described in each individual source file, and
 * distribute linked combinations including the two.
 *
 * You must obey the GNU General Public License in all respects for all of the
 * code used other than OpenSSL. If you modify file(s) with this exception, you
 * may extend this exception to your version of the file(s), but you are not
 * obligated to do so. If you do not wish to do so, delete this exception
 * statement from your version. If you delete this exception statement from all
 * source files in the program, then also delete it here.
 *
 */

#include "config.h"

#include <string.h>
#include <glib.h>

#ifdef HAVE_GIT_VERSION
#include "gitversion.h"
#endif

#ifdef HAVE_LIBOTR
#include "otr/otr.h"
#endif

#ifdef HAVE_LIBGPGME
#include "pgp/gpg.h"
#endif

#ifdef HAVE_PYTHON
#include "plugins/python_plugins.h"
#endif

#include "profani-tty.h"
#include "common.h"
#include "command/cmd_defs.h"

static gboolean version = FALSE;
static char* log = NULL;
static char* log_file = NULL;
static char* account_name = NULL;
static char* config_file = NULL;
static char* theme_name = NULL;

int
main(int argc, char** argv)
{
    if (argc == 2 && g_strcmp0(PACKAGE_STATUS, "development") == 0) {
        if (g_strcmp0(argv[1], "docgen") == 0) {
            command_docgen();
            return 0;
        } else if (g_strcmp0(argv[1], "mangen") == 0) {
            command_mangen();
            return 0;
        }
    }

    static GOptionEntry entries[] = {
        { "version", 'v', 0, G_OPTION_ARG_NONE, &version, "Show version information", NULL },
        { "account", 'a', 0, G_OPTION_ARG_STRING, &account_name, "Auto connect to an account on startup" },
        { "log", 'l', 0, G_OPTION_ARG_STRING, &log, "Set logging levels, DEBUG, INFO, WARN (default), ERROR", "LEVEL" },
        { "config", 'c', 0, G_OPTION_ARG_STRING, &config_file, "Use an alternative configuration file", NULL },
        { "logfile", 'f', 0, G_OPTION_ARG_STRING, &log_file, "Specify log file", NULL },
        { "theme", 't', 0, G_OPTION_ARG_STRING, &theme_name, "Specify theme name", NULL },
        { NULL }
    };

    GError* error = NULL;
    GOptionContext* context;

    context = g_option_context_new(NULL);
    g_option_context_add_main_entries(context, entries, NULL);
    if (!g_option_context_parse(context, &argc, &argv, &error)) {
        g_print("%s\n", error->message);
        g_option_context_free(context);
        g_error_free(error);
        return 1;
    }

    g_option_context_free(context);

    if (version == TRUE) {
        if (strcmp(PACKAGE_STATUS, "development") == 0) {
#ifdef HAVE_GIT_VERSION
            g_print("Profani-tty, version %sdev.%s.%s\n", PACKAGE_VERSION, PROF_GIT_BRANCH, PROF_GIT_REVISION);
#else
            g_print("Profani-tty, version %sdev\n", PACKAGE_VERSION);
#endif
        } else {
            g_print("Profani-tty, version %s\n", PACKAGE_VERSION);
        }

        // lets use fixed email instead of PACKAGE_BUGREPORT
        g_print("Copyright (C) 2012 - 2019 James Booth <boothj5web@gmail.com>.\n");
        g_print("Copyright (C) 2019 - 2023 Michael Vetter <jubalh@iodoru.org>.\n");
        g_print("License GPLv3+: GNU GPL version 3 or later <https://www.gnu.org/licenses/gpl.html>\n");
        g_print("\n");
        g_print("This is free software; you are free to change and redistribute it.\n");
        g_print("There is NO WARRANTY, to the extent permitted by law.\n");
        g_print("\n");

        g_print("Build information:\n");

        g_print("XMPP library: libstrophe\n");

        if (is_notify_enabled()) {
            g_print("Desktop notification support: Enabled\n");
        } else {
            g_print("Desktop notification support: Disabled\n");
        }

#ifdef HAVE_LIBOTR
        char* otr_version = otr_libotr_version();
        g_print("OTR support: Enabled (libotr %s)\n", otr_version);
#else
        g_print("OTR support: Disabled\n");
#endif

#ifdef HAVE_LIBGPGME
        const char* pgp_version = p_gpg_libver();
        g_print("PGP support: Enabled (libgpgme %s)\n", pgp_version);
#else
        g_print("PGP support: Disabled\n");
#endif

#ifdef HAVE_OMEMO
        g_print("OMEMO support: Enabled\n");
#else
        g_print("OMEMO support: Disabled\n");
#endif

#ifdef HAVE_C
        g_print("C plugins: Enabled\n");
#else
        g_print("C plugins: Disabled\n");
#endif

#ifdef HAVE_PYTHON
        auto_gchar gchar* python_version = python_get_version_number();
        g_print("Python plugins: Enabled (%s)\n", python_version);
#else
        g_print("Python plugins: Disabled\n");
#endif

#ifdef HAVE_GTK
        g_print("GTK icons/clipboard: Enabled\n");
#else
        g_print("GTK icons/clipboard: Disabled\n");
#endif

#ifdef HAVE_PIXBUF
        g_print("GDK Pixbuf: Enabled\n");
#else
        g_print("GDK Pixbuf: Disabled\n");
#endif

        return 0;
    }

    /* Default logging WARN */
    prof_run(log ? log : "WARN", account_name, config_file, log_file, theme_name);

    /* Free resources allocated by GOptionContext */
    g_free(log);
    g_free(account_name);
    g_free(config_file);
    g_free(log_file);
    g_free(theme_name);

    return 0;
}