Skip to main content

rhwp/render_backend/
fixture.rs

1//! 장면 픽스처 스키마 — JSON 한 장이 한 계약.
2//!
3//! 픽스처는 실제 HWP 가 아니다. `SceneSpec` 을 직렬화한 것이며,
4//! 통합 시험이 디렉터리를 읽어 TraceBackend 산출물과 expected_trace 를
5//! 맞댄다. 생성기는 `tools/render_backend/gen_m06f.py` 다.
6
7use std::path::{Path, PathBuf};
8
9use super::catalog::OpBounds;
10use super::scenes::{SceneOp, SceneSpec};
11
12/// 픽스처 JSON 한 장.
13#[derive(Debug, Clone, PartialEq)]
14pub struct FixtureScene {
15    /// 스키마 버전.
16    pub schema: u32,
17    /// 장면.
18    pub scene: SceneSpec,
19    /// 기대 추적 줄. `None` 이면 시험이 직접 계산한다.
20    pub expected_trace: Option<Vec<String>>,
21    /// 기대 replay kind 순서.
22    pub expected_kinds: Vec<String>,
23}
24
25impl FixtureScene {
26    /// 현재 스키마 버전.
27    pub const SCHEMA: u32 = 1;
28
29    /// `SceneSpec` 에서 만든다. expected_trace 는 비운다.
30    pub fn from_scene(scene: SceneSpec) -> Self {
31        let expected_kinds = scene
32            .expected_replay_kinds()
33            .into_iter()
34            .map(str::to_string)
35            .collect();
36        Self {
37            schema: Self::SCHEMA,
38            scene,
39            expected_trace: None,
40            expected_kinds,
41        }
42    }
43
44    /// JSON 객체로 직렬화한다. 외부 crate 없이 손으로 쓴다.
45    pub fn to_json_value(&self) -> String {
46        let mut ops = String::new();
47        for (i, op) in self.scene.ops.iter().enumerate() {
48            if i > 0 {
49                ops.push(',');
50            }
51            ops.push_str(&format!(
52                "{{\"kind\":{},\"x\":{},\"y\":{},\"w\":{},\"h\":{},\"text\":{},\"gradient\":{},\"image\":{}}}",
53                json_string(&op.kind),
54                json_f64(op.bounds.x),
55                json_f64(op.bounds.y),
56                json_f64(op.bounds.width),
57                json_f64(op.bounds.height),
58                match &op.text {
59                    Some(t) => json_string(t),
60                    None => "null".into(),
61                },
62                if op.gradient { "true" } else { "false" },
63                if op.image { "true" } else { "false" },
64            ));
65        }
66        let kinds: Vec<String> = self.expected_kinds.iter().map(|k| json_string(k)).collect();
67        let trace = match &self.expected_trace {
68            Some(lines) => {
69                let parts: Vec<String> = lines.iter().map(|l| json_string(l)).collect();
70                format!("[{}]", parts.join(","))
71            }
72            None => "null".into(),
73        };
74        format!(
75            "{{\n  \"schema\": {},\n  \"id\": {},\n  \"width\": {},\n  \"height\": {},\n  \"contract\": {},\n  \"ops\": [{}],\n  \"expectedKinds\": [{}],\n  \"expectedTrace\": {}\n}}\n",
76            self.schema,
77            json_string(&self.scene.id),
78            json_f64(self.scene.width),
79            json_f64(self.scene.height),
80            json_string(&self.scene.contract),
81            ops,
82            kinds.join(","),
83            trace
84        )
85    }
86}
87
88fn json_string(value: &str) -> String {
89    let mut out = String::from("\"");
90    for ch in value.chars() {
91        match ch {
92            '"' => out.push_str("\\\""),
93            '\\' => out.push_str("\\\\"),
94            '\n' => out.push_str("\\n"),
95            '\r' => out.push_str("\\r"),
96            '\t' => out.push_str("\\t"),
97            c if c.is_control() => out.push_str(&format!("\\u{:04x}", c as u32)),
98            c => out.push(c),
99        }
100    }
101    out.push('"');
102    out
103}
104
105fn json_f64(value: f64) -> String {
106    if value.fract() == 0.0 && value.abs() < 1e15 {
107        format!("{:.1}", value)
108    } else {
109        format!("{}", value)
110    }
111}
112
113/// 최소 JSON 객체 파서 — 픽스처 필드만 읽는다.
114pub fn parse_fixture_json(text: &str) -> Result<FixtureScene, String> {
115    let value = MiniJson::parse(text)?;
116    let obj = value.as_object().ok_or("픽스처 루트는 객체여야 한다")?;
117    let schema = obj.get_u32("schema")?;
118    if schema != FixtureScene::SCHEMA {
119        return Err(format!("지원하지 않는 schema {schema}"));
120    }
121    let id = obj.get_string("id")?;
122    let width = obj.get_f64("width")?;
123    let height = obj.get_f64("height")?;
124    let contract = obj.get_string("contract")?;
125    let ops_val = obj.get("ops").ok_or("ops 없음")?;
126    let ops_arr = ops_val.as_array().ok_or("ops 는 배열")?;
127    let mut ops = Vec::new();
128    for item in ops_arr {
129        let op = item.as_object().ok_or("op 는 객체")?;
130        let mut scene_op = SceneOp {
131            kind: op.get_string("kind")?,
132            bounds: OpBounds {
133                x: op.get_f64("x")?,
134                y: op.get_f64("y")?,
135                width: op.get_f64("w")?,
136                height: op.get_f64("h")?,
137            },
138            text: op.get_string_opt("text")?,
139            gradient: op.get_bool("gradient").unwrap_or(false),
140            image: op.get_bool("image").unwrap_or(false),
141        };
142        if scene_op.kind.is_empty() {
143            return Err("빈 kind".into());
144        }
145        let _ = &mut scene_op;
146        ops.push(scene_op);
147    }
148    let kinds_val = obj.get("expectedKinds").ok_or("expectedKinds 없음")?;
149    let kinds_arr = kinds_val.as_array().ok_or("expectedKinds 는 배열")?;
150    let mut expected_kinds = Vec::new();
151    for item in kinds_arr {
152        expected_kinds.push(item.as_str().ok_or("kind 는 문자열")?.to_string());
153    }
154    let expected_trace = match obj.get("expectedTrace") {
155        None | Some(MiniJson::Null) => None,
156        Some(MiniJson::Array(lines)) => {
157            let mut out = Vec::new();
158            for line in lines {
159                out.push(line.as_str().ok_or("trace 줄은 문자열")?.to_string());
160            }
161            Some(out)
162        }
163        Some(_) => return Err("expectedTrace 는 배열 또는 null".into()),
164    };
165    Ok(FixtureScene {
166        schema,
167        scene: SceneSpec {
168            id,
169            width,
170            height,
171            ops,
172            contract,
173        },
174        expected_trace,
175        expected_kinds,
176    })
177}
178
179/// 픽스처 디렉터리. `CARGO_MANIFEST_DIR` 기준.
180pub fn fixture_root(manifest_dir: &Path) -> PathBuf {
181    manifest_dir
182        .join("tests")
183        .join("fixtures")
184        .join("render_backend")
185}
186
187/// `scenes/` 아래 JSON 을 이름 순으로 읽는다.
188pub fn load_scene_fixtures(manifest_dir: &Path) -> Result<Vec<(PathBuf, FixtureScene)>, String> {
189    let dir = fixture_root(manifest_dir).join("scenes");
190    if !dir.is_dir() {
191        return Err(format!("픽스처 디렉터리가 없다: {}", dir.display()));
192    }
193    let mut paths: Vec<PathBuf> = std::fs::read_dir(&dir)
194        .map_err(|err| err.to_string())?
195        .filter_map(|entry| entry.ok().map(|e| e.path()))
196        .filter(|p| p.extension().and_then(|e| e.to_str()) == Some("json"))
197        .collect();
198    paths.sort();
199    let mut out = Vec::new();
200    for path in paths {
201        let text =
202            std::fs::read_to_string(&path).map_err(|err| format!("{}: {err}", path.display()))?;
203        let fixture =
204            parse_fixture_json(&text).map_err(|err| format!("{}: {err}", path.display()))?;
205        out.push((path, fixture));
206    }
207    Ok(out)
208}
209
210/// 매니페스트 JSON (`manifest.json`) 의 최소 필드.
211#[derive(Debug, Clone, PartialEq)]
212pub struct FixtureManifest {
213    /// 스키마.
214    pub schema: u32,
215    /// 장면 수.
216    pub scene_count: usize,
217    /// 장면 id 목록.
218    pub ids: Vec<String>,
219}
220
221/// 매니페스트를 읽는다.
222pub fn load_manifest(manifest_dir: &Path) -> Result<FixtureManifest, String> {
223    let path = fixture_root(manifest_dir).join("manifest.json");
224    let text = std::fs::read_to_string(&path).map_err(|err| err.to_string())?;
225    let value = MiniJson::parse(&text)?;
226    let obj = value.as_object().ok_or("매니페스트 루트는 객체")?;
227    let schema = obj.get_u32("schema")?;
228    let scene_count = obj.get_u32("sceneCount")? as usize;
229    let ids_val = obj.get("ids").ok_or("ids 없음")?;
230    let ids_arr = ids_val.as_array().ok_or("ids 는 배열")?;
231    let mut ids = Vec::new();
232    for item in ids_arr {
233        ids.push(item.as_str().ok_or("id 는 문자열")?.to_string());
234    }
235    if ids.len() != scene_count {
236        return Err(format!("sceneCount {scene_count} != ids {}", ids.len()));
237    }
238    Ok(FixtureManifest {
239        schema,
240        scene_count,
241        ids,
242    })
243}
244
245#[derive(Debug, Clone, PartialEq)]
246enum MiniJson {
247    Null,
248    Bool(bool),
249    Number(f64),
250    String(String),
251    Array(Vec<MiniJson>),
252    Object(MiniObject),
253}
254
255#[derive(Debug, Clone, PartialEq)]
256struct MiniObject {
257    entries: Vec<(String, MiniJson)>,
258}
259
260impl MiniObject {
261    fn get(&self, key: &str) -> Option<&MiniJson> {
262        self.entries.iter().find(|(k, _)| k == key).map(|(_, v)| v)
263    }
264
265    fn get_string(&self, key: &str) -> Result<String, String> {
266        match self.get(key) {
267            Some(MiniJson::String(s)) => Ok(s.clone()),
268            Some(other) => Err(format!("{key} 는 문자열이어야 한다: {other:?}")),
269            None => Err(format!("{key} 없음")),
270        }
271    }
272
273    fn get_string_opt(&self, key: &str) -> Result<Option<String>, String> {
274        match self.get(key) {
275            None | Some(MiniJson::Null) => Ok(None),
276            Some(MiniJson::String(s)) => Ok(Some(s.clone())),
277            Some(other) => Err(format!("{key} 는 문자열 또는 null: {other:?}")),
278        }
279    }
280
281    fn get_f64(&self, key: &str) -> Result<f64, String> {
282        match self.get(key) {
283            Some(MiniJson::Number(n)) => Ok(*n),
284            Some(other) => Err(format!("{key} 는 숫자여야 한다: {other:?}")),
285            None => Err(format!("{key} 없음")),
286        }
287    }
288
289    fn get_u32(&self, key: &str) -> Result<u32, String> {
290        let n = self.get_f64(key)?;
291        if n < 0.0 || n.fract() != 0.0 || n > u32::MAX as f64 {
292            return Err(format!("{key} 는 u32 가 아니다: {n}"));
293        }
294        Ok(n as u32)
295    }
296
297    fn get_bool(&self, key: &str) -> Option<bool> {
298        match self.get(key) {
299            Some(MiniJson::Bool(b)) => Some(*b),
300            _ => None,
301        }
302    }
303}
304
305impl MiniJson {
306    fn as_object(&self) -> Option<&MiniObject> {
307        match self {
308            MiniJson::Object(o) => Some(o),
309            _ => None,
310        }
311    }
312
313    fn as_array(&self) -> Option<&[MiniJson]> {
314        match self {
315            MiniJson::Array(a) => Some(a),
316            _ => None,
317        }
318    }
319
320    fn as_str(&self) -> Option<&str> {
321        match self {
322            MiniJson::String(s) => Some(s),
323            _ => None,
324        }
325    }
326
327    fn parse(text: &str) -> Result<Self, String> {
328        let mut p = Parser {
329            chars: text.chars().collect(),
330            i: 0,
331        };
332        let value = p.parse_value()?;
333        p.skip_ws();
334        if p.i != p.chars.len() {
335            return Err("JSON 뒤에 잔여 문자가 있다".into());
336        }
337        Ok(value)
338    }
339}
340
341struct Parser {
342    chars: Vec<char>,
343    i: usize,
344}
345
346impl Parser {
347    fn peek(&self) -> Option<char> {
348        self.chars.get(self.i).copied()
349    }
350
351    fn bump(&mut self) -> Option<char> {
352        let ch = self.peek()?;
353        self.i += 1;
354        Some(ch)
355    }
356
357    fn skip_ws(&mut self) {
358        while matches!(self.peek(), Some(c) if c.is_whitespace()) {
359            self.i += 1;
360        }
361    }
362
363    fn parse_value(&mut self) -> Result<MiniJson, String> {
364        self.skip_ws();
365        match self.peek() {
366            Some('n') => self.parse_lit("null", MiniJson::Null),
367            Some('t') => self.parse_lit("true", MiniJson::Bool(true)),
368            Some('f') => self.parse_lit("false", MiniJson::Bool(false)),
369            Some('"') => Ok(MiniJson::String(self.parse_string()?)),
370            Some('[') => self.parse_array(),
371            Some('{') => self.parse_object(),
372            Some(c) if c == '-' || c.is_ascii_digit() => Ok(MiniJson::Number(self.parse_number()?)),
373            Some(c) => Err(format!("예상치 못한 문자 {c}")),
374            None => Err("입력이 끝났다".into()),
375        }
376    }
377
378    fn parse_lit(&mut self, lit: &str, value: MiniJson) -> Result<MiniJson, String> {
379        for expected in lit.chars() {
380            match self.bump() {
381                Some(c) if c == expected => {}
382                _ => return Err(format!("{lit} 리터럴 불일치")),
383            }
384        }
385        Ok(value)
386    }
387
388    fn parse_string(&mut self) -> Result<String, String> {
389        if self.bump() != Some('"') {
390            return Err("문자열이 \" 로 시작하지 않는다".into());
391        }
392        let mut out = String::new();
393        loop {
394            match self.bump() {
395                Some('"') => return Ok(out),
396                Some('\\') => match self.bump() {
397                    Some('"') => out.push('"'),
398                    Some('\\') => out.push('\\'),
399                    Some('/') => out.push('/'),
400                    Some('b') => out.push('\u{0008}'),
401                    Some('f') => out.push('\u{000c}'),
402                    Some('n') => out.push('\n'),
403                    Some('r') => out.push('\r'),
404                    Some('t') => out.push('\t'),
405                    Some('u') => {
406                        let mut hex = String::new();
407                        for _ in 0..4 {
408                            hex.push(self.bump().ok_or("\\u 자리 부족")?);
409                        }
410                        let code = u32::from_str_radix(&hex, 16)
411                            .map_err(|_| format!("잘못된 \\u{hex}"))?;
412                        out.push(char::from_u32(code).ok_or("잘못된 유니코드")?);
413                    }
414                    Some(c) => return Err(format!("알 수 없는 이스케이프 \\{c}")),
415                    None => return Err("문자열 이스케이프가 끝났다".into()),
416                },
417                Some(c) => out.push(c),
418                None => return Err("문자열이 닫히지 않았다".into()),
419            }
420        }
421    }
422
423    fn parse_number(&mut self) -> Result<f64, String> {
424        let start = self.i;
425        if self.peek() == Some('-') {
426            self.i += 1;
427        }
428        while matches!(self.peek(), Some(c) if c.is_ascii_digit()) {
429            self.i += 1;
430        }
431        if self.peek() == Some('.') {
432            self.i += 1;
433            while matches!(self.peek(), Some(c) if c.is_ascii_digit()) {
434                self.i += 1;
435            }
436        }
437        if matches!(self.peek(), Some('e' | 'E')) {
438            self.i += 1;
439            if matches!(self.peek(), Some('+' | '-')) {
440                self.i += 1;
441            }
442            while matches!(self.peek(), Some(c) if c.is_ascii_digit()) {
443                self.i += 1;
444            }
445        }
446        let raw: String = self.chars[start..self.i].iter().collect();
447        raw.parse::<f64>()
448            .map_err(|_| format!("숫자 파싱 실패: {raw}"))
449    }
450
451    fn parse_array(&mut self) -> Result<MiniJson, String> {
452        if self.bump() != Some('[') {
453            return Err("[ 필요".into());
454        }
455        self.skip_ws();
456        let mut items = Vec::new();
457        if self.peek() == Some(']') {
458            self.i += 1;
459            return Ok(MiniJson::Array(items));
460        }
461        loop {
462            items.push(self.parse_value()?);
463            self.skip_ws();
464            match self.bump() {
465                Some(',') => continue,
466                Some(']') => return Ok(MiniJson::Array(items)),
467                _ => return Err("배열 , 또는 ] 필요".into()),
468            }
469        }
470    }
471
472    fn parse_object(&mut self) -> Result<MiniJson, String> {
473        if self.bump() != Some('{') {
474            return Err("{{ 필요".into());
475        }
476        self.skip_ws();
477        let mut entries = Vec::new();
478        if self.peek() == Some('}') {
479            self.i += 1;
480            return Ok(MiniJson::Object(MiniObject { entries }));
481        }
482        loop {
483            self.skip_ws();
484            let key = self.parse_string()?;
485            self.skip_ws();
486            if self.bump() != Some(':') {
487                return Err(": 필요".into());
488            }
489            let value = self.parse_value()?;
490            entries.push((key, value));
491            self.skip_ws();
492            match self.bump() {
493                Some(',') => continue,
494                Some('}') => return Ok(MiniJson::Object(MiniObject { entries })),
495                _ => return Err("객체 , 또는 }} 필요".into()),
496            }
497        }
498    }
499}