use std::{borrow::Cow, collections::hash_map::Entry};
use rustc_hash::{FxHashMap, FxHashSet};
use smallvec::SmallVec;
use oxc_ast::{
Comment, CommentKind,
ast::{Expression, Program},
};
use oxc_span::GetSpan;
use oxc_syntax::line_terminator::LineTerminatorSplitter;
use crate::{Codegen, LegalComment, options::CommentOptions};
type CommentList = SmallVec<[Comment; 1]>;
pub type CommentsMap = FxHashMap< u32, CommentList>;
fn preserve_when_orphaned(comment: &Comment) -> bool {
comment.is_legal() || comment.is_coverage_ignore_file()
}
fn breaks_line_between(prev: &Comment, comment: &Comment) -> bool {
breaks_line_after(prev) || comment.preceded_by_newline() || comment.is_legal()
}
fn breaks_line_after(last: &Comment) -> bool {
last.is_line() || last.followed_by_newline()
}
fn would_strand_comments(comments: &[Comment]) -> bool {
let first_line =
match comments.windows(2).position(|pair| breaks_line_between(&pair[0], &pair[1])) {
Some(i) => &comments[..=i],
None if comments.last().is_some_and(breaks_line_after) => comments,
None => return false,
};
first_line.iter().any(|c| !c.is_legal() && !c.is_property_key_annotation())
}
fn is_pife_function(expression: &Expression<'_>) -> bool {
match expression {
Expression::ArrowFunctionExpression(arrow) => arrow.pife,
Expression::FunctionExpression(function) => function.pife,
_ => false,
}
}
#[derive(Clone, Copy)]
pub enum AnnotationKind {
Pure,
NoSideEffects,
}
impl AnnotationKind {
#[inline]
fn matches(self, comment: &Comment) -> bool {
match self {
Self::Pure => comment.is_pure(),
Self::NoSideEffects => comment.is_no_side_effects(),
}
}
#[inline]
fn canonical(self, newline_after: bool) -> &'static str {
match (self, newline_after) {
(Self::Pure, false) => "/* @__PURE__ */ ",
(Self::Pure, true) => "/* @__PURE__ */\n",
(Self::NoSideEffects, false) => "/* @__NO_SIDE_EFFECTS__ */ ",
(Self::NoSideEffects, true) => "/* @__NO_SIDE_EFFECTS__ */\n",
}
}
}
impl Codegen<'_> {
pub(crate) fn build_comments(&mut self, comments: &[Comment]) {
if self.options.comments == CommentOptions::disabled() {
return;
}
self.comments.reserve(comments.len());
for comment in comments {
if comment.is_pure() || comment.is_no_side_effects() {
if comment.is_leading() && self.options.print_annotation_comment() {
self.annotation_comments.insert(comment.attached_to, comment.clone());
}
continue;
}
let mut add = false;
if comment.is_leading() {
add = (comment.is_legal() && self.options.print_legal_comment())
|| (comment.is_jsdoc() && self.options.print_jsdoc_comment())
|| (comment.is_annotation() && self.options.print_annotation_comment())
|| (comment.is_normal() && self.options.print_normal_comment());
}
if add {
self.has_property_key_annotations |= comment.is_property_key_annotation();
if preserve_when_orphaned(comment)
&& let Err(idx) = self.orphan_comment_keys.binary_search(&comment.attached_to)
{
self.orphan_comment_keys.insert(idx, comment.attached_to);
}
self.comments.entry(comment.attached_to).or_default().push(comment.clone());
}
}
}
pub(crate) fn has_comment(&self, start: u32) -> bool {
self.comments.contains_key(&start)
}
pub(crate) fn print_annotation_comment(
&mut self,
start: u32,
kind: AnnotationKind,
newline_after: bool,
) {
if self.source_text.is_some()
&& !self.annotation_comments.is_empty()
&& let Entry::Occupied(entry) = self.annotation_comments.entry(start)
&& kind.matches(entry.get())
&& (!entry.get().is_line() || newline_after)
{
let comment = entry.remove();
self.print_comment(&comment);
if newline_after {
self.print_hard_newline();
} else {
self.print_str(" ");
}
return;
}
self.print_str(kind.canonical(newline_after));
}
pub(crate) fn print_leading_comments(&mut self, start: u32) {
if let Some(comments) = self.comments.remove(&start) {
self.print_comments(&comments);
}
}
pub(crate) fn get_comments(&mut self, start: u32) -> Option<CommentList> {
if self.comments.is_empty() {
return None;
}
self.comments.remove(&start)
}
#[inline]
pub(crate) fn print_comments_at(&mut self, start: u32) {
if let Some(comments) = self.get_comments(start) {
self.print_comments(&comments);
}
}
#[inline]
pub(crate) fn print_leading_comments_anchored_to_self(&mut self, start: u32) {
if let Some(comments) = self.get_comments(start) {
self.print_comments_anchored_to_self(&comments);
}
}
fn print_comments_anchored_to_self(&mut self, comments: &[Comment]) {
self.print_comments(comments);
if self.last_byte() == Some(b'\n') {
self.print_indent();
} else {
self.consume_pending_indent_space();
}
}
#[inline]
pub(crate) fn print_property_key_annotation(&mut self, start: u32) {
if !self.has_property_key_annotations {
return;
}
if self
.comments
.get(&start)
.is_some_and(|comments| comments.iter().any(Comment::is_property_key_annotation))
{
self.print_leading_comments_anchored_to_self(start);
}
}
pub(crate) fn print_leading_comments_before_expression(&mut self, expression: &Expression<'_>) {
self.print_comments_through_parens(expression, |_| true);
}
pub(crate) fn print_annotation_comments_before_expression(
&mut self,
expression: &Expression<'_>,
) {
self.print_comments_through_parens(expression, |comments| {
comments.iter().any(Comment::is_annotation)
});
}
fn print_comments_through_parens(
&mut self,
mut expression: &Expression<'_>,
keep: impl Fn(&CommentList) -> bool,
) {
if self.comments.is_empty() {
return;
}
let mut merged = CommentList::new();
while !is_pife_function(expression) {
let start = expression.span().start;
if self.comments.get(&start).is_some_and(&keep) {
let group = self.comments.remove(&start).unwrap();
if merged.is_empty() {
merged = group;
} else {
merged.extend(group);
}
}
let Expression::ParenthesizedExpression(paren) = expression else { break };
expression = &paren.expression;
}
if !merged.is_empty() {
self.print_comments_anchored_to_self(&merged);
}
}
#[inline]
pub(crate) fn has_orphan_comments_before(&self, end: u32) -> bool {
self.orphan_comment_keys
.iter()
.take_while(|&&k| k < end)
.any(|k| self.comments.contains_key(k))
}
#[inline]
pub(crate) fn print_orphan_comments_before(&mut self, end: u32) {
if self.orphan_comment_keys.is_empty() {
return;
}
let idx = self.orphan_comment_keys.partition_point(|&k| k < end);
if idx == 0 {
return;
}
let mut orphans: Vec<Comment> = Vec::new();
let comments = &mut self.comments;
for k in self.orphan_comment_keys.drain(..idx) {
let Some(entry) = comments.get_mut(&k) else { continue };
debug_assert!(entry.iter().any(preserve_when_orphaned));
entry.retain(|comment| {
if preserve_when_orphaned(comment) {
orphans.push(comment.clone());
false
} else {
true
}
});
if entry.is_empty() {
comments.remove(&k);
}
}
if let Some(last) = orphans.last_mut() {
last.set_followed_by_newline(true);
self.print_comments(&orphans);
}
}
pub(crate) fn print_comments_in_range(&mut self, start: u32, end: u32) -> bool {
if self.comments.is_empty() {
return false;
}
let key = self.comments.keys().find(|&&k| k > start && k < end).copied();
if let Some(key) = key {
let comments = self.comments.remove(&key).unwrap();
self.print_comments(&comments);
return true;
}
false
}
pub(crate) fn print_expr_comments(&mut self, start: u32) -> bool {
if self.comments.is_empty() {
return false;
}
let Some(comments) = self.comments.remove(&start) else { return false };
for comment in &comments {
self.print_hard_newline();
self.print_indent();
self.print_comment(comment);
}
if comments.is_empty() {
false
} else {
self.print_hard_newline();
true
}
}
pub(crate) fn print_comments(&mut self, comments: &[Comment]) {
let Some((first, rest)) = comments.split_first() else {
return;
};
if first.preceded_by_newline() || would_strand_comments(comments) {
if let Some(b) = self.last_byte() {
match b {
b'\n' => self.print_indent(),
b'\t' => { }
_ => {
self.print_hard_newline();
self.print_indent();
}
}
}
} else if !self.consume_pending_indent_space()
&& matches!(self.last_byte(), None | Some(b'\n'))
{
self.print_indent();
}
self.print_comment(first);
let mut prev = first;
for comment in rest {
if breaks_line_between(prev, comment) {
self.print_hard_newline();
self.print_indent();
} else {
self.print_soft_space();
}
self.print_comment(comment);
prev = comment;
}
if breaks_line_after(prev) {
self.print_hard_newline();
} else {
self.print_next_indent_as_space = true;
}
}
fn print_comment(&mut self, comment: &Comment) {
let Some(source_text) = self.source_text else {
return;
};
let comment_source = comment.span.source_text(source_text);
match comment.kind {
CommentKind::Line | CommentKind::HtmlOpen | CommentKind::SingleLineBlock => {
self.print_str_escaping_script_close_tag(comment_source);
}
CommentKind::HtmlClose => {
let is_mid_line = self
.code()
.as_bytes()
.iter()
.rfind(|&&byte| !matches!(byte, b' ' | b'\t'))
.is_some_and(|&byte| byte != b'\n');
let text = if is_mid_line {
self.print_str("//");
comment.content_span().source_text(source_text)
} else {
comment_source
};
self.print_str_escaping_script_close_tag(text);
}
CommentKind::MultiLineBlock => {
for line in LineTerminatorSplitter::new(comment_source) {
if !line.starts_with("/*") {
self.print_indent();
}
self.print_str_escaping_script_close_tag(line.trim_start());
if !line.ends_with("*/") {
self.print_hard_newline();
}
}
}
}
}
pub(crate) fn handle_eof_linked_or_external_comments(
&mut self,
program: &Program<'_>,
) -> Vec<Comment> {
let legal_comments = &self.options.comments.legal;
if matches!(legal_comments, LegalComment::None | LegalComment::Inline) {
return vec![];
}
let mut set = FxHashSet::default();
let mut comments = vec![];
let source_text = program.source_text;
for comment in program.comments.iter().filter(|c| c.is_legal()) {
let mut text = Cow::Borrowed(comment.span.source_text(source_text));
if comment.is_multiline_block() {
let mut buffer = String::with_capacity(text.len());
for line in LineTerminatorSplitter::new(&text) {
if !line.starts_with("/*") {
buffer.push('\t');
}
buffer.push_str(line.trim_start());
if !line.ends_with("*/") {
buffer.push('\n');
}
}
text = Cow::Owned(buffer);
}
if set.insert(text) {
comments.push(comment.clone());
}
}
if comments.is_empty() {
return vec![];
}
match legal_comments {
LegalComment::Eof => {
self.print_hard_newline();
self.print_next_indent_as_space = false;
for c in comments {
self.print_comment(&c);
self.print_hard_newline();
}
vec![]
}
LegalComment::Linked(path) => {
let path = path.clone();
self.print_hard_newline();
self.print_str("/*! For license information please see ");
self.print_str(&path);
self.print_str(" */");
comments
}
LegalComment::External => comments,
LegalComment::None | LegalComment::Inline => unreachable!(),
}
}
}