Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

pragma ... cannot be set when runtime is automatic is emitted two times and at wrong position #4703

Closed
mischnic opened this issue May 18, 2022 · 2 comments · Fixed by #4704 or parcel-bundler/parcel#8107
Assignees
Milestone

Comments

@mischnic
Copy link
Contributor

After running the react transform, there are two errors/diagnostics emitted for pragma and pragmaFrag cannot be set when runtime is automatic (the two diagnostics have a slightly different end position though)

And ideally, it would also point to the actual comment on the first line and not to the line function ProductItem() {

Input code

(Using the automatic runtime)

/** @jsx foo */

function ProductItem() {
    return <div>Hello World</div>;
}

console.log(ProductItem);   

Current behaviour

-- Diagnostic --
Message:pragma and pragmaFrag cannot be set when runtime is automatic
Loc { file: SourceFile(test.js), line: 3, col: CharPos(0), col_display: 0 } - Loc { file: SourceFile(test.js), line: 7, col: CharPos(25), col_display: 25 } :: None
-- Diagnostic --
Message:pragma and pragmaFrag cannot be set when runtime is automatic
Loc { file: SourceFile(test.js), line: 3, col: CharPos(0), col_display: 0 } - Loc { file: SourceFile(test.js), line: 5, col: CharPos(1), col_display: 1 } :: None

Full Reproduction

Details
use std::collections::HashSet;

use swc::{self};
use swc_atoms::JsWord;
use swc_common::{
    chain,
    comments::SingleThreadedComments,
    errors::{DiagnosticBuilder, Emitter, Handler},
    sync::Lrc,
    FileName, Globals, Mark, SourceMap, SyntaxContext, DUMMY_SP,
};
use swc_ecma_ast::{CatchClause, Decl, Id, Ident, Module, Pat, Stmt, VarDeclKind};
use swc_ecma_codegen::{text_writer::JsWriter, Config};
use swc_ecma_parser::{lexer::Lexer, EsConfig, PResult, Parser, StringInput, Syntax, TsConfig};
use swc_ecma_preset_env::{preset_env, BrowserData, Mode, Targets, Version};
use swc_ecma_transforms::{
    compat::reserved_words::reserved_words,
    fixer,
    fixer::paren_remover,
    helpers, hygiene,
    optimization::simplify::{dead_branch_remover, expr_simplifier},
    react::{self, Runtime},
    resolver,
};
use swc_ecma_visit::{Fold, FoldWith, Visit, VisitWith};

#[derive(Debug, Clone, Default)]
pub struct ErrorBuffer(std::sync::Arc<std::sync::Mutex<Vec<swc_common::errors::Diagnostic>>>);

impl Emitter for ErrorBuffer {
    fn emit(&mut self, db: &DiagnosticBuilder) {
        self.0.lock().unwrap().push((**db).clone());
    }
}

fn main() {
    let cm = Lrc::<SourceMap>::default();
    let src = r#"/** @jsx foo */

function ProductItem() {
    return <div>Hello World</div>;
}

console.log(ProductItem);     
"#;
    let (module, comments) = parse(src, "test.js", &cm).unwrap();

    let error_buffer = ErrorBuffer::default();
    let handler = Handler::with_emitter(true, false, Box::new(error_buffer.clone()));
    swc_common::errors::HANDLER.set(&handler, || {
        swc_common::GLOBALS.set(&Globals::new(), || {
            helpers::HELPERS.set(&helpers::Helpers::default(), || {
                let unresolved_mark = Mark::fresh(Mark::root());
                let top_level_mark = Mark::fresh(Mark::root());
                let module =
                    module.fold_with(&mut resolver(unresolved_mark, top_level_mark, false));

                let module = module.fold_with(&mut react::react(
                    cm.clone(),
                    Some(&comments),
                    react::Options {
                        runtime: Some(Runtime::Automatic),
                        development: Some(false),
                        refresh: Some(Default::default()),
                        ..Default::default()
                    },
                    top_level_mark,
                ));
                let module = module.fold_with(&mut chain!(
                    reserved_words(),
                    hygiene(),
                    fixer(Some(&comments))
                ));

                for diagnostic in error_buffer.0.lock().unwrap().clone() {
                    let message = diagnostic.message();
                    let span = diagnostic.span.clone();
                    println!("-- Diagnostic --\nMessage:{}", message);

                    let span_labels = span.span_labels();
                    if !span_labels.is_empty() {
                        for span_label in span_labels {
                            let start = cm.lookup_char_pos(span_label.span.lo);
                            let end = cm.lookup_char_pos(span_label.span.hi);
                            println!("{:?} - {:?} :: {:?}", start, end, span_label.label);
                        }
                    };
                }

            });
        });
    });
}

fn parse(
    code: &str,
    filename: &str,
    cm: &Lrc<SourceMap>,
) -> PResult<(Module, SingleThreadedComments)> {
    let source_file = cm.new_source_file(FileName::Real(filename.into()), code.into());
    let comments = SingleThreadedComments::default();

    let lexer = Lexer::new(
        Syntax::Es(EsConfig {
            jsx: true,
            ..Default::default()
        }),
        Default::default(),
        StringInput::from(&*source_file),
        Some(&comments),
    );
    let mut parser = Parser::new_from(lexer);
    match parser.parse_module() {
        Err(err) => Err(err),
        Ok(module) => Ok((module, comments)),
    }
}

Version

6a7240f

Context

An example of how this manifests in Parcel at the moment. Duplicate error and wrong position

Bildschirmfoto 2022-05-18 um 19 57 33

@mischnic mischnic changed the title pragma and pragmaFrag cannot be set when runtime is automatic is emitted two times and at wrong position pragma ... cannot be set when runtime is automatic is emitted two times and at wrong position May 18, 2022
@kdy1 kdy1 added this to the Planned milestone May 18, 2022
@kdy1 kdy1 self-assigned this May 18, 2022
kdy1 added a commit to kdy1/swc that referenced this issue May 18, 2022
@mischnic
Copy link
Contributor Author

Thank you!

@swc-bot
Copy link
Collaborator

swc-bot commented Oct 16, 2022

This closed issue has been automatically locked because it had no new activity for a month. If you are running into a similar issue, please create a new issue with the steps to reproduce. Thank you.

@swc-project swc-project locked as resolved and limited conversation to collaborators Oct 16, 2022
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
3 participants