1use crate::ast::*;
4use crate::check::{check_submission, CheckEnv};
5use crate::{Budget, DiagCode, Diagnostic, Engine, Env, Host, Span, Value};
6use std::collections::HashSet;
7use std::sync::atomic::{AtomicU64, Ordering};
8mod prepare;
9mod source_limits;
10#[cfg(test)]
11mod tests;
12mod values;
13#[cfg(test)]
14mod validation_tests;
15#[cfg(test)]
16mod binding_validation_tests;
17
18static NEXT_SESSION: AtomicU64 = AtomicU64::new(1);
19
20#[derive(Clone, Debug)]
21pub struct SessionLimits {
22 pub submission_bytes: usize,
23 pub retained_source_bytes: usize,
24 pub declarations: usize,
25 pub bindings: usize,
26 pub retained_value_bytes: usize,
29 pub revisions: u64,
30 pub call_depth: u32,
32 pub expression_depth: u32,
34}
35impl Default for SessionLimits {
36 fn default() -> Self {
37 Self {
38 submission_bytes: 64 * 1024,
39 retained_source_bytes: 1024 * 1024,
40 declarations: 1024,
41 bindings: 1024,
42 retained_value_bytes: crate::SENTINEL_BYTES as usize,
43 revisions: 1024,
44 call_depth: 8,
45 expression_depth: 64,
46 }
47 }
48}
49
50#[derive(Debug)]
54pub struct SubmissionError {
55 pub diagnostic: Diagnostic,
56 pub execution_attempted: bool,
57 pub host_reconciliation_required: bool,
58 pub active_revision: u64,
59}
60
61#[derive(Debug)]
62pub struct SubmissionResult {
63 pub value: Value,
64 pub revision: u64,
65}
66
67enum Body {
68 Program(Program),
69 Expression(Expr),
70}
71
72pub struct CheckedSubmission {
75 owner: u64,
76 base_revision: u64,
77 source: String,
78 definitions: Program,
79 checked: CheckEnv,
80 mutables: HashSet<String>,
81 body: Body,
82 replace_env: bool,
83}
84
85pub struct SessionBindings<'a> {
88 env: &'a Env,
89}
90impl SessionBindings<'_> {
91 pub fn value(&self, name: &str) -> Option<&Value> {
92 self.env.vars.get(name)
93 }
94}
95pub struct SourceSession {
96 owner: u64,
97 revision: u64,
98 limits: SessionLimits,
99 grants: Vec<String>,
101 definitions: Program,
102 checked: CheckEnv,
103 mutables: HashSet<String>,
104 env: Env,
105 sources: Vec<String>,
106 source_bytes: usize,
107}
108
109impl Default for SourceSession {
110 fn default() -> Self {
111 Self::new(Vec::new(), SessionLimits::default())
112 }
113}
114
115impl SourceSession {
116 pub fn new(grants: Vec<String>, limits: SessionLimits) -> Self {
117 Self {
118 owner: NEXT_SESSION.fetch_add(1, Ordering::Relaxed),
119 revision: 0,
120 limits,
121 grants,
122 definitions: Program {
123 span: Span::point(0),
124 module: None,
125 imports: Vec::new(),
126 prefixes: Vec::new(),
127 locales: Vec::new(),
128 requires: Vec::new(),
129 items: Vec::new(),
130 },
131 checked: CheckEnv::default(),
132 mutables: HashSet::new(),
133 env: Env::default(),
134 sources: Vec::new(),
135 source_bytes: 0,
136 }
137 }
138 pub fn revision(&self) -> u64 {
139 self.revision
140 }
141 pub fn bindings(&self) -> SessionBindings<'_> {
143 SessionBindings { env: &self.env }
144 }
145 pub fn value(&self, name: &str) -> Option<&Value> {
146 self.env.vars.get(name)
147 }
148 pub fn is_mutable(&self, name: &str) -> bool {
149 self.mutables.contains(name)
150 }
151 pub fn sources(&self) -> &[String] {
152 &self.sources
153 }
154 pub fn binding_type(&self, name: &str) -> Option<String> {
155 self.checked.get(name).map(|t| format!("{t:?}"))
156 }
157 fn error(&self, diagnostic: Diagnostic, attempted: bool) -> SubmissionError {
158 SubmissionError {
159 diagnostic,
160 execution_attempted: attempted,
161 host_reconciliation_required: attempted,
164 active_revision: self.revision,
165 }
166 }
167 pub fn submit<H: Host>(
168 &mut self,
169 source: &str,
170 host: &mut H,
171 budget: Budget,
172 ) -> Result<SubmissionResult, SubmissionError> {
173 self.submit_validated(source, host, budget, |_| Ok(()))
174 }
175 pub fn submit_validated<H: Host, F: FnOnce(&Value) -> Result<(), Diagnostic>>(
178 &mut self,
179 source: &str,
180 host: &mut H,
181 budget: Budget,
182 validate: F,
183 ) -> Result<SubmissionResult, SubmissionError> {
184 let candidate = self.prepare(source).map_err(|e| self.error(e, false))?;
185 self.execute_validated(candidate, host, budget, validate)
186 }
187 pub fn submit_validated_bindings<H: Host, F>(
190 &mut self,
191 source: &str,
192 host: &mut H,
193 budget: Budget,
194 validate: F,
195 ) -> Result<SubmissionResult, SubmissionError>
196 where
197 F: FnOnce(&Value, SessionBindings<'_>, &mut H) -> Result<(), Diagnostic>,
198 {
199 let candidate = self.prepare(source).map_err(|e| self.error(e, false))?;
200 self.execute_validated_bindings(candidate, host, budget, validate)
201 }
202 pub fn execute<H: Host>(
203 &mut self,
204 candidate: CheckedSubmission,
205 host: &mut H,
206 budget: Budget,
207 ) -> Result<SubmissionResult, SubmissionError> {
208 self.execute_validated(candidate, host, budget, |_| Ok(()))
209 }
210
211 pub fn apply_edit<H: Host>(
214 &mut self,
215 edit: &crate::projectional::Edit,
216 host: &mut H,
217 budget: Budget,
218 ) -> Result<SubmissionResult, SubmissionError> {
219 let candidate = self.prepare_edit(edit).map_err(|e| self.error(e, false))?;
220 self.execute(candidate, host, budget)
221 }
222
223 pub fn replace<H: Host>(
226 &mut self,
227 source: &str,
228 host: &mut H,
229 budget: Budget,
230 ) -> Result<SubmissionResult, SubmissionError> {
231 let candidate = self.prepare_replace(source).map_err(|e| self.error(e, false))?;
232 self.execute(candidate, host, budget)
233 }
234 pub fn execute_validated<H: Host, F: FnOnce(&Value) -> Result<(), Diagnostic>>(
238 &mut self,
239 candidate: CheckedSubmission,
240 host: &mut H,
241 budget: Budget,
242 validate: F,
243 ) -> Result<SubmissionResult, SubmissionError> {
244 self.execute_validated_bindings(candidate, host, budget, |value, _, _| validate(value))
245 }
246
247 pub fn execute_validated_bindings<H: Host, F>(
251 &mut self,
252 candidate: CheckedSubmission,
253 host: &mut H,
254 budget: Budget,
255 validate: F,
256 ) -> Result<SubmissionResult, SubmissionError>
257 where
258 F: FnOnce(&Value, SessionBindings<'_>, &mut H) -> Result<(), Diagnostic>,
259 {
260 if candidate.owner != self.owner || candidate.base_revision != self.revision {
261 return Err(self.error(
262 Diagnostic::new(
263 DiagCode::E701,
264 Span::point(0),
265 "checked submission belongs to another session or stale revision",
266 ),
267 false,
268 ));
269 }
270 let mut tentative = if candidate.replace_env {
271 Env::default()
272 } else {
273 self.env.clone()
274 };
275 crate::populate_import_aliases(&mut tentative, &candidate.definitions.imports)
276 .map_err(|e| self.error(e, false))?;
277 let mut budget = budget;
278 budget.workspace_left = budget
279 .workspace_left
280 .min(self.limits.retained_value_bytes as u64);
281 let mut engine = Engine::with_program(host, budget, &candidate.definitions);
282 engine.set_session_stack_limits(self.limits.call_depth, self.limits.expression_depth);
283 let result = match &candidate.body {
286 Body::Program(program) => engine.eval_program(program, &mut tentative),
287 Body::Expression(expr) => engine.eval_expr(expr, &mut tentative),
288 };
289 drop(engine);
290 let value = result.map_err(|e| self.error(e, true))?;
291 if tentative.vars.len() > self.limits.bindings {
292 return Err(self.error(
293 Diagnostic::new(
294 DiagCode::E400,
295 Span::point(0),
296 "session binding limit exceeded after evaluation",
297 ),
298 true,
299 ));
300 }
301 values::validate(&candidate.checked, &tentative).map_err(|e| self.error(e, true))?;
302 values::check_retained_size(&tentative, self.limits.retained_value_bytes)
303 .map_err(|e| self.error(e, true))?;
304 validate(&value, SessionBindings { env: &tentative }, host).map_err(|e| self.error(e, true))?;
305 self.env = tentative;
306 self.checked = candidate.checked;
307 self.mutables = candidate.mutables;
308 self.definitions = candidate.definitions;
309 if candidate.replace_env {
310 self.source_bytes = candidate.source.len();
311 self.sources = vec![candidate.source];
312 } else {
313 self.source_bytes += candidate.source.len();
314 self.sources.push(candidate.source);
315 }
316 self.revision += 1;
317 Ok(SubmissionResult {
318 value,
319 revision: self.revision,
320 })
321 }
322}