Skip to main content

meta_language/translation/
rust.rs

1//! The Rust frontend: reads a Rust program into the surface AST.
2//!
3//! It reads the subset of Rust the core can represent faithfully: modules
4//! with `use` of crate items, enums with unit and tuple variants (`Box<T>`
5//! fields are the recursive occurrences of a value type), free functions over
6//! machine integers, `bool` and `String`, anonymous scalar Copy tuple products,
7//! expression bodies with `let`, `if`, `match` and `format!`, and a `main` made
8//! of `println!`, `let` and `assert!`/`assert_eq!` statements. Everything else is rejected with a
9//! precise obligation.
10//!
11//! Mirrors `js/src/translation/rust.js`.
12
13use std::collections::{HashMap, HashSet};
14use std::sync::Arc;
15
16use super::aborts::rust_macro_message;
17use super::diagnostics::{Result, TranslationError, type_error, unsupported};
18use super::lexer::{Token, TokenCursor, TokenKind, describe, tokenize};
19use super::surface::{
20    BinaryOp, Flavor, Rounding, SArrayItem, SComparison, SCtor, SData, SEffect, SExpr, SField, SFn,
21    SItem, SMain, SModule, SNode, SParam, SPattern, SPatternNode, SProgram, SProp, SPropNode, SRow,
22    ShowStyle, UnaryOp,
23};
24use super::types::{BOOL, FLOAT, STRING, Type, UNIT, rust_fixed_type};
25use super::{Language, Span};
26
27mod array_rules;
28mod cast_syntax_rules;
29mod completion_rules;
30pub(crate) mod const_function_rules;
31pub(crate) mod const_functions;
32mod diagnostic_attributes;
33pub(crate) mod empty_option_rules;
34mod empty_options;
35mod expressions;
36mod float_predicate_rules;
37mod float_predicates;
38pub(super) mod indirection_rules;
39mod items;
40mod owned_local_state;
41pub(crate) mod owned_local_state_rules;
42pub(crate) mod owned_tuple_call_rules;
43pub(crate) mod primitive_owner_rules;
44pub(crate) mod primitive_owners;
45mod product_rules;
46pub(crate) mod pure_unit_call_rules;
47mod pure_unit_calls;
48mod read_only_query_rules;
49mod scalar_loops;
50mod scalar_parameter_rules;
51mod scalar_parameters;
52mod source_origins;
53pub(crate) mod type_namespaces;
54
55use source_origins::{SourceDeclaration, SourceOrigin, SourceOrigins};
56
57const ACCEPTED_DERIVES: [&str; 8] = [
58    "Clone",
59    "Copy",
60    "Debug",
61    "PartialEq",
62    "Eq",
63    "Hash",
64    "PartialOrd",
65    "Ord",
66];
67const ACCEPTED_LINTS: [&str; 6] = ["allow", "warn", "deny", "expect", "must_use", "inline"];
68const RESERVED_ITEMS: [&str; 10] = [
69    "impl",
70    "trait",
71    "struct",
72    "union",
73    "static",
74    "type",
75    "extern",
76    "macro_rules",
77    "async",
78    "unsafe",
79];
80const UNSUPPORTED_TYPES: [&str; 10] = [
81    "str", "char", "f32", "Vec", "Option", "Result", "Rc", "Arc", "HashMap", "Self",
82];
83
84fn comparison_op(value: &str) -> Option<BinaryOp> {
85    Some(match value {
86        "==" => BinaryOp::Eq,
87        "!=" => BinaryOp::Ne,
88        "<" => BinaryOp::Lt,
89        "<=" => BinaryOp::Le,
90        ">" => BinaryOp::Gt,
91        ">=" => BinaryOp::Ge,
92        _ => return None,
93    })
94}
95
96fn additive_op(value: &str) -> Option<BinaryOp> {
97    Some(match value {
98        "+" => BinaryOp::Add,
99        "-" => BinaryOp::Sub,
100        _ => return None,
101    })
102}
103
104fn multiplicative_op(value: &str) -> Option<BinaryOp> {
105    Some(match value {
106        "*" => BinaryOp::Mul,
107        "/" => BinaryOp::Div,
108        "%" => BinaryOp::Rem,
109        _ => return None,
110    })
111}
112
113mod source_profiles;
114pub(crate) use source_profiles::parse_rust_with_loop_profiles;
115pub use source_profiles::{
116    parse_rust, parse_rust_with_array_result_model, parse_rust_with_completion_model,
117    parse_rust_with_empty_option_source_model, parse_rust_with_primitive_owner_model,
118    parse_rust_with_pure_unit_call_model, parse_rust_with_runtime_shell_model,
119    parse_rust_with_scalar_loop_model, parse_rust_with_source_models,
120    parse_rust_with_source_profiles, parse_rust_with_source_signature_model,
121    parse_rust_with_type_namespace_model,
122};
123
124/// Read explicit owned String local state and its exact source interface.
125///
126/// # Errors
127/// Refuses unknown models and unproved source ownership or local state.
128pub fn parse_rust_with_owned_local_state_model(
129    source: &str,
130    model: &str,
131    source_signature_model: &str,
132) -> Result<SProgram> {
133    parse_rust_with_selected_profiles(
134        source,
135        SourceProfiles {
136            local_value_state: model,
137            source_signature: source_signature_model,
138            ..SourceProfiles::default()
139        },
140    )
141}
142
143/// Read owned const qualification on closed primitive Rust predicates.
144///
145/// # Errors
146/// Refuses unknown models and unsupported source or compilation context.
147pub fn parse_rust_with_const_function_model(
148    source: &str,
149    model: &str,
150    source_signature_model: &str,
151) -> Result<SProgram> {
152    parse_rust_with_selected_profiles(
153        source,
154        SourceProfiles {
155            const_function: model,
156            source_signature: source_signature_model,
157            ..SourceProfiles::default()
158        },
159    )
160}
161
162#[derive(Clone, Copy, Default)]
163struct SourceProfiles<'a> {
164    const_function: &'a str,
165    array_result: &'a str,
166    completion: &'a str,
167    source_signature: &'a str,
168    scalar_loop: &'a str,
169    primitive_owner: &'a str,
170    empty_option_source: &'a str,
171    type_namespace: &'a str,
172    pure_unit_call: &'a str,
173    local_value_state: &'a str,
174}
175
176fn parse_rust_with_selected_profiles(
177    source: &str,
178    profiles: SourceProfiles<'_>,
179) -> Result<SProgram> {
180    let SourceProfiles {
181        const_function: const_function_model,
182        array_result: array_result_model,
183        completion: completion_model,
184        source_signature: source_signature_model,
185        scalar_loop: scalar_loop_model,
186        primitive_owner: primitive_owner_model,
187        empty_option_source: empty_option_source_model,
188        type_namespace: type_namespace_model,
189        pure_unit_call: pure_unit_call_model,
190        local_value_state: local_value_state_model,
191    } = profiles;
192    if !const_function_rules::accept_rust_const_function_model(const_function_model) {
193        return Err(unsupported(
194            "Rust const function model",
195            "select the legacy model or closed pure Rust const predicates 1",
196            None,
197        ));
198    }
199    if !const_function_model.is_empty()
200        && [
201            array_result_model,
202            completion_model,
203            scalar_loop_model,
204            primitive_owner_model,
205            empty_option_source_model,
206            type_namespace_model,
207            local_value_state_model,
208            pure_unit_call_model,
209        ]
210        .iter()
211        .any(|model| !model.is_empty())
212    {
213        return Err(unsupported(
214            "Rust const function model",
215            "other source interpretations require independent composition proofs",
216            None,
217        ));
218    }
219    if !pure_unit_call_rules::accept_rust_pure_unit_call_model(pure_unit_call_model) {
220        return Err(unsupported(
221            "Rust pure Unit-call model",
222            "select the legacy model, closed pure Rust unit calls 1 or closed public pure Rust unit calls 1",
223            None,
224        ));
225    }
226    if !pure_unit_call_model.is_empty()
227        && [
228            array_result_model,
229            completion_model,
230            source_signature_model,
231            scalar_loop_model,
232            primitive_owner_model,
233            empty_option_source_model,
234            type_namespace_model,
235            local_value_state_model,
236        ]
237        .iter()
238        .any(|model| !model.is_empty())
239    {
240        return Err(unsupported(
241            "Rust pure Unit-call model",
242            "the closed Unit-call interpretation requires its independent source profile",
243            None,
244        ));
245    }
246    if !owned_local_state_rules::accept_rust_owned_local_state_model(local_value_state_model)
247        && !owned_tuple_call_rules::accept_rust_owned_tuple_call_model(local_value_state_model)
248    {
249        return Err(unsupported(
250            "Rust owned local state model",
251            "select the original move profile or canonical String copy profile",
252            None,
253        ));
254    }
255    if !super::type_namespace_rules::accept_rust_type_namespace_model(type_namespace_model) {
256        return Err(unsupported(
257            "Rust type namespace model",
258            "select the legacy model or resolved Rust type namespace 1",
259            None,
260        ));
261    }
262    if !primitive_owner_rules::accept_rust_primitive_owner_model(primitive_owner_model) {
263        return Err(unsupported(
264            "Rust primitive owner model",
265            "select the legacy model or standard primitive Rust binary64 owner 1",
266            None,
267        ));
268    }
269    if !super::scalar_loop_rules::accept_rust_scalar_loop_model(scalar_loop_model) {
270        return Err(unsupported(
271            "Rust scalar loop model",
272            "select the legacy model or closed primitive scalar loop 1",
273            None,
274        ));
275    }
276    if !array_rules::accept_rust_source_array_result_model(array_result_model) {
277        return Err(unsupported(
278            "Rust array result model",
279            "select the legacy model or immutable fresh scalar vector results 1",
280            None,
281        ));
282    }
283    if !completion_rules::accept_rust_completion_model(completion_model) {
284        return Err(unsupported(
285            "Rust completion model",
286            "select the legacy model or closed guarded function returns 1",
287            None,
288        ));
289    }
290    if !super::source_signature_rules::accept_rust_source_signature_model(source_signature_model) {
291        return Err(unsupported(
292            "Rust source signature model",
293            "select the legacy model or Rust source function signature 1",
294            None,
295        ));
296    }
297    if !empty_option_rules::accept_rust_empty_option_source_model(empty_option_source_model) {
298        return Err(unsupported(
299            "Rust empty option source model",
300            "select the legacy model or closed empty primitive Rust option 1",
301            None,
302        ));
303    }
304    if !empty_option_source_model.is_empty()
305        && [
306            array_result_model,
307            completion_model,
308            source_signature_model,
309            scalar_loop_model,
310            primitive_owner_model,
311            type_namespace_model,
312            local_value_state_model,
313        ]
314        .iter()
315        .any(|model| !model.is_empty())
316    {
317        return Err(unsupported(
318            "Rust empty option source model",
319            "the closed empty interpretation requires its independent source profile",
320            None,
321        ));
322    }
323    let tokens = tokenize(source, Language::Rust)?.tokens;
324    let original_source = (!const_function_model.is_empty()).then(|| Arc::<str>::from(source));
325    let mut declarations = RustParser::new(
326        tokens.clone(),
327        SourceOrigins::new(None, array_result_model),
328        profiles,
329        true,
330        original_source.clone(),
331    );
332    declarations.file()?;
333    let mut origins = std::mem::replace(
334        &mut declarations.origins,
335        SourceOrigins::new(None, array_result_model),
336    );
337    origins.resolve_catalog_types(|segments, path| declarations.resolve(segments, path));
338    let mut source_origins = SourceOrigins::new(Some(origins.catalog), array_result_model);
339    source_origins.collecting = true;
340    source_origins.unit_clone_facts = origins.unit_clone_facts;
341    let mut syntax = RustParser::new(
342        tokens.clone(),
343        source_origins,
344        profiles,
345        false,
346        original_source.clone(),
347    );
348    syntax.aliases = declarations.aliases;
349    syntax.primitive_imports = declarations.primitive_imports;
350    let surface = syntax.file()?;
351    // Preserve the existing checker's rejection and syntax-tree contract;
352    // every public Rust source pipeline checks this identical Surface again.
353    if super::check::check_program(&surface).is_err() {
354        return Ok(surface);
355    }
356    let mut parser = RustParser::new(
357        tokens,
358        SourceOrigins::new(Some(syntax.origins.catalog), array_result_model),
359        profiles,
360        false,
361        original_source,
362    );
363    parser.origins.unit_clone_facts = syntax.origins.unit_clone_facts;
364    parser.aliases = syntax.aliases;
365    parser.primitive_imports = syntax.primitive_imports;
366    parser.file()
367}
368
369/// Where a sequence of items ends: at the end of the file or at a module's `}`.
370#[derive(Clone, Copy)]
371enum ItemsEnd {
372    File,
373    Module,
374}
375
376/// Parsing context an expression inherits from its position.
377#[derive(Clone, Copy, Default)]
378struct Options {
379    /// The expression starts a statement, so a leading `if`/`match` ends there.
380    statement: bool,
381    /// `{` opens a block, not a struct literal (`if`/`match` heads).
382    no_struct: bool,
383}
384
385/// A `name @ pattern` binding, bound around the arm's body.
386struct Alias {
387    name: String,
388    value: SExpr,
389}
390
391/// A parsed `let` statement.
392struct Binding {
393    name: String,
394    ty: Option<Type>,
395    value: SExpr,
396    span: Option<Span>,
397}
398
399/// An irrefutable source pattern, lowered to ordinary ordered value bindings.
400enum ProductBindingPattern {
401    Name(Token),
402    Wildcard(Token),
403    Tuple {
404        items: Vec<Self>,
405        span: Option<Span>,
406    },
407    Unit {
408        span: Option<Span>,
409    },
410}
411
412impl ProductBindingPattern {
413    const fn source_span(&self) -> Option<Span> {
414        match self {
415            Self::Name(token) | Self::Wildcard(token) => Some(token.span()),
416            Self::Tuple { span, .. } | Self::Unit { span } => *span,
417        }
418    }
419}
420
421struct RustParser {
422    const_function_model: String,
423    const_function_keyword: Option<Token>,
424    original_source: Option<Arc<str>>,
425    diagnostic_attribute_columns: Option<diagnostic_attributes::DiagnosticAttributeColumns>,
426    cursor: TokenCursor,
427    /// `use` aliases, per module path.
428    aliases: HashMap<String, HashMap<String, Vec<String>>>,
429    module_path: Vec<String>,
430    crate_declarations: HashSet<String>,
431    main: Option<SMain>,
432    origins: SourceOrigins,
433    completion_model: String,
434    source_signature_model: String,
435    scalar_loop_model: String,
436    primitive_owner_model: String,
437    empty_option_source_model: String,
438    type_namespace_model: String,
439    pure_unit_call_model: String,
440    pure_unit_public_token: Option<Token>,
441    local_value_state_model: String,
442    owned_tuple_call_discovery: Option<()>,
443    local_value_copies: HashSet<Span>,
444    local_value_constructors: HashMap<Span, Span>,
445    type_namespace_frames: Vec<Vec<Vec<String>>>,
446    /// Selected initial catalog discovery, never a later collecting pass.
447    type_namespace_discovery: Option<()>,
448    empty_option_result: Option<serde_json::Value>,
449    empty_option_main_seen: bool,
450    primitive_owner_frames: Vec<Vec<Option<serde_json::Value>>>,
451    primitive_constant_sites: Vec<serde_json::Value>,
452    primitive_import_names: HashSet<String>,
453    primitive_imports: Vec<serde_json::Value>,
454    scalar_loop_active: bool,
455    source_owner_frames: Vec<Vec<super::source_signatures::SourceOwner>>,
456    reserved_binding_names: HashSet<String>,
457    next_product_binding: usize,
458    lifetime_bindings: HashSet<String>,
459    lifetime_header: bool,
460}
461
462impl RustParser {
463    fn new(
464        tokens: Vec<Token>,
465        mut origins: SourceOrigins,
466        profiles: SourceProfiles<'_>,
467        initial_discovery: bool,
468        original_source: Option<Arc<str>>,
469    ) -> Self {
470        let reserved_binding_names = tokens
471            .iter()
472            .filter(|token| token.kind == TokenKind::Identifier)
473            .map(|token| token.value.clone())
474            .collect();
475        origins.owned_local_values = !profiles.local_value_state.is_empty();
476        Self {
477            const_function_model: profiles.const_function.to_owned(),
478            const_function_keyword: None,
479            original_source,
480            diagnostic_attribute_columns: None,
481            cursor: TokenCursor::new(tokens, Language::Rust),
482            aliases: HashMap::new(),
483            module_path: Vec::new(),
484            crate_declarations: HashSet::new(),
485            main: None,
486            origins,
487            completion_model: profiles.completion.to_owned(),
488            source_signature_model: if profiles.source_signature.is_empty()
489                && (!profiles.type_namespace.is_empty()
490                    || !profiles.local_value_state.is_empty()
491                    || !profiles.const_function.is_empty())
492            {
493                "Rust source function signature 1".to_owned()
494            } else {
495                profiles.source_signature.to_owned()
496            },
497            scalar_loop_model: profiles.scalar_loop.to_owned(),
498            primitive_owner_model: profiles.primitive_owner.to_owned(),
499            empty_option_source_model: profiles.empty_option_source.to_owned(),
500            type_namespace_model: profiles.type_namespace.to_owned(),
501            pure_unit_call_model: profiles.pure_unit_call.to_owned(),
502            pure_unit_public_token: None,
503            local_value_state_model: profiles.local_value_state.to_owned(),
504            owned_tuple_call_discovery:
505                (owned_tuple_call_rules::accept_rust_owned_tuple_call_model(
506                    profiles.local_value_state,
507                ) && initial_discovery)
508                    .then_some(()),
509            local_value_copies: HashSet::new(),
510            local_value_constructors: HashMap::new(),
511            type_namespace_frames: Vec::new(),
512            type_namespace_discovery: (!profiles.type_namespace.is_empty() && initial_discovery)
513                .then_some(()),
514            empty_option_result: None,
515            empty_option_main_seen: false,
516            primitive_owner_frames: Vec::new(),
517            primitive_constant_sites: Vec::new(),
518            primitive_import_names: HashSet::new(),
519            primitive_imports: Vec::new(),
520            scalar_loop_active: false,
521            source_owner_frames: Vec::new(),
522            reserved_binding_names,
523            next_product_binding: 0,
524            lifetime_bindings: HashSet::new(),
525            lifetime_header: false,
526        }
527    }
528
529    fn peek(&self) -> Token {
530        self.cursor.peek().clone()
531    }
532
533    fn fail(message: &str, token: &Token) -> TranslationError {
534        TranslationError::syntax(
535            format!("{message} but found {}", describe(token)),
536            Some(token.span()),
537        )
538    }
539}
540
541/// `format!("{} and {name}", a)`: `{}` takes the next argument, `{name}` a
542/// variable in scope, `{{`/`}}` are braces; every value is rendered with
543/// Display, which for integers is its decimal text.
544fn format(args: Vec<SExpr>, token: &Token) -> Result<SExpr> {
545    let mut args = args.into_iter();
546    let template = args.next();
547    let values: Vec<SExpr> = args.collect();
548    let Some(SExpr {
549        node: SNode::Str { value: source },
550        span: template_span,
551        ..
552    }) = template
553    else {
554        return Err(unsupported(
555            &format!("{}!", token.value),
556            "the format string must be a literal",
557            span(token, token),
558        ));
559    };
560    let chars: Vec<char> = source.chars().collect();
561    let mut pieces: Vec<SExpr> = Vec::new();
562    let mut text = String::new();
563    let mut next = 0;
564    let mut index = 0;
565    while index < chars.len() {
566        let char = chars[index];
567        let following = chars.get(index + 1).copied();
568        if char == '{' && following == Some('{') {
569            text.push('{');
570            index += 2;
571            continue;
572        }
573        if char == '}' && following == Some('}') {
574            text.push('}');
575            index += 2;
576            continue;
577        }
578        if char == '}' {
579            return Err(TranslationError::syntax(
580                "unmatched } in format string",
581                template_span,
582            ));
583        }
584        if char != '{' {
585            text.push(char);
586            index += 1;
587            continue;
588        }
589        let Some(end) = chars[index..]
590            .iter()
591            .position(|&candidate| candidate == '}')
592            .map(|offset| index + offset)
593        else {
594            return Err(TranslationError::syntax(
595                "unclosed { in format string",
596                template_span,
597            ));
598        };
599        let spec: String = chars[index + 1..end].iter().collect();
600        if spec.contains(':') {
601            return Err(unsupported(
602                &format!("format spec {{{spec}}}"),
603                "only plain {} Display formatting is portable",
604                template_span,
605            ));
606        }
607        let value = if spec.is_empty() {
608            let value = values.get(next).cloned();
609            next += 1;
610            value.ok_or_else(|| {
611                TranslationError::syntax("format string has more {} than arguments", template_span)
612            })?
613        } else if spec.bytes().all(|byte| byte.is_ascii_digit()) {
614            // A position too large for an index names no argument either.
615            let position = spec.parse::<usize>().ok();
616            let value = position.and_then(|position| values.get(position).cloned());
617            let (Some(position), Some(value)) = (position, value) else {
618                return Err(TranslationError::syntax(
619                    format!("format argument {spec} is missing"),
620                    template_span,
621                ));
622            };
623            next = next.max(position + 1);
624            value
625        } else if is_identifier(&spec) {
626            SExpr::new(SNode::Name { path: vec![spec] }, template_span)
627        } else {
628            return Err(unsupported(
629                &format!("format argument {{{spec}}}"),
630                "outside the portable core",
631                template_span,
632            ));
633        };
634        if !text.is_empty() {
635            pieces.push(SExpr::new(
636                SNode::Str {
637                    value: std::mem::take(&mut text),
638                },
639                template_span,
640            ));
641        }
642        let value_span = value.span;
643        pieces.push(SExpr::new(
644            SNode::Show {
645                arg: Box::new(value),
646                style: ShowStyle::Rust,
647            },
648            value_span,
649        ));
650        index = end + 1;
651    }
652    if next < values.len() {
653        return Err(TranslationError::syntax(
654            "format string has fewer {} than arguments",
655            template_span,
656        ));
657    }
658    if !text.is_empty() || pieces.is_empty() {
659        pieces.push(SExpr::new(SNode::Str { value: text }, template_span));
660    }
661    let mut pieces = pieces.into_iter();
662    let first = pieces
663        .next()
664        .unwrap_or_else(|| unreachable!("a piece was pushed"));
665    Ok(pieces.fold(first, |left, right| {
666        SExpr::new(
667            SNode::Binary {
668                op: BinaryOp::Concat,
669                left: Box::new(left),
670                right: Box::new(right),
671                rounding: None,
672            },
673            template_span,
674        )
675    }))
676}
677
678/// `/^[A-Za-z_][A-Za-z0-9_]*$/`.
679fn is_identifier(text: &str) -> bool {
680    let mut bytes = text.bytes();
681    bytes
682        .next()
683        .is_some_and(|first| first.is_ascii_alphabetic() || first == b'_')
684        && bytes.all(|byte| byte.is_ascii_alphanumeric() || byte == b'_')
685}
686
687fn method_call(
688    receiver: SExpr,
689    method: &Token,
690    args: Vec<SExpr>,
691    range: Option<Span>,
692) -> Result<SExpr> {
693    let expect = |count: usize| {
694        if args.len() == count {
695            Ok(())
696        } else {
697            Err(type_error(
698                format!(
699                    "{} expects {count} arguments but got {}",
700                    method.value,
701                    args.len()
702                ),
703                range,
704            ))
705        }
706    };
707    let mapping =
708        crate::translation::frontend_rules::read_string_map_operation("Rust", &method.value);
709    if !mapping.is_empty() {
710        expect(0)?;
711        return Ok(SExpr::new(
712            SNode::StringMap {
713                op: mapping,
714                object: Box::new(receiver),
715            },
716            range,
717        ));
718    }
719    let operation =
720        crate::translation::frontend_rules::read_string_test_operation("Rust", &method.value);
721    if !operation.is_empty() {
722        expect(1)?;
723        return Ok(SExpr::new(
724            SNode::StringTest {
725                op: operation,
726                object: Box::new(receiver),
727                search: Box::new(args.into_iter().next().expect("one search argument")),
728            },
729            range,
730        ));
731    }
732    match method.value.as_str() {
733        "clone" | "to_owned" | "as_str" => {
734            expect(0)?;
735            Ok(receiver)
736        }
737        "to_string" => {
738            expect(0)?;
739            Ok(SExpr::new(
740                SNode::ToString {
741                    arg: Box::new(receiver),
742                },
743                range,
744            ))
745        }
746        "div_euclid" | "rem_euclid" => {
747            expect(1)?;
748            let op = if method.value == "div_euclid" {
749                BinaryOp::Div
750            } else {
751                BinaryOp::Rem
752            };
753            let right = args
754                .into_iter()
755                .next()
756                .unwrap_or_else(|| unreachable!("one argument"));
757            Ok(SExpr::new(
758                SNode::Binary {
759                    op,
760                    left: Box::new(receiver),
761                    right: Box::new(right),
762                    rounding: Some(Rounding::Euclid),
763                },
764                range,
765            ))
766        }
767        _ => Err(unsupported(
768            &format!("method {}", method.value),
769            "outside the portable core",
770            range,
771        )),
772    }
773}
774
775/// An imported path from the crate root, so it means the same wherever it is used.
776fn absolute(segments: &[String], path: &[String], range: Option<Span>) -> Result<Vec<String>> {
777    let crate_root = || vec!["crate".to_owned()];
778    if segments[0] == "crate" {
779        return Ok(segments.to_vec());
780    }
781    if segments[0] == "self" {
782        let mut result = crate_root();
783        result.extend_from_slice(path);
784        result.extend_from_slice(&segments[1..]);
785        return Ok(result);
786    }
787    let up = segments
788        .iter()
789        .take_while(|segment| *segment == "super")
790        .count();
791    if up > path.len() {
792        return Err(type_error("super beyond crate root", range));
793    }
794    let mut result = crate_root();
795    result.extend_from_slice(&path[..path.len() - up]);
796    result.extend_from_slice(&segments[up..]);
797    Ok(result)
798}
799
800fn prop_of(expr: SExpr) -> SProp {
801    let node = match expr.node {
802        SNode::Binary {
803            op:
804                op @ (BinaryOp::Eq
805                | BinaryOp::Ne
806                | BinaryOp::Lt
807                | BinaryOp::Le
808                | BinaryOp::Gt
809                | BinaryOp::Ge),
810            left,
811            right,
812            ..
813        } => {
814            let comparison = SComparison {
815                left: *left,
816                right: *right,
817                reference: false,
818                same_value: false,
819            };
820            match op {
821                BinaryOp::Eq => SPropNode::Eq(comparison),
822                BinaryOp::Ne => SPropNode::Ne(comparison),
823                BinaryOp::Lt => SPropNode::Lt(comparison),
824                BinaryOp::Le => SPropNode::Le(comparison),
825                BinaryOp::Gt => SPropNode::Gt(comparison),
826                _ => SPropNode::Ge(comparison),
827            }
828        }
829        SNode::Binary {
830            op: BinaryOp::And,
831            left,
832            right,
833            ..
834        } => SPropNode::And {
835            left: Box::new(prop_of(*left)),
836            right: Box::new(prop_of(*right)),
837        },
838        SNode::Binary {
839            op: BinaryOp::Or,
840            left,
841            right,
842            ..
843        } => SPropNode::Or {
844            left: Box::new(prop_of(*left)),
845            right: Box::new(prop_of(*right)),
846        },
847        SNode::Unary {
848            op: UnaryOp::Not,
849            arg,
850        } => SPropNode::Not {
851            arg: Box::new(prop_of(*arg)),
852        },
853        node => SPropNode::Bool {
854            expr: SExpr { node, ..expr },
855        },
856    };
857    SProp { node, span: None }
858}
859
860/// The value a pattern matched, for `name @ p`.
861fn pattern_value(pattern: &SPattern, range: Option<Span>) -> Result<SExpr> {
862    let node = match &pattern.node {
863        SPatternNode::BindOrCtor { name } => SNode::Name {
864            path: vec![name.clone()],
865        },
866        SPatternNode::NumLit { value, negative } => SNode::Num {
867            value: value.clone(),
868            ty: None,
869            negative: *negative,
870            unit: false,
871        },
872        SPatternNode::BoolLit { value, .. } => SNode::Bool { value: *value },
873        SPatternNode::Ctor { path, args } if args.is_empty() => SNode::Name { path: path.clone() },
874        SPatternNode::Ctor { path, args } => SNode::App {
875            func: Box::new(SExpr::new(SNode::Name { path: path.clone() }, range)),
876            args: args
877                .iter()
878                .map(|arg| pattern_value(arg, range))
879                .collect::<Result<_>>()?,
880        },
881        _ => {
882            return Err(unsupported(
883                "@ binding",
884                "the aliased pattern must bind every field",
885                range,
886            ));
887        }
888    };
889    Ok(SExpr::new(node, range))
890}
891
892const fn is_if_or_match(expr: &SExpr) -> bool {
893    matches!(expr.node, SNode::If { .. } | SNode::Match { .. })
894}
895
896fn operator(token: &Token, table: fn(&str) -> Option<BinaryOp>) -> Option<BinaryOp> {
897    if token.kind == TokenKind::Punct {
898        table(&token.value)
899    } else {
900        None
901    }
902}
903
904fn binary(op: BinaryOp, left: SExpr, right: SExpr, token: &Token) -> SExpr {
905    let range = joined(left.span, right.span, token);
906    SExpr::new(
907        SNode::Binary {
908            op,
909            left: Box::new(left),
910            right: Box::new(right),
911            rounding: None,
912        },
913        range,
914    )
915}
916
917#[allow(clippy::unnecessary_wraps)] // nodes and errors take an optional span
918fn joined(left: Option<Span>, right: Option<Span>, token: &Token) -> Option<Span> {
919    Some(Span::new(
920        left.map_or(token.start, |left| left.start),
921        right.map_or(token.end, |right| right.end),
922    ))
923}
924
925#[allow(clippy::unnecessary_wraps)] // nodes and errors take an optional span
926fn span(from: &Token, to: &Token) -> Option<Span> {
927    let to_start = if to.kind == TokenKind::Eof {
928        from.end
929    } else {
930        to.start
931    };
932    Some(Span::new(from.start, from.end.max(to_start)))
933}