RESS Scanners

In the initial implementation of the ress scanner, it was more important to get something working correctly than to have something blazing fast. To that end, the original Scanner performs a significant amount of memory allocation, which slows everything down quite a bit. To improve upon that ress offers a section option the RefScanner, which is a bit unfortunately named as it doesn't actually use any references. The RefScanner provides almost the same information as the Scanner but it does so without making any copies from the original javascript string, it the has the option to request the String for any Item giving the control to the user. Here is an example of the two approaches.

Example JS

function things() {
    return [1,2,3,4];

Example Rust

use ress::{
fn main() {
    let js = include_str!("../example.js");
    let scanner = Scanner::new(js);
    let ref_scanner = RefScanner::new(js);
    for (i, (item, ref_item) )in {
        let prefix = if i < 10 {
            format!(" {}", i)
        } else {
            format!("{}", i)
        println!("{} token: {:?}", prefix, item.token);
        println!("     ref: {:?}", ref_item.token);


 0 token: Keyword(Function)
     ref: Keyword(Function)
 1 token: Ident(Ident("things"))
     ref: Ident
 2 token: Punct(OpenParen)
     ref: Punct(OpenParen)
 3 token: Punct(CloseParen)
     ref: Punct(CloseParen)
 4 token: Punct(OpenBrace)
     ref: Punct(OpenBrace)
 5 token: Keyword(Return)
     ref: Keyword(Return)
 6 token: Punct(OpenBracket)
     ref: Punct(OpenBracket)
 7 token: Numeric(Number("1"))
     ref: Numeric(Dec)
 8 token: Punct(Comma)
     ref: Punct(Comma)
 9 token: Numeric(Number("2"))
     ref: Numeric(Dec)
10 token: Punct(Comma)
     ref: Punct(Comma)
11 token: Numeric(Number("3"))
     ref: Numeric(Dec)
12 token: Punct(Comma)
     ref: Punct(Comma)
13 token: Numeric(Number("4"))
     ref: Numeric(Dec)
14 token: Punct(CloseBracket)
     ref: Punct(CloseBracket)
15 token: Punct(SemiColon)
     ref: Punct(SemiColon)
16 token: Punct(CloseBrace)
     ref: Punct(CloseBrace)
17 token: EoF
     ref: EoF

Let's look at token 7, the original token is Token::Numeric(Number(String::From("1"))) while the ref token is Token::Numeric(Number::Dec), both give similar information but the ref token doesn't allocate a new string for the text being represented, instead just informing the user that it is a decimal number. If you wanted to know what that string was, you could use the RefScanner::string_for method by passing it RefItem.span, this will return an Option<String> and so long as your span doesn't overflow the length of the js provided, it will have the value you are looking for.