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
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
// Copyright 2018-2024 the Deno authors. MIT license.

use crate::analyzer::DependencyDescriptor;
use crate::analyzer::DynamicArgument;
use crate::analyzer::DynamicDependencyDescriptor;
use crate::analyzer::DynamicTemplatePart;
use crate::analyzer::ModuleAnalyzer;
use crate::analyzer::ModuleInfo;
use crate::analyzer::PositionRange;
use crate::analyzer::SpecifierWithRange;
use crate::analyzer::StaticDependencyDescriptor;
use crate::analyzer::TypeScriptReference;
use crate::graph::Position;
use crate::module_specifier::ModuleSpecifier;

use deno_ast::dep::DependencyComment;
use deno_ast::MultiThreadedComments;
use deno_ast::SourcePos;
use deno_ast::SourceRanged;
use deno_ast::SourceRangedForSpanned;

use deno_ast::swc::common::comments::CommentKind;
use deno_ast::MediaType;
use deno_ast::ParseDiagnostic;
use deno_ast::ParsedSource;
use deno_ast::SourceTextInfo;
use once_cell::sync::Lazy;
use regex::Match;
use regex::Regex;
use std::cell::RefCell;
use std::collections::HashMap;
use std::sync::Arc;

/// Matches a JSDoc import type reference (`{import("./example.js")}`
static JSDOC_IMPORT_RE: Lazy<Regex> = Lazy::new(|| {
  Regex::new(r#"\{[^}]*import\(['"]([^'"]+)['"]\)[^}]*}"#).unwrap()
});
/// Matches the `@jsxImportSource` pragma.
static JSX_IMPORT_SOURCE_RE: Lazy<Regex> =
  Lazy::new(|| Regex::new(r"(?i)^[\s*]*@jsxImportSource\s+(\S+)").unwrap());
/// Matches the `@jsxImportSourceTypes` pragma.
static JSX_IMPORT_SOURCE_TYPES_RE: Lazy<Regex> = Lazy::new(|| {
  Regex::new(r"(?i)^[\s*]*@jsxImportSourceTypes\s+(\S+)").unwrap()
});
/// Matches a `/// <reference ... />` comment reference.
static TRIPLE_SLASH_REFERENCE_RE: Lazy<Regex> =
  Lazy::new(|| Regex::new(r"(?i)^/\s*<reference\s.*?/>").unwrap());
/// Matches a path reference, which adds a dependency to a module
static PATH_REFERENCE_RE: Lazy<Regex> =
  Lazy::new(|| Regex::new(r#"(?i)\spath\s*=\s*["']([^"']*)["']"#).unwrap());
/// Matches a types reference, which for JavaScript files indicates the
/// location of types to use when type checking a program that includes it as
/// a dependency.
static TYPES_REFERENCE_RE: Lazy<Regex> =
  Lazy::new(|| Regex::new(r#"(?i)\stypes\s*=\s*["']([^"']*)["']"#).unwrap());
/// Matches the `@ts-self-types` pragma.
static TS_SELF_TYPES_RE: Lazy<Regex> = Lazy::new(|| {
  Regex::new(r#"(?i)^\s*@ts-self-types\s*=\s*["']([^"']+)["']"#).unwrap()
});
/// Matches the `@ts-types` pragma.
static TS_TYPES_RE: Lazy<Regex> = Lazy::new(|| {
  Regex::new(r#"(?i)^\s*@ts-types\s*=\s*["']([^"']+)["']"#).unwrap()
});
/// Matches the `@deno-types` pragma.
pub static DENO_TYPES_RE: Lazy<Regex> = Lazy::new(|| {
  Regex::new(r#"(?i)^\s*@deno-types\s*=\s*(?:["']([^"']+)["']|(\S+))"#).unwrap()
});

pub struct ParseOptions<'a> {
  pub specifier: &'a ModuleSpecifier,
  pub source: Arc<str>,
  pub media_type: MediaType,
  pub scope_analysis: bool,
}

/// Parses modules to a ParsedSource.
pub trait ModuleParser {
  fn parse_module(
    &self,
    options: ParseOptions,
  ) -> Result<ParsedSource, ParseDiagnostic>;
}

#[derive(Default, Clone)]
pub struct DefaultModuleParser;

impl ModuleParser for DefaultModuleParser {
  fn parse_module(
    &self,
    options: ParseOptions,
  ) -> Result<ParsedSource, ParseDiagnostic> {
    deno_ast::parse_module(deno_ast::ParseParams {
      specifier: options.specifier.clone(),
      text_info: SourceTextInfo::new(options.source),
      media_type: options.media_type,
      capture_tokens: options.scope_analysis,
      scope_analysis: options.scope_analysis,
      maybe_syntax: None,
    })
  }
}

/// Stores parsed sources.
///
/// Note: This interface is racy and not thread safe, as it's assumed
/// it will only store the latest changes or that the source text
/// will never change.
pub trait ParsedSourceStore {
  /// Sets the parsed source, potentially returning the previous value.
  fn set_parsed_source(
    &self,
    specifier: ModuleSpecifier,
    parsed_source: ParsedSource,
  ) -> Option<ParsedSource>;
  fn get_parsed_source(
    &self,
    specifier: &ModuleSpecifier,
  ) -> Option<ParsedSource>;
  fn remove_parsed_source(
    &self,
    specifier: &ModuleSpecifier,
  ) -> Option<ParsedSource> {
    // todo(dsherret): remove this default implementation once a breaking change is done to deno_graph
    self.get_parsed_source(specifier)
  }
  /// Gets a `deno_ast::ParsedSource` from the store, upgrading it
  /// to have scope analysis if it doesn't already.
  fn get_scope_analysis_parsed_source(
    &self,
    specifier: &ModuleSpecifier,
  ) -> Option<ParsedSource>;
}

/// Default store that works on a single thread.
#[derive(Default)]
pub struct DefaultParsedSourceStore {
  store: RefCell<HashMap<ModuleSpecifier, ParsedSource>>,
}

impl ParsedSourceStore for DefaultParsedSourceStore {
  fn set_parsed_source(
    &self,
    specifier: ModuleSpecifier,
    parsed_source: ParsedSource,
  ) -> Option<ParsedSource> {
    self.store.borrow_mut().insert(specifier, parsed_source)
  }

  fn get_parsed_source(
    &self,
    specifier: &ModuleSpecifier,
  ) -> Option<ParsedSource> {
    self.store.borrow().get(specifier).cloned()
  }

  fn remove_parsed_source(
    &self,
    specifier: &ModuleSpecifier,
  ) -> Option<ParsedSource> {
    self.store.borrow_mut().remove(specifier)
  }

  fn get_scope_analysis_parsed_source(
    &self,
    specifier: &ModuleSpecifier,
  ) -> Option<ParsedSource> {
    let mut store = self.store.borrow_mut();
    let parsed_source = store.get_mut(specifier)?;
    if parsed_source.has_scope_analysis() {
      Some(parsed_source.clone())
    } else {
      let parsed_source = store.remove(specifier).unwrap();
      let parsed_source = parsed_source.into_with_scope_analysis();
      store.insert(specifier.clone(), parsed_source.clone());
      Some(parsed_source.clone())
    }
  }
}

/// Stores parsed files in the provided store after parsing.
/// in a provided store. Parses that match the previous one
/// will be cached.
///
/// Note that this will insert into the store whatever was
/// last parsed, so if two threads race to parse, when they're
/// both done it will have whatever was last stored.
#[derive(Clone, Copy)]
pub struct CapturingModuleParser<'a> {
  parser: Option<&'a dyn ModuleParser>,
  store: &'a dyn ParsedSourceStore,
}

impl<'a> CapturingModuleParser<'a> {
  pub fn new(
    parser: Option<&'a dyn ModuleParser>,
    store: &'a dyn ParsedSourceStore,
  ) -> Self {
    Self { parser, store }
  }

  fn get_from_store_if_matches(
    &self,
    options: &ParseOptions,
  ) -> Option<ParsedSource> {
    let parsed_source = if options.scope_analysis {
      self
        .store
        .get_scope_analysis_parsed_source(options.specifier)?
    } else {
      self.store.get_parsed_source(options.specifier)?
    };
    if parsed_source.media_type() == options.media_type
      && parsed_source.text_info().text_str() == options.source.as_ref()
    {
      Some(parsed_source)
    } else {
      None
    }
  }
}

impl<'a> ModuleParser for CapturingModuleParser<'a> {
  fn parse_module(
    &self,
    options: ParseOptions,
  ) -> Result<ParsedSource, ParseDiagnostic> {
    if let Some(parsed_source) = self.get_from_store_if_matches(&options) {
      Ok(parsed_source)
    } else {
      let default_parser = DefaultModuleParser;
      let parser = self.parser.unwrap_or(&default_parser);
      let specifier = options.specifier.clone();
      let parsed_source = parser.parse_module(options)?;
      self
        .store
        .set_parsed_source(specifier, parsed_source.clone());
      Ok(parsed_source)
    }
  }
}

#[derive(Default)]
pub struct DefaultModuleAnalyzer;

impl ModuleAnalyzer for DefaultModuleAnalyzer {
  fn analyze(
    &self,
    specifier: &deno_ast::ModuleSpecifier,
    source: Arc<str>,
    media_type: MediaType,
  ) -> Result<ModuleInfo, ParseDiagnostic> {
    ParserModuleAnalyzer::default().analyze(specifier, source, media_type)
  }
}

/// Default module analyzer that analyzes based on a deno_ast::ParsedSource.
pub struct ParserModuleAnalyzer<'a> {
  parser: &'a dyn ModuleParser,
}

impl<'a> ParserModuleAnalyzer<'a> {
  /// Creates a new module analyzer.
  pub fn new(parser: &'a dyn ModuleParser) -> Self {
    Self { parser }
  }

  /// Gets the module info from a parsed source.
  pub fn module_info(parsed_source: &ParsedSource) -> ModuleInfo {
    let module = match parsed_source.program_ref() {
      deno_ast::swc::ast::Program::Module(m) => m,
      deno_ast::swc::ast::Program::Script(_) => return ModuleInfo::default(),
    };
    Self::module_info_from_swc(
      parsed_source.media_type(),
      module,
      parsed_source.text_info(),
      parsed_source.comments(),
    )
  }

  pub fn module_info_from_swc(
    media_type: MediaType,
    module: &deno_ast::swc::ast::Module,
    text_info: &SourceTextInfo,
    comments: &MultiThreadedComments,
  ) -> ModuleInfo {
    let leading_comments = match module.body.first() {
      Some(item) => comments.get_leading(item.start()),
      None => match module.shebang {
        Some(_) => comments.get_trailing(module.end()),
        None => comments.get_leading(module.start()),
      },
    };
    ModuleInfo {
      dependencies: analyze_dependencies(module, text_info, comments),
      ts_references: analyze_ts_references(text_info, leading_comments),
      self_types_specifier: analyze_ts_self_types(
        media_type,
        text_info,
        leading_comments,
      ),
      jsx_import_source: analyze_jsx_import_source(
        media_type,
        text_info,
        leading_comments,
      ),
      jsx_import_source_types: analyze_jsx_import_source_types(
        media_type,
        text_info,
        leading_comments,
      ),
      jsdoc_imports: analyze_jsdoc_imports(media_type, text_info, comments),
    }
  }
}

impl<'a> Default for ParserModuleAnalyzer<'a> {
  fn default() -> Self {
    Self {
      parser: &DefaultModuleParser,
    }
  }
}

impl<'a> ModuleAnalyzer for ParserModuleAnalyzer<'a> {
  fn analyze(
    &self,
    specifier: &deno_ast::ModuleSpecifier,
    source: Arc<str>,
    media_type: MediaType,
  ) -> Result<ModuleInfo, ParseDiagnostic> {
    let parsed_source = self.parser.parse_module(ParseOptions {
      specifier,
      source,
      media_type,
      // scope analysis is not necessary for module parsing
      scope_analysis: false,
    })?;
    Ok(ParserModuleAnalyzer::module_info(&parsed_source))
  }
}

/// Helper struct for creating a single object that implements
/// `deno_graph::ModuleAnalyzer`, `deno_graph::ModuleParser`,
/// and `deno_graph::ParsedSourceStore`. All parses will be captured
/// to prevent them from occuring more than one time.
pub struct CapturingModuleAnalyzer {
  parser: Box<dyn ModuleParser>,
  store: Box<dyn ParsedSourceStore>,
}

impl Default for CapturingModuleAnalyzer {
  fn default() -> Self {
    Self::new(None, None)
  }
}

impl CapturingModuleAnalyzer {
  pub fn new(
    parser: Option<Box<dyn ModuleParser>>,
    store: Option<Box<dyn ParsedSourceStore>>,
  ) -> Self {
    Self {
      parser: parser.unwrap_or_else(|| Box::<DefaultModuleParser>::default()),
      store: store
        .unwrap_or_else(|| Box::<DefaultParsedSourceStore>::default()),
    }
  }

  pub fn as_capturing_parser(&self) -> CapturingModuleParser {
    CapturingModuleParser::new(Some(&*self.parser), &*self.store)
  }
}

impl ModuleAnalyzer for CapturingModuleAnalyzer {
  fn analyze(
    &self,
    specifier: &deno_ast::ModuleSpecifier,
    source: Arc<str>,
    media_type: MediaType,
  ) -> Result<ModuleInfo, ParseDiagnostic> {
    let capturing_parser = self.as_capturing_parser();
    let module_analyzer = ParserModuleAnalyzer::new(&capturing_parser);
    module_analyzer.analyze(specifier, source, media_type)
  }
}

impl ModuleParser for CapturingModuleAnalyzer {
  fn parse_module(
    &self,
    options: ParseOptions,
  ) -> Result<ParsedSource, ParseDiagnostic> {
    let capturing_parser = self.as_capturing_parser();
    capturing_parser.parse_module(options)
  }
}

impl ParsedSourceStore for CapturingModuleAnalyzer {
  fn set_parsed_source(
    &self,
    specifier: ModuleSpecifier,
    parsed_source: ParsedSource,
  ) -> Option<ParsedSource> {
    self.store.set_parsed_source(specifier, parsed_source)
  }

  fn get_parsed_source(
    &self,
    specifier: &ModuleSpecifier,
  ) -> Option<ParsedSource> {
    self.store.get_parsed_source(specifier)
  }

  fn remove_parsed_source(
    &self,
    specifier: &ModuleSpecifier,
  ) -> Option<ParsedSource> {
    self.store.remove_parsed_source(specifier)
  }

  fn get_scope_analysis_parsed_source(
    &self,
    specifier: &ModuleSpecifier,
  ) -> Option<ParsedSource> {
    self.store.get_scope_analysis_parsed_source(specifier)
  }
}

fn analyze_dependencies(
  module: &deno_ast::swc::ast::Module,
  text_info: &SourceTextInfo,
  comments: &MultiThreadedComments,
) -> Vec<DependencyDescriptor> {
  let deps = deno_ast::dep::analyze_module_dependencies(module, comments);

  deps
    .into_iter()
    .map(|d| match d {
      deno_ast::dep::DependencyDescriptor::Static(d) => {
        DependencyDescriptor::Static(StaticDependencyDescriptor {
          kind: d.kind,
          types_specifier: analyze_ts_or_deno_types(
            text_info,
            &d.leading_comments,
          ),
          specifier: d.specifier.to_string(),
          specifier_range: PositionRange::from_source_range(
            d.specifier_range,
            text_info,
          ),
          import_attributes: d.import_attributes,
        })
      }
      deno_ast::dep::DependencyDescriptor::Dynamic(d) => {
        DependencyDescriptor::Dynamic(DynamicDependencyDescriptor {
          types_specifier: analyze_ts_or_deno_types(
            text_info,
            &d.leading_comments,
          ),
          argument: match d.argument {
            deno_ast::dep::DynamicArgument::String(text) => {
              DynamicArgument::String(text.to_string())
            }
            deno_ast::dep::DynamicArgument::Template(parts) => {
              DynamicArgument::Template(
                parts
                  .into_iter()
                  .map(|part| match part {
                    deno_ast::dep::DynamicTemplatePart::String(text) => {
                      DynamicTemplatePart::String {
                        value: text.to_string(),
                      }
                    }
                    deno_ast::dep::DynamicTemplatePart::Expr => {
                      DynamicTemplatePart::Expr
                    }
                  })
                  .collect(),
              )
            }
            deno_ast::dep::DynamicArgument::Expr => DynamicArgument::Expr,
          },
          argument_range: PositionRange::from_source_range(
            d.argument_range,
            text_info,
          ),
          import_attributes: d.import_attributes,
        })
      }
    })
    .collect()
}

fn analyze_ts_references(
  text_info: &SourceTextInfo,
  leading_comments: Option<&Vec<deno_ast::swc::common::comments::Comment>>,
) -> Vec<TypeScriptReference> {
  let mut references = Vec::new();
  if let Some(c) = leading_comments {
    for comment in c {
      if comment.kind == CommentKind::Line
        && TRIPLE_SLASH_REFERENCE_RE.is_match(&comment.text)
      {
        let comment_start = comment.start();
        if let Some(captures) = PATH_REFERENCE_RE.captures(&comment.text) {
          let m = captures.get(1).unwrap();
          references.push(TypeScriptReference::Path(SpecifierWithRange {
            text: m.as_str().to_string(),
            range: comment_source_to_position_range(
              comment_start,
              &m,
              text_info,
              false,
            ),
          }));
        } else if let Some(captures) =
          TYPES_REFERENCE_RE.captures(&comment.text)
        {
          let m = captures.get(1).unwrap();
          references.push(TypeScriptReference::Types(SpecifierWithRange {
            text: m.as_str().to_string(),
            range: comment_source_to_position_range(
              comment_start,
              &m,
              text_info,
              false,
            ),
          }));
        }
      }
    }
  }
  references
}

fn analyze_jsx_import_source(
  media_type: MediaType,
  text_info: &SourceTextInfo,
  leading_comments: Option<&Vec<deno_ast::swc::common::comments::Comment>>,
) -> Option<SpecifierWithRange> {
  if !matches!(media_type, MediaType::Jsx | MediaType::Tsx) {
    return None;
  }

  leading_comments.and_then(|c| {
    c.iter().find_map(|c| {
      if c.kind != CommentKind::Block {
        return None; // invalid
      }
      let captures = JSX_IMPORT_SOURCE_RE.captures(&c.text)?;
      let m = captures.get(1)?;
      Some(SpecifierWithRange {
        text: m.as_str().to_string(),
        range: comment_source_to_position_range(c.start(), &m, text_info, true),
      })
    })
  })
}

fn analyze_jsx_import_source_types(
  media_type: MediaType,
  text_info: &SourceTextInfo,
  leading_comments: Option<&Vec<deno_ast::swc::common::comments::Comment>>,
) -> Option<SpecifierWithRange> {
  if !matches!(media_type, MediaType::Jsx | MediaType::Tsx) {
    return None;
  }

  leading_comments.and_then(|c| {
    c.iter().find_map(|c| {
      if c.kind != CommentKind::Block {
        return None; // invalid
      }
      let captures = JSX_IMPORT_SOURCE_TYPES_RE.captures(&c.text)?;
      let m = captures.get(1)?;
      Some(SpecifierWithRange {
        text: m.as_str().to_string(),
        range: comment_source_to_position_range(c.start(), &m, text_info, true),
      })
    })
  })
}

fn analyze_ts_self_types(
  media_type: MediaType,
  text_info: &SourceTextInfo,
  leading_comments: Option<&Vec<deno_ast::swc::common::comments::Comment>>,
) -> Option<SpecifierWithRange> {
  if media_type.is_typed() {
    return None;
  }

  leading_comments.and_then(|c| {
    c.iter().find_map(|c| {
      let captures = TS_SELF_TYPES_RE.captures(&c.text)?;
      let m = captures.get(1)?;
      Some(SpecifierWithRange {
        text: m.as_str().to_string(),
        range: comment_source_to_position_range(
          c.start(),
          &m,
          text_info,
          false,
        ),
      })
    })
  })
}

/// Searches comments for any `@ts-types` or `@deno-types` compiler hints.
pub fn analyze_ts_or_deno_types(
  text_info: &SourceTextInfo,
  leading_comments: &[DependencyComment],
) -> Option<SpecifierWithRange> {
  let comment = leading_comments.last()?;

  if let Some(captures) = TS_TYPES_RE.captures(&comment.text) {
    if let Some(m) = captures.get(1) {
      return Some(SpecifierWithRange {
        text: m.as_str().to_string(),
        range: comment_source_to_position_range(
          comment.range.start(),
          &m,
          text_info,
          false,
        ),
      });
    }
  }
  let captures = DENO_TYPES_RE.captures(&comment.text)?;
  if let Some(m) = captures.get(1) {
    Some(SpecifierWithRange {
      text: m.as_str().to_string(),
      range: comment_source_to_position_range(
        comment.range.start(),
        &m,
        text_info,
        false,
      ),
    })
  } else if let Some(m) = captures.get(2) {
    Some(SpecifierWithRange {
      text: m.as_str().to_string(),
      range: comment_source_to_position_range(
        comment.range.start(),
        &m,
        text_info,
        true,
      ),
    })
  } else {
    unreachable!("Unexpected captures from deno types regex")
  }
}

fn analyze_jsdoc_imports(
  media_type: MediaType,
  text_info: &SourceTextInfo,
  comments: &MultiThreadedComments,
) -> Vec<SpecifierWithRange> {
  // Analyze any JSDoc type imports
  // We only analyze these on JavaScript types of modules, since they are
  // ignored by TypeScript when type checking anyway and really shouldn't be
  // there, but some people do strange things.
  if !matches!(
    media_type,
    MediaType::JavaScript | MediaType::Jsx | MediaType::Mjs | MediaType::Cjs
  ) {
    return Vec::new();
  }

  let mut deps = Vec::new();
  for comment in comments.iter_unstable() {
    if comment.kind != CommentKind::Block || !comment.text.starts_with('*') {
      continue;
    }
    for captures in JSDOC_IMPORT_RE.captures_iter(&comment.text) {
      if let Some(m) = captures.get(1) {
        deps.push(SpecifierWithRange {
          text: m.as_str().to_string(),
          range: comment_source_to_position_range(
            comment.range().start,
            &m,
            text_info,
            false,
          ),
        });
      }
    }
  }
  deps.sort_by(|a, b| a.range.start.cmp(&b.range.start));
  deps
}

fn comment_source_to_position_range(
  comment_start: SourcePos,
  m: &Match,
  text_info: &SourceTextInfo,
  is_specifier_quoteless: bool,
) -> PositionRange {
  // the comment text starts after the double slash or slash star, so add 2
  let comment_start = comment_start + 2;
  // -1 and +1 to include the quotes, but not for pragmas that don't have quotes
  let padding = if is_specifier_quoteless { 0 } else { 1 };
  PositionRange {
    start: Position::from_source_pos(
      comment_start + m.start() - padding,
      text_info,
    ),
    end: Position::from_source_pos(
      comment_start + m.end() + padding,
      text_info,
    ),
  }
}

#[cfg(test)]
mod tests {
  use super::*;
  use pretty_assertions::assert_eq;

  #[test]
  fn test_parse() {
    let specifier =
      ModuleSpecifier::parse("file:///a/test.tsx").expect("bad specifier");
    let source = r#"
    /// <reference path="./ref.d.ts" />
    /// <reference types="./types.d.ts" />
    // @jsxImportSource http://example.com/invalid
    /* @jsxImportSource http://example.com/preact */
    // @jsxImportSourceTypes http://example.com/invalidTypes
    /* @jsxImportSourceTypes http://example.com/preactTypes */
    import {
      A,
      B,
      C,
      D,
    } from "https://deno.land/x/example@v1.0.0/mod.ts";

    export * from "./mod.ts";

    import type { Component } from "https://esm.sh/preact";
    import { h, Fragment } from "https://esm.sh/preact";

    // other
    // @deno-types="https://deno.land/x/types/react/index.d.ts"
    import React from "https://cdn.skypack.dev/react";

    // @deno-types=https://deno.land/x/types/react/index.d.ts
    import React2 from "https://cdn.skypack.dev/react";

    // @deno-types="https://deno.land/x/types/react/index.d.ts"
    // other comment first
    import React3 from "https://cdn.skypack.dev/react";

    const a = await import("./a.ts");

    const React4 = await /* @deno-types="https://deno.land/x/types/react/index.d.ts" */ import("https://cdn.skypack.dev/react");
    "#;
    let parsed_source = DefaultModuleParser
      .parse_module(ParseOptions {
        specifier: &specifier,
        source: source.into(),
        media_type: MediaType::Tsx,
        scope_analysis: false,
      })
      .unwrap();
    let text_info = parsed_source.text_info();
    let module_info = ParserModuleAnalyzer::module_info(&parsed_source);
    let dependencies = module_info.dependencies;
    assert_eq!(dependencies.len(), 9);

    let ts_references = module_info.ts_references;
    assert_eq!(ts_references.len(), 2);
    match &ts_references[0] {
      TypeScriptReference::Path(specifier) => {
        assert_eq!(specifier.text, "./ref.d.ts");
        assert_eq!(
          text_info.range_text(&specifier.range.as_source_range(text_info)),
          r#""./ref.d.ts""#
        );
      }
      TypeScriptReference::Types(_) => panic!("expected path"),
    }
    match &ts_references[1] {
      TypeScriptReference::Path(_) => panic!("expected types"),
      TypeScriptReference::Types(specifier) => {
        assert_eq!(specifier.text, "./types.d.ts");
        assert_eq!(
          text_info.range_text(&specifier.range.as_source_range(text_info)),
          r#""./types.d.ts""#
        );
      }
    }

    let dep_deno_types = &dependencies[4]
      .as_static()
      .unwrap()
      .types_specifier
      .as_ref()
      .unwrap();
    assert_eq!(
      dep_deno_types.text,
      "https://deno.land/x/types/react/index.d.ts"
    );
    assert_eq!(
      text_info.range_text(&dep_deno_types.range.as_source_range(text_info)),
      r#""https://deno.land/x/types/react/index.d.ts""#
    );

    let dep_deno_types = &dependencies[5]
      .as_static()
      .unwrap()
      .types_specifier
      .as_ref()
      .unwrap();
    assert_eq!(
      dep_deno_types.text,
      "https://deno.land/x/types/react/index.d.ts"
    );
    assert_eq!(
      text_info.range_text(&dep_deno_types.range.as_source_range(text_info)),
      r#"https://deno.land/x/types/react/index.d.ts"#
    );

    assert!(dependencies[6]
      .as_static()
      .unwrap()
      .types_specifier
      .is_none());

    let dep_deno_types = &dependencies[8]
      .as_dynamic()
      .unwrap()
      .types_specifier
      .as_ref()
      .unwrap();
    assert_eq!(
      dep_deno_types.text,
      "https://deno.land/x/types/react/index.d.ts"
    );
    assert_eq!(
      text_info.range_text(&dep_deno_types.range.as_source_range(text_info)),
      r#""https://deno.land/x/types/react/index.d.ts""#
    );

    let jsx_import_source = module_info.jsx_import_source.unwrap();
    assert_eq!(jsx_import_source.text, "http://example.com/preact");
    assert_eq!(
      text_info.range_text(&jsx_import_source.range.as_source_range(text_info)),
      "http://example.com/preact"
    );

    let jsx_import_source_types = module_info.jsx_import_source_types.unwrap();
    assert_eq!(
      jsx_import_source_types.text,
      "http://example.com/preactTypes"
    );
    assert_eq!(
      text_info
        .range_text(&jsx_import_source_types.range.as_source_range(text_info)),
      "http://example.com/preactTypes"
    );

    assert!(module_info.self_types_specifier.is_none());
  }

  #[test]
  fn test_analyze_dependencies() {
    let specifier =
      ModuleSpecifier::parse("file:///a/test.ts").expect("bad specifier");
    let source = r#"
    import * as a from "./a.ts";
    import "./b.ts";
    import { c } from "./c.ts";
    import d from "./d.ts";
    import e, { ee } from "./e.ts";
    const f = await import("./f.ts");
    export * from "./g.ts";
    export { h } from "./h.ts";

    import type { i } from "./i.d.ts";
    export type { j } from "./j.d.ts";
    "#;
    let parsed_source = DefaultModuleParser
      .parse_module(ParseOptions {
        specifier: &specifier,
        source: source.into(),
        media_type: MediaType::TypeScript,
        scope_analysis: false,
      })
      .unwrap();
    let module_info = ParserModuleAnalyzer::module_info(&parsed_source);
    let text_info = parsed_source.text_info();
    let dependencies = module_info.dependencies;
    assert_eq!(dependencies.len(), 10);
    let dep = dependencies[0].as_static().unwrap();
    assert_eq!(dep.specifier.to_string(), "./a.ts");
    assert_eq!(
      text_info.range_text(&dep.specifier_range.as_source_range(text_info)),
      "\"./a.ts\""
    );
    let dep = dependencies[1].as_static().unwrap();
    assert_eq!(dep.specifier.to_string(), "./b.ts");
    assert_eq!(
      text_info.range_text(&dep.specifier_range.as_source_range(text_info)),
      "\"./b.ts\""
    );
  }

  #[test]
  fn test_analyze_self_types() {
    let specifier =
      ModuleSpecifier::parse("file:///a/test.js").expect("bad specifier");
    let source = r#"
      // @ts-self-types="./self.d.ts"

      import * as a from "./a.ts";
    "#;
    let parsed_source = DefaultModuleParser
      .parse_module(ParseOptions {
        specifier: &specifier,
        source: source.into(),
        media_type: MediaType::JavaScript,
        scope_analysis: false,
      })
      .unwrap();
    let module_info = ParserModuleAnalyzer::module_info(&parsed_source);
    let text_info = parsed_source.text_info();
    let dependencies = module_info.dependencies;
    assert_eq!(dependencies.len(), 1);
    let dep = dependencies[0].as_static().unwrap();
    assert_eq!(dep.specifier.to_string(), "./a.ts");
    assert_eq!(
      text_info.range_text(&dep.specifier_range.as_source_range(text_info)),
      "\"./a.ts\""
    );

    let self_types_specifier = module_info.self_types_specifier.unwrap();
    assert_eq!(self_types_specifier.text, "./self.d.ts");
    assert_eq!(
      text_info
        .range_text(&self_types_specifier.range.as_source_range(text_info)),
      "\"./self.d.ts\""
    );
  }

  #[test]
  fn test_analyze_dependencies_import_attributes() {
    let specifier =
      ModuleSpecifier::parse("file:///a/test.ts").expect("bad specifier");
    for keyword in ["assert", "with"] {
      let source = format!(
        "
      import a from \"./a.json\" {keyword} {{ type: \"json\" }};
      await import(\"./b.json\", {{ {keyword}: {{ type: \"json\" }} }});
      "
      );
      let parsed_source = DefaultModuleParser
        .parse_module(ParseOptions {
          specifier: &specifier,
          source: source.into(),
          media_type: MediaType::TypeScript,
          scope_analysis: false,
        })
        .unwrap();
      let module_info = ParserModuleAnalyzer::module_info(&parsed_source);
      let dependencies = module_info.dependencies;
      assert_eq!(dependencies.len(), 2);
      let dep = dependencies[0].as_static().unwrap();
      assert_eq!(dep.specifier.to_string(), "./a.json");
      assert_eq!(dep.import_attributes.get("type"), Some(&"json".to_string()));
      let dep = dependencies[1].as_dynamic().unwrap();
      assert_eq!(
        dep.argument,
        DynamicArgument::String("./b.json".to_string())
      );
      assert_eq!(dep.import_attributes.get("type"), Some(&"json".to_string()));
    }
  }

  #[test]
  fn test_analyze_jsdoc_imports() {
    let specifier = ModuleSpecifier::parse("file:///a/test.js").unwrap();
    let source = r#"
/** @module */

/**
 * Some stuff here
 *
 * @type {import("./a.js").A}
 */
const a = "a";

/**
 * Some other stuff here
 *
 * @param {import('./b.js').C}
 * @returns {import("./d.js")}
 */
function b(c) {
  return;
}

/**
 * @type {Set<import("./e.js").F>}
 */
const f = new Set();
"#;
    let parsed_source = DefaultModuleParser
      .parse_module(ParseOptions {
        specifier: &specifier,
        source: source.into(),
        media_type: MediaType::JavaScript,
        scope_analysis: false,
      })
      .unwrap();
    let module_info = ParserModuleAnalyzer::module_info(&parsed_source);
    let dependencies = module_info.jsdoc_imports;
    assert_eq!(
      dependencies,
      [
        SpecifierWithRange {
          text: "./a.js".to_string(),
          range: PositionRange {
            start: Position {
              line: 6,
              character: 17
            },
            end: Position {
              line: 6,
              character: 25
            }
          }
        },
        SpecifierWithRange {
          text: "./b.js".to_string(),
          range: PositionRange {
            start: Position {
              line: 13,
              character: 18
            },
            end: Position {
              line: 13,
              character: 26
            }
          }
        },
        SpecifierWithRange {
          text: "./d.js".to_string(),
          range: PositionRange {
            start: Position {
              line: 14,
              character: 20
            },
            end: Position {
              line: 14,
              character: 28
            }
          }
        },
        SpecifierWithRange {
          text: "./e.js".to_string(),
          range: PositionRange {
            start: Position {
              line: 21,
              character: 21
            },
            end: Position {
              line: 21,
              character: 29
            }
          }
        },
      ]
    );
  }

  #[test]
  fn test_analyze_ts_references_and_jsx_import_source_with_shebang() {
    let specifier = ModuleSpecifier::parse("file:///a/test.tsx").unwrap();
    let source = r#"#!/usr/bin/env -S deno run
/// <reference path="./ref.d.ts" />
/* @jsxImportSource preact */
export {};
"#;
    let module_info = DefaultModuleAnalyzer
      .analyze(&specifier, source.into(), MediaType::Tsx)
      .unwrap();
    assert_eq!(
      module_info,
      ModuleInfo {
        dependencies: vec![],
        ts_references: vec![TypeScriptReference::Path(SpecifierWithRange {
          text: "./ref.d.ts".to_owned(),
          range: PositionRange {
            start: Position {
              line: 1,
              character: 20,
            },
            end: Position {
              line: 1,
              character: 32,
            },
          },
        })],
        self_types_specifier: None,
        jsx_import_source: Some(SpecifierWithRange {
          text: "preact".to_owned(),
          range: PositionRange {
            start: Position {
              line: 2,
              character: 20,
            },
            end: Position {
              line: 2,
              character: 26,
            },
          },
        }),
        jsx_import_source_types: None,
        jsdoc_imports: vec![],
      },
    );
  }
}