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
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
//! A mechanism used to detect language fragments that can be represented more concisely
//! by using a specialized dictionary.
//!
//! For instance, if it is known that a file contains a large fragment composed of JSON,
//! we may switch the dictionary to JSON for this subtree.

use ast::*;
use binjs_shared::{SharedString, VisitMe};
use EnrichError;

use std::cell::RefCell;
use std::rc::Rc;

type EnterResult = Result<VisitMe<PropertiesGuard>, EnrichError>;
type ExitResult<T> = Result<Option<T>, EnrichError>;

/// The name of the dictionary used to represent pure data subtrees (aka "JSON").
///
/// We use the monicker "pojo" (plain old javascript objects).
pub const DICTIONARY_NAME_PURE_DATA: &'static str = "pojo";

/// Properties observed when examining a subtree.
#[derive(Clone, Copy, Debug)]
enum Properties {
    /// The subtree contains only pure data nodes.
    PureDataSoFar {
        /// The number of nodes in the subtree.
        ///
        /// We use this to determine whether it's worth wrapping a subtree
        /// in a scoped dictionary, e.g. we're not going to wrap every single
        /// `LiteralNumber` in a scoped dictionary as this would waste space.
        size: usize,
    },
    /// The subtree contains at least one node that is not pure data.
    Complex,
}

impl Default for Properties {
    fn default() -> Self {
        Properties::Complex
    }
}

/// A visitor dedicated to detecting fragments of a file that are pure data
/// and injecting scoped dictionary changes to DICTIONARY_NAME_PURE_DATA for
/// these fragments.
///
/// As of this writing, the definition of pure data (or POJO) is:
///
/// ```bnf
/// POJO ::= literal number
///       |  literal boolean
///       |  literal string
///       |  literal null
///       |  [ POJO ]
///       |  { (string: POJO)* }
/// ```
///
/// Note that literal infinity is *not* a literal number.
///
/// As of this writing, this visitor does NOT attempt to introduce scoped
/// dictionary changes in the case of an ArrayExpression or an ObjectExpression
/// containing both pure data elements and complex data elements.
///
/// More precisely, consider a JS array `[pure_1, complex, pure_2]`, where `pure_1`
/// and `pure_2` are pure data, while `complex` isn't. As we have walked `pure_1`
/// before `complex`, we do not have the information that `pure_1`'s parent is
/// `complex`, so we do not attempt to rewrite `pure_1` to inject a scoped
/// dictionary change around this child. On the other hand, as we walk `pure_2`
/// after `complex`, we already have the information, so we may decide to inject
/// a scoped dictionary change around `pure_2`.
///
/// Future versions may fix this limitation.
pub struct InjectVisitor {
    /// If a subtree `T` is pure data and has a size >= `pure_data_threshold`, measured
    /// in number of nodes, and if its parent is not pure data, we should rewrite `T`
    /// to wrap it in a scoped dictionary change to DICTIONARY_NAME_PURE_DATA.
    pure_data_threshold: usize,

    /// The stack obtained by examining the tree so far.
    ///
    /// Note that default implementations of `InjectVisitor` methods automatically
    /// call `(PropertiesGuard as WalkGuard)::new()`, thus inserting `Properties::Complex`.
    stack: Rc<RefCell<Vec<Properties>>>,
}

/// A guard used to propagate `Properties` upwards in the tree.
struct PropertiesGuard {
    /// A mutable reference to the stack of the InjectVisitor.
    stack: Rc<RefCell<Vec<Properties>>>,
}
impl PropertiesGuard {
    fn new(stack: Rc<RefCell<Vec<Properties>>>, top: Properties) -> Self {
        {
            stack.borrow_mut().push(top);
        }
        PropertiesGuard { stack }
    }

    /// Create a new `PropertiesGuard` for a complex tree.
    fn complex(visitor: &InjectVisitor, _path: &WalkPath) -> Self {
        let top = Properties::Complex;
        Self::new(visitor.stack.clone(), top)
    }

