1use std::collections::HashMap;
4
5use ruso_runtime::opcode::Opcode as Instr;
6use ruso_runtime::{BytecodeProgram, EvidenceKind, ExtractSource, QualifiedMatch};
7
8use crate::script::Program;
9use crate::script::ast::{ListSource, Stmt, Value};
10use crate::spec_build::build_program_spec;
11
12#[derive(Debug, thiserror::Error)]
17pub enum CompileError {
18 #[error("script has match/evidence logic but no `name` metadata for the finding title")]
21 MissingFindingTitle,
22 #[error("`mitigation` may appear at most once; it is a single free-text field, not a list")]
26 DuplicateMitigation,
27}
28
29pub fn compile(program: &Program) -> Result<BytecodeProgram, CompileError> {
40 if program
44 .statements
45 .iter()
46 .filter(|s| matches!(s, Stmt::Mitigation(_)))
47 .count()
48 > 1
49 {
50 return Err(CompileError::DuplicateMitigation);
51 }
52 let spec = build_program_spec(&program.statements);
53 validate_finding_metadata(&spec.metadata, &program.statements)?;
54 let mut compiler = Compiler::new(spec);
55 compiler.emit_program(&program.statements);
56 Ok(compiler.finish())
57}
58
59fn validate_finding_metadata(
60 metadata: &ruso_runtime::CheckMetadata,
61 statements: &[Stmt],
62) -> Result<(), CompileError> {
63 if !statements.iter().any(needs_finding_title) {
64 return Ok(());
65 }
66 if metadata.name.is_some() {
67 return Ok(());
68 }
69 Err(CompileError::MissingFindingTitle)
70}
71
72fn needs_finding_title(stmt: &Stmt) -> bool {
73 match stmt {
74 Stmt::Match(_)
75 | Stmt::MatchAll(_)
76 | Stmt::MatchAny(_)
77 | Stmt::Assert(_)
78 | Stmt::Evidence(_) => true,
79 Stmt::If { body, .. } => body.iter().any(needs_finding_title),
80 Stmt::ForIn { body, .. } => body.iter().any(needs_finding_title),
81 _ => false,
82 }
83}
84
85struct Compiler {
86 spec: ruso_runtime::ProgramSpec,
87 code: Vec<Instr>,
88 strings: Vec<String>,
89 string_ids: HashMap<String, u32>,
90 payloads: Vec<Vec<u8>>,
91 payload_ids: HashMap<Vec<u8>, u32>,
92 matchers: Vec<QualifiedMatch>,
93 extracts: Vec<ExtractSource>,
94 evidence: Vec<EvidenceKind>,
95}
96
97impl Compiler {
98 fn new(spec: ruso_runtime::ProgramSpec) -> Self {
99 Self {
100 spec,
101 code: Vec::new(),
102 strings: Vec::new(),
103 string_ids: HashMap::new(),
104 payloads: Vec::new(),
105 payload_ids: HashMap::new(),
106 matchers: Vec::new(),
107 extracts: Vec::new(),
108 evidence: Vec::new(),
109 }
110 }
111
112 fn finish(self) -> BytecodeProgram {
113 BytecodeProgram {
114 spec: self.spec,
115 code: self.code,
116 strings: self.strings,
117 payloads: self.payloads,
118 matchers: self.matchers,
119 extracts: self.extracts,
120 evidence: self.evidence,
121 }
122 }
123
124 fn str_id(&mut self, value: impl Into<String>) -> u32 {
125 let value = value.into();
126 if let Some(&id) = self.string_ids.get(&value) {
127 return id;
128 }
129 let id = self.strings.len() as u32;
130 self.string_ids.insert(value.clone(), id);
131 self.strings.push(value);
132 id
133 }
134
135 fn string_span(&mut self, values: &[String]) -> (u32, u16) {
136 let start = self.strings.len() as u32;
137 for value in values {
138 self.strings.push(value.clone());
139 }
140 (start, values.len() as u16)
141 }
142
143 fn payload_id(&mut self, bytes: Vec<u8>) -> u32 {
144 if let Some(&id) = self.payload_ids.get(&bytes) {
145 return id;
146 }
147 let id = self.payloads.len() as u32;
148 self.payload_ids.insert(bytes.clone(), id);
149 self.payloads.push(bytes);
150 id
151 }
152
153 fn matcher_id(&mut self, matcher: QualifiedMatch) -> u32 {
154 let id = self.matchers.len() as u32;
155 self.matchers.push(matcher);
156 id
157 }
158
159 fn extract_id(&mut self, source: ExtractSource) -> u32 {
160 let id = self.extracts.len() as u32;
161 self.extracts.push(source);
162 id
163 }
164
165 fn evidence_id(&mut self, kind: EvidenceKind) -> u32 {
166 let id = self.evidence.len() as u32;
167 self.evidence.push(kind);
168 id
169 }
170
171 fn emit(&mut self, instr: Instr) -> usize {
172 let pc = self.code.len();
173 self.code.push(instr);
174 pc
175 }
176
177 fn emit_program(&mut self, statements: &[Stmt]) {
178 for stmt in statements {
179 self.emit_stmt(stmt);
180 }
181 }
182
183 fn emit_stmt(&mut self, stmt: &Stmt) {
184 match stmt {
185 Stmt::Set { name, value } => {
186 let name = self.str_id(name);
187 match value {
188 Value::String(value) => {
189 let value = self.str_id(value);
190 self.emit(Instr::Set { name, value });
191 }
192 Value::List(values) => {
193 let (start, len) = self.string_span(values);
194 self.emit(Instr::SetList { name, start, len });
195 }
196 }
197 }
198 Stmt::Send { probe, payload } => {
199 let probe = self.str_id(probe);
200 let payload = payload.as_ref().map(|bytes| self.payload_id(bytes.clone()));
201 self.emit(Instr::Send { probe, payload });
202 }
203 Stmt::Match(matcher) => {
204 let id = self.matcher_id(matcher.clone());
205 self.emit(Instr::Match(id));
206 }
207 Stmt::MatchAll(matchers) => {
208 let start = self.matchers.len() as u32;
209 for matcher in matchers {
210 self.matchers.push(matcher.clone());
211 }
212 let len = (self.matchers.len() as u32 - start) as u16;
213 self.emit(Instr::MatchAll { start, len });
214 }
215 Stmt::MatchAny(matchers) => {
216 let start = self.matchers.len() as u32;
217 for matcher in matchers {
218 self.matchers.push(matcher.clone());
219 }
220 let len = (self.matchers.len() as u32 - start) as u16;
221 self.emit(Instr::MatchAny { start, len });
222 }
223 Stmt::Assert(matcher) => {
224 let id = self.matcher_id(matcher.clone());
225 self.emit(Instr::Assert(id));
226 }
227 Stmt::Extract { name, source } => {
228 let name = self.str_id(name);
229 let source = self.extract_id(source.clone());
230 self.emit(Instr::Extract { name, source });
231 }
232 Stmt::If { condition, body } => {
233 let matcher = self.matcher_id(condition.clone());
234 let if_pc = self.emit(Instr::IfMatch {
235 matcher,
236 else_pc: 0,
237 });
238 self.emit_program(body);
239 let else_pc = self.code.len() as u32;
240 self.code[if_pc] = Instr::IfMatch { matcher, else_pc };
241 }
242 Stmt::ForIn { item, list, body } => {
243 let item = self.str_id(item);
244 let enter = match list {
245 ListSource::Literal(values) => {
246 let (start, len) = self.string_span(values);
247 Instr::ForList {
248 item,
249 start,
250 len,
251 end_pc: 0,
252 }
253 }
254 ListSource::Variable(name) => {
255 let list = self.str_id(name);
256 Instr::ForVar {
257 item,
258 list,
259 end_pc: 0,
260 }
261 }
262 };
263 let for_pc = self.emit(enter);
264 self.emit_program(body);
265 self.emit(Instr::LoopBack);
266 let end_pc = self.code.len() as u32;
267 self.code[for_pc] = match self.code[for_pc].clone() {
268 Instr::ForList {
269 item, start, len, ..
270 } => Instr::ForList {
271 item,
272 start,
273 len,
274 end_pc,
275 },
276 Instr::ForVar { item, list, .. } => Instr::ForVar { item, list, end_pc },
277 other => other,
278 };
279 }
280 Stmt::Break => {
281 self.emit(Instr::Break);
282 }
283 Stmt::Save { request, alias } => {
284 let from = self.str_id(request);
285 let to = self.str_id(alias);
286 self.emit(Instr::Save { from, to });
287 }
288 Stmt::Evidence(kind) => {
289 let id = self.evidence_id(kind.clone());
290 self.emit(Instr::Evidence(id));
291 }
292 Stmt::Retry { request, count } => {
293 let probe = self.str_id(request);
294 self.emit(Instr::Retry {
295 probe,
296 count: *count,
297 });
298 }
299 Stmt::RetryDelay(value) => {
300 let id = self.str_id(value);
301 self.emit(Instr::RetryDelay(id));
302 }
303 Stmt::Sleep(value) => {
304 let id = self.str_id(value);
305 self.emit(Instr::Sleep(id));
306 }
307 Stmt::Stop => {
308 self.emit(Instr::Stop);
309 }
310 Stmt::Fail => {
311 self.emit(Instr::Fail);
312 }
313 Stmt::Continue => {
314 self.emit(Instr::Continue);
315 }
316 Stmt::Exit => {
317 self.emit(Instr::Exit);
318 }
319 Stmt::Name(_)
320 | Stmt::Description(_)
321 | Stmt::Impact(_)
322 | Stmt::Severity(_)
323 | Stmt::Author(_)
324 | Stmt::Cve(_)
325 | Stmt::Cwe(_)
326 | Stmt::Reference(_)
327 | Stmt::Cvss(_)
328 | Stmt::CvssScore(_)
329 | Stmt::Mitigation(_)
330 | Stmt::Tag(_)
331 | Stmt::Version(_)
332 | Stmt::Family(_)
333 | Stmt::Http { .. }
334 | Stmt::Dns(_)
335 | Stmt::Tcp(_)
336 | Stmt::Udp(_) => {}
337 }
338 }
339}
340
341#[cfg(test)]
342mod tests {
343 use ruso_runtime::opcode::Opcode as Instr;
344
345 use crate::script::Program;
346 use crate::script::ast::{
347 CmpOp, CmpValue, FieldKind, MatchPredicate, QualifiedField, QualifiedMatch, Stmt,
348 };
349
350 use super::{CompileError, compile};
351
352 #[test]
353 fn compile_skips_metadata_and_probe_definitions() {
354 let program = Program {
355 statements: vec![
356 Stmt::Name("Check".into()),
357 Stmt::Http {
358 name: "home".into(),
359 items: vec![],
360 },
361 Stmt::Send {
362 probe: "home".into(),
363 payload: None,
364 },
365 Stmt::Match(QualifiedMatch {
366 field: QualifiedField {
367 target: "home".into(),
368 kind: FieldKind::Status,
369 },
370 predicate: MatchPredicate::Compare {
371 op: CmpOp::Eq,
372 value: CmpValue::Number(200),
373 },
374 }),
375 ],
376 };
377 let bytecode = compile(&program).unwrap();
378 assert_eq!(bytecode.code.len(), 2);
379 assert!(matches!(bytecode.code[0], Instr::Send { .. }));
380 assert!(matches!(bytecode.code[1], Instr::Match(_)));
381 }
382
383 #[test]
384 fn compile_rejects_match_without_finding_title() {
385 let program = Program {
386 statements: vec![
387 Stmt::Send {
388 probe: "home".into(),
389 payload: None,
390 },
391 Stmt::Match(QualifiedMatch {
392 field: QualifiedField {
393 target: "home".into(),
394 kind: FieldKind::Status,
395 },
396 predicate: MatchPredicate::Compare {
397 op: CmpOp::Eq,
398 value: CmpValue::Number(200),
399 },
400 }),
401 ],
402 };
403 assert!(matches!(
404 compile(&program),
405 Err(CompileError::MissingFindingTitle)
406 ));
407 }
408
409 #[test]
410 fn compile_rejects_duplicate_mitigation() {
411 let program = Program {
412 statements: vec![
413 Stmt::Name("Dup".into()),
414 Stmt::Mitigation("first".into()),
415 Stmt::Mitigation("second".into()),
416 ],
417 };
418 assert!(matches!(
419 compile(&program),
420 Err(CompileError::DuplicateMitigation)
421 ));
422 }
423
424 #[test]
425 fn compile_accepts_single_mitigation() {
426 let program = Program {
427 statements: vec![
428 Stmt::Name("Single".into()),
429 Stmt::Mitigation("patch it".into()),
430 ],
431 };
432 assert!(compile(&program).is_ok());
433 }
434}