summaryrefslogtreecommitdiff
path: root/willow/tools/willowc/lib/sourcemanager.cpp
blob: e2a8e727c5a0a5f8c60492f039d07c36e1f3c204 (plain)
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
#include <filesystem>

#include <fstream>
#include <sourcemanager.hpp>

namespace willowc {

std::optional<FileID> SourceManager::addFile(std::string_view _path) {
  std::error_code ec;

  std::filesystem::path uncanonical_path{_path};
  auto path = std::filesystem::weakly_canonical(uncanonical_path, ec);
  if (ec) {
    return false;
  }
  std::string display_path = path.make_preferred();

  if (!std::filesystem::exists(path, ec) || ec)
    return std::nullopt;

  if (!std::filesystem::is_regular_file(path, ec) || ec)
    return std::nullopt;

  std::size_t filesize = std::filesystem::file_size(path, ec);
  if (ec)
    return std::nullopt;

  std::ifstream f{display_path, std::ios::binary};
  if (!f)
    return std::nullopt;

  auto buf = std::make_unique<char[]>(filesize);
  f.read(buf.get(), filesize);

  const FileID id = file_table.size();
  file_table.push_back(File{std::move(display_path), std::move(buf)});

  return id;
}

} // namespace willowc