aboutsummaryrefslogtreecommitdiff
path: root/pw_tokenizer/rust/pw_tokenizer_macro.rs
blob: d22a10ef9516a3ec55a0201f1a5d1e15abb2cd01 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
// Copyright 2023 The Pigweed Authors
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.

// This proc macro crate is a private API for the `pw_tokenizer` crate.
#![doc(hidden)]

use std::collections::VecDeque;
use std::ffi::CString;

use proc_macro::TokenStream;
use quote::{format_ident, quote, ToTokens};
use syn::{
    parse::{Parse, ParseStream},
    parse_macro_input,
    punctuated::Punctuated,
    Expr, LitStr, Token,
};

use pw_tokenizer_core::{hash_string, TOKENIZER_ENTRY_MAGIC};
use pw_tokenizer_printf as printf;

type TokenStream2 = proc_macro2::TokenStream;

struct Error {
    text: String,
}

impl Error {
    fn new(text: &str) -> Self {
        Self {
            text: text.to_string(),
        }
    }
}

type Result<T> = core::result::Result<T, Error>;

// Handles tokenizing (hashing) `string` and adding it to the token database
// with the specified `domain`.  A detailed description of what's happening is
// found in the docs for [`pw_tokenizer::token`] macro.
fn token_backend(domain: &str, string: &str) -> TokenStream2 {
    let hash = hash_string(string);

    // Line number is omitted as getting that info requires an experimental API:
    // https://doc.rust-lang.org/proc_macro/struct.Span.html#method.start
    let ident = format_ident!("_pw_tokenizer_string_entry_{:08X}", hash);

    // pw_tokenizer is intended for use with ELF files only. Mach-O files (macOS
    // executables) do not support section names longer than 16 characters, so a
    // short, unused section name is used on macOS.
    let section = if cfg!(target_os = "macos") {
        ",pw,".to_string()
    } else {
        format!(".pw_tokenizer.entries.{:08X}", hash)
    };

    let string = CString::new(string).unwrap();
    let string_bytes = string.as_bytes_with_nul();
    let string_bytes_len = string_bytes.len();

    let domain = CString::new(domain).unwrap();
    let domain_bytes = domain.as_bytes_with_nul();
    let domain_bytes_len = domain_bytes.len();

    quote! {
        // Use an inner scope to avoid identifier collision.  Name mangling
        // will disambiguate these in the symbol table.
        {
            #[repr(C, packed(1))]
            struct TokenEntry {
                magic: u32,
                token: u32,
                domain_size: u32,
                string_length: u32,
                domain: [u8; #domain_bytes_len],
                string: [u8; #string_bytes_len],
            };
            // This is currently manually verified to be correct.
            // TODO: b/287132907 - Add integration tests for token database.
            #[link_section = #section ]
            static #ident: TokenEntry = TokenEntry {
                magic: #TOKENIZER_ENTRY_MAGIC,
                token: #hash,
                domain_size: #domain_bytes_len as u32,
                string_length: #string_bytes_len as u32,
                domain: [ #(#domain_bytes),* ],
                string: [ #(#string_bytes),* ],
            };

            #hash
        }
    }
}

// Documented in `pw_tokenizer::token`.
#[proc_macro]
pub fn _token(tokens: TokenStream) -> TokenStream {
    let input = parse_macro_input!(tokens as LitStr);
    token_backend("", &input.value()).into()
}

// Args to tokenize to buffer that are parsed according to the pattern:
//   ($buffer:expr, $format_string:literal, $($args:expr),*)
#[derive(Debug)]
struct TokenizeToBuffer {
    buffer: Expr,
    format_string: LitStr,
    args: VecDeque<Expr>,
}

impl Parse for TokenizeToBuffer {
    fn parse(input: ParseStream) -> syn::parse::Result<Self> {
        let buffer: Expr = input.parse()?;
        input.parse::<Token![,]>()?;
        let format_string: LitStr = input.parse()?;

        let args = if input.is_empty() {
            // If there are no more tokens, no arguments were specified.
            VecDeque::new()
        } else {
            // Eat the `,` following the format string.
            input.parse::<Token![,]>()?;

            let punctuated = Punctuated::<Expr, Token![,]>::parse_terminated(input)?;
            punctuated.into_iter().collect()
        };

        Ok(TokenizeToBuffer {
            buffer,
            format_string,
            args,
        })
    }
}

// Grab the next argument returning a descriptive error if no more args are left.
fn next_arg(spec: &printf::ConversionSpec, args: &mut VecDeque<Expr>) -> Result<Expr> {
    args.pop_front()
        .ok_or_else(|| Error::new(&format!("No argument given for {spec:?}")))
}

// Handle a single format conversion specifier (i.e. `%08x`).  Grabs the
// necessary arguments for the specifier from `args` and generates code
// to marshal the arguments into the buffer declared in `_tokenize_to_buffer`.
// Returns an error if args is too short of if a format specifier is unsupported.
fn handle_conversion(
    spec: &printf::ConversionSpec,
    args: &mut VecDeque<Expr>,
) -> Result<TokenStream2> {
    match spec.specifier {
        printf::Specifier::Decimal
        | printf::Specifier::Integer
        | printf::Specifier::Octal
        | printf::Specifier::Unsigned
        | printf::Specifier::Hex
        | printf::Specifier::UpperHex => {
            // TODO: b/281862660 - Support Width::Variable and Precision::Variable.
            if spec.min_field_width == printf::MinFieldWidth::Variable {
                return Err(Error::new(
                    "Variable width '*' integer formats are not supported.",
                ));
            }

            if spec.precision == printf::Precision::Variable {
                return Err(Error::new(
                    "Variable precision '*' integer formats are not supported.",
                ));
            }

            let arg = next_arg(spec, args)?;
            let bits = match spec.length.unwrap_or(printf::Length::Long) {
                printf::Length::Char => 8,
                printf::Length::Short => 16,
                printf::Length::Long => 32,
                printf::Length::LongLong => 64,
                printf::Length::IntMax => 64,
                printf::Length::Size => 32,
                printf::Length::PointerDiff => 32,
                printf::Length::LongDouble => {
                    return Err(Error::new(
                        "Long double length parameter invalid for integer formats",
                    ))
                }
            };
            let ty = format_ident!("i{bits}");
            Ok(quote! {
              // pw_tokenizer always uses signed packing for all integers.
              cursor.write_signed_varint(#ty::from(#arg) as i64)?;
            })
        }
        printf::Specifier::String => {
            // TODO: b/281862660 - Support Width::Variable and Precision::Variable.
            if spec.min_field_width == printf::MinFieldWidth::Variable {
                return Err(Error::new(
                    "Variable width '*' string formats are not supported.",
                ));
            }

            if spec.precision == printf::Precision::Variable {
                return Err(Error::new(
                    "Variable precision '*' string formats are not supported.",
                ));
            }

            let arg = next_arg(spec, args)?;
            Ok(quote! {
              let mut buffer = __pw_tokenizer_crate::internal::encode_string(&mut cursor, #arg)?;
            })
        }
        printf::Specifier::Char => {
            let arg = next_arg(spec, args)?;
            Ok(quote! {
              cursor.write_u8_le(&u8::from(#arg))?;
            })
        }

        printf::Specifier::Double
        | printf::Specifier::UpperDouble
        | printf::Specifier::Exponential
        | printf::Specifier::UpperExponential
        | printf::Specifier::SmallDouble
        | printf::Specifier::UpperSmallDouble => {
            // TODO: b/281862328 - Support floating point numbers.
            Err(Error::new("Floating point numbers are not supported."))
        }

        // TODO: b/281862333 - Support pointers.
        printf::Specifier::Pointer => Err(Error::new("Pointer types are not supported.")),
    }
}

// Generates code to marshal a tokenized string and arguments into a buffer.
// See [`pw_tokenizer::tokenize_to_buffer`] for details on behavior.
//
// Internally the [`AsMut<u8>`] is wrapped in a [`pw_stream::Cursor`] to
// fill the buffer incrementally.
#[proc_macro]
pub fn _tokenize_to_buffer(tokens: TokenStream) -> TokenStream {
    let input = parse_macro_input!(tokens as TokenizeToBuffer);
    let token = token_backend("", &input.format_string.value());
    let buffer = input.buffer;

    let format_string = input.format_string.value();

    let format = match printf::FormatString::parse(&format_string) {
        Ok(format) => format,
        Err(e) => {
            return syn::Error::new_spanned(
                input.format_string.to_token_stream(),
                format!("Error parsing format string {e}"),
            )
            .to_compile_error()
            .into()
        }
    };
    let mut args = input.args;
    let mut arg_encodings = Vec::new();

    let mut errors = Vec::new();

    for fragment in format.fragments {
        if let printf::FormatFragment::Conversion(spec) = fragment {
            match handle_conversion(&spec, &mut args) {
                Ok(encoding) => arg_encodings.push(encoding),
                Err(e) => errors.push(syn::Error::new_spanned(
                    input.format_string.to_token_stream(),
                    e.text,
                )),
            }
        }
    }

    if !errors.is_empty() {
        return errors
            .into_iter()
            .reduce(|mut accumulated_errors, error| {
                accumulated_errors.combine(error);
                accumulated_errors
            })
            .expect("errors should not be empty")
            .to_compile_error()
            .into();
    }

    let code = quote! {
      {
        // Wrapping code in an internal function to allow `?` to work in
        // functions that don't return Results.
        fn _pw_tokenizer_internal_encode(buffer: &mut [u8], token: u32) -> pw_status::Result<usize> {
          // use pw_tokenizer's private re-export of these pw_stream bits to
          // allow referencing with needing `pw_stream` in scope.
          use __pw_tokenizer_crate::{Cursor, Seek, WriteInteger, WriteVarint};
          let mut cursor = Cursor::new(buffer);
          cursor.write_u32_le(&token)?;
          #(#arg_encodings);*;
          Ok(cursor.stream_position()? as usize)
        }
        _pw_tokenizer_internal_encode(#buffer, #token)
      }
    };
    code.into()
}

// Macros tested in `pw_tokenizer` crate.
#[cfg(test)]
mod tests {}