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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
// Copyright 2019-2021 the Deno authors. All rights reserved. MIT license.
use std::os::raw::c_int;
use std::{marker::PhantomData, mem::MaybeUninit};

use crate::Function;
use crate::Local;
use crate::Module;
use crate::Object;
use crate::ScriptOrigin;
use crate::String;
use crate::{Context, Isolate, Script, UnboundScript};
use crate::{HandleScope, UniqueRef};

extern "C" {
  fn v8__ScriptCompiler__Source__CONSTRUCT(
    buf: *mut MaybeUninit<Source>,
    source_string: *const String,
    origin: *const ScriptOrigin,
    cached_data: *mut CachedData,
  );
  fn v8__ScriptCompiler__Source__DESTRUCT(this: *mut Source);
  fn v8__ScriptCompiler__Source__GetCachedData<'a>(
    this: *const Source,
  ) -> *const CachedData<'a>;
  fn v8__ScriptCompiler__CachedData__NEW<'a>(
    data: *const u8,
    length: i32,
  ) -> *mut CachedData<'a>;
  fn v8__ScriptCompiler__CachedData__DELETE<'a>(this: *mut CachedData<'a>);
  fn v8__ScriptCompiler__CompileModule(
    isolate: *mut Isolate,
    source: *mut Source,
    options: CompileOptions,
    no_cache_reason: NoCacheReason,
  ) -> *const Module;
  fn v8__ScriptCompiler__Compile(
    context: *const Context,
    source: *mut Source,
    options: CompileOptions,
    no_cache_reason: NoCacheReason,
  ) -> *const Script;
  fn v8__ScriptCompiler__CompileFunction(
    context: *const Context,
    source: *mut Source,
    arguments_count: usize,
    arguments: *const *const String,
    context_extensions_count: usize,
    context_extensions: *const *const Object,
    options: CompileOptions,
    no_cache_reason: NoCacheReason,
  ) -> *const Function;
  fn v8__ScriptCompiler__CompileUnboundScript(
    isolate: *mut Isolate,
    source: *mut Source,
    options: CompileOptions,
    no_cache_reason: NoCacheReason,
  ) -> *const UnboundScript;

  fn v8__ScriptCompiler__CachedDataVersionTag() -> u32;
}

/// Source code which can then be compiled to a UnboundScript or Script.
#[repr(C)]
#[derive(Debug)]
pub struct Source {
  _source_string: usize,
  _resource_name: usize,
  _resource_line_offset: c_int,
  _resource_column_offset: c_int,
  _resource_options: c_int,
  _source_map_url: usize,
  _host_defined_options: usize,
  _cached_data: usize,
  _consume_cache_task: usize,
}

/// Compilation data that the embedder can cache and pass back to speed up future
/// compilations. The data is produced if the CompilerOptions passed to the compilation
/// functions in ScriptCompiler contains produce_data_to_cache = true. The data to cache
/// can then can be retrieved from UnboundScript.
#[repr(C)]
#[derive(Debug)]
pub struct CachedData<'a> {
  data: *const u8,
  length: i32,
  rejected: bool,
  buffer_policy: BufferPolicy,
  _phantom: PhantomData<&'a ()>,
}

impl<'a> Drop for CachedData<'a> {
  fn drop(&mut self) {
    unsafe {
      v8__ScriptCompiler__CachedData__DELETE(self);
    }
  }
}

impl<'a> CachedData<'a> {
  pub fn new(data: &'a [u8]) -> UniqueRef<Self> {
    let cached_data = unsafe {
      UniqueRef::from_raw(v8__ScriptCompiler__CachedData__NEW(
        data.as_ptr(),
        data.len() as i32,
      ))
    };
    debug_assert_eq!(
      cached_data.buffer_policy(),
      crate::script_compiler::BufferPolicy::BufferNotOwned
    );
    cached_data
  }

  #[inline(always)]
  pub(crate) fn buffer_policy(&self) -> BufferPolicy {
    self.buffer_policy
  }
}

impl<'a> std::ops::Deref for CachedData<'a> {
  type Target = [u8];
  fn deref(&self) -> &Self::Target {
    unsafe { std::slice::from_raw_parts(self.data, self.length as usize) }
  }
}

#[allow(dead_code)]
#[repr(C)]
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) enum BufferPolicy {
  BufferNotOwned = 0,
  BufferOwned,
}

impl Source {
  #[inline(always)]
  pub fn new(
    source_string: Local<String>,
    origin: Option<&ScriptOrigin>,
  ) -> Self {
    let mut buf = MaybeUninit::<Self>::uninit();
    unsafe {
      v8__ScriptCompiler__Source__CONSTRUCT(
        &mut buf,
        &*source_string,
        origin.map(|x| x as *const _).unwrap_or(std::ptr::null()),
        std::ptr::null_mut(),
      );
      buf.assume_init()
    }
  }

