Skip to main content

vibe/session/
prepare.rs

1use super::*;
2
3impl SourceSession {
4    pub fn prepare(&self, source: &str) -> Result<CheckedSubmission, Diagnostic> {
5        self.prepare_inner(source, false)
6    }
7
8    /// Prepare a submission that explicitly replaces matching top-level declarations
9    /// using `projectional::Edit::ReplaceItem` with full rollback on failure.
10    pub fn prepare_replace(&self, source: &str) -> Result<CheckedSubmission, Diagnostic> {
11        self.prepare_inner(source, true)
12    }
13
14    /// Prepare an incremental `projectional::Edit` against the retained session program.
15    /// Returns an error without mutating session state if bounds, limits, or checks fail.
16    pub fn prepare_edit(
17        &self,
18        edit: &crate::projectional::Edit,
19    ) -> Result<CheckedSubmission, Diagnostic> {
20        if self.revision >= self.limits.revisions {
21            return Err(Diagnostic::new(
22                DiagCode::E400,
23                Span::point(0),
24                "session source/revision limit exceeded",
25            ));
26        }
27        let edited = crate::projectional::try_apply_edit(&self.definitions, edit)
28            .map_err(|msg| Diagnostic::new(DiagCode::E701, Span::point(0), msg))?;
29        if edited.items.len() > self.limits.declarations {
30            return Err(Diagnostic::new(
31                DiagCode::E400,
32                edited.span,
33                "session declaration limit exceeded",
34            ));
35        }
36        for request in &edited.requires {
37            if !(crate::catalog::is_known(&request.id)
38                && crate::catalog::granted_covers(
39                    &self.grants.iter().map(String::as_str).collect::<Vec<_>>(),
40                    &request.id,
41                ))
42                && !self.grants.iter().any(|g| g == &request.id)
43            {
44                return Err(Diagnostic::new(
45                    DiagCode::E300,
46                    request.span,
47                    format!("session host has not granted capability `{}`", request.id),
48                ));
49            }
50        }
51        let projected = crate::projectional::project_program(
52            &edited,
53            &crate::projectional::ProjectOptions::default(),
54        );
55        if projected.len() > self.limits.submission_bytes
56            || projected.len() > self.limits.retained_source_bytes
57        {
58            return Err(Diagnostic::new(
59                DiagCode::E400,
60                edited.span,
61                "session source/revision limit exceeded",
62            ));
63        }
64        source_limits::check(&projected)?;
65        let (_, checked, mutables) =
66            check_submission(&edited, &edited, &CheckEnv::default(), &HashSet::new())?;
67        values::validate_source(&checked)?;
68        if checked.len() > self.limits.bindings {
69            return Err(Diagnostic::new(
70                DiagCode::E400,
71                edited.span,
72                "session binding limit exceeded",
73            ));
74        }
75        Ok(CheckedSubmission {
76            owner: self.owner,
77            base_revision: self.revision,
78            source: projected,
79            definitions: edited.clone(),
80            checked,
81            mutables,
82            body: Body::Program(edited),
83            replace_env: true,
84        })
85    }
86
87    fn prepare_inner(&self, source: &str, allow_replace: bool) -> Result<CheckedSubmission, Diagnostic> {
88        if source.len() > self.limits.submission_bytes
89            || self.source_bytes.saturating_add(source.len()) > self.limits.retained_source_bytes
90            || self.revision >= self.limits.revisions
91        {
92            return Err(Diagnostic::new(
93                DiagCode::E400,
94                Span::point(0),
95                "session source/revision limit exceeded",
96            ));
97        }
98        source_limits::check(source)?;
99        let trimmed = source.strip_prefix('\u{FEFF}').unwrap_or(source).trim();
100        // Mode selection uses parsing only; no check/runtime fallback.
101        let parsed_program = if trimmed.starts_with('=') {
102            None
103        } else {
104            crate::parse_program(trimmed).ok()
105        };
106        let (mut submission, expression) = match parsed_program {
107            Some(p) => (p, None),
108            None => {
109                let input = if trimmed.starts_with('=') {
110                    trimmed.to_string()
111                } else {
112                    format!("= {trimmed}")
113                };
114                let expr = crate::parse_cell(&input)?;
115                let mut p = self.definitions.clone();
116                p.items = vec![Item::Cell(CellDecl {
117                    span: expr.span,
118                    effect: Some(EffectClass::Pure),
119                    name: "__session_expression".into(),
120                    params: Vec::new(),
121                    expr: expr.clone(),
122                    when: None,
123                })];
124                p.imports.clear();
125                p.requires.clear();
126                p.prefixes.clear();
127                p.locales.clear();
128                (p, Some(expr))
129            }
130        };
131        if submission.module.is_some() {
132            return Err(Diagnostic::new(
133                DiagCode::E100,
134                submission.span,
135                "module installation is separate from source-session execution",
136            ));
137        }
138        let mut definitions = self.definitions.clone();
139        definitions.imports.extend(submission.imports.clone());
140        definitions.prefixes.extend(submission.prefixes.clone());
141        definitions.locales.extend(submission.locales.clone());
142        for request in &submission.requires {
143            if !(crate::catalog::is_known(&request.id)
144                && crate::catalog::granted_covers(
145                    &self.grants.iter().map(String::as_str).collect::<Vec<_>>(),
146                    &request.id,
147                ))
148                && !self.grants.iter().any(|g| g == &request.id)
149            {
150                return Err(Diagnostic::new(
151                    DiagCode::E300,
152                    request.span,
153                    format!("session host has not granted capability `{}`", request.id),
154                ));
155            }
156            if !definitions.requires.iter().any(|c| c.id == request.id) {
157                definitions.requires.push(request.clone());
158            }
159        }
160        let mut new_names = HashSet::new();
161        let mut replaced_any = false;
162        for item in &submission.items {
163            if matches!(item, Item::Statement(s) if contains_return(s)) {
164                return Err(Diagnostic::new(DiagCode::E100, submission.span,
165                    "top-level return is unsupported in additive 0.1 source sessions; use a result expression"));
166            }
167            let mut item_names = Vec::new();
168            collect_item_names(item, &mut item_names);
169            for name in item_names {
170                if !new_names.insert(name) {
171                    return Err(Diagnostic::new(DiagCode::E701, submission.span,
172                        format!("session declaration `{name}` already exists in this submission")));
173                }
174                let exists_in_defs = definitions
175                    .items
176                    .iter()
177                    .filter_map(declaration_name)
178                    .any(|n| n == name);
179                let exists_in_env = self.env.vars.contains_key(name)
180                    || self.env.fields.contains_key(name)
181                    || self.env.materials.contains_key(name)
182                    || self.env.laws.contains_key(name);
183                if (exists_in_defs || exists_in_env) && !allow_replace {
184                    return Err(Diagnostic::new(DiagCode::E701, submission.span,
185                        format!("session declaration `{name}` already exists; explicit replacement is unsupported")));
186                }
187            }
188            if matches!(item, Item::Statement(s) if !matches!(s, Stmt::Let { .. }|Stmt::LetPat { .. }))
189            {
190                let mut nested_names = Vec::new();
191                collect_item_names(item, &mut nested_names);
192                if !nested_names.is_empty() {
193                    return Err(Diagnostic::new(DiagCode::E100, submission.span,
194                        "nested global declarations are unsupported in additive 0.1 source sessions; declare persistent bindings at top level"));
195                }
196            }
197            if allow_replace {
198                if let Some(decl_name) = declaration_name(item) {
199                    if let Some(idx) = definitions
200                        .items
201                        .iter()
202                        .position(|existing| declaration_name(existing) == Some(decl_name))
203                    {
204                        definitions = crate::projectional::try_apply_edit(
205                            &definitions,
206                            &crate::projectional::Edit::ReplaceItem {
207                                index: idx,
208                                item: item.clone(),
209                            },
210                        )
211                        .map_err(|msg| Diagnostic::new(DiagCode::E701, submission.span, msg))?;
212                        replaced_any = true;
213                        continue;
214                    }
215                }
216            }
217            if matches!(item, Item::Function(_) | Item::Hook(_) | Item::Enum(_)) {
218                definitions = crate::projectional::try_apply_edit(
219                    &definitions,
220                    &crate::projectional::Edit::AddItem {
221                        item: item.clone(),
222                        index: None,
223                    },
224                )
225                .map_err(|msg| Diagnostic::new(DiagCode::E701, submission.span, msg))?;
226            }
227        }
228        if definitions.items.len() > self.limits.declarations {
229            return Err(Diagnostic::new(
230                DiagCode::E400,
231                submission.span,
232                "session declaration limit exceeded",
233            ));
234        }
235        let (_, checked, mutables) = if replaced_any {
236            check_submission(&definitions, &definitions, &CheckEnv::default(), &HashSet::new())?
237        } else {
238            check_submission(&definitions, &submission, &self.checked, &self.mutables)?
239        };
240        values::validate_source(&checked)?;
241        for item in &submission.items {
242            if let Item::Bind(bind) = item {
243                for endpoint in [&bind.left, &bind.right] {
244                    if !bind_root(endpoint).is_some_and(|name| mutables.contains(name)) {
245                        return Err(Diagnostic::new(
246                            DiagCode::E701,
247                            endpoint.span,
248                            "session bind endpoint must have a declared mutable root",
249                        ));
250                    }
251                }
252            }
253        }
254        if checked.len() > self.limits.bindings {
255            return Err(Diagnostic::new(
256                DiagCode::E400,
257                submission.span,
258                "session binding limit exceeded",
259            ));
260        }
261        // Execute with admitted retained requests; this does not grant new ones.
262        submission.requires = definitions.requires.clone();
263        Ok(CheckedSubmission {
264            owner: self.owner,
265            base_revision: self.revision,
266            source: source.to_string(),
267            definitions,
268            checked,
269            mutables,
270            body: expression
271                .map(Body::Expression)
272                .unwrap_or(Body::Program(submission)),
273            replace_env: false,
274        })
275    }
276}
277
278fn declaration_name(item: &Item) -> Option<&str> {
279    match item {
280        Item::Function(f) => Some(&f.name),
281        Item::Enum(e) => Some(&e.name),
282        Item::Const(c) => Some(&c.name),
283        Item::Cell(c) => Some(&c.name),
284        Item::Field(f) => Some(&f.name),
285        Item::Material(m) => Some(&m.name),
286        Item::Law(l) => Some(&l.name),
287        Item::Present(p) => Some(&p.name),
288        Item::Statement(Stmt::Let { name, .. }) => Some(name),
289        _ => None,
290    }
291}
292
293fn bind_root(expr: &Expr) -> Option<&str> {
294    match &expr.kind {
295        ExprKind::Ident(n) => Some(n),
296        ExprKind::Member { recv, .. } => bind_root(recv),
297        _ => None,
298    }
299}
300
301fn contains_return(stmt: &Stmt) -> bool {
302    let block_returns = |block: &Block| block.stmts.iter().any(contains_return);
303    match stmt {
304        Stmt::Return { .. } => true,
305        Stmt::If {
306            then_block,
307            else_block,
308            ..
309        } => block_returns(then_block) || else_block.as_deref().is_some_and(contains_return),
310        Stmt::For { body, .. }
311        | Stmt::While { body, .. }
312        | Stmt::Transaction { body, .. }
313        | Stmt::Block(body) => block_returns(body),
314        Stmt::Match { arms, .. } => arms.iter().any(|a| {
315            matches!(&a.body,
316            ArmBody::Block(b) if block_returns(b))
317        }),
318        _ => false,
319    }
320}
321
322fn collect_item_names<'a>(item: &'a Item, names: &mut Vec<&'a str>) {
323    if let Item::Statement(s) = item {
324        collect_stmt_names(s, names)
325    } else if let Some(name) = declaration_name(item) {
326        names.push(name)
327    }
328}
329fn collect_block_names<'a>(block: &'a Block, names: &mut Vec<&'a str>) {
330    for s in &block.stmts {
331        collect_stmt_names(s, names)
332    }
333}
334fn collect_stmt_names<'a>(stmt: &'a Stmt, names: &mut Vec<&'a str>) {
335    match stmt {
336        Stmt::Let { name, .. } => names.push(name),
337        Stmt::LetPat { pattern, .. } => collect_pattern_names(pattern, names),
338        Stmt::If {
339            then_block,
340            else_block,
341            ..
342        } => {
343            collect_block_names(then_block, names);
344            if let Some(s) = else_block {
345                collect_stmt_names(s, names)
346            }
347        }
348        Stmt::For { name, body, .. } => {
349            names.push(name);
350            collect_block_names(body, names)
351        }
352        Stmt::While { body, .. } | Stmt::Transaction { body, .. } | Stmt::Block(body) => {
353            collect_block_names(body, names)
354        }
355        Stmt::Match { arms, .. } => {
356            for arm in arms {
357                collect_pattern_names(&arm.pattern, names);
358                if let ArmBody::Block(b) = &arm.body {
359                    collect_block_names(b, names)
360                }
361            }
362        }
363        _ => {}
364    }
365}
366fn collect_pattern_names<'a>(pattern: &'a Pattern, names: &mut Vec<&'a str>) {
367    match pattern {
368        Pattern::Ident(n) => names.push(n),
369        Pattern::Record(fs) => {
370            for (_, p) in fs {
371                collect_pattern_names(p, names)
372            }
373        }
374        Pattern::List(ps)
375        | Pattern::Constructor { args: ps, .. }
376        | Pattern::Variant { args: ps, .. } => {
377            for p in ps {
378                collect_pattern_names(p, names)
379            }
380        }
381        Pattern::Ok(p) | Pattern::Err(p) | Pattern::Some(p) => collect_pattern_names(p, names),
382        _ => {}
383    }
384}