    /// Create a new `PropertiesGuard` for a pure data tree.
    fn pure_data(visitor: &InjectVisitor, size: usize, _path: &WalkPath) -> Self {
        let top = Properties::PureDataSoFar { size };
        Self::new(visitor.stack.clone(), top)
    }
}
impl Drop for PropertiesGuard {
    /// When we drop the PropertiesGuard:
    ///
    /// - if both child and parent are `PureDataSoFar`, increase the number of nodes
    ///   in the parent subtree;
    /// - otherwise, mark the parent as `Complex`.
    fn drop(&mut self) {
        let mut stack = self.stack.borrow_mut();
        let me = stack.pop().unwrap();

        if stack.len() == 0 {
            // We are the root, nothing to do.
            return;
        }

        let parent = stack.last_mut().unwrap();
        let new_parent = match (&me, &*parent) {
            // If either the parent or the child is complex, the parent is complex.
            (&Properties::Complex, _) | (_, &Properties::Complex) => Properties::Complex,

            // If both are pure so far, add both sizes.
            (
                &Properties::PureDataSoFar { size: my_size },
                &Properties::PureDataSoFar { size: parent_size },
            ) => Properties::PureDataSoFar {
                size: my_size + parent_size,
            },
        };
        *parent = new_parent
    }
}

impl WalkGuard<InjectVisitor> for PropertiesGuard {
    /// Constructor called by default methods of `InjectVisitor`
    fn new(origin: &InjectVisitor, path: &WalkPath) -> Self {
        PropertiesGuard::complex(origin, path)
    }
}

impl InjectVisitor {
    pub fn new(pure_data_threshold: usize) -> Self {
        Self {
            pure_data_threshold,
            stack: Rc::new(RefCell::new(Vec::new())),
        }
    }
    pub fn rewrite_script(
        pure_data_threshold: usize,
        script: &mut Script,
    ) -> Result<(), EnrichError> {
        let mut visitor = Self::new(pure_data_threshold);
        script.walk(&mut WalkPath::new(), &mut visitor)?;
        Ok(())
    }

    /// The properties of the current node.
    fn properties(&self) -> Properties {
        self.stack.borrow().last().unwrap().clone()
    }

    /// The properties of the parent node, or `None` if there is no parent.
    fn parent_properties(&self) -> Option<Properties> {
        let stack = self.stack.borrow();
        if stack.len() >= 2 {
            Some(stack[stack.len() - 2].clone())
        } else {
            None
        }
    }
}
impl Visitor<EnrichError, PropertiesGuard> for InjectVisitor {
    // --- Literals