  #[inline(always)]
  pub fn new_with_cached_data(
    source_string: Local<String>,
    origin: Option<&ScriptOrigin>,
    cached_data: UniqueRef<CachedData>,
  ) -> Self {
    let mut buf = MaybeUninit::<Self>::uninit();
    unsafe {
      v8__ScriptCompiler__Source__CONSTRUCT(
        &mut buf,
        &*source_string,
        origin.map(|x| x as *const _).unwrap_or(std::ptr::null()),
        cached_data.into_raw(), // Source constructor takes ownership.
      );
      buf.assume_init()
    }
  }

  #[inline(always)]
  pub fn get_cached_data(&self) -> Option<&CachedData> {
    unsafe {
      let cached_data = v8__ScriptCompiler__Source__GetCachedData(self);
      if cached_data.is_null() {
        None
      } else {
        Some(&*cached_data)
      }
    }
  }
}

impl Drop for Source {
  fn drop(&mut self) {
    unsafe { v8__ScriptCompiler__Source__DESTRUCT(self) }
  }
}

#[repr(C)]
#[derive(Debug)]
pub enum CompileOptions {
  NoCompileOptions = 0,
  ConsumeCodeCache,
  EagerCompile,
}

/// The reason for which we are not requesting or providing a code cache.
#[repr(C)]
#[derive(Debug)]
pub enum NoCacheReason {
  NoReason = 0,
  BecauseCachingDisabled,
  BecauseNoResource,
  BecauseInlineScript,
  BecauseModule,
  BecauseStreamingSource,
  BecauseInspector,
  BecauseScriptTooSmall,
  BecauseCacheTooCold,
  BecauseV8Extension,
  BecauseExtensionModule,
  BecausePacScript,
  BecauseInDocumentWrite,
  BecauseResourceWithNoCacheHandler,
  BecauseDeferredProduceCodeCache,
}

/// Compile an ES module, returning a Module that encapsulates the compiled
/// code.
///
/// Corresponds to the ParseModule abstract operation in the ECMAScript
/// specification.
#[inline(always)]
pub fn compile_module<'s>(
  scope: &mut HandleScope<'s>,
  source: Source,
) -> Option<Local<'s, Module>> {
  compile_module2(
    scope,
    source,
    CompileOptions::NoCompileOptions,
    NoCacheReason::NoReason,
  )
}

/// Same as compile_module with more options.
#[inline(always)]
pub fn compile_module2<'s>(
  scope: &mut HandleScope<'s>,
  mut source: Source,
  options: CompileOptions,
  no_cache_reason: NoCacheReason,
) -> Option<Local<'s, Module>> {
  unsafe {
    scope.cast_local(|sd| {
      v8__ScriptCompiler__CompileModule(
        sd.get_isolate_ptr(),
        &mut source,
        options,
        no_cache_reason,
      )
    })
  }
}

#[inline(always)]
pub fn compile<'s>(
  scope: &mut HandleScope<'s>,
  mut source: Source,
  options: CompileOptions,
  no_cache_reason: NoCacheReason,
) -> Option<Local<'s, Script>> {
  unsafe {
    scope.cast_local(|sd| {
      v8__ScriptCompiler__Compile(
        &*sd.get_current_context(),
        &mut source,
        options,
        no_cache_reason,
      )
    })
  }
}

#[inline(always)]
pub fn compile_function<'s>(
  scope: &mut HandleScope<'s>,
  mut source: Source,
  arguments: &[Local<String>],
  context_extensions: &[Local<Object>],
  options: CompileOptions,
  no_cache_reason: NoCacheReason,
) -> Option<Local<'s, Function>> {
  let arguments = Local::slice_into_raw(arguments);
  let context_extensions = Local::slice_into_raw(context_extensions);
  unsafe {
    scope.cast_local(|sd| {
      v8__ScriptCompiler__CompileFunction(
        &*sd.get_current_context(),
        &mut source,
        arguments.len(),
        arguments.as_ptr(),
        context_extensions.len(),
        context_extensions.as_ptr(),
        options,
        no_cache_reason,
      )
    })
  }
}

#[inline(always)]
pub fn compile_unbound_script<'s>(
  scope: &mut HandleScope<'s>,
  mut source: Source,
  options: CompileOptions,
  no_cache_reason: NoCacheReason,
) -> Option<Local<'s, UnboundScript>> {
  unsafe {
    scope.cast_local(|sd| {
      v8__ScriptCompiler__CompileUnboundScript(
        sd.get_isolate_ptr(),
        &mut source,
        options,
        no_cache_reason,
      )
    })
  }
}

/// Return a version tag for CachedData for the current V8 version & flags.
///
/// This value is meant only for determining whether a previously generated
/// CachedData instance is still valid; the tag has no other meaing.
///
/// Background: The data carried by CachedData may depend on the exact V8
/// version number or current compiler flags. This means that when persisting
/// CachedData, the embedder must take care to not pass in data from another V8
/// version, or the same version with different features enabled.
///
/// The easiest way to do so is to clear the embedder's cache on any such
/// change.
///
/// Alternatively, this tag can be stored alongside the cached data and compared
/// when it is being used.
#[inline(always)]
pub fn cached_data_version_tag() -> u32 {
  unsafe { v8__ScriptCompiler__CachedDataVersionTag() }
}