oxc_codegen/context.rs
1//! Code generation context management
2//!
3//! This module provides the [`Context`] type for managing the state and configuration
4//! during code generation, including JavaScript/TypeScript-specific syntax rules.
5
6use bitflags::bitflags;
7
8bitflags! {
9 /// Code generation context flags
10 ///
11 /// Controls various aspects of code generation including operator precedence,
12 /// language features, and syntax restrictions.
13 #[derive(Debug, Default, Clone, Copy)]
14 pub struct Context: u8 {
15 /// Forbid the `in` operator in expressions
16 ///
17 /// Used in contexts where the `in` operator could be ambiguous,
18 /// such as in the init clause of a for loop.
19 const FORBID_IN = 1 << 0;
20 /// Forbid call expressions
21 ///
22 /// Used to prevent ambiguity in contexts like new expressions
23 /// where parentheses could be interpreted differently.
24 const FORBID_CALL = 1 << 1;
25 /// Enable TypeScript-specific code generation
26 ///
27 /// When set, TypeScript syntax features are enabled in the output.
28 const TYPESCRIPT = 1 << 2;
29 /// The current template literal is tagged, so preserve its raw quasis.
30 const TAGGED_TEMPLATE = 1 << 3;
31 }
32}
33
34impl Context {
35 /// Check if the `in` operator is forbidden in the current context
36 #[inline]
37 pub fn forbid_in(self) -> bool {
38 self.contains(Self::FORBID_IN)
39 }
40
41 /// Check if call expressions are forbidden in the current context
42 #[inline]
43 pub fn forbid_call(self) -> bool {
44 self.contains(Self::FORBID_CALL)
45 }
46
47 /// Create a new context with TypeScript support enabled
48 #[inline]
49 #[must_use]
50 pub fn with_typescript(mut self) -> Self {
51 self |= Self::TYPESCRIPT;
52 self
53 }
54
55 /// Conditionally set or unset the `FORBID_IN` flag
56 #[inline]
57 #[must_use]
58 pub fn and_forbid_in(self, include: bool) -> Self {
59 self.and(Self::FORBID_IN, include)
60 }
61
62 /// Conditionally set or unset the `FORBID_CALL` flag
63 #[inline]
64 #[must_use]
65 pub fn and_forbid_call(self, include: bool) -> Self {
66 self.and(Self::FORBID_CALL, include)
67 }
68
69 /// Helper method to conditionally set or unset a flag
70 #[inline]
71 fn and(self, flag: Self, set: bool) -> Self {
72 if set { self | flag } else { self - flag }
73 }
74}