1 // Copyright 2018 the V8 project authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 #include "src/torque/source-positions.h" 6 7 #include <fstream> 8 #include "src/torque/utils.h" 9 10 namespace v8 { 11 namespace internal { 12 namespace torque { 13 14 DEFINE_CONTEXTUAL_VARIABLE(CurrentSourceFile) DEFINE_CONTEXTUAL_VARIABLE(CurrentSourcePosition)15DEFINE_CONTEXTUAL_VARIABLE(CurrentSourcePosition) 16 DEFINE_CONTEXTUAL_VARIABLE(SourceFileMap) 17 18 // static 19 const std::string& SourceFileMap::PathFromV8Root(SourceId file) { 20 CHECK(file.IsValid()); 21 return Get().sources_[file.id_]; 22 } 23 24 // static AbsolutePath(SourceId file)25std::string SourceFileMap::AbsolutePath(SourceId file) { 26 const std::string& root_path = PathFromV8Root(file); 27 if (StringStartsWith(root_path, "file://")) return root_path; 28 return Get().v8_root_ + "/" + PathFromV8Root(file); 29 } 30 31 // static PathFromV8RootWithoutExtension(SourceId file)32std::string SourceFileMap::PathFromV8RootWithoutExtension(SourceId file) { 33 std::string path_from_root = PathFromV8Root(file); 34 if (!StringEndsWith(path_from_root, ".tq")) { 35 Error("Not a .tq file: ", path_from_root).Throw(); 36 } 37 path_from_root.resize(path_from_root.size() - strlen(".tq")); 38 return path_from_root; 39 } 40 41 // static AddSource(std::string path)42SourceId SourceFileMap::AddSource(std::string path) { 43 Get().sources_.push_back(std::move(path)); 44 return SourceId(static_cast<int>(Get().sources_.size()) - 1); 45 } 46 47 // static GetSourceId(const std::string & path)48SourceId SourceFileMap::GetSourceId(const std::string& path) { 49 for (size_t i = 0; i < Get().sources_.size(); ++i) { 50 if (Get().sources_[i] == path) { 51 return SourceId(static_cast<int>(i)); 52 } 53 } 54 return SourceId::Invalid(); 55 } 56 57 // static AllSources()58std::vector<SourceId> SourceFileMap::AllSources() { 59 SourceFileMap& self = Get(); 60 std::vector<SourceId> result; 61 result.reserve(static_cast<int>(self.sources_.size())); 62 for (int i = 0; i < static_cast<int>(self.sources_.size()); ++i) { 63 result.push_back(SourceId(i)); 64 } 65 return result; 66 } 67 68 // static FileRelativeToV8RootExists(const std::string & path)69bool SourceFileMap::FileRelativeToV8RootExists(const std::string& path) { 70 const std::string file = Get().v8_root_ + "/" + path; 71 std::ifstream stream(file); 72 return stream.good(); 73 } 74 75 } // namespace torque 76 } // namespace internal 77 } // namespace v8 78