(
context: &mut ParserContext,
env: &mut Environment,
tokens: &[Token],
position: &mut usize,
)
| 2765 | } |
| 2766 | |
| 2767 | pub(crate) fn parse_index_or_slice_expression( |
| 2768 | context: &mut ParserContext, |
| 2769 | env: &mut Environment, |
| 2770 | tokens: &[Token], |
| 2771 | position: &mut usize, |
| 2772 | ) -> Result<Box<dyn Expr>, Box<Diagnostic>> { |
| 2773 | let mut lhs = parse_prefix_unary_expression(context, env, tokens, position)?; |
| 2774 | |
| 2775 | 'parse_expr: while *position < tokens.len() && tokens[*position].kind == TokenKind::LeftBracket |
| 2776 | { |
| 2777 | let operator = &tokens[*position]; |
| 2778 | |
| 2779 | // Consume Left Bracket `[` |
| 2780 | *position += 1; |
| 2781 | |
| 2782 | let lhs_type = lhs.expr_type(); |
| 2783 | |
| 2784 | // Slice with end only range [:end] |
| 2785 | if is_current_token(tokens, position, TokenKind::Colon) { |
| 2786 | // Consume Colon `:` |
| 2787 | *position += 1; |
| 2788 | |
| 2789 | // In case the user use default slice start and end, we can ignore the slice expression |
| 2790 | // and return array or any kind of expression value directly |
| 2791 | if is_current_token(tokens, position, TokenKind::RightBracket) { |
| 2792 | // Consume right bracket `]` |
| 2793 | *position += 1; |
| 2794 | return Ok(lhs); |
| 2795 | } |
| 2796 | |
| 2797 | let slice_end = parse_prefix_unary_expression(context, env, tokens, position)?; |
| 2798 | let end_type = slice_end.expr_type(); |
| 2799 | |
| 2800 | // Check if LHS already support slice op |
| 2801 | if !lhs_type.can_perform_slice_op() { |
| 2802 | return Err(Diagnostic::error(&format!( |
| 2803 | "Operator `[:]` can't be performed on type `{lhs_type}`" |
| 2804 | )) |
| 2805 | .with_location(calculate_safe_location(tokens, *position)) |
| 2806 | .as_boxed()); |
| 2807 | } |
| 2808 | |
| 2809 | // Check that LHS support slice op with this type |
| 2810 | let rhs_expected_types = lhs_type.can_perform_slice_op_with(); |
| 2811 | if !rhs_expected_types.contains(&end_type) { |
| 2812 | return Err(Diagnostic::error(&format!( |
| 2813 | "Operator `[:]` can't be performed with type of index `{}`", |
| 2814 | end_type.literal() |
| 2815 | )) |
| 2816 | .with_location(calculate_safe_location(tokens, *position)) |
| 2817 | .as_boxed()); |
| 2818 | } |
| 2819 | |
| 2820 | // Consume Right Bracket `]` |
| 2821 | consume_token_or_error( |
| 2822 | tokens, |
| 2823 | position, |
| 2824 | TokenKind::RightBracket, |
no test coverage detected
searching dependent graphs…