Skip to main content

nativeview_codegen/frontend/rn_spec/
mod.rs

1//! Recursive-descent parser for React Native Fabric `*NativeComponent.{ts,js}`
2//! and TurboModule `Native*.{ts,js}` specifications (both TypeScript and Flow syntax).
3
4mod calls;
5pub mod lexer;
6mod lowering;
7mod syntax;
8
9use std::collections::{HashMap, HashSet};
10use std::path::{Path, PathBuf};
11
12use crate::error::CodegenError;
13use crate::schema::export::{
14    CommandSpec, ComponentOptions, DefaultValue, EventBubbling, EventSpec, ObjectField, ParamSpec,
15    ParsedRnSpec, PropSpec, PropType, RnComponentSpec, TurboModuleMethod, TurboModuleSpec,
16};
17use lexer::{tokenize, Token, TokenKind};
18
19/// Parses a React Native Fabric component or TurboModule specification from source text.
20pub fn parse_rn_spec(source: &str) -> Result<ParsedRnSpec, CodegenError> {
21    let tokens = tokenize(source)?;
22    let mut parser = Parser::new(tokens);
23    parser.parse_file()
24}
25
26/// Parses a React Native spec file from disk.
27///
28/// Automatically follows relative re-export wrapper files (common in React Native's
29/// `Libraries/**/*NativeComponent.js` which re-export from `src/private/.../specs/...`).
30pub fn parse_rn_spec_file(path: &Path) -> Result<ParsedRnSpec, CodegenError> {
31    parse_rn_spec_file_inner(path, 0)
32}
33
34fn parse_rn_spec_file_inner(path: &Path, depth: usize) -> Result<ParsedRnSpec, CodegenError> {
35    if depth > 4 {
36        return Err(CodegenError::validation(format!(
37            "exceeded max re-export indirection depth while reading {}",
38            path.display()
39        )));
40    }
41    let source = std::fs::read_to_string(path)
42        .map_err(|e| CodegenError::io(path.display().to_string(), e))?;
43
44    match parse_rn_spec(&source) {
45        Ok(spec) => Ok(spec),
46        Err(orig_err) => {
47            if let Some(target_rel) = detect_reexport_target(&source)
48                && let Some(resolved) = resolve_relative_spec(path, &target_rel)
49            {
50                return parse_rn_spec_file_inner(&resolved, depth + 1);
51            }
52            Err(orig_err)
53        }
54    }
55}
56
57fn detect_reexport_target(source: &str) -> Option<String> {
58    let tokens = tokenize(source).ok()?;
59    for (i, tok) in tokens.iter().enumerate() {
60        if matches!(&tok.kind, TokenKind::Ident(s) if s == "from")
61            && let Some(Token {
62                kind: TokenKind::StringLit(rel),
63                ..
64            }) = tokens.get(i + 1)
65            && rel.starts_with('.')
66        {
67            return Some(rel.clone());
68        }
69    }
70    None
71}
72
73fn resolve_relative_spec(base_file: &Path, rel: &str) -> Option<PathBuf> {
74    let parent = base_file.parent()?;
75    let candidate = parent.join(rel);
76    if candidate.is_file() {
77        return Some(candidate);
78    }
79    for ext in ["ts", "tsx", "js", "jsx"] {
80        let with_ext = parent.join(format!("{rel}.{ext}"));
81        if with_ext.is_file() {
82            return Some(with_ext);
83        }
84    }
85    None
86}
87
88// ---------------------------------------------------------------------------
89// Internal AST collected in pass 1 before resolving aliases into final IR.
90// ---------------------------------------------------------------------------
91
92#[derive(Debug, Clone)]
93enum TypeExpr {
94    Named {
95        name: String,
96        args: Vec<TypeExpr>,
97    },
98    StringLit(String),
99    IntLit(i64),
100    FloatLit(f64),
101    BoolLit(bool),
102    Null,
103    Undefined,
104    Void,
105    Nullable(Box<TypeExpr>),
106    Array(Box<TypeExpr>),
107    Union(Vec<TypeExpr>),
108    Intersection(Vec<TypeExpr>),
109    Object {
110        spreads: Vec<String>,
111        members: Vec<RawMember>,
112    },
113    Function {
114        params: Vec<RawParam>,
115        ret: Box<TypeExpr>,
116    },
117    Unknown,
118}
119
120#[derive(Debug, Clone)]
121struct RawParam {
122    name: String,
123    optional: bool,
124    ty: TypeExpr,
125}
126
127#[derive(Debug, Clone)]
128enum RawMember {
129    Property {
130        name: String,
131        optional: bool,
132        ty: TypeExpr,
133        doc: Option<String>,
134    },
135    Method {
136        name: String,
137        params: Vec<RawParam>,
138        ret: TypeExpr,
139        doc: Option<String>,
140    },
141}
142
143#[derive(Debug, Clone)]
144struct InterfaceDecl {
145    name: String,
146    extends: Vec<String>,
147    members: Vec<RawMember>,
148}
149
150#[derive(Debug, Clone)]
151struct ComponentCall {
152    props_type: Option<String>,
153    component_name: String,
154    options: ComponentOptions,
155}
156
157#[derive(Debug, Clone)]
158struct CommandsCall {
159    interface_name: Option<String>,
160    supported_commands: Vec<String>,
161}
162
163#[derive(Debug, Clone)]
164struct TurboModuleCall {
165    spec_name: Option<String>,
166    module_name: String,
167    enforcing: bool,
168}
169
170const MAX_PARSE_DEPTH: usize = 128;
171
172struct Parser {
173    tokens: Vec<Token>,
174    eof: Token,
175    pos: usize,
176    depth: usize,
177    type_aliases: HashMap<String, TypeExpr>,
178    interfaces: HashMap<String, InterfaceDecl>,
179    component_call: Option<ComponentCall>,
180    commands_call: Option<CommandsCall>,
181    turbomodule_call: Option<TurboModuleCall>,
182}
183
184impl Parser {
185    fn new(tokens: Vec<Token>) -> Self {
186        let eof = tokens
187            .last()
188            .filter(|t| matches!(t.kind, TokenKind::Eof))
189            .cloned()
190            .unwrap_or(Token {
191                kind: TokenKind::Eof,
192                line: 1,
193                col: 1,
194            });
195        Self {
196            tokens,
197            eof,
198            pos: 0,
199            depth: 0,
200            type_aliases: HashMap::new(),
201            interfaces: HashMap::new(),
202            component_call: None,
203            commands_call: None,
204            turbomodule_call: None,
205        }
206    }
207
208    fn enter_depth(&mut self) -> Result<(), CodegenError> {
209        if self.depth >= MAX_PARSE_DEPTH {
210            let tok = self.peek();
211            return Err(CodegenError::parse(
212                tok.line,
213                tok.col,
214                "maximum type nesting depth exceeded",
215            ));
216        }
217        self.depth += 1;
218        Ok(())
219    }
220
221    fn exit_depth(&mut self) {
222        self.depth = self.depth.saturating_sub(1);
223    }
224
225    fn peek(&self) -> &Token {
226        self.tokens.get(self.pos).unwrap_or(&self.eof)
227    }
228
229    fn peek_skip_docs(&self) -> &Token {
230        let mut idx = self.pos;
231        while let Some(tok) = self.tokens.get(idx) {
232            if !matches!(tok.kind, TokenKind::DocComment(_)) {
233                return tok;
234            }
235            idx += 1;
236        }
237        &self.eof
238    }
239
240    fn peek_nth_non_doc(&self, n: usize) -> &Token {
241        let mut idx = self.pos;
242        let mut seen = 0;
243        while let Some(tok) = self.tokens.get(idx) {
244            if !matches!(tok.kind, TokenKind::DocComment(_)) {
245                if seen == n {
246                    return tok;
247                }
248                seen += 1;
249            }
250            idx += 1;
251        }
252        &self.eof
253    }
254
255    fn take_doc_comments(&mut self) -> Option<String> {
256        let mut last = None;
257        while let TokenKind::DocComment(doc) = &self.peek().kind {
258            last = Some(doc.clone());
259            self.pos += 1;
260        }
261        last
262    }
263
264    fn skip_docs(&mut self) {
265        while matches!(self.peek().kind, TokenKind::DocComment(_)) {
266            self.pos += 1;
267        }
268    }
269
270    fn next_tok(&mut self) -> Token {
271        self.skip_docs();
272        let tok = self.peek().clone();
273        if !matches!(tok.kind, TokenKind::Eof) {
274            self.pos += 1;
275        }
276        tok
277    }
278
279    fn at_eof(&self) -> bool {
280        matches!(self.peek_skip_docs().kind, TokenKind::Eof)
281    }
282
283    fn at_ident(&self, expected: &str) -> bool {
284        matches!(&self.peek_skip_docs().kind, TokenKind::Ident(s) if s == expected)
285    }
286
287    fn eat_ident(&mut self, expected: &str) -> bool {
288        if self.at_ident(expected) {
289            self.next_tok();
290            true
291        } else {
292            false
293        }
294    }
295
296    fn eat(&mut self, expected: &TokenKind) -> bool {
297        if &self.peek_skip_docs().kind == expected {
298            self.next_tok();
299            true
300        } else {
301            false
302        }
303    }
304
305    fn expect(&mut self, expected: &TokenKind, label: &str) -> Result<Token, CodegenError> {
306        let tok = self.next_tok();
307        if &tok.kind == expected {
308            Ok(tok)
309        } else {
310            Err(CodegenError::parse(
311                tok.line,
312                tok.col,
313                format!("expected {label}, found {:?}", tok.kind),
314            ))
315        }
316    }
317
318    fn expect_ident(&mut self, label: &str) -> Result<String, CodegenError> {
319        let tok = self.next_tok();
320        match tok.kind {
321            TokenKind::Ident(s) => Ok(s),
322            other => Err(CodegenError::parse(
323                tok.line,
324                tok.col,
325                format!("expected {label}, found {other:?}"),
326            )),
327        }
328    }
329
330    fn parse_file(&mut self) -> Result<ParsedRnSpec, CodegenError> {
331        while !self.at_eof() {
332            let _doc = self.take_doc_comments();
333            if self.at_eof() {
334                break;
335            }
336
337            if self.at_ident("import") {
338                self.skip_import();
339                continue;
340            }
341
342            if self.at_ident("export") {
343                self.next_tok();
344                if self.eat_ident("default") {
345                    self.parse_export_default()?;
346                    continue;
347                }
348                if self.eat_ident("declare") {
349                    // fall through to type/interface
350                }
351            } else if self.eat_ident("declare") {
352                // fall through
353            }
354
355            if self.at_ident("interface") {
356                let decl = self.parse_interface_decl()?;
357                self.interfaces.insert(decl.name.clone(), decl);
358                continue;
359            }
360
361            if self.at_ident("type") && matches!(self.peek_nth_non_doc(1).kind, TokenKind::Ident(_))
362            {
363                self.parse_type_alias()?;
364                continue;
365            }
366
367            if self.at_ident("const") || self.at_ident("let") || self.at_ident("var") {
368                self.parse_var_statement()?;
369                continue;
370            }
371
372            // Check standalone calls (e.g. `codegenNativeComponent<...>(...)`)
373            if self.at_ident("codegenNativeComponent") {
374                let call = self.parse_codegen_native_component_call()?;
375                self.component_call = Some(call);
376                continue;
377            }
378
379            if self.at_ident("codegenNativeCommands") {
380                let call = self.parse_codegen_native_commands_call()?;
381                self.commands_call = Some(call);
382                continue;
383            }
384
385            if self.at_ident("TurboModuleRegistry")
386                && let Some(call) = self.try_parse_turbomodule_call()?
387            {
388                self.turbomodule_call = Some(call);
389                continue;
390            }
391
392            // Skip any other top-level token cleanly
393            self.next_tok();
394        }
395
396        self.build_ir()
397    }
398
399    fn skip_import(&mut self) {
400        // Consume `import ... ;` or up to string literal after `from`
401        self.next_tok(); // `import`
402        while !self.at_eof() {
403            let tok = self.next_tok();
404            match tok.kind {
405                TokenKind::Semi => break,
406                TokenKind::StringLit(_) => {
407                    self.eat(&TokenKind::Semi);
408                    break;
409                }
410                _ => {}
411            }
412        }
413    }
414
415    fn parse_export_default(&mut self) -> Result<(), CodegenError> {
416        // Handle optional parens: `export default (codegenNativeComponent<...>(...))`
417        while self.eat(&TokenKind::LParen) {}
418
419        if self.at_ident("codegenNativeComponent") {
420            let call = self.parse_codegen_native_component_call()?;
421            self.component_call = Some(call);
422            self.skip_to_statement_end();
423            return Ok(());
424        }
425
426        if self.at_ident("TurboModuleRegistry")
427            && let Some(call) = self.try_parse_turbomodule_call()?
428        {
429            self.turbomodule_call = Some(call);
430            self.skip_to_statement_end();
431            return Ok(());
432        }
433
434        // Handle `(TurboModuleRegistry.get<Spec>(...) as ?Spec)` or other expressions
435        let mut depth = 0usize;
436        while !self.at_eof() {
437            if self.at_ident("codegenNativeComponent") {
438                let call = self.parse_codegen_native_component_call()?;
439                self.component_call = Some(call);
440                self.skip_to_statement_end();
441                return Ok(());
442            }
443            if self.at_ident("TurboModuleRegistry")
444                && let Some(call) = self.try_parse_turbomodule_call()?
445            {
446                self.turbomodule_call = Some(call);
447                self.skip_to_statement_end();
448                return Ok(());
449            }
450            let tok = self.next_tok();
451            match tok.kind {
452                TokenKind::LParen | TokenKind::LBrace | TokenKind::LBracket => depth += 1,
453                TokenKind::RParen | TokenKind::RBrace | TokenKind::RBracket => {
454                    depth = depth.saturating_sub(1);
455                }
456                TokenKind::Semi if depth == 0 => break,
457                _ => {}
458            }
459        }
460        Ok(())
461    }
462
463    fn parse_var_statement(&mut self) -> Result<(), CodegenError> {
464        self.next_tok(); // const / let / var
465        let mut depth = 0usize;
466        while !self.at_eof() {
467            if self.at_ident("codegenNativeComponent") {
468                let call = self.parse_codegen_native_component_call()?;
469                self.component_call = Some(call);
470                continue;
471            }
472            if self.at_ident("codegenNativeCommands") {
473                let call = self.parse_codegen_native_commands_call()?;
474                self.commands_call = Some(call);
475                continue;
476            }
477            if self.at_ident("TurboModuleRegistry")
478                && let Some(call) = self.try_parse_turbomodule_call()?
479            {
480                self.turbomodule_call = Some(call);
481                continue;
482            }
483            let tok = self.next_tok();
484            match tok.kind {
485                TokenKind::LParen | TokenKind::LBrace | TokenKind::LBracket => depth += 1,
486                TokenKind::RParen | TokenKind::RBrace | TokenKind::RBracket => {
487                    depth = depth.saturating_sub(1);
488                }
489                TokenKind::Semi if depth == 0 => break,
490                _ => {}
491            }
492        }
493        Ok(())
494    }
495
496    fn skip_to_statement_end(&mut self) {
497        let mut depth = 0usize;
498        while !self.at_eof() {
499            match self.peek_skip_docs().kind {
500                TokenKind::Semi if depth == 0 => {
501                    self.next_tok();
502                    break;
503                }
504                TokenKind::Ident(ref s)
505                    if depth == 0
506                        && matches!(
507                            s.as_str(),
508                            "export" | "import" | "interface" | "type" | "const" | "declare"
509                        ) =>
510                {
511                    break;
512                }
513                TokenKind::LParen | TokenKind::LBrace | TokenKind::LBracket => {
514                    depth += 1;
515                    self.next_tok();
516                }
517                TokenKind::RParen | TokenKind::RBrace | TokenKind::RBracket => {
518                    depth = depth.saturating_sub(1);
519                    self.next_tok();
520                }
521                _ => {
522                    self.next_tok();
523                }
524            }
525        }
526    }
527
528}