text_handler.cpp 13 KB

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