treelite
semantic.cc
Go to the documentation of this file.
1 
8 #include <treelite/semantic.h>
9 #include "./common/filesystem.h"
10 
11 namespace treelite {
12 namespace semantic {
13 
14 std::vector<std::string>
15 TranslationUnit::Compile(const std::string& header_filename) const {
16  std::string header_basename
17  = common::filesystem::GetBasename(header_filename);
18  std::vector<std::string> lines{std::string("#include \"")
19  + header_basename + "\"", ""};
20  auto preamble_lines = preamble->Compile();
21  if (preamble_lines.size() > 0) {
22  common::TransformPushBack(&lines, preamble_lines,
23  [] (std::string line) {
24  return line;
25  });
26  lines.emplace_back();
27  }
28  common::TransformPushBack(&lines, body->Compile(),
29  [] (std::string line) {
30  return line;
31  });
32  return lines;
33 }
34 
35 std::vector<std::string>
36 PlainBlock::Compile() const {
37  return inner_text;
38 }
39 
40 std::vector<std::string>
41 FunctionBlock::Compile() const {
42  std::vector<std::string> ret{prototype + " {"};
43  common::TransformPushBack(&ret, body->Compile(), [] (std::string line) {
44  return " " + line;
45  });
46  ret.emplace_back("}");
47 
48  return ret;
49 }
50 
51 std::vector<std::string>
52 SequenceBlock::Compile() const {
53  std::vector<std::string> ret;
54  for (const auto& block : sequence) {
55  common::TransformPushBack(&ret, block->Compile(), [] (std::string line) {
56  return line;
57  });
58  }
59  return ret;
60 }
61 
62 void
63 SequenceBlock::Reserve(size_t size) {
64  sequence.reserve(size);
65 }
66 
67 void
68 SequenceBlock::PushBack(const CodeBlock& block) {
69  sequence.emplace_back(block);
70 }
71 
72 void
73 SequenceBlock::PushBack(CodeBlock&& block) {
74  sequence.push_back(DeepCopyUniquePtr<CodeBlock>(std::move(block)));
75 }
76 
77 std::vector<std::string>
78 IfElseBlock::Compile() const {
79  std::vector<std::string> ret;
80 
81  if (branch_hint == BranchHint::kNone) {
82  ret.push_back(std::string("if (") + condition->Compile() + ") {");
83  } else {
84  const std::string tag =
85  (branch_hint == BranchHint::kLikely) ? "LIKELY" : "UNLIKELY";
86  ret.push_back(std::string("if ( ") + tag + "( "
87  + condition->Compile() + " ) ) {");
88  }
89  common::TransformPushBack(&ret, if_block->Compile(), [] (std::string line) {
90  return " " + line;
91  });
92  ret.emplace_back("} else {");
93  common::TransformPushBack(&ret, else_block->Compile(), [] (std::string line) {
94  return " " + line;
95  });
96  ret.emplace_back("}");
97  return ret;
98 }
99 
100 } // namespace semantic
101 } // namespace treelite
Cross-platform wrapper for common filesystem functions.
Building blocks for semantic model of tree prediction code.