"""不透明 JSON 验证与原文往返:独立事件库 Rust 对照,固定七轮,不共享 Dever runtime。""" import argparse import json import os from pathlib import Path import statistics from scale import execute, fingerprint DEVER = '''loop measure(source: Text, n: Int) (total: Int) | each iteration in range(0, n) | result | | total | sum length(dever.json.toText(dever.json.fromText(source))) | cmd bench = app.measure ''' # 独立实现使用库的高层事件接口和递归遍历,不引用 Dever 的类型、验证器或生成代码。 RUST = r'''use json_event_parser::{JsonEvent, SliceJsonParser}; use std::{borrow::Cow, collections::HashSet}; fn value<'a>(event: JsonEvent<'a>, parser: &mut SliceJsonParser<'a>, count: &mut usize, depth: usize) -> Result<(), String> { *count += 1; if *count > 65536 { return Err("value limit".into()); } match event { JsonEvent::StartArray => { if depth == 64 { return Err("depth limit".into()); } loop { let event = parser.parse_next().map_err(|e| e.to_string())?; if event == JsonEvent::EndArray { break; } value(event, parser, count, depth + 1)?; } } JsonEvent::StartObject => { if depth == 64 { return Err("depth limit".into()); } let mut names: HashSet> = HashSet::new(); loop { let event = parser.parse_next().map_err(|e| e.to_string())?; if event == JsonEvent::EndObject { break; } let JsonEvent::ObjectKey(name) = event else { return Err("key expected".into()); }; if !names.insert(name) { return Err("duplicate key".into()); } let event = parser.parse_next().map_err(|e| e.to_string())?; value(event, parser, count, depth + 1)?; } } JsonEvent::String(_) | JsonEvent::Number(_) | JsonEvent::Boolean(_) | JsonEvent::Null => {} _ => return Err("value expected".into()), } Ok(()) } fn validated(source: String) -> Result { if source.len() > 16 * 1024 * 1024 { return Err("byte limit".into()); } let mut parser = SliceJsonParser::new(source.as_bytes()); let first = parser.parse_next().map_err(|e| e.to_string())?; value(first, &mut parser, &mut 0, 0)?; if parser.parse_next().map_err(|e| e.to_string())? != JsonEvent::Eof { return Err("trailing content".into()); } Ok(source) } fn main() { let args = std::env::args().collect::>(); let count: i64 = args[2].parse().unwrap(); let mut total = 0i64; for _ in 0..count { let raw = validated(args[1].clone()).unwrap(); total = total.checked_add(raw.chars().count() as i64).unwrap(); } println!("{total}"); } ''' def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--compiler', type=Path, required=True) parser.add_argument('--output', type=Path, required=True) parser.add_argument('--core-source', type=Path, required=True) parser.add_argument('--iterations', type=int, default=1000) args = parser.parse_args() compiler = args.compiler.resolve(strict=True) root = args.output.resolve() root.mkdir(parents=True, exist_ok=False) core = args.core_source.resolve(strict=True) inputs = [core / 'rust/Cargo.lock'] inputs += sorted(path for path in (core / 'rust/src/runtime').rglob('*') if path.is_file() and path.suffix in {'.rs', '.toml'}) inputs += sorted((core / 'lib').rglob('*.dv')) source_hashes = {str(path.relative_to(core)): fingerprint(path) for path in inputs} for path in inputs: saved = root / 'inputs' / path.relative_to(core) saved.parent.mkdir(parents=True, exist_ok=True) saved.write_bytes(path.read_bytes()) for name in ['json_roundtrip.py', 'scale.py']: (root / name).write_bytes(Path(__file__).with_name(name).read_bytes()) source = '[\n' + ',\n'.join('{"number":1e9999,"text":"雪\\u96ea","flags":[true,null]}' for _ in range(1000)) + '\n]' (root / 'input.json').write_text(source) os.environ['CARGO_BUILD_JOBS'] = '1' report = dict(compiler=str(compiler), compiler_sha256=fingerprint(compiler), driver_sha256=fingerprint(root / 'json_roundtrip.py'), input_sha256=fingerprint(root / 'input.json'), iterations=args.iterations, rounds=7, builds=[], samples=[], core_source=str(core), source_hashes=source_hashes, scope='Whole process: validated owned raw text, no AST, exact raw number/whitespace preservation, then Unicode scalar length. Both use json-event-parser 0.2.3. Rust has independent traversal, no Dever runtime. Dever additionally decodes CMD JSON.', missing=['old Dever on this workload', 'Go with equivalent Unicode/duplicate/budget contract'], memory_scope='wait4 may include Python fork; not application-only RSS', environment={name: Path('/sys/fs/cgroup', name).read_text().strip() for name in ['cpu.max', 'memory.max']}) def save(): (root / 'results.json').write_text(json.dumps(report, indent=2) + '\n') programs = {} for language, text in [('dever', DEVER), ('rust', RUST)]: case = root / language case.mkdir() path = case / ('main.dever' if language == 'dever' else 'main.rs') path.write_text(text) binary = case / 'program' if language == 'dever': formatted = execute([str(compiler), 'fmt', str(path)], case, 'format', 30) if formatted['exit_code']: raise SystemExit(formatted['stderr']) command = [str(compiler), 'build', str(path), '--output', str(binary)] else: (case / 'Cargo.toml').write_text('''[package] name = "json-reference" version = "0.0.1" edition = "2024" [[bin]] name = "json-reference" path = "main.rs" [dependencies] json-event-parser = "=0.2.3" [profile.release] lto = "fat" codegen-units = 1 overflow-checks = true strip = "symbols" ''') command = ['cargo', '+1.95.0', 'build', '--offline', '--release', '--manifest-path', str(case / 'Cargo.toml'), '--target-dir', str(case / 'target')] binary = case / 'target/release/json-reference' build = dict(language=language, source_sha256=fingerprint(path), **execute(command, case, 'build', 900)) report['builds'].append(build) save() if build['exit_code']: raise SystemExit(build['stderr']) build['binary_sha256'] = fingerprint(binary) programs[language] = binary for repeat in range(-1, 7): assert source_hashes == {str(path.relative_to(core)): fingerprint(path) for path in inputs}, 'runtime/library inputs changed during measurement' for language in (['dever', 'rust'] if repeat % 2 else ['rust', 'dever']): binary = programs[language] command = [str(binary), 'main.main.bench', json.dumps(dict(source=source, n=args.iterations), ensure_ascii=False)] if language == 'dever' else [str(binary), source, str(args.iterations)] row = dict(language=language, repeat=repeat, **execute(command, binary.parent, f'run-{repeat}', 60)) output = Path(row['stdout']).read_text() row['expected'] = len(source) * args.iterations row['correct'] = row['exit_code'] == 0 and (json.loads(output)['data'] if language == 'dever' else int(output)) == row['expected'] report['samples'].append(row) save() print(json.dumps({key: row[key] for key in ['language', 'repeat', 'seconds', 'correct']}), flush=True) if not row['correct']: raise SystemExit(row['stderr']) report['medians'] = {language: statistics.median(row['seconds'] for row in report['samples'] if row['language'] == language and row['repeat'] >= 0) for language in programs} save() print(json.dumps(report['medians']), flush=True) if __name__ == '__main__': main()