-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
parser.rs
3914 lines (3572 loc) · 146 KB
/
parser.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Parser for .clif files.
use crate::error::{Location, ParseError, ParseResult};
use crate::isaspec;
use crate::lexer::{LexError, Lexer, LocatedError, LocatedToken, Token};
use crate::run_command::{Comparison, DataValue, Invocation, RunCommand};
use crate::sourcemap::SourceMap;
use crate::testcommand::TestCommand;
use crate::testfile::{Comment, Details, Feature, TestFile};
use cranelift_codegen::entity::EntityRef;
use cranelift_codegen::ir;
use cranelift_codegen::ir::entities::AnyEntity;
use cranelift_codegen::ir::immediates::{Ieee32, Ieee64, Imm64, Offset32, Uimm32, Uimm64};
use cranelift_codegen::ir::instructions::{InstructionData, InstructionFormat, VariableArgs};
use cranelift_codegen::ir::types::INVALID;
use cranelift_codegen::ir::types::*;
use cranelift_codegen::ir::{
AbiParam, ArgumentExtension, ArgumentLoc, Block, Constant, ConstantData, ExtFuncData,
ExternalName, FuncRef, Function, GlobalValue, GlobalValueData, Heap, HeapData, HeapStyle,
JumpTable, JumpTableData, MemFlags, Opcode, SigRef, Signature, StackSlot, StackSlotData,
StackSlotKind, Table, TableData, Type, Value, ValueLoc,
};
use cranelift_codegen::isa::{self, CallConv, Encoding, RegUnit, TargetIsa};
use cranelift_codegen::packed_option::ReservedValue;
use cranelift_codegen::{settings, timing};
use smallvec::SmallVec;
use std::mem;
use std::str::FromStr;
use std::{u16, u32};
use target_lexicon::Triple;
/// After some quick benchmarks a program should never have more than 100,000 blocks.
const MAX_BLOCKS_IN_A_FUNCTION: u32 = 100_000;
/// Parse the entire `text` into a list of functions.
///
/// Any test commands or target declarations are ignored.
pub fn parse_functions(text: &str) -> ParseResult<Vec<Function>> {
let _tt = timing::parse_text();
parse_test(text, ParseOptions::default())
.map(|file| file.functions.into_iter().map(|(func, _)| func).collect())
}
/// Options for configuring the parsing of filetests.
pub struct ParseOptions<'a> {
/// Compiler passes to run on the parsed functions.
pub passes: Option<&'a [String]>,
/// Target ISA for compiling the parsed functions, e.g. "x86_64 skylake".
pub target: Option<&'a str>,
/// Default calling convention used when none is specified for a parsed function.
pub default_calling_convention: CallConv,
}
impl Default for ParseOptions<'_> {
fn default() -> Self {
Self {
passes: None,
target: None,
default_calling_convention: CallConv::Fast,
}
}
}
/// Parse the entire `text` as a test case file.
///
/// The returned `TestFile` contains direct references to substrings of `text`.
pub fn parse_test<'a>(text: &'a str, options: ParseOptions<'a>) -> ParseResult<TestFile<'a>> {
let _tt = timing::parse_text();
let mut parser = Parser::new(text);
// Gather the preamble comments.
parser.start_gathering_comments();
let isa_spec: isaspec::IsaSpec;
let commands: Vec<TestCommand<'a>>;
// Check for specified passes and target, if present throw out test commands/targets specified
// in file.
match options.passes {
Some(pass_vec) => {
parser.parse_test_commands();
commands = parser.parse_cmdline_passes(pass_vec);
parser.parse_target_specs()?;
isa_spec = parser.parse_cmdline_target(options.target)?;
}
None => {
commands = parser.parse_test_commands();
isa_spec = parser.parse_target_specs()?;
}
};
let features = parser.parse_cranelift_features()?;
// Decide between using the calling convention passed in the options or using the
// host's calling convention--if any tests are to be run on the host we should default to the
// host's calling convention.
parser = if commands.iter().any(|tc| tc.command == "run") {
let host_default_calling_convention = CallConv::triple_default(&Triple::host());
parser.with_default_calling_convention(host_default_calling_convention)
} else {
parser.with_default_calling_convention(options.default_calling_convention)
};
parser.token();
parser.claim_gathered_comments(AnyEntity::Function);
let preamble_comments = parser.take_comments();
let functions = parser.parse_function_list(isa_spec.unique_isa())?;
Ok(TestFile {
commands,
isa_spec,
features,
preamble_comments,
functions,
})
}
/// Parse a CLIF comment `text` as a run command.
///
/// Return:
/// - `Ok(None)` if the comment is not intended to be a `RunCommand` (i.e. does not start with `run`
/// or `print`
/// - `Ok(Some(command))` if the comment is intended as a `RunCommand` and can be parsed to one
/// - `Err` otherwise.
pub fn parse_run_command<'a>(text: &str, signature: &Signature) -> ParseResult<Option<RunCommand>> {
let _tt = timing::parse_text();
// We remove leading spaces and semi-colons for convenience here instead of at the call sites
// since this function will be attempting to parse a RunCommand from a CLIF comment.
let trimmed_text = text.trim_start_matches(|c| c == ' ' || c == ';');
let mut parser = Parser::new(trimmed_text);
match parser.token() {
Some(Token::Identifier("run")) | Some(Token::Identifier("print")) => {
parser.parse_run_command(signature).map(|c| Some(c))
}
Some(_) | None => Ok(None),
}
}
pub struct Parser<'a> {
lex: Lexer<'a>,
lex_error: Option<LexError>,
/// Current lookahead token.
lookahead: Option<Token<'a>>,
/// Location of lookahead.
loc: Location,
/// Are we gathering any comments that we encounter?
gathering_comments: bool,
/// The gathered comments; claim them with `claim_gathered_comments`.
gathered_comments: Vec<&'a str>,
/// Comments collected so far.
comments: Vec<Comment<'a>>,
/// Default calling conventions; used when none is specified.
default_calling_convention: CallConv,
}
/// Context for resolving references when parsing a single function.
struct Context<'a> {
function: Function,
map: SourceMap,
/// Aliases to resolve once value definitions are known.
aliases: Vec<Value>,
/// Reference to the unique_isa for things like parsing target-specific instruction encoding
/// information. This is only `Some` if exactly one set of `isa` directives were found in the
/// prologue (it is valid to have directives for multiple different targets, but in that case
/// we couldn't know which target the provided encodings are intended for)
unique_isa: Option<&'a dyn TargetIsa>,
}
impl<'a> Context<'a> {
fn new(f: Function, unique_isa: Option<&'a dyn TargetIsa>) -> Self {
Self {
function: f,
map: SourceMap::new(),
unique_isa,
aliases: Vec::new(),
}
}
// Get the index of a recipe name if it exists.
fn find_recipe_index(&self, recipe_name: &str) -> Option<u16> {
if let Some(unique_isa) = self.unique_isa {
unique_isa
.encoding_info()
.names
.iter()
.position(|&name| name == recipe_name)
.map(|idx| idx as u16)
} else {
None
}
}
// Allocate a new stack slot.
fn add_ss(&mut self, ss: StackSlot, data: StackSlotData, loc: Location) -> ParseResult<()> {
self.map.def_ss(ss, loc)?;
while self.function.stack_slots.next_key().index() <= ss.index() {
self.function
.create_stack_slot(StackSlotData::new(StackSlotKind::SpillSlot, 0));
}
self.function.stack_slots[ss] = data;
Ok(())
}
// Resolve a reference to a stack slot.
fn check_ss(&self, ss: StackSlot, loc: Location) -> ParseResult<()> {
if !self.map.contains_ss(ss) {
err!(loc, "undefined stack slot {}", ss)
} else {
Ok(())
}
}
// Allocate a global value slot.
fn add_gv(&mut self, gv: GlobalValue, data: GlobalValueData, loc: Location) -> ParseResult<()> {
self.map.def_gv(gv, loc)?;
while self.function.global_values.next_key().index() <= gv.index() {
self.function.create_global_value(GlobalValueData::Symbol {
name: ExternalName::testcase(""),
offset: Imm64::new(0),
colocated: false,
tls: false,
});
}
self.function.global_values[gv] = data;
Ok(())
}
// Resolve a reference to a global value.
fn check_gv(&self, gv: GlobalValue, loc: Location) -> ParseResult<()> {
if !self.map.contains_gv(gv) {
err!(loc, "undefined global value {}", gv)
} else {
Ok(())
}
}
// Allocate a heap slot.
fn add_heap(&mut self, heap: Heap, data: HeapData, loc: Location) -> ParseResult<()> {
self.map.def_heap(heap, loc)?;
while self.function.heaps.next_key().index() <= heap.index() {
self.function.create_heap(HeapData {
base: GlobalValue::reserved_value(),
min_size: Uimm64::new(0),
offset_guard_size: Uimm64::new(0),
style: HeapStyle::Static {
bound: Uimm64::new(0),
},
index_type: INVALID,
});
}
self.function.heaps[heap] = data;
Ok(())
}
// Resolve a reference to a heap.
fn check_heap(&self, heap: Heap, loc: Location) -> ParseResult<()> {
if !self.map.contains_heap(heap) {
err!(loc, "undefined heap {}", heap)
} else {
Ok(())
}
}
// Allocate a table slot.
fn add_table(&mut self, table: Table, data: TableData, loc: Location) -> ParseResult<()> {
while self.function.tables.next_key().index() <= table.index() {
self.function.create_table(TableData {
base_gv: GlobalValue::reserved_value(),
min_size: Uimm64::new(0),
bound_gv: GlobalValue::reserved_value(),
element_size: Uimm64::new(0),
index_type: INVALID,
});
}
self.function.tables[table] = data;
self.map.def_table(table, loc)
}
// Resolve a reference to a table.
fn check_table(&self, table: Table, loc: Location) -> ParseResult<()> {
if !self.map.contains_table(table) {
err!(loc, "undefined table {}", table)
} else {
Ok(())
}
}
// Allocate a new signature.
fn add_sig(
&mut self,
sig: SigRef,
data: Signature,
loc: Location,
defaultcc: CallConv,
) -> ParseResult<()> {
self.map.def_sig(sig, loc)?;
while self.function.dfg.signatures.next_key().index() <= sig.index() {
self.function.import_signature(Signature::new(defaultcc));
}
self.function.dfg.signatures[sig] = data;
Ok(())
}
// Resolve a reference to a signature.
fn check_sig(&self, sig: SigRef, loc: Location) -> ParseResult<()> {
if !self.map.contains_sig(sig) {
err!(loc, "undefined signature {}", sig)
} else {
Ok(())
}
}
// Allocate a new external function.
fn add_fn(&mut self, fn_: FuncRef, data: ExtFuncData, loc: Location) -> ParseResult<()> {
self.map.def_fn(fn_, loc)?;
while self.function.dfg.ext_funcs.next_key().index() <= fn_.index() {
self.function.import_function(ExtFuncData {
name: ExternalName::testcase(""),
signature: SigRef::reserved_value(),
colocated: false,
});
}
self.function.dfg.ext_funcs[fn_] = data;
Ok(())
}
// Resolve a reference to a function.
fn check_fn(&self, fn_: FuncRef, loc: Location) -> ParseResult<()> {
if !self.map.contains_fn(fn_) {
err!(loc, "undefined function {}", fn_)
} else {
Ok(())
}
}
// Allocate a new jump table.
fn add_jt(&mut self, jt: JumpTable, data: JumpTableData, loc: Location) -> ParseResult<()> {
self.map.def_jt(jt, loc)?;
while self.function.jump_tables.next_key().index() <= jt.index() {
self.function.create_jump_table(JumpTableData::new());
}
self.function.jump_tables[jt] = data;
Ok(())
}
// Resolve a reference to a jump table.
fn check_jt(&self, jt: JumpTable, loc: Location) -> ParseResult<()> {
if !self.map.contains_jt(jt) {
err!(loc, "undefined jump table {}", jt)
} else {
Ok(())
}
}
// Allocate a new constant.
fn add_constant(
&mut self,
constant: Constant,
data: ConstantData,
loc: Location,
) -> ParseResult<()> {
self.map.def_constant(constant, loc)?;
self.function.dfg.constants.set(constant, data);
Ok(())
}
// Configure the stack limit of the current function.
fn add_stack_limit(&mut self, limit: GlobalValue, loc: Location) -> ParseResult<()> {
if self.function.stack_limit.is_some() {
return err!(loc, "stack limit defined twice");
}
self.function.stack_limit = Some(limit);
Ok(())
}
// Resolve a reference to a constant.
fn check_constant(&self, c: Constant, loc: Location) -> ParseResult<()> {
if !self.map.contains_constant(c) {
err!(loc, "undefined constant {}", c)
} else {
Ok(())
}
}
// Allocate a new block.
fn add_block(&mut self, block: Block, loc: Location) -> ParseResult<Block> {
self.map.def_block(block, loc)?;
while self.function.dfg.num_blocks() <= block.index() {
self.function.dfg.make_block();
}
self.function.layout.append_block(block);
Ok(block)
}
}
impl<'a> Parser<'a> {
/// Create a new `Parser` which reads `text`. The referenced text must outlive the parser.
pub fn new(text: &'a str) -> Self {
Self {
lex: Lexer::new(text),
lex_error: None,
lookahead: None,
loc: Location { line_number: 0 },
gathering_comments: false,
gathered_comments: Vec::new(),
comments: Vec::new(),
default_calling_convention: CallConv::Fast,
}
}
/// Modify the default calling convention; returns a new parser with the changed calling
/// convention.
pub fn with_default_calling_convention(self, default_calling_convention: CallConv) -> Self {
Self {
default_calling_convention,
..self
}
}
// Consume the current lookahead token and return it.
fn consume(&mut self) -> Token<'a> {
self.lookahead.take().expect("No token to consume")
}
// Consume the whole line following the current lookahead token.
// Return the text of the line tail.
fn consume_line(&mut self) -> &'a str {
let rest = self.lex.rest_of_line();
self.consume();
rest
}
// Get the current lookahead token, after making sure there is one.
fn token(&mut self) -> Option<Token<'a>> {
// clippy says self.lookahead is immutable so this loop is either infinite or never
// running. I don't think this is true - self.lookahead is mutated in the loop body - so
// maybe this is a clippy bug? Either way, disable clippy for this.
#[cfg_attr(feature = "cargo-clippy", allow(clippy::while_immutable_condition))]
while self.lookahead == None {
match self.lex.next() {
Some(Ok(LocatedToken { token, location })) => {
match token {
Token::Comment(text) => {
if self.gathering_comments {
self.gathered_comments.push(text);
}
}
_ => self.lookahead = Some(token),
}
self.loc = location;
}
Some(Err(LocatedError { error, location })) => {
self.lex_error = Some(error);
self.loc = location;
break;
}
None => break,
}
}
self.lookahead
}
// Enable gathering of all comments encountered.
fn start_gathering_comments(&mut self) {
debug_assert!(!self.gathering_comments);
self.gathering_comments = true;
debug_assert!(self.gathered_comments.is_empty());
}
// Claim the comments gathered up to the current position for the
// given entity.
fn claim_gathered_comments<E: Into<AnyEntity>>(&mut self, entity: E) {
debug_assert!(self.gathering_comments);
let entity = entity.into();
self.comments.extend(
self.gathered_comments
.drain(..)
.map(|text| Comment { entity, text }),
);
self.gathering_comments = false;
}
// Get the comments collected so far, clearing out the internal list.
fn take_comments(&mut self) -> Vec<Comment<'a>> {
debug_assert!(!self.gathering_comments);
mem::replace(&mut self.comments, Vec::new())
}
// Match and consume a token without payload.
fn match_token(&mut self, want: Token<'a>, err_msg: &str) -> ParseResult<Token<'a>> {
if self.token() == Some(want) {
Ok(self.consume())
} else {
err!(self.loc, err_msg)
}
}
// If the next token is a `want`, consume it, otherwise do nothing.
fn optional(&mut self, want: Token<'a>) -> bool {
if self.token() == Some(want) {
self.consume();
true
} else {
false
}
}
// Match and consume a specific identifier string.
// Used for pseudo-keywords like "stack_slot" that only appear in certain contexts.
fn match_identifier(&mut self, want: &'static str, err_msg: &str) -> ParseResult<Token<'a>> {
if self.token() == Some(Token::Identifier(want)) {
Ok(self.consume())
} else {
err!(self.loc, err_msg)
}
}
// Match and consume a type.
fn match_type(&mut self, err_msg: &str) -> ParseResult<Type> {
if let Some(Token::Type(t)) = self.token() {
self.consume();
Ok(t)
} else {
err!(self.loc, err_msg)
}
}
// Match and consume a stack slot reference.
fn match_ss(&mut self, err_msg: &str) -> ParseResult<StackSlot> {
if let Some(Token::StackSlot(ss)) = self.token() {
self.consume();
if let Some(ss) = StackSlot::with_number(ss) {
return Ok(ss);
}
}
err!(self.loc, err_msg)
}
// Match and consume a global value reference.
fn match_gv(&mut self, err_msg: &str) -> ParseResult<GlobalValue> {
if let Some(Token::GlobalValue(gv)) = self.token() {
self.consume();
if let Some(gv) = GlobalValue::with_number(gv) {
return Ok(gv);
}
}
err!(self.loc, err_msg)
}
// Match and consume a function reference.
fn match_fn(&mut self, err_msg: &str) -> ParseResult<FuncRef> {
if let Some(Token::FuncRef(fnref)) = self.token() {
self.consume();
if let Some(fnref) = FuncRef::with_number(fnref) {
return Ok(fnref);
}
}
err!(self.loc, err_msg)
}
// Match and consume a signature reference.
fn match_sig(&mut self, err_msg: &str) -> ParseResult<SigRef> {
if let Some(Token::SigRef(sigref)) = self.token() {
self.consume();
if let Some(sigref) = SigRef::with_number(sigref) {
return Ok(sigref);
}
}
err!(self.loc, err_msg)
}
// Match and consume a heap reference.
fn match_heap(&mut self, err_msg: &str) -> ParseResult<Heap> {
if let Some(Token::Heap(heap)) = self.token() {
self.consume();
if let Some(heap) = Heap::with_number(heap) {
return Ok(heap);
}
}
err!(self.loc, err_msg)
}
// Match and consume a table reference.
fn match_table(&mut self, err_msg: &str) -> ParseResult<Table> {
if let Some(Token::Table(table)) = self.token() {
self.consume();
if let Some(table) = Table::with_number(table) {
return Ok(table);
}
}
err!(self.loc, err_msg)
}
// Match and consume a jump table reference.
fn match_jt(&mut self) -> ParseResult<JumpTable> {
if let Some(Token::JumpTable(jt)) = self.token() {
self.consume();
if let Some(jt) = JumpTable::with_number(jt) {
return Ok(jt);
}
}
err!(self.loc, "expected jump table number: jt«n»")
}
// Match and consume a constant reference.
fn match_constant(&mut self) -> ParseResult<Constant> {
if let Some(Token::Constant(c)) = self.token() {
self.consume();
if let Some(c) = Constant::with_number(c) {
return Ok(c);
}
}
err!(self.loc, "expected constant number: const«n»")
}
// Match and consume a stack limit token
fn match_stack_limit(&mut self) -> ParseResult<()> {
if let Some(Token::Identifier("stack_limit")) = self.token() {
self.consume();
return Ok(());
}
err!(self.loc, "expected identifier: stack_limit")
}
// Match and consume a block reference.
fn match_block(&mut self, err_msg: &str) -> ParseResult<Block> {
if let Some(Token::Block(block)) = self.token() {
self.consume();
Ok(block)
} else {
err!(self.loc, err_msg)
}
}
// Match and consume a value reference.
fn match_value(&mut self, err_msg: &str) -> ParseResult<Value> {
if let Some(Token::Value(v)) = self.token() {
self.consume();
Ok(v)
} else {
err!(self.loc, err_msg)
}
}
fn error(&self, message: &str) -> ParseError {
ParseError {
location: self.loc,
message: message.to_string(),
is_warning: false,
}
}
// Match and consume an Imm64 immediate.
fn match_imm64(&mut self, err_msg: &str) -> ParseResult<Imm64> {
if let Some(Token::Integer(text)) = self.token() {
self.consume();
// Lexer just gives us raw text that looks like an integer.
// Parse it as an Imm64 to check for overflow and other issues.
text.parse().map_err(|e| self.error(e))
} else {
err!(self.loc, err_msg)
}
}
// Match and consume a hexadeximal immediate
fn match_hexadecimal_constant(&mut self, err_msg: &str) -> ParseResult<ConstantData> {
if let Some(Token::Integer(text)) = self.token() {
self.consume();
text.parse().map_err(|e| {
self.error(&format!(
"expected hexadecimal immediate, failed to parse: {}",
e
))
})
} else {
err!(self.loc, err_msg)
}
}
// Match and consume a sequence of immediate bytes (uimm8); e.g. [0x42 0x99 0x32]
fn match_constant_data(&mut self) -> ParseResult<ConstantData> {
self.match_token(Token::LBracket, "expected an opening left bracket")?;
let mut data = ConstantData::default();
while !self.optional(Token::RBracket) {
data = data.append(self.match_uimm8("expected a sequence of bytes (uimm8)")?);
}
Ok(data)
}
// Match and consume either a hexadecimal Uimm128 immediate (e.g. 0x000102...) or its literal
// list form (e.g. [0 1 2...]). For convenience, since uimm128 values are stored in the
// `ConstantPool`, this returns `ConstantData`.
fn match_uimm128(&mut self, controlling_type: Type) -> ParseResult<ConstantData> {
let expected_size = controlling_type.bytes() as usize;
let constant_data = if self.optional(Token::LBracket) {
// parse using a list of values, e.g. vconst.i32x4 [0 1 2 3]
let uimm128 = self.parse_literals_to_constant_data(controlling_type)?;
self.match_token(Token::RBracket, "expected a terminating right bracket")?;
uimm128
} else {
// parse using a hexadecimal value, e.g. 0x000102...
let uimm128 =
self.match_hexadecimal_constant("expected an immediate hexadecimal operand")?;
uimm128.expand_to(expected_size)
};
if constant_data.len() == expected_size {
Ok(constant_data)
} else {
Err(self.error(&format!(
"expected parsed constant to have {} bytes",
expected_size
)))
}
}
// Match and consume a Uimm64 immediate.
fn match_uimm64(&mut self, err_msg: &str) -> ParseResult<Uimm64> {
if let Some(Token::Integer(text)) = self.token() {
self.consume();
// Lexer just gives us raw text that looks like an integer.
// Parse it as an Uimm64 to check for overflow and other issues.
text.parse()
.map_err(|_| self.error("expected u64 decimal immediate"))
} else {
err!(self.loc, err_msg)
}
}
// Match and consume a Uimm32 immediate.
fn match_uimm32(&mut self, err_msg: &str) -> ParseResult<Uimm32> {
if let Some(Token::Integer(text)) = self.token() {
self.consume();
// Lexer just gives us raw text that looks like an integer.
// Parse it as an Uimm32 to check for overflow and other issues.
text.parse().map_err(|e| self.error(e))
} else {
err!(self.loc, err_msg)
}
}
// Match and consume a u8 immediate.
// This is used for lane numbers in SIMD vectors.
fn match_uimm8(&mut self, err_msg: &str) -> ParseResult<u8> {
if let Some(Token::Integer(text)) = self.token() {
self.consume();
// Lexer just gives us raw text that looks like an integer.
if text.starts_with("0x") {
// Parse it as a u8 in hexadecimal form.
u8::from_str_radix(&text[2..], 16)
.map_err(|_| self.error("unable to parse u8 as a hexadecimal immediate"))
} else {
// Parse it as a u8 to check for overflow and other issues.
text.parse()
.map_err(|_| self.error("expected u8 decimal immediate"))
}
} else {
err!(self.loc, err_msg)
}
}
// Match and consume an i8 immediate.
fn match_imm8(&mut self, err_msg: &str) -> ParseResult<i8> {
if let Some(Token::Integer(text)) = self.token() {
self.consume();
let negative = text.starts_with('-');
let positive = text.starts_with('+');
let text = if negative || positive {
// Strip sign prefix.
&text[1..]
} else {
text
};
// Parse the text value; the lexer gives us raw text that looks like an integer.
let value = if text.starts_with("0x") {
// Skip underscores.
let text = text.replace("_", "");
// Parse it as a i8 in hexadecimal form.
u8::from_str_radix(&text[2..], 16)
.map_err(|_| self.error("unable to parse i8 as a hexadecimal immediate"))?
} else {
// Parse it as a i8 to check for overflow and other issues.
text.parse()
.map_err(|_| self.error("expected i8 decimal immediate"))?
};
// Apply sign if necessary.
let signed = if negative {
let value = value.wrapping_neg() as i8;
if value > 0 {
return Err(self.error("negative number too small"));
}
value
} else {
value as i8
};
Ok(signed)
} else {
err!(self.loc, err_msg)
}
}
// Match and consume a signed 16-bit immediate.
fn match_imm16(&mut self, err_msg: &str) -> ParseResult<i16> {
if let Some(Token::Integer(text)) = self.token() {
self.consume();
let negative = text.starts_with('-');
let positive = text.starts_with('+');
let text = if negative || positive {
// Strip sign prefix.
&text[1..]
} else {
text
};
// Parse the text value; the lexer gives us raw text that looks like an integer.
let value = if text.starts_with("0x") {
// Skip underscores.
let text = text.replace("_", "");
// Parse it as a i16 in hexadecimal form.
u16::from_str_radix(&text[2..], 16)
.map_err(|_| self.error("unable to parse i16 as a hexadecimal immediate"))?
} else {
// Parse it as a i16 to check for overflow and other issues.
text.parse()
.map_err(|_| self.error("expected i16 decimal immediate"))?
};
// Apply sign if necessary.
let signed = if negative {
let value = value.wrapping_neg() as i16;
if value > 0 {
return Err(self.error("negative number too small"));
}
value
} else {
value as i16
};
Ok(signed)
} else {
err!(self.loc, err_msg)
}
}
// Match and consume an i32 immediate.
// This is used for stack argument byte offsets.
fn match_imm32(&mut self, err_msg: &str) -> ParseResult<i32> {
if let Some(Token::Integer(text)) = self.token() {
self.consume();
let negative = text.starts_with('-');
let positive = text.starts_with('+');
let text = if negative || positive {
// Strip sign prefix.
&text[1..]
} else {
text
};
// Parse the text value; the lexer gives us raw text that looks like an integer.
let value = if text.starts_with("0x") {
// Skip underscores.
let text = text.replace("_", "");
// Parse it as a i32 in hexadecimal form.
u32::from_str_radix(&text[2..], 16)
.map_err(|_| self.error("unable to parse i32 as a hexadecimal immediate"))?
} else {
// Parse it as a i32 to check for overflow and other issues.
text.parse()
.map_err(|_| self.error("expected i32 decimal immediate"))?
};
// Apply sign if necessary.
let signed = if negative {
let value = value.wrapping_neg() as i32;
if value > 0 {
return Err(self.error("negative number too small"));
}
value
} else {
value as i32
};
Ok(signed)
} else {
err!(self.loc, err_msg)
}
}
// Match and consume an optional offset32 immediate.
//
// Note that this will match an empty string as an empty offset, and that if an offset is
// present, it must contain a sign.
fn optional_offset32(&mut self) -> ParseResult<Offset32> {
if let Some(Token::Integer(text)) = self.token() {
if text.starts_with('+') || text.starts_with('-') {
self.consume();
// Lexer just gives us raw text that looks like an integer.
// Parse it as an `Offset32` to check for overflow and other issues.
return text.parse().map_err(|e| self.error(e));
}
}
// An offset32 operand can be absent.
Ok(Offset32::new(0))
}
// Match and consume an optional offset32 immediate.
//
// Note that this will match an empty string as an empty offset, and that if an offset is
// present, it must contain a sign.
fn optional_offset_imm64(&mut self) -> ParseResult<Imm64> {
if let Some(Token::Integer(text)) = self.token() {
if text.starts_with('+') || text.starts_with('-') {
self.consume();
// Lexer just gives us raw text that looks like an integer.
// Parse it as an `Offset32` to check for overflow and other issues.
return text.parse().map_err(|e| self.error(e));
}
}
// If no explicit offset is present, the offset is 0.
Ok(Imm64::new(0))
}
// Match and consume an Ieee32 immediate.
fn match_ieee32(&mut self, err_msg: &str) -> ParseResult<Ieee32> {
if let Some(Token::Float(text)) = self.token() {
self.consume();
// Lexer just gives us raw text that looks like a float.
// Parse it as an Ieee32 to check for the right number of digits and other issues.
text.parse().map_err(|e| self.error(e))
} else {
err!(self.loc, err_msg)
}
}
// Match and consume an Ieee64 immediate.
fn match_ieee64(&mut self, err_msg: &str) -> ParseResult<Ieee64> {
if let Some(Token::Float(text)) = self.token() {
self.consume();
// Lexer just gives us raw text that looks like a float.
// Parse it as an Ieee64 to check for the right number of digits and other issues.
text.parse().map_err(|e| self.error(e))
} else {
err!(self.loc, err_msg)
}
}
// Match and consume a boolean immediate.
fn match_bool(&mut self, err_msg: &str) -> ParseResult<bool> {
if let Some(Token::Identifier(text)) = self.token() {
self.consume();
match text {
"true" => Ok(true),
"false" => Ok(false),
_ => err!(self.loc, err_msg),
}
} else {
err!(self.loc, err_msg)
}
}
// Match and consume an enumerated immediate, like one of the condition codes.
fn match_enum<T: FromStr>(&mut self, err_msg: &str) -> ParseResult<T> {
if let Some(Token::Identifier(text)) = self.token() {
self.consume();
text.parse().map_err(|_| self.error(err_msg))
} else {
err!(self.loc, err_msg)
}
}
// Match and a consume a possibly empty sequence of memory operation flags.
fn optional_memflags(&mut self) -> MemFlags {
let mut flags = MemFlags::new();
while let Some(Token::Identifier(text)) = self.token() {
if flags.set_by_name(text) {
self.consume();
} else {
break;
}
}
flags
}
// Match and consume an identifier.
fn match_any_identifier(&mut self, err_msg: &str) -> ParseResult<&'a str> {
if let Some(Token::Identifier(text)) = self.token() {
self.consume();
Ok(text)