text_handler.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  1. // Copyright (c) 2015-2016 The Khronos Group Inc.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #include "source/text_handler.h"
  15. #include <algorithm>
  16. #include <cassert>
  17. #include <cstdlib>
  18. #include <cstring>
  19. #include <tuple>
  20. #include "source/assembly_grammar.h"
  21. #include "source/binary.h"
  22. #include "source/ext_inst.h"
  23. #include "source/instruction.h"
  24. #include "source/opcode.h"
  25. #include "source/text.h"
  26. #include "source/util/bitutils.h"
  27. #include "source/util/hex_float.h"
  28. #include "source/util/parse_number.h"
  29. namespace spvtools {
  30. namespace {
  31. // Advances |text| to the start of the next line and writes the new position to
  32. // |position|.
  33. spv_result_t advanceLine(spv_text text, spv_position position) {
  34. while (true) {
  35. if (position->index >= text->length) return SPV_END_OF_STREAM;
  36. switch (text->str[position->index]) {
  37. case '\0':
  38. return SPV_END_OF_STREAM;
  39. case '\n':
  40. position->column = 0;
  41. position->line++;
  42. position->index++;
  43. return SPV_SUCCESS;
  44. default:
  45. position->column++;
  46. position->index++;
  47. break;
  48. }
  49. }
  50. }
  51. // Advances |text| to first non white space character and writes the new
  52. // position to |position|.
  53. // If a null terminator is found during the text advance, SPV_END_OF_STREAM is
  54. // returned, SPV_SUCCESS otherwise. No error checking is performed on the
  55. // parameters, its the users responsibility to ensure these are non null.
  56. spv_result_t advance(spv_text text, spv_position position) {
  57. // NOTE: Consume white space, otherwise don't advance.
  58. if (position->index >= text->length) return SPV_END_OF_STREAM;
  59. switch (text->str[position->index]) {
  60. case '\0':
  61. return SPV_END_OF_STREAM;
  62. case ';':
  63. if (spv_result_t error = advanceLine(text, position)) return error;
  64. return advance(text, position);
  65. case ' ':
  66. case '\t':
  67. case '\r':
  68. position->column++;
  69. position->index++;
  70. return advance(text, position);
  71. case '\n':
  72. position->column = 0;
  73. position->line++;
  74. position->index++;
  75. return advance(text, position);
  76. default:
  77. break;
  78. }
  79. return SPV_SUCCESS;
  80. }
  81. // Fetches the next word from the given text stream starting from the given
  82. // *position. On success, writes the decoded word into *word and updates
  83. // *position to the location past the returned word.
  84. //
  85. // A word ends at the next comment or whitespace. However, double-quoted
  86. // strings remain intact, and a backslash always escapes the next character.
  87. spv_result_t getWord(spv_text text, spv_position position, std::string* word) {
  88. if (!text->str || !text->length) return SPV_ERROR_INVALID_TEXT;
  89. if (!position) return SPV_ERROR_INVALID_POINTER;
  90. const size_t start_index = position->index;
  91. bool quoting = false;
  92. bool escaping = false;
  93. // NOTE: Assumes first character is not white space!
  94. while (true) {
  95. if (position->index >= text->length) {
  96. word->assign(text->str + start_index, text->str + position->index);
  97. return SPV_SUCCESS;
  98. }
  99. const char ch = text->str[position->index];
  100. if (ch == '\\') {
  101. escaping = !escaping;
  102. } else {
  103. switch (ch) {
  104. case '"':
  105. if (!escaping) quoting = !quoting;
  106. break;
  107. case ' ':
  108. case ';':
  109. case '\t':
  110. case '\n':
  111. case '\r':
  112. if (escaping || quoting) break;
  113. // Fall through.
  114. case '\0': { // NOTE: End of word found!
  115. word->assign(text->str + start_index, text->str + position->index);
  116. return SPV_SUCCESS;
  117. }
  118. default:
  119. break;
  120. }
  121. escaping = false;
  122. }
  123. position->column++;
  124. position->index++;
  125. }
  126. }
  127. // Returns true if the characters in the text as position represent
  128. // the start of an Opcode.
  129. bool startsWithOp(spv_text text, spv_position position) {
  130. if (text->length < position->index + 3) return false;
  131. char ch0 = text->str[position->index];
  132. char ch1 = text->str[position->index + 1];
  133. char ch2 = text->str[position->index + 2];
  134. return ('O' == ch0 && 'p' == ch1 && ('A' <= ch2 && ch2 <= 'Z'));
  135. }
  136. } // namespace
  137. const IdType kUnknownType = {0, false, IdTypeClass::kBottom};
  138. // TODO(dneto): Reorder AssemblyContext definitions to match declaration order.
  139. // This represents all of the data that is only valid for the duration of
  140. // a single compilation.
  141. uint32_t AssemblyContext::spvNamedIdAssignOrGet(const char* textValue) {
  142. if (!ids_to_preserve_.empty()) {
  143. uint32_t id = 0;
  144. if (spvtools::utils::ParseNumber(textValue, &id)) {
  145. if (ids_to_preserve_.find(id) != ids_to_preserve_.end()) {
  146. bound_ = std::max(bound_, id + 1);
  147. return id;
  148. }
  149. }
  150. }
  151. const auto it = named_ids_.find(textValue);
  152. if (it == named_ids_.end()) {
  153. uint32_t id = next_id_++;
  154. if (!ids_to_preserve_.empty()) {
  155. while (ids_to_preserve_.find(id) != ids_to_preserve_.end()) {
  156. id = next_id_++;
  157. }
  158. }
  159. named_ids_.emplace(textValue, id);
  160. bound_ = std::max(bound_, id + 1);
  161. return id;
  162. }
  163. return it->second;
  164. }
  165. uint32_t AssemblyContext::getBound() const { return bound_; }
  166. spv_result_t AssemblyContext::advance() {
  167. return spvtools::advance(text_, &current_position_);
  168. }
  169. spv_result_t AssemblyContext::getWord(std::string* word,
  170. spv_position next_position) {
  171. *next_position = current_position_;
  172. return spvtools::getWord(text_, next_position, word);
  173. }
  174. bool AssemblyContext::startsWithOp() {
  175. return spvtools::startsWithOp(text_, &current_position_);
  176. }
  177. bool AssemblyContext::isStartOfNewInst() {
  178. spv_position_t pos = current_position_;
  179. if (spvtools::advance(text_, &pos)) return false;
  180. if (spvtools::startsWithOp(text_, &pos)) return true;
  181. std::string word;
  182. pos = current_position_;
  183. if (spvtools::getWord(text_, &pos, &word)) return false;
  184. if ('%' != word.front()) return false;
  185. if (spvtools::advance(text_, &pos)) return false;
  186. if (spvtools::getWord(text_, &pos, &word)) return false;
  187. if ("=" != word) return false;
  188. if (spvtools::advance(text_, &pos)) return false;
  189. if (spvtools::startsWithOp(text_, &pos)) return true;
  190. return false;
  191. }
  192. char AssemblyContext::peek() const {
  193. return text_->str[current_position_.index];
  194. }
  195. bool AssemblyContext::hasText() const {
  196. return text_->length > current_position_.index;
  197. }
  198. void AssemblyContext::seekForward(uint32_t size) {
  199. current_position_.index += size;
  200. current_position_.column += size;
  201. }
  202. spv_result_t AssemblyContext::binaryEncodeU32(const uint32_t value,
  203. spv_instruction_t* pInst) {
  204. pInst->words.insert(pInst->words.end(), value);
  205. return SPV_SUCCESS;
  206. }
  207. spv_result_t AssemblyContext::binaryEncodeNumericLiteral(
  208. const char* val, spv_result_t error_code, const IdType& type,
  209. spv_instruction_t* pInst) {
  210. using spvtools::utils::EncodeNumberStatus;
  211. // Populate the NumberType from the IdType for parsing.
  212. spvtools::utils::NumberType number_type;
  213. switch (type.type_class) {
  214. case IdTypeClass::kOtherType:
  215. return diagnostic(SPV_ERROR_INTERNAL)
  216. << "Unexpected numeric literal type";
  217. case IdTypeClass::kScalarIntegerType:
  218. if (type.isSigned) {
  219. number_type = {type.bitwidth, SPV_NUMBER_SIGNED_INT};
  220. } else {
  221. number_type = {type.bitwidth, SPV_NUMBER_UNSIGNED_INT};
  222. }
  223. break;
  224. case IdTypeClass::kScalarFloatType:
  225. number_type = {type.bitwidth, SPV_NUMBER_FLOATING};
  226. break;
  227. case IdTypeClass::kBottom:
  228. // kBottom means the type is unknown and we need to infer the type before
  229. // parsing the number. The rule is: If there is a decimal point, treat
  230. // the value as a floating point value, otherwise a integer value, then
  231. // if the first char of the integer text is '-', treat the integer as a
  232. // signed integer, otherwise an unsigned integer.
  233. uint32_t bitwidth = static_cast<uint32_t>(assumedBitWidth(type));
  234. if (strchr(val, '.')) {
  235. number_type = {bitwidth, SPV_NUMBER_FLOATING};
  236. } else if (type.isSigned || val[0] == '-') {
  237. number_type = {bitwidth, SPV_NUMBER_SIGNED_INT};
  238. } else {
  239. number_type = {bitwidth, SPV_NUMBER_UNSIGNED_INT};
  240. }
  241. break;
  242. }
  243. std::string error_msg;
  244. EncodeNumberStatus parse_status = ParseAndEncodeNumber(
  245. val, number_type,
  246. [this, pInst](uint32_t d) { this->binaryEncodeU32(d, pInst); },
  247. &error_msg);
  248. switch (parse_status) {
  249. case EncodeNumberStatus::kSuccess:
  250. return SPV_SUCCESS;
  251. case EncodeNumberStatus::kInvalidText:
  252. return diagnostic(error_code) << error_msg;
  253. case EncodeNumberStatus::kUnsupported:
  254. return diagnostic(SPV_ERROR_INTERNAL) << error_msg;
  255. case EncodeNumberStatus::kInvalidUsage:
  256. return diagnostic(SPV_ERROR_INVALID_TEXT) << error_msg;
  257. }
  258. // This line is not reachable, only added to satisfy the compiler.
  259. return diagnostic(SPV_ERROR_INTERNAL)
  260. << "Unexpected result code from ParseAndEncodeNumber()";
  261. }
  262. spv_result_t AssemblyContext::binaryEncodeString(const char* value,
  263. spv_instruction_t* pInst) {
  264. const size_t length = strlen(value);
  265. const size_t wordCount = (length / 4) + 1;
  266. const size_t oldWordCount = pInst->words.size();
  267. const size_t newWordCount = oldWordCount + wordCount;
  268. // TODO(dneto): We can just defer this check until later.
  269. if (newWordCount > SPV_LIMIT_INSTRUCTION_WORD_COUNT_MAX) {
  270. return diagnostic() << "Instruction too long: more than "
  271. << SPV_LIMIT_INSTRUCTION_WORD_COUNT_MAX << " words.";
  272. }
  273. pInst->words.resize(newWordCount);
  274. // Make sure all the bytes in the last word are 0, in case we only
  275. // write a partial word at the end.
  276. pInst->words.back() = 0;
  277. char* dest = (char*)&pInst->words[oldWordCount];
  278. strncpy(dest, value, length + 1);
  279. return SPV_SUCCESS;
  280. }
  281. spv_result_t AssemblyContext::recordTypeDefinition(
  282. const spv_instruction_t* pInst) {
  283. uint32_t value = pInst->words[1];
  284. if (types_.find(value) != types_.end()) {
  285. return diagnostic() << "Value " << value
  286. << " has already been used to generate a type";
  287. }
  288. if (pInst->opcode == SpvOpTypeInt) {
  289. if (pInst->words.size() != 4)
  290. return diagnostic() << "Invalid OpTypeInt instruction";
  291. types_[value] = {pInst->words[2], pInst->words[3] != 0,
  292. IdTypeClass::kScalarIntegerType};
  293. } else if (pInst->opcode == SpvOpTypeFloat) {
  294. if (pInst->words.size() != 3)
  295. return diagnostic() << "Invalid OpTypeFloat instruction";
  296. types_[value] = {pInst->words[2], false, IdTypeClass::kScalarFloatType};
  297. } else {
  298. types_[value] = {0, false, IdTypeClass::kOtherType};
  299. }
  300. return SPV_SUCCESS;
  301. }
  302. IdType AssemblyContext::getTypeOfTypeGeneratingValue(uint32_t value) const {
  303. auto type = types_.find(value);
  304. if (type == types_.end()) {
  305. return kUnknownType;
  306. }
  307. return std::get<1>(*type);
  308. }
  309. IdType AssemblyContext::getTypeOfValueInstruction(uint32_t value) const {
  310. auto type_value = value_types_.find(value);
  311. if (type_value == value_types_.end()) {
  312. return {0, false, IdTypeClass::kBottom};
  313. }
  314. return getTypeOfTypeGeneratingValue(std::get<1>(*type_value));
  315. }
  316. spv_result_t AssemblyContext::recordTypeIdForValue(uint32_t value,
  317. uint32_t type) {
  318. bool successfully_inserted = false;
  319. std::tie(std::ignore, successfully_inserted) =
  320. value_types_.insert(std::make_pair(value, type));
  321. if (!successfully_inserted)
  322. return diagnostic() << "Value is being defined a second time";
  323. return SPV_SUCCESS;
  324. }
  325. spv_result_t AssemblyContext::recordIdAsExtInstImport(
  326. uint32_t id, spv_ext_inst_type_t type) {
  327. bool successfully_inserted = false;
  328. std::tie(std::ignore, successfully_inserted) =
  329. import_id_to_ext_inst_type_.insert(std::make_pair(id, type));
  330. if (!successfully_inserted)
  331. return diagnostic() << "Import Id is being defined a second time";
  332. return SPV_SUCCESS;
  333. }
  334. spv_ext_inst_type_t AssemblyContext::getExtInstTypeForId(uint32_t id) const {
  335. auto type = import_id_to_ext_inst_type_.find(id);
  336. if (type == import_id_to_ext_inst_type_.end()) {
  337. return SPV_EXT_INST_TYPE_NONE;
  338. }
  339. return std::get<1>(*type);
  340. }
  341. std::set<uint32_t> AssemblyContext::GetNumericIds() const {
  342. std::set<uint32_t> ids;
  343. for (const auto& kv : named_ids_) {
  344. uint32_t id;
  345. if (spvtools::utils::ParseNumber(kv.first.c_str(), &id)) ids.insert(id);
  346. }
  347. return ids;
  348. }
  349. } // namespace spvtools