forked from chipsalliance/verible
-
Notifications
You must be signed in to change notification settings - Fork 0
/
verilog-language-server_test.cc
1897 lines (1557 loc) · 69.6 KB
/
verilog-language-server_test.cc
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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2017-2020 The Verible Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "verilog/tools/ls/verilog-language-server.h"
#include <filesystem>
#include "absl/flags/flag.h"
#include "absl/strings/match.h"
#include "absl/strings/str_replace.h"
#include "common/lsp/lsp-file-utils.h"
#include "common/lsp/lsp-protocol-enums.h"
#include "common/lsp/lsp-protocol.h"
#include "common/util/file_util.h"
#include "gtest/gtest.h"
#include "verilog/analysis/verilog_linter.h"
#undef ASSERT_OK
#define ASSERT_OK(value) \
if (const auto &status__ = (value); status__.ok()) \
; \
else \
EXPECT_TRUE(status__.ok()) << status__
namespace verilog {
namespace {
// TODO (glatosinski) for JSON messages use types defined in lsp-protocol.h
using nlohmann::json;
using verible::lsp::PathToLSPUri;
// TODO (glatosinski) use better sample modules
static constexpr absl::string_view //
kSampleModuleA(
R"(module a;
assign var1 = 1'b0;
assign var2 = var1 | 1'b1;
endmodule
)");
static constexpr absl::string_view //
kSampleModuleB(
R"(module b;
assign var1 = 1'b0;
assign var2 = var1 | 1'b1;
a vara;
assign vara.var1 = 1'b1;
endmodule
)");
class VerilogLanguageServerTest : public ::testing::Test {
public:
// Sends initialize request from client mock to the Language Server.
// It does not parse the response nor fetch it in any way (for other
// tests to check e.g. server/client capabilities).
virtual absl::Status InitializeCommunication() {
const absl::string_view initialize =
R"({ "jsonrpc": "2.0", "id": 1, "method": "initialize", "params": null })";
SetRequest(initialize);
return ServerStep();
}
// Runs SetRequest and ServerStep, returning the status from the
// Language Server
// TODO: accept nlohmann::json object directly ?
absl::Status SendRequest(absl::string_view request) {
SetRequest(request);
return ServerStep();
}
// Returns the latest responses from the Language Server
std::string GetResponse() {
std::string response = response_stream_.str();
response_stream_.str("");
response_stream_.clear();
absl::SetFlag(&FLAGS_rules_config_search, true);
return response;
}
// Returns response to textDocument/initialize request
const std::string &GetInitializeResponse() const {
return initialize_response_;
}
protected:
// Wraps request for the Language Server in RPC header
void SetRequest(absl::string_view request) {
request_stream_.clear();
request_stream_.str(
absl::StrCat("Content-Length: ", request.size(), "\r\n\r\n", request));
}
// Performs single VerilogLanguageServer step, fetching latest request
absl::Status ServerStep() {
return server_->Step([this](char *message, int size) -> int {
request_stream_.read(message, size);
return request_stream_.gcount();
});
}
// Sets up the testing environment - creates Language Server object and
// sends textDocument/initialize request.
// It stores the response in initialize_response field for further processing
void SetUp() override {
server_ = std::make_unique<VerilogLanguageServer>(
[this](absl::string_view response) { response_stream_ << response; });
absl::Status status = InitializeCommunication();
EXPECT_TRUE(status.ok()) << "Failed to read request: " << status;
initialize_response_ = GetResponse();
}
// Currently tested instance of VerilogLanguageServer
std::unique_ptr<VerilogLanguageServer> server_;
// Response from textDocument/initialize request - left for checking e.g
// server capabilities
std::string initialize_response_;
// Stream for passing requests to the Language Server
std::stringstream request_stream_;
// Stream for receiving responses from the Language Server
std::stringstream response_stream_;
};
class VerilogLanguageServerSymbolTableTest : public VerilogLanguageServerTest {
public:
absl::Status InitializeCommunication() override {
json initialize_request = {
{"jsonrpc", "2.0"},
{"id", 1},
{"method", "initialize"},
{"params", {{"rootUri", PathToLSPUri(root_dir)}}}};
return SendRequest(initialize_request.dump());
}
protected:
void SetUp() override {
absl::SetFlag(&FLAGS_rules_config_search, true);
root_dir = verible::file::JoinPath(
::testing::TempDir(),
::testing::UnitTest::GetInstance()->current_test_info()->name());
absl::Status status = verible::file::CreateDir(root_dir);
ASSERT_OK(status) << status;
VerilogLanguageServerTest::SetUp();
}
void TearDown() override { std::filesystem::remove(root_dir); }
// path to the project
std::string root_dir;
};
// Verifies textDocument/initialize request handling
TEST_F(VerilogLanguageServerTest, InitializeRequest) {
std::string response_str = GetInitializeResponse();
json response = json::parse(response_str);
EXPECT_EQ(response["id"], 1) << "Response message ID invalid";
EXPECT_EQ(response["result"]["serverInfo"]["name"],
"Verible Verilog language server.")
<< "Invalid Language Server name";
}
static std::string DidOpenRequest(absl::string_view name,
absl::string_view content) {
return nlohmann::json{//
{"jsonrpc", "2.0"},
{"method", "textDocument/didOpen"},
{"params",
{{"textDocument",
{
{"uri", name},
{"text", content},
}}}}}
.dump();
}
// Checks automatic diagnostics for opened file and textDocument/diagnostic
// request for file with invalid syntax
TEST_F(VerilogLanguageServerTest, SyntaxError) {
const std::string wrong_file =
DidOpenRequest("file://syntaxerror.sv", "brokenfile");
ASSERT_OK(SendRequest(wrong_file)) << "process file with syntax error";
json response = json::parse(GetResponse());
EXPECT_EQ(response["method"], "textDocument/publishDiagnostics")
<< "textDocument/publishDiagnostics not received";
EXPECT_EQ(response["params"]["uri"], "file://syntaxerror.sv")
<< "Diagnostics for invalid file";
EXPECT_TRUE(absl::StrContains(
response["params"]["diagnostics"][0]["message"].get<std::string>(),
"syntax error"))
<< "No syntax error found";
// query diagnostics explicitly
const absl::string_view diagnostic_request = R"(
{
"jsonrpc": "2.0", "id": 2, "method": "textDocument/diagnostic",
"params":
{
"textDocument": {"uri": "file://syntaxerror.sv"}
}
}
)";
ASSERT_OK(SendRequest(diagnostic_request))
<< "Failed to process file with syntax error";
response = json::parse(GetResponse());
EXPECT_EQ(response["id"], 2) << "Invalid id";
EXPECT_EQ(response["result"]["kind"], "full") << "Diagnostics kind invalid";
EXPECT_TRUE(absl::StrContains(
response["result"]["items"][0]["message"].get<std::string>(),
"syntax error"))
<< "No syntax error found";
}
// Tests diagnostics for file with linting error before and after fix
TEST_F(VerilogLanguageServerTest, LintErrorDetection) {
const std::string lint_error =
DidOpenRequest("file://mini.sv", "module mini();\nendmodule");
ASSERT_OK(SendRequest(lint_error)) << "process file with linting error";
const json diagnostics = json::parse(GetResponse());
// Firstly, check correctness of diagnostics
EXPECT_EQ(diagnostics["method"], "textDocument/publishDiagnostics")
<< "textDocument/publishDiagnostics not received";
EXPECT_EQ(diagnostics["params"]["uri"], "file://mini.sv")
<< "Diagnostics for invalid file";
EXPECT_TRUE(absl::StrContains(
diagnostics["params"]["diagnostics"][0]["message"].get<std::string>(),
"File must end with a newline."))
<< "No syntax error found";
EXPECT_EQ(diagnostics["params"]["diagnostics"][0]["range"]["start"]["line"],
1);
EXPECT_EQ(
diagnostics["params"]["diagnostics"][0]["range"]["start"]["character"],
9);
// Secondly, request a code action at the EOF error message position
const absl::string_view action_request =
R"({"jsonrpc":"2.0", "id":10, "method":"textDocument/codeAction","params":{"textDocument":{"uri":"file://mini.sv"},"range":{"start":{"line":1,"character":9},"end":{"line":1,"character":9}}}})";
ASSERT_OK(SendRequest(action_request));
const json action = json::parse(GetResponse());
EXPECT_EQ(action["id"], 10);
EXPECT_EQ(
action["result"][0]["edit"]["changes"]["file://mini.sv"][0]["newText"],
"\n");
// Thirdly, apply change suggested by a code action and check diagnostics
const absl::string_view apply_fix =
R"({"jsonrpc":"2.0","method":"textDocument/didChange","params":{"textDocument":{"uri":"file://mini.sv"},"contentChanges":[{"range":{"start":{"character":9,"line":1},"end":{"character":9,"line":1}},"text":"\n"}]}})";
ASSERT_OK(SendRequest(apply_fix));
const json diagnostic_of_fixed = json::parse(GetResponse());
EXPECT_EQ(diagnostic_of_fixed["method"], "textDocument/publishDiagnostics");
EXPECT_EQ(diagnostic_of_fixed["params"]["uri"], "file://mini.sv");
EXPECT_EQ(diagnostic_of_fixed["params"]["diagnostics"].size(), 0);
}
// Tests textDocument/documentSymbol request support; expect document outline.
TEST_F(VerilogLanguageServerTest, DocumentSymbolRequestTest) {
// Create file, absorb diagnostics
const std::string mini_module = DidOpenRequest("file://mini_pkg.sv", R"(
package mini;
function static void fun_foo();
endfunction
class some_class;
function void member();
endfunction
endclass
endpackage
module mini(input clk);
always@(posedge clk) begin : labelled_block
end
reg foo;
net bar;
some_class baz();
endmodule
)");
ASSERT_OK(SendRequest(mini_module));
// Expect to receive diagnostics right away. Ignore.
const json diagnostics = json::parse(GetResponse());
EXPECT_EQ(diagnostics["method"], "textDocument/publishDiagnostics")
<< "textDocument/publishDiagnostics not received";
// Request a document symbol
const absl::string_view document_symbol_request =
R"({"jsonrpc":"2.0", "id":11, "method":"textDocument/documentSymbol","params":{"textDocument":{"uri":"file://mini_pkg.sv"}}})";
ASSERT_OK(SendRequest(document_symbol_request));
// TODO: by default, the Kate workarounds are active, so
// Module -> Method and Namespace -> Class. Remove by default.
const json document_symbol = json::parse(GetResponse());
EXPECT_EQ(document_symbol["id"], 11);
std::vector<verible::lsp::DocumentSymbol> toplevel =
document_symbol["result"];
EXPECT_EQ(toplevel.size(), 2);
EXPECT_EQ(toplevel[0].kind, verible::lsp::SymbolKind::kPackage);
EXPECT_EQ(toplevel[0].name, "mini");
EXPECT_EQ(toplevel[1].kind, verible::lsp::SymbolKind::kMethod); // module.
EXPECT_EQ(toplevel[1].name, "mini");
// Descend tree into package and look at expected nested symbols there.
std::vector<verible::lsp::DocumentSymbol> package = toplevel[0].children;
EXPECT_EQ(package.size(), 2);
EXPECT_EQ(package[0].kind, verible::lsp::SymbolKind::kFunction);
EXPECT_EQ(package[0].name, "fun_foo");
EXPECT_EQ(package[1].kind, verible::lsp::SymbolKind::kClass);
EXPECT_EQ(package[1].name, "some_class");
// Descend tree into class and find nested function.
std::vector<verible::lsp::DocumentSymbol> class_block = package[1].children;
EXPECT_EQ(class_block.size(), 1);
EXPECT_EQ(class_block[0].kind, verible::lsp::SymbolKind::kFunction);
EXPECT_EQ(class_block[0].name, "member");
// Descent tree into module and find labelled block.
std::vector<verible::lsp::DocumentSymbol> module = toplevel[1].children;
EXPECT_EQ(module.size(), 4);
EXPECT_EQ(module[0].kind, verible::lsp::SymbolKind::kNamespace);
EXPECT_EQ(module[0].name, "labelled_block");
EXPECT_EQ(module[1].kind, verible::lsp::SymbolKind::kVariable);
EXPECT_EQ(module[1].name, "foo");
EXPECT_EQ(module[2].kind, verible::lsp::SymbolKind::kVariable);
EXPECT_EQ(module[2].name, "bar");
EXPECT_EQ(module[3].kind, verible::lsp::SymbolKind::kVariable);
EXPECT_EQ(module[3].name, "baz");
}
TEST_F(VerilogLanguageServerTest, DocumentSymbolRequestWithoutVariablesTest) {
server_->include_variables = false;
// Create file, absorb diagnostics
const std::string mini_module = DidOpenRequest("file://mini_pkg.sv", R"(
package mini;
function static void fun_foo();
endfunction
class some_class;
function void member();
endfunction
endclass
endpackage
module mini(input clk);
always@(posedge clk) begin : labelled_block
end
reg foo;
net bar;
some_class baz();
endmodule
)");
ASSERT_OK(SendRequest(mini_module));
// Expect to receive diagnostics right away. Ignore.
const json diagnostics = json::parse(GetResponse());
EXPECT_EQ(diagnostics["method"], "textDocument/publishDiagnostics")
<< "textDocument/publishDiagnostics not received";
// Request a document symbol
const absl::string_view document_symbol_request =
R"({"jsonrpc":"2.0", "id":11, "method":"textDocument/documentSymbol","params":{"textDocument":{"uri":"file://mini_pkg.sv"}}})";
ASSERT_OK(SendRequest(document_symbol_request));
// TODO: by default, the Kate workarounds are active, so
// Module -> Method and Namespace -> Class. Remove by default.
const json document_symbol = json::parse(GetResponse());
EXPECT_EQ(document_symbol["id"], 11);
std::vector<verible::lsp::DocumentSymbol> toplevel =
document_symbol["result"];
EXPECT_EQ(toplevel.size(), 2);
EXPECT_EQ(toplevel[0].kind, verible::lsp::SymbolKind::kPackage);
EXPECT_EQ(toplevel[0].name, "mini");
EXPECT_EQ(toplevel[1].kind, verible::lsp::SymbolKind::kMethod); // module.
EXPECT_EQ(toplevel[1].name, "mini");
// Descend tree into package and look at expected nested symbols there.
std::vector<verible::lsp::DocumentSymbol> package = toplevel[0].children;
EXPECT_EQ(package.size(), 2);
EXPECT_EQ(package[0].kind, verible::lsp::SymbolKind::kFunction);
EXPECT_EQ(package[0].name, "fun_foo");
EXPECT_EQ(package[1].kind, verible::lsp::SymbolKind::kClass);
EXPECT_EQ(package[1].name, "some_class");
// Descend tree into class and find nested function.
std::vector<verible::lsp::DocumentSymbol> class_block = package[1].children;
EXPECT_EQ(class_block.size(), 1);
EXPECT_EQ(class_block[0].kind, verible::lsp::SymbolKind::kFunction);
EXPECT_EQ(class_block[0].name, "member");
// Descent tree into module and find labelled block.
std::vector<verible::lsp::DocumentSymbol> module = toplevel[1].children;
EXPECT_EQ(module.size(), 1);
EXPECT_EQ(module[0].kind, verible::lsp::SymbolKind::kNamespace);
EXPECT_EQ(module[0].name, "labelled_block");
}
// Tests closing of the file in the LS context and checks if the LS
// responds gracefully to textDocument/documentSymbol request for
// closed file.
TEST_F(VerilogLanguageServerTest,
DocumentClosingFollowedByDocumentSymbolRequest) {
const std::string mini_module =
DidOpenRequest("file://mini.sv", "module mini();\nendmodule\n");
ASSERT_OK(SendRequest(mini_module));
std::string discard_diagnostics = GetResponse();
// Close the file from the Language Server perspective
const absl::string_view closing_request = R"(
{
"jsonrpc":"2.0",
"method":"textDocument/didClose",
"params":{
"textDocument":{
"uri":"file://mini.sv"
}
}
})";
ASSERT_OK(SendRequest(closing_request));
// Try to request document symbol for closed file (server should return empty
// response gracefully)
const absl::string_view document_symbol_request =
R"({"jsonrpc":"2.0", "id":13, "method":"textDocument/documentSymbol","params":{"textDocument":{"uri":"file://mini.sv"}}})";
ASSERT_OK(SendRequest(document_symbol_request));
json document_symbol = json::parse(GetResponse());
EXPECT_EQ(document_symbol["id"], 13);
EXPECT_EQ(document_symbol["result"].size(), 0);
}
// Tests textDocument/documentHighlight request
TEST_F(VerilogLanguageServerTest, SymbolHighlightingTest) {
// Create sample file and make sure diagnostics do not have errors
const std::string mini_module = DidOpenRequest(
"file://sym.sv", "module sym();\nassign a=1;assign b=a+1;endmodule\n");
ASSERT_OK(SendRequest(mini_module));
const json diagnostics = json::parse(GetResponse());
EXPECT_EQ(diagnostics["method"], "textDocument/publishDiagnostics")
<< "textDocument/publishDiagnostics not received";
EXPECT_EQ(diagnostics["params"]["uri"], "file://sym.sv")
<< "Diagnostics for invalid file";
EXPECT_EQ(diagnostics["params"]["diagnostics"].size(), 0)
<< "The test file has errors";
const absl::string_view highlight_request1 =
R"({"jsonrpc":"2.0", "id":20, "method":"textDocument/documentHighlight","params":{"textDocument":{"uri":"file://sym.sv"},"position":{"line":1,"character":7}}})";
ASSERT_OK(SendRequest(highlight_request1));
const json highlight_response1 = json::parse(GetResponse());
EXPECT_EQ(highlight_response1["id"], 20);
EXPECT_EQ(highlight_response1["result"].size(), 2);
EXPECT_EQ(
highlight_response1["result"][0],
json::parse(
R"({"range":{"start":{"line":1, "character": 7}, "end":{"line":1, "character": 8}}})"));
EXPECT_EQ(
highlight_response1["result"][1],
json::parse(
R"({"range":{"start":{"line":1, "character": 20}, "end":{"line":1, "character": 21}}})"));
const absl::string_view highlight_request2 =
R"({"jsonrpc":"2.0", "id":21, "method":"textDocument/documentHighlight","params":{"textDocument":{"uri":"file://sym.sv"},"position":{"line":1,"character":2}}})";
ASSERT_OK(SendRequest(highlight_request2));
const json highlight_response2 = json::parse(GetResponse());
EXPECT_EQ(highlight_response2["id"], 21);
EXPECT_EQ(highlight_response2["result"].size(), 0);
}
// Tests structure holding data for test textDocument/rangeFormatting requests
struct FormattingRequestParams {
FormattingRequestParams(int id, int start_line, int start_character,
int end_line, int end_character,
absl::string_view new_text, int new_text_start_line,
int new_text_start_character, int new_text_end_line,
int new_text_end_character)
: id(id),
start_line(start_line),
start_character(start_character),
end_line(end_line),
end_character(end_character),
new_text(new_text),
new_text_start_line(new_text_start_line),
new_text_start_character(new_text_start_character),
new_text_end_line(new_text_end_line),
new_text_end_character(new_text_end_character) {}
int id;
int start_line;
int start_character;
int end_line;
int end_character;
absl::string_view new_text;
int new_text_start_line;
int new_text_start_character;
int new_text_end_line;
int new_text_end_character;
};
// Creates a textDocument/rangeFormatting request from FormattingRequestParams
// structure
std::string FormattingRequest(absl::string_view file,
const FormattingRequestParams ¶ms) {
json formattingrequest = {
{"jsonrpc", "2.0"},
{"id", params.id},
{"method", "textDocument/rangeFormatting"},
{"params",
{{"textDocument", {{"uri", file}}},
{"range",
{
{"start",
{{"line", params.start_line},
{"character", params.start_character}}},
{"end",
{{"line", params.end_line}, {"character", params.end_character}}},
}}}}};
return formattingrequest.dump();
}
// Runs tests for textDocument/rangeFormatting requests
TEST_F(VerilogLanguageServerTest, RangeFormattingTest) {
// Create sample file and make sure diagnostics do not have errors
const std::string mini_module = DidOpenRequest(
"file://fmt.sv", "module fmt();\nassign a=1;\nassign b=2;endmodule\n");
ASSERT_OK(SendRequest(mini_module));
const json diagnostics = json::parse(GetResponse());
EXPECT_EQ(diagnostics["method"], "textDocument/publishDiagnostics")
<< "textDocument/publishDiagnostics not received";
EXPECT_EQ(diagnostics["params"]["uri"], "file://fmt.sv")
<< "Diagnostics for invalid file";
EXPECT_EQ(diagnostics["params"]["diagnostics"].size(), 0)
<< "The test file has errors";
const std::vector<FormattingRequestParams> formatting_params{
{30, 1, 0, 2, 0, " assign a=1;\n", 1, 0, 2, 0},
{31, 1, 0, 1, 1, " assign a=1;\n", 1, 0, 2, 0},
{32, 2, 0, 2, 1, " assign b=2;\nendmodule\n", 2, 0, 3, 0},
{33, 1, 0, 3, 0, " assign a = 1;\n assign b = 2;\nendmodule\n", 1, 0, 3,
0}};
for (const auto ¶ms : formatting_params) {
const std::string request = FormattingRequest("file://fmt.sv", params);
ASSERT_OK(SendRequest(request));
const json response = json::parse(GetResponse());
EXPECT_EQ(response["id"], params.id) << "Invalid id";
EXPECT_EQ(response["result"].size(), 1)
<< "Invalid result size for id: " << params.id;
EXPECT_EQ(std::string(response["result"][0]["newText"]), params.new_text)
<< "Invalid patch for id: " << params.id;
EXPECT_EQ(response["result"][0]["range"]["start"]["line"],
params.new_text_start_line)
<< "Invalid range for id: " << params.id;
EXPECT_EQ(response["result"][0]["range"]["start"]["character"],
params.new_text_start_character)
<< "Invalid range for id: " << params.id;
EXPECT_EQ(response["result"][0]["range"]["end"]["line"],
params.new_text_end_line)
<< "Invalid range for id: " << params.id;
EXPECT_EQ(response["result"][0]["range"]["end"]["character"],
params.new_text_end_character)
<< "Invalid range for id: " << params.id;
}
}
// Runs test of entire document formatting with textDocument/formatting request
TEST_F(VerilogLanguageServerTest, FormattingTest) {
// Create sample file and make sure diagnostics do not have errors
const std::string mini_module = DidOpenRequest(
"file://fmt.sv", "module fmt();\nassign a=1;\nassign b=2;endmodule\n");
ASSERT_OK(SendRequest(mini_module));
const json diagnostics = json::parse(GetResponse());
EXPECT_EQ(diagnostics["method"], "textDocument/publishDiagnostics")
<< "textDocument/publishDiagnostics not received";
EXPECT_EQ(diagnostics["params"]["uri"], "file://fmt.sv")
<< "Diagnostics for invalid file";
EXPECT_EQ(diagnostics["params"]["diagnostics"].size(), 0)
<< "The test file has errors";
const absl::string_view formatting_request =
R"({"jsonrpc":"2.0", "id":34, "method":"textDocument/formatting","params":{"textDocument":{"uri":"file://fmt.sv"}}})";
ASSERT_OK(SendRequest(formatting_request));
const json response = json::parse(GetResponse());
EXPECT_EQ(response["id"], 34);
EXPECT_EQ(response["result"].size(), 1);
EXPECT_EQ(std::string(response["result"][0]["newText"]),
"module fmt ();\n assign a = 1;\n assign b = 2;\nendmodule\n");
EXPECT_EQ(
response["result"][0]["range"],
json::parse(
R"({"start":{"line":0, "character": 0}, "end":{"line":3, "character": 0}})"));
}
TEST_F(VerilogLanguageServerTest, FormattingFileWithEmptyNewline_issue1667) {
const std::string fmt_module = DidOpenRequest(
"file://fmt.sv", "module fmt();\nassign a=1;\nassign b=2;endmodule");
// ---------------------------------------------------- no newline ---^
ASSERT_OK(SendRequest(fmt_module));
GetResponse(); // Ignore diagnostics.
const absl::string_view formatting_request = R"(
{"jsonrpc":"2.0", "id":1,
"method": "textDocument/formatting",
"params": {"textDocument":{"uri":"file://fmt.sv"}}})";
ASSERT_OK(SendRequest(formatting_request));
const json response = json::parse(GetResponse());
// Formatted output now has a newline at end.
EXPECT_EQ(std::string(response["result"][0]["newText"]),
"module fmt ();\n assign a = 1;\n assign b = 2;\nendmodule\n");
// Full range of original file, including the characters of the last line.
EXPECT_EQ(response["result"][0]["range"], json::parse(R"(
{"start":{"line":0, "character": 0},
"end": {"line":2, "character": 20}})"));
}
TEST_F(VerilogLanguageServerTest, FormattingFileWithSyntaxErrors_issue1843) {
// Contains syntax errors. Shouldn't crash
const std::string file_contents =
"module fmt(input logic a,);\nassign a=1;\nendmodule";
const std::string fmt_module = DidOpenRequest("file://fmt.sv", file_contents);
ASSERT_OK(SendRequest(fmt_module));
GetResponse(); // Ignore diagnostics.
const absl::string_view formatting_request = R"(
{"jsonrpc":"2.0", "id":1,
"method": "textDocument/formatting",
"params": {"textDocument":{"uri":"file://fmt.sv"}}})";
// Doesn't crash.
ASSERT_OK(SendRequest(formatting_request));
const json response = json::parse(GetResponse());
}
// Creates a request based on TextDocumentPosition parameters
std::string TextDocumentPositionBasedRequest(absl::string_view method,
absl::string_view file, int id,
int line, int character) {
verible::lsp::TextDocumentPositionParams params{
.textDocument = {.uri = {file.begin(), file.end()}},
.position = {.line = line, .character = character}};
json request = {
{"jsonrpc", "2.0"}, {"id", id}, {"method", method}, {"params", params}};
return request.dump();
}
// Creates a textDocument/definition request
std::string DefinitionRequest(absl::string_view file, int id, int line,
int character) {
return TextDocumentPositionBasedRequest("textDocument/definition", file, id,
line, character);
}
// Creates a textDocument/references request
std::string ReferencesRequest(absl::string_view file, int id, int line,
int character) {
return TextDocumentPositionBasedRequest("textDocument/references", file, id,
line, character);
}
void CheckDefinitionEntry(const json &entry, verible::LineColumn start,
verible::LineColumn end,
const std::string &file_uri) {
ASSERT_EQ(entry["range"]["start"]["line"], start.line);
ASSERT_EQ(entry["range"]["start"]["character"], start.column);
ASSERT_EQ(entry["range"]["end"]["line"], end.line);
ASSERT_EQ(entry["range"]["end"]["character"], end.column);
ASSERT_EQ(entry["uri"], file_uri);
}
// Performs assertions on textDocument/definition responses where single
// definition is expected
void CheckDefinitionResponseSingleDefinition(const json &response, int id,
verible::LineColumn start,
verible::LineColumn end,
const std::string &file_uri) {
ASSERT_EQ(response["id"], id);
ASSERT_EQ(response["result"].size(), 1);
CheckDefinitionEntry(response["result"][0], start, end, file_uri);
}
// Performs simple textDocument/definition request with no VerilogProject set
TEST_F(VerilogLanguageServerSymbolTableTest, DefinitionRequestNoProjectTest) {
std::string definition_request = DefinitionRequest("file://b.sv", 2, 3, 18);
ASSERT_OK(SendRequest(definition_request));
json response = json::parse(GetResponse());
ASSERT_EQ(response["id"], 2);
ASSERT_EQ(response["result"].size(), 0);
}
// Performs simple textDocument/definition request
TEST_F(VerilogLanguageServerSymbolTableTest, DefinitionRequestTest) {
absl::string_view filelist_content = "a.sv\n";
const verible::file::testing::ScopedTestFile filelist(
root_dir, filelist_content, "verible.filelist");
const verible::file::testing::ScopedTestFile module_a(root_dir,
kSampleModuleA, "a.sv");
const std::string module_a_uri = PathToLSPUri(module_a.filename());
const std::string module_a_open_request =
DidOpenRequest(module_a_uri, kSampleModuleA);
ASSERT_OK(SendRequest(module_a_open_request));
// obtain diagnostics
GetResponse();
// find definition for "var1" variable in a.sv file
const std::string definition_request =
DefinitionRequest(module_a_uri, 2, 2, 16);
ASSERT_OK(SendRequest(definition_request));
json response = json::parse(GetResponse());
CheckDefinitionResponseSingleDefinition(response, 2, {.line = 1, .column = 9},
{.line = 1, .column = 13},
module_a_uri);
}
// Check textDocument/definition request when there are two symbols of the same
// name (variable name), but in different modules
TEST_F(VerilogLanguageServerSymbolTableTest,
DefinitionRequestSameVariablesDifferentModules) {
absl::string_view filelist_content = "a.sv\nb.sv\n";
const verible::file::testing::ScopedTestFile filelist(
root_dir, filelist_content, "verible.filelist");
const verible::file::testing::ScopedTestFile module_a(root_dir,
kSampleModuleA, "a.sv");
const verible::file::testing::ScopedTestFile module_b(root_dir,
kSampleModuleB, "b.sv");
const std::string module_a_uri = PathToLSPUri(module_a.filename());
const std::string module_b_uri = PathToLSPUri(module_b.filename());
const std::string module_a_open_request =
DidOpenRequest(module_a_uri, kSampleModuleA);
ASSERT_OK(SendRequest(module_a_open_request));
const std::string module_b_open_request =
DidOpenRequest(module_b_uri, kSampleModuleB);
ASSERT_OK(SendRequest(module_b_open_request));
// obtain diagnostics for both files
GetResponse();
// find definition for "var1" variable in b.sv file
std::string definition_request = DefinitionRequest(module_b_uri, 2, 2, 16);
ASSERT_OK(SendRequest(definition_request));
json response_b = json::parse(GetResponse());
CheckDefinitionResponseSingleDefinition(
response_b, 2, {.line = 1, .column = 9}, {.line = 1, .column = 13},
module_b_uri);
// find definition for "var1" variable in a.sv file
const std::string definition_request2 =
DefinitionRequest(module_a_uri, 3, 2, 16);
ASSERT_OK(SendRequest(definition_request2));
json response_a = json::parse(GetResponse());
CheckDefinitionResponseSingleDefinition(
response_a, 3, {.line = 1, .column = 9}, {.line = 1, .column = 13},
module_a_uri);
}
// Check textDocument/definition request where we want definition of a symbol
// inside other module edited in buffer
TEST_F(VerilogLanguageServerSymbolTableTest,
DefinitionRequestSymbolFromDifferentOpenedModule) {
absl::string_view filelist_content = "a.sv\nb.sv\n";
const verible::file::testing::ScopedTestFile filelist(
root_dir, filelist_content, "verible.filelist");
const verible::file::testing::ScopedTestFile module_a(root_dir,
kSampleModuleA, "a.sv");
const verible::file::testing::ScopedTestFile module_b(root_dir,
kSampleModuleB, "b.sv");
const std::string module_a_uri = PathToLSPUri(module_a.filename());
const std::string module_b_uri = PathToLSPUri(module_b.filename());
const std::string module_a_open_request =
DidOpenRequest(module_a_uri, kSampleModuleA);
ASSERT_OK(SendRequest(module_a_open_request));
const std::string module_b_open_request =
DidOpenRequest(module_b_uri, kSampleModuleB);
ASSERT_OK(SendRequest(module_b_open_request));
// obtain diagnostics for both files
GetResponse();
// find definition for "var1" variable in b.sv file
const std::string definition_request =
DefinitionRequest(module_b_uri, 2, 4, 14);
ASSERT_OK(SendRequest(definition_request));
json response_b = json::parse(GetResponse());
CheckDefinitionResponseSingleDefinition(
response_b, 2, {.line = 1, .column = 9}, {.line = 1, .column = 13},
module_a_uri);
}
// Check textDocument/definition request where we want definition of a symbol
// inside other module that is not edited in buffer
TEST_F(VerilogLanguageServerSymbolTableTest,
DefinitionRequestSymbolFromDifferentNotOpenedModule) {
absl::string_view filelist_content = "a.sv\nb.sv\n";
const verible::file::testing::ScopedTestFile filelist(
root_dir, filelist_content, "verible.filelist");
const verible::file::testing::ScopedTestFile module_a(root_dir,
kSampleModuleA, "a.sv");
const verible::file::testing::ScopedTestFile module_b(root_dir,
kSampleModuleB, "b.sv");
const std::string module_a_uri = PathToLSPUri(module_a.filename());
const std::string module_b_uri = PathToLSPUri(module_b.filename());
const std::string module_b_open_request =
DidOpenRequest(module_b_uri, kSampleModuleB);
ASSERT_OK(SendRequest(module_b_open_request));
// obtain diagnostics for both files
GetResponse();
// find definition for "var1" variable in b.sv file
const std::string definition_request =
DefinitionRequest(module_b_uri, 2, 4, 14);
ASSERT_OK(SendRequest(definition_request));
json response_b = json::parse(GetResponse());
CheckDefinitionResponseSingleDefinition(
response_b, 2, {.line = 1, .column = 9}, {.line = 1, .column = 13},
module_a_uri);
}
// Check textDocument/definition request where we want definition of a symbol
// inside other module which was opened and closed
TEST_F(VerilogLanguageServerSymbolTableTest,
DefinitionRequestSymbolFromDifferentOpenedAndClosedModule) {
absl::string_view filelist_content = "a.sv\nb.sv\n";
const verible::file::testing::ScopedTestFile filelist(
root_dir, filelist_content, "verible.filelist");
const verible::file::testing::ScopedTestFile module_a(root_dir,
kSampleModuleA, "a.sv");
const verible::file::testing::ScopedTestFile module_b(root_dir,
kSampleModuleB, "b.sv");
const std::string module_a_uri = PathToLSPUri(module_a.filename());
const std::string module_b_uri = PathToLSPUri(module_b.filename());
const std::string module_a_open_request =
DidOpenRequest(module_a_uri, kSampleModuleA);
ASSERT_OK(SendRequest(module_a_open_request));
const std::string module_b_open_request =
DidOpenRequest(module_b_uri, kSampleModuleB);
ASSERT_OK(SendRequest(module_b_open_request));
// Close a.sv from the Language Server perspective
const std::string closing_request = json{
//
{"jsonrpc", "2.0"},
{"method", "textDocument/didClose"},
{"params",
{{"textDocument",
{
{"uri", module_a_uri},
}}}}}.dump();
ASSERT_OK(SendRequest(closing_request));
// obtain diagnostics for both files
GetResponse();
// find definition for "var1" variable of a module in b.sv file
const std::string definition_request =
DefinitionRequest(module_b_uri, 2, 4, 14);
ASSERT_OK(SendRequest(definition_request));
json response_b = json::parse(GetResponse());
CheckDefinitionResponseSingleDefinition(
response_b, 2, {.line = 1, .column = 9}, {.line = 1, .column = 13},
module_a_uri);
// perform double check
ASSERT_OK(SendRequest(definition_request));
response_b = json::parse(GetResponse());
CheckDefinitionResponseSingleDefinition(
response_b, 2, {.line = 1, .column = 9}, {.line = 1, .column = 13},
module_a_uri);
}
// Check textDocument/definition request where we want definition of a symbol
// when there are incorrect files in the project
TEST_F(VerilogLanguageServerSymbolTableTest,
DefinitionRequestInvalidFileInWorkspace) {
absl::string_view filelist_content = "a.sv\nb.sv\n";
static constexpr absl::string_view //
sample_module_b_with_error(
R"(module b;
assign var1 = 1'b0;
assigne var2 = var1 | 1'b1;
a vara;
assign vara.var1 = 1'b1;
endmodule
)");
const verible::file::testing::ScopedTestFile filelist(
root_dir, filelist_content, "verible.filelist");
const verible::file::testing::ScopedTestFile module_a(root_dir,
kSampleModuleA, "a.sv");
const verible::file::testing::ScopedTestFile module_b(
root_dir, sample_module_b_with_error, "b.sv");
const std::string module_a_uri = PathToLSPUri(module_a.filename());
const std::string module_b_uri = PathToLSPUri(module_b.filename());
const std::string module_a_open_request =
DidOpenRequest(module_a_uri, kSampleModuleA);
ASSERT_OK(SendRequest(module_a_open_request));
// obtain diagnostics for both files
GetResponse();
// find definition for "var1" variable in a.sv file
const std::string definition_request =
DefinitionRequest(module_a_uri, 2, 2, 16);
ASSERT_OK(SendRequest(definition_request));
json response = json::parse(GetResponse());
CheckDefinitionResponseSingleDefinition(response, 2, {.line = 1, .column = 9},
{.line = 1, .column = 13},
module_a_uri);
}
// Check textDocument/definition request where we want definition of a symbol
// inside incorrect file
TEST_F(VerilogLanguageServerSymbolTableTest, DefinitionRequestInInvalidFile) {
absl::string_view filelist_content = "a.sv\nb.sv\n";
static constexpr absl::string_view //
sample_module_b_with_error(
R"(module b;
assign var1 = 1'b0;
assigne var2 = var1 | 1'b1;
a vara;
assign vara.var1 = 1'b1;
endmodule
)");