1use crate::common::*;
10use crate::error::Error;
11use crate::lexer::{LexedToken, Token};
12
13use std::collections::VecDeque;
14
15use enumset::EnumSet;
16
17pub const MAX_ADDRESS_DEPTH: u8 = 127;
18pub const MAX_REFERENCE_DEPTH: usize = 127;
19
20pub fn parse(tokens: Vec<LexedToken>) -> Vec<Declaration>
21{
22 let mut declarations = Vec::new();
23
24 if !tokens.is_empty()
25 {
26 let mut tokens = Tokens::from(tokens);
27 while !tokens.is_empty()
28 {
29 match parse_declaration(&mut tokens)
30 {
31 Ok(declaration) =>
32 {
33 declarations.push(declaration);
34 }
35 Err(error) =>
36 {
37 let poison = error.into();
38 let declaration = Declaration::Poison(poison);
39 declarations.push(declaration);
40 skip_until_next_declaration(&mut tokens);
41 }
42 }
43 }
44 }
45
46 declarations
47}
48
49#[derive(Debug)]
50struct Tokens
51{
52 tokens: VecDeque<LexedToken>,
53 last_location: Location,
54 reserved_token: Option<Token>,
55}
56
57impl From<Vec<LexedToken>> for Tokens
58{
59 fn from(tokens: Vec<LexedToken>) -> Tokens
60 {
61 let last_location = match tokens.first()
62 {
63 Some(LexedToken {
64 result: _,
65 location,
66 }) => location.clone(),
67 None => unreachable!(),
68 };
69 Tokens {
70 tokens: VecDeque::from(tokens),
71 last_location,
72 reserved_token: None,
73 }
74 }
75}
76
77impl Tokens
78{
79 fn is_empty(&self) -> bool
80 {
81 self.tokens.is_empty()
82 }
83
84 fn pop_front(&mut self) -> Option<LexedToken>
85 {
86 let popped = self.tokens.pop_front();
87 match &popped
88 {
89 Some(LexedToken {
90 result: _,
91 location,
92 }) =>
93 {
94 self.last_location = location.clone();
95 }
96 None => (),
97 }
98 popped
99 }
100
101 fn start_location_span(&self) -> Option<Location>
102 {
103 match self.tokens.front()
104 {
105 Some(LexedToken {
106 result: _,
107 location,
108 }) => Some(location.clone()),
109 None => None,
110 }
111 }
112
113 fn location_of_span(&self, start: Option<Location>) -> Location
114 {
115 match start
116 {
117 Some(location) => location.combined_with(&self.last_location),
118 None => self.last_location.clone(),
119 }
120 }
121
122 fn with_reservation(&mut self, token: Token) -> TokenReservation
123 {
124 self.reserved_token.get_or_insert(token);
125 TokenReservation(self)
126 }
127}
128
129struct TokenReservation<'a>(&'a mut Tokens);
130
131impl<'a> AsMut<Tokens> for TokenReservation<'a>
132{
133 fn as_mut(&mut self) -> &mut Tokens
134 {
135 self.0
136 }
137}
138
139impl<'a> Drop for TokenReservation<'a>
140{
141 fn drop(&mut self)
142 {
143 self.0.reserved_token = None;
144 }
145}
146
147fn peek(tokens: &mut Tokens) -> Option<&Token>
148{
149 match tokens.tokens.front()
150 {
151 Some(LexedToken {
152 result: Ok(token),
153 location: _,
154 }) => match &tokens.reserved_token
155 {
156 Some(x) if x == token => None,
157 Some(_) => Some(token),
158 None => Some(token),
159 },
160 Some(LexedToken {
161 result: Err(_),
162 location: _,
163 }) => None,
164 None => None,
165 }
166}
167
168fn consume(
169 expected_token: Token,
170 expectation: &str,
171 tokens: &mut Tokens,
172) -> Result<(), Error>
173{
174 match tokens.pop_front()
175 {
176 Some(LexedToken {
177 result: Ok(token),
178 location: _,
179 }) if token == expected_token => Ok(()),
180 Some(LexedToken {
181 result: Ok(_),
182 location,
183 }) => Err(Error::UnexpectedToken {
184 expectation: expectation.to_string(),
185 location,
186 }),
187 Some(LexedToken {
188 result: Err(error),
189 location,
190 }) => Err(Error::Lexical {
191 error,
192 expectation: expectation.to_string(),
193 location,
194 }),
195 None => Err(Error::UnexpectedEndOfFile {
196 expectation: expectation.to_string(),
197 last_location: tokens.last_location.clone(),
198 }),
199 }
200}
201
202fn extract_identifier(
203 expectation: &str,
204 tokens: &mut Tokens,
205) -> Result<Identifier, Error>
206{
207 match tokens.pop_front()
208 {
209 Some(LexedToken {
210 result: Ok(Token::Identifier(name)),
211 location,
212 }) => Ok(Identifier {
213 name,
214 location,
215 resolution_id: 0,
216 is_authoritative: false,
217 }),
218 Some(LexedToken {
219 result: Ok(_),
220 location,
221 }) => Err(Error::UnexpectedToken {
222 expectation: expectation.to_string(),
223 location,
224 }),
225 Some(LexedToken {
226 result: Err(error),
227 location,
228 }) => Err(Error::Lexical {
229 error,
230 expectation: expectation.to_string(),
231 location,
232 }),
233 None => Err(Error::UnexpectedEndOfFile {
234 expectation: expectation.to_string(),
235 last_location: tokens.last_location.clone(),
236 }),
237 }
238}
239
240fn extract(
241 expectation: &str,
242 tokens: &mut Tokens,
243) -> Result<(Token, Location), Error>
244{
245 match tokens.pop_front()
246 {
247 Some(LexedToken {
248 result: Ok(token),
249 location,
250 }) => Ok((token, location)),
251 Some(LexedToken {
252 result: Err(error),
253 location,
254 }) => Err(Error::Lexical {
255 error,
256 expectation: expectation.to_string(),
257 location,
258 }),
259 None => Err(Error::UnexpectedEndOfFile {
260 expectation: expectation.to_string(),
261 last_location: tokens.last_location.clone(),
262 }),
263 }
264}
265
266fn can_start_declaration(token: &Token) -> bool
267{
268 match token
269 {
270 Token::Import => true,
271 Token::Pub => true,
272 Token::Extern => true,
273 Token::Const => true,
274 Token::Fn => true,
275 Token::Struct => true,
276 Token::Word8 => true,
277 Token::Word16 => true,
278 Token::Word32 => true,
279 Token::Word64 => true,
280 Token::Word128 => true,
281 Token::DebugDollar => true,
282 _ => false,
283 }
284}
285
286fn skip_until_next_declaration(tokens: &mut Tokens)
287{
288 loop
289 {
290 match tokens.tokens.front()
291 {
292 Some(LexedToken {
293 result: Ok(token),
294 location: _,
295 }) =>
296 {
297 if can_start_declaration(token)
298 {
299 return;
300 }
301 else
302 {
303 tokens.pop_front();
304 }
305 }
306 Some(LexedToken {
307 result: Err(_),
308 location: _,
309 }) =>
310 {
311 tokens.pop_front();
312 }
313 None => return,
314 }
315 }
316}
317
318fn parse_declaration(tokens: &mut Tokens) -> Result<Declaration, Error>
319{
320 let mut flags = EnumSet::new();
321 let mut location_of_declaration = None;
322 if let Some(Token::Pub) = peek(tokens)
323 {
324 tokens.pop_front();
325 location_of_declaration = Some(tokens.last_location.clone());
326 flags.insert(DeclarationFlag::Public);
327 }
328 if let Some(Token::Extern) = peek(tokens)
329 {
330 tokens.pop_front();
331 location_of_declaration = Some(tokens.last_location.clone());
332 flags.insert(DeclarationFlag::External);
333 }
334
335 let (token, location) = extract("expected top-level declaration", tokens)?;
336 let location_of_declaration =
337 location_of_declaration.unwrap_or_else(|| location.clone());
338 match token
339 {
340 Token::Import => parse_import(location_of_declaration, tokens),
341 Token::Const =>
342 {
343 parse_constant_declaration(flags, location_of_declaration, tokens)
344 }
345 Token::Fn =>
346 {
347 parse_function_declaration(flags, location_of_declaration, tokens)
348 }
349 Token::Struct =>
350 {
351 parse_struct_declaration(flags, location_of_declaration, tokens)
352 }
353 Token::Word8 =>
354 {
355 parse_word_declaration(1, flags, location_of_declaration, tokens)
356 }
357 Token::Word16 =>
358 {
359 parse_word_declaration(2, flags, location_of_declaration, tokens)
360 }
361 Token::Word32 =>
362 {
363 parse_word_declaration(4, flags, location_of_declaration, tokens)
364 }
365 Token::Word64 =>
366 {
367 parse_word_declaration(8, flags, location_of_declaration, tokens)
368 }
369 Token::Word128 =>
370 {
371 parse_word_declaration(16, flags, location_of_declaration, tokens)
372 }
373 _ => Err(Error::UnexpectedToken {
374 location,
375 expectation: "expected top-level declaration".to_string(),
376 }),
377 }
378}
379
380fn parse_import(
381 location_of_import: Location,
382 tokens: &mut Tokens,
383) -> Result<Declaration, Error>
384{
385 let filename = parse_quoted_path(tokens)?;
386 consume(Token::Semicolon, "expected semicolon", tokens)?;
387 let declaration = Declaration::Import {
388 filename,
389 location: location_of_import,
390 };
391 Ok(declaration)
392}
393
394fn parse_quoted_path(tokens: &mut Tokens) -> Result<String, Error>
395{
396 let (token, location) = extract("expected path", tokens)?;
397 match token
398 {
399 Token::StringLiteral { bytes } => match String::from_utf8(bytes)
400 {
401 Ok(filename) => Ok(filename),
402 Err(_error) => Err(Error::UnexpectedToken {
403 location,
404 expectation: "expected UTF-8 encoded path".to_string(),
405 }),
406 },
407 _ => Err(Error::UnexpectedToken {
408 location,
409 expectation: "expected path".to_string(),
410 }),
411 }
412}
413
414fn parse_constant_declaration(
415 flags: EnumSet<DeclarationFlag>,
416 location_of_declaration: Location,
417 tokens: &mut Tokens,
418) -> Result<Declaration, Error>
419{
420 let name = extract_identifier("expected constant name", tokens)?;
421 let location_of_declaration =
422 location_of_declaration.combined_with(&tokens.last_location);
423
424 let start = tokens.start_location_span();
425 let value_type = if let Some(Token::Colon) = peek(tokens)
426 {
427 tokens.pop_front();
428 let value_type = parse_wellformed_type(tokens)?;
429 Ok(value_type)
430 }
431 else
432 {
433 Err(Error::MissingConstantType {
434 location: name.location.clone(),
435 })
436 };
437 let value_type = value_type.map_err(|e| e.into());
438 let location_of_type = tokens.location_of_span(start);
439
440 consume(Token::Assignment, "expected assignment", tokens)?;
441 let expression = parse_expression(tokens)?;
442 consume(Token::Semicolon, "expected semicolon", tokens)?;
443
444 let declaration = Declaration::Constant {
445 name,
446 value: expression,
447 value_type,
448 flags,
449 depth: None,
450 location_of_declaration,
451 location_of_type,
452 };
453 Ok(declaration)
454}
455
456fn parse_word_declaration(
457 size_in_bytes: usize,
458 flags: EnumSet<DeclarationFlag>,
459 location_of_declaration: Location,
460 tokens: &mut Tokens,
461) -> Result<Declaration, Error>
462{
463 let name = extract_identifier("expected structure name", tokens)?;
464 let structural_type = Ok(ValueType::Word {
465 identifier: name.clone(),
466 size_in_bytes,
467 });
468 let members = parse_struct_members(tokens)?;
469 Ok(Declaration::Structure {
470 name,
471 members,
472 structural_type,
473 flags,
474 depth: None,
475 location_of_declaration,
476 })
477}
478
479fn parse_struct_declaration(
480 flags: EnumSet<DeclarationFlag>,
481 location_of_declaration: Location,
482 tokens: &mut Tokens,
483) -> Result<Declaration, Error>
484{
485 let name = extract_identifier("expected structure name", tokens)?;
486 let structural_type = Ok(ValueType::Struct {
487 identifier: name.clone(),
488 });
489 let members = parse_struct_members(tokens)?;
490 Ok(Declaration::Structure {
491 name,
492 members,
493 structural_type,
494 flags,
495 depth: None,
496 location_of_declaration,
497 })
498}
499
500fn parse_struct_members(tokens: &mut Tokens) -> Result<Vec<Member>, Error>
501{
502 consume(Token::BraceLeft, "expected left brace", tokens)?;
503
504 let mut members = Vec::new();
505 loop
506 {
507 if let Some(Token::BraceRight) = peek(tokens)
508 {
509 break;
510 }
511
512 match parse_member(tokens)
513 {
514 Ok(member) =>
515 {
516 members.push(member);
517
518 if let Some(Token::Comma) = peek(tokens)
519 {
520 tokens.pop_front();
521 }
522 else
523 {
524 break;
527 }
528 }
529 Err(error) =>
530 {
531 return Err(error);
532 }
533 }
534 }
535
536 consume(Token::BraceRight, "expected right brace", tokens)?;
537 Ok(members)
538}
539
540fn parse_function_declaration(
541 flags: EnumSet<DeclarationFlag>,
542 location_of_declaration: Location,
543 tokens: &mut Tokens,
544) -> Result<Declaration, Error>
545{
546 let name = extract_identifier("expected function name", tokens)?;
547 consume(Token::ParenLeft, "expected left parenthesis", tokens)?;
548 let signature = parse_rest_of_function_signature(tokens)?;
549 let (parameters, return_type, location_of_return_type) = signature;
550 let location_of_return_type =
551 location_of_return_type.unwrap_or_else(|| tokens.last_location.clone());
552 let return_type = Ok(return_type);
553
554 if peek(tokens) == Some(&Token::Semicolon)
555 {
556 tokens.pop_front();
557 Ok(Declaration::FunctionHead {
558 name,
559 parameters,
560 return_type,
561 flags,
562 location_of_declaration,
563 location_of_return_type,
564 })
565 }
566 else
567 {
568 let body = match parse_function_body(&name.name, tokens)
569 {
570 Ok(body) => Ok(body),
571 Err(poison) =>
572 {
573 skip_until_next_declaration(tokens);
574 Err(poison)
575 }
576 };
577 Ok(Declaration::Function {
578 name,
579 parameters,
580 body,
581 return_type,
582 flags,
583 location_of_declaration,
584 location_of_return_type,
585 })
586 }
587}
588
589fn parse_rest_of_function_signature(
590 tokens: &mut Tokens,
591) -> Result<(Vec<Parameter>, ValueType, Option<Location>), Error>
592{
593 let mut parameters = Vec::new();
594 loop
595 {
596 if let Some(Token::ParenRight) = peek(tokens)
597 {
598 break;
599 }
600
601 let parameter = parse_parameter(tokens)?;
602 parameters.push(parameter);
603
604 if let Some(Token::Comma) = peek(tokens)
605 {
606 tokens.pop_front();
607 }
608 else
609 {
610 break;
611 }
612 }
613
614 consume(Token::ParenRight, "expected right parenthesis", tokens)?;
615
616 if let Some(Token::Arrow) = peek(tokens)
617 {
618 tokens.pop_front();
619
620 let start = tokens.start_location_span();
621 let return_type = parse_wellformed_type(tokens)?;
622 let location = tokens.location_of_span(start);
623 Ok((parameters, return_type, Some(location)))
624 }
625 else
626 {
627 Ok((parameters, ValueType::Void, None))
628 }
629}
630
631fn parse_member(tokens: &mut Tokens) -> Result<Member, Error>
632{
633 let name = extract_identifier("expected member name", tokens)?;
634
635 let start = tokens.start_location_span();
636 let value_type = if let Some(Token::Colon) = peek(tokens)
637 {
638 tokens.pop_front();
639 let value_type = parse_wellformed_type(tokens)?;
640 Ok(value_type)
641 }
642 else
643 {
644 Err(Error::MissingMemberType {
645 location: name.location.clone(),
646 })
647 };
648 let value_type = value_type.map_err(|e| e.into());
649 let location_of_type = tokens.location_of_span(start);
650
651 Ok(Member {
652 name: Ok(name),
653 value_type,
654 location_of_type,
655 })
656}
657
658fn parse_parameter(tokens: &mut Tokens) -> Result<Parameter, Error>
659{
660 let name = extract_identifier("expected parameter name", tokens)?;
661
662 let start = tokens.start_location_span();
663 let value_type = if let Some(Token::Colon) = peek(tokens)
664 {
665 tokens.pop_front();
666 let value_type = parse_wellformed_type(tokens)?;
667 Ok(value_type)
668 }
669 else
670 {
671 Err(Error::MissingParameterType {
672 location: name.location.clone(),
673 })
674 };
675 let value_type = value_type.map_err(|e| e.into());
676 let location_of_type = tokens.location_of_span(start);
677
678 Ok(Parameter {
679 name: Ok(name),
680 value_type,
681 location_of_type,
682 })
683}
684
685fn parse_wellformed_type(tokens: &mut Tokens) -> Result<ValueType, Error>
686{
687 let start = tokens.start_location_span();
688 let value_type = parse_type(tokens)?;
689 if value_type.is_wellformed()
690 {
691 Ok(value_type)
692 }
693 else
694 {
695 let location = tokens.location_of_span(start);
696 Err(Error::IllegalType {
697 value_type,
698 location,
699 })
700 }
701}
702
703fn parse_type(tokens: &mut Tokens) -> Result<ValueType, Error>
704{
705 let (token, location) = extract("expected type keyword", tokens)?;
706 match token
707 {
708 Token::Type(value_type) => Ok(value_type),
709 Token::Identifier(name) =>
710 {
711 let identifier = Identifier {
712 name,
713 location,
714 resolution_id: 0,
715 is_authoritative: false,
716 };
717 Ok(ValueType::UnresolvedStructOrWord {
718 identifier: Some(identifier),
719 })
720 }
721 Token::Ampersand =>
722 {
723 let deref_type = parse_type(tokens)?;
724 Ok(ValueType::Pointer {
725 deref_type: Box::new(deref_type),
726 })
727 }
728 Token::ParenLeft =>
729 {
730 let deref_type = parse_type(tokens)?;
731 consume(Token::ParenRight, "expected right parenthesis", tokens)?;
732 Ok(ValueType::View {
733 deref_type: Box::new(deref_type),
734 })
735 }
736 Token::BracketLeft => match peek(tokens)
737 {
738 Some(Token::Colon) =>
739 {
740 tokens.pop_front();
741 consume(Token::BracketRight, "expected right bracket", tokens)?;
742 let element_type = parse_type(tokens)?;
743 Ok(ValueType::Slice {
744 element_type: Box::new(element_type),
745 })
746 }
747 Some(Token::Dot) =>
748 {
749 tokens.pop_front();
750 consume(Token::Dot, "expected dot", tokens)?;
751 consume(Token::Dot, "expected dot", tokens)?;
752 consume(Token::BracketRight, "expected right bracket", tokens)?;
753 let element_type = parse_type(tokens)?;
754 Ok(ValueType::EndlessArray {
755 element_type: Box::new(element_type),
756 })
757 }
758 Some(Token::BracketRight) | None =>
759 {
760 consume(Token::BracketRight, "expected right bracket", tokens)?;
761 let element_type = parse_type(tokens)?;
762 Ok(ValueType::Arraylike {
763 element_type: Box::new(element_type),
764 })
765 }
766 Some(Token::NakedInteger(x)) if *x > 0 =>
767 {
768 let length = *x as usize;
769 tokens.pop_front();
770 consume(Token::BracketRight, "expected right bracket", tokens)?;
771 let element_type = parse_type(tokens)?;
772 Ok(ValueType::Array {
773 element_type: Box::new(element_type),
774 length,
775 })
776 }
777 Some(Token::Usize(x)) if *x > 0 =>
778 {
779 let length = *x;
780 tokens.pop_front();
781 consume(Token::BracketRight, "expected right bracket", tokens)?;
782 let element_type = parse_type(tokens)?;
783 Ok(ValueType::Array {
784 element_type: Box::new(element_type),
785 length,
786 })
787 }
788 Some(_) => Err(Error::UnexpectedToken {
789 expectation: "expected right bracket".to_string(),
790 location,
791 }),
792 },
793 _ => Err(Error::UnexpectedToken {
794 expectation: "expected type keyword".to_string(),
795 location,
796 }),
797 }
798}
799
800fn parse_function_body(
801 function_name: &str,
802 tokens: &mut Tokens,
803) -> Poisonable<FunctionBody>
804{
805 consume(Token::BraceLeft, "expected function body", tokens)?;
806
807 let mut statements = Vec::new();
808
809 loop
810 {
811 if let Some(Token::BraceRight) = peek(tokens)
812 {
813 tokens.pop_front();
814
815 let body = FunctionBody {
816 statements,
817 return_value: None,
818 return_value_identifier: Identifier {
819 name: function_name.to_string(),
820 location: tokens.last_location.clone(),
821 resolution_id: 0,
822 is_authoritative: false,
823 },
824 };
825 return Ok(body);
826 }
827
828 let statement = parse_statement(tokens)?;
829
830 let is_return = match &statement
831 {
832 Statement::Label { label, .. } => label.name == "return",
833 _ => false,
834 };
835 if is_return
836 {
837 if let Some(Token::BraceRight) = peek(tokens)
838 {
839 tokens.pop_front();
840 let return_value_location = tokens.last_location.clone();
841 let return_statement_location = statement.location().clone();
842 statements.push(statement);
843 let error = Error::MissingReturnValueAfterStatement {
844 location: return_value_location.clone(),
845 after: return_statement_location,
846 };
847 let return_value = Expression::Poison(Poison::Error(error));
848 let body = FunctionBody {
849 statements,
850 return_value: Some(return_value),
851 return_value_identifier: Identifier {
852 name: function_name.to_string(),
853 location: return_value_location,
854 resolution_id: 0,
855 is_authoritative: false,
856 },
857 };
858 return Ok(body);
859 }
860 else
861 {
862 statements.push(statement);
863
864 let return_value = parse_expression(tokens)?;
865 if let Some(Token::Semicolon) = peek(tokens)
866 {
867 tokens.pop_front();
868 let error = Error::UnexpectedSemicolonAfterReturnValue {
869 location: tokens.last_location.clone(),
870 after: return_value.location().clone(),
871 };
872 return Err(error.into());
873 }
874 consume(
875 Token::BraceRight,
876 "expected closing brace after return value",
877 tokens,
878 )?;
879 let return_value_location = return_value.location().clone();
880 let body = FunctionBody {
881 statements,
882 return_value: Some(return_value),
883 return_value_identifier: Identifier {
884 name: function_name.to_string(),
885 location: return_value_location,
886 resolution_id: 0,
887 is_authoritative: false,
888 },
889 };
890 return Ok(body);
891 };
892 }
893 else
894 {
895 statements.push(statement);
896 }
897 }
898}
899
900fn parse_rest_of_block(
901 mut block: Block,
902 tokens: &mut Tokens,
903) -> Result<Block, Error>
904{
905 loop
906 {
907 if let Some(Token::BraceRight) = peek(tokens)
908 {
909 tokens.pop_front();
910 block.location =
911 block.location.combined_with(&tokens.last_location);
912 return Ok(block);
913 }
914
915 let statement = parse_statement(tokens)?;
916 block.statements.push(statement);
917 }
918}
919
920fn parse_statement(tokens: &mut Tokens) -> Result<Statement, Error>
921{
922 let (token, location) = extract("expected statement", tokens)?;
923
924 match token
925 {
926 Token::BraceLeft =>
927 {
928 let block = Block {
929 statements: Vec::new(),
930 location,
931 };
932 let block = parse_rest_of_block(block, tokens)?;
933 let statement = Statement::Block(block);
934 Ok(statement)
935 }
936 Token::If =>
937 {
938 let condition = {
939 let mut tokens = tokens.with_reservation(Token::BraceLeft);
943 parse_comparison(tokens.as_mut())?
944 };
945 let then_stmt = parse_statement(tokens)?;
946 let then_branch = Box::new(then_stmt);
947
948 if let Some(Token::Else) = peek(tokens)
949 {
950 tokens.pop_front();
951 let location_of_else = tokens.last_location.clone();
952
953 let else_stmt = parse_statement(tokens)?;
954 let else_branch = Some(Else {
955 branch: Box::new(else_stmt),
956 location_of_else,
957 });
958 let statement = Statement::If {
959 condition,
960 then_branch,
961 else_branch,
962 location,
963 };
964 Ok(statement)
965 }
966 else
967 {
968 let statement = Statement::If {
969 condition,
970 then_branch,
971 else_branch: None,
972 location,
973 };
974 Ok(statement)
975 }
976 }
977 Token::Loop =>
978 {
979 let statement = Statement::Loop { location };
980 consume(Token::Semicolon, "expected semicolon", tokens)?;
981 Ok(statement)
982 }
983 Token::Goto =>
984 {
985 let label = extract_identifier("expected label", tokens)?;
986 let statement = Statement::Goto { label, location };
987 consume(Token::Semicolon, "expected semicolon", tokens)?;
988 Ok(statement)
989 }
990 Token::Var =>
991 {
992 let name = extract_identifier("expected variable name", tokens)?;
993
994 let value_type = if let Some(Token::Colon) = peek(tokens)
995 {
996 tokens.pop_front();
997 let value_type = parse_wellformed_type(tokens)?;
998 Some(Ok(value_type))
999 }
1000 else
1001 {
1002 None
1003 };
1004
1005 let value = if let Some(Token::Assignment) = peek(tokens)
1006 {
1007 tokens.pop_front();
1008 let expression = parse_expression(tokens)?;
1009 Some(expression)
1010 }
1011 else
1012 {
1013 None
1014 };
1015
1016 let statement = Statement::Declaration {
1017 name,
1018 value,
1019 value_type,
1020 location,
1021 };
1022 consume(Token::Semicolon, "expected semicolon", tokens)?;
1023 Ok(statement)
1024 }
1025 Token::Identifier(x) =>
1026 {
1027 if let Some(Token::Colon) = peek(tokens)
1028 {
1029 tokens.pop_front();
1030 let location = location.combined_with(&tokens.last_location);
1031 let statement = Statement::Label {
1032 label: Identifier {
1033 name: x,
1034 location: location.clone(),
1035 resolution_id: 0,
1036 is_authoritative: false,
1037 },
1038 location,
1039 };
1040 return Ok(statement);
1041 }
1042 else if let Some(Token::ParenLeft) = peek(tokens)
1043 {
1044 let identifier = Identifier {
1045 name: x,
1046 location,
1047 resolution_id: 0,
1048 is_authoritative: false,
1049 };
1050 let arguments = parse_arguments(tokens)?;
1051 let statement = Statement::MethodCall {
1052 name: identifier,
1053 arguments,
1054 };
1055 consume(Token::Semicolon, "expected semicolon", tokens)?;
1056 return Ok(statement);
1057 }
1058
1059 let reference =
1060 parse_rest_of_reference(x, location.clone(), tokens)?;
1061
1062 if let Some(Token::Semicolon) = peek(tokens)
1063 {
1064 tokens.pop_front();
1065 return Err(Error::UnexpectedSemicolonAfterIdentifier {
1066 location: tokens.last_location.clone(),
1067 after: reference.location,
1068 });
1069 }
1070 consume(Token::Assignment, "expected assignment", tokens)?;
1071 let expression = parse_expression(tokens)?;
1072
1073 let statement = Statement::Assignment {
1074 reference,
1075 value: expression,
1076 location,
1077 };
1078 consume(Token::Semicolon, "expected semicolon", tokens)?;
1079 Ok(statement)
1080 }
1081 Token::Ampersand =>
1082 {
1083 let assignment_location = location.clone();
1084 let reference = parse_addressed_reference(location, tokens)?;
1085
1086 if let Some(Token::Semicolon) = peek(tokens)
1087 {
1088 tokens.pop_front();
1089 return Err(Error::UnexpectedSemicolonAfterIdentifier {
1090 location: tokens.last_location.clone(),
1091 after: reference.location,
1092 });
1093 }
1094 consume(Token::Assignment, "expected assignment", tokens)?;
1095 let expression = parse_expression(tokens)?;
1096
1097 let statement = Statement::Assignment {
1098 reference,
1099 value: expression,
1100 location: assignment_location,
1101 };
1102 consume(Token::Semicolon, "expected semicolon", tokens)?;
1103 Ok(statement)
1104 }
1105 _ => Err(Error::UnexpectedToken {
1106 location,
1107 expectation: "expected statement".to_string(),
1108 }),
1109 }
1110}
1111
1112fn parse_comparison(tokens: &mut Tokens) -> Result<Comparison, Error>
1113{
1114 let left = parse_expression(tokens)?;
1115
1116 let (token, location_of_op) =
1117 extract("expected comparison operator", tokens)?;
1118 let op = match token
1119 {
1120 Token::Equals => ComparisonOp::Equals,
1121 Token::DoesNotEqual => ComparisonOp::DoesNotEqual,
1122 Token::AngleLeft => ComparisonOp::IsLess,
1123 Token::AngleRight => ComparisonOp::IsGreater,
1124 Token::IsGE => ComparisonOp::IsGE,
1125 Token::IsLE => ComparisonOp::IsLE,
1126 _ =>
1127 {
1128 return Err(Error::UnexpectedToken {
1129 location: location_of_op,
1130 expectation: "expected comparison operator".to_string(),
1131 });
1132 }
1133 };
1134
1135 let right = parse_expression(tokens)?;
1136 let location = left.location().clone().combined_with(right.location());
1137
1138 Ok(Comparison {
1139 op,
1140 left,
1141 right,
1142 location,
1143 location_of_op,
1144 })
1145}
1146
1147fn parse_expression(tokens: &mut Tokens) -> Result<Expression, Error>
1148{
1149 parse_addition(tokens)
1150}
1151
1152fn parse_addition(tokens: &mut Tokens) -> Result<Expression, Error>
1153{
1154 let mut expression = parse_multiplication(tokens)?;
1155 let mut location = expression.location().clone();
1156
1157 loop
1158 {
1159 let op = match peek(tokens)
1160 {
1161 Some(Token::Ampersand) | Some(Token::Pipe) | Some(Token::Caret) =>
1162 {
1163 return parse_rest_of_bitwise_expression(expression, tokens);
1164 }
1165 Some(Token::ShiftLeft) | Some(Token::ShiftRight) =>
1166 {
1167 return parse_rest_of_bitshift_operation(expression, tokens);
1168 }
1169 Some(Token::Plus) => BinaryOp::Add,
1170 Some(Token::Minus) => BinaryOp::Subtract,
1171 _ =>
1172 {
1173 return Ok(expression);
1174 }
1175 };
1176 tokens.pop_front();
1177 let location_of_op = tokens.last_location.clone();
1178
1179 let right = parse_multiplication(tokens)?;
1180 location = location.combined_with(right.location());
1181
1182 expression = Expression::Binary {
1183 op,
1184 left: Box::new(expression),
1185 right: Box::new(right),
1186 location: location.clone(),
1187 location_of_op,
1188 };
1189 }
1190}
1191
1192fn parse_rest_of_bitwise_expression(
1193 mut expression: Expression,
1194 tokens: &mut Tokens,
1195) -> Result<Expression, Error>
1196{
1197 let (op_token, location_of_op) =
1198 extract("expected bitwise operator", tokens)?;
1199 let op = match op_token
1200 {
1201 Token::Ampersand => BinaryOp::BitwiseAnd,
1202 Token::Pipe => BinaryOp::BitwiseOr,
1203 Token::Caret => BinaryOp::BitwiseXor,
1204 _ =>
1205 {
1206 return Err(Error::UnexpectedToken {
1207 location: location_of_op,
1208 expectation: "expected bitwise operator".to_string(),
1209 });
1210 }
1211 };
1212
1213 match expression
1215 {
1216 Expression::Binary { .. } =>
1217 {
1218 return Err(Error::UnexpectedToken {
1219 location: location_of_op,
1220 expectation: "bitwise operator is not allowed here".to_string(),
1221 });
1222 }
1223 _ => (),
1224 }
1225
1226 let mut location = expression.location().clone();
1227 let mut location_of_op = location_of_op;
1228 loop
1229 {
1230 let right = parse_unary_expression(tokens)?;
1231 location = location.combined_with(right.location());
1232
1233 expression = Expression::Binary {
1234 op,
1235 left: Box::new(expression),
1236 right: Box::new(right),
1237 location: location.clone(),
1238 location_of_op,
1239 };
1240
1241 match peek(tokens)
1242 {
1243 Some(token) if token == &op_token =>
1244 {
1245 tokens.pop_front();
1246 location_of_op = tokens.last_location.clone();
1247 }
1248 _ =>
1249 {
1250 return Ok(expression);
1251 }
1252 }
1253 }
1254}
1255
1256fn parse_rest_of_bitshift_operation(
1257 mut expression: Expression,
1258 tokens: &mut Tokens,
1259) -> Result<Expression, Error>
1260{
1261 let (op_token, location_of_op) =
1262 extract("expected bitshift operator", tokens)?;
1263 let op = match op_token
1264 {
1265 Token::ShiftLeft => BinaryOp::ShiftLeft,
1266 Token::ShiftRight => BinaryOp::ShiftRight,
1267 _ =>
1268 {
1269 return Err(Error::UnexpectedToken {
1270 location: location_of_op,
1271 expectation: "expected bitshift operator".to_string(),
1272 });
1273 }
1274 };
1275
1276 match expression
1278 {
1279 Expression::Binary { .. } =>
1280 {
1281 return Err(Error::UnexpectedToken {
1282 location: location_of_op,
1283 expectation: "bitshift operator is not allowed here"
1284 .to_string(),
1285 });
1286 }
1287 _ => (),
1288 }
1289
1290 let right = parse_unary_expression(tokens)?;
1291 let location = expression
1292 .location()
1293 .clone()
1294 .combined_with(right.location());
1295
1296 expression = Expression::Binary {
1297 op,
1298 left: Box::new(expression),
1299 right: Box::new(right),
1300 location,
1301 location_of_op,
1302 };
1303 Ok(expression)
1304}
1305
1306fn parse_multiplication(tokens: &mut Tokens) -> Result<Expression, Error>
1307{
1308 let mut expression = parse_singular_expression(tokens)?;
1309 let mut location = expression.location().clone();
1310
1311 loop
1312 {
1313 let op = match peek(tokens)
1314 {
1315 Some(Token::Times) => BinaryOp::Multiply,
1316 Some(Token::Divide) => BinaryOp::Divide,
1317 Some(Token::Modulo) => BinaryOp::Modulo,
1318 _ =>
1319 {
1320 return Ok(expression);
1321 }
1322 };
1323 tokens.pop_front();
1324 let location_of_op = tokens.last_location.clone();
1325
1326 let right = parse_singular_expression(tokens)?;
1327 location = location.combined_with(right.location());
1328
1329 expression = Expression::Binary {
1330 op,
1331 left: Box::new(expression),
1332 right: Box::new(right),
1333 location: location.clone(),
1334 location_of_op,
1335 };
1336 }
1337}
1338
1339fn parse_singular_expression(tokens: &mut Tokens) -> Result<Expression, Error>
1340{
1341 let mut expression = parse_unary_expression(tokens)?;
1342 let mut location = expression.location().clone();
1343
1344 loop
1345 {
1346 match peek(tokens)
1347 {
1348 Some(Token::As) => (),
1349 _ =>
1350 {
1351 return Ok(expression);
1352 }
1353 };
1354 tokens.pop_front();
1355
1356 let start = tokens.start_location_span();
1357 let coerced_type = parse_wellformed_type(tokens)?;
1358 let location_of_type = tokens.location_of_span(start);
1359 location = location.combined_with(&location_of_type);
1360
1361 expression = Expression::PrimitiveCast {
1362 expression: Box::new(expression),
1363 coerced_type,
1364 location: location.clone(),
1365 location_of_type,
1366 };
1367 }
1368}
1369
1370fn parse_unary_expression(tokens: &mut Tokens) -> Result<Expression, Error>
1371{
1372 match peek(tokens)
1373 {
1374 Some(Token::PipeForType) =>
1375 {
1376 let start = tokens.start_location_span();
1377 tokens.pop_front();
1378 let name = extract_identifier("expected structure name", tokens)?;
1379 consume(Token::Pipe, "expected pipe", tokens)?;
1380 let location = tokens.location_of_span(start);
1381 let expression = Expression::SizeOfStructure { name, location };
1382 Ok(expression)
1383 }
1384 Some(Token::Pipe) =>
1385 {
1386 let start = tokens.start_location_span();
1387 tokens.pop_front();
1388 let reference = parse_reference(tokens)?;
1389 consume(Token::Pipe, "expected pipe", tokens)?;
1390 let location = tokens.location_of_span(start);
1391 let expression = Expression::LengthOfArray {
1392 reference,
1393 location,
1394 };
1395 Ok(expression)
1396 }
1397 Some(Token::Exclamation) =>
1398 {
1399 tokens.pop_front();
1400 let location_of_op = tokens.last_location.clone();
1401 let expr = parse_primary_expression(tokens)?;
1402 let location =
1403 location_of_op.clone().combined_with(expr.location());
1404 let expression = Expression::Unary {
1405 op: UnaryOp::BitwiseComplement,
1406 expression: Box::new(expr),
1407 location,
1408 location_of_op,
1409 };
1410 Ok(expression)
1411 }
1412 Some(Token::Minus) =>
1413 {
1414 tokens.pop_front();
1415 let location_of_op = tokens.last_location.clone();
1416 let expr = parse_primary_expression(tokens)?;
1417 let location =
1418 location_of_op.clone().combined_with(expr.location());
1419 match expr
1420 {
1421 Expression::NakedIntegerLiteral {
1422 value,
1423 value_type,
1424 location: _,
1425 } => Ok(Expression::NakedIntegerLiteral {
1426 value: -value,
1427 value_type,
1428 location,
1429 }),
1430 Expression::PrimitiveLiteral {
1431 literal: PrimitiveLiteral::Int8(value),
1432 location: _,
1433 } => Ok(Expression::PrimitiveLiteral {
1434 literal: PrimitiveLiteral::Int8(-value),
1435 location,
1436 }),
1437 Expression::PrimitiveLiteral {
1438 literal: PrimitiveLiteral::Int16(value),
1439 location: _,
1440 } => Ok(Expression::PrimitiveLiteral {
1441 literal: PrimitiveLiteral::Int16(-value),
1442 location,
1443 }),
1444 Expression::PrimitiveLiteral {
1445 literal: PrimitiveLiteral::Int32(value),
1446 location: _,
1447 } => Ok(Expression::PrimitiveLiteral {
1448 literal: PrimitiveLiteral::Int32(-value),
1449 location,
1450 }),
1451 Expression::PrimitiveLiteral {
1452 literal: PrimitiveLiteral::Int64(value),
1453 location: _,
1454 } => Ok(Expression::PrimitiveLiteral {
1455 literal: PrimitiveLiteral::Int64(-value),
1456 location,
1457 }),
1458 Expression::PrimitiveLiteral {
1459 literal: PrimitiveLiteral::Int128(value),
1460 location: _,
1461 } => Ok(Expression::PrimitiveLiteral {
1462 literal: PrimitiveLiteral::Int128(-value),
1463 location,
1464 }),
1465 expr =>
1466 {
1467 let expression = Expression::Unary {
1468 op: UnaryOp::Negative,
1469 expression: Box::new(expr),
1470 location,
1471 location_of_op,
1472 };
1473 Ok(expression)
1474 }
1475 }
1476 }
1477 _ => parse_primary_expression(tokens),
1478 }
1479}
1480
1481fn parse_primary_expression(tokens: &mut Tokens) -> Result<Expression, Error>
1482{
1483 let (token, location) = extract("expected literal or identifier", tokens)?;
1484 match token
1485 {
1486 Token::NakedInteger(value) => Ok(Expression::NakedIntegerLiteral {
1487 value,
1488 value_type: None,
1489 location,
1490 }),
1491 Token::BitInteger(value) => Ok(Expression::BitIntegerLiteral {
1492 value,
1493 value_type: None,
1494 location,
1495 }),
1496 Token::Int8(value) =>
1497 {
1498 let literal = PrimitiveLiteral::Int8(value);
1499 Ok(Expression::PrimitiveLiteral { literal, location })
1500 }
1501 Token::Int16(value) =>
1502 {
1503 let literal = PrimitiveLiteral::Int16(value);
1504 Ok(Expression::PrimitiveLiteral { literal, location })
1505 }
1506 Token::Int32(value) =>
1507 {
1508 let literal = PrimitiveLiteral::Int32(value);
1509 Ok(Expression::PrimitiveLiteral { literal, location })
1510 }
1511 Token::Int64(value) =>
1512 {
1513 let literal = PrimitiveLiteral::Int64(value);
1514 Ok(Expression::PrimitiveLiteral { literal, location })
1515 }
1516 Token::Int128(value) =>
1517 {
1518 let literal = PrimitiveLiteral::Int128(value);
1519 Ok(Expression::PrimitiveLiteral { literal, location })
1520 }
1521 Token::Uint8(value) =>
1522 {
1523 let literal = PrimitiveLiteral::Uint8(value);
1524 Ok(Expression::PrimitiveLiteral { literal, location })
1525 }
1526 Token::Uint16(value) =>
1527 {
1528 let literal = PrimitiveLiteral::Uint16(value);
1529 Ok(Expression::PrimitiveLiteral { literal, location })
1530 }
1531 Token::Uint32(value) =>
1532 {
1533 let literal = PrimitiveLiteral::Uint32(value);
1534 Ok(Expression::PrimitiveLiteral { literal, location })
1535 }
1536 Token::Uint64(value) =>
1537 {
1538 let literal = PrimitiveLiteral::Uint64(value);
1539 Ok(Expression::PrimitiveLiteral { literal, location })
1540 }
1541 Token::Uint128(value) =>
1542 {
1543 let literal = PrimitiveLiteral::Uint128(value);
1544 Ok(Expression::PrimitiveLiteral { literal, location })
1545 }
1546 Token::Usize(value) =>
1547 {
1548 let literal = PrimitiveLiteral::Usize(value);
1549 Ok(Expression::PrimitiveLiteral { literal, location })
1550 }
1551 Token::Bool(value) =>
1552 {
1553 let literal = PrimitiveLiteral::Bool(value);
1554 Ok(Expression::PrimitiveLiteral { literal, location })
1555 }
1556 Token::StringLiteral { bytes } =>
1557 {
1558 let mut bytes = bytes;
1559 let mut location = location;
1560 while let Some(next_token) = peek(tokens)
1561 {
1562 match next_token
1563 {
1564 Token::StringLiteral { .. } =>
1565 {}
1566 _ => break,
1567 }
1568
1569 let (token, extra_location) = extract("", tokens)?;
1570 match token
1571 {
1572 Token::StringLiteral {
1573 bytes: mut extra_bytes,
1574 } =>
1575 {
1576 bytes.append(&mut extra_bytes);
1577 }
1578 _ => unreachable!(),
1579 }
1580 location = location.combined_with(&extra_location);
1581 }
1582 Ok(Expression::StringLiteral { bytes, location })
1583 }
1584 Token::Identifier(name) =>
1585 {
1586 if let Some(Token::ParenLeft) = peek(tokens)
1587 {
1588 let identifier = Identifier {
1589 name,
1590 location,
1591 resolution_id: 0,
1592 is_authoritative: false,
1593 };
1594 let arguments = parse_arguments(tokens)?;
1595 Ok(Expression::FunctionCall {
1596 name: identifier,
1597 arguments,
1598 return_type: None,
1599 })
1600 }
1601 else if let Some(Token::BraceLeft) = peek(tokens)
1602 {
1603 let identifier = Identifier {
1604 name,
1605 location: location.clone(),
1606 resolution_id: 0,
1607 is_authoritative: false,
1608 };
1609 let structural_type = Ok(ValueType::UnresolvedStructOrWord {
1610 identifier: Some(identifier),
1611 });
1612 let members = parse_body_of_structural(tokens)?;
1613 let location = location.combined_with(&tokens.last_location);
1614 Ok(Expression::Structural {
1615 structural_type,
1616 members,
1617 location,
1618 })
1619 }
1620 else
1621 {
1622 let reference =
1623 parse_rest_of_reference(name, location, tokens)?;
1624 Ok(Expression::Deref {
1625 reference,
1626 deref_type: None,
1627 })
1628 }
1629 }
1630 Token::Ampersand =>
1631 {
1632 let reference = parse_addressed_reference(location, tokens)?;
1633 Ok(Expression::Deref {
1634 reference,
1635 deref_type: None,
1636 })
1637 }
1638 Token::BracketLeft =>
1639 {
1640 let array = Array {
1641 elements: Vec::new(),
1642 location,
1643 resolution_id: 0,
1644 };
1645 let array = parse_rest_of_array(array, tokens)?;
1646 let expression = Expression::ArrayLiteral {
1647 array,
1648 element_type: None,
1649 };
1650 Ok(expression)
1651 }
1652 Token::ParenLeft =>
1653 {
1654 let inner = parse_expression(tokens)?;
1655 consume(Token::ParenRight, "expected closing parenthesis", tokens)?;
1656 let location = location.combined_with(&tokens.last_location);
1657 let expression = Expression::Parenthesized {
1658 inner: Box::new(inner),
1659 location,
1660 };
1661 Ok(expression)
1662 }
1663 _ => Err(Error::UnexpectedToken {
1664 location,
1665 expectation: "expected literal or identifier".to_string(),
1666 }),
1667 }
1668}
1669
1670fn parse_arguments(tokens: &mut Tokens) -> Result<Vec<Expression>, Error>
1671{
1672 consume(Token::ParenLeft, "expected argument list", tokens)?;
1673
1674 let mut arguments = Vec::new();
1675
1676 loop
1677 {
1678 if let Some(Token::ParenRight) = peek(tokens)
1679 {
1680 break;
1681 }
1682
1683 let expression = parse_expression(tokens)?;
1684 arguments.push(expression);
1685
1686 if let Some(Token::Comma) = peek(tokens)
1687 {
1688 tokens.pop_front();
1689 }
1690 else
1691 {
1692 break;
1693 }
1694 }
1695
1696 consume(
1697 Token::ParenRight,
1698 "expect comma or right parenthesis",
1699 tokens,
1700 )?;
1701
1702 Ok(arguments)
1703}
1704
1705fn parse_rest_of_array(
1706 mut array: Array,
1707 tokens: &mut Tokens,
1708) -> Result<Array, Error>
1709{
1710 loop
1711 {
1712 if let Some(Token::BracketRight) = peek(tokens)
1713 {
1714 break;
1715 }
1716
1717 let element = parse_expression(tokens)?;
1718 array.elements.push(element);
1719
1720 if let Some(Token::Comma) = peek(tokens)
1721 {
1722 tokens.pop_front();
1723 }
1724 else
1725 {
1726 break;
1727 }
1728 }
1729
1730 consume(
1731 Token::BracketRight,
1732 "expected comma or right bracket",
1733 tokens,
1734 )?;
1735 array.location = array.location.combined_with(&tokens.last_location);
1736
1737 Ok(array)
1738}
1739
1740fn parse_body_of_structural(
1741 tokens: &mut Tokens,
1742) -> Result<Vec<MemberExpression>, Error>
1743{
1744 consume(Token::BraceLeft, "expected left brace", tokens)?;
1745
1746 let mut members = Vec::new();
1747 loop
1748 {
1749 if let Some(Token::BraceRight) = peek(tokens)
1750 {
1751 break;
1752 }
1753
1754 let name = extract_identifier("expected member name", tokens)?;
1755
1756 let expression = if let Some(Token::Colon) = peek(tokens)
1757 {
1758 tokens.pop_front();
1759
1760 let expression = parse_expression(tokens)?;
1761 expression
1762 }
1763 else
1764 {
1765 let reference = Reference {
1767 base: Ok(name.clone()),
1768 steps: Vec::new(),
1769 address_depth: 0,
1770 location: name.location.clone(),
1771 location_of_unaddressed: name.location.clone(),
1772 };
1773 Expression::Deref {
1774 reference,
1775 deref_type: None,
1776 }
1777 };
1778
1779 members.push(MemberExpression {
1780 name: Ok(name),
1781 offset: None,
1782 expression,
1783 });
1784
1785 if let Some(Token::Comma) = peek(tokens)
1786 {
1787 tokens.pop_front();
1788 }
1789 else
1790 {
1791 break;
1792 }
1793 }
1794
1795 consume(Token::BraceRight, "expected right brace", tokens)?;
1796 Ok(members)
1797}
1798
1799fn parse_addressed_reference(
1800 location: Location,
1801 tokens: &mut Tokens,
1802) -> Result<Reference, Error>
1803{
1804 let Reference {
1805 base,
1806 steps,
1807 address_depth,
1808 location: _,
1809 location_of_unaddressed,
1810 } = parse_reference(tokens)?;
1811 if address_depth + 1 > MAX_ADDRESS_DEPTH
1812 {
1813 return Err(Error::MaximumParseDepthExceeded {
1814 location: location.combined_with(&tokens.last_location),
1815 });
1816 }
1817 let reference = Reference {
1818 base,
1819 steps,
1820 address_depth: address_depth + 1,
1821 location: location.combined_with(&tokens.last_location),
1822 location_of_unaddressed,
1823 };
1824 Ok(reference)
1825}
1826
1827fn parse_reference(tokens: &mut Tokens) -> Result<Reference, Error>
1828{
1829 let (token, location) = extract("expected identifier", tokens)?;
1830 match token
1831 {
1832 Token::Ampersand =>
1833 {
1834 let mut address_depth: u8 = 1;
1835 while let Some(Token::Ampersand) = peek(tokens)
1836 {
1837 tokens.pop_front();
1838 let location_of_address = tokens.last_location.clone();
1839 address_depth += 1;
1840 if address_depth > MAX_ADDRESS_DEPTH
1841 {
1842 return Err(Error::MaximumParseDepthExceeded {
1843 location: location.combined_with(&location_of_address),
1844 });
1845 }
1846 }
1847 let reference = parse_reference(tokens)?;
1848 Ok(Reference {
1849 base: reference.base,
1850 steps: reference.steps,
1851 address_depth,
1852 location: location.combined_with(&tokens.last_location),
1853 location_of_unaddressed: reference.location_of_unaddressed,
1854 })
1855 }
1856 Token::Identifier(name) =>
1857 {
1858 parse_rest_of_reference(name, location, tokens)
1859 }
1860 _ => Err(Error::UnexpectedToken {
1861 location,
1862 expectation: "expected identifier".to_string(),
1863 }),
1864 }
1865}
1866
1867fn parse_rest_of_reference(
1868 name: String,
1869 location: Location,
1870 tokens: &mut Tokens,
1871) -> Result<Reference, Error>
1872{
1873 let base = Identifier {
1874 name,
1875 location: location.clone(),
1876 resolution_id: 0,
1877 is_authoritative: false,
1878 };
1879 let mut steps = Vec::new();
1880 let mut location = location;
1881 loop
1882 {
1883 let step = match peek(tokens)
1884 {
1885 Some(Token::BracketLeft) =>
1886 {
1887 tokens.pop_front();
1888 let argument = parse_expression(tokens)?;
1889 consume(Token::BracketRight, "expected right bracket", tokens)?;
1890 ReferenceStep::Element {
1891 argument: Box::new(argument),
1892 is_endless: None,
1893 }
1894 }
1895 Some(Token::Dot) =>
1896 {
1897 tokens.pop_front();
1898 let member =
1899 extract_identifier("expected member name", tokens)?;
1900 ReferenceStep::Member {
1901 member,
1902 offset: None,
1903 }
1904 }
1905 _ => break,
1906 };
1907 steps.push(step);
1908 location = location.combined_with(&tokens.last_location);
1909 if steps.len() > MAX_REFERENCE_DEPTH
1910 {
1911 return Err(Error::MaximumParseDepthExceeded { location });
1912 }
1913 }
1914 let location_of_unaddressed = location.clone();
1915 Ok(Reference {
1916 base: Ok(base),
1917 steps,
1918 address_depth: 0,
1919 location,
1920 location_of_unaddressed,
1921 })
1922}