SILICON
Loading...
Searching...
No Matches
verilog.cpp
Go to the documentation of this file.
1/*
2 Copyright (c) 2026. Giulio Cocconi
3
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>.
16 */
17
20
21#include <array>
22#include <regex>
23#include <string>
24
25namespace SILICON::ui {
26namespace {
27
36
37 // Adapted from Vim's runtime/syntax/verilog.vim.
38 constexpr auto STATEMENT_WORDS = std::to_array<std::string_view>({
39 std::string_view{"always"},
40 "and",
41 "assign",
42 "automatic",
43 "buf",
44 "bufif0",
45 "bufif1",
46 "cell",
47 "cmos",
48 "config",
49 "deassign",
50 "defparam",
51 "design",
52 "disable",
53 "edge",
54 "endconfig",
55 "endfunction",
56 "endgenerate",
57 "endmodule",
58 "endprimitive",
59 "endspecify",
60 "endtable",
61 "endtask",
62 "event",
63 "force",
64 "function",
65 "generate",
66 "genvar",
67 "highz0",
68 "highz1",
69 "ifnone",
70 "incdir",
71 "include",
72 "initial",
73 "inout",
74 "input",
75 "instance",
76 "integer",
77 "large",
78 "liblist",
79 "library",
80 "localparam",
81 "macromodule",
82 "medium",
83 "module",
84 "nand",
85 "negedge",
86 "nmos",
87 "nor",
88 "noshowcancelled",
89 "not",
90 "notif0",
91 "notif1",
92 "or",
93 "output",
94 "parameter",
95 "pmos",
96 "posedge",
97 "primitive",
98 "pull0",
99 "pull1",
100 "pulldown",
101 "pullup",
102 "pulsestyle_onevent",
103 "pulsestyle_ondetect",
104 "rcmos",
105 "real",
106 "realtime",
107 "reg",
108 "release",
109 "rnmos",
110 "rpmos",
111 "rtran",
112 "rtranif0",
113 "rtranif1",
114 "scalared",
115 "showcancelled",
116 "signed",
117 "small",
118 "specify",
119 "specparam",
120 "strong0",
121 "strong1",
122 "supply0",
123 "supply1",
124 "table",
125 "task",
126 "time",
127 "tran",
128 "tranif0",
129 "tranif1",
130 "tri",
131 "tri0",
132 "tri1",
133 "triand",
134 "trior",
135 "trireg",
136 "unsigned",
137 "use",
138 "vectored",
139 "wait",
140 "wand",
141 "weak0",
142 "weak1",
143 "wire",
144 "wor",
145 "xnor",
146 "xor",
147 });
148
149 constexpr auto LABEL_WORDS =
150 std::to_array<std::string_view>({"begin", "end", "fork", "join"});
151 constexpr auto CONDITIONAL_WORDS = std::to_array<std::string_view>(
152 {"if", "else", "case", "casex", "casez", "default", "endcase"});
153 constexpr auto REPEAT_WORDS =
154 std::to_array<std::string_view>({"forever", "repeat", "while", "for"});
155
156 constexpr std::array KEYWORD_GROUPS{
161 };
162
163 constexpr std::array TODO_RULES{CodeSyntaxContainedRule{
164 CodeSyntaxStyle::Todo, R"((?<![A-Za-z0-9_?])(?:TODO|FIXME)(?![A-Za-z0-9_?]))"}};
165 constexpr std::array ESCAPE_RULES{
166 CodeSyntaxContainedRule{CodeSyntaxStyle::Escape, R"(\\‍(?:[nt"\\‍]|[0-7]{1,3}))"}};
167
168 constexpr std::array MATCH_RULES{
170 CodeSyntaxStyle::Operator, R"([&|~><!)(*#%@+/=?:;}{,.^\-\‍[\‍]])", {}},
172 R"((?<![A-Za-z0-9_?])[A-Z][A-Z0-9_]+(?![A-Za-z0-9_?]))",
173 {}},
176 R"((?<![A-Za-z0-9_?])(?:[0-9]+)?'[sS]?[bB]\s*[0-1_xXzZ?]+(?![A-Za-z0-9_?]))",
177 {}},
180 R"((?<![A-Za-z0-9_?])(?:[0-9]+)?'[sS]?[oO]\s*[0-7_xXzZ?]+(?![A-Za-z0-9_?]))",
181 {}},
184 R"((?<![A-Za-z0-9_?])(?:[0-9]+)?'[sS]?[dD]\s*[0-9_xXzZ?]+(?![A-Za-z0-9_?]))",
185 {}},
188 R"((?<![A-Za-z0-9_?])(?:[0-9]+)?'[sS]?[hH]\s*[0-9a-fA-F_xXzZ?]+(?![A-Za-z0-9_?]))",
189 {}},
192 R"((?<![A-Za-z0-9_?])[+-]?[0-9_]+(?:\.[0-9_]*)?(?:e[0-9_]*)?(?![A-Za-z0-9_?]))",
193 {}},
196 R"(`(?:celldefine|default_nettype|define|else|elsif|endcelldefine|endif|ifdef|ifndef|include|line|nounconnected_drive|resetall|timescale|unconnected_drive|undef)(?![A-Za-z0-9_?]))",
197 {}},
198 CodeSyntaxMatchRule{CodeSyntaxStyle::Global, R"(\$[A-Za-z0-9_]+\b)", {}},
199 };
200
201 // More specific regions precede their generic comment counterparts so ties at
202 // the same start position resolve like Vim's contained syntax groups.
203 constexpr std::array REGION_RULES{
205 R"(//\s*synopsys dc_script_begin\b)",
206 R"(//\s*synopsys dc_script_end\b)",
207 {},
208 {},
209 true},
211 R"(//\s*\$s dc_script_begin\b)",
212 R"(//\s*\$s dc_script_end\b)",
213 {},
214 {},
215 true},
217 CodeSyntaxStyle::Directive, R"(/\*\s*synopsys\b)", R"(\*/)", {}, {}, true},
219 CodeSyntaxStyle::Directive, R"(/\*\s*\$s\b)", R"(\*/)", {}, {}, true},
221 CodeSyntaxStyle::Directive, R"(//\s*synopsys\b)", R"($)", {}, {}, false},
223 CodeSyntaxStyle::Directive, R"(//\s*\$s\b)", R"($)", {}, {}, false},
225 CodeSyntaxStyle::Comment, R"(/\*)", R"(\*/)", {}, TODO_RULES, true},
227 CodeSyntaxStyle::Comment, R"(//)", R"($)", {}, TODO_RULES, false},
228 CodeSyntaxRegionRule{CodeSyntaxStyle::String, R"(")", R"(")", R"(\\.)", ESCAPE_RULES,
229 false},
230 };
231
232 [[nodiscard]] bool startsWithBlockStatement(const std::string_view code)
233 {
234 static const std::regex expression(
235 R"(^\s*(?:(?:end)\s+)?(?:if|else)\b|^\s*(?:for|case|casex|casez|always|initial|specify|fork)\b)",
236 std::regex::optimize);
237 return regexSearch(code, expression);
238 }
239
240 [[nodiscard]] bool startsWithDeclarationBlock(const std::string_view code)
241 {
242 static const std::regex expression(
243 R"(^\s*(?:function|task|config|generate|primitive|table)\b)",
244 std::regex::optimize);
245 return regexSearch(code, expression);
246 }
247
248 [[nodiscard]] bool startsWithModule(const std::string_view code)
249 {
250 static const std::regex expression(R"(^\s*module\b)", std::regex::optimize);
251 return regexSearch(code, expression);
252 }
253
254 [[nodiscard]] bool startsWithEndModule(const std::string_view code)
255 {
256 static const std::regex expression(R"(^\s*endmodule\b)", std::regex::optimize);
257 return regexSearch(code, expression);
258 }
259
260 [[nodiscard]] bool startsWithPreprocessorBranch(const std::string_view code)
261 {
262 static const std::regex expression(R"(^\s*`(?:ifdef|ifndef|elsif|else)\b)",
263 std::regex::optimize);
264 return regexSearch(code, expression);
265 }
266
267 [[nodiscard]] bool startsWithPreprocessorCloser(const std::string_view code)
268 {
269 static const std::regex expression(R"(^\s*`(?:elsif|else|endif)\b)",
270 std::regex::optimize);
271 return regexSearch(code, expression);
272 }
273
274 [[nodiscard]] bool startsWithBlockCloser(const std::string_view code)
275 {
276 static const std::regex expression(
277 R"(^\s*(?:join|end|endcase|endfunction|endtask|endspecify|endconfig|endgenerate|endprimitive|endtable)\b)",
278 std::regex::optimize);
279 return regexSearch(code, expression);
280 }
281
282 [[nodiscard]] bool startsWithStandaloneBegin(const std::string_view code)
283 {
284 static const std::regex expression(R"(^\s*begin\b)", std::regex::optimize);
285 return regexSearch(code, expression);
286 }
287
288 [[nodiscard]] bool containsBegin(const std::string_view code)
289 {
290 static const std::regex expression(R"(\bbegin\b)", std::regex::optimize);
291 return regexSearch(code, expression);
292 }
293
294 [[nodiscard]] bool endsWithBegin(const std::string_view code)
295 {
296 static const std::regex expression(R"(\bbegin\b(?:\s*:\s*\w+)?\s*$)",
297 std::regex::optimize);
298 return regexSearch(code, expression);
299 }
300
301 [[nodiscard]] bool isTerminatedBlockStatement(const std::string_view code)
302 {
303 const auto trimmed = trimRight(code);
304 return trimmed.ends_with(';') || endsWithWord(trimmed, "end");
305 }
306
307 [[nodiscard]] bool isOpenStatement(const std::string_view code)
308 {
309 const auto trimmed = trimRight(code);
310 if (trimmed.empty())
311 return false;
312 if (endsWithWord(trimmed, "or"))
313 return true;
314 constexpr std::string_view OPEN_CHARACTERS = "*(,{><+-/%^&|!=?:";
315 return OPEN_CHARACTERS.contains(trimmed.back());
316 }
317
318 [[nodiscard]] bool isCaseLabel(const std::string_view code)
319 {
320 static const std::regex expression(R"(^\s*[^=!]+\s*:\s*$)", std::regex::optimize);
321 return regexSearch(code, expression);
322 }
323
324 [[nodiscard]] bool closesMultilineStatement(const std::string_view code)
325 {
326 const auto trimmed = trimRight(code);
327 if (!trimmed.ends_with(';'))
328 return false;
329 const auto beforeSemicolon = trimRight(trimmed.substr(0, trimmed.size() - 1));
330 return !beforeSemicolon.empty();
331 }
332
333 [[nodiscard]] bool isOnlyClosingStatement(const std::string_view code)
334 {
335 static const std::regex expression(R"(^\s*\)*\s*;?\s*$)", std::regex::optimize);
336 return std::regex_match(code.begin(), code.end(), expression);
337 }
338
339 [[nodiscard]] bool closesMultilineComment(const std::string_view line)
340 {
341 const auto trimmed = trimRight(line);
342 if (!trimmed.ends_with("*/"))
343 return false;
344 const auto closing = trimmed.rfind("*/");
345 const auto opening = trimmed.rfind("/*", closing);
346 return opening == std::string_view::npos;
347 }
348
349 [[nodiscard]] std::string verilogIndentationFor(const CodeIndentationContext& context)
350 {
351 if (context.previousNonBlankLines.empty())
352 return {};
353
354 const auto previousLine = context.previousNonBlankLines[0];
355 const auto olderLine = context.previousNonBlankLines.size() > 1
356 ? context.previousNonBlankLines[1]
357 : std::string_view{};
358 static const std::regex strippedPortions(
359 R"(//.*|/\*.*?(?:\*/|$)|"(?:\\.|[^"\\‍])*(?:"|$))", std::regex::optimize);
360 const auto previousCode = codePortion(previousLine, strippedPortions);
361 const auto olderCode = codePortion(olderLine, strippedPortions);
362 const auto currentCode = codePortion(context.currentLine, strippedPortions);
363 auto indentation = leadingWhitespace(previousLine);
364
365 // Keep this branch order aligned with Vim's GetVerilogIndent(): the first
366 // matching previous-line rule wins.
367 if (closesMultilineComment(previousLine)) {
368 if (!indentation.empty() && indentation.back() == ' ')
369 indentation.pop_back();
370 } else if (startsWithBlockStatement(previousCode)) {
371 if (!isTerminatedBlockStatement(previousCode))
372 addIndentLevel(indentation, context.indentWidth);
373 } else if (startsWithDeclarationBlock(previousCode)) {
374 if (!endsWithWord(previousCode, "end"))
375 addIndentLevel(indentation, context.indentWidth);
376 } else if (startsWithModule(previousCode)) {
377 const auto trimmed = trimRight(previousCode);
378 if (!trimmed.empty() && (trimmed.back() == '(' || trimmed.back() == ','))
379 addIndentLevel(indentation, context.indentWidth);
380 } else if (endsWithBegin(previousCode)
381 && (!isOpenStatement(olderCode) || isCaseLabel(olderCode))) {
382 addIndentLevel(indentation, context.indentWidth);
383 } else if (!containsBegin(previousCode) && startsWithBlockStatement(olderCode)
384 && !isOpenStatement(olderCode) && !containsBegin(olderCode)) {
385 removeIndentLevel(indentation, context.indentWidth);
386 } else if (isOpenStatement(previousCode) && !isOpenStatement(olderCode)) {
387 addIndentLevel(indentation, context.indentWidth);
388 } else if (closesMultilineStatement(previousCode)
389 && !isOnlyClosingStatement(previousCode) && isOpenStatement(olderCode)
390 && !trimLeft(olderCode).empty()) {
391 removeIndentLevel(indentation, context.indentWidth);
392 } else if (startsWithPreprocessorBranch(previousCode)) {
393 addIndentLevel(indentation, context.indentWidth);
394 }
395
396 // Current-line corrections mirror Vim's indentkeys-triggered reindent pass.
397 if (startsWithBlockCloser(currentCode)) {
398 removeIndentLevel(indentation, context.indentWidth);
399 } else if (startsWithEndModule(currentCode)) {
400 // Module indentation is deliberately disabled, matching Vim's default.
401 } else if (startsWithStandaloneBegin(currentCode)) {
402 const bool previousStartsDeclaration =
403 startsWithDeclarationBlock(previousCode) || startsWithModule(previousCode)
404 || regexSearch(previousCode,
405 std::regex(R"(^\s*specify\b)", std::regex::optimize));
406 if (!previousStartsDeclaration && !isOnlyClosingStatement(previousCode)
407 && (startsWithBlockStatement(previousCode)
408 || trimRight(previousCode).ends_with(')')
409 || isOpenStatement(previousCode))) {
410 removeIndentLevel(indentation, context.indentWidth);
411 }
412 } else if (trimLeft(currentCode).starts_with(')')
413 && (isOpenStatement(previousCode) || isOpenStatement(olderCode))) {
414 removeIndentLevel(indentation, context.indentWidth);
415 } else if (startsWithPreprocessorCloser(currentCode)) {
416 removeIndentLevel(indentation, context.indentWidth);
417 }
418
419 return indentation;
420 }
421
422 constexpr auto INDENTATION_TRIGGER_PATTERNS = std::to_array<std::string_view>({
423 std::string_view{
424 R"((?<![A-Za-z0-9_?])(?:begin|end|join|endcase|endmodule|endfunction|endtask|endspecify|endconfig|endgenerate|endprimitive|endtable)\s*$)"},
425 R"(^\s*\))",
426 R"(^\s*`(?:else|elsif|endif)\b)",
427 });
428
429 constexpr CodeIndentation VERILOG_INDENTATION{
430 .indentationFor = verilogIndentationFor,
431 .triggerPatterns = INDENTATION_TRIGGER_PATTERNS,
432 .indentWidth = 2,
433 };
434
435} // namespace
436
438 .keywordGroups = KEYWORD_GROUPS,
439 .matchRules = MATCH_RULES,
440 .regionRules = REGION_RULES,
441 .extraWordCharacters = "?",
442 .indentation = &VERILOG_INDENTATION,
443};
444
445} // namespace SILICON::ui
std::string leadingWhitespace(const std::string_view line)
std::string_view trimRight(std::string_view value)
bool endsWithWord(const std::string_view value, const std::string_view word)
std::string_view trimLeft(std::string_view value)
bool regexSearch(const std::string_view value, const std::regex &expression)
void addIndentLevel(std::string &indentation, const int indentWidth)
std::string codePortion(const std::string_view line, const std::regex &strippedPortions)
void removeIndentLevel(std::string &indentation, const int indentWidth)
std::string leadingWhitespace(const std::string_view line)
std::string_view trimRight(std::string_view value)
bool endsWithWord(const std::string_view value, const std::string_view word)
std::string_view trimLeft(std::string_view value)
bool regexSearch(const std::string_view value, const std::regex &expression)
void addIndentLevel(std::string &indentation, const int indentWidth)
const CodeSyntax VERILOG_CODE_SYNTAX
Definition verilog.cpp:437
std::string codePortion(const std::string_view line, const std::regex &strippedPortions)
void removeIndentLevel(std::string &indentation, const int indentWidth)