0.5.4
C++ to UML diagram generator based on Clang
Loading...
Searching...
No Matches
generator.h
Go to the documentation of this file.
1/**
2 * @file src/common/generators/plantuml/generator.h
3 *
4 * Copyright (c) 2021-2024 Bartek Kryza <bkryza@gmail.com>
5 *
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 */
18#pragma once
19
23#include "config/config.h"
24#include "util/util.h"
25#include "version.h"
26
27#include <clang/Basic/Version.h>
28#include <clang/Frontend/CompilerInstance.h>
29#include <clang/Tooling/CompilationDatabase.h>
30#include <clang/Tooling/Tooling.h>
31#include <glob/glob.hpp>
32#include <inja/inja.hpp>
33
35
40
41std::string to_plantuml(const relationship &r, const config::diagram &cfg);
42std::string to_plantuml(access_t scope);
43std::string to_plantuml(message_t r);
44
45/**
46 * @brief Base class for diagram generators
47 *
48 * @tparam ConfigType Configuration type
49 * @tparam DiagramType Diagram model type
50 */
51template <typename ConfigType, typename DiagramType>
53 : public clanguml::common::generators::generator<ConfigType, DiagramType> {
54public:
55 /**
56 * @brief Constructor
57 *
58 * @param config Reference to instance of @link clanguml::config::diagram
59 * @param model Reference to instance of @link clanguml::model::diagram
60 */
61 generator(ConfigType &config, DiagramType &model)
62 : clanguml::common::generators::generator<ConfigType, DiagramType>{
64 {
65 }
66
67 ~generator() override = default;
68
69 /**
70 * @brief Generate diagram
71 *
72 * This is the main diagram generation entrypoint. It is responsible for
73 * calling other methods in appropriate order to generate the diagram into
74 * the output stream. It generates diagram elements, that are common
75 * to all types of diagrams in a given generator.
76 *
77 * @param ostr Output stream
78 */
79 void generate(std::ostream &ostr) const override;
80
81 /**
82 * @brief Generate diagram specific part
83 *
84 * This method must be implemented in subclasses for specific diagram
85 * types.
86 *
87 * @param ostr Output stream
88 */
89 virtual void generate_diagram(std::ostream &ostr) const = 0;
90
91 /**
92 * @brief Generate diagram layout hints
93 *
94 * This method adds to the diagram any layout hints that were provided
95 * in the configuration file.
96 *
97 * @param ostr Output stream
98 */
99 void generate_config_layout_hints(std::ostream &ostr) const;
100
101 /**
102 * @brief Generate PlantUML directives from config file.
103 *
104 * This method renders the PlantUML directives provided in the configuration
105 * file, including resolving any element aliases and Jinja templates.
106 *
107 * @param ostr Output stream
108 * @param directives List of directives from the configuration file
109 */
111 std::ostream &ostr, const std::vector<std::string> &directives) const;
112
113 /**
114 * @brief Generate diagram notes
115 *
116 * This method adds any notes in the diagram, which were declared in the
117 * code using inline directives
118 *
119 * @param ostr Output stream
120 * @param element Element to which the note should be attached
121 */
122 void generate_notes(
123 std::ostream &ostr, const model::element &element) const;
124
125 /**
126 * @brief Generate diagram element PlantUML style
127 *
128 * This method renders a style for a specific `el` element if specified
129 * in the config file or inline comment directive.
130 *
131 * @param ostr Output stream
132 * @param element_type Name of the element type (e.g. "class")
133 * @param el Reference to a stylable diagram element
134 */
135 void generate_style(std::ostream &ostr, const std::string &element_type,
136 const model::stylable_element &el) const;
137
138 /**
139 * @brief Generate comment with diagram metadata
140 *
141 * @param ostr Output stream
142 */
143 void generate_metadata(std::ostream &ostr) const;
144
145 /**
146 * @brief Generate diagram title
147 *
148 * Generates a PlantUML diagram title directive if diagram title
149 * is provided in the diagram configuration.
150 *
151 * @param ostr Output stream
152 */
153 void generate_title(std::ostream &ostr) const;
154
155 /**
156 * @brief Generate hyper link to element
157 *
158 * This method renders links to URL's based on templates provided
159 * in the configuration file (e.g. Git browser with specific line and
160 * column offset)
161 *
162 * @param ostr Output stream
163 * @param e Reference to diagram element
164 * @tparam E Diagram element type
165 */
166 template <typename E>
167 void generate_link(std::ostream &ostr, const E &e) const;
168
169 /**
170 * @brief Print debug information in diagram comments
171 *
172 * @param m Diagram element to describe
173 * @param ostr Output stream
174 */
175 void print_debug(
176 const common::model::source_location &e, std::ostream &ostr) const;
177
178private:
179 void generate_row_column_hints(std::ostream &ostr,
180 const std::string &entity_name, const config::layout_hint &hint) const;
181
182 void generate_position_hints(std::ostream &ostr,
183 const std::string &entity_name, const config::layout_hint &hint) const;
184
185protected:
186 mutable std::set<std::string> m_generated_aliases;
187};
188
189template <typename C, typename D>
190void generator<C, D>::generate(std::ostream &ostr) const
191{
192 const auto &config = generators::generator<C, D>::config();
193 const auto &model = generators::generator<C, D>::model();
194
196
197 if (!config.allow_empty_diagrams() && model.is_empty() &&
198 config.puml().before.empty() && config.puml().after.empty()) {
200 "Diagram configuration resulted in empty diagram."};
201 }
202
203 ostr << "@startuml" << '\n';
204
205 generate_title(ostr);
206
207 // Generate PlantUML directives before auto generated content
208 generate_plantuml_directives(ostr, config.puml().before);
209
210 generate_diagram(ostr);
211
212 // Generate PlantUML directives after auto generated content
213 generate_plantuml_directives(ostr, config.puml().after);
214
215 generate_metadata(ostr);
216
217 ostr << "@enduml" << '\n';
218}
219
220template <typename C, typename D>
222{
223 using namespace clanguml::util;
224
225 const auto &config = generators::generator<C, D>::config();
226
227 // Generate layout hints
228 for (const auto &[entity_name, hints] : config.layout()) {
229 for (const auto &hint : hints) {
230 try {
231 if (hint.hint == config::hint_t::together) {
232 // 'together' layout hint is handled separately
233 }
234 else if (hint.hint == config::hint_t::row ||
235 hint.hint == config::hint_t::column) {
236 generate_row_column_hints(ostr, entity_name, hint);
237 }
238 else {
239 generate_position_hints(ostr, entity_name, hint);
240 }
241 }
243 LOG_DBG("=== Skipping layout hint '{}' from {} due "
244 "to: {}",
245 to_string(hint.hint), entity_name, e.what());
246 }
247 }
248 }
249}
250
251template <typename C, typename D>
253 const std::string &entity_name, const config::layout_hint &hint) const
254{
255 const auto &config = generators::generator<C, D>::config();
256 const auto &model = generators::generator<C, D>::model();
257
258 const auto &uns = config.using_namespace();
259
260 std::vector<std::string> group_elements;
261 std::vector<std::pair<std::string, std::string>> element_aliases_pairs;
262
263 group_elements.push_back(entity_name);
264 const auto &group_tail = std::get<std::vector<std::string>>(hint.entity);
265 std::copy(group_tail.begin(), group_tail.end(),
266 std::back_inserter(group_elements));
267
268 auto element_opt = model.get(entity_name);
269 if (!element_opt)
270 element_opt = model.get((uns | entity_name).to_string());
271
272 for (auto it = cbegin(group_elements);
273 it != cend(group_elements) && std::next(it) != cend(group_elements);
274 ++it) {
275 const auto &first = *it;
276 const auto &second = *std::next(it);
277
278 auto first_opt = model.get(first);
279 if (!first_opt)
280 first_opt = model.get((uns | first).to_string());
281
282 auto second_opt = model.get(second);
283 if (!second_opt)
284 second_opt = model.get((uns | second).to_string());
285
286 element_aliases_pairs.emplace_back(
287 first_opt.value().alias(), second_opt.value().alias());
288 }
289
290 std::string hint_direction =
291 hint.hint == clanguml::config::hint_t::row ? "right" : "down";
292
293 for (const auto &[f, s] : element_aliases_pairs) {
294 ostr << f << " -[hidden]" << hint_direction << "- " << s << '\n';
295 }
296}
297
298template <typename C, typename D>
300 const std::string &entity_name, const config::layout_hint &hint) const
301{
302 const auto &config = generators::generator<C, D>::config();
303 const auto &model = generators::generator<C, D>::model();
304
305 const auto &uns = config.using_namespace();
306
307 const auto &hint_entity = std::get<std::string>(hint.entity);
308
309 auto element_opt = model.get(entity_name);
310 if (!element_opt)
311 element_opt = model.get((uns | entity_name).to_string());
312
313 auto hint_element_opt = model.get(hint_entity);
314 if (!hint_element_opt)
315 hint_element_opt = model.get((uns | hint_entity).to_string());
316
317 if (!element_opt || !hint_element_opt)
318 return;
319
320 std::stringstream hint_str;
321
322 hint_str << element_opt.value().alias() << " -[hidden]"
323 << clanguml::config::to_string(hint.hint) << "- "
324 << hint_element_opt.value().alias() << '\n';
325
326 ostr << hint_str.str();
327}
328
329template <typename C, typename D>
331 std::ostream &ostr, const std::vector<std::string> &directives) const
332{
333 const auto &config = generators::generator<C, D>::config();
334 const auto &model = generators::generator<C, D>::model();
335
337
338 for (const auto &d : directives) {
339 try {
340 // Render the directive with template engine first
341 std::string directive{generators::generator<C, D>::env().render(
342 std::string_view{d}, generators::generator<C, D>::context())};
343
344 // Now search for alias `@A()` directives in the text
345 // (this is deprecated)
346 std::tuple<std::string, size_t, size_t> alias_match;
347 while (util::find_element_alias(directive, alias_match)) {
348 const auto full_name =
349 config.using_namespace() | std::get<0>(alias_match);
350 auto element_opt = model.get(full_name.to_string());
351
352 if (element_opt)
353 directive.replace(std::get<1>(alias_match),
354 std::get<2>(alias_match), element_opt.value().alias());
355 else {
356 LOG_WARN("Cannot find clang-uml alias for element {}",
357 full_name.to_string());
358 directive.replace(std::get<1>(alias_match),
359 std::get<2>(alias_match), "UNKNOWN_ALIAS");
360 }
361 }
362
363 ostr << directive << '\n';
364 }
365 catch (const clanguml::error::uml_alias_missing &e) {
366 LOG_WARN("Failed to render PlantUML directive due to unresolvable "
367 "alias: {}",
368 e.what());
369 }
370 catch (const inja::json::parse_error &e) {
371 LOG_WARN("Failed to parse Jinja template: {}", d);
372 }
373 catch (const inja::json::exception &e) {
374 LOG_WARN("Failed to render PlantUML directive: \n{}\n due to: {}",
375 d, e.what());
376 }
377 catch (const std::regex_error &e) {
378 LOG_WARN("Failed to render PlantUML directive: \n{}\n due to "
379 "std::regex_error: {}",
380 d, e.what());
381 }
382 catch (const std::exception &e) {
383 LOG_WARN("Failed to render PlantUML directive: \n{}\n due to: {}",
384 d, e.what());
385 }
386 }
387}
388
389template <typename C, typename D>
390void generator<C, D>::generate_style(std::ostream &ostr,
391 const std::string &element_type, const model::stylable_element &el) const
392{
393 const auto &config = generators::generator<C, D>::config();
394
395 if (el.style() && !el.style().value().empty()) // NOLINT
396 ostr << " " << *el.style(); // NOLINT
397 else if (config.puml) {
398 if (const auto config_style = config.puml().get_style(element_type);
399 config_style) {
400 ostr << " " << *config_style;
401 }
402 }
403}
404
405template <typename C, typename D>
407 std::ostream &ostr, const model::element &e) const
408{
409 const auto &config = generators::generator<C, D>::config();
410
411 for (const auto &decorator : e.decorators()) {
412 auto note = std::dynamic_pointer_cast<decorators::note>(decorator);
413 if (note && note->applies_to_diagram(config.name)) {
414 ostr << "note " << note->position << " of " << e.alias() << '\n'
415 << note->text << '\n'
416 << "end note\n";
417 }
418 }
419}
420
421template <typename C, typename D>
422void generator<C, D>::generate_metadata(std::ostream &ostr) const
423{
424 const auto &config = generators::generator<C, D>::config();
425
426 if (config.generate_metadata()) {
427 ostr << '\n'
428 << "'Generated with clang-uml, version "
429 << clanguml::version::CLANG_UML_VERSION << '\n'
430 << "'LLVM version " << clang::getClangFullVersion() << '\n';
431 }
432}
433
434template <typename C, typename D>
435void generator<C, D>::generate_title(std::ostream &ostr) const
436{
437 const auto &config = generators::generator<C, D>::config();
438
439 if (config.title) {
440 ostr << "title " << config.title() << '\n';
441 }
442}
443
444template <typename C, typename D>
445template <typename E>
446void generator<C, D>::generate_link(std::ostream &ostr, const E &e) const
447{
448 if (e.file().empty() && e.file_relative().empty())
449 return;
450
451 auto maybe_link_pattern = generators::generator<C, D>::get_link_pattern(e);
452
453 if (!maybe_link_pattern) {
454 return;
455 }
456
457 const auto &[link_prefix, link_pattern] = *maybe_link_pattern;
458
459 ostr << " [[";
460 try {
461 if (!link_pattern.empty()) {
464 ostr << generators::generator<C, D>::env().render(
465 std::string_view{link_pattern}, ec);
466 }
467 }
468 catch (const inja::json::parse_error &e) {
469 LOG_ERROR("Failed to parse Jinja template: {}", link_pattern);
470 }
471 catch (const std::exception &e) {
472 LOG_ERROR("Failed to render PlantUML directive: \n{}\n due to: {}",
473 link_pattern, e.what());
474 }
475
476 auto maybe_tooltip_pattern =
478
479 if (maybe_tooltip_pattern) {
480 const auto &[tooltip_prefix, tooltip_pattern] = *maybe_tooltip_pattern;
481
482 ostr << "{";
483 try {
486 ec, tooltip_prefix);
487 if (!tooltip_pattern.empty()) {
488 ostr << generators::generator<C, D>::env().render(
489 std::string_view{tooltip_pattern}, ec);
490 }
491 }
492 catch (const inja::json::parse_error &e) {
493 LOG_ERROR("Failed to parse Jinja template: {}", tooltip_pattern);
494 }
495 catch (const std::exception &e) {
496 LOG_ERROR("Failed to render PlantUML directive: \n{}\n due to: {}",
497 tooltip_pattern, e.what());
498 }
499 ostr << "}";
500 }
501 ostr << "]]";
502}
503
504template <typename C, typename D>
506 const common::model::source_location &e, std::ostream &ostr) const
507{
508 const auto &config = generators::generator<C, D>::config();
509
510 if (config.debug_mode())
511 ostr << "' " << e.file() << ":" << e.line() << '\n';
512}
513
514template <typename DiagramModel, typename DiagramConfig>
515std::ostream &operator<<(
516 std::ostream &os, const generator<DiagramModel, DiagramConfig> &g)
517{
518 g.generate(os);
519 return os;
520}
521
522} // namespace clanguml::common::generators::plantuml