|
| 1 | +// |
| 2 | +// Created by redsun82 on 18.01.22. |
| 3 | +// |
| 4 | + |
| 5 | +#pragma once |
| 6 | + |
| 7 | +#include <iostream> |
| 8 | +#include <sstream> |
| 9 | +#include <vector> |
| 10 | + |
| 11 | +#include "swift/extractor/trap/TrapLabel.h" |
| 12 | + |
| 13 | +namespace codeql { |
| 14 | + |
| 15 | +// TrapArena has the responsibilities to |
| 16 | +// * allocate distinct trap #-labels outputting their assignment to '*' or a @-keys to a trap output |
| 17 | +// * forwarding trap entries to said output |
| 18 | +// TODO: split or move these responsibilities into separate classes |
| 19 | +class TrapArena { |
| 20 | + public: |
| 21 | + explicit TrapArena(std::ostream& out) : out_{out} {} |
| 22 | + |
| 23 | + // get a new label for * |
| 24 | + template <typename Tag> |
| 25 | + TrapLabel<Tag> getLabel() { |
| 26 | + auto ret = allocateLabel<Tag>(); |
| 27 | + print(ret, "=*"); |
| 28 | + return ret; |
| 29 | + } |
| 30 | + |
| 31 | + // get a new label for an @-key |
| 32 | + template <typename Tag> |
| 33 | + TrapLabel<Tag> getLabel(const std::string& key) { |
| 34 | + auto ret = allocateLabel<Tag>(); |
| 35 | + // prefix the key with the id to guarantee the same key is not used wrongly with different tags |
| 36 | + auto prefixed = std::string(Tag::prefix) + '_' + key; |
| 37 | + print(ret, "=@", quoted(prefixed)); |
| 38 | + return ret; |
| 39 | + } |
| 40 | + |
| 41 | + // same as getLabel(const std::string&) above, concatenating keyParts |
| 42 | + template <typename Tag, typename... Args> |
| 43 | + TrapLabel<Tag> getLabel(const Args&... keyParts) { |
| 44 | + std::ostringstream oss; |
| 45 | + (oss << ... << keyParts); |
| 46 | + return getLabel<Tag>(oss.str()); |
| 47 | + } |
| 48 | + |
| 49 | + // emit a trap entry |
| 50 | + template <typename Entry> |
| 51 | + void emit(const Entry& e) { |
| 52 | + print(e); |
| 53 | + } |
| 54 | + |
| 55 | + private: |
| 56 | + template <typename... Args> |
| 57 | + void print(const Args&... args) { |
| 58 | + (out_ << ... << args) << '\n'; |
| 59 | + } |
| 60 | + |
| 61 | + template <typename Tag> |
| 62 | + TrapLabel<Tag> allocateLabel() { |
| 63 | + return {id_++}; |
| 64 | + } |
| 65 | + |
| 66 | + uint64_t id_{0}; |
| 67 | + std::ostream& out_; |
| 68 | +}; |
| 69 | + |
| 70 | +} // namespace codeql |
0 commit comments