    fn enter_literal<'a>(&mut self, path: &WalkPath, node: &mut ViewMutLiteral<'a>) -> EnterResult {
        let _guard = if let ViewMutLiteral::LiteralInfinityExpression(_) = *node {
            // In JavaScript, this is not considered pure data as there is no syntax for it.
            PropertiesGuard::complex(self, path)
        } else {
            // Other literals are pure data.
            PropertiesGuard::pure_data(self, 1, path)
        };
        // No need to visit the children.
        Ok(VisitMe::DoneHere)
    }

    // --- Objects

    fn enter_property_name<'a>(
        &mut self,
        path: &WalkPath,
        _node: &mut ViewMutPropertyName<'a>,
    ) -> EnterResult {
        // Pure data so far.
        Ok(VisitMe::HoldThis(PropertiesGuard::pure_data(self, 0, path)))
    }

    fn enter_object_property<'a>(
        &mut self,
        path: &WalkPath,
        _node: &mut ViewMutObjectProperty<'a>,
    ) -> EnterResult {
        // Pure data so far.
        Ok(VisitMe::HoldThis(PropertiesGuard::pure_data(self, 0, path)))
    }

    fn enter_literal_property_name(
        &mut self,
        path: &WalkPath,
        _node: &mut LiteralPropertyName,
    ) -> EnterResult {
        // Pure data so far.
        Ok(VisitMe::HoldThis(PropertiesGuard::pure_data(self, 1, path)))
    }

    fn enter_object_expression(
        &mut self,
        path: &WalkPath,
        _node: &mut ObjectExpression,
    ) -> EnterResult {
        // Pure data so far.
        Ok(VisitMe::HoldThis(PropertiesGuard::pure_data(self, 1, path)))
    }

    fn enter_data_property(&mut self, path: &WalkPath, _node: &mut DataProperty) -> EnterResult {
        // Pure data so far.
        Ok(VisitMe::HoldThis(PropertiesGuard::pure_data(self, 1, path)))
    }

    // --- Arrays

    fn enter_expression_or_spread_element<'a>(
        &mut self,
        path: &WalkPath,
        _node: &mut ViewMutExpressionOrSpreadElement<'a>,
    ) -> EnterResult {
        // Pure data so far.
        Ok(VisitMe::HoldThis(PropertiesGuard::pure_data(self, 1, path)))
    }

    fn enter_array_expression(
        &mut self,
        path: &WalkPath,
        _node: &mut ArrayExpression,
    ) -> EnterResult {
        // Pure data so far.
        Ok(VisitMe::HoldThis(PropertiesGuard::pure_data(self, 1, path)))
    }

    // --- Wrapping in a scoped dictionary

    fn enter_expression<'a>(
        &mut self,
        path: &WalkPath,
        node: &mut ViewMutExpression<'a>,
    ) -> EnterResult {
        match *node {
            ViewMutExpression::LiteralNumericExpression(_)
            | ViewMutExpression::ObjectExpression(_)
            | ViewMutExpression::LiteralStringExpression(_)
            | ViewMutExpression::LiteralNullExpression(_)
            | ViewMutExpression::LiteralBooleanExpression(_)
            | ViewMutExpression::ArrayExpression(_) =>
            // For the moment, this is is pure data
            {
                Ok(VisitMe::HoldThis(PropertiesGuard::pure_data(self, 0, path)))
            }
            _ =>
            // We already know that this is complex.
            {
                Ok(VisitMe::HoldThis(PropertiesGuard::complex(self, path)))
            }
        }
    }

    fn exit_expression<'a>(
        &mut self,
        _path: &WalkPath,
        node: &mut ViewMutExpression<'a>,
    ) -> ExitResult<Expression> {
        if let Properties::PureDataSoFar { size } = self.properties() {
            match self.parent_properties() {
                None | Some(Properties::Complex) => {
                    // We're the topmost root of a pure data subtree,
                    // so embed `node` in a `BinASTExpressionWithProbabilityTable`.
                    if size >= self.pure_data_threshold {
                        return Ok(Some(
                            BinASTExpressionWithProbabilityTable {
                                table: SharedString::from_str(DICTIONARY_NAME_PURE_DATA),
                                expression: node.steal(),
                            }
                            .into(),
                        ));
                    }
                }
                _ => {}
            }
        }
        // Otherwise, nothing to change.
        Ok(None)
    }
}

/// A visitor dedicated to removing instances of `BinASTExpressionWithProbabilityTable`.
pub struct CleanupVisitor;
impl CleanupVisitor {
    pub fn rewrite_script(script: &mut Script) {
        let mut visitor = Self;
        script
            .walk(&mut WalkPath::new(), &mut visitor)
            .expect("Could not walk script");
    }
}

impl Visitor<()> for CleanupVisitor {
    fn exit_expression<'a>(
        &mut self,
        _path: &WalkPath,
        node: &mut ViewMutExpression<'a>,
    ) -> Result<Option<Expression>, ()> {
        if let ViewMutExpression::BinASTExpressionWithProbabilityTable(_) = *node {
            if let Expression::BinASTExpressionWithProbabilityTable(scoped) = node.steal() {
                Ok(Some(scoped.expression))
            } else {
                // We just stole `ViewMutExpression::BinASTExpressionWithProbabilityTable`.
                // If the result is not a `Expression::BinASTExpressionWithProbabilityTable`,
                // that's a bug in our implementation of `steal()`.
                panic!();
            }
        } else {
            Ok(None)
        }
    }
}

#[cfg(test)]
mod test {
    use ast::*;
    use binjs_shared::*;
    use sublanguages::{CleanupVisitor, InjectVisitor, DICTIONARY_NAME_PURE_DATA};

