rust-parse.c 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401
  1. /* Rust expression parsing for GDB, the GNU debugger.
  2. Copyright (C) 2016-2022 Free Software Foundation, Inc.
  3. This file is part of GDB.
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 3 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program. If not, see <http://www.gnu.org/licenses/>. */
  14. #include "defs.h"
  15. #include "block.h"
  16. #include "charset.h"
  17. #include "cp-support.h"
  18. #include "gdbsupport/gdb_obstack.h"
  19. #include "gdbsupport/gdb_regex.h"
  20. #include "rust-lang.h"
  21. #include "parser-defs.h"
  22. #include "gdbsupport/selftest.h"
  23. #include "value.h"
  24. #include "gdbarch.h"
  25. #include "rust-exp.h"
  26. using namespace expr;
  27. /* A regular expression for matching Rust numbers. This is split up
  28. since it is very long and this gives us a way to comment the
  29. sections. */
  30. static const char number_regex_text[] =
  31. /* subexpression 1: allows use of alternation, otherwise uninteresting */
  32. "^("
  33. /* First comes floating point. */
  34. /* Recognize number after the decimal point, with optional
  35. exponent and optional type suffix.
  36. subexpression 2: allows "?", otherwise uninteresting
  37. subexpression 3: if present, type suffix
  38. */
  39. "[0-9][0-9_]*\\.[0-9][0-9_]*([eE][-+]?[0-9][0-9_]*)?(f32|f64)?"
  40. #define FLOAT_TYPE1 3
  41. "|"
  42. /* Recognize exponent without decimal point, with optional type
  43. suffix.
  44. subexpression 4: if present, type suffix
  45. */
  46. #define FLOAT_TYPE2 4
  47. "[0-9][0-9_]*[eE][-+]?[0-9][0-9_]*(f32|f64)?"
  48. "|"
  49. /* "23." is a valid floating point number, but "23.e5" and
  50. "23.f32" are not. So, handle the trailing-. case
  51. separately. */
  52. "[0-9][0-9_]*\\."
  53. "|"
  54. /* Finally come integers.
  55. subexpression 5: text of integer
  56. subexpression 6: if present, type suffix
  57. subexpression 7: allows use of alternation, otherwise uninteresting
  58. */
  59. #define INT_TEXT 5
  60. #define INT_TYPE 6
  61. "(0x[a-fA-F0-9_]+|0o[0-7_]+|0b[01_]+|[0-9][0-9_]*)"
  62. "([iu](size|8|16|32|64))?"
  63. ")";
  64. /* The number of subexpressions to allocate space for, including the
  65. "0th" whole match subexpression. */
  66. #define NUM_SUBEXPRESSIONS 8
  67. /* The compiled number-matching regex. */
  68. static regex_t number_regex;
  69. /* The kinds of tokens. Note that single-character tokens are
  70. represented by themselves, so for instance '[' is a token. */
  71. enum token_type : int
  72. {
  73. /* Make sure to start after any ASCII character. */
  74. GDBVAR = 256,
  75. IDENT,
  76. COMPLETE,
  77. INTEGER,
  78. DECIMAL_INTEGER,
  79. STRING,
  80. BYTESTRING,
  81. FLOAT,
  82. COMPOUND_ASSIGN,
  83. /* Keyword tokens. */
  84. KW_AS,
  85. KW_IF,
  86. KW_TRUE,
  87. KW_FALSE,
  88. KW_SUPER,
  89. KW_SELF,
  90. KW_MUT,
  91. KW_EXTERN,
  92. KW_CONST,
  93. KW_FN,
  94. KW_SIZEOF,
  95. /* Operator tokens. */
  96. DOTDOT,
  97. DOTDOTEQ,
  98. OROR,
  99. ANDAND,
  100. EQEQ,
  101. NOTEQ,
  102. LTEQ,
  103. GTEQ,
  104. LSH,
  105. RSH,
  106. COLONCOLON,
  107. ARROW,
  108. };
  109. /* A typed integer constant. */
  110. struct typed_val_int
  111. {
  112. ULONGEST val;
  113. struct type *type;
  114. };
  115. /* A typed floating point constant. */
  116. struct typed_val_float
  117. {
  118. float_data val;
  119. struct type *type;
  120. };
  121. /* A struct of this type is used to describe a token. */
  122. struct token_info
  123. {
  124. const char *name;
  125. int value;
  126. enum exp_opcode opcode;
  127. };
  128. /* Identifier tokens. */
  129. static const struct token_info identifier_tokens[] =
  130. {
  131. { "as", KW_AS, OP_NULL },
  132. { "false", KW_FALSE, OP_NULL },
  133. { "if", 0, OP_NULL },
  134. { "mut", KW_MUT, OP_NULL },
  135. { "const", KW_CONST, OP_NULL },
  136. { "self", KW_SELF, OP_NULL },
  137. { "super", KW_SUPER, OP_NULL },
  138. { "true", KW_TRUE, OP_NULL },
  139. { "extern", KW_EXTERN, OP_NULL },
  140. { "fn", KW_FN, OP_NULL },
  141. { "sizeof", KW_SIZEOF, OP_NULL },
  142. };
  143. /* Operator tokens, sorted longest first. */
  144. static const struct token_info operator_tokens[] =
  145. {
  146. { ">>=", COMPOUND_ASSIGN, BINOP_RSH },
  147. { "<<=", COMPOUND_ASSIGN, BINOP_LSH },
  148. { "<<", LSH, OP_NULL },
  149. { ">>", RSH, OP_NULL },
  150. { "&&", ANDAND, OP_NULL },
  151. { "||", OROR, OP_NULL },
  152. { "==", EQEQ, OP_NULL },
  153. { "!=", NOTEQ, OP_NULL },
  154. { "<=", LTEQ, OP_NULL },
  155. { ">=", GTEQ, OP_NULL },
  156. { "+=", COMPOUND_ASSIGN, BINOP_ADD },
  157. { "-=", COMPOUND_ASSIGN, BINOP_SUB },
  158. { "*=", COMPOUND_ASSIGN, BINOP_MUL },
  159. { "/=", COMPOUND_ASSIGN, BINOP_DIV },
  160. { "%=", COMPOUND_ASSIGN, BINOP_REM },
  161. { "&=", COMPOUND_ASSIGN, BINOP_BITWISE_AND },
  162. { "|=", COMPOUND_ASSIGN, BINOP_BITWISE_IOR },
  163. { "^=", COMPOUND_ASSIGN, BINOP_BITWISE_XOR },
  164. { "..=", DOTDOTEQ, OP_NULL },
  165. { "::", COLONCOLON, OP_NULL },
  166. { "..", DOTDOT, OP_NULL },
  167. { "->", ARROW, OP_NULL }
  168. };
  169. /* An instance of this is created before parsing, and destroyed when
  170. parsing is finished. */
  171. struct rust_parser
  172. {
  173. explicit rust_parser (struct parser_state *state)
  174. : pstate (state)
  175. {
  176. }
  177. DISABLE_COPY_AND_ASSIGN (rust_parser);
  178. /* Return the parser's language. */
  179. const struct language_defn *language () const
  180. {
  181. return pstate->language ();
  182. }
  183. /* Return the parser's gdbarch. */
  184. struct gdbarch *arch () const
  185. {
  186. return pstate->gdbarch ();
  187. }
  188. /* A helper to look up a Rust type, or fail. This only works for
  189. types defined by rust_language_arch_info. */
  190. struct type *get_type (const char *name)
  191. {
  192. struct type *type;
  193. type = language_lookup_primitive_type (language (), arch (), name);
  194. if (type == NULL)
  195. error (_("Could not find Rust type %s"), name);
  196. return type;
  197. }
  198. std::string crate_name (const std::string &name);
  199. std::string super_name (const std::string &ident, unsigned int n_supers);
  200. int lex_character ();
  201. int lex_number ();
  202. int lex_string ();
  203. int lex_identifier ();
  204. uint32_t lex_hex (int min, int max);
  205. uint32_t lex_escape (int is_byte);
  206. int lex_operator ();
  207. int lex_one_token ();
  208. void push_back (char c);
  209. /* The main interface to lexing. Lexes one token and updates the
  210. internal state. */
  211. void lex ()
  212. {
  213. current_token = lex_one_token ();
  214. }
  215. /* Assuming the current token is TYPE, lex the next token. */
  216. void assume (int type)
  217. {
  218. gdb_assert (current_token == type);
  219. lex ();
  220. }
  221. /* Require the single-character token C, and lex the next token; or
  222. throw an exception. */
  223. void require (char type)
  224. {
  225. if (current_token != type)
  226. error (_("'%c' expected"), type);
  227. lex ();
  228. }
  229. /* Entry point for all parsing. */
  230. operation_up parse_entry_point ()
  231. {
  232. lex ();
  233. operation_up result = parse_expr ();
  234. if (current_token != 0)
  235. error (_("Syntax error near '%s'"), pstate->prev_lexptr);
  236. return result;
  237. }
  238. operation_up parse_tuple ();
  239. operation_up parse_array ();
  240. operation_up name_to_operation (const std::string &name);
  241. operation_up parse_struct_expr (struct type *type);
  242. operation_up parse_binop (bool required);
  243. operation_up parse_range ();
  244. operation_up parse_expr ();
  245. operation_up parse_sizeof ();
  246. operation_up parse_addr ();
  247. operation_up parse_field (operation_up &&);
  248. operation_up parse_index (operation_up &&);
  249. std::vector<operation_up> parse_paren_args ();
  250. operation_up parse_call (operation_up &&);
  251. std::vector<struct type *> parse_type_list ();
  252. std::vector<struct type *> parse_maybe_type_list ();
  253. struct type *parse_array_type ();
  254. struct type *parse_slice_type ();
  255. struct type *parse_pointer_type ();
  256. struct type *parse_function_type ();
  257. struct type *parse_tuple_type ();
  258. struct type *parse_type ();
  259. std::string parse_path (bool for_expr);
  260. operation_up parse_string ();
  261. operation_up parse_tuple_struct (struct type *type);
  262. operation_up parse_path_expr ();
  263. operation_up parse_atom (bool required);
  264. void update_innermost_block (struct block_symbol sym);
  265. struct block_symbol lookup_symbol (const char *name,
  266. const struct block *block,
  267. const domain_enum domain);
  268. struct type *rust_lookup_type (const char *name);
  269. /* Clear some state. This is only used for testing. */
  270. #if GDB_SELF_TEST
  271. void reset (const char *input)
  272. {
  273. pstate->prev_lexptr = nullptr;
  274. pstate->lexptr = input;
  275. paren_depth = 0;
  276. current_token = 0;
  277. current_int_val = {};
  278. current_float_val = {};
  279. current_string_val = {};
  280. current_opcode = OP_NULL;
  281. }
  282. #endif /* GDB_SELF_TEST */
  283. /* Return the token's string value as a string. */
  284. std::string get_string () const
  285. {
  286. return std::string (current_string_val.ptr, current_string_val.length);
  287. }
  288. /* A pointer to this is installed globally. */
  289. auto_obstack obstack;
  290. /* The parser state gdb gave us. */
  291. struct parser_state *pstate;
  292. /* Depth of parentheses. */
  293. int paren_depth = 0;
  294. /* The current token's type. */
  295. int current_token = 0;
  296. /* The current token's payload, if any. */
  297. typed_val_int current_int_val {};
  298. typed_val_float current_float_val {};
  299. struct stoken current_string_val {};
  300. enum exp_opcode current_opcode = OP_NULL;
  301. /* When completing, this may be set to the field operation to
  302. complete. */
  303. operation_up completion_op;
  304. };
  305. /* Return an string referring to NAME, but relative to the crate's
  306. name. */
  307. std::string
  308. rust_parser::crate_name (const std::string &name)
  309. {
  310. std::string crate = rust_crate_for_block (pstate->expression_context_block);
  311. if (crate.empty ())
  312. error (_("Could not find crate for current location"));
  313. return "::" + crate + "::" + name;
  314. }
  315. /* Return a string referring to a "super::" qualified name. IDENT is
  316. the base name and N_SUPERS is how many "super::"s were provided.
  317. N_SUPERS can be zero. */
  318. std::string
  319. rust_parser::super_name (const std::string &ident, unsigned int n_supers)
  320. {
  321. const char *scope = block_scope (pstate->expression_context_block);
  322. int offset;
  323. if (scope[0] == '\0')
  324. error (_("Couldn't find namespace scope for self::"));
  325. if (n_supers > 0)
  326. {
  327. int len;
  328. std::vector<int> offsets;
  329. unsigned int current_len;
  330. current_len = cp_find_first_component (scope);
  331. while (scope[current_len] != '\0')
  332. {
  333. offsets.push_back (current_len);
  334. gdb_assert (scope[current_len] == ':');
  335. /* The "::". */
  336. current_len += 2;
  337. current_len += cp_find_first_component (scope
  338. + current_len);
  339. }
  340. len = offsets.size ();
  341. if (n_supers >= len)
  342. error (_("Too many super:: uses from '%s'"), scope);
  343. offset = offsets[len - n_supers];
  344. }
  345. else
  346. offset = strlen (scope);
  347. return "::" + std::string (scope, offset) + "::" + ident;
  348. }
  349. /* A helper to appropriately munge NAME and BLOCK depending on the
  350. presence of a leading "::". */
  351. static void
  352. munge_name_and_block (const char **name, const struct block **block)
  353. {
  354. /* If it is a global reference, skip the current block in favor of
  355. the static block. */
  356. if (startswith (*name, "::"))
  357. {
  358. *name += 2;
  359. *block = block_static_block (*block);
  360. }
  361. }
  362. /* Like lookup_symbol, but handles Rust namespace conventions, and
  363. doesn't require field_of_this_result. */
  364. struct block_symbol
  365. rust_parser::lookup_symbol (const char *name, const struct block *block,
  366. const domain_enum domain)
  367. {
  368. struct block_symbol result;
  369. munge_name_and_block (&name, &block);
  370. result = ::lookup_symbol (name, block, domain, NULL);
  371. if (result.symbol != NULL)
  372. update_innermost_block (result);
  373. return result;
  374. }
  375. /* Look up a type, following Rust namespace conventions. */
  376. struct type *
  377. rust_parser::rust_lookup_type (const char *name)
  378. {
  379. struct block_symbol result;
  380. struct type *type;
  381. const struct block *block = pstate->expression_context_block;
  382. munge_name_and_block (&name, &block);
  383. result = ::lookup_symbol (name, block, STRUCT_DOMAIN, NULL);
  384. if (result.symbol != NULL)
  385. {
  386. update_innermost_block (result);
  387. return result.symbol->type ();
  388. }
  389. type = lookup_typename (language (), name, NULL, 1);
  390. if (type != NULL)
  391. return type;
  392. /* Last chance, try a built-in type. */
  393. return language_lookup_primitive_type (language (), arch (), name);
  394. }
  395. /* A helper that updates the innermost block as appropriate. */
  396. void
  397. rust_parser::update_innermost_block (struct block_symbol sym)
  398. {
  399. if (symbol_read_needs_frame (sym.symbol))
  400. pstate->block_tracker->update (sym);
  401. }
  402. /* Lex a hex number with at least MIN digits and at most MAX
  403. digits. */
  404. uint32_t
  405. rust_parser::lex_hex (int min, int max)
  406. {
  407. uint32_t result = 0;
  408. int len = 0;
  409. /* We only want to stop at MAX if we're lexing a byte escape. */
  410. int check_max = min == max;
  411. while ((check_max ? len <= max : 1)
  412. && ((pstate->lexptr[0] >= 'a' && pstate->lexptr[0] <= 'f')
  413. || (pstate->lexptr[0] >= 'A' && pstate->lexptr[0] <= 'F')
  414. || (pstate->lexptr[0] >= '0' && pstate->lexptr[0] <= '9')))
  415. {
  416. result *= 16;
  417. if (pstate->lexptr[0] >= 'a' && pstate->lexptr[0] <= 'f')
  418. result = result + 10 + pstate->lexptr[0] - 'a';
  419. else if (pstate->lexptr[0] >= 'A' && pstate->lexptr[0] <= 'F')
  420. result = result + 10 + pstate->lexptr[0] - 'A';
  421. else
  422. result = result + pstate->lexptr[0] - '0';
  423. ++pstate->lexptr;
  424. ++len;
  425. }
  426. if (len < min)
  427. error (_("Not enough hex digits seen"));
  428. if (len > max)
  429. {
  430. gdb_assert (min != max);
  431. error (_("Overlong hex escape"));
  432. }
  433. return result;
  434. }
  435. /* Lex an escape. IS_BYTE is true if we're lexing a byte escape;
  436. otherwise we're lexing a character escape. */
  437. uint32_t
  438. rust_parser::lex_escape (int is_byte)
  439. {
  440. uint32_t result;
  441. gdb_assert (pstate->lexptr[0] == '\\');
  442. ++pstate->lexptr;
  443. switch (pstate->lexptr[0])
  444. {
  445. case 'x':
  446. ++pstate->lexptr;
  447. result = lex_hex (2, 2);
  448. break;
  449. case 'u':
  450. if (is_byte)
  451. error (_("Unicode escape in byte literal"));
  452. ++pstate->lexptr;
  453. if (pstate->lexptr[0] != '{')
  454. error (_("Missing '{' in Unicode escape"));
  455. ++pstate->lexptr;
  456. result = lex_hex (1, 6);
  457. /* Could do range checks here. */
  458. if (pstate->lexptr[0] != '}')
  459. error (_("Missing '}' in Unicode escape"));
  460. ++pstate->lexptr;
  461. break;
  462. case 'n':
  463. result = '\n';
  464. ++pstate->lexptr;
  465. break;
  466. case 'r':
  467. result = '\r';
  468. ++pstate->lexptr;
  469. break;
  470. case 't':
  471. result = '\t';
  472. ++pstate->lexptr;
  473. break;
  474. case '\\':
  475. result = '\\';
  476. ++pstate->lexptr;
  477. break;
  478. case '0':
  479. result = '\0';
  480. ++pstate->lexptr;
  481. break;
  482. case '\'':
  483. result = '\'';
  484. ++pstate->lexptr;
  485. break;
  486. case '"':
  487. result = '"';
  488. ++pstate->lexptr;
  489. break;
  490. default:
  491. error (_("Invalid escape \\%c in literal"), pstate->lexptr[0]);
  492. }
  493. return result;
  494. }
  495. /* A helper for lex_character. Search forward for the closing single
  496. quote, then convert the bytes from the host charset to UTF-32. */
  497. static uint32_t
  498. lex_multibyte_char (const char *text, int *len)
  499. {
  500. /* Only look a maximum of 5 bytes for the closing quote. This is
  501. the maximum for UTF-8. */
  502. int quote;
  503. gdb_assert (text[0] != '\'');
  504. for (quote = 1; text[quote] != '\0' && text[quote] != '\''; ++quote)
  505. ;
  506. *len = quote;
  507. /* The caller will issue an error. */
  508. if (text[quote] == '\0')
  509. return 0;
  510. auto_obstack result;
  511. convert_between_encodings (host_charset (), HOST_UTF32,
  512. (const gdb_byte *) text,
  513. quote, 1, &result, translit_none);
  514. int size = obstack_object_size (&result);
  515. if (size > 4)
  516. error (_("overlong character literal"));
  517. uint32_t value;
  518. memcpy (&value, obstack_finish (&result), size);
  519. return value;
  520. }
  521. /* Lex a character constant. */
  522. int
  523. rust_parser::lex_character ()
  524. {
  525. int is_byte = 0;
  526. uint32_t value;
  527. if (pstate->lexptr[0] == 'b')
  528. {
  529. is_byte = 1;
  530. ++pstate->lexptr;
  531. }
  532. gdb_assert (pstate->lexptr[0] == '\'');
  533. ++pstate->lexptr;
  534. if (pstate->lexptr[0] == '\'')
  535. error (_("empty character literal"));
  536. else if (pstate->lexptr[0] == '\\')
  537. value = lex_escape (is_byte);
  538. else
  539. {
  540. int len;
  541. value = lex_multibyte_char (&pstate->lexptr[0], &len);
  542. pstate->lexptr += len;
  543. }
  544. if (pstate->lexptr[0] != '\'')
  545. error (_("Unterminated character literal"));
  546. ++pstate->lexptr;
  547. current_int_val.val = value;
  548. current_int_val.type = get_type (is_byte ? "u8" : "char");
  549. return INTEGER;
  550. }
  551. /* Return the offset of the double quote if STR looks like the start
  552. of a raw string, or 0 if STR does not start a raw string. */
  553. static int
  554. starts_raw_string (const char *str)
  555. {
  556. const char *save = str;
  557. if (str[0] != 'r')
  558. return 0;
  559. ++str;
  560. while (str[0] == '#')
  561. ++str;
  562. if (str[0] == '"')
  563. return str - save;
  564. return 0;
  565. }
  566. /* Return true if STR looks like the end of a raw string that had N
  567. hashes at the start. */
  568. static bool
  569. ends_raw_string (const char *str, int n)
  570. {
  571. int i;
  572. gdb_assert (str[0] == '"');
  573. for (i = 0; i < n; ++i)
  574. if (str[i + 1] != '#')
  575. return false;
  576. return true;
  577. }
  578. /* Lex a string constant. */
  579. int
  580. rust_parser::lex_string ()
  581. {
  582. int is_byte = pstate->lexptr[0] == 'b';
  583. int raw_length;
  584. if (is_byte)
  585. ++pstate->lexptr;
  586. raw_length = starts_raw_string (pstate->lexptr);
  587. pstate->lexptr += raw_length;
  588. gdb_assert (pstate->lexptr[0] == '"');
  589. ++pstate->lexptr;
  590. while (1)
  591. {
  592. uint32_t value;
  593. if (raw_length > 0)
  594. {
  595. if (pstate->lexptr[0] == '"' && ends_raw_string (pstate->lexptr,
  596. raw_length - 1))
  597. {
  598. /* Exit with lexptr pointing after the final "#". */
  599. pstate->lexptr += raw_length;
  600. break;
  601. }
  602. else if (pstate->lexptr[0] == '\0')
  603. error (_("Unexpected EOF in string"));
  604. value = pstate->lexptr[0] & 0xff;
  605. if (is_byte && value > 127)
  606. error (_("Non-ASCII value in raw byte string"));
  607. obstack_1grow (&obstack, value);
  608. ++pstate->lexptr;
  609. }
  610. else if (pstate->lexptr[0] == '"')
  611. {
  612. /* Make sure to skip the quote. */
  613. ++pstate->lexptr;
  614. break;
  615. }
  616. else if (pstate->lexptr[0] == '\\')
  617. {
  618. value = lex_escape (is_byte);
  619. if (is_byte)
  620. obstack_1grow (&obstack, value);
  621. else
  622. convert_between_encodings (HOST_UTF32, "UTF-8",
  623. (gdb_byte *) &value,
  624. sizeof (value), sizeof (value),
  625. &obstack, translit_none);
  626. }
  627. else if (pstate->lexptr[0] == '\0')
  628. error (_("Unexpected EOF in string"));
  629. else
  630. {
  631. value = pstate->lexptr[0] & 0xff;
  632. if (is_byte && value > 127)
  633. error (_("Non-ASCII value in byte string"));
  634. obstack_1grow (&obstack, value);
  635. ++pstate->lexptr;
  636. }
  637. }
  638. current_string_val.length = obstack_object_size (&obstack);
  639. current_string_val.ptr = (const char *) obstack_finish (&obstack);
  640. return is_byte ? BYTESTRING : STRING;
  641. }
  642. /* Return true if STRING starts with whitespace followed by a digit. */
  643. static bool
  644. space_then_number (const char *string)
  645. {
  646. const char *p = string;
  647. while (p[0] == ' ' || p[0] == '\t')
  648. ++p;
  649. if (p == string)
  650. return false;
  651. return *p >= '0' && *p <= '9';
  652. }
  653. /* Return true if C can start an identifier. */
  654. static bool
  655. rust_identifier_start_p (char c)
  656. {
  657. return ((c >= 'a' && c <= 'z')
  658. || (c >= 'A' && c <= 'Z')
  659. || c == '_'
  660. || c == '$'
  661. /* Allow any non-ASCII character as an identifier. There
  662. doesn't seem to be a need to be picky about this. */
  663. || (c & 0x80) != 0);
  664. }
  665. /* Lex an identifier. */
  666. int
  667. rust_parser::lex_identifier ()
  668. {
  669. unsigned int length;
  670. const struct token_info *token;
  671. int is_gdb_var = pstate->lexptr[0] == '$';
  672. bool is_raw = false;
  673. if (pstate->lexptr[0] == 'r'
  674. && pstate->lexptr[1] == '#'
  675. && rust_identifier_start_p (pstate->lexptr[2]))
  676. {
  677. is_raw = true;
  678. pstate->lexptr += 2;
  679. }
  680. const char *start = pstate->lexptr;
  681. gdb_assert (rust_identifier_start_p (pstate->lexptr[0]));
  682. ++pstate->lexptr;
  683. /* Allow any non-ASCII character here. This "handles" UTF-8 by
  684. passing it through. */
  685. while ((pstate->lexptr[0] >= 'a' && pstate->lexptr[0] <= 'z')
  686. || (pstate->lexptr[0] >= 'A' && pstate->lexptr[0] <= 'Z')
  687. || pstate->lexptr[0] == '_'
  688. || (is_gdb_var && pstate->lexptr[0] == '$')
  689. || (pstate->lexptr[0] >= '0' && pstate->lexptr[0] <= '9')
  690. || (pstate->lexptr[0] & 0x80) != 0)
  691. ++pstate->lexptr;
  692. length = pstate->lexptr - start;
  693. token = NULL;
  694. if (!is_raw)
  695. {
  696. for (const auto &candidate : identifier_tokens)
  697. {
  698. if (length == strlen (candidate.name)
  699. && strncmp (candidate.name, start, length) == 0)
  700. {
  701. token = &candidate;
  702. break;
  703. }
  704. }
  705. }
  706. if (token != NULL)
  707. {
  708. if (token->value == 0)
  709. {
  710. /* Leave the terminating token alone. */
  711. pstate->lexptr = start;
  712. return 0;
  713. }
  714. }
  715. else if (token == NULL
  716. && !is_raw
  717. && (strncmp (start, "thread", length) == 0
  718. || strncmp (start, "task", length) == 0)
  719. && space_then_number (pstate->lexptr))
  720. {
  721. /* "task" or "thread" followed by a number terminates the
  722. parse, per gdb rules. */
  723. pstate->lexptr = start;
  724. return 0;
  725. }
  726. if (token == NULL || (pstate->parse_completion && pstate->lexptr[0] == '\0'))
  727. {
  728. current_string_val.length = length;
  729. current_string_val.ptr = start;
  730. }
  731. if (pstate->parse_completion && pstate->lexptr[0] == '\0')
  732. {
  733. /* Prevent rustyylex from returning two COMPLETE tokens. */
  734. pstate->prev_lexptr = pstate->lexptr;
  735. return COMPLETE;
  736. }
  737. if (token != NULL)
  738. return token->value;
  739. if (is_gdb_var)
  740. return GDBVAR;
  741. return IDENT;
  742. }
  743. /* Lex an operator. */
  744. int
  745. rust_parser::lex_operator ()
  746. {
  747. const struct token_info *token = NULL;
  748. for (const auto &candidate : operator_tokens)
  749. {
  750. if (strncmp (candidate.name, pstate->lexptr,
  751. strlen (candidate.name)) == 0)
  752. {
  753. pstate->lexptr += strlen (candidate.name);
  754. token = &candidate;
  755. break;
  756. }
  757. }
  758. if (token != NULL)
  759. {
  760. current_opcode = token->opcode;
  761. return token->value;
  762. }
  763. return *pstate->lexptr++;
  764. }
  765. /* Lex a number. */
  766. int
  767. rust_parser::lex_number ()
  768. {
  769. regmatch_t subexps[NUM_SUBEXPRESSIONS];
  770. int match;
  771. int is_integer = 0;
  772. int could_be_decimal = 1;
  773. int implicit_i32 = 0;
  774. const char *type_name = NULL;
  775. struct type *type;
  776. int end_index;
  777. int type_index = -1;
  778. int i;
  779. match = regexec (&number_regex, pstate->lexptr, ARRAY_SIZE (subexps),
  780. subexps, 0);
  781. /* Failure means the regexp is broken. */
  782. gdb_assert (match == 0);
  783. if (subexps[INT_TEXT].rm_so != -1)
  784. {
  785. /* Integer part matched. */
  786. is_integer = 1;
  787. end_index = subexps[INT_TEXT].rm_eo;
  788. if (subexps[INT_TYPE].rm_so == -1)
  789. {
  790. type_name = "i32";
  791. implicit_i32 = 1;
  792. }
  793. else
  794. {
  795. type_index = INT_TYPE;
  796. could_be_decimal = 0;
  797. }
  798. }
  799. else if (subexps[FLOAT_TYPE1].rm_so != -1)
  800. {
  801. /* Found floating point type suffix. */
  802. end_index = subexps[FLOAT_TYPE1].rm_so;
  803. type_index = FLOAT_TYPE1;
  804. }
  805. else if (subexps[FLOAT_TYPE2].rm_so != -1)
  806. {
  807. /* Found floating point type suffix. */
  808. end_index = subexps[FLOAT_TYPE2].rm_so;
  809. type_index = FLOAT_TYPE2;
  810. }
  811. else
  812. {
  813. /* Any other floating point match. */
  814. end_index = subexps[0].rm_eo;
  815. type_name = "f64";
  816. }
  817. /* We need a special case if the final character is ".". In this
  818. case we might need to parse an integer. For example, "23.f()" is
  819. a request for a trait method call, not a syntax error involving
  820. the floating point number "23.". */
  821. gdb_assert (subexps[0].rm_eo > 0);
  822. if (pstate->lexptr[subexps[0].rm_eo - 1] == '.')
  823. {
  824. const char *next = skip_spaces (&pstate->lexptr[subexps[0].rm_eo]);
  825. if (rust_identifier_start_p (*next) || *next == '.')
  826. {
  827. --subexps[0].rm_eo;
  828. is_integer = 1;
  829. end_index = subexps[0].rm_eo;
  830. type_name = "i32";
  831. could_be_decimal = 1;
  832. implicit_i32 = 1;
  833. }
  834. }
  835. /* Compute the type name if we haven't already. */
  836. std::string type_name_holder;
  837. if (type_name == NULL)
  838. {
  839. gdb_assert (type_index != -1);
  840. type_name_holder = std::string ((pstate->lexptr
  841. + subexps[type_index].rm_so),
  842. (subexps[type_index].rm_eo
  843. - subexps[type_index].rm_so));
  844. type_name = type_name_holder.c_str ();
  845. }
  846. /* Look up the type. */
  847. type = get_type (type_name);
  848. /* Copy the text of the number and remove the "_"s. */
  849. std::string number;
  850. for (i = 0; i < end_index && pstate->lexptr[i]; ++i)
  851. {
  852. if (pstate->lexptr[i] == '_')
  853. could_be_decimal = 0;
  854. else
  855. number.push_back (pstate->lexptr[i]);
  856. }
  857. /* Advance past the match. */
  858. pstate->lexptr += subexps[0].rm_eo;
  859. /* Parse the number. */
  860. if (is_integer)
  861. {
  862. uint64_t value;
  863. int radix = 10;
  864. int offset = 0;
  865. if (number[0] == '0')
  866. {
  867. if (number[1] == 'x')
  868. radix = 16;
  869. else if (number[1] == 'o')
  870. radix = 8;
  871. else if (number[1] == 'b')
  872. radix = 2;
  873. if (radix != 10)
  874. {
  875. offset = 2;
  876. could_be_decimal = 0;
  877. }
  878. }
  879. value = strtoulst (number.c_str () + offset, NULL, radix);
  880. if (implicit_i32 && value >= ((uint64_t) 1) << 31)
  881. type = get_type ("i64");
  882. current_int_val.val = value;
  883. current_int_val.type = type;
  884. }
  885. else
  886. {
  887. current_float_val.type = type;
  888. bool parsed = parse_float (number.c_str (), number.length (),
  889. current_float_val.type,
  890. current_float_val.val.data ());
  891. gdb_assert (parsed);
  892. }
  893. return is_integer ? (could_be_decimal ? DECIMAL_INTEGER : INTEGER) : FLOAT;
  894. }
  895. /* The lexer. */
  896. int
  897. rust_parser::lex_one_token ()
  898. {
  899. /* Skip all leading whitespace. */
  900. while (pstate->lexptr[0] == ' '
  901. || pstate->lexptr[0] == '\t'
  902. || pstate->lexptr[0] == '\r'
  903. || pstate->lexptr[0] == '\n')
  904. ++pstate->lexptr;
  905. /* If we hit EOF and we're completing, then return COMPLETE -- maybe
  906. we're completing an empty string at the end of a field_expr.
  907. But, we don't want to return two COMPLETE tokens in a row. */
  908. if (pstate->lexptr[0] == '\0' && pstate->lexptr == pstate->prev_lexptr)
  909. return 0;
  910. pstate->prev_lexptr = pstate->lexptr;
  911. if (pstate->lexptr[0] == '\0')
  912. {
  913. if (pstate->parse_completion)
  914. {
  915. current_string_val.length =0;
  916. current_string_val.ptr = "";
  917. return COMPLETE;
  918. }
  919. return 0;
  920. }
  921. if (pstate->lexptr[0] >= '0' && pstate->lexptr[0] <= '9')
  922. return lex_number ();
  923. else if (pstate->lexptr[0] == 'b' && pstate->lexptr[1] == '\'')
  924. return lex_character ();
  925. else if (pstate->lexptr[0] == 'b' && pstate->lexptr[1] == '"')
  926. return lex_string ();
  927. else if (pstate->lexptr[0] == 'b' && starts_raw_string (pstate->lexptr + 1))
  928. return lex_string ();
  929. else if (starts_raw_string (pstate->lexptr))
  930. return lex_string ();
  931. else if (rust_identifier_start_p (pstate->lexptr[0]))
  932. return lex_identifier ();
  933. else if (pstate->lexptr[0] == '"')
  934. return lex_string ();
  935. else if (pstate->lexptr[0] == '\'')
  936. return lex_character ();
  937. else if (pstate->lexptr[0] == '}' || pstate->lexptr[0] == ']')
  938. {
  939. /* Falls through to lex_operator. */
  940. --paren_depth;
  941. }
  942. else if (pstate->lexptr[0] == '(' || pstate->lexptr[0] == '{')
  943. {
  944. /* Falls through to lex_operator. */
  945. ++paren_depth;
  946. }
  947. else if (pstate->lexptr[0] == ',' && pstate->comma_terminates
  948. && paren_depth == 0)
  949. return 0;
  950. return lex_operator ();
  951. }
  952. /* Push back a single character to be re-lexed. */
  953. void
  954. rust_parser::push_back (char c)
  955. {
  956. /* Can't be called before any lexing. */
  957. gdb_assert (pstate->prev_lexptr != NULL);
  958. --pstate->lexptr;
  959. gdb_assert (*pstate->lexptr == c);
  960. }
  961. /* Parse a tuple or paren expression. */
  962. operation_up
  963. rust_parser::parse_tuple ()
  964. {
  965. assume ('(');
  966. if (current_token == ')')
  967. {
  968. lex ();
  969. struct type *unit = get_type ("()");
  970. return make_operation<long_const_operation> (unit, 0);
  971. }
  972. operation_up expr = parse_expr ();
  973. if (current_token == ')')
  974. {
  975. /* Parenthesized expression. */
  976. lex ();
  977. return make_operation<rust_parenthesized_operation> (std::move (expr));
  978. }
  979. std::vector<operation_up> ops;
  980. ops.push_back (std::move (expr));
  981. while (current_token != ')')
  982. {
  983. if (current_token != ',')
  984. error (_("',' or ')' expected"));
  985. lex ();
  986. /* A trailing "," is ok. */
  987. if (current_token != ')')
  988. ops.push_back (parse_expr ());
  989. }
  990. assume (')');
  991. error (_("Tuple expressions not supported yet"));
  992. }
  993. /* Parse an array expression. */
  994. operation_up
  995. rust_parser::parse_array ()
  996. {
  997. assume ('[');
  998. if (current_token == KW_MUT)
  999. lex ();
  1000. operation_up result;
  1001. operation_up expr = parse_expr ();
  1002. if (current_token == ';')
  1003. {
  1004. lex ();
  1005. operation_up rhs = parse_expr ();
  1006. result = make_operation<rust_array_operation> (std::move (expr),
  1007. std::move (rhs));
  1008. }
  1009. else if (current_token == ',')
  1010. {
  1011. std::vector<operation_up> ops;
  1012. ops.push_back (std::move (expr));
  1013. while (current_token != ']')
  1014. {
  1015. if (current_token != ',')
  1016. error (_("',' or ']' expected"));
  1017. lex ();
  1018. ops.push_back (parse_expr ());
  1019. }
  1020. ops.shrink_to_fit ();
  1021. int len = ops.size () - 1;
  1022. result = make_operation<array_operation> (0, len, std::move (ops));
  1023. }
  1024. else if (current_token != ']')
  1025. error (_("',', ';', or ']' expected"));
  1026. require (']');
  1027. return result;
  1028. }
  1029. /* Turn a name into an operation. */
  1030. operation_up
  1031. rust_parser::name_to_operation (const std::string &name)
  1032. {
  1033. struct block_symbol sym = lookup_symbol (name.c_str (),
  1034. pstate->expression_context_block,
  1035. VAR_DOMAIN);
  1036. if (sym.symbol != nullptr && sym.symbol->aclass () != LOC_TYPEDEF)
  1037. return make_operation<var_value_operation> (sym);
  1038. struct type *type = nullptr;
  1039. if (sym.symbol != nullptr)
  1040. {
  1041. gdb_assert (sym.symbol->aclass () == LOC_TYPEDEF);
  1042. type = sym.symbol->type ();
  1043. }
  1044. if (type == nullptr)
  1045. type = rust_lookup_type (name.c_str ());
  1046. if (type == nullptr)
  1047. error (_("No symbol '%s' in current context"), name.c_str ());
  1048. if (type->code () == TYPE_CODE_STRUCT && type->num_fields () == 0)
  1049. {
  1050. /* A unit-like struct. */
  1051. operation_up result (new rust_aggregate_operation (type, {}, {}));
  1052. return result;
  1053. }
  1054. else
  1055. return make_operation<type_operation> (type);
  1056. }
  1057. /* Parse a struct expression. */
  1058. operation_up
  1059. rust_parser::parse_struct_expr (struct type *type)
  1060. {
  1061. assume ('{');
  1062. if (type->code () != TYPE_CODE_STRUCT
  1063. || rust_tuple_type_p (type)
  1064. || rust_tuple_struct_type_p (type))
  1065. error (_("Struct expression applied to non-struct type"));
  1066. std::vector<std::pair<std::string, operation_up>> field_v;
  1067. while (current_token != '}' && current_token != DOTDOT)
  1068. {
  1069. if (current_token != IDENT)
  1070. error (_("'}', '..', or identifier expected"));
  1071. std::string name = get_string ();
  1072. lex ();
  1073. operation_up expr;
  1074. if (current_token == ',' || current_token == '}'
  1075. || current_token == DOTDOT)
  1076. expr = name_to_operation (name);
  1077. else
  1078. {
  1079. require (':');
  1080. expr = parse_expr ();
  1081. }
  1082. field_v.emplace_back (std::move (name), std::move (expr));
  1083. /* A trailing "," is ok. */
  1084. if (current_token == ',')
  1085. lex ();
  1086. }
  1087. operation_up others;
  1088. if (current_token == DOTDOT)
  1089. {
  1090. lex ();
  1091. others = parse_expr ();
  1092. }
  1093. require ('}');
  1094. return make_operation<rust_aggregate_operation> (type,
  1095. std::move (others),
  1096. std::move (field_v));
  1097. }
  1098. /* Used by the operator precedence parser. */
  1099. struct rustop_item
  1100. {
  1101. rustop_item (int token_, int precedence_, enum exp_opcode opcode_,
  1102. operation_up &&op_)
  1103. : token (token_),
  1104. precedence (precedence_),
  1105. opcode (opcode_),
  1106. op (std::move (op_))
  1107. {
  1108. }
  1109. /* The token value. */
  1110. int token;
  1111. /* Precedence of this operator. */
  1112. int precedence;
  1113. /* This is used only for assign-modify. */
  1114. enum exp_opcode opcode;
  1115. /* The right hand side of this operation. */
  1116. operation_up op;
  1117. };
  1118. /* An operator precedence parser for binary operations, including
  1119. "as". */
  1120. operation_up
  1121. rust_parser::parse_binop (bool required)
  1122. {
  1123. /* All the binary operators. Each one is of the form
  1124. OPERATION(TOKEN, PRECEDENCE, TYPE)
  1125. TOKEN is the corresponding operator token.
  1126. PRECEDENCE is a value indicating relative precedence.
  1127. TYPE is the operation type corresponding to the operator.
  1128. Assignment operations are handled specially, not via this
  1129. table; they have precedence 0. */
  1130. #define ALL_OPS \
  1131. OPERATION ('*', 10, mul_operation) \
  1132. OPERATION ('/', 10, div_operation) \
  1133. OPERATION ('%', 10, rem_operation) \
  1134. OPERATION ('@', 9, repeat_operation) \
  1135. OPERATION ('+', 8, add_operation) \
  1136. OPERATION ('-', 8, sub_operation) \
  1137. OPERATION (LSH, 7, lsh_operation) \
  1138. OPERATION (RSH, 7, rsh_operation) \
  1139. OPERATION ('&', 6, bitwise_and_operation) \
  1140. OPERATION ('^', 5, bitwise_xor_operation) \
  1141. OPERATION ('|', 4, bitwise_ior_operation) \
  1142. OPERATION (EQEQ, 3, equal_operation) \
  1143. OPERATION (NOTEQ, 3, notequal_operation) \
  1144. OPERATION ('<', 3, less_operation) \
  1145. OPERATION (LTEQ, 3, leq_operation) \
  1146. OPERATION ('>', 3, gtr_operation) \
  1147. OPERATION (GTEQ, 3, geq_operation) \
  1148. OPERATION (ANDAND, 2, logical_and_operation) \
  1149. OPERATION (OROR, 1, logical_or_operation)
  1150. operation_up start = parse_atom (required);
  1151. if (start == nullptr)
  1152. {
  1153. gdb_assert (!required);
  1154. return start;
  1155. }
  1156. std::vector<rustop_item> operator_stack;
  1157. operator_stack.emplace_back (0, -1, OP_NULL, std::move (start));
  1158. while (true)
  1159. {
  1160. int this_token = current_token;
  1161. enum exp_opcode compound_assign_op = OP_NULL;
  1162. int precedence = -2;
  1163. switch (this_token)
  1164. {
  1165. #define OPERATION(TOKEN, PRECEDENCE, TYPE) \
  1166. case TOKEN: \
  1167. precedence = PRECEDENCE; \
  1168. lex (); \
  1169. break;
  1170. ALL_OPS
  1171. #undef OPERATION
  1172. case COMPOUND_ASSIGN:
  1173. compound_assign_op = current_opcode;
  1174. /* FALLTHROUGH */
  1175. case '=':
  1176. precedence = 0;
  1177. lex ();
  1178. break;
  1179. /* "as" must be handled specially. */
  1180. case KW_AS:
  1181. {
  1182. lex ();
  1183. rustop_item &lhs = operator_stack.back ();
  1184. struct type *type = parse_type ();
  1185. lhs.op = make_operation<unop_cast_operation> (std::move (lhs.op),
  1186. type);
  1187. }
  1188. /* Bypass the rest of the loop. */
  1189. continue;
  1190. default:
  1191. /* Arrange to pop the entire stack. */
  1192. precedence = -2;
  1193. break;
  1194. }
  1195. while (precedence < operator_stack.back ().precedence
  1196. && operator_stack.size () > 1)
  1197. {
  1198. rustop_item rhs = std::move (operator_stack.back ());
  1199. operator_stack.pop_back ();
  1200. rustop_item &lhs = operator_stack.back ();
  1201. switch (rhs.token)
  1202. {
  1203. #define OPERATION(TOKEN, PRECEDENCE, TYPE) \
  1204. case TOKEN: \
  1205. lhs.op = make_operation<TYPE> (std::move (lhs.op), \
  1206. std::move (rhs.op)); \
  1207. break;
  1208. ALL_OPS
  1209. #undef OPERATION
  1210. case '=':
  1211. case COMPOUND_ASSIGN:
  1212. {
  1213. if (rhs.token == '=')
  1214. lhs.op = (make_operation<assign_operation>
  1215. (std::move (lhs.op), std::move (rhs.op)));
  1216. else
  1217. lhs.op = (make_operation<assign_modify_operation>
  1218. (rhs.opcode, std::move (lhs.op),
  1219. std::move (rhs.op)));
  1220. struct type *unit_type = get_type ("()");
  1221. operation_up nil (new long_const_operation (unit_type, 0));
  1222. lhs.op = (make_operation<comma_operation>
  1223. (std::move (lhs.op), std::move (nil)));
  1224. }
  1225. break;
  1226. default:
  1227. gdb_assert_not_reached ("bad binary operator");
  1228. }
  1229. }
  1230. if (precedence == -2)
  1231. break;
  1232. operator_stack.emplace_back (this_token, precedence, compound_assign_op,
  1233. parse_atom (true));
  1234. }
  1235. gdb_assert (operator_stack.size () == 1);
  1236. return std::move (operator_stack[0].op);
  1237. #undef ALL_OPS
  1238. }
  1239. /* Parse a range expression. */
  1240. operation_up
  1241. rust_parser::parse_range ()
  1242. {
  1243. enum range_flag kind = (RANGE_HIGH_BOUND_DEFAULT
  1244. | RANGE_LOW_BOUND_DEFAULT);
  1245. operation_up lhs;
  1246. if (current_token != DOTDOT && current_token != DOTDOTEQ)
  1247. {
  1248. lhs = parse_binop (true);
  1249. kind &= ~RANGE_LOW_BOUND_DEFAULT;
  1250. }
  1251. if (current_token == DOTDOT)
  1252. kind |= RANGE_HIGH_BOUND_EXCLUSIVE;
  1253. else if (current_token != DOTDOTEQ)
  1254. return lhs;
  1255. lex ();
  1256. /* A "..=" range requires a high bound, but otherwise it is
  1257. optional. */
  1258. operation_up rhs = parse_binop ((kind & RANGE_HIGH_BOUND_EXCLUSIVE) == 0);
  1259. if (rhs != nullptr)
  1260. kind &= ~RANGE_HIGH_BOUND_DEFAULT;
  1261. return make_operation<rust_range_operation> (kind,
  1262. std::move (lhs),
  1263. std::move (rhs));
  1264. }
  1265. /* Parse an expression. */
  1266. operation_up
  1267. rust_parser::parse_expr ()
  1268. {
  1269. return parse_range ();
  1270. }
  1271. /* Parse a sizeof expression. */
  1272. operation_up
  1273. rust_parser::parse_sizeof ()
  1274. {
  1275. assume (KW_SIZEOF);
  1276. require ('(');
  1277. operation_up result = make_operation<unop_sizeof_operation> (parse_expr ());
  1278. require (')');
  1279. return result;
  1280. }
  1281. /* Parse an address-of operation. */
  1282. operation_up
  1283. rust_parser::parse_addr ()
  1284. {
  1285. assume ('&');
  1286. if (current_token == KW_MUT)
  1287. lex ();
  1288. return make_operation<rust_unop_addr_operation> (parse_atom (true));
  1289. }
  1290. /* Parse a field expression. */
  1291. operation_up
  1292. rust_parser::parse_field (operation_up &&lhs)
  1293. {
  1294. assume ('.');
  1295. operation_up result;
  1296. switch (current_token)
  1297. {
  1298. case IDENT:
  1299. case COMPLETE:
  1300. {
  1301. bool is_complete = current_token == COMPLETE;
  1302. auto struct_op = new rust_structop (std::move (lhs), get_string ());
  1303. lex ();
  1304. if (is_complete)
  1305. {
  1306. completion_op.reset (struct_op);
  1307. pstate->mark_struct_expression (struct_op);
  1308. /* Throw to the outermost level of the parser. */
  1309. error (_("not really an error"));
  1310. }
  1311. result.reset (struct_op);
  1312. }
  1313. break;
  1314. case DECIMAL_INTEGER:
  1315. result = make_operation<rust_struct_anon> (current_int_val.val,
  1316. std::move (lhs));
  1317. lex ();
  1318. break;
  1319. case INTEGER:
  1320. error (_("'_' not allowed in integers in anonymous field references"));
  1321. default:
  1322. error (_("field name expected"));
  1323. }
  1324. return result;
  1325. }
  1326. /* Parse an index expression. */
  1327. operation_up
  1328. rust_parser::parse_index (operation_up &&lhs)
  1329. {
  1330. assume ('[');
  1331. operation_up rhs = parse_expr ();
  1332. require (']');
  1333. return make_operation<rust_subscript_operation> (std::move (lhs),
  1334. std::move (rhs));
  1335. }
  1336. /* Parse a sequence of comma-separated expressions in parens. */
  1337. std::vector<operation_up>
  1338. rust_parser::parse_paren_args ()
  1339. {
  1340. assume ('(');
  1341. std::vector<operation_up> args;
  1342. while (current_token != ')')
  1343. {
  1344. if (!args.empty ())
  1345. {
  1346. if (current_token != ',')
  1347. error (_("',' or ')' expected"));
  1348. lex ();
  1349. }
  1350. args.push_back (parse_expr ());
  1351. }
  1352. assume (')');
  1353. return args;
  1354. }
  1355. /* Parse the parenthesized part of a function call. */
  1356. operation_up
  1357. rust_parser::parse_call (operation_up &&lhs)
  1358. {
  1359. std::vector<operation_up> args = parse_paren_args ();
  1360. return make_operation<funcall_operation> (std::move (lhs),
  1361. std::move (args));
  1362. }
  1363. /* Parse a list of types. */
  1364. std::vector<struct type *>
  1365. rust_parser::parse_type_list ()
  1366. {
  1367. std::vector<struct type *> result;
  1368. result.push_back (parse_type ());
  1369. while (current_token == ',')
  1370. {
  1371. lex ();
  1372. result.push_back (parse_type ());
  1373. }
  1374. return result;
  1375. }
  1376. /* Parse a possibly-empty list of types, surrounded in parens. */
  1377. std::vector<struct type *>
  1378. rust_parser::parse_maybe_type_list ()
  1379. {
  1380. assume ('(');
  1381. std::vector<struct type *> types;
  1382. if (current_token != ')')
  1383. types = parse_type_list ();
  1384. require (')');
  1385. return types;
  1386. }
  1387. /* Parse an array type. */
  1388. struct type *
  1389. rust_parser::parse_array_type ()
  1390. {
  1391. assume ('[');
  1392. struct type *elt_type = parse_type ();
  1393. require (';');
  1394. if (current_token != INTEGER && current_token != DECIMAL_INTEGER)
  1395. error (_("integer expected"));
  1396. ULONGEST val = current_int_val.val;
  1397. lex ();
  1398. require (']');
  1399. return lookup_array_range_type (elt_type, 0, val - 1);
  1400. }
  1401. /* Parse a slice type. */
  1402. struct type *
  1403. rust_parser::parse_slice_type ()
  1404. {
  1405. assume ('&');
  1406. bool is_slice = current_token == '[';
  1407. if (is_slice)
  1408. lex ();
  1409. struct type *target = parse_type ();
  1410. if (is_slice)
  1411. {
  1412. require (']');
  1413. return rust_slice_type ("&[*gdb*]", target, get_type ("usize"));
  1414. }
  1415. /* For now we treat &x and *x identically. */
  1416. return lookup_pointer_type (target);
  1417. }
  1418. /* Parse a pointer type. */
  1419. struct type *
  1420. rust_parser::parse_pointer_type ()
  1421. {
  1422. assume ('*');
  1423. if (current_token == KW_MUT || current_token == KW_CONST)
  1424. lex ();
  1425. struct type *target = parse_type ();
  1426. /* For the time being we ignore mut/const. */
  1427. return lookup_pointer_type (target);
  1428. }
  1429. /* Parse a function type. */
  1430. struct type *
  1431. rust_parser::parse_function_type ()
  1432. {
  1433. assume (KW_FN);
  1434. if (current_token != '(')
  1435. error (_("'(' expected"));
  1436. std::vector<struct type *> types = parse_maybe_type_list ();
  1437. if (current_token != ARROW)
  1438. error (_("'->' expected"));
  1439. lex ();
  1440. struct type *result_type = parse_type ();
  1441. struct type **argtypes = nullptr;
  1442. if (!types.empty ())
  1443. argtypes = types.data ();
  1444. result_type = lookup_function_type_with_arguments (result_type,
  1445. types.size (),
  1446. argtypes);
  1447. return lookup_pointer_type (result_type);
  1448. }
  1449. /* Parse a tuple type. */
  1450. struct type *
  1451. rust_parser::parse_tuple_type ()
  1452. {
  1453. std::vector<struct type *> types = parse_maybe_type_list ();
  1454. auto_obstack obstack;
  1455. obstack_1grow (&obstack, '(');
  1456. for (int i = 0; i < types.size (); ++i)
  1457. {
  1458. std::string type_name = type_to_string (types[i]);
  1459. if (i > 0)
  1460. obstack_1grow (&obstack, ',');
  1461. obstack_grow_str (&obstack, type_name.c_str ());
  1462. }
  1463. obstack_grow_str0 (&obstack, ")");
  1464. const char *name = (const char *) obstack_finish (&obstack);
  1465. /* We don't allow creating new tuple types (yet), but we do allow
  1466. looking up existing tuple types. */
  1467. struct type *result = rust_lookup_type (name);
  1468. if (result == nullptr)
  1469. error (_("could not find tuple type '%s'"), name);
  1470. return result;
  1471. }
  1472. /* Parse a type. */
  1473. struct type *
  1474. rust_parser::parse_type ()
  1475. {
  1476. switch (current_token)
  1477. {
  1478. case '[':
  1479. return parse_array_type ();
  1480. case '&':
  1481. return parse_slice_type ();
  1482. case '*':
  1483. return parse_pointer_type ();
  1484. case KW_FN:
  1485. return parse_function_type ();
  1486. case '(':
  1487. return parse_tuple_type ();
  1488. case KW_SELF:
  1489. case KW_SUPER:
  1490. case COLONCOLON:
  1491. case KW_EXTERN:
  1492. case IDENT:
  1493. {
  1494. std::string path = parse_path (false);
  1495. struct type *result = rust_lookup_type (path.c_str ());
  1496. if (result == nullptr)
  1497. error (_("No type name '%s' in current context"), path.c_str ());
  1498. return result;
  1499. }
  1500. default:
  1501. error (_("type expected"));
  1502. }
  1503. }
  1504. /* Parse a path. */
  1505. std::string
  1506. rust_parser::parse_path (bool for_expr)
  1507. {
  1508. unsigned n_supers = 0;
  1509. int first_token = current_token;
  1510. switch (current_token)
  1511. {
  1512. case KW_SELF:
  1513. lex ();
  1514. if (current_token != COLONCOLON)
  1515. return "self";
  1516. lex ();
  1517. /* FALLTHROUGH */
  1518. case KW_SUPER:
  1519. while (current_token == KW_SUPER)
  1520. {
  1521. ++n_supers;
  1522. lex ();
  1523. if (current_token != COLONCOLON)
  1524. error (_("'::' expected"));
  1525. lex ();
  1526. }
  1527. break;
  1528. case COLONCOLON:
  1529. lex ();
  1530. break;
  1531. case KW_EXTERN:
  1532. /* This is a gdb extension to make it possible to refer to items
  1533. in other crates. It just bypasses adding the current crate
  1534. to the front of the name. */
  1535. lex ();
  1536. break;
  1537. }
  1538. if (current_token != IDENT)
  1539. error (_("identifier expected"));
  1540. std::string path = get_string ();
  1541. bool saw_ident = true;
  1542. lex ();
  1543. /* The condition here lets us enter the loop even if we see
  1544. "ident<...>". */
  1545. while (current_token == COLONCOLON || current_token == '<')
  1546. {
  1547. if (current_token == COLONCOLON)
  1548. {
  1549. lex ();
  1550. saw_ident = false;
  1551. if (current_token == IDENT)
  1552. {
  1553. path = path + "::" + get_string ();
  1554. lex ();
  1555. saw_ident = true;
  1556. }
  1557. else if (current_token == COLONCOLON)
  1558. {
  1559. /* The code below won't detect this scenario. */
  1560. error (_("unexpected '::'"));
  1561. }
  1562. }
  1563. if (current_token != '<')
  1564. continue;
  1565. /* Expression use name::<...>, whereas types use name<...>. */
  1566. if (for_expr)
  1567. {
  1568. /* Expressions use "name::<...>", so if we saw an identifier
  1569. after the "::", we ignore the "<" here. */
  1570. if (saw_ident)
  1571. break;
  1572. }
  1573. else
  1574. {
  1575. /* Types use "name<...>", so we need to have seen the
  1576. identifier. */
  1577. if (!saw_ident)
  1578. break;
  1579. }
  1580. lex ();
  1581. std::vector<struct type *> types = parse_type_list ();
  1582. if (current_token == '>')
  1583. lex ();
  1584. else if (current_token == RSH)
  1585. {
  1586. push_back ('>');
  1587. lex ();
  1588. }
  1589. else
  1590. error (_("'>' expected"));
  1591. path += "<";
  1592. for (int i = 0; i < types.size (); ++i)
  1593. {
  1594. if (i > 0)
  1595. path += ",";
  1596. path += type_to_string (types[i]);
  1597. }
  1598. path += ">";
  1599. break;
  1600. }
  1601. switch (first_token)
  1602. {
  1603. case KW_SELF:
  1604. case KW_SUPER:
  1605. return super_name (path, n_supers);
  1606. case COLONCOLON:
  1607. return crate_name (path);
  1608. case KW_EXTERN:
  1609. return "::" + path;
  1610. case IDENT:
  1611. return path;
  1612. default:
  1613. gdb_assert_not_reached ("missing case in path parsing");
  1614. }
  1615. }
  1616. /* Handle the parsing for a string expression. */
  1617. operation_up
  1618. rust_parser::parse_string ()
  1619. {
  1620. gdb_assert (current_token == STRING);
  1621. /* Wrap the raw string in the &str struct. */
  1622. struct type *type = rust_lookup_type ("&str");
  1623. if (type == nullptr)
  1624. error (_("Could not find type '&str'"));
  1625. std::vector<std::pair<std::string, operation_up>> field_v;
  1626. size_t len = current_string_val.length;
  1627. operation_up str = make_operation<string_operation> (get_string ());
  1628. operation_up addr
  1629. = make_operation<rust_unop_addr_operation> (std::move (str));
  1630. field_v.emplace_back ("data_ptr", std::move (addr));
  1631. struct type *valtype = get_type ("usize");
  1632. operation_up lenop = make_operation<long_const_operation> (valtype, len);
  1633. field_v.emplace_back ("length", std::move (lenop));
  1634. return make_operation<rust_aggregate_operation> (type,
  1635. operation_up (),
  1636. std::move (field_v));
  1637. }
  1638. /* Parse a tuple struct expression. */
  1639. operation_up
  1640. rust_parser::parse_tuple_struct (struct type *type)
  1641. {
  1642. std::vector<operation_up> args = parse_paren_args ();
  1643. std::vector<std::pair<std::string, operation_up>> field_v (args.size ());
  1644. for (int i = 0; i < args.size (); ++i)
  1645. field_v[i] = { string_printf ("__%d", i), std::move (args[i]) };
  1646. return (make_operation<rust_aggregate_operation>
  1647. (type, operation_up (), std::move (field_v)));
  1648. }
  1649. /* Parse a path expression. */
  1650. operation_up
  1651. rust_parser::parse_path_expr ()
  1652. {
  1653. std::string path = parse_path (true);
  1654. if (current_token == '{')
  1655. {
  1656. struct type *type = rust_lookup_type (path.c_str ());
  1657. if (type == nullptr)
  1658. error (_("Could not find type '%s'"), path.c_str ());
  1659. return parse_struct_expr (type);
  1660. }
  1661. else if (current_token == '(')
  1662. {
  1663. struct type *type = rust_lookup_type (path.c_str ());
  1664. /* If this is actually a tuple struct expression, handle it
  1665. here. If it is a call, it will be handled elsewhere. */
  1666. if (type != nullptr)
  1667. {
  1668. if (!rust_tuple_struct_type_p (type))
  1669. error (_("Type %s is not a tuple struct"), path.c_str ());
  1670. return parse_tuple_struct (type);
  1671. }
  1672. }
  1673. return name_to_operation (path);
  1674. }
  1675. /* Parse an atom. "Atom" isn't a Rust term, but this refers to a
  1676. single unitary item in the grammar; but here including some unary
  1677. prefix and postfix expressions. */
  1678. operation_up
  1679. rust_parser::parse_atom (bool required)
  1680. {
  1681. operation_up result;
  1682. switch (current_token)
  1683. {
  1684. case '(':
  1685. result = parse_tuple ();
  1686. break;
  1687. case '[':
  1688. result = parse_array ();
  1689. break;
  1690. case INTEGER:
  1691. case DECIMAL_INTEGER:
  1692. result = make_operation<long_const_operation> (current_int_val.type,
  1693. current_int_val.val);
  1694. lex ();
  1695. break;
  1696. case FLOAT:
  1697. result = make_operation<float_const_operation> (current_float_val.type,
  1698. current_float_val.val);
  1699. lex ();
  1700. break;
  1701. case STRING:
  1702. result = parse_string ();
  1703. lex ();
  1704. break;
  1705. case BYTESTRING:
  1706. result = make_operation<string_operation> (get_string ());
  1707. lex ();
  1708. break;
  1709. case KW_TRUE:
  1710. case KW_FALSE:
  1711. result = make_operation<bool_operation> (current_token == KW_TRUE);
  1712. lex ();
  1713. break;
  1714. case GDBVAR:
  1715. /* This is kind of a hacky approach. */
  1716. {
  1717. pstate->push_dollar (current_string_val);
  1718. result = pstate->pop ();
  1719. lex ();
  1720. }
  1721. break;
  1722. case KW_SELF:
  1723. case KW_SUPER:
  1724. case COLONCOLON:
  1725. case KW_EXTERN:
  1726. case IDENT:
  1727. result = parse_path_expr ();
  1728. break;
  1729. case '*':
  1730. lex ();
  1731. result = make_operation<rust_unop_ind_operation> (parse_atom (true));
  1732. break;
  1733. case '+':
  1734. lex ();
  1735. result = make_operation<unary_plus_operation> (parse_atom (true));
  1736. break;
  1737. case '-':
  1738. lex ();
  1739. result = make_operation<unary_neg_operation> (parse_atom (true));
  1740. break;
  1741. case '!':
  1742. lex ();
  1743. result = make_operation<rust_unop_compl_operation> (parse_atom (true));
  1744. break;
  1745. case KW_SIZEOF:
  1746. result = parse_sizeof ();
  1747. break;
  1748. case '&':
  1749. result = parse_addr ();
  1750. break;
  1751. default:
  1752. if (!required)
  1753. return {};
  1754. error (_("unexpected token"));
  1755. }
  1756. /* Now parse suffixes. */
  1757. while (true)
  1758. {
  1759. switch (current_token)
  1760. {
  1761. case '.':
  1762. result = parse_field (std::move (result));
  1763. break;
  1764. case '[':
  1765. result = parse_index (std::move (result));
  1766. break;
  1767. case '(':
  1768. result = parse_call (std::move (result));
  1769. break;
  1770. default:
  1771. return result;
  1772. }
  1773. }
  1774. }
  1775. /* The parser as exposed to gdb. */
  1776. int
  1777. rust_language::parser (struct parser_state *state) const
  1778. {
  1779. rust_parser parser (state);
  1780. operation_up result;
  1781. try
  1782. {
  1783. result = parser.parse_entry_point ();
  1784. }
  1785. catch (const gdb_exception &exc)
  1786. {
  1787. if (state->parse_completion)
  1788. {
  1789. result = std::move (parser.completion_op);
  1790. if (result == nullptr)
  1791. throw;
  1792. }
  1793. else
  1794. throw;
  1795. }
  1796. state->set_operation (std::move (result));
  1797. return 0;
  1798. }
  1799. #if GDB_SELF_TEST
  1800. /* A test helper that lexes a string, expecting a single token. */
  1801. static void
  1802. rust_lex_test_one (rust_parser *parser, const char *input, int expected)
  1803. {
  1804. int token;
  1805. parser->reset (input);
  1806. token = parser->lex_one_token ();
  1807. SELF_CHECK (token == expected);
  1808. if (token)
  1809. {
  1810. token = parser->lex_one_token ();
  1811. SELF_CHECK (token == 0);
  1812. }
  1813. }
  1814. /* Test that INPUT lexes as the integer VALUE. */
  1815. static void
  1816. rust_lex_int_test (rust_parser *parser, const char *input,
  1817. ULONGEST value, int kind)
  1818. {
  1819. rust_lex_test_one (parser, input, kind);
  1820. SELF_CHECK (parser->current_int_val.val == value);
  1821. }
  1822. /* Test that INPUT throws an exception with text ERR. */
  1823. static void
  1824. rust_lex_exception_test (rust_parser *parser, const char *input,
  1825. const char *err)
  1826. {
  1827. try
  1828. {
  1829. /* The "kind" doesn't matter. */
  1830. rust_lex_test_one (parser, input, DECIMAL_INTEGER);
  1831. SELF_CHECK (0);
  1832. }
  1833. catch (const gdb_exception_error &except)
  1834. {
  1835. SELF_CHECK (strcmp (except.what (), err) == 0);
  1836. }
  1837. }
  1838. /* Test that INPUT lexes as the identifier, string, or byte-string
  1839. VALUE. KIND holds the expected token kind. */
  1840. static void
  1841. rust_lex_stringish_test (rust_parser *parser, const char *input,
  1842. const char *value, int kind)
  1843. {
  1844. rust_lex_test_one (parser, input, kind);
  1845. SELF_CHECK (parser->get_string () == value);
  1846. }
  1847. /* Helper to test that a string parses as a given token sequence. */
  1848. static void
  1849. rust_lex_test_sequence (rust_parser *parser, const char *input, int len,
  1850. const int expected[])
  1851. {
  1852. int i;
  1853. parser->reset (input);
  1854. for (i = 0; i < len; ++i)
  1855. {
  1856. int token = parser->lex_one_token ();
  1857. SELF_CHECK (token == expected[i]);
  1858. }
  1859. }
  1860. /* Tests for an integer-parsing corner case. */
  1861. static void
  1862. rust_lex_test_trailing_dot (rust_parser *parser)
  1863. {
  1864. const int expected1[] = { DECIMAL_INTEGER, '.', IDENT, '(', ')', 0 };
  1865. const int expected2[] = { INTEGER, '.', IDENT, '(', ')', 0 };
  1866. const int expected3[] = { FLOAT, EQEQ, '(', ')', 0 };
  1867. const int expected4[] = { DECIMAL_INTEGER, DOTDOT, DECIMAL_INTEGER, 0 };
  1868. rust_lex_test_sequence (parser, "23.g()", ARRAY_SIZE (expected1), expected1);
  1869. rust_lex_test_sequence (parser, "23_0.g()", ARRAY_SIZE (expected2),
  1870. expected2);
  1871. rust_lex_test_sequence (parser, "23.==()", ARRAY_SIZE (expected3),
  1872. expected3);
  1873. rust_lex_test_sequence (parser, "23..25", ARRAY_SIZE (expected4), expected4);
  1874. }
  1875. /* Tests of completion. */
  1876. static void
  1877. rust_lex_test_completion (rust_parser *parser)
  1878. {
  1879. const int expected[] = { IDENT, '.', COMPLETE, 0 };
  1880. parser->pstate->parse_completion = 1;
  1881. rust_lex_test_sequence (parser, "something.wha", ARRAY_SIZE (expected),
  1882. expected);
  1883. rust_lex_test_sequence (parser, "something.", ARRAY_SIZE (expected),
  1884. expected);
  1885. parser->pstate->parse_completion = 0;
  1886. }
  1887. /* Test pushback. */
  1888. static void
  1889. rust_lex_test_push_back (rust_parser *parser)
  1890. {
  1891. int token;
  1892. parser->reset (">>=");
  1893. token = parser->lex_one_token ();
  1894. SELF_CHECK (token == COMPOUND_ASSIGN);
  1895. SELF_CHECK (parser->current_opcode == BINOP_RSH);
  1896. parser->push_back ('=');
  1897. token = parser->lex_one_token ();
  1898. SELF_CHECK (token == '=');
  1899. token = parser->lex_one_token ();
  1900. SELF_CHECK (token == 0);
  1901. }
  1902. /* Unit test the lexer. */
  1903. static void
  1904. rust_lex_tests (void)
  1905. {
  1906. /* Set up dummy "parser", so that rust_type works. */
  1907. struct parser_state ps (language_def (language_rust), target_gdbarch (),
  1908. nullptr, 0, 0, nullptr, 0, nullptr, false);
  1909. rust_parser parser (&ps);
  1910. rust_lex_test_one (&parser, "", 0);
  1911. rust_lex_test_one (&parser, " \t \n \r ", 0);
  1912. rust_lex_test_one (&parser, "thread 23", 0);
  1913. rust_lex_test_one (&parser, "task 23", 0);
  1914. rust_lex_test_one (&parser, "th 104", 0);
  1915. rust_lex_test_one (&parser, "ta 97", 0);
  1916. rust_lex_int_test (&parser, "'z'", 'z', INTEGER);
  1917. rust_lex_int_test (&parser, "'\\xff'", 0xff, INTEGER);
  1918. rust_lex_int_test (&parser, "'\\u{1016f}'", 0x1016f, INTEGER);
  1919. rust_lex_int_test (&parser, "b'z'", 'z', INTEGER);
  1920. rust_lex_int_test (&parser, "b'\\xfe'", 0xfe, INTEGER);
  1921. rust_lex_int_test (&parser, "b'\\xFE'", 0xfe, INTEGER);
  1922. rust_lex_int_test (&parser, "b'\\xfE'", 0xfe, INTEGER);
  1923. /* Test all escapes in both modes. */
  1924. rust_lex_int_test (&parser, "'\\n'", '\n', INTEGER);
  1925. rust_lex_int_test (&parser, "'\\r'", '\r', INTEGER);
  1926. rust_lex_int_test (&parser, "'\\t'", '\t', INTEGER);
  1927. rust_lex_int_test (&parser, "'\\\\'", '\\', INTEGER);
  1928. rust_lex_int_test (&parser, "'\\0'", '\0', INTEGER);
  1929. rust_lex_int_test (&parser, "'\\''", '\'', INTEGER);
  1930. rust_lex_int_test (&parser, "'\\\"'", '"', INTEGER);
  1931. rust_lex_int_test (&parser, "b'\\n'", '\n', INTEGER);
  1932. rust_lex_int_test (&parser, "b'\\r'", '\r', INTEGER);
  1933. rust_lex_int_test (&parser, "b'\\t'", '\t', INTEGER);
  1934. rust_lex_int_test (&parser, "b'\\\\'", '\\', INTEGER);
  1935. rust_lex_int_test (&parser, "b'\\0'", '\0', INTEGER);
  1936. rust_lex_int_test (&parser, "b'\\''", '\'', INTEGER);
  1937. rust_lex_int_test (&parser, "b'\\\"'", '"', INTEGER);
  1938. rust_lex_exception_test (&parser, "'z", "Unterminated character literal");
  1939. rust_lex_exception_test (&parser, "b'\\x0'", "Not enough hex digits seen");
  1940. rust_lex_exception_test (&parser, "b'\\u{0}'",
  1941. "Unicode escape in byte literal");
  1942. rust_lex_exception_test (&parser, "'\\x0'", "Not enough hex digits seen");
  1943. rust_lex_exception_test (&parser, "'\\u0'", "Missing '{' in Unicode escape");
  1944. rust_lex_exception_test (&parser, "'\\u{0", "Missing '}' in Unicode escape");
  1945. rust_lex_exception_test (&parser, "'\\u{0000007}", "Overlong hex escape");
  1946. rust_lex_exception_test (&parser, "'\\u{}", "Not enough hex digits seen");
  1947. rust_lex_exception_test (&parser, "'\\Q'", "Invalid escape \\Q in literal");
  1948. rust_lex_exception_test (&parser, "b'\\Q'", "Invalid escape \\Q in literal");
  1949. rust_lex_int_test (&parser, "23", 23, DECIMAL_INTEGER);
  1950. rust_lex_int_test (&parser, "2_344__29", 234429, INTEGER);
  1951. rust_lex_int_test (&parser, "0x1f", 0x1f, INTEGER);
  1952. rust_lex_int_test (&parser, "23usize", 23, INTEGER);
  1953. rust_lex_int_test (&parser, "23i32", 23, INTEGER);
  1954. rust_lex_int_test (&parser, "0x1_f", 0x1f, INTEGER);
  1955. rust_lex_int_test (&parser, "0b1_101011__", 0x6b, INTEGER);
  1956. rust_lex_int_test (&parser, "0o001177i64", 639, INTEGER);
  1957. rust_lex_int_test (&parser, "0x123456789u64", 0x123456789ull, INTEGER);
  1958. rust_lex_test_trailing_dot (&parser);
  1959. rust_lex_test_one (&parser, "23.", FLOAT);
  1960. rust_lex_test_one (&parser, "23.99f32", FLOAT);
  1961. rust_lex_test_one (&parser, "23e7", FLOAT);
  1962. rust_lex_test_one (&parser, "23E-7", FLOAT);
  1963. rust_lex_test_one (&parser, "23e+7", FLOAT);
  1964. rust_lex_test_one (&parser, "23.99e+7f64", FLOAT);
  1965. rust_lex_test_one (&parser, "23.82f32", FLOAT);
  1966. rust_lex_stringish_test (&parser, "hibob", "hibob", IDENT);
  1967. rust_lex_stringish_test (&parser, "hibob__93", "hibob__93", IDENT);
  1968. rust_lex_stringish_test (&parser, "thread", "thread", IDENT);
  1969. rust_lex_stringish_test (&parser, "r#true", "true", IDENT);
  1970. const int expected1[] = { IDENT, DECIMAL_INTEGER, 0 };
  1971. rust_lex_test_sequence (&parser, "r#thread 23", ARRAY_SIZE (expected1),
  1972. expected1);
  1973. const int expected2[] = { IDENT, '#', 0 };
  1974. rust_lex_test_sequence (&parser, "r#", ARRAY_SIZE (expected2), expected2);
  1975. rust_lex_stringish_test (&parser, "\"string\"", "string", STRING);
  1976. rust_lex_stringish_test (&parser, "\"str\\ting\"", "str\ting", STRING);
  1977. rust_lex_stringish_test (&parser, "\"str\\\"ing\"", "str\"ing", STRING);
  1978. rust_lex_stringish_test (&parser, "r\"str\\ing\"", "str\\ing", STRING);
  1979. rust_lex_stringish_test (&parser, "r#\"str\\ting\"#", "str\\ting", STRING);
  1980. rust_lex_stringish_test (&parser, "r###\"str\\\"ing\"###", "str\\\"ing",
  1981. STRING);
  1982. rust_lex_stringish_test (&parser, "b\"string\"", "string", BYTESTRING);
  1983. rust_lex_stringish_test (&parser, "b\"\x73tring\"", "string", BYTESTRING);
  1984. rust_lex_stringish_test (&parser, "b\"str\\\"ing\"", "str\"ing", BYTESTRING);
  1985. rust_lex_stringish_test (&parser, "br####\"\\x73tring\"####", "\\x73tring",
  1986. BYTESTRING);
  1987. for (const auto &candidate : identifier_tokens)
  1988. rust_lex_test_one (&parser, candidate.name, candidate.value);
  1989. for (const auto &candidate : operator_tokens)
  1990. rust_lex_test_one (&parser, candidate.name, candidate.value);
  1991. rust_lex_test_completion (&parser);
  1992. rust_lex_test_push_back (&parser);
  1993. }
  1994. #endif /* GDB_SELF_TEST */
  1995. void _initialize_rust_exp ();
  1996. void
  1997. _initialize_rust_exp ()
  1998. {
  1999. int code = regcomp (&number_regex, number_regex_text, REG_EXTENDED);
  2000. /* If the regular expression was incorrect, it was a programming
  2001. error. */
  2002. gdb_assert (code == 0);
  2003. #if GDB_SELF_TEST
  2004. selftests::register_test ("rust-lex", rust_lex_tests);
  2005. #endif
  2006. }