Skip to main content

big_code_analysis_ast/getter/
objc.rs

1//! `Getter` implementation for Objective-C.
2#![allow(clippy::wildcard_imports, clippy::enum_glob_use)]
3
4use super::*;
5use crate::c_declarator::declarator_name;
6
7// ObjC has no templates, but four nodes delimit a generic list with a
8// bare `<` / `>`: `generic_specifier` (`NSArray<NSString *>`),
9// `protocol_reference_list` (`id<NSCopying>`), `parameterized_arguments`
10// (`@interface A : NSObject <NSCopying>`), and `argument_list`, whose
11// `Type<…>` alternative (`f(NSArray<NSString *>)`) holds the brackets as
12// direct children. A well-formed comparison's `<` / `>` is the child of
13// a `binary_expression` or `preproc_binary_expression`; the one
14// exception is `objc_argument_list_misparse`. `LT2` is the
15// `token.immediate` `<` that `argument_list`'s form opens with; the
16// parser reports it as `LT`, so it is listed defensively, here and in
17// the operator arm, and its absence is pinned by
18// `objc_generic_opener_alias_never_reaches_kind_id`. The call's
19// `argument_list` is `ArgumentList2`; `ArgumentList` is
20// `preproc_call_expression`'s alias, which holds no angle brackets.
21const GENERIC_ANGLES: GenericAngleKinds = GenericAngleKinds {
22    lists: &[
23        Objc::GenericSpecifier as u16,
24        Objc::ProtocolReferenceList as u16,
25        Objc::ParameterizedArguments as u16,
26        Objc::ArgumentList2 as u16,
27    ],
28    openers: &[Objc::LT as u16, Objc::LT2 as u16],
29    closers: &[Objc::GT as u16],
30    is_misparse: objc_argument_list_misparse,
31};
32
33// Whether `list` is an `argument_list` holding two comparisons that
34// tree-sitter-objc read as its `Type<…>` form: an unspaced
35// `g(a<b, c>d)`, where a `<` glued to the first argument opens the form.
36// The real form is the whole argument list, so `f(NSArray<NSString *>)`
37// parses cleanly, while the misparse leaves an `ERROR` after the `>`, or
38// a MISSING `)` (`g(i<n, j>=0)`) that only `has_error` sees.
39fn objc_argument_list_misparse(list: &Node, _ancestors: Ancestors) -> bool {
40    list.kind_id() == Objc::ArgumentList2 as u16 && list.has_error()
41}
42
43impl Getter for ObjcCode {
44    fn get_func_space_name<'a, 'tree>(
45        node: &Node<'tree>,
46        code: &'a [u8],
47        _ancestors: Ancestors<'tree, '_>,
48    ) -> Option<&'a str> {
49        // Every `function_definition` alias the `FuncOpener` row names is
50        // listed here too (#285). Free functions reach their name through
51        // the C declarator chain; the
52        // ObjC containers (`method_definition`, `class_interface` /
53        // `class_implementation`, `protocol_declaration`) carry no `name`
54        // field, so their name is the first `identifier` child — the
55        // class / protocol name, or a method's first selector keyword.
56        // role-bypass: allow(FuncOpener, Container, Modifier) — a naming
57        // rule: which node is named, and which declarator leaf is the
58        // name; not whether the node opens a space or an identifier is a
59        // property-attribute word
60        match node.kind_id().into() {
61            Objc::FunctionDefinition | Objc::FunctionDefinition2 => {
62                // The name is not a child of the function node — see
63                // `crate::c_declarator` (#1208).
64                if let Some(name) = declarator_name::<Self>(node)
65                    && matches!(
66                        name.kind_id().into(),
67                        Objc::TypeIdentifier | Objc::Identifier | Objc::FieldIdentifier
68                    )
69                {
70                    return node_text(code, &name);
71                }
72            }
73            Objc::MethodDefinition
74            | Objc::ClassInterface
75            | Objc::ClassImplementation
76            | Objc::ProtocolDeclaration => {
77                if let Some(ident) = node.first_child(|id| Objc::Identifier == id) {
78                    return node_text(code, &ident);
79                }
80            }
81            _ => {
82                if let Some(name) = node.child_by_field_name("name") {
83                    return node_text(code, &name);
84                }
85            }
86        }
87        None
88    }
89
90    // The mapping is the `opens` annotations of `roles/objc.rs`
91    // (#1696). The rows read no bytes and no chain, so the byte-less
92    // spelling forwards with none.
93    impl_byte_less_space_kind!(objc);
94
95    fn get_space_kind_with_code<'a>(
96        node: &Node<'a>,
97        code: &[u8],
98        ancestors: Ancestors<'a, '_>,
99    ) -> SpaceKind {
100        crate::roles::objc::opens_space(node, code, ancestors)
101    }
102
103    keyword_roles!(objc);
104
105    paying_roles!(objc, control_flow);
106
107    fn get_op_type<'a>(node: &Node<'a>, ancestors: Ancestors<'a, '_>) -> TokenRole {
108        use Objc::*;
109
110        if GENERIC_ANGLES.is_closer(node, ancestors) {
111            return TokenRole::Unknown;
112        }
113
114        // ObjC is C plus message sends, blocks, and the `@`-directives.
115        // The operator alphabet is therefore the C set (`src/getter.rs`
116        // `impl Getter for CCode`) extended with the ObjC structural
117        // keywords: fast-enumeration `in`, the boxing/`@`-literal marker
118        // `@`, the `@try` / `@catch` / `@finally` / `@throw` /
119        // `@synchronized` / `@autoreleasepool` control keywords, and the
120        // `@selector` / `@encode` compile-time directives. Each keeps a
121        // distinct kind_id, so keying by kind_id keeps them distinct in n1.
122        // `LPAREN2` is a defensive arm (collapsed to `LPAREN` before
123        // `kind_id()`; #768, see the Cpp note).
124        match node.kind_id().into() {
125            // `@"…"` is one `string_literal` holding its `@` as a child
126            // (tree-sitter-objc 3.0.2), unlike `@42` / `@[…]` / `@{…}`,
127            // where the `@` is a child of the `at_expression` /
128            // `array_literal` / `dictionary_literal` it boxes. The
129            // literal is already the operand, keyed by its whole text,
130            // so billing the marker as an operator too paid the same
131            // byte twice and planted a phantom `@` in n1 for a file
132            // whose only `@` was in NSString literals (grammar-dispatch
133            // §5, the compound-leaf guard).
134            AT if ancestors.parent_has_kind(node, StringLiteral as u16) => TokenRole::Unknown,
135            // The C operator set, then the ObjC-specific structural
136            // keywords / markers from `In` onwards. `in` is one kind for
137            // the fast-enumeration keyword and the method-type
138            // qualifier, so it bills here rather than on the `Modifier`
139            // row. The modifiers, the declaration keywords and the
140            // primitive types are not here: `roles/objc.rs` declares
141            // them and `get_keyword_role` bills them (#1693). Nor are
142            // `<=` `>=` `==` `!=` `&&` `||`: the `Comparison` and
143            // `ShortCircuit` rows pay them ungated and `get_paying_role`
144            // bills them (#1695). `<` / `>` stay for the spellings the
145            // rows' `under BinaryExpression` gate leaves out — a generic
146            // specifier, a protocol list (`id<NSCopying>`), a recovered
147            // token — which billed before the rows existed; `LT2` is the
148            // grammar's own generic-opener kind and pays nowhere. The
149            // ternary `?` and the `case` label are not here: the `Ternary`
150            // and `CaseArm` rows pay them ungated.
151            // The `if` / `for` / `while` keywords are the `Branch` / `Loop`
152            // rows' payers and `get_paying_role` bills them (#1697).
153            // role-bypass: allow(Comparison) — the operator classification of the spellings the
154            // row's `under BinaryExpression` gate leaves out
155            LT | GT | LT2 | DOT | LPAREN | LPAREN2 | COMMA | STAR | GTGT | COLON | SEMI
156            | Return | Break | Continue | Else | Switch | Default | Goto | Do | EQ | DASH
157            | DASHDASH | DASHGT | PLUS | PLUSPLUS | SLASH | PERCENT | PIPE | AMP | LTLT | TILDE
158            | PLUSEQ | DASHEQ | BANG | STAREQ | SLASHEQ | PERCENTEQ | GTGTEQ | LTLTEQ | AMPEQ
159            | CARET | CARETEQ | PIPEEQ | LBRACK | LBRACE | Sizeof | In | AT | ATtry | ATcatch
160            | ATfinally | ATthrow | ATsynchronized | ATautoreleasepool | ATselector | ATencode => {
161                TokenRole::Operator
162            }
163            // `CharLiteral` — the full derivation lives on the same arm
164            // in `src/getter/c.rs` (#1316): the wrapper is the only
165            // classified node in a character literal, so it bills one
166            // operand per literal, keyed by text, and `Checker::is_string`
167            // deliberately stays without a `CharLiteral` arm.
168            //
169            // An `identifier` is an operand unless it is a property
170            // attribute's word, which the `Modifier` row claims under
171            // its gate and `get_keyword_role` bills first.
172            // role-bypass: allow(Modifier, StringLit) — the operand classification of the
173            // ungated identifier spelling and of the string literal, a projection
174            // the `StringLit` row does not answer
175            Identifier | TypeIdentifier | FieldIdentifier | StringLiteral | CharLiteral
176            | NumberLiteral | True | False | Null | DOTDOTDOT => TokenRole::Operand,
177            _ => TokenRole::Unknown,
178        }
179    }
180
181    fn get_operator_spelling<'a>(
182        node: &Node<'a>,
183        ancestors: Ancestors<'a, '_>,
184    ) -> Option<&'static str> {
185        GENERIC_ANGLES.opener_spelling(node, ancestors)
186    }
187
188    get_operator!(Objc);
189}