boa icon indicating copy to clipboard operation
boa copied to clipboard

to_interned_string breaks on object string keys

Open julianbraha opened this issue 1 year ago • 2 comments

See this example javascript code:

export const IconText = {
      extend: 'Flex',

      type: 'checkbox',
      ':checked + div': 'primary',
      display: 'none',
    };

and notice the ':checked + div' field.

After parsing this code, like so:

fn main() {
    let js_str = r#"export const IconText = {
      extend: 'Flex',

      type: 'checkbox',
      ':checked + div': 'primary',
      display: 'none',
    };"#;

    let js_code_bytes = js_str.as_bytes();

    let source = Source::from_bytes(js_code_bytes);

    let mut parser = parser::Parser::new(source);
    let mut interner = Interner::new();
    let tree = parser.parse_module(&mut interner);

    let output = match tree {
        Ok(root) => {
            let module_item_list: &boa_ast::ModuleItemList = module.items();
            let items: &[ModuleItem] = module_item_list.items();
            let item_0 = items[0].clone();

            if let ModuleItem::ExportDeclaration(e) = item_0 {
                if let ExportDeclaration::Declaration(d) = e {
                    let interned_string = d.to_interned_string(interner);
                    dbg!(interned_string);
                }
            }
        },
        Err(e) => panic!(),
    };
}

And after printing out the javascript code using d.to_interned_string(interner);, we see this result:

interned_string = "const IconText = {\n    extend: \"Flex\",\n    type: \"checkbox\",\n    :checked + div: \"primary\",\n    display: \"none\",\n};"

And most importantly, notice that \n :checked + div: no longer has the quotes that were in the input. But as you can see, the rest of the values in the object still have their quotes - just not this key.

julianbraha avatar Sep 02 '24 16:09 julianbraha

Hmm, this is a bit complex. We don't store the quotes on string properties because they're not needed on the AST itself, so we save a bit of memory doing this.

What I can think of is that this'll probably be resolved if we start implementing the AST spans, which will allow to reference the original lines of code (including quotes) when printing the AST as code.

jedel1043 avatar Sep 02 '24 17:09 jedel1043

Couldn't strings and identifiers just be parsed as separate constructs? Seems to me like PropertyDefinition just needs to support a String variant

julianbraha avatar Sep 08 '24 15:09 julianbraha