    fn check(threshold: usize, source: Script, expected: Script) {
        // Rewrite.
        let mut injected = source.clone();
        InjectVisitor::rewrite_script(threshold, &mut injected).unwrap();
        assert_eq!(injected, expected);

        // Rewrite back.
        let mut cleaned = injected.clone();
        CleanupVisitor::rewrite_script(&mut cleaned);
        assert_eq!(source, cleaned);
    }

    #[test]
    fn test_sublanguage_pure_data_positive() {
        let source = Script {
            scope: Default::default(),
            directives: vec![],
            statements: vec![ExpressionStatement {
                expression: ArrayExpression {
                    elements: vec![
                        Some(LiteralBooleanExpression { value: true }.into()),
                        Some(LiteralNullExpression {}.into()),
                        Some(LiteralNumericExpression { value: 5. }.into()),
                        Some(LiteralBooleanExpression { value: true }.into()),
                        Some(LiteralBooleanExpression { value: true }.into()),
                        Some(LiteralBooleanExpression { value: true }.into()),
                        Some(LiteralBooleanExpression { value: true }.into()),
                        Some(LiteralBooleanExpression { value: true }.into()),
                    ],
                }
                .into(),
            }
            .into()],
        };
        let expected = Script {
            scope: Default::default(),
            directives: vec![],
            statements: vec![ExpressionStatement {
                expression: BinASTExpressionWithProbabilityTable {
                    table: SharedString::from_str(DICTIONARY_NAME_PURE_DATA),
                    expression: ArrayExpression {
                        elements: vec![
                            Some(LiteralBooleanExpression { value: true }.into()),
                            Some(LiteralNullExpression {}.into()),
                            Some(LiteralNumericExpression { value: 5. }.into()),
                            Some(LiteralBooleanExpression { value: true }.into()),
                            Some(LiteralBooleanExpression { value: true }.into()),
                            Some(LiteralBooleanExpression { value: true }.into()),
                            Some(LiteralBooleanExpression { value: true }.into()),
                            Some(LiteralBooleanExpression { value: true }.into()),
                        ],
                    }
                    .into(),
                }
                .into(),
            }
            .into()],
        };

        check(5, source, expected);
    }

    #[test]
    fn test_sublanguage_pure_data_positive_object() {
        let source = Script {
            scope: Default::default(),
            directives: vec![],
            statements: vec![ExpressionStatement {
                expression: ObjectExpression {
                    properties: vec![
                        DataProperty {
                            name: LiteralPropertyName {
                                value: SharedString::from_str("a"),
                            }
                            .into(),
                            expression: LiteralBooleanExpression { value: true }.into(),
                        }
                        .into(),
                        DataProperty {
                            name: LiteralPropertyName {
                                value: SharedString::from_str("b"),
                            }
                            .into(),
                            expression: LiteralBooleanExpression { value: true }.into(),
                        }
                        .into(),
                        DataProperty {
                            name: LiteralPropertyName {
                                value: SharedString::from_str("c"),
                            }
                            .into(),
                            expression: LiteralBooleanExpression { value: true }.into(),
                        }
                        .into(),
                        DataProperty {
                            name: LiteralPropertyName {
                                value: SharedString::from_str("d"),
                            }
                            .into(),
                            expression: LiteralBooleanExpression { value: true }.into(),
                        }
                        .into(),
                    ],
                }
                .into(),
            }
            .into()],
        };
        let expected = Script {
            scope: Default::default(),
            directives: vec![],
            statements: vec![ExpressionStatement {
                expression: BinASTExpressionWithProbabilityTable {
                    table: SharedString::from_str(DICTIONARY_NAME_PURE_DATA),
                    expression: ObjectExpression {
                        properties: vec![
                            DataProperty {
                                name: LiteralPropertyName {
                                    value: SharedString::from_str("a"),
                                }
                                .into(),
                                expression: LiteralBooleanExpression { value: true }.into(),
                            }
                            .into(),
                            DataProperty {
                                name: LiteralPropertyName {
                                    value: SharedString::from_str("b"),
                                }
                                .into(),
                                expression: LiteralBooleanExpression { value: true }.into(),
                            }
                            .into(),
                            DataProperty {
                                name: LiteralPropertyName {
                                    value: SharedString::from_str("c"),
                                }
                                .into(),
                                expression: LiteralBooleanExpression { value: true }.into(),
                            }
                            .into(),
                            DataProperty {
                                name: LiteralPropertyName {
                                    value: SharedString::from_str("d"),
                                }
                                .into(),
                                expression: LiteralBooleanExpression { value: true }.into(),
                            }
                            .into(),
                        ],
                    }
                    .into(),
                }
                .into(),
            }
            .into()],
        };

        check(5, source, expected);
    }
    /// We have manually specified that `LiteralInfinityExpression` is complex.
    /// Check that this is taken into account.
    #[test]
    fn test_sublanguage_pure_data_negative_with_infinity() {
        let source = Script {
            scope: Default::default(),
            directives: vec![],
            statements: vec![ExpressionStatement {
                expression: ArrayExpression {
                    elements: vec![
                        Some(LiteralBooleanExpression { value: true }.into()),
                        Some(LiteralInfinityExpression {}.into()), // This prevents the subtree from being pure data.
                        Some(LiteralNumericExpression { value: 5. }.into()),
                        Some(LiteralBooleanExpression { value: true }.into()),
                        Some(LiteralBooleanExpression { value: true }.into()),
                        Some(LiteralBooleanExpression { value: true }.into()),
                        Some(LiteralBooleanExpression { value: true }.into()),
                        Some(LiteralBooleanExpression { value: true }.into()),
                    ],
                }
                .into(),
            }
            .into()],
        };

        check(5, source.clone(), source);
    }

