text_handler.cpp 13 KB

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