1 //! Parser for .clif files.
2 
3 use crate::error::{Location, ParseError, ParseResult};
4 use crate::isaspec;
5 use crate::lexer::{LexError, Lexer, LocatedError, LocatedToken, Token};
6 use crate::run_command::{Comparison, Invocation, RunCommand};
7 use crate::sourcemap::SourceMap;
8 use crate::testcommand::TestCommand;
9 use crate::testfile::{Comment, Details, Feature, TestFile};
10 use cranelift_codegen::data_value::DataValue;
11 use cranelift_codegen::entity::{EntityRef, PrimaryMap};
12 use cranelift_codegen::ir::entities::{AnyEntity, DynamicType};
13 use cranelift_codegen::ir::immediates::{Ieee32, Ieee64, Imm64, Offset32, Uimm32, Uimm64};
14 use cranelift_codegen::ir::instructions::{InstructionData, InstructionFormat, VariableArgs};
15 use cranelift_codegen::ir::types::INVALID;
16 use cranelift_codegen::ir::types::*;
17 use cranelift_codegen::ir::{self, UserExternalNameRef};
18 use cranelift_codegen::ir::{
19     AbiParam, ArgumentExtension, ArgumentPurpose, Block, Constant, ConstantData, DynamicStackSlot,
20     DynamicStackSlotData, DynamicTypeData, ExtFuncData, ExternalName, FuncRef, Function,
21     GlobalValue, GlobalValueData, JumpTable, JumpTableData, MemFlags, Opcode, SigRef, Signature,
22     StackSlot, StackSlotData, StackSlotKind, Table, TableData, Type, UserFuncName, Value,
23 };
24 use cranelift_codegen::isa::{self, CallConv};
25 use cranelift_codegen::packed_option::ReservedValue;
26 use cranelift_codegen::{settings, settings::Configurable, timing};
27 use smallvec::SmallVec;
28 use std::mem;
29 use std::str::FromStr;
30 use std::{u16, u32};
31 use target_lexicon::Triple;
32 
33 macro_rules! match_imm {
34     ($signed:ty, $unsigned:ty, $parser:expr, $err_msg:expr) => {{
35         if let Some(Token::Integer(text)) = $parser.token() {
36             $parser.consume();
37             let negative = text.starts_with('-');
38             let positive = text.starts_with('+');
39             let text = if negative || positive {
40                 // Strip sign prefix.
41                 &text[1..]
42             } else {
43                 text
44             };
45 
46             // Parse the text value; the lexer gives us raw text that looks like an integer.
47             let value = if text.starts_with("0x") {
48                 // Skip underscores.
49                 let text = text.replace("_", "");
50                 // Parse it in hexadecimal form.
51                 <$unsigned>::from_str_radix(&text[2..], 16).map_err(|_| {
52                     $parser.error("unable to parse value as a hexadecimal immediate")
53                 })?
54             } else {
55                 // Parse it as a signed type to check for overflow and other issues.
56                 text.parse()
57                     .map_err(|_| $parser.error("expected decimal immediate"))?
58             };
59 
60             // Apply sign if necessary.
61             let signed = if negative {
62                 let value = value.wrapping_neg() as $signed;
63                 if value > 0 {
64                     return Err($parser.error("negative number too small"));
65                 }
66                 value
67             } else {
68                 value as $signed
69             };
70 
71             Ok(signed)
72         } else {
73             err!($parser.loc, $err_msg)
74         }
75     }};
76 }
77 
78 /// After some quick benchmarks a program should never have more than 100,000 blocks.
79 const MAX_BLOCKS_IN_A_FUNCTION: u32 = 100_000;
80 
81 /// Parse the entire `text` into a list of functions.
82 ///
83 /// Any test commands or target declarations are ignored.
84 pub fn parse_functions(text: &str) -> ParseResult<Vec<Function>> {
85     let _tt = timing::parse_text();
86     parse_test(text, ParseOptions::default())
87         .map(|file| file.functions.into_iter().map(|(func, _)| func).collect())
88 }
89 
90 /// Options for configuring the parsing of filetests.
91 pub struct ParseOptions<'a> {
92     /// Compiler passes to run on the parsed functions.
93     pub passes: Option<&'a [String]>,
94     /// Target ISA for compiling the parsed functions, e.g. "x86_64 skylake".
95     pub target: Option<&'a str>,
96     /// Default calling convention used when none is specified for a parsed function.
97     pub default_calling_convention: CallConv,
98     /// Default for unwind-info setting (enabled or disabled).
99     pub unwind_info: bool,
100 }
101 
102 impl Default for ParseOptions<'_> {
103     fn default() -> Self {
104         Self {
105             passes: None,
106             target: None,
107             default_calling_convention: CallConv::Fast,
108             unwind_info: false,
109         }
110     }
111 }
112 
113 /// Parse the entire `text` as a test case file.
114 ///
115 /// The returned `TestFile` contains direct references to substrings of `text`.
116 pub fn parse_test<'a>(text: &'a str, options: ParseOptions<'a>) -> ParseResult<TestFile<'a>> {
117     let _tt = timing::parse_text();
118     let mut parser = Parser::new(text);
119 
120     // Gather the preamble comments.
121     parser.start_gathering_comments();
122 
123     let isa_spec: isaspec::IsaSpec;
124     let commands: Vec<TestCommand<'a>>;
125 
126     // Check for specified passes and target, if present throw out test commands/targets specified
127     // in file.
128     match options.passes {
129         Some(pass_vec) => {
130             parser.parse_test_commands();
131             commands = parser.parse_cmdline_passes(pass_vec);
132             parser.parse_target_specs(&options)?;
133             isa_spec = parser.parse_cmdline_target(options.target)?;
134         }
135         None => {
136             commands = parser.parse_test_commands();
137             isa_spec = parser.parse_target_specs(&options)?;
138         }
139     };
140     let features = parser.parse_cranelift_features()?;
141 
142     // Decide between using the calling convention passed in the options or using the
143     // host's calling convention--if any tests are to be run on the host we should default to the
144     // host's calling convention.
145     parser = if commands.iter().any(|tc| tc.command == "run") {
146         let host_default_calling_convention = CallConv::triple_default(&Triple::host());
147         parser.with_default_calling_convention(host_default_calling_convention)
148     } else {
149         parser.with_default_calling_convention(options.default_calling_convention)
150     };
151 
152     parser.token();
153     parser.claim_gathered_comments(AnyEntity::Function);
154 
155     let preamble_comments = parser.take_comments();
156     let functions = parser.parse_function_list()?;
157 
158     Ok(TestFile {
159         commands,
160         isa_spec,
161         features,
162         preamble_comments,
163         functions,
164     })
165 }
166 
167 /// Parse a CLIF comment `text` as a run command.
168 ///
169 /// Return:
170 ///  - `Ok(None)` if the comment is not intended to be a `RunCommand` (i.e. does not start with `run`
171 ///    or `print`
172 ///  - `Ok(Some(command))` if the comment is intended as a `RunCommand` and can be parsed to one
173 ///  - `Err` otherwise.
174 pub fn parse_run_command<'a>(text: &str, signature: &Signature) -> ParseResult<Option<RunCommand>> {
175     let _tt = timing::parse_text();
176     // We remove leading spaces and semi-colons for convenience here instead of at the call sites
177     // since this function will be attempting to parse a RunCommand from a CLIF comment.
178     let trimmed_text = text.trim_start_matches(|c| c == ' ' || c == ';');
179     let mut parser = Parser::new(trimmed_text);
180     match parser.token() {
181         Some(Token::Identifier("run")) | Some(Token::Identifier("print")) => {
182             parser.parse_run_command(signature).map(|c| Some(c))
183         }
184         Some(_) | None => Ok(None),
185     }
186 }
187 
188 pub struct Parser<'a> {
189     lex: Lexer<'a>,
190 
191     lex_error: Option<LexError>,
192 
193     /// Current lookahead token.
194     lookahead: Option<Token<'a>>,
195 
196     /// Location of lookahead.
197     loc: Location,
198 
199     /// Are we gathering any comments that we encounter?
200     gathering_comments: bool,
201 
202     /// The gathered comments; claim them with `claim_gathered_comments`.
203     gathered_comments: Vec<&'a str>,
204 
205     /// Comments collected so far.
206     comments: Vec<Comment<'a>>,
207 
208     /// Maps inlined external names to a ref value, so they can be declared before parsing the rest
209     /// of the function later.
210     ///
211     /// This maintains backward compatibility with previous ways for declaring external names.
212     predeclared_external_names: PrimaryMap<UserExternalNameRef, ir::UserExternalName>,
213 
214     /// Default calling conventions; used when none is specified.
215     default_calling_convention: CallConv,
216 }
217 
218 /// Context for resolving references when parsing a single function.
219 struct Context {
220     function: Function,
221     map: SourceMap,
222 
223     /// Aliases to resolve once value definitions are known.
224     aliases: Vec<Value>,
225 }
226 
227 impl Context {
228     fn new(f: Function) -> Self {
229         Self {
230             function: f,
231             map: SourceMap::new(),
232             aliases: Vec::new(),
233         }
234     }
235 
236     // Allocate a new stack slot.
237     fn add_ss(&mut self, ss: StackSlot, data: StackSlotData, loc: Location) -> ParseResult<()> {
238         self.map.def_ss(ss, loc)?;
239         while self.function.sized_stack_slots.next_key().index() <= ss.index() {
240             self.function
241                 .create_sized_stack_slot(StackSlotData::new(StackSlotKind::ExplicitSlot, 0));
242         }
243         self.function.sized_stack_slots[ss] = data;
244         Ok(())
245     }
246 
247     // Resolve a reference to a stack slot.
248     fn check_ss(&self, ss: StackSlot, loc: Location) -> ParseResult<()> {
249         if !self.map.contains_ss(ss) {
250             err!(loc, "undefined stack slot {}", ss)
251         } else {
252             Ok(())
253         }
254     }
255 
256     // Allocate a new stack slot.
257     fn add_dss(
258         &mut self,
259         ss: DynamicStackSlot,
260         data: DynamicStackSlotData,
261         loc: Location,
262     ) -> ParseResult<()> {
263         self.map.def_dss(ss, loc)?;
264         while self.function.dynamic_stack_slots.next_key().index() <= ss.index() {
265             self.function
266                 .create_dynamic_stack_slot(DynamicStackSlotData::new(
267                     StackSlotKind::ExplicitDynamicSlot,
268                     data.dyn_ty,
269                 ));
270         }
271         self.function.dynamic_stack_slots[ss] = data;
272         Ok(())
273     }
274 
275     // Resolve a reference to a dynamic stack slot.
276     fn check_dss(&self, dss: DynamicStackSlot, loc: Location) -> ParseResult<()> {
277         if !self.map.contains_dss(dss) {
278             err!(loc, "undefined dynamic stack slot {}", dss)
279         } else {
280             Ok(())
281         }
282     }
283 
284     // Allocate a new dynamic type.
285     fn add_dt(&mut self, dt: DynamicType, data: DynamicTypeData, loc: Location) -> ParseResult<()> {
286         self.map.def_dt(dt, loc)?;
287         while self.function.dfg.dynamic_types.next_key().index() <= dt.index() {
288             self.function.dfg.make_dynamic_ty(DynamicTypeData::new(
289                 data.base_vector_ty,
290                 data.dynamic_scale,
291             ));
292         }
293         self.function.dfg.dynamic_types[dt] = data;
294         Ok(())
295     }
296 
297     // Allocate a global value slot.
298     fn add_gv(&mut self, gv: GlobalValue, data: GlobalValueData, loc: Location) -> ParseResult<()> {
299         self.map.def_gv(gv, loc)?;
300         while self.function.global_values.next_key().index() <= gv.index() {
301             self.function.create_global_value(GlobalValueData::Symbol {
302                 name: ExternalName::testcase(""),
303                 offset: Imm64::new(0),
304                 colocated: false,
305                 tls: false,
306             });
307         }
308         self.function.global_values[gv] = data;
309         Ok(())
310     }
311 
312     // Resolve a reference to a global value.
313     fn check_gv(&self, gv: GlobalValue, loc: Location) -> ParseResult<()> {
314         if !self.map.contains_gv(gv) {
315             err!(loc, "undefined global value {}", gv)
316         } else {
317             Ok(())
318         }
319     }
320 
321     // Allocate a table slot.
322     fn add_table(&mut self, table: Table, data: TableData, loc: Location) -> ParseResult<()> {
323         while self.function.tables.next_key().index() <= table.index() {
324             self.function.create_table(TableData {
325                 base_gv: GlobalValue::reserved_value(),
326                 min_size: Uimm64::new(0),
327                 bound_gv: GlobalValue::reserved_value(),
328                 element_size: Uimm64::new(0),
329                 index_type: INVALID,
330             });
331         }
332         self.function.tables[table] = data;
333         self.map.def_table(table, loc)
334     }
335 
336     // Resolve a reference to a table.
337     fn check_table(&self, table: Table, loc: Location) -> ParseResult<()> {
338         if !self.map.contains_table(table) {
339             err!(loc, "undefined table {}", table)
340         } else {
341             Ok(())
342         }
343     }
344 
345     // Allocate a new signature.
346     fn add_sig(
347         &mut self,
348         sig: SigRef,
349         data: Signature,
350         loc: Location,
351         defaultcc: CallConv,
352     ) -> ParseResult<()> {
353         self.map.def_sig(sig, loc)?;
354         while self.function.dfg.signatures.next_key().index() <= sig.index() {
355             self.function.import_signature(Signature::new(defaultcc));
356         }
357         self.function.dfg.signatures[sig] = data;
358         Ok(())
359     }
360 
361     // Resolve a reference to a signature.
362     fn check_sig(&self, sig: SigRef, loc: Location) -> ParseResult<()> {
363         if !self.map.contains_sig(sig) {
364             err!(loc, "undefined signature {}", sig)
365         } else {
366             Ok(())
367         }
368     }
369 
370     // Allocate a new external function.
371     fn add_fn(&mut self, fn_: FuncRef, data: ExtFuncData, loc: Location) -> ParseResult<()> {
372         self.map.def_fn(fn_, loc)?;
373         while self.function.dfg.ext_funcs.next_key().index() <= fn_.index() {
374             self.function.import_function(ExtFuncData {
375                 name: ExternalName::testcase(""),
376                 signature: SigRef::reserved_value(),
377                 colocated: false,
378             });
379         }
380         self.function.dfg.ext_funcs[fn_] = data;
381         Ok(())
382     }
383 
384     // Resolve a reference to a function.
385     fn check_fn(&self, fn_: FuncRef, loc: Location) -> ParseResult<()> {
386         if !self.map.contains_fn(fn_) {
387             err!(loc, "undefined function {}", fn_)
388         } else {
389             Ok(())
390         }
391     }
392 
393     // Allocate a new jump table.
394     fn add_jt(&mut self, jt: JumpTable, data: JumpTableData, loc: Location) -> ParseResult<()> {
395         self.map.def_jt(jt, loc)?;
396         while self.function.jump_tables.next_key().index() <= jt.index() {
397             self.function.create_jump_table(JumpTableData::new());
398         }
399         self.function.jump_tables[jt] = data;
400         Ok(())
401     }
402 
403     // Resolve a reference to a jump table.
404     fn check_jt(&self, jt: JumpTable, loc: Location) -> ParseResult<()> {
405         if !self.map.contains_jt(jt) {
406             err!(loc, "undefined jump table {}", jt)
407         } else {
408             Ok(())
409         }
410     }
411 
412     // Allocate a new constant.
413     fn add_constant(
414         &mut self,
415         constant: Constant,
416         data: ConstantData,
417         loc: Location,
418     ) -> ParseResult<()> {
419         self.map.def_constant(constant, loc)?;
420         self.function.dfg.constants.set(constant, data);
421         Ok(())
422     }
423 
424     // Configure the stack limit of the current function.
425     fn add_stack_limit(&mut self, limit: GlobalValue, loc: Location) -> ParseResult<()> {
426         if self.function.stack_limit.is_some() {
427             return err!(loc, "stack limit defined twice");
428         }
429         self.function.stack_limit = Some(limit);
430         Ok(())
431     }
432 
433     // Resolve a reference to a constant.
434     fn check_constant(&self, c: Constant, loc: Location) -> ParseResult<()> {
435         if !self.map.contains_constant(c) {
436             err!(loc, "undefined constant {}", c)
437         } else {
438             Ok(())
439         }
440     }
441 
442     // Allocate a new block.
443     fn add_block(&mut self, block: Block, loc: Location) -> ParseResult<Block> {
444         self.map.def_block(block, loc)?;
445         while self.function.dfg.num_blocks() <= block.index() {
446             self.function.dfg.make_block();
447         }
448         self.function.layout.append_block(block);
449         Ok(block)
450     }
451 
452     /// Set a block as cold.
453     fn set_cold_block(&mut self, block: Block) {
454         self.function.layout.set_cold(block);
455     }
456 }
457 
458 impl<'a> Parser<'a> {
459     /// Create a new `Parser` which reads `text`. The referenced text must outlive the parser.
460     pub fn new(text: &'a str) -> Self {
461         Self {
462             lex: Lexer::new(text),
463             lex_error: None,
464             lookahead: None,
465             loc: Location { line_number: 0 },
466             gathering_comments: false,
467             gathered_comments: Vec::new(),
468             comments: Vec::new(),
469             default_calling_convention: CallConv::Fast,
470             predeclared_external_names: Default::default(),
471         }
472     }
473 
474     /// Modify the default calling convention; returns a new parser with the changed calling
475     /// convention.
476     pub fn with_default_calling_convention(self, default_calling_convention: CallConv) -> Self {
477         Self {
478             default_calling_convention,
479             ..self
480         }
481     }
482 
483     // Consume the current lookahead token and return it.
484     fn consume(&mut self) -> Token<'a> {
485         self.lookahead.take().expect("No token to consume")
486     }
487 
488     // Consume the whole line following the current lookahead token.
489     // Return the text of the line tail.
490     fn consume_line(&mut self) -> &'a str {
491         let rest = self.lex.rest_of_line();
492         self.consume();
493         rest
494     }
495 
496     // Get the current lookahead token, after making sure there is one.
497     fn token(&mut self) -> Option<Token<'a>> {
498         // clippy says self.lookahead is immutable so this loop is either infinite or never
499         // running. I don't think this is true - self.lookahead is mutated in the loop body - so
500         // maybe this is a clippy bug? Either way, disable clippy for this.
501         #[cfg_attr(feature = "cargo-clippy", allow(clippy::while_immutable_condition))]
502         while self.lookahead.is_none() {
503             match self.lex.next() {
504                 Some(Ok(LocatedToken { token, location })) => {
505                     match token {
506                         Token::Comment(text) => {
507                             if self.gathering_comments {
508                                 self.gathered_comments.push(text);
509                             }
510                         }
511                         _ => self.lookahead = Some(token),
512                     }
513                     self.loc = location;
514                 }
515                 Some(Err(LocatedError { error, location })) => {
516                     self.lex_error = Some(error);
517                     self.loc = location;
518                     break;
519                 }
520                 None => break,
521             }
522         }
523         self.lookahead
524     }
525 
526     // Enable gathering of all comments encountered.
527     fn start_gathering_comments(&mut self) {
528         debug_assert!(!self.gathering_comments);
529         self.gathering_comments = true;
530         debug_assert!(self.gathered_comments.is_empty());
531     }
532 
533     // Claim the comments gathered up to the current position for the
534     // given entity.
535     fn claim_gathered_comments<E: Into<AnyEntity>>(&mut self, entity: E) {
536         debug_assert!(self.gathering_comments);
537         let entity = entity.into();
538         self.comments.extend(
539             self.gathered_comments
540                 .drain(..)
541                 .map(|text| Comment { entity, text }),
542         );
543         self.gathering_comments = false;
544     }
545 
546     // Get the comments collected so far, clearing out the internal list.
547     fn take_comments(&mut self) -> Vec<Comment<'a>> {
548         debug_assert!(!self.gathering_comments);
549         mem::replace(&mut self.comments, Vec::new())
550     }
551 
552     // Match and consume a token without payload.
553     fn match_token(&mut self, want: Token<'a>, err_msg: &str) -> ParseResult<Token<'a>> {
554         if self.token() == Some(want) {
555             Ok(self.consume())
556         } else {
557             err!(self.loc, err_msg)
558         }
559     }
560 
561     // If the next token is a `want`, consume it, otherwise do nothing.
562     fn optional(&mut self, want: Token<'a>) -> bool {
563         if self.token() == Some(want) {
564             self.consume();
565             true
566         } else {
567             false
568         }
569     }
570 
571     // Match and consume a specific identifier string.
572     // Used for pseudo-keywords like "stack_slot" that only appear in certain contexts.
573     fn match_identifier(&mut self, want: &'static str, err_msg: &str) -> ParseResult<Token<'a>> {
574         if self.token() == Some(Token::Identifier(want)) {
575             Ok(self.consume())
576         } else {
577             err!(self.loc, err_msg)
578         }
579     }
580 
581     // Match and consume a type.
582     fn match_type(&mut self, err_msg: &str) -> ParseResult<Type> {
583         if let Some(Token::Type(t)) = self.token() {
584             self.consume();
585             Ok(t)
586         } else {
587             err!(self.loc, err_msg)
588         }
589     }
590 
591     // Match and consume a stack slot reference.
592     fn match_ss(&mut self, err_msg: &str) -> ParseResult<StackSlot> {
593         if let Some(Token::StackSlot(ss)) = self.token() {
594             self.consume();
595             if let Some(ss) = StackSlot::with_number(ss) {
596                 return Ok(ss);
597             }
598         }
599         err!(self.loc, err_msg)
600     }
601 
602     // Match and consume a dynamic stack slot reference.
603     fn match_dss(&mut self, err_msg: &str) -> ParseResult<DynamicStackSlot> {
604         if let Some(Token::DynamicStackSlot(ss)) = self.token() {
605             self.consume();
606             if let Some(ss) = DynamicStackSlot::with_number(ss) {
607                 return Ok(ss);
608             }
609         }
610         err!(self.loc, err_msg)
611     }
612 
613     // Match and consume a dynamic type reference.
614     fn match_dt(&mut self, err_msg: &str) -> ParseResult<DynamicType> {
615         if let Some(Token::DynamicType(dt)) = self.token() {
616             self.consume();
617             if let Some(dt) = DynamicType::with_number(dt) {
618                 return Ok(dt);
619             }
620         }
621         err!(self.loc, err_msg)
622     }
623 
624     // Extract Type from DynamicType
625     fn concrete_from_dt(&mut self, dt: DynamicType, ctx: &mut Context) -> Option<Type> {
626         ctx.function.get_concrete_dynamic_ty(dt)
627     }
628 
629     // Match and consume a global value reference.
630     fn match_gv(&mut self, err_msg: &str) -> ParseResult<GlobalValue> {
631         if let Some(Token::GlobalValue(gv)) = self.token() {
632             self.consume();
633             if let Some(gv) = GlobalValue::with_number(gv) {
634                 return Ok(gv);
635             }
636         }
637         err!(self.loc, err_msg)
638     }
639 
640     // Match and consume a function reference.
641     fn match_fn(&mut self, err_msg: &str) -> ParseResult<FuncRef> {
642         if let Some(Token::FuncRef(fnref)) = self.token() {
643             self.consume();
644             if let Some(fnref) = FuncRef::with_number(fnref) {
645                 return Ok(fnref);
646             }
647         }
648         err!(self.loc, err_msg)
649     }
650 
651     // Match and consume a signature reference.
652     fn match_sig(&mut self, err_msg: &str) -> ParseResult<SigRef> {
653         if let Some(Token::SigRef(sigref)) = self.token() {
654             self.consume();
655             if let Some(sigref) = SigRef::with_number(sigref) {
656                 return Ok(sigref);
657             }
658         }
659         err!(self.loc, err_msg)
660     }
661 
662     // Match and consume a table reference.
663     fn match_table(&mut self, err_msg: &str) -> ParseResult<Table> {
664         if let Some(Token::Table(table)) = self.token() {
665             self.consume();
666             if let Some(table) = Table::with_number(table) {
667                 return Ok(table);
668             }
669         }
670         err!(self.loc, err_msg)
671     }
672 
673     // Match and consume a jump table reference.
674     fn match_jt(&mut self) -> ParseResult<JumpTable> {
675         if let Some(Token::JumpTable(jt)) = self.token() {
676             self.consume();
677             if let Some(jt) = JumpTable::with_number(jt) {
678                 return Ok(jt);
679             }
680         }
681         err!(self.loc, "expected jump table number: jt«n»")
682     }
683 
684     // Match and consume a constant reference.
685     fn match_constant(&mut self) -> ParseResult<Constant> {
686         if let Some(Token::Constant(c)) = self.token() {
687             self.consume();
688             if let Some(c) = Constant::with_number(c) {
689                 return Ok(c);
690             }
691         }
692         err!(self.loc, "expected constant number: const«n»")
693     }
694 
695     // Match and consume a stack limit token
696     fn match_stack_limit(&mut self) -> ParseResult<()> {
697         if let Some(Token::Identifier("stack_limit")) = self.token() {
698             self.consume();
699             return Ok(());
700         }
701         err!(self.loc, "expected identifier: stack_limit")
702     }
703 
704     // Match and consume a block reference.
705     fn match_block(&mut self, err_msg: &str) -> ParseResult<Block> {
706         if let Some(Token::Block(block)) = self.token() {
707             self.consume();
708             Ok(block)
709         } else {
710             err!(self.loc, err_msg)
711         }
712     }
713 
714     // Match and consume a value reference.
715     fn match_value(&mut self, err_msg: &str) -> ParseResult<Value> {
716         if let Some(Token::Value(v)) = self.token() {
717             self.consume();
718             Ok(v)
719         } else {
720             err!(self.loc, err_msg)
721         }
722     }
723 
724     fn error(&self, message: &str) -> ParseError {
725         ParseError {
726             location: self.loc,
727             message: message.to_string(),
728             is_warning: false,
729         }
730     }
731 
732     // Match and consume an Imm64 immediate.
733     fn match_imm64(&mut self, err_msg: &str) -> ParseResult<Imm64> {
734         if let Some(Token::Integer(text)) = self.token() {
735             self.consume();
736             // Lexer just gives us raw text that looks like an integer.
737             // Parse it as an Imm64 to check for overflow and other issues.
738             text.parse().map_err(|e| self.error(e))
739         } else {
740             err!(self.loc, err_msg)
741         }
742     }
743 
744     // Match and consume a hexadeximal immediate
745     fn match_hexadecimal_constant(&mut self, err_msg: &str) -> ParseResult<ConstantData> {
746         if let Some(Token::Integer(text)) = self.token() {
747             self.consume();
748             text.parse().map_err(|e| {
749                 self.error(&format!(
750                     "expected hexadecimal immediate, failed to parse: {}",
751                     e
752                 ))
753             })
754         } else {
755             err!(self.loc, err_msg)
756         }
757     }
758 
759     // Match and consume a sequence of immediate bytes (uimm8); e.g. [0x42 0x99 0x32]
760     fn match_constant_data(&mut self) -> ParseResult<ConstantData> {
761         self.match_token(Token::LBracket, "expected an opening left bracket")?;
762         let mut data = ConstantData::default();
763         while !self.optional(Token::RBracket) {
764             data = data.append(self.match_uimm8("expected a sequence of bytes (uimm8)")?);
765         }
766         Ok(data)
767     }
768 
769     // Match and consume either a hexadecimal Uimm128 immediate (e.g. 0x000102...) or its literal
770     // list form (e.g. [0 1 2...]). For convenience, since uimm128 values are stored in the
771     // `ConstantPool`, this returns `ConstantData`.
772     fn match_uimm128(&mut self, controlling_type: Type) -> ParseResult<ConstantData> {
773         let expected_size = controlling_type.bytes() as usize;
774         let constant_data = if self.optional(Token::LBracket) {
775             // parse using a list of values, e.g. vconst.i32x4 [0 1 2 3]
776             let uimm128 = self.parse_literals_to_constant_data(controlling_type)?;
777             self.match_token(Token::RBracket, "expected a terminating right bracket")?;
778             uimm128
779         } else {
780             // parse using a hexadecimal value, e.g. 0x000102...
781             let uimm128 =
782                 self.match_hexadecimal_constant("expected an immediate hexadecimal operand")?;
783             uimm128.expand_to(expected_size)
784         };
785 
786         if constant_data.len() == expected_size {
787             Ok(constant_data)
788         } else {
789             Err(self.error(&format!(
790                 "expected parsed constant to have {} bytes",
791                 expected_size
792             )))
793         }
794     }
795 
796     // Match and consume a Uimm64 immediate.
797     fn match_uimm64(&mut self, err_msg: &str) -> ParseResult<Uimm64> {
798         if let Some(Token::Integer(text)) = self.token() {
799             self.consume();
800             // Lexer just gives us raw text that looks like an integer.
801             // Parse it as an Uimm64 to check for overflow and other issues.
802             text.parse()
803                 .map_err(|_| self.error("expected u64 decimal immediate"))
804         } else {
805             err!(self.loc, err_msg)
806         }
807     }
808 
809     // Match and consume a Uimm32 immediate.
810     fn match_uimm32(&mut self, err_msg: &str) -> ParseResult<Uimm32> {
811         if let Some(Token::Integer(text)) = self.token() {
812             self.consume();
813             // Lexer just gives us raw text that looks like an integer.
814             // Parse it as an Uimm32 to check for overflow and other issues.
815             text.parse().map_err(|e| self.error(e))
816         } else {
817             err!(self.loc, err_msg)
818         }
819     }
820 
821     // Match and consume a u8 immediate.
822     // This is used for lane numbers in SIMD vectors.
823     fn match_uimm8(&mut self, err_msg: &str) -> ParseResult<u8> {
824         if let Some(Token::Integer(text)) = self.token() {
825             self.consume();
826             // Lexer just gives us raw text that looks like an integer.
827             if text.starts_with("0x") {
828                 // Parse it as a u8 in hexadecimal form.
829                 u8::from_str_radix(&text[2..], 16)
830                     .map_err(|_| self.error("unable to parse u8 as a hexadecimal immediate"))
831             } else {
832                 // Parse it as a u8 to check for overflow and other issues.
833                 text.parse()
834                     .map_err(|_| self.error("expected u8 decimal immediate"))
835             }
836         } else {
837             err!(self.loc, err_msg)
838         }
839     }
840 
841     // Match and consume an i8 immediate.
842     fn match_imm8(&mut self, err_msg: &str) -> ParseResult<i8> {
843         match_imm!(i8, u8, self, err_msg)
844     }
845 
846     // Match and consume a signed 16-bit immediate.
847     fn match_imm16(&mut self, err_msg: &str) -> ParseResult<i16> {
848         match_imm!(i16, u16, self, err_msg)
849     }
850 
851     // Match and consume an i32 immediate.
852     // This is used for stack argument byte offsets.
853     fn match_imm32(&mut self, err_msg: &str) -> ParseResult<i32> {
854         match_imm!(i32, u32, self, err_msg)
855     }
856 
857     // Match and consume an i128 immediate.
858     fn match_imm128(&mut self, err_msg: &str) -> ParseResult<i128> {
859         match_imm!(i128, u128, self, err_msg)
860     }
861 
862     // Match and consume an optional offset32 immediate.
863     //
864     // Note that this will match an empty string as an empty offset, and that if an offset is
865     // present, it must contain a sign.
866     fn optional_offset32(&mut self) -> ParseResult<Offset32> {
867         if let Some(Token::Integer(text)) = self.token() {
868             if text.starts_with('+') || text.starts_with('-') {
869                 self.consume();
870                 // Lexer just gives us raw text that looks like an integer.
871                 // Parse it as an `Offset32` to check for overflow and other issues.
872                 return text.parse().map_err(|e| self.error(e));
873             }
874         }
875         // An offset32 operand can be absent.
876         Ok(Offset32::new(0))
877     }
878 
879     // Match and consume an optional offset32 immediate.
880     //
881     // Note that this will match an empty string as an empty offset, and that if an offset is
882     // present, it must contain a sign.
883     fn optional_offset_imm64(&mut self) -> ParseResult<Imm64> {
884         if let Some(Token::Integer(text)) = self.token() {
885             if text.starts_with('+') || text.starts_with('-') {
886                 self.consume();
887                 // Lexer just gives us raw text that looks like an integer.
888                 // Parse it as an `Offset32` to check for overflow and other issues.
889                 return text.parse().map_err(|e| self.error(e));
890             }
891         }
892         // If no explicit offset is present, the offset is 0.
893         Ok(Imm64::new(0))
894     }
895 
896     // Match and consume an Ieee32 immediate.
897     fn match_ieee32(&mut self, err_msg: &str) -> ParseResult<Ieee32> {
898         if let Some(Token::Float(text)) = self.token() {
899             self.consume();
900             // Lexer just gives us raw text that looks like a float.
901             // Parse it as an Ieee32 to check for the right number of digits and other issues.
902             text.parse().map_err(|e| self.error(e))
903         } else {
904             err!(self.loc, err_msg)
905         }
906     }
907 
908     // Match and consume an Ieee64 immediate.
909     fn match_ieee64(&mut self, err_msg: &str) -> ParseResult<Ieee64> {
910         if let Some(Token::Float(text)) = self.token() {
911             self.consume();
912             // Lexer just gives us raw text that looks like a float.
913             // Parse it as an Ieee64 to check for the right number of digits and other issues.
914             text.parse().map_err(|e| self.error(e))
915         } else {
916             err!(self.loc, err_msg)
917         }
918     }
919 
920     // Match and consume an enumerated immediate, like one of the condition codes.
921     fn match_enum<T: FromStr>(&mut self, err_msg: &str) -> ParseResult<T> {
922         if let Some(Token::Identifier(text)) = self.token() {
923             self.consume();
924             text.parse().map_err(|_| self.error(err_msg))
925         } else {
926             err!(self.loc, err_msg)
927         }
928     }
929 
930     // Match and a consume a possibly empty sequence of memory operation flags.
931     fn optional_memflags(&mut self) -> MemFlags {
932         let mut flags = MemFlags::new();
933         while let Some(Token::Identifier(text)) = self.token() {
934             if flags.set_by_name(text) {
935                 self.consume();
936             } else {
937                 break;
938             }
939         }
940         flags
941     }
942 
943     // Match and consume an identifier.
944     fn match_any_identifier(&mut self, err_msg: &str) -> ParseResult<&'a str> {
945         if let Some(Token::Identifier(text)) = self.token() {
946             self.consume();
947             Ok(text)
948         } else {
949             err!(self.loc, err_msg)
950         }
951     }
952 
953     /// Parse an optional source location.
954     ///
955     /// Return an optional source location if no real location is present.
956     fn optional_srcloc(&mut self) -> ParseResult<ir::SourceLoc> {
957         if let Some(Token::SourceLoc(text)) = self.token() {
958             match u32::from_str_radix(text, 16) {
959                 Ok(num) => {
960                     self.consume();
961                     Ok(ir::SourceLoc::new(num))
962                 }
963                 Err(_) => return err!(self.loc, "invalid source location: {}", text),
964             }
965         } else {
966             Ok(Default::default())
967         }
968     }
969 
970     /// Parse a list of literals (i.e. integers, floats, booleans); e.g. `0 1 2 3`, usually as
971     /// part of something like `vconst.i32x4 [0 1 2 3]`.
972     fn parse_literals_to_constant_data(&mut self, ty: Type) -> ParseResult<ConstantData> {
973         macro_rules! consume {
974             ( $ty:ident, $match_fn:expr ) => {{
975                 assert!($ty.is_vector());
976                 let mut data = ConstantData::default();
977                 for _ in 0..$ty.lane_count() {
978                     data = data.append($match_fn);
979                 }
980                 data
981             }};
982         }
983 
984         if !ty.is_vector() && !ty.is_dynamic_vector() {
985             err!(self.loc, "Expected a controlling vector type, not {}", ty)
986         } else {
987             let constant_data = match ty.lane_type() {
988                 I8 => consume!(ty, self.match_imm8("Expected an 8-bit integer")?),
989                 I16 => consume!(ty, self.match_imm16("Expected a 16-bit integer")?),
990                 I32 => consume!(ty, self.match_imm32("Expected a 32-bit integer")?),
991                 I64 => consume!(ty, self.match_imm64("Expected a 64-bit integer")?),
992                 F32 => consume!(ty, self.match_ieee32("Expected a 32-bit float")?),
993                 F64 => consume!(ty, self.match_ieee64("Expected a 64-bit float")?),
994                 _ => return err!(self.loc, "Expected a type of: float, int, bool"),
995             };
996             Ok(constant_data)
997         }
998     }
999 
1000     /// Parse a list of test command passes specified in command line.
1001     pub fn parse_cmdline_passes(&mut self, passes: &'a [String]) -> Vec<TestCommand<'a>> {
1002         let mut list = Vec::new();
1003         for pass in passes {
1004             list.push(TestCommand::new(pass));
1005         }
1006         list
1007     }
1008 
1009     /// Parse a list of test commands.
1010     pub fn parse_test_commands(&mut self) -> Vec<TestCommand<'a>> {
1011         let mut list = Vec::new();
1012         while self.token() == Some(Token::Identifier("test")) {
1013             list.push(TestCommand::new(self.consume_line()));
1014         }
1015         list
1016     }
1017 
1018     /// Parse a target spec.
1019     ///
1020     /// Accept the target from the command line for pass command.
1021     ///
1022     fn parse_cmdline_target(&mut self, target_pass: Option<&str>) -> ParseResult<isaspec::IsaSpec> {
1023         // Were there any `target` commands specified?
1024         let mut specified_target = false;
1025 
1026         let mut targets = Vec::new();
1027         let flag_builder = settings::builder();
1028 
1029         if let Some(targ) = target_pass {
1030             let loc = self.loc;
1031             let triple = match Triple::from_str(targ) {
1032                 Ok(triple) => triple,
1033                 Err(err) => return err!(loc, err),
1034             };
1035             let isa_builder = match isa::lookup(triple) {
1036                 Err(isa::LookupError::SupportDisabled) => {
1037                     return err!(loc, "support disabled target '{}'", targ);
1038                 }
1039                 Err(isa::LookupError::Unsupported) => {
1040                     return warn!(loc, "unsupported target '{}'", targ);
1041                 }
1042                 Ok(b) => b,
1043             };
1044             specified_target = true;
1045 
1046             // Construct a trait object with the aggregate settings.
1047             targets.push(
1048                 isa_builder
1049                     .finish(settings::Flags::new(flag_builder.clone()))
1050                     .map_err(|e| ParseError {
1051                         location: loc,
1052                         message: format!("invalid ISA flags for '{}': {:?}", targ, e),
1053                         is_warning: false,
1054                     })?,
1055             );
1056         }
1057 
1058         if !specified_target {
1059             // No `target` commands.
1060             Ok(isaspec::IsaSpec::None(settings::Flags::new(flag_builder)))
1061         } else {
1062             Ok(isaspec::IsaSpec::Some(targets))
1063         }
1064     }
1065 
1066     /// Parse a list of target specs.
1067     ///
1068     /// Accept a mix of `target` and `set` command lines. The `set` commands are cumulative.
1069     ///
1070     fn parse_target_specs(&mut self, options: &ParseOptions) -> ParseResult<isaspec::IsaSpec> {
1071         // Were there any `target` commands?
1072         let mut seen_target = false;
1073         // Location of last `set` command since the last `target`.
1074         let mut last_set_loc = None;
1075 
1076         let mut targets = Vec::new();
1077         let mut flag_builder = settings::builder();
1078 
1079         let unwind_info = if options.unwind_info { "true" } else { "false" };
1080         flag_builder
1081             .set("unwind_info", unwind_info)
1082             .expect("unwind_info option should be present");
1083 
1084         while let Some(Token::Identifier(command)) = self.token() {
1085             match command {
1086                 "set" => {
1087                     last_set_loc = Some(self.loc);
1088                     isaspec::parse_options(
1089                         self.consume_line().trim().split_whitespace(),
1090                         &mut flag_builder,
1091                         self.loc,
1092                     )
1093                     .map_err(|err| ParseError::from(err))?;
1094                 }
1095                 "target" => {
1096                     let loc = self.loc;
1097                     // Grab the whole line so the lexer won't go looking for tokens on the
1098                     // following lines.
1099                     let mut words = self.consume_line().trim().split_whitespace().peekable();
1100                     // Look for `target foo`.
1101                     let target_name = match words.next() {
1102                         Some(w) => w,
1103                         None => return err!(loc, "expected target triple"),
1104                     };
1105                     let triple = match Triple::from_str(target_name) {
1106                         Ok(triple) => triple,
1107                         Err(err) => return err!(loc, err),
1108                     };
1109                     let mut isa_builder = match isa::lookup(triple) {
1110                         Err(isa::LookupError::SupportDisabled) => {
1111                             continue;
1112                         }
1113                         Err(isa::LookupError::Unsupported) => {
1114                             return warn!(loc, "unsupported target '{}'", target_name);
1115                         }
1116                         Ok(b) => b,
1117                     };
1118                     last_set_loc = None;
1119                     seen_target = true;
1120                     // Apply the target-specific settings to `isa_builder`.
1121                     isaspec::parse_options(words, &mut isa_builder, self.loc)?;
1122 
1123                     // Construct a trait object with the aggregate settings.
1124                     targets.push(
1125                         isa_builder
1126                             .finish(settings::Flags::new(flag_builder.clone()))
1127                             .map_err(|e| ParseError {
1128                                 location: loc,
1129                                 message: format!(
1130                                     "invalid ISA flags for '{}': {:?}",
1131                                     target_name, e
1132                                 ),
1133                                 is_warning: false,
1134                             })?,
1135                     );
1136                 }
1137                 _ => break,
1138             }
1139         }
1140 
1141         if !seen_target {
1142             // No `target` commands, but we allow for `set` commands.
1143             Ok(isaspec::IsaSpec::None(settings::Flags::new(flag_builder)))
1144         } else if let Some(loc) = last_set_loc {
1145             err!(
1146                 loc,
1147                 "dangling 'set' command after ISA specification has no effect."
1148             )
1149         } else {
1150             Ok(isaspec::IsaSpec::Some(targets))
1151         }
1152     }
1153 
1154     /// Parse a list of expected features that Cranelift should be compiled with, or without.
1155     pub fn parse_cranelift_features(&mut self) -> ParseResult<Vec<Feature<'a>>> {
1156         let mut list = Vec::new();
1157         while self.token() == Some(Token::Identifier("feature")) {
1158             self.consume();
1159             let has = !self.optional(Token::Not);
1160             match (self.token(), has) {
1161                 (Some(Token::String(flag)), true) => list.push(Feature::With(flag)),
1162                 (Some(Token::String(flag)), false) => list.push(Feature::Without(flag)),
1163                 (tok, _) => {
1164                     return err!(
1165                         self.loc,
1166                         format!("Expected feature flag string, got {:?}", tok)
1167                     )
1168                 }
1169             }
1170             self.consume();
1171         }
1172         Ok(list)
1173     }
1174 
1175     /// Parse a list of function definitions.
1176     ///
1177     /// This is the top-level parse function matching the whole contents of a file.
1178     pub fn parse_function_list(&mut self) -> ParseResult<Vec<(Function, Details<'a>)>> {
1179         let mut list = Vec::new();
1180         while self.token().is_some() {
1181             list.push(self.parse_function()?);
1182         }
1183         if let Some(err) = self.lex_error {
1184             return match err {
1185                 LexError::InvalidChar => err!(self.loc, "invalid character"),
1186             };
1187         }
1188         Ok(list)
1189     }
1190 
1191     // Parse a whole function definition.
1192     //
1193     // function ::= * "function" name signature "{" preamble function-body "}"
1194     //
1195     fn parse_function(&mut self) -> ParseResult<(Function, Details<'a>)> {
1196         // Begin gathering comments.
1197         // Make sure we don't include any comments before the `function` keyword.
1198         self.token();
1199         debug_assert!(self.comments.is_empty());
1200         self.start_gathering_comments();
1201 
1202         self.match_identifier("function", "expected 'function'")?;
1203 
1204         let location = self.loc;
1205 
1206         // function ::= "function" * name signature "{" preamble function-body "}"
1207         let name = self.parse_user_func_name()?;
1208 
1209         // function ::= "function" name * signature "{" preamble function-body "}"
1210         let sig = self.parse_signature()?;
1211 
1212         let mut ctx = Context::new(Function::with_name_signature(name, sig));
1213 
1214         // function ::= "function" name signature * "{" preamble function-body "}"
1215         self.match_token(Token::LBrace, "expected '{' before function body")?;
1216 
1217         self.token();
1218         self.claim_gathered_comments(AnyEntity::Function);
1219 
1220         // function ::= "function" name signature "{" * preamble function-body "}"
1221         self.parse_preamble(&mut ctx)?;
1222         // function ::= "function" name signature "{"  preamble * function-body "}"
1223         self.parse_function_body(&mut ctx)?;
1224         // function ::= "function" name signature "{" preamble function-body * "}"
1225         self.match_token(Token::RBrace, "expected '}' after function body")?;
1226 
1227         // Collect any comments following the end of the function, then stop gathering comments.
1228         self.start_gathering_comments();
1229         self.token();
1230         self.claim_gathered_comments(AnyEntity::Function);
1231 
1232         // Claim all the declared user-defined function names.
1233         for (user_func_ref, user_external_name) in
1234             std::mem::take(&mut self.predeclared_external_names)
1235         {
1236             let actual_ref = ctx
1237                 .function
1238                 .declare_imported_user_function(user_external_name);
1239             assert_eq!(user_func_ref, actual_ref);
1240         }
1241 
1242         let details = Details {
1243             location,
1244             comments: self.take_comments(),
1245             map: ctx.map,
1246         };
1247 
1248         Ok((ctx.function, details))
1249     }
1250 
1251     // Parse a user-defined function name
1252     //
1253     // For example, in a function decl, the parser would be in this state:
1254     //
1255     // function ::= "function" * name signature { ... }
1256     //
1257     fn parse_user_func_name(&mut self) -> ParseResult<UserFuncName> {
1258         match self.token() {
1259             Some(Token::Name(s)) => {
1260                 self.consume();
1261                 Ok(UserFuncName::testcase(s))
1262             }
1263             Some(Token::UserRef(namespace)) => {
1264                 self.consume();
1265                 match self.token() {
1266                     Some(Token::Colon) => {
1267                         self.consume();
1268                         match self.token() {
1269                             Some(Token::Integer(index_str)) => {
1270                                 self.consume();
1271                                 let index: u32 =
1272                                     u32::from_str_radix(index_str, 10).map_err(|_| {
1273                                         self.error("the integer given overflows the u32 type")
1274                                     })?;
1275                                 Ok(UserFuncName::user(namespace, index))
1276                             }
1277                             _ => err!(self.loc, "expected integer"),
1278                         }
1279                     }
1280                     _ => {
1281                         err!(self.loc, "expected user function name in the form uX:Y")
1282                     }
1283                 }
1284             }
1285             _ => err!(self.loc, "expected external name"),
1286         }
1287     }
1288 
1289     // Parse an external name.
1290     //
1291     // For example, in a function reference decl, the parser would be in this state:
1292     //
1293     // fn0 = * name signature
1294     //
1295     fn parse_external_name(&mut self) -> ParseResult<ExternalName> {
1296         match self.token() {
1297             Some(Token::Name(s)) => {
1298                 self.consume();
1299                 s.parse()
1300                     .map_err(|_| self.error("invalid test case or libcall name"))
1301             }
1302 
1303             Some(Token::UserNameRef(name_ref)) => {
1304                 self.consume();
1305                 Ok(ExternalName::user(UserExternalNameRef::new(
1306                     name_ref as usize,
1307                 )))
1308             }
1309 
1310             Some(Token::UserRef(namespace)) => {
1311                 self.consume();
1312                 if let Some(Token::Colon) = self.token() {
1313                     self.consume();
1314                     match self.token() {
1315                         Some(Token::Integer(index_str)) => {
1316                             let index: u32 = u32::from_str_radix(index_str, 10).map_err(|_| {
1317                                 self.error("the integer given overflows the u32 type")
1318                             })?;
1319                             self.consume();
1320 
1321                             // Deduplicate the reference (O(n), but should be fine for tests),
1322                             // to follow `FunctionParameters::declare_imported_user_function`,
1323                             // otherwise this will cause ref mismatches when asserted below.
1324                             let name_ref = self
1325                                 .predeclared_external_names
1326                                 .iter()
1327                                 .find_map(|(reff, name)| {
1328                                     if name.index == index && name.namespace == namespace {
1329                                         Some(reff)
1330                                     } else {
1331                                         None
1332                                     }
1333                                 })
1334                                 .unwrap_or_else(|| {
1335                                     self.predeclared_external_names
1336                                         .push(ir::UserExternalName { namespace, index })
1337                                 });
1338 
1339                             Ok(ExternalName::user(name_ref))
1340                         }
1341                         _ => err!(self.loc, "expected integer"),
1342                     }
1343                 } else {
1344                     err!(self.loc, "expected colon")
1345                 }
1346             }
1347 
1348             _ => err!(self.loc, "expected external name"),
1349         }
1350     }
1351 
1352     // Parse a function signature.
1353     //
1354     // signature ::=  * "(" [paramlist] ")" ["->" retlist] [callconv]
1355     //
1356     fn parse_signature(&mut self) -> ParseResult<Signature> {
1357         // Calling convention defaults to `fast`, but can be changed.
1358         let mut sig = Signature::new(self.default_calling_convention);
1359 
1360         self.match_token(Token::LPar, "expected function signature: ( args... )")?;
1361         // signature ::=  "(" * [abi-param-list] ")" ["->" retlist] [callconv]
1362         if self.token() != Some(Token::RPar) {
1363             sig.params = self.parse_abi_param_list()?;
1364         }
1365         self.match_token(Token::RPar, "expected ')' after function arguments")?;
1366         if self.optional(Token::Arrow) {
1367             sig.returns = self.parse_abi_param_list()?;
1368         }
1369 
1370         // The calling convention is optional.
1371         if let Some(Token::Identifier(text)) = self.token() {
1372             match text.parse() {
1373                 Ok(cc) => {
1374                     self.consume();
1375                     sig.call_conv = cc;
1376                 }
1377                 _ => return err!(self.loc, "unknown calling convention: {}", text),
1378             }
1379         }
1380 
1381         Ok(sig)
1382     }
1383 
1384     // Parse list of function parameter / return value types.
1385     //
1386     // paramlist ::= * param { "," param }
1387     //
1388     fn parse_abi_param_list(&mut self) -> ParseResult<Vec<AbiParam>> {
1389         let mut list = Vec::new();
1390 
1391         // abi-param-list ::= * abi-param { "," abi-param }
1392         list.push(self.parse_abi_param()?);
1393 
1394         // abi-param-list ::= abi-param * { "," abi-param }
1395         while self.optional(Token::Comma) {
1396             // abi-param-list ::= abi-param { "," * abi-param }
1397             list.push(self.parse_abi_param()?);
1398         }
1399 
1400         Ok(list)
1401     }
1402 
1403     // Parse a single argument type with flags.
1404     fn parse_abi_param(&mut self) -> ParseResult<AbiParam> {
1405         // abi-param ::= * type { flag }
1406         let mut arg = AbiParam::new(self.match_type("expected parameter type")?);
1407 
1408         // abi-param ::= type * { flag }
1409         while let Some(Token::Identifier(s)) = self.token() {
1410             match s {
1411                 "uext" => arg.extension = ArgumentExtension::Uext,
1412                 "sext" => arg.extension = ArgumentExtension::Sext,
1413                 "sarg" => {
1414                     self.consume();
1415                     self.match_token(Token::LPar, "expected '(' to begin sarg size")?;
1416                     let size = self.match_uimm32("expected byte-size in sarg decl")?;
1417                     self.match_token(Token::RPar, "expected ')' to end sarg size")?;
1418                     arg.purpose = ArgumentPurpose::StructArgument(size.into());
1419                     continue;
1420                 }
1421                 _ => {
1422                     if let Ok(purpose) = s.parse() {
1423                         arg.purpose = purpose;
1424                     } else {
1425                         break;
1426                     }
1427                 }
1428             }
1429             self.consume();
1430         }
1431 
1432         Ok(arg)
1433     }
1434 
1435     // Parse the function preamble.
1436     //
1437     // preamble      ::= * { preamble-decl }
1438     // preamble-decl ::= * stack-slot-decl
1439     //                   * function-decl
1440     //                   * signature-decl
1441     //                   * jump-table-decl
1442     //                   * stack-limit-decl
1443     //
1444     // The parsed decls are added to `ctx` rather than returned.
1445     fn parse_preamble(&mut self, ctx: &mut Context) -> ParseResult<()> {
1446         loop {
1447             match self.token() {
1448                 Some(Token::StackSlot(..)) => {
1449                     self.start_gathering_comments();
1450                     let loc = self.loc;
1451                     self.parse_stack_slot_decl()
1452                         .and_then(|(ss, dat)| ctx.add_ss(ss, dat, loc))
1453                 }
1454                 Some(Token::DynamicStackSlot(..)) => {
1455                     self.start_gathering_comments();
1456                     let loc = self.loc;
1457                     self.parse_dynamic_stack_slot_decl()
1458                         .and_then(|(dss, dat)| ctx.add_dss(dss, dat, loc))
1459                 }
1460                 Some(Token::DynamicType(..)) => {
1461                     self.start_gathering_comments();
1462                     let loc = self.loc;
1463                     self.parse_dynamic_type_decl()
1464                         .and_then(|(dt, dat)| ctx.add_dt(dt, dat, loc))
1465                 }
1466                 Some(Token::GlobalValue(..)) => {
1467                     self.start_gathering_comments();
1468                     self.parse_global_value_decl()
1469                         .and_then(|(gv, dat)| ctx.add_gv(gv, dat, self.loc))
1470                 }
1471                 Some(Token::Table(..)) => {
1472                     self.start_gathering_comments();
1473                     self.parse_table_decl()
1474                         .and_then(|(table, dat)| ctx.add_table(table, dat, self.loc))
1475                 }
1476                 Some(Token::SigRef(..)) => {
1477                     self.start_gathering_comments();
1478                     self.parse_signature_decl().and_then(|(sig, dat)| {
1479                         ctx.add_sig(sig, dat, self.loc, self.default_calling_convention)
1480                     })
1481                 }
1482                 Some(Token::FuncRef(..)) => {
1483                     self.start_gathering_comments();
1484                     self.parse_function_decl(ctx)
1485                         .and_then(|(fn_, dat)| ctx.add_fn(fn_, dat, self.loc))
1486                 }
1487                 Some(Token::JumpTable(..)) => {
1488                     self.start_gathering_comments();
1489                     self.parse_jump_table_decl()
1490                         .and_then(|(jt, dat)| ctx.add_jt(jt, dat, self.loc))
1491                 }
1492                 Some(Token::Constant(..)) => {
1493                     self.start_gathering_comments();
1494                     self.parse_constant_decl()
1495                         .and_then(|(c, v)| ctx.add_constant(c, v, self.loc))
1496                 }
1497                 Some(Token::Identifier("stack_limit")) => {
1498                     self.start_gathering_comments();
1499                     self.parse_stack_limit_decl()
1500                         .and_then(|gv| ctx.add_stack_limit(gv, self.loc))
1501                 }
1502                 // More to come..
1503                 _ => return Ok(()),
1504             }?;
1505         }
1506     }
1507 
1508     // Parse a stack slot decl.
1509     //
1510     // stack-slot-decl ::= * StackSlot(ss) "=" stack-slot-kind Bytes {"," stack-slot-flag}
1511     // stack-slot-kind ::= "explicit_slot"
1512     //                   | "spill_slot"
1513     //                   | "incoming_arg"
1514     //                   | "outgoing_arg"
1515     fn parse_stack_slot_decl(&mut self) -> ParseResult<(StackSlot, StackSlotData)> {
1516         let ss = self.match_ss("expected stack slot number: ss«n»")?;
1517         self.match_token(Token::Equal, "expected '=' in stack slot declaration")?;
1518         let kind = self.match_enum("expected stack slot kind")?;
1519 
1520         // stack-slot-decl ::= StackSlot(ss) "=" stack-slot-kind * Bytes {"," stack-slot-flag}
1521         let bytes: i64 = self
1522             .match_imm64("expected byte-size in stack_slot decl")?
1523             .into();
1524         if bytes < 0 {
1525             return err!(self.loc, "negative stack slot size");
1526         }
1527         if bytes > i64::from(u32::MAX) {
1528             return err!(self.loc, "stack slot too large");
1529         }
1530         let data = StackSlotData::new(kind, bytes as u32);
1531 
1532         // Collect any trailing comments.
1533         self.token();
1534         self.claim_gathered_comments(ss);
1535 
1536         // TBD: stack-slot-decl ::= StackSlot(ss) "=" stack-slot-kind Bytes * {"," stack-slot-flag}
1537         Ok((ss, data))
1538     }
1539 
1540     fn parse_dynamic_stack_slot_decl(
1541         &mut self,
1542     ) -> ParseResult<(DynamicStackSlot, DynamicStackSlotData)> {
1543         let dss = self.match_dss("expected stack slot number: dss«n»")?;
1544         self.match_token(Token::Equal, "expected '=' in stack slot declaration")?;
1545         let kind = self.match_enum("expected stack slot kind")?;
1546         let dt = self.match_dt("expected dynamic type")?;
1547         let data = DynamicStackSlotData::new(kind, dt);
1548         // Collect any trailing comments.
1549         self.token();
1550         self.claim_gathered_comments(dss);
1551 
1552         // TBD: stack-slot-decl ::= StackSlot(ss) "=" stack-slot-kind Bytes * {"," stack-slot-flag}
1553         Ok((dss, data))
1554     }
1555 
1556     fn parse_dynamic_type_decl(&mut self) -> ParseResult<(DynamicType, DynamicTypeData)> {
1557         let dt = self.match_dt("expected dynamic type number: dt«n»")?;
1558         self.match_token(Token::Equal, "expected '=' in stack slot declaration")?;
1559         let vector_base_ty = self.match_type("expected base type")?;
1560         assert!(vector_base_ty.is_vector(), "expected vector type");
1561         self.match_token(
1562             Token::Multiply,
1563             "expected '*' followed by a dynamic scale value",
1564         )?;
1565         let dyn_scale = self.match_gv("expected dynamic scale global value")?;
1566         let data = DynamicTypeData::new(vector_base_ty, dyn_scale);
1567         // Collect any trailing comments.
1568         self.token();
1569         self.claim_gathered_comments(dt);
1570         Ok((dt, data))
1571     }
1572 
1573     // Parse a global value decl.
1574     //
1575     // global-val-decl ::= * GlobalValue(gv) "=" global-val-desc
1576     // global-val-desc ::= "vmctx"
1577     //                   | "load" "." type "notrap" "aligned" GlobalValue(base) [offset]
1578     //                   | "iadd_imm" "(" GlobalValue(base) ")" imm64
1579     //                   | "symbol" ["colocated"] name + imm64
1580     //                   | "dyn_scale_target_const" "." type
1581     //
1582     fn parse_global_value_decl(&mut self) -> ParseResult<(GlobalValue, GlobalValueData)> {
1583         let gv = self.match_gv("expected global value number: gv«n»")?;
1584 
1585         self.match_token(Token::Equal, "expected '=' in global value declaration")?;
1586 
1587         let data = match self.match_any_identifier("expected global value kind")? {
1588             "vmctx" => GlobalValueData::VMContext,
1589             "load" => {
1590                 self.match_token(
1591                     Token::Dot,
1592                     "expected '.' followed by type in load global value decl",
1593                 )?;
1594                 let global_type = self.match_type("expected load type")?;
1595                 let flags = self.optional_memflags();
1596                 let base = self.match_gv("expected global value: gv«n»")?;
1597                 let offset = self.optional_offset32()?;
1598 
1599                 if !(flags.notrap() && flags.aligned()) {
1600                     return err!(self.loc, "global-value load must be notrap and aligned");
1601                 }
1602                 GlobalValueData::Load {
1603                     base,
1604                     offset,
1605                     global_type,
1606                     readonly: flags.readonly(),
1607                 }
1608             }
1609             "iadd_imm" => {
1610                 self.match_token(
1611                     Token::Dot,
1612                     "expected '.' followed by type in iadd_imm global value decl",
1613                 )?;
1614                 let global_type = self.match_type("expected iadd type")?;
1615                 let base = self.match_gv("expected global value: gv«n»")?;
1616                 self.match_token(
1617                     Token::Comma,
1618                     "expected ',' followed by rhs in iadd_imm global value decl",
1619                 )?;
1620                 let offset = self.match_imm64("expected iadd_imm immediate")?;
1621                 GlobalValueData::IAddImm {
1622                     base,
1623                     offset,
1624                     global_type,
1625                 }
1626             }
1627             "symbol" => {
1628                 let colocated = self.optional(Token::Identifier("colocated"));
1629                 let tls = self.optional(Token::Identifier("tls"));
1630                 let name = self.parse_external_name()?;
1631                 let offset = self.optional_offset_imm64()?;
1632                 GlobalValueData::Symbol {
1633                     name,
1634                     offset,
1635                     colocated,
1636                     tls,
1637                 }
1638             }
1639             "dyn_scale_target_const" => {
1640                 self.match_token(
1641                     Token::Dot,
1642                     "expected '.' followed by type in dynamic scale global value decl",
1643                 )?;
1644                 let vector_type = self.match_type("expected load type")?;
1645                 assert!(vector_type.is_vector(), "Expected vector type");
1646                 GlobalValueData::DynScaleTargetConst { vector_type }
1647             }
1648             other => return err!(self.loc, "Unknown global value kind '{}'", other),
1649         };
1650 
1651         // Collect any trailing comments.
1652         self.token();
1653         self.claim_gathered_comments(gv);
1654 
1655         Ok((gv, data))
1656     }
1657 
1658     // Parse a table decl.
1659     //
1660     // table-decl ::= * Table(table) "=" table-desc
1661     // table-desc ::= table-style table-base { "," table-attr }
1662     // table-style ::= "dynamic"
1663     // table-base ::= GlobalValue(base)
1664     // table-attr ::= "min" Imm64(bytes)
1665     //              | "bound" Imm64(bytes)
1666     //              | "element_size" Imm64(bytes)
1667     //              | "index_type" type
1668     //
1669     fn parse_table_decl(&mut self) -> ParseResult<(Table, TableData)> {
1670         let table = self.match_table("expected table number: table«n»")?;
1671         self.match_token(Token::Equal, "expected '=' in table declaration")?;
1672 
1673         let style_name = self.match_any_identifier("expected 'static' or 'dynamic'")?;
1674 
1675         // table-desc ::= table-style * table-base { "," table-attr }
1676         // table-base ::= * GlobalValue(base)
1677         let base = match self.token() {
1678             Some(Token::GlobalValue(base_num)) => match GlobalValue::with_number(base_num) {
1679                 Some(gv) => gv,
1680                 None => return err!(self.loc, "invalid global value number for table base"),
1681             },
1682             _ => return err!(self.loc, "expected table base"),
1683         };
1684         self.consume();
1685 
1686         let mut data = TableData {
1687             base_gv: base,
1688             min_size: 0.into(),
1689             bound_gv: GlobalValue::reserved_value(),
1690             element_size: 0.into(),
1691             index_type: ir::types::I32,
1692         };
1693 
1694         // table-desc ::= * { "," table-attr }
1695         while self.optional(Token::Comma) {
1696             match self.match_any_identifier("expected table attribute name")? {
1697                 "min" => {
1698                     data.min_size = self.match_uimm64("expected integer min size")?;
1699                 }
1700                 "bound" => {
1701                     data.bound_gv = match style_name {
1702                         "dynamic" => self.match_gv("expected gv bound")?,
1703                         t => return err!(self.loc, "unknown table style '{}'", t),
1704                     };
1705                 }
1706                 "element_size" => {
1707                     data.element_size = self.match_uimm64("expected integer element size")?;
1708                 }
1709                 "index_type" => {
1710                     data.index_type = self.match_type("expected index type")?;
1711                 }
1712                 t => return err!(self.loc, "unknown table attribute '{}'", t),
1713             }
1714         }
1715 
1716         // Collect any trailing comments.
1717         self.token();
1718         self.claim_gathered_comments(table);
1719 
1720         Ok((table, data))
1721     }
1722 
1723     // Parse a signature decl.
1724     //
1725     // signature-decl ::= SigRef(sigref) "=" signature
1726     //
1727     fn parse_signature_decl(&mut self) -> ParseResult<(SigRef, Signature)> {
1728         let sig = self.match_sig("expected signature number: sig«n»")?;
1729         self.match_token(Token::Equal, "expected '=' in signature decl")?;
1730         let data = self.parse_signature()?;
1731 
1732         // Collect any trailing comments.
1733         self.token();
1734         self.claim_gathered_comments(sig);
1735 
1736         Ok((sig, data))
1737     }
1738 
1739     // Parse a function decl.
1740     //
1741     // Two variants:
1742     //
1743     // function-decl ::= FuncRef(fnref) "=" ["colocated"]" name function-decl-sig
1744     // function-decl-sig ::= SigRef(sig) | signature
1745     //
1746     // The first variant allocates a new signature reference. The second references an existing
1747     // signature which must be declared first.
1748     //
1749     fn parse_function_decl(&mut self, ctx: &mut Context) -> ParseResult<(FuncRef, ExtFuncData)> {
1750         let fn_ = self.match_fn("expected function number: fn«n»")?;
1751         self.match_token(Token::Equal, "expected '=' in function decl")?;
1752 
1753         let loc = self.loc;
1754 
1755         // function-decl ::= FuncRef(fnref) "=" * ["colocated"] name function-decl-sig
1756         let colocated = self.optional(Token::Identifier("colocated"));
1757 
1758         // function-decl ::= FuncRef(fnref) "=" ["colocated"] * name function-decl-sig
1759         let name = self.parse_external_name()?;
1760 
1761         // function-decl ::= FuncRef(fnref) "=" ["colocated"] name * function-decl-sig
1762         let data = match self.token() {
1763             Some(Token::LPar) => {
1764                 // function-decl ::= FuncRef(fnref) "=" ["colocated"] name * signature
1765                 let sig = self.parse_signature()?;
1766                 let sigref = ctx.function.import_signature(sig);
1767                 ctx.map
1768                     .def_entity(sigref.into(), loc)
1769                     .expect("duplicate SigRef entities created");
1770                 ExtFuncData {
1771                     name,
1772                     signature: sigref,
1773                     colocated,
1774                 }
1775             }
1776             Some(Token::SigRef(sig_src)) => {
1777                 let sig = match SigRef::with_number(sig_src) {
1778                     None => {
1779                         return err!(self.loc, "attempted to use invalid signature ss{}", sig_src);
1780                     }
1781                     Some(sig) => sig,
1782                 };
1783                 ctx.check_sig(sig, self.loc)?;
1784                 self.consume();
1785                 ExtFuncData {
1786                     name,
1787                     signature: sig,
1788                     colocated,
1789                 }
1790             }
1791             _ => return err!(self.loc, "expected 'function' or sig«n» in function decl"),
1792         };
1793 
1794         // Collect any trailing comments.
1795         self.token();
1796         self.claim_gathered_comments(fn_);
1797 
1798         Ok((fn_, data))
1799     }
1800 
1801     // Parse a jump table decl.
1802     //
1803     // jump-table-decl ::= * JumpTable(jt) "=" "jump_table" "[" jt-entry {"," jt-entry} "]"
1804     fn parse_jump_table_decl(&mut self) -> ParseResult<(JumpTable, JumpTableData)> {
1805         let jt = self.match_jt()?;
1806         self.match_token(Token::Equal, "expected '=' in jump_table decl")?;
1807         self.match_identifier("jump_table", "expected 'jump_table'")?;
1808         self.match_token(Token::LBracket, "expected '[' before jump table contents")?;
1809 
1810         let mut data = JumpTableData::new();
1811 
1812         // jump-table-decl ::= JumpTable(jt) "=" "jump_table" "[" * Block(dest) {"," Block(dest)} "]"
1813         match self.token() {
1814             Some(Token::Block(dest)) => {
1815                 self.consume();
1816                 data.push_entry(dest);
1817 
1818                 loop {
1819                     match self.token() {
1820                         Some(Token::Comma) => {
1821                             self.consume();
1822                             if let Some(Token::Block(dest)) = self.token() {
1823                                 self.consume();
1824                                 data.push_entry(dest);
1825                             } else {
1826                                 return err!(self.loc, "expected jump_table entry");
1827                             }
1828                         }
1829                         Some(Token::RBracket) => break,
1830                         _ => return err!(self.loc, "expected ']' after jump table contents"),
1831                     }
1832                 }
1833             }
1834             Some(Token::RBracket) => (),
1835             _ => return err!(self.loc, "expected jump_table entry"),
1836         }
1837 
1838         self.consume();
1839 
1840         // Collect any trailing comments.
1841         self.token();
1842         self.claim_gathered_comments(jt);
1843 
1844         Ok((jt, data))
1845     }
1846 
1847     // Parse a constant decl.
1848     //
1849     // constant-decl ::= * Constant(c) "=" ty? "[" literal {"," literal} "]"
1850     fn parse_constant_decl(&mut self) -> ParseResult<(Constant, ConstantData)> {
1851         let name = self.match_constant()?;
1852         self.match_token(Token::Equal, "expected '=' in constant decl")?;
1853         let data = if let Some(Token::Type(_)) = self.token() {
1854             let ty = self.match_type("expected type of constant")?;
1855             self.match_uimm128(ty)
1856         } else {
1857             self.match_constant_data()
1858         }?;
1859 
1860         // Collect any trailing comments.
1861         self.token();
1862         self.claim_gathered_comments(name);
1863 
1864         Ok((name, data))
1865     }
1866 
1867     // Parse a stack limit decl
1868     //
1869     // stack-limit-decl ::= * StackLimit "=" GlobalValue(gv)
1870     fn parse_stack_limit_decl(&mut self) -> ParseResult<GlobalValue> {
1871         self.match_stack_limit()?;
1872         self.match_token(Token::Equal, "expected '=' in stack limit decl")?;
1873         let limit = match self.token() {
1874             Some(Token::GlobalValue(base_num)) => match GlobalValue::with_number(base_num) {
1875                 Some(gv) => gv,
1876                 None => return err!(self.loc, "invalid global value number for stack limit"),
1877             },
1878             _ => return err!(self.loc, "expected global value"),
1879         };
1880         self.consume();
1881 
1882         // Collect any trailing comments.
1883         self.token();
1884         self.claim_gathered_comments(AnyEntity::StackLimit);
1885 
1886         Ok(limit)
1887     }
1888 
1889     // Parse a function body, add contents to `ctx`.
1890     //
1891     // function-body ::= * { extended-basic-block }
1892     //
1893     fn parse_function_body(&mut self, ctx: &mut Context) -> ParseResult<()> {
1894         while self.token() != Some(Token::RBrace) {
1895             self.parse_basic_block(ctx)?;
1896         }
1897 
1898         // Now that we've seen all defined values in the function, ensure that
1899         // all references refer to a definition.
1900         for block in &ctx.function.layout {
1901             for inst in ctx.function.layout.block_insts(block) {
1902                 for value in ctx.function.dfg.inst_args(inst) {
1903                     if !ctx.map.contains_value(*value) {
1904                         return err!(
1905                             ctx.map.location(AnyEntity::Inst(inst)).unwrap(),
1906                             "undefined operand value {}",
1907                             value
1908                         );
1909                     }
1910                 }
1911             }
1912         }
1913 
1914         for alias in &ctx.aliases {
1915             if !ctx.function.dfg.set_alias_type_for_parser(*alias) {
1916                 let loc = ctx.map.location(AnyEntity::Value(*alias)).unwrap();
1917                 return err!(loc, "alias cycle involving {}", alias);
1918             }
1919         }
1920 
1921         Ok(())
1922     }
1923 
1924     // Parse a basic block, add contents to `ctx`.
1925     //
1926     // extended-basic-block ::= * block-header { instruction }
1927     // block-header         ::= Block(block) [block-params] [block-flags] ":"
1928     // block-flags          ::= [Cold]
1929     //
1930     fn parse_basic_block(&mut self, ctx: &mut Context) -> ParseResult<()> {
1931         // Collect comments for the next block.
1932         self.start_gathering_comments();
1933 
1934         let block_num = self.match_block("expected block header")?;
1935         let block = ctx.add_block(block_num, self.loc)?;
1936 
1937         if block_num.as_u32() >= MAX_BLOCKS_IN_A_FUNCTION {
1938             return Err(self.error("too many blocks"));
1939         }
1940 
1941         if self.token() == Some(Token::LPar) {
1942             self.parse_block_params(ctx, block)?;
1943         }
1944 
1945         if self.optional(Token::Cold) {
1946             ctx.set_cold_block(block);
1947         }
1948 
1949         self.match_token(Token::Colon, "expected ':' after block parameters")?;
1950 
1951         // Collect any trailing comments.
1952         self.token();
1953         self.claim_gathered_comments(block);
1954 
1955         // extended-basic-block ::= block-header * { instruction }
1956         while match self.token() {
1957             Some(Token::Value(_))
1958             | Some(Token::Identifier(_))
1959             | Some(Token::LBracket)
1960             | Some(Token::SourceLoc(_)) => true,
1961             _ => false,
1962         } {
1963             let srcloc = self.optional_srcloc()?;
1964 
1965             // We need to parse instruction results here because they are shared
1966             // between the parsing of value aliases and the parsing of instructions.
1967             //
1968             // inst-results ::= Value(v) { "," Value(v) }
1969             let results = self.parse_inst_results()?;
1970 
1971             for result in &results {
1972                 while ctx.function.dfg.num_values() <= result.index() {
1973                     ctx.function.dfg.make_invalid_value_for_parser();
1974                 }
1975             }
1976 
1977             match self.token() {
1978                 Some(Token::Arrow) => {
1979                     self.consume();
1980                     self.parse_value_alias(&results, ctx)?;
1981                 }
1982                 Some(Token::Equal) => {
1983                     self.consume();
1984                     self.parse_instruction(&results, srcloc, ctx, block)?;
1985                 }
1986                 _ if !results.is_empty() => return err!(self.loc, "expected -> or ="),
1987                 _ => self.parse_instruction(&results, srcloc, ctx, block)?,
1988             }
1989         }
1990 
1991         Ok(())
1992     }
1993 
1994     // Parse parenthesized list of block parameters. Returns a vector of (u32, Type) pairs with the
1995     // value numbers of the defined values and the defined types.
1996     //
1997     // block-params ::= * "(" block-param { "," block-param } ")"
1998     fn parse_block_params(&mut self, ctx: &mut Context, block: Block) -> ParseResult<()> {
1999         // block-params ::= * "(" block-param { "," block-param } ")"
2000         self.match_token(Token::LPar, "expected '(' before block parameters")?;
2001 
2002         // block-params ::= "(" * block-param { "," block-param } ")"
2003         self.parse_block_param(ctx, block)?;
2004 
2005         // block-params ::= "(" block-param * { "," block-param } ")"
2006         while self.optional(Token::Comma) {
2007             // block-params ::= "(" block-param { "," * block-param } ")"
2008             self.parse_block_param(ctx, block)?;
2009         }
2010 
2011         // block-params ::= "(" block-param { "," block-param } * ")"
2012         self.match_token(Token::RPar, "expected ')' after block parameters")?;
2013 
2014         Ok(())
2015     }
2016 
2017     // Parse a single block parameter declaration, and append it to `block`.
2018     //
2019     // block-param ::= * Value(v) ":" Type(t) arg-loc?
2020     // arg-loc ::= "[" value-location "]"
2021     //
2022     fn parse_block_param(&mut self, ctx: &mut Context, block: Block) -> ParseResult<()> {
2023         // block-param ::= * Value(v) ":" Type(t) arg-loc?
2024         let v = self.match_value("block argument must be a value")?;
2025         let v_location = self.loc;
2026         // block-param ::= Value(v) * ":" Type(t) arg-loc?
2027         self.match_token(Token::Colon, "expected ':' after block argument")?;
2028         // block-param ::= Value(v) ":" * Type(t) arg-loc?
2029 
2030         while ctx.function.dfg.num_values() <= v.index() {
2031             ctx.function.dfg.make_invalid_value_for_parser();
2032         }
2033 
2034         let t = self.match_type("expected block argument type")?;
2035         // Allocate the block argument.
2036         ctx.function.dfg.append_block_param_for_parser(block, t, v);
2037         ctx.map.def_value(v, v_location)?;
2038 
2039         Ok(())
2040     }
2041 
2042     // Parse instruction results and return them.
2043     //
2044     // inst-results ::= Value(v) { "," Value(v) }
2045     //
2046     fn parse_inst_results(&mut self) -> ParseResult<SmallVec<[Value; 1]>> {
2047         // Result value numbers.
2048         let mut results = SmallVec::new();
2049 
2050         // instruction  ::=  * [inst-results "="] Opcode(opc) ["." Type] ...
2051         // inst-results ::= * Value(v) { "," Value(v) }
2052         if let Some(Token::Value(v)) = self.token() {
2053             self.consume();
2054 
2055             results.push(v);
2056 
2057             // inst-results ::= Value(v) * { "," Value(v) }
2058             while self.optional(Token::Comma) {
2059                 // inst-results ::= Value(v) { "," * Value(v) }
2060                 results.push(self.match_value("expected result value")?);
2061             }
2062         }
2063 
2064         Ok(results)
2065     }
2066 
2067     // Parse a value alias, and append it to `block`.
2068     //
2069     // value_alias ::= [inst-results] "->" Value(v)
2070     //
2071     fn parse_value_alias(&mut self, results: &[Value], ctx: &mut Context) -> ParseResult<()> {
2072         if results.len() != 1 {
2073             return err!(self.loc, "wrong number of aliases");
2074         }
2075         let result = results[0];
2076         let dest = self.match_value("expected value alias")?;
2077 
2078         // Allow duplicate definitions of aliases, as long as they are identical.
2079         if ctx.map.contains_value(result) {
2080             if let Some(old) = ctx.function.dfg.value_alias_dest_for_serialization(result) {
2081                 if old != dest {
2082                     return err!(
2083                         self.loc,
2084                         "value {} is already defined as an alias with destination {}",
2085                         result,
2086                         old
2087                     );
2088                 }
2089             } else {
2090                 return err!(self.loc, "value {} is already defined");
2091             }
2092         } else {
2093             ctx.map.def_value(result, self.loc)?;
2094         }
2095 
2096         if !ctx.map.contains_value(dest) {
2097             return err!(self.loc, "value {} is not yet defined", dest);
2098         }
2099 
2100         ctx.function
2101             .dfg
2102             .make_value_alias_for_serialization(dest, result);
2103 
2104         ctx.aliases.push(result);
2105         Ok(())
2106     }
2107 
2108     // Parse an instruction, append it to `block`.
2109     //
2110     // instruction ::= [inst-results "="] Opcode(opc) ["." Type] ...
2111     //
2112     fn parse_instruction(
2113         &mut self,
2114         results: &[Value],
2115         srcloc: ir::SourceLoc,
2116         ctx: &mut Context,
2117         block: Block,
2118     ) -> ParseResult<()> {
2119         // Define the result values.
2120         for val in results {
2121             ctx.map.def_value(*val, self.loc)?;
2122         }
2123 
2124         // Collect comments for the next instruction.
2125         self.start_gathering_comments();
2126 
2127         // instruction ::=  [inst-results "="] * Opcode(opc) ["." Type] ...
2128         let opcode = if let Some(Token::Identifier(text)) = self.token() {
2129             match text.parse() {
2130                 Ok(opc) => opc,
2131                 Err(msg) => return err!(self.loc, "{}: '{}'", msg, text),
2132             }
2133         } else {
2134             return err!(self.loc, "expected instruction opcode");
2135         };
2136         let opcode_loc = self.loc;
2137         self.consume();
2138 
2139         // Look for a controlling type variable annotation.
2140         // instruction ::=  [inst-results "="] Opcode(opc) * ["." Type] ...
2141         let explicit_ctrl_type = if self.optional(Token::Dot) {
2142             if let Some(Token::Type(_t)) = self.token() {
2143                 Some(self.match_type("expected type after 'opcode.'")?)
2144             } else {
2145                 let dt = self.match_dt("expected dynamic type")?;
2146                 self.concrete_from_dt(dt, ctx)
2147             }
2148         } else {
2149             None
2150         };
2151 
2152         // instruction ::=  [inst-results "="] Opcode(opc) ["." Type] * ...
2153         let inst_data = self.parse_inst_operands(ctx, opcode, explicit_ctrl_type)?;
2154 
2155         // We're done parsing the instruction now.
2156         //
2157         // We still need to check that the number of result values in the source matches the opcode
2158         // or function call signature. We also need to create values with the right type for all
2159         // the instruction results.
2160         let ctrl_typevar = self.infer_typevar(ctx, opcode, explicit_ctrl_type, &inst_data)?;
2161         let inst = ctx.function.dfg.make_inst(inst_data);
2162         let num_results =
2163             ctx.function
2164                 .dfg
2165                 .make_inst_results_for_parser(inst, ctrl_typevar, results);
2166         ctx.function.layout.append_inst(inst, block);
2167         ctx.map
2168             .def_entity(inst.into(), opcode_loc)
2169             .expect("duplicate inst references created");
2170 
2171         if !srcloc.is_default() {
2172             ctx.function.set_srcloc(inst, srcloc);
2173         }
2174 
2175         if results.len() != num_results {
2176             return err!(
2177                 self.loc,
2178                 "instruction produces {} result values, {} given",
2179                 num_results,
2180                 results.len()
2181             );
2182         }
2183 
2184         // Collect any trailing comments.
2185         self.token();
2186         self.claim_gathered_comments(inst);
2187 
2188         Ok(())
2189     }
2190 
2191     // Type inference for polymorphic instructions.
2192     //
2193     // The controlling type variable can be specified explicitly as 'splat.i32x4 v5', or it can be
2194     // inferred from `inst_data.typevar_operand` for some opcodes.
2195     //
2196     // Returns the controlling typevar for a polymorphic opcode, or `INVALID` for a non-polymorphic
2197     // opcode.
2198     fn infer_typevar(
2199         &self,
2200         ctx: &Context,
2201         opcode: Opcode,
2202         explicit_ctrl_type: Option<Type>,
2203         inst_data: &InstructionData,
2204     ) -> ParseResult<Type> {
2205         let constraints = opcode.constraints();
2206         let ctrl_type = match explicit_ctrl_type {
2207             Some(t) => t,
2208             None => {
2209                 if constraints.use_typevar_operand() {
2210                     // This is an opcode that supports type inference, AND there was no
2211                     // explicit type specified. Look up `ctrl_value` to see if it was defined
2212                     // already.
2213                     // TBD: If it is defined in another block, the type should have been
2214                     // specified explicitly. It is unfortunate that the correctness of IR
2215                     // depends on the layout of the blocks.
2216                     let ctrl_src_value = inst_data
2217                         .typevar_operand(&ctx.function.dfg.value_lists)
2218                         .expect("Constraints <-> Format inconsistency");
2219                     if !ctx.map.contains_value(ctrl_src_value) {
2220                         return err!(
2221                             self.loc,
2222                             "type variable required for polymorphic opcode, e.g. '{}.{}'; \
2223                              can't infer from {} which is not yet defined",
2224                             opcode,
2225                             constraints.ctrl_typeset().unwrap().example(),
2226                             ctrl_src_value
2227                         );
2228                     }
2229                     if !ctx.function.dfg.value_is_valid_for_parser(ctrl_src_value) {
2230                         return err!(
2231                             self.loc,
2232                             "type variable required for polymorphic opcode, e.g. '{}.{}'; \
2233                              can't infer from {} which is not yet resolved",
2234                             opcode,
2235                             constraints.ctrl_typeset().unwrap().example(),
2236                             ctrl_src_value
2237                         );
2238                     }
2239                     ctx.function.dfg.value_type(ctrl_src_value)
2240                 } else if constraints.is_polymorphic() {
2241                     // This opcode does not support type inference, so the explicit type
2242                     // variable is required.
2243                     return err!(
2244                         self.loc,
2245                         "type variable required for polymorphic opcode, e.g. '{}.{}'",
2246                         opcode,
2247                         constraints.ctrl_typeset().unwrap().example()
2248                     );
2249                 } else {
2250                     // This is a non-polymorphic opcode. No typevar needed.
2251                     INVALID
2252                 }
2253             }
2254         };
2255 
2256         // Verify that `ctrl_type` is valid for the controlling type variable. We don't want to
2257         // attempt deriving types from an incorrect basis.
2258         // This is not a complete type check. The verifier does that.
2259         if let Some(typeset) = constraints.ctrl_typeset() {
2260             // This is a polymorphic opcode.
2261             if !typeset.contains(ctrl_type) {
2262                 return err!(
2263                     self.loc,
2264                     "{} is not a valid typevar for {}",
2265                     ctrl_type,
2266                     opcode
2267                 );
2268             }
2269         // Treat it as a syntax error to specify a typevar on a non-polymorphic opcode.
2270         } else if ctrl_type != INVALID {
2271             return err!(self.loc, "{} does not take a typevar", opcode);
2272         }
2273 
2274         Ok(ctrl_type)
2275     }
2276 
2277     // Parse comma-separated value list into a VariableArgs struct.
2278     //
2279     // value_list ::= [ value { "," value } ]
2280     //
2281     fn parse_value_list(&mut self) -> ParseResult<VariableArgs> {
2282         let mut args = VariableArgs::new();
2283 
2284         if let Some(Token::Value(v)) = self.token() {
2285             args.push(v);
2286             self.consume();
2287         } else {
2288             return Ok(args);
2289         }
2290 
2291         while self.optional(Token::Comma) {
2292             args.push(self.match_value("expected value in argument list")?);
2293         }
2294 
2295         Ok(args)
2296     }
2297 
2298     // Parse an optional value list enclosed in parentheses.
2299     fn parse_opt_value_list(&mut self) -> ParseResult<VariableArgs> {
2300         if !self.optional(Token::LPar) {
2301             return Ok(VariableArgs::new());
2302         }
2303 
2304         let args = self.parse_value_list()?;
2305 
2306         self.match_token(Token::RPar, "expected ')' after arguments")?;
2307 
2308         Ok(args)
2309     }
2310 
2311     /// Parse a CLIF run command.
2312     ///
2313     /// run-command ::= "run" [":" invocation comparison expected]
2314     ///               \ "print" [":" invocation]
2315     fn parse_run_command(&mut self, sig: &Signature) -> ParseResult<RunCommand> {
2316         // skip semicolon
2317         match self.token() {
2318             Some(Token::Identifier("run")) => {
2319                 self.consume();
2320                 if self.optional(Token::Colon) {
2321                     let invocation = self.parse_run_invocation(sig)?;
2322                     let comparison = self.parse_run_comparison()?;
2323                     let expected = self.parse_run_returns(sig)?;
2324                     Ok(RunCommand::Run(invocation, comparison, expected))
2325                 } else if sig.params.is_empty()
2326                     && sig.returns.len() == 1
2327                     && sig.returns[0].value_type.is_int()
2328                 {
2329                     // To match the existing run behavior that does not require an explicit
2330                     // invocation, we create an invocation from a function like `() -> i*` and
2331                     // require the result to be non-zero.
2332                     let invocation = Invocation::new("default", vec![]);
2333                     let expected = vec![DataValue::I8(0)];
2334                     let comparison = Comparison::NotEquals;
2335                     Ok(RunCommand::Run(invocation, comparison, expected))
2336                 } else {
2337                     Err(self.error("unable to parse the run command"))
2338                 }
2339             }
2340             Some(Token::Identifier("print")) => {
2341                 self.consume();
2342                 if self.optional(Token::Colon) {
2343                     Ok(RunCommand::Print(self.parse_run_invocation(sig)?))
2344                 } else if sig.params.is_empty() {
2345                     // To allow printing of functions like `() -> *`, we create a no-arg invocation.
2346                     let invocation = Invocation::new("default", vec![]);
2347                     Ok(RunCommand::Print(invocation))
2348                 } else {
2349                     Err(self.error("unable to parse the print command"))
2350                 }
2351             }
2352             _ => Err(self.error("expected a 'run:' or 'print:' command")),
2353         }
2354     }
2355 
2356     /// Parse the invocation of a CLIF function.
2357     ///
2358     /// This is different from parsing a CLIF `call`; it is used in parsing run commands like
2359     /// `run: %fn(42, 4.2) == false`.
2360     ///
2361     /// invocation ::= name "(" [data-value-list] ")"
2362     fn parse_run_invocation(&mut self, sig: &Signature) -> ParseResult<Invocation> {
2363         if let Some(Token::Name(name)) = self.token() {
2364             self.consume();
2365             self.match_token(
2366                 Token::LPar,
2367                 "expected invocation parentheses, e.g. %fn(...)",
2368             )?;
2369 
2370             let arg_types = sig
2371                 .params
2372                 .iter()
2373                 .enumerate()
2374                 .filter_map(|(i, p)| {
2375                     // The first argument being VMCtx indicates that this is a argument that is going
2376                     // to be passed in with info about the test environment, and should not be passed
2377                     // in the run params.
2378                     if p.purpose == ir::ArgumentPurpose::VMContext && i == 0 {
2379                         None
2380                     } else {
2381                         Some(p.value_type)
2382                     }
2383                 })
2384                 .collect::<Vec<_>>();
2385             let args = self.parse_data_value_list(&arg_types)?;
2386 
2387             self.match_token(
2388                 Token::RPar,
2389                 "expected invocation parentheses, e.g. %fn(...)",
2390             )?;
2391             Ok(Invocation::new(name, args))
2392         } else {
2393             Err(self.error("expected a function name, e.g. %my_fn"))
2394         }
2395     }
2396 
2397     /// Parse a comparison operator for run commands.
2398     ///
2399     /// comparison ::= "==" | "!="
2400     fn parse_run_comparison(&mut self) -> ParseResult<Comparison> {
2401         if self.optional(Token::Equal) {
2402             self.match_token(Token::Equal, "expected another =")?;
2403             Ok(Comparison::Equals)
2404         } else if self.optional(Token::Not) {
2405             self.match_token(Token::Equal, "expected a =")?;
2406             Ok(Comparison::NotEquals)
2407         } else {
2408             Err(self.error("unable to parse a valid comparison operator"))
2409         }
2410     }
2411 
2412     /// Parse the expected return values of a run invocation.
2413     ///
2414     /// expected ::= "[" "]"
2415     ///            | data-value
2416     ///            | "[" data-value-list "]"
2417     fn parse_run_returns(&mut self, sig: &Signature) -> ParseResult<Vec<DataValue>> {
2418         if sig.returns.len() != 1 {
2419             self.match_token(Token::LBracket, "expected a left bracket [")?;
2420         }
2421 
2422         let returns = self
2423             .parse_data_value_list(&sig.returns.iter().map(|a| a.value_type).collect::<Vec<_>>())?;
2424 
2425         if sig.returns.len() != 1 {
2426             self.match_token(Token::RBracket, "expected a right bracket ]")?;
2427         }
2428         Ok(returns)
2429     }
2430 
2431     /// Parse a comma-separated list of data values.
2432     ///
2433     /// data-value-list ::= [data-value {"," data-value-list}]
2434     fn parse_data_value_list(&mut self, types: &[Type]) -> ParseResult<Vec<DataValue>> {
2435         let mut values = vec![];
2436         for ty in types.iter().take(1) {
2437             values.push(self.parse_data_value(*ty)?);
2438         }
2439         for ty in types.iter().skip(1) {
2440             self.match_token(
2441                 Token::Comma,
2442                 "expected a comma between invocation arguments",
2443             )?;
2444             values.push(self.parse_data_value(*ty)?);
2445         }
2446         Ok(values)
2447     }
2448 
2449     /// Parse a data value; e.g. `42`, `4.2`, `true`.
2450     ///
2451     /// data-value-list ::= [data-value {"," data-value-list}]
2452     fn parse_data_value(&mut self, ty: Type) -> ParseResult<DataValue> {
2453         let dv = match ty {
2454             I8 => DataValue::from(self.match_imm8("expected a i8")?),
2455             I16 => DataValue::from(self.match_imm16("expected an i16")?),
2456             I32 => DataValue::from(self.match_imm32("expected an i32")?),
2457             I64 => DataValue::from(Into::<i64>::into(self.match_imm64("expected an i64")?)),
2458             I128 => DataValue::from(self.match_imm128("expected an i128")?),
2459             F32 => DataValue::from(self.match_ieee32("expected an f32")?),
2460             F64 => DataValue::from(self.match_ieee64("expected an f64")?),
2461             _ if (ty.is_vector() || ty.is_dynamic_vector()) => {
2462                 let as_vec = self.match_uimm128(ty)?.into_vec();
2463                 if as_vec.len() == 16 {
2464                     let mut as_array = [0; 16];
2465                     as_array.copy_from_slice(&as_vec[..]);
2466                     DataValue::from(as_array)
2467                 } else if as_vec.len() == 8 {
2468                     let mut as_array = [0; 8];
2469                     as_array.copy_from_slice(&as_vec[..]);
2470                     DataValue::from(as_array)
2471                 } else {
2472                     return Err(self.error("only 128-bit vectors are currently supported"));
2473                 }
2474             }
2475             _ => return Err(self.error(&format!("don't know how to parse data values of: {}", ty))),
2476         };
2477         Ok(dv)
2478     }
2479 
2480     // Parse the operands following the instruction opcode.
2481     // This depends on the format of the opcode.
2482     fn parse_inst_operands(
2483         &mut self,
2484         ctx: &mut Context,
2485         opcode: Opcode,
2486         explicit_control_type: Option<Type>,
2487     ) -> ParseResult<InstructionData> {
2488         let idata = match opcode.format() {
2489             InstructionFormat::Unary => InstructionData::Unary {
2490                 opcode,
2491                 arg: self.match_value("expected SSA value operand")?,
2492             },
2493             InstructionFormat::UnaryImm => InstructionData::UnaryImm {
2494                 opcode,
2495                 imm: self.match_imm64("expected immediate integer operand")?,
2496             },
2497             InstructionFormat::UnaryIeee32 => InstructionData::UnaryIeee32 {
2498                 opcode,
2499                 imm: self.match_ieee32("expected immediate 32-bit float operand")?,
2500             },
2501             InstructionFormat::UnaryIeee64 => InstructionData::UnaryIeee64 {
2502                 opcode,
2503                 imm: self.match_ieee64("expected immediate 64-bit float operand")?,
2504             },
2505             InstructionFormat::UnaryConst => {
2506                 let constant_handle = if let Some(Token::Constant(_)) = self.token() {
2507                     // If handed a `const?`, use that.
2508                     let c = self.match_constant()?;
2509                     ctx.check_constant(c, self.loc)?;
2510                     c
2511                 } else if let Some(controlling_type) = explicit_control_type {
2512                     // If an explicit control type is present, we expect a sized value and insert
2513                     // it in the constant pool.
2514                     let uimm128 = self.match_uimm128(controlling_type)?;
2515                     ctx.function.dfg.constants.insert(uimm128)
2516                 } else {
2517                     return err!(
2518                         self.loc,
2519                         "Expected either a const entity or a typed value, e.g. inst.i32x4 [...]"
2520                     );
2521                 };
2522                 InstructionData::UnaryConst {
2523                     opcode,
2524                     constant_handle,
2525                 }
2526             }
2527             InstructionFormat::UnaryGlobalValue => {
2528                 let gv = self.match_gv("expected global value")?;
2529                 ctx.check_gv(gv, self.loc)?;
2530                 InstructionData::UnaryGlobalValue {
2531                     opcode,
2532                     global_value: gv,
2533                 }
2534             }
2535             InstructionFormat::Binary => {
2536                 let lhs = self.match_value("expected SSA value first operand")?;
2537                 self.match_token(Token::Comma, "expected ',' between operands")?;
2538                 let rhs = self.match_value("expected SSA value second operand")?;
2539                 InstructionData::Binary {
2540                     opcode,
2541                     args: [lhs, rhs],
2542                 }
2543             }
2544             InstructionFormat::BinaryImm8 => {
2545                 let arg = self.match_value("expected SSA value first operand")?;
2546                 self.match_token(Token::Comma, "expected ',' between operands")?;
2547                 let imm = self.match_uimm8("expected unsigned 8-bit immediate")?;
2548                 InstructionData::BinaryImm8 { opcode, arg, imm }
2549             }
2550             InstructionFormat::BinaryImm64 => {
2551                 let lhs = self.match_value("expected SSA value first operand")?;
2552                 self.match_token(Token::Comma, "expected ',' between operands")?;
2553                 let rhs = self.match_imm64("expected immediate integer second operand")?;
2554                 InstructionData::BinaryImm64 {
2555                     opcode,
2556                     arg: lhs,
2557                     imm: rhs,
2558                 }
2559             }
2560             InstructionFormat::Ternary => {
2561                 // Names here refer to the `select` instruction.
2562                 // This format is also use by `fma`.
2563                 let ctrl_arg = self.match_value("expected SSA value control operand")?;
2564                 self.match_token(Token::Comma, "expected ',' between operands")?;
2565                 let true_arg = self.match_value("expected SSA value true operand")?;
2566                 self.match_token(Token::Comma, "expected ',' between operands")?;
2567                 let false_arg = self.match_value("expected SSA value false operand")?;
2568                 InstructionData::Ternary {
2569                     opcode,
2570                     args: [ctrl_arg, true_arg, false_arg],
2571                 }
2572             }
2573             InstructionFormat::MultiAry => {
2574                 let args = self.parse_value_list()?;
2575                 InstructionData::MultiAry {
2576                     opcode,
2577                     args: args.into_value_list(&[], &mut ctx.function.dfg.value_lists),
2578                 }
2579             }
2580             InstructionFormat::NullAry => InstructionData::NullAry { opcode },
2581             InstructionFormat::Jump => {
2582                 // Parse the destination block number.
2583                 let block_num = self.match_block("expected jump destination block")?;
2584                 let args = self.parse_opt_value_list()?;
2585                 InstructionData::Jump {
2586                     opcode,
2587                     destination: block_num,
2588                     args: args.into_value_list(&[], &mut ctx.function.dfg.value_lists),
2589                 }
2590             }
2591             InstructionFormat::Branch => {
2592                 let ctrl_arg = self.match_value("expected SSA value control operand")?;
2593                 self.match_token(Token::Comma, "expected ',' between operands")?;
2594                 let block_num = self.match_block("expected branch destination block")?;
2595                 let args = self.parse_opt_value_list()?;
2596                 InstructionData::Branch {
2597                     opcode,
2598                     destination: block_num,
2599                     args: args.into_value_list(&[ctrl_arg], &mut ctx.function.dfg.value_lists),
2600                 }
2601             }
2602             InstructionFormat::BranchTable => {
2603                 let arg = self.match_value("expected SSA value operand")?;
2604                 self.match_token(Token::Comma, "expected ',' between operands")?;
2605                 let block_num = self.match_block("expected branch destination block")?;
2606                 self.match_token(Token::Comma, "expected ',' between operands")?;
2607                 let table = self.match_jt()?;
2608                 ctx.check_jt(table, self.loc)?;
2609                 InstructionData::BranchTable {
2610                     opcode,
2611                     arg,
2612                     destination: block_num,
2613                     table,
2614                 }
2615             }
2616             InstructionFormat::TernaryImm8 => {
2617                 let lhs = self.match_value("expected SSA value first operand")?;
2618                 self.match_token(Token::Comma, "expected ',' between operands")?;
2619                 let rhs = self.match_value("expected SSA value last operand")?;
2620                 self.match_token(Token::Comma, "expected ',' between operands")?;
2621                 let imm = self.match_uimm8("expected 8-bit immediate")?;
2622                 InstructionData::TernaryImm8 {
2623                     opcode,
2624                     imm,
2625                     args: [lhs, rhs],
2626                 }
2627             }
2628             InstructionFormat::Shuffle => {
2629                 let a = self.match_value("expected SSA value first operand")?;
2630                 self.match_token(Token::Comma, "expected ',' between operands")?;
2631                 let b = self.match_value("expected SSA value second operand")?;
2632                 self.match_token(Token::Comma, "expected ',' between operands")?;
2633                 let uimm128 = self.match_uimm128(I8X16)?;
2634                 let imm = ctx.function.dfg.immediates.push(uimm128);
2635                 InstructionData::Shuffle {
2636                     opcode,
2637                     imm,
2638                     args: [a, b],
2639                 }
2640             }
2641             InstructionFormat::IntCompare => {
2642                 let cond = self.match_enum("expected intcc condition code")?;
2643                 let lhs = self.match_value("expected SSA value first operand")?;
2644                 self.match_token(Token::Comma, "expected ',' between operands")?;
2645                 let rhs = self.match_value("expected SSA value second operand")?;
2646                 InstructionData::IntCompare {
2647                     opcode,
2648                     cond,
2649                     args: [lhs, rhs],
2650                 }
2651             }
2652             InstructionFormat::IntCompareImm => {
2653                 let cond = self.match_enum("expected intcc condition code")?;
2654                 let lhs = self.match_value("expected SSA value first operand")?;
2655                 self.match_token(Token::Comma, "expected ',' between operands")?;
2656                 let rhs = self.match_imm64("expected immediate second operand")?;
2657                 InstructionData::IntCompareImm {
2658                     opcode,
2659                     cond,
2660                     arg: lhs,
2661                     imm: rhs,
2662                 }
2663             }
2664             InstructionFormat::FloatCompare => {
2665                 let cond = self.match_enum("expected floatcc condition code")?;
2666                 let lhs = self.match_value("expected SSA value first operand")?;
2667                 self.match_token(Token::Comma, "expected ',' between operands")?;
2668                 let rhs = self.match_value("expected SSA value second operand")?;
2669                 InstructionData::FloatCompare {
2670                     opcode,
2671                     cond,
2672                     args: [lhs, rhs],
2673                 }
2674             }
2675             InstructionFormat::Call => {
2676                 let func_ref = self.match_fn("expected function reference")?;
2677                 ctx.check_fn(func_ref, self.loc)?;
2678                 self.match_token(Token::LPar, "expected '(' before arguments")?;
2679                 let args = self.parse_value_list()?;
2680                 self.match_token(Token::RPar, "expected ')' after arguments")?;
2681                 InstructionData::Call {
2682                     opcode,
2683                     func_ref,
2684                     args: args.into_value_list(&[], &mut ctx.function.dfg.value_lists),
2685                 }
2686             }
2687             InstructionFormat::CallIndirect => {
2688                 let sig_ref = self.match_sig("expected signature reference")?;
2689                 ctx.check_sig(sig_ref, self.loc)?;
2690                 self.match_token(Token::Comma, "expected ',' between operands")?;
2691                 let callee = self.match_value("expected SSA value callee operand")?;
2692                 self.match_token(Token::LPar, "expected '(' before arguments")?;
2693                 let args = self.parse_value_list()?;
2694                 self.match_token(Token::RPar, "expected ')' after arguments")?;
2695                 InstructionData::CallIndirect {
2696                     opcode,
2697                     sig_ref,
2698                     args: args.into_value_list(&[callee], &mut ctx.function.dfg.value_lists),
2699                 }
2700             }
2701             InstructionFormat::FuncAddr => {
2702                 let func_ref = self.match_fn("expected function reference")?;
2703                 ctx.check_fn(func_ref, self.loc)?;
2704                 InstructionData::FuncAddr { opcode, func_ref }
2705             }
2706             InstructionFormat::StackLoad => {
2707                 let ss = self.match_ss("expected stack slot number: ss«n»")?;
2708                 ctx.check_ss(ss, self.loc)?;
2709                 let offset = self.optional_offset32()?;
2710                 InstructionData::StackLoad {
2711                     opcode,
2712                     stack_slot: ss,
2713                     offset,
2714                 }
2715             }
2716             InstructionFormat::StackStore => {
2717                 let arg = self.match_value("expected SSA value operand")?;
2718                 self.match_token(Token::Comma, "expected ',' between operands")?;
2719                 let ss = self.match_ss("expected stack slot number: ss«n»")?;
2720                 ctx.check_ss(ss, self.loc)?;
2721                 let offset = self.optional_offset32()?;
2722                 InstructionData::StackStore {
2723                     opcode,
2724                     arg,
2725                     stack_slot: ss,
2726                     offset,
2727                 }
2728             }
2729             InstructionFormat::DynamicStackLoad => {
2730                 let dss = self.match_dss("expected dynamic stack slot number: dss«n»")?;
2731                 ctx.check_dss(dss, self.loc)?;
2732                 InstructionData::DynamicStackLoad {
2733                     opcode,
2734                     dynamic_stack_slot: dss,
2735                 }
2736             }
2737             InstructionFormat::DynamicStackStore => {
2738                 let arg = self.match_value("expected SSA value operand")?;
2739                 self.match_token(Token::Comma, "expected ',' between operands")?;
2740                 let dss = self.match_dss("expected dynamic stack slot number: dss«n»")?;
2741                 ctx.check_dss(dss, self.loc)?;
2742                 InstructionData::DynamicStackStore {
2743                     opcode,
2744                     arg,
2745                     dynamic_stack_slot: dss,
2746                 }
2747             }
2748             InstructionFormat::TableAddr => {
2749                 let table = self.match_table("expected table identifier")?;
2750                 ctx.check_table(table, self.loc)?;
2751                 self.match_token(Token::Comma, "expected ',' between operands")?;
2752                 let arg = self.match_value("expected SSA value table address")?;
2753                 self.match_token(Token::Comma, "expected ',' between operands")?;
2754                 let offset = self.optional_offset32()?;
2755                 InstructionData::TableAddr {
2756                     opcode,
2757                     table,
2758                     arg,
2759                     offset,
2760                 }
2761             }
2762             InstructionFormat::Load => {
2763                 let flags = self.optional_memflags();
2764                 let addr = self.match_value("expected SSA value address")?;
2765                 let offset = self.optional_offset32()?;
2766                 InstructionData::Load {
2767                     opcode,
2768                     flags,
2769                     arg: addr,
2770                     offset,
2771                 }
2772             }
2773             InstructionFormat::Store => {
2774                 let flags = self.optional_memflags();
2775                 let arg = self.match_value("expected SSA value operand")?;
2776                 self.match_token(Token::Comma, "expected ',' between operands")?;
2777                 let addr = self.match_value("expected SSA value address")?;
2778                 let offset = self.optional_offset32()?;
2779                 InstructionData::Store {
2780                     opcode,
2781                     flags,
2782                     args: [arg, addr],
2783                     offset,
2784                 }
2785             }
2786             InstructionFormat::Trap => {
2787                 let code = self.match_enum("expected trap code")?;
2788                 InstructionData::Trap { opcode, code }
2789             }
2790             InstructionFormat::CondTrap => {
2791                 let arg = self.match_value("expected SSA value operand")?;
2792                 self.match_token(Token::Comma, "expected ',' between operands")?;
2793                 let code = self.match_enum("expected trap code")?;
2794                 InstructionData::CondTrap { opcode, arg, code }
2795             }
2796             InstructionFormat::AtomicCas => {
2797                 let flags = self.optional_memflags();
2798                 let addr = self.match_value("expected SSA value address")?;
2799                 self.match_token(Token::Comma, "expected ',' between operands")?;
2800                 let expected = self.match_value("expected SSA value address")?;
2801                 self.match_token(Token::Comma, "expected ',' between operands")?;
2802                 let replacement = self.match_value("expected SSA value address")?;
2803                 InstructionData::AtomicCas {
2804                     opcode,
2805                     flags,
2806                     args: [addr, expected, replacement],
2807                 }
2808             }
2809             InstructionFormat::AtomicRmw => {
2810                 let flags = self.optional_memflags();
2811                 let op = self.match_enum("expected AtomicRmwOp")?;
2812                 let addr = self.match_value("expected SSA value address")?;
2813                 self.match_token(Token::Comma, "expected ',' between operands")?;
2814                 let arg2 = self.match_value("expected SSA value address")?;
2815                 InstructionData::AtomicRmw {
2816                     opcode,
2817                     flags,
2818                     op,
2819                     args: [addr, arg2],
2820                 }
2821             }
2822             InstructionFormat::LoadNoOffset => {
2823                 let flags = self.optional_memflags();
2824                 let addr = self.match_value("expected SSA value address")?;
2825                 InstructionData::LoadNoOffset {
2826                     opcode,
2827                     flags,
2828                     arg: addr,
2829                 }
2830             }
2831             InstructionFormat::StoreNoOffset => {
2832                 let flags = self.optional_memflags();
2833                 let arg = self.match_value("expected SSA value operand")?;
2834                 self.match_token(Token::Comma, "expected ',' between operands")?;
2835                 let addr = self.match_value("expected SSA value address")?;
2836                 InstructionData::StoreNoOffset {
2837                     opcode,
2838                     flags,
2839                     args: [arg, addr],
2840                 }
2841             }
2842             InstructionFormat::IntAddTrap => {
2843                 let a = self.match_value("expected SSA value operand")?;
2844                 self.match_token(Token::Comma, "expected ',' between operands")?;
2845                 let b = self.match_value("expected SSA value operand")?;
2846                 self.match_token(Token::Comma, "expected ',' between operands")?;
2847                 let code = self.match_enum("expected trap code")?;
2848                 InstructionData::IntAddTrap {
2849                     opcode,
2850                     args: [a, b],
2851                     code,
2852                 }
2853             }
2854         };
2855         Ok(idata)
2856     }
2857 }
2858 
2859 #[cfg(test)]
2860 mod tests {
2861     use super::*;
2862     use crate::error::ParseError;
2863     use crate::isaspec::IsaSpec;
2864     use crate::testfile::{Comment, Details};
2865     use cranelift_codegen::ir::entities::AnyEntity;
2866     use cranelift_codegen::ir::types;
2867     use cranelift_codegen::ir::StackSlotKind;
2868     use cranelift_codegen::ir::{ArgumentExtension, ArgumentPurpose};
2869     use cranelift_codegen::isa::CallConv;
2870 
2871     #[test]
2872     fn argument_type() {
2873         let mut p = Parser::new("i32 sext");
2874         let arg = p.parse_abi_param().unwrap();
2875         assert_eq!(arg.value_type, types::I32);
2876         assert_eq!(arg.extension, ArgumentExtension::Sext);
2877         assert_eq!(arg.purpose, ArgumentPurpose::Normal);
2878         let ParseError {
2879             location,
2880             message,
2881             is_warning,
2882         } = p.parse_abi_param().unwrap_err();
2883         assert_eq!(location.line_number, 1);
2884         assert_eq!(message, "expected parameter type");
2885         assert!(!is_warning);
2886     }
2887 
2888     #[test]
2889     fn aliases() {
2890         let (func, details) = Parser::new(
2891             "function %qux() system_v {
2892                                            block0:
2893                                              v4 = iconst.i8 6
2894                                              v3 -> v4
2895                                              v1 = iadd_imm v3, 17
2896                                            }",
2897         )
2898         .parse_function()
2899         .unwrap();
2900         assert_eq!(func.name.to_string(), "%qux");
2901         let v4 = details.map.lookup_str("v4").unwrap();
2902         assert_eq!(v4.to_string(), "v4");
2903         let v3 = details.map.lookup_str("v3").unwrap();
2904         assert_eq!(v3.to_string(), "v3");
2905         match v3 {
2906             AnyEntity::Value(v3) => {
2907                 let aliased_to = func.dfg.resolve_aliases(v3);
2908                 assert_eq!(aliased_to.to_string(), "v4");
2909             }
2910             _ => panic!("expected value: {}", v3),
2911         }
2912     }
2913 
2914     #[test]
2915     fn signature() {
2916         let sig = Parser::new("()system_v").parse_signature().unwrap();
2917         assert_eq!(sig.params.len(), 0);
2918         assert_eq!(sig.returns.len(), 0);
2919         assert_eq!(sig.call_conv, CallConv::SystemV);
2920 
2921         let sig2 = Parser::new("(i8 uext, f32, f64, i32 sret) -> i32 sext, f64 system_v")
2922             .parse_signature()
2923             .unwrap();
2924         assert_eq!(
2925             sig2.to_string(),
2926             "(i8 uext, f32, f64, i32 sret) -> i32 sext, f64 system_v"
2927         );
2928         assert_eq!(sig2.call_conv, CallConv::SystemV);
2929 
2930         // Old-style signature without a calling convention.
2931         assert_eq!(
2932             Parser::new("()").parse_signature().unwrap().to_string(),
2933             "() fast"
2934         );
2935         assert_eq!(
2936             Parser::new("() notacc")
2937                 .parse_signature()
2938                 .unwrap_err()
2939                 .to_string(),
2940             "1: unknown calling convention: notacc"
2941         );
2942 
2943         // `void` is not recognized as a type by the lexer. It should not appear in files.
2944         assert_eq!(
2945             Parser::new("() -> void")
2946                 .parse_signature()
2947                 .unwrap_err()
2948                 .to_string(),
2949             "1: expected parameter type"
2950         );
2951         assert_eq!(
2952             Parser::new("i8 -> i8")
2953                 .parse_signature()
2954                 .unwrap_err()
2955                 .to_string(),
2956             "1: expected function signature: ( args... )"
2957         );
2958         assert_eq!(
2959             Parser::new("(i8 -> i8")
2960                 .parse_signature()
2961                 .unwrap_err()
2962                 .to_string(),
2963             "1: expected ')' after function arguments"
2964         );
2965     }
2966 
2967     #[test]
2968     fn stack_slot_decl() {
2969         let (func, _) = Parser::new(
2970             "function %foo() system_v {
2971                                        ss3 = explicit_slot 13
2972                                        ss1 = explicit_slot 1
2973                                      }",
2974         )
2975         .parse_function()
2976         .unwrap();
2977         assert_eq!(func.name.to_string(), "%foo");
2978         let mut iter = func.sized_stack_slots.keys();
2979         let _ss0 = iter.next().unwrap();
2980         let ss1 = iter.next().unwrap();
2981         assert_eq!(ss1.to_string(), "ss1");
2982         assert_eq!(
2983             func.sized_stack_slots[ss1].kind,
2984             StackSlotKind::ExplicitSlot
2985         );
2986         assert_eq!(func.sized_stack_slots[ss1].size, 1);
2987         let _ss2 = iter.next().unwrap();
2988         let ss3 = iter.next().unwrap();
2989         assert_eq!(ss3.to_string(), "ss3");
2990         assert_eq!(
2991             func.sized_stack_slots[ss3].kind,
2992             StackSlotKind::ExplicitSlot
2993         );
2994         assert_eq!(func.sized_stack_slots[ss3].size, 13);
2995         assert_eq!(iter.next(), None);
2996 
2997         // Catch duplicate definitions.
2998         assert_eq!(
2999             Parser::new(
3000                 "function %bar() system_v {
3001                                     ss1  = explicit_slot 13
3002                                     ss1  = explicit_slot 1
3003                                 }",
3004             )
3005             .parse_function()
3006             .unwrap_err()
3007             .to_string(),
3008             "3: duplicate entity: ss1"
3009         );
3010     }
3011 
3012     #[test]
3013     fn block_header() {
3014         let (func, _) = Parser::new(
3015             "function %blocks() system_v {
3016                                      block0:
3017                                      block4(v3: i32):
3018                                      }",
3019         )
3020         .parse_function()
3021         .unwrap();
3022         assert_eq!(func.name.to_string(), "%blocks");
3023 
3024         let mut blocks = func.layout.blocks();
3025 
3026         let block0 = blocks.next().unwrap();
3027         assert_eq!(func.dfg.block_params(block0), &[]);
3028 
3029         let block4 = blocks.next().unwrap();
3030         let block4_args = func.dfg.block_params(block4);
3031         assert_eq!(block4_args.len(), 1);
3032         assert_eq!(func.dfg.value_type(block4_args[0]), types::I32);
3033     }
3034 
3035     #[test]
3036     fn duplicate_block() {
3037         let ParseError {
3038             location,
3039             message,
3040             is_warning,
3041         } = Parser::new(
3042             "function %blocks() system_v {
3043                 block0:
3044                 block0:
3045                     return 2",
3046         )
3047         .parse_function()
3048         .unwrap_err();
3049 
3050         assert_eq!(location.line_number, 3);
3051         assert_eq!(message, "duplicate entity: block0");
3052         assert!(!is_warning);
3053     }
3054 
3055     #[test]
3056     fn number_of_blocks() {
3057         let ParseError {
3058             location,
3059             message,
3060             is_warning,
3061         } = Parser::new(
3062             "function %a() {
3063                 block100000:",
3064         )
3065         .parse_function()
3066         .unwrap_err();
3067 
3068         assert_eq!(location.line_number, 2);
3069         assert_eq!(message, "too many blocks");
3070         assert!(!is_warning);
3071     }
3072 
3073     #[test]
3074     fn duplicate_jt() {
3075         let ParseError {
3076             location,
3077             message,
3078             is_warning,
3079         } = Parser::new(
3080             "function %blocks() system_v {
3081                 jt0 = jump_table []
3082                 jt0 = jump_table []",
3083         )
3084         .parse_function()
3085         .unwrap_err();
3086 
3087         assert_eq!(location.line_number, 3);
3088         assert_eq!(message, "duplicate entity: jt0");
3089         assert!(!is_warning);
3090     }
3091 
3092     #[test]
3093     fn duplicate_ss() {
3094         let ParseError {
3095             location,
3096             message,
3097             is_warning,
3098         } = Parser::new(
3099             "function %blocks() system_v {
3100                 ss0 = explicit_slot 8
3101                 ss0 = explicit_slot 8",
3102         )
3103         .parse_function()
3104         .unwrap_err();
3105 
3106         assert_eq!(location.line_number, 3);
3107         assert_eq!(message, "duplicate entity: ss0");
3108         assert!(!is_warning);
3109     }
3110 
3111     #[test]
3112     fn duplicate_gv() {
3113         let ParseError {
3114             location,
3115             message,
3116             is_warning,
3117         } = Parser::new(
3118             "function %blocks() system_v {
3119                 gv0 = vmctx
3120                 gv0 = vmctx",
3121         )
3122         .parse_function()
3123         .unwrap_err();
3124 
3125         assert_eq!(location.line_number, 3);
3126         assert_eq!(message, "duplicate entity: gv0");
3127         assert!(!is_warning);
3128     }
3129 
3130     #[test]
3131     fn duplicate_sig() {
3132         let ParseError {
3133             location,
3134             message,
3135             is_warning,
3136         } = Parser::new(
3137             "function %blocks() system_v {
3138                 sig0 = ()
3139                 sig0 = ()",
3140         )
3141         .parse_function()
3142         .unwrap_err();
3143 
3144         assert_eq!(location.line_number, 3);
3145         assert_eq!(message, "duplicate entity: sig0");
3146         assert!(!is_warning);
3147     }
3148 
3149     #[test]
3150     fn duplicate_fn() {
3151         let ParseError {
3152             location,
3153             message,
3154             is_warning,
3155         } = Parser::new(
3156             "function %blocks() system_v {
3157                 sig0 = ()
3158                 fn0 = %foo sig0
3159                 fn0 = %foo sig0",
3160         )
3161         .parse_function()
3162         .unwrap_err();
3163 
3164         assert_eq!(location.line_number, 4);
3165         assert_eq!(message, "duplicate entity: fn0");
3166         assert!(!is_warning);
3167     }
3168 
3169     #[test]
3170     fn comments() {
3171         let (func, Details { comments, .. }) = Parser::new(
3172             "; before
3173                          function %comment() system_v { ; decl
3174                             ss10  = explicit_slot 13 ; stackslot.
3175                             ; Still stackslot.
3176                             jt10 = jump_table [block0]
3177                             ; Jumptable
3178                          block0: ; Basic block
3179                          trap user42; Instruction
3180                          } ; Trailing.
3181                          ; More trailing.",
3182         )
3183         .parse_function()
3184         .unwrap();
3185         assert_eq!(func.name.to_string(), "%comment");
3186         assert_eq!(comments.len(), 8); // no 'before' comment.
3187         assert_eq!(
3188             comments[0],
3189             Comment {
3190                 entity: AnyEntity::Function,
3191                 text: "; decl",
3192             }
3193         );
3194         assert_eq!(comments[1].entity.to_string(), "ss10");
3195         assert_eq!(comments[2].entity.to_string(), "ss10");
3196         assert_eq!(comments[2].text, "; Still stackslot.");
3197         assert_eq!(comments[3].entity.to_string(), "jt10");
3198         assert_eq!(comments[3].text, "; Jumptable");
3199         assert_eq!(comments[4].entity.to_string(), "block0");
3200         assert_eq!(comments[4].text, "; Basic block");
3201 
3202         assert_eq!(comments[5].entity.to_string(), "inst0");
3203         assert_eq!(comments[5].text, "; Instruction");
3204 
3205         assert_eq!(comments[6].entity, AnyEntity::Function);
3206         assert_eq!(comments[7].entity, AnyEntity::Function);
3207     }
3208 
3209     #[test]
3210     fn test_file() {
3211         let tf = parse_test(
3212             r#"; before
3213                              test cfg option=5
3214                              test verify
3215                              set enable_float=false
3216                              feature "foo"
3217                              feature !"bar"
3218                              ; still preamble
3219                              function %comment() system_v {}"#,
3220             ParseOptions::default(),
3221         )
3222         .unwrap();
3223         assert_eq!(tf.commands.len(), 2);
3224         assert_eq!(tf.commands[0].command, "cfg");
3225         assert_eq!(tf.commands[1].command, "verify");
3226         match tf.isa_spec {
3227             IsaSpec::None(s) => {
3228                 assert!(s.enable_verifier());
3229                 assert!(!s.enable_float());
3230             }
3231             _ => panic!("unexpected ISAs"),
3232         }
3233         assert_eq!(tf.features[0], Feature::With(&"foo"));
3234         assert_eq!(tf.features[1], Feature::Without(&"bar"));
3235         assert_eq!(tf.preamble_comments.len(), 2);
3236         assert_eq!(tf.preamble_comments[0].text, "; before");
3237         assert_eq!(tf.preamble_comments[1].text, "; still preamble");
3238         assert_eq!(tf.functions.len(), 1);
3239         assert_eq!(tf.functions[0].0.name.to_string(), "%comment");
3240     }
3241 
3242     #[test]
3243     fn isa_spec() {
3244         assert!(parse_test(
3245             "target
3246                             function %foo() system_v {}",
3247             ParseOptions::default()
3248         )
3249         .is_err());
3250 
3251         assert!(parse_test(
3252             "target x86_64
3253                             set enable_float=false
3254                             function %foo() system_v {}",
3255             ParseOptions::default()
3256         )
3257         .is_err());
3258 
3259         match parse_test(
3260             "set enable_float=false
3261                           target x86_64
3262                           function %foo() system_v {}",
3263             ParseOptions::default(),
3264         )
3265         .unwrap()
3266         .isa_spec
3267         {
3268             IsaSpec::None(_) => panic!("Expected some ISA"),
3269             IsaSpec::Some(v) => {
3270                 assert_eq!(v.len(), 1);
3271                 assert!(v[0].name() == "x64" || v[0].name() == "x86");
3272             }
3273         }
3274     }
3275 
3276     #[test]
3277     fn user_function_name() {
3278         // Valid characters in the name:
3279         let func = Parser::new(
3280             "function u1:2() system_v {
3281                                            block0:
3282                                              trap int_divz
3283                                            }",
3284         )
3285         .parse_function()
3286         .unwrap()
3287         .0;
3288         assert_eq!(func.name.to_string(), "u1:2");
3289 
3290         // Invalid characters in the name:
3291         let mut parser = Parser::new(
3292             "function u123:abc() system_v {
3293                                            block0:
3294                                              trap stk_ovf
3295                                            }",
3296         );
3297         assert!(parser.parse_function().is_err());
3298 
3299         // Incomplete function names should not be valid:
3300         let mut parser = Parser::new(
3301             "function u() system_v {
3302                                            block0:
3303                                              trap int_ovf
3304                                            }",
3305         );
3306         assert!(parser.parse_function().is_err());
3307 
3308         let mut parser = Parser::new(
3309             "function u0() system_v {
3310                                            block0:
3311                                              trap int_ovf
3312                                            }",
3313         );
3314         assert!(parser.parse_function().is_err());
3315 
3316         let mut parser = Parser::new(
3317             "function u0:() system_v {
3318                                            block0:
3319                                              trap int_ovf
3320                                            }",
3321         );
3322         assert!(parser.parse_function().is_err());
3323     }
3324 
3325     #[test]
3326     fn change_default_calling_convention() {
3327         let code = "function %test() {
3328         block0:
3329             return
3330         }";
3331 
3332         // By default the parser will use the fast calling convention if none is specified.
3333         let mut parser = Parser::new(code);
3334         assert_eq!(
3335             parser.parse_function().unwrap().0.signature.call_conv,
3336             CallConv::Fast
3337         );
3338 
3339         // However, we can specify a different calling convention to be the default.
3340         let mut parser = Parser::new(code).with_default_calling_convention(CallConv::Cold);
3341         assert_eq!(
3342             parser.parse_function().unwrap().0.signature.call_conv,
3343             CallConv::Cold
3344         );
3345     }
3346 
3347     #[test]
3348     fn u8_as_hex() {
3349         fn parse_as_uimm8(text: &str) -> ParseResult<u8> {
3350             Parser::new(text).match_uimm8("unable to parse u8")
3351         }
3352 
3353         assert_eq!(parse_as_uimm8("0").unwrap(), 0);
3354         assert_eq!(parse_as_uimm8("0xff").unwrap(), 255);
3355         assert!(parse_as_uimm8("-1").is_err());
3356         assert!(parse_as_uimm8("0xffa").is_err());
3357     }
3358 
3359     #[test]
3360     fn i16_as_hex() {
3361         fn parse_as_imm16(text: &str) -> ParseResult<i16> {
3362             Parser::new(text).match_imm16("unable to parse i16")
3363         }
3364 
3365         assert_eq!(parse_as_imm16("0x8000").unwrap(), -32768);
3366         assert_eq!(parse_as_imm16("0xffff").unwrap(), -1);
3367         assert_eq!(parse_as_imm16("0").unwrap(), 0);
3368         assert_eq!(parse_as_imm16("0x7fff").unwrap(), 32767);
3369         assert_eq!(
3370             parse_as_imm16("-0x0001").unwrap(),
3371             parse_as_imm16("0xffff").unwrap()
3372         );
3373         assert_eq!(
3374             parse_as_imm16("-0x7fff").unwrap(),
3375             parse_as_imm16("0x8001").unwrap()
3376         );
3377         assert!(parse_as_imm16("0xffffa").is_err());
3378     }
3379 
3380     #[test]
3381     fn i32_as_hex() {
3382         fn parse_as_imm32(text: &str) -> ParseResult<i32> {
3383             Parser::new(text).match_imm32("unable to parse i32")
3384         }
3385 
3386         assert_eq!(parse_as_imm32("0x80000000").unwrap(), -2147483648);
3387         assert_eq!(parse_as_imm32("0xffffffff").unwrap(), -1);
3388         assert_eq!(parse_as_imm32("0").unwrap(), 0);
3389         assert_eq!(parse_as_imm32("0x7fffffff").unwrap(), 2147483647);
3390         assert_eq!(
3391             parse_as_imm32("-0x00000001").unwrap(),
3392             parse_as_imm32("0xffffffff").unwrap()
3393         );
3394         assert_eq!(
3395             parse_as_imm32("-0x7fffffff").unwrap(),
3396             parse_as_imm32("0x80000001").unwrap()
3397         );
3398         assert!(parse_as_imm32("0xffffffffa").is_err());
3399     }
3400 
3401     #[test]
3402     fn i64_as_hex() {
3403         fn parse_as_imm64(text: &str) -> ParseResult<Imm64> {
3404             Parser::new(text).match_imm64("unable to parse Imm64")
3405         }
3406 
3407         assert_eq!(
3408             parse_as_imm64("0x8000000000000000").unwrap(),
3409             Imm64::new(-9223372036854775808)
3410         );
3411         assert_eq!(
3412             parse_as_imm64("0xffffffffffffffff").unwrap(),
3413             Imm64::new(-1)
3414         );
3415         assert_eq!(parse_as_imm64("0").unwrap(), Imm64::new(0));
3416         assert_eq!(
3417             parse_as_imm64("0x7fffffffffffffff").unwrap(),
3418             Imm64::new(9223372036854775807)
3419         );
3420         assert_eq!(
3421             parse_as_imm64("-0x0000000000000001").unwrap(),
3422             parse_as_imm64("0xffffffffffffffff").unwrap()
3423         );
3424         assert_eq!(
3425             parse_as_imm64("-0x7fffffffffffffff").unwrap(),
3426             parse_as_imm64("0x8000000000000001").unwrap()
3427         );
3428         assert!(parse_as_imm64("0xffffffffffffffffa").is_err());
3429     }
3430 
3431     #[test]
3432     fn uimm128() {
3433         macro_rules! parse_as_constant_data {
3434             ($text:expr, $type:expr) => {{
3435                 Parser::new($text).parse_literals_to_constant_data($type)
3436             }};
3437         }
3438         macro_rules! can_parse_as_constant_data {
3439             ($text:expr, $type:expr) => {{
3440                 assert!(parse_as_constant_data!($text, $type).is_ok())
3441             }};
3442         }
3443         macro_rules! cannot_parse_as_constant_data {
3444             ($text:expr, $type:expr) => {{
3445                 assert!(parse_as_constant_data!($text, $type).is_err())
3446             }};
3447         }
3448 
3449         can_parse_as_constant_data!("1 2 3 4", I32X4);
3450         can_parse_as_constant_data!("1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16", I8X16);
3451         can_parse_as_constant_data!("0x1.1 0x2.2 0x3.3 0x4.4", F32X4);
3452         can_parse_as_constant_data!("0x0 0x1 0x2 0x3", I32X4);
3453         can_parse_as_constant_data!("-1 0 -1 0 -1 0 -1 0", I16X8);
3454         can_parse_as_constant_data!("0 -1", I64X2);
3455         can_parse_as_constant_data!("-1 0", I64X2);
3456         can_parse_as_constant_data!("-1 -1 -1 -1 -1", I32X4); // note that parse_literals_to_constant_data will leave extra tokens unconsumed
3457 
3458         cannot_parse_as_constant_data!("1 2 3", I32X4);
3459         cannot_parse_as_constant_data!(" ", F32X4);
3460     }
3461 
3462     #[test]
3463     fn parse_constant_from_booleans() {
3464         let c = Parser::new("-1 0 -1 0")
3465             .parse_literals_to_constant_data(I32X4)
3466             .unwrap();
3467         assert_eq!(
3468             c.into_vec(),
3469             [0xFF, 0xFF, 0xFF, 0xFF, 0, 0, 0, 0, 0xFF, 0xFF, 0xFF, 0xFF, 0, 0, 0, 0]
3470         )
3471     }
3472 
3473     #[test]
3474     fn parse_unbounded_constants() {
3475         // Unlike match_uimm128, match_constant_data can parse byte sequences of any size:
3476         assert_eq!(
3477             Parser::new("[0 1]").match_constant_data().unwrap(),
3478             vec![0, 1].into()
3479         );
3480 
3481         // Only parse byte literals:
3482         assert!(Parser::new("[256]").match_constant_data().is_err());
3483     }
3484 
3485     #[test]
3486     fn parse_run_commands() {
3487         // Helper for creating signatures.
3488         fn sig(ins: &[Type], outs: &[Type]) -> Signature {
3489             let mut sig = Signature::new(CallConv::Fast);
3490             for i in ins {
3491                 sig.params.push(AbiParam::new(*i));
3492             }
3493             for o in outs {
3494                 sig.returns.push(AbiParam::new(*o));
3495             }
3496             sig
3497         }
3498 
3499         // Helper for parsing run commands.
3500         fn parse(text: &str, sig: &Signature) -> ParseResult<RunCommand> {
3501             Parser::new(text).parse_run_command(sig)
3502         }
3503 
3504         // Check that we can parse and display the same set of run commands.
3505         fn assert_roundtrip(text: &str, sig: &Signature) {
3506             assert_eq!(parse(text, sig).unwrap().to_string(), text);
3507         }
3508         assert_roundtrip("run: %fn0() == 42", &sig(&[], &[I32]));
3509         assert_roundtrip(
3510             "run: %fn0(8, 16, 32, 64) == 1",
3511             &sig(&[I8, I16, I32, I64], &[I8]),
3512         );
3513         assert_roundtrip(
3514             "run: %my_func(1) == 0x0f0e0d0c0b0a09080706050403020100",
3515             &sig(&[I32], &[I8X16]),
3516         );
3517 
3518         // Verify that default invocations are created when not specified.
3519         assert_eq!(
3520             parse("run", &sig(&[], &[I32])).unwrap().to_string(),
3521             "run: %default() != 0"
3522         );
3523         assert_eq!(
3524             parse("print", &sig(&[], &[F32X4, I16X8]))
3525                 .unwrap()
3526                 .to_string(),
3527             "print: %default()"
3528         );
3529 
3530         // Demonstrate some unparseable cases.
3531         assert!(parse("print", &sig(&[I32], &[I32])).is_err());
3532         assert!(parse("print:", &sig(&[], &[])).is_err());
3533         assert!(parse("run: ", &sig(&[], &[])).is_err());
3534     }
3535 
3536     #[test]
3537     fn parse_data_values() {
3538         fn parse(text: &str, ty: Type) -> DataValue {
3539             Parser::new(text).parse_data_value(ty).unwrap()
3540         }
3541 
3542         assert_eq!(parse("8", I8).to_string(), "8");
3543         assert_eq!(parse("16", I16).to_string(), "16");
3544         assert_eq!(parse("32", I32).to_string(), "32");
3545         assert_eq!(parse("64", I64).to_string(), "64");
3546         assert_eq!(
3547             parse("0x01234567_01234567_01234567_01234567", I128).to_string(),
3548             "1512366032949150931280199141537564007"
3549         );
3550         assert_eq!(parse("1234567", I128).to_string(), "1234567");
3551         assert_eq!(parse("0x32.32", F32).to_string(), "0x1.919000p5");
3552         assert_eq!(parse("0x64.64", F64).to_string(), "0x1.9190000000000p6");
3553         assert_eq!(
3554             parse("[0 1 2 3]", I32X4).to_string(),
3555             "0x00000003000000020000000100000000"
3556         );
3557     }
3558 
3559     #[test]
3560     fn parse_cold_blocks() {
3561         let code = "function %test() {
3562         block0 cold:
3563             return
3564         block1(v0: i32) cold:
3565             return
3566         block2(v1: i32):
3567             return
3568         }";
3569 
3570         let mut parser = Parser::new(code);
3571         let func = parser.parse_function().unwrap().0;
3572         assert_eq!(func.layout.blocks().count(), 3);
3573         assert!(func.layout.is_cold(Block::from_u32(0)));
3574         assert!(func.layout.is_cold(Block::from_u32(1)));
3575         assert!(!func.layout.is_cold(Block::from_u32(2)));
3576     }
3577 }
3578