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