text_handler.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  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. word->assign(text->str + start_index, text->str + position->index);
  114. return SPV_SUCCESS;
  115. case '\0': { // NOTE: End of word found!
  116. word->assign(text->str + start_index, text->str + position->index);
  117. return SPV_SUCCESS;
  118. }
  119. default:
  120. break;
  121. }
  122. escaping = false;
  123. }
  124. position->column++;
  125. position->index++;
  126. }
  127. }
  128. // Returns true if the characters in the text as position represent
  129. // the start of an Opcode.
  130. bool startsWithOp(spv_text text, spv_position position) {
  131. if (text->length < position->index + 3) return false;
  132. char ch0 = text->str[position->index];
  133. char ch1 = text->str[position->index + 1];
  134. char ch2 = text->str[position->index + 2];
  135. return ('O' == ch0 && 'p' == ch1 && ('A' <= ch2 && ch2 <= 'Z'));
  136. }
  137. } // namespace
  138. const IdType kUnknownType = {0, false, IdTypeClass::kBottom};
  139. // TODO(dneto): Reorder AssemblyContext definitions to match declaration order.
  140. // This represents all of the data that is only valid for the duration of
  141. // a single compilation.
  142. uint32_t AssemblyContext::spvNamedIdAssignOrGet(const char* textValue) {
  143. if (!ids_to_preserve_.empty()) {
  144. uint32_t id = 0;
  145. if (spvtools::utils::ParseNumber(textValue, &id)) {
  146. if (ids_to_preserve_.find(id) != ids_to_preserve_.end()) {
  147. bound_ = std::max(bound_, id + 1);
  148. return id;
  149. }
  150. }
  151. }
  152. const auto it = named_ids_.find(textValue);
  153. if (it == named_ids_.end()) {
  154. uint32_t id = next_id_++;
  155. if (!ids_to_preserve_.empty()) {
  156. while (ids_to_preserve_.find(id) != ids_to_preserve_.end()) {
  157. id = next_id_++;
  158. }
  159. }
  160. named_ids_.emplace(textValue, id);
  161. bound_ = std::max(bound_, id + 1);
  162. return id;
  163. }
  164. return it->second;
  165. }
  166. uint32_t AssemblyContext::getBound() const { return bound_; }
  167. spv_result_t AssemblyContext::advance() {
  168. return spvtools::advance(text_, &current_position_);
  169. }
  170. spv_result_t AssemblyContext::getWord(std::string* word,
  171. spv_position next_position) {
  172. *next_position = current_position_;
  173. return spvtools::getWord(text_, next_position, word);
  174. }
  175. bool AssemblyContext::startsWithOp() {
  176. return spvtools::startsWithOp(text_, &current_position_);
  177. }
  178. bool AssemblyContext::isStartOfNewInst() {
  179. spv_position_t pos = current_position_;
  180. if (spvtools::advance(text_, &pos)) return false;
  181. if (spvtools::startsWithOp(text_, &pos)) return true;
  182. std::string word;
  183. pos = current_position_;
  184. if (spvtools::getWord(text_, &pos, &word)) return false;
  185. if ('%' != word.front()) return false;
  186. if (spvtools::advance(text_, &pos)) return false;
  187. if (spvtools::getWord(text_, &pos, &word)) return false;
  188. if ("=" != word) return false;
  189. if (spvtools::advance(text_, &pos)) return false;
  190. if (spvtools::startsWithOp(text_, &pos)) return true;
  191. return false;
  192. }
  193. char AssemblyContext::peek() const {
  194. return text_->str[current_position_.index];
  195. }
  196. bool AssemblyContext::hasText() const {
  197. return text_->length > current_position_.index;
  198. }
  199. void AssemblyContext::seekForward(uint32_t size) {
  200. current_position_.index += size;
  201. current_position_.column += size;
  202. }
  203. spv_result_t AssemblyContext::binaryEncodeU32(const uint32_t value,
  204. spv_instruction_t* pInst) {
  205. pInst->words.insert(pInst->words.end(), value);
  206. return SPV_SUCCESS;
  207. }
  208. spv_result_t AssemblyContext::binaryEncodeNumericLiteral(
  209. const char* val, spv_result_t error_code, const IdType& type,
  210. spv_instruction_t* pInst) {
  211. using spvtools::utils::EncodeNumberStatus;
  212. // Populate the NumberType from the IdType for parsing.
  213. spvtools::utils::NumberType number_type;
  214. switch (type.type_class) {
  215. case IdTypeClass::kOtherType:
  216. return diagnostic(SPV_ERROR_INTERNAL)
  217. << "Unexpected numeric literal type";
  218. case IdTypeClass::kScalarIntegerType:
  219. if (type.isSigned) {
  220. number_type = {type.bitwidth, SPV_NUMBER_SIGNED_INT};
  221. } else {
  222. number_type = {type.bitwidth, SPV_NUMBER_UNSIGNED_INT};
  223. }
  224. break;
  225. case IdTypeClass::kScalarFloatType:
  226. number_type = {type.bitwidth, SPV_NUMBER_FLOATING};
  227. break;
  228. case IdTypeClass::kBottom:
  229. // kBottom means the type is unknown and we need to infer the type before
  230. // parsing the number. The rule is: If there is a decimal point, treat
  231. // the value as a floating point value, otherwise a integer value, then
  232. // if the first char of the integer text is '-', treat the integer as a
  233. // signed integer, otherwise an unsigned integer.
  234. uint32_t bitwidth = static_cast<uint32_t>(assumedBitWidth(type));
  235. if (strchr(val, '.')) {
  236. number_type = {bitwidth, SPV_NUMBER_FLOATING};
  237. } else if (type.isSigned || val[0] == '-') {
  238. number_type = {bitwidth, SPV_NUMBER_SIGNED_INT};
  239. } else {
  240. number_type = {bitwidth, SPV_NUMBER_UNSIGNED_INT};
  241. }
  242. break;
  243. }
  244. std::string error_msg;
  245. EncodeNumberStatus parse_status = ParseAndEncodeNumber(
  246. val, number_type,
  247. [this, pInst](uint32_t d) { this->binaryEncodeU32(d, pInst); },
  248. &error_msg);
  249. switch (parse_status) {
  250. case EncodeNumberStatus::kSuccess:
  251. return SPV_SUCCESS;
  252. case EncodeNumberStatus::kInvalidText:
  253. return diagnostic(error_code) << error_msg;
  254. case EncodeNumberStatus::kUnsupported:
  255. return diagnostic(SPV_ERROR_INTERNAL) << error_msg;
  256. case EncodeNumberStatus::kInvalidUsage:
  257. return diagnostic(SPV_ERROR_INVALID_TEXT) << error_msg;
  258. }
  259. // This line is not reachable, only added to satisfy the compiler.
  260. return diagnostic(SPV_ERROR_INTERNAL)
  261. << "Unexpected result code from ParseAndEncodeNumber()";
  262. }
  263. spv_result_t AssemblyContext::binaryEncodeString(const char* value,
  264. spv_instruction_t* pInst) {
  265. const size_t length = strlen(value);
  266. const size_t wordCount = (length / 4) + 1;
  267. const size_t oldWordCount = pInst->words.size();
  268. const size_t newWordCount = oldWordCount + wordCount;
  269. // TODO(dneto): We can just defer this check until later.
  270. if (newWordCount > SPV_LIMIT_INSTRUCTION_WORD_COUNT_MAX) {
  271. return diagnostic() << "Instruction too long: more than "
  272. << SPV_LIMIT_INSTRUCTION_WORD_COUNT_MAX << " words.";
  273. }
  274. pInst->words.resize(newWordCount);
  275. // Make sure all the bytes in the last word are 0, in case we only
  276. // write a partial word at the end.
  277. pInst->words.back() = 0;
  278. char* dest = (char*)&pInst->words[oldWordCount];
  279. strncpy(dest, value, length + 1);
  280. return SPV_SUCCESS;
  281. }
  282. spv_result_t AssemblyContext::recordTypeDefinition(
  283. const spv_instruction_t* pInst) {
  284. uint32_t value = pInst->words[1];
  285. if (types_.find(value) != types_.end()) {
  286. return diagnostic() << "Value " << value
  287. << " has already been used to generate a type";
  288. }
  289. if (pInst->opcode == SpvOpTypeInt) {
  290. if (pInst->words.size() != 4)
  291. return diagnostic() << "Invalid OpTypeInt instruction";
  292. types_[value] = {pInst->words[2], pInst->words[3] != 0,
  293. IdTypeClass::kScalarIntegerType};
  294. } else if (pInst->opcode == SpvOpTypeFloat) {
  295. if (pInst->words.size() != 3)
  296. return diagnostic() << "Invalid OpTypeFloat instruction";
  297. types_[value] = {pInst->words[2], false, IdTypeClass::kScalarFloatType};
  298. } else {
  299. types_[value] = {0, false, IdTypeClass::kOtherType};
  300. }
  301. return SPV_SUCCESS;
  302. }
  303. IdType AssemblyContext::getTypeOfTypeGeneratingValue(uint32_t value) const {
  304. auto type = types_.find(value);
  305. if (type == types_.end()) {
  306. return kUnknownType;
  307. }
  308. return std::get<1>(*type);
  309. }
  310. IdType AssemblyContext::getTypeOfValueInstruction(uint32_t value) const {
  311. auto type_value = value_types_.find(value);
  312. if (type_value == value_types_.end()) {
  313. return {0, false, IdTypeClass::kBottom};
  314. }
  315. return getTypeOfTypeGeneratingValue(std::get<1>(*type_value));
  316. }
  317. spv_result_t AssemblyContext::recordTypeIdForValue(uint32_t value,
  318. uint32_t type) {
  319. bool successfully_inserted = false;
  320. std::tie(std::ignore, successfully_inserted) =
  321. value_types_.insert(std::make_pair(value, type));
  322. if (!successfully_inserted)
  323. return diagnostic() << "Value is being defined a second time";
  324. return SPV_SUCCESS;
  325. }
  326. spv_result_t AssemblyContext::recordIdAsExtInstImport(
  327. uint32_t id, spv_ext_inst_type_t type) {
  328. bool successfully_inserted = false;
  329. std::tie(std::ignore, successfully_inserted) =
  330. import_id_to_ext_inst_type_.insert(std::make_pair(id, type));
  331. if (!successfully_inserted)
  332. return diagnostic() << "Import Id is being defined a second time";
  333. return SPV_SUCCESS;
  334. }
  335. spv_ext_inst_type_t AssemblyContext::getExtInstTypeForId(uint32_t id) const {
  336. auto type = import_id_to_ext_inst_type_.find(id);
  337. if (type == import_id_to_ext_inst_type_.end()) {
  338. return SPV_EXT_INST_TYPE_NONE;
  339. }
  340. return std::get<1>(*type);
  341. }
  342. std::set<uint32_t> AssemblyContext::GetNumericIds() const {
  343. std::set<uint32_t> ids;
  344. for (const auto& kv : named_ids_) {
  345. uint32_t id;
  346. if (spvtools::utils::ParseNumber(kv.first.c_str(), &id)) ids.insert(id);
  347. }
  348. return ids;
  349. }
  350. } // namespace spvtools