    /// We have no rule for `ThisExpression`, so it should be complex.
    /// Check that this is taken into account.
    #[test]
    fn test_sublanguage_pure_data_negative_with_this() {
        let source = Script {
            scope: Default::default(),
            directives: vec![],
            statements: vec![ExpressionStatement {
                expression: ArrayExpression {
                    elements: vec![
                        Some(LiteralBooleanExpression { value: true }.into()),
                        Some(ThisExpression {}.into()), // This prevents the subtree from being pure data.
                        Some(LiteralNumericExpression { value: 5. }.into()),
                        Some(LiteralBooleanExpression { value: true }.into()),
                        Some(LiteralBooleanExpression { value: true }.into()),
                        Some(LiteralBooleanExpression { value: true }.into()),
                        Some(LiteralBooleanExpression { value: true }.into()),
                        Some(LiteralBooleanExpression { value: true }.into()),
                    ],
                }
                .into(),
            }
            .into()],
        };

        check(5, source.clone(), source);
    }

    /// We have no rule for `ThisExpression`, so it should be complex.
    /// Check that this is taken into account.
    #[test]
    fn test_sublanguage_pure_data_negative_object_with_this() {
        let source = Script {
            scope: Default::default(),
            directives: vec![],
            statements: vec![ExpressionStatement {
                expression: ObjectExpression {
                    properties: vec![
                        DataProperty {
                            name: LiteralPropertyName {
                                value: SharedString::from_str("a"),
                            }
                            .into(),
                            expression: LiteralBooleanExpression { value: true }.into(),
                        }
                        .into(),
                        DataProperty {
                            name: LiteralPropertyName {
                                value: SharedString::from_str("b"),
                            }
                            .into(),
                            expression: LiteralBooleanExpression { value: true }.into(),
                        }
                        .into(),
                        DataProperty {
                            name: LiteralPropertyName {
                                value: SharedString::from_str("c"),
                            }
                            .into(),
                            expression: LiteralBooleanExpression { value: true }.into(),
                        }
                        .into(),
                        DataProperty {
                            name: LiteralPropertyName {
                                value: SharedString::from_str("d"),
                            }
                            .into(),
                            expression: ThisExpression {}.into(),
                        }
                        .into(),
                    ],
                }
                .into(),
            }
            .into()],
        };

        check(5, source.clone(), source);
    }
}