1#![doc = include_str!("../examples/parser.rs")]
41#![doc = include_str!("../examples/parser_tsx.rs")]
46#![allow(clippy::all, clippy::wildcard_imports)]
70
71use std::any::Any;
72
73pub mod config;
74
75mod context;
76mod cursor;
77mod embedding;
78mod error_handler;
79mod markup;
80mod modifiers;
81mod module_record;
82mod observation;
83mod speculation;
84mod state;
85
86mod js;
87mod jsx;
88mod ts;
89
90mod diagnostics;
91
92#[cfg(not(feature = "benchmarking"))]
94mod lexer;
95#[cfg(feature = "benchmarking")]
96#[doc(hidden)]
97pub mod lexer;
98
99use oxc_allocator::{Allocator, ArenaBox, ArenaVec, Dummy, GetAllocator};
100use oxc_ast::{
101 ast::{Expression, Program, Statement},
102 builder::{AstBuilder, GetAstBuilder},
103};
104use oxc_diagnostics::Diagnostics;
105use oxc_span::{SourceType, Span};
106use oxc_syntax::module_record::ModuleRecord;
107
108pub use crate::lexer::{Kind, Token};
109use crate::{
110 config::{
111 LexerConfig, NoTokensParserConfig, ParserConfig, RuntimeParserConfig, TokensParserConfig,
112 },
113 context::{Context, StatementContext},
114 diagnostics::ParserDiagnostic,
115 error_handler::FatalError,
116 lexer::Lexer,
117 module_record::ModuleRecordBuilder,
118 state::ParserState,
119};
120pub use embedding::AdmittedBorrowedExpression;
121pub use embedding::{
122 AdmittedExpression, AdmittedHandlerBody, AdmittedParameters, EmbeddingGoal, EmbeddingHole,
123 EmbeddingInput, EmbeddingInputError, EmbeddingObservation, ExpressionObservation,
124 HandlerBodyObservation, ParametersObservation,
125};
126pub use markup::{MarkupCursor, MarkupGrammar, MarkupSite};
127pub use observation::{AdmittedProgram, OriginalDefaultExport, ProgramObservation};
128
129pub(crate) const MAX_LEN: usize = if size_of::<usize>() >= 8 {
136 u32::MAX as usize
138} else {
139 isize::MAX as usize
141};
142
143#[non_exhaustive]
167pub struct ParserReturn<'a> {
168 pub program: Program<'a>,
180
181 pub module_record: ModuleRecord<'a>,
183
184 pub diagnostics: Diagnostics,
190
191 pub irregular_whitespaces: Box<[Span]>,
193
194 pub tokens: ArenaVec<'a, Token>,
198
199 pub panicked: bool,
208
209 pub is_flow_language: bool,
211
212 pub(crate) has_legacy_literals: bool,
214 pub(crate) has_jsdoc_comments: bool,
216}
217
218#[derive(Debug, Clone, Copy, PartialEq, Eq)]
222pub struct ParseOptions {
223 #[cfg(feature = "regular_expression")]
227 pub parse_regular_expression: bool,
228
229 pub allow_return_outside_function: bool,
237
238 pub preserve_parens: bool,
249
250 pub allow_v8_intrinsics: bool,
257
258 pub enable_ident_hashes: bool,
270}
271
272impl Default for ParseOptions {
273 fn default() -> Self {
274 Self {
275 #[cfg(feature = "regular_expression")]
276 parse_regular_expression: false,
277 allow_return_outside_function: false,
278 preserve_parens: true,
279 allow_v8_intrinsics: false,
280 enable_ident_hashes: true,
281 }
282 }
283}
284
285pub struct Parser<'a, C: ParserConfig = NoTokensParserConfig> {
289 allocator: &'a Allocator,
290 source_text: &'a str,
291 source_type: SourceType,
292 options: ParseOptions,
293 config: C,
294}
295
296impl<'a> Parser<'a> {
297 pub fn new(allocator: &'a Allocator, source_text: &'a str, source_type: SourceType) -> Self {
304 let options = ParseOptions::default();
305 Self { allocator, source_text, source_type, options, config: NoTokensParserConfig }
306 }
307}
308
309impl<'a, C: ParserConfig> Parser<'a, C> {
310 #[must_use]
312 pub fn with_options(mut self, options: ParseOptions) -> Self {
313 self.options = options;
314 self
315 }
316
317 #[must_use]
321 pub fn with_config<Config: ParserConfig>(self, config: Config) -> Parser<'a, Config> {
322 Parser {
323 allocator: self.allocator,
324 source_text: self.source_text,
325 source_type: self.source_type,
326 options: self.options,
327 config,
328 }
329 }
330}
331
332mod parser_parse {
333 use super::*;
334
335 mod slot_parameters;
336
337 pub struct UniquePromise(());
352
353 impl UniquePromise {
354 #[inline]
355 fn new() -> Self {
356 Self(())
357 }
358
359 #[cfg(any(test, feature = "benchmarking"))]
363 pub fn new_for_tests_and_benchmarks() -> Self {
364 Self(())
365 }
366 }
367
368 impl<'a, C: ParserConfig> Parser<'a, C> {
369 pub fn parse(self) -> ParserReturn<'a> {
386 let config: &dyn Any = &self.config;
387 if config.is::<NoTokensParserConfig>() {
388 parse_with_no_tokens_config(
389 self.allocator,
390 self.source_text,
391 self.source_type,
392 self.options,
393 )
394 } else if config.is::<TokensParserConfig>() {
395 parse_with_tokens_config(
396 self.allocator,
397 self.source_text,
398 self.source_type,
399 self.options,
400 )
401 } else if let Some(&config) = config.downcast_ref::<RuntimeParserConfig>() {
402 parse_with_runtime_config(
403 self.allocator,
404 self.source_text,
405 self.source_type,
406 self.options,
407 config,
408 )
409 } else {
410 ParserImpl::<C>::new(
413 self.allocator,
414 self.source_text,
415 self.source_type,
416 self.options,
417 self.config,
418 UniquePromise::new(),
419 )
420 .parse()
421 }
422 }
423
424 pub fn parse_expression(self) -> Result<Expression<'a>, Diagnostics> {
447 let config: &dyn Any = &self.config;
448 if config.is::<NoTokensParserConfig>() {
449 parse_expression_with_no_tokens_config(
450 self.allocator,
451 self.source_text,
452 self.source_type,
453 self.options,
454 )
455 } else if config.is::<TokensParserConfig>() {
456 parse_expression_with_tokens_config(
457 self.allocator,
458 self.source_text,
459 self.source_type,
460 self.options,
461 )
462 } else if let Some(&config) = config.downcast_ref::<RuntimeParserConfig>() {
463 parse_expression_with_runtime_config(
464 self.allocator,
465 self.source_text,
466 self.source_type,
467 self.options,
468 config,
469 )
470 } else {
471 ParserImpl::<C>::new(
472 self.allocator,
473 self.source_text,
474 self.source_type,
475 self.options,
476 self.config,
477 UniquePromise::new(),
478 )
479 .parse_expression()
480 }
481 }
482 }
483
484 #[inline(never)]
512 fn parse_with_no_tokens_config<'a>(
513 allocator: &'a Allocator,
514 source_text: &'a str,
515 source_type: SourceType,
516 options: ParseOptions,
517 ) -> ParserReturn<'a> {
518 ParserImpl::<NoTokensParserConfig>::new(
519 allocator,
520 source_text,
521 source_type,
522 options,
523 NoTokensParserConfig,
524 UniquePromise::new(),
525 )
526 .parse()
527 }
528
529 #[inline(never)]
530 fn parse_with_tokens_config<'a>(
531 allocator: &'a Allocator,
532 source_text: &'a str,
533 source_type: SourceType,
534 options: ParseOptions,
535 ) -> ParserReturn<'a> {
536 ParserImpl::<TokensParserConfig>::new(
537 allocator,
538 source_text,
539 source_type,
540 options,
541 TokensParserConfig,
542 UniquePromise::new(),
543 )
544 .parse()
545 }
546
547 #[inline(never)]
548 fn parse_with_runtime_config<'a>(
549 allocator: &'a Allocator,
550 source_text: &'a str,
551 source_type: SourceType,
552 options: ParseOptions,
553 config: RuntimeParserConfig,
554 ) -> ParserReturn<'a> {
555 ParserImpl::<RuntimeParserConfig>::new(
556 allocator,
557 source_text,
558 source_type,
559 options,
560 config,
561 UniquePromise::new(),
562 )
563 .parse()
564 }
565
566 #[inline(never)]
568 pub(crate) fn parse_with_markup<'a>(
569 allocator: &'a Allocator,
570 source_text: &'a str,
571 source_type: SourceType,
572 options: ParseOptions,
573 grammar: &'a dyn crate::MarkupGrammar<'a>,
574 ) -> ParserReturn<'a> {
575 let mut parser = ParserImpl::<crate::config::MarkupParserConfig>::new(
576 allocator,
577 source_text,
578 source_type,
579 options,
580 crate::config::MarkupParserConfig,
581 UniquePromise::new(),
582 );
583 parser.markup = Some(grammar);
584 parser.parse()
585 }
586
587 #[inline(never)]
588 fn parse_expression_with_no_tokens_config<'a>(
589 allocator: &'a Allocator,
590 source_text: &'a str,
591 source_type: SourceType,
592 options: ParseOptions,
593 ) -> Result<Expression<'a>, Diagnostics> {
594 ParserImpl::<NoTokensParserConfig>::new(
595 allocator,
596 source_text,
597 source_type,
598 options,
599 NoTokensParserConfig,
600 UniquePromise::new(),
601 )
602 .parse_expression()
603 }
604
605 #[inline(never)]
606 fn parse_expression_with_tokens_config<'a>(
607 allocator: &'a Allocator,
608 source_text: &'a str,
609 source_type: SourceType,
610 options: ParseOptions,
611 ) -> Result<Expression<'a>, Diagnostics> {
612 ParserImpl::<TokensParserConfig>::new(
613 allocator,
614 source_text,
615 source_type,
616 options,
617 TokensParserConfig,
618 UniquePromise::new(),
619 )
620 .parse_expression()
621 }
622
623 #[inline(never)]
624 fn parse_expression_with_runtime_config<'a>(
625 allocator: &'a Allocator,
626 source_text: &'a str,
627 source_type: SourceType,
628 options: ParseOptions,
629 config: RuntimeParserConfig,
630 ) -> Result<Expression<'a>, Diagnostics> {
631 ParserImpl::<RuntimeParserConfig>::new(
632 allocator,
633 source_text,
634 source_type,
635 options,
636 config,
637 UniquePromise::new(),
638 )
639 .parse_expression()
640 }
641}
642use parser_parse::UniquePromise;
643pub(crate) use parser_parse::parse_with_markup;
644
645struct ParserImpl<'a, C: ParserConfig> {
648 options: ParseOptions,
650
651 pub(crate) lexer: Lexer<'a, C::LexerConfig>,
652
653 source_type: SourceType,
655
656 source_text: &'a str,
658
659 errors: Vec<ParserDiagnostic<'a>>,
664
665 deferred_script_errors: Vec<ParserDiagnostic<'a>>,
671
672 fatal_error: Option<FatalError<'a>>,
673
674 token: Token,
676
677 prev_token_end: u32,
679
680 state: ParserState<'a>,
682
683 ctx: Context,
685
686 ast: AstBuilder<'a>,
688
689 module_record_builder: ModuleRecordBuilder<'a>,
691
692 is_ts: bool,
694
695 markup: Option<&'a dyn MarkupGrammar<'a>>,
697}
698
699impl<'a, C: ParserConfig> ParserImpl<'a, C> {
700 #[inline]
705 #[expect(clippy::needless_pass_by_value)]
706 pub fn new(
707 allocator: &'a Allocator,
708 source_text: &'a str,
709 source_type: SourceType,
710 options: ParseOptions,
711 config: C,
712 unique: UniquePromise,
713 ) -> Self {
714 Self {
715 options,
716 lexer: Lexer::new(allocator, source_text, source_type, config.lexer_config(), unique),
717 source_type,
718 source_text,
719 errors: vec![],
720 deferred_script_errors: vec![],
721 fatal_error: None,
722 token: Token::default(),
723 prev_token_end: 0,
724 state: ParserState::new(),
725 ctx: Self::default_context(source_type, options),
726 ast: AstBuilder::new(allocator),
727 module_record_builder: ModuleRecordBuilder::new(allocator, source_type),
728 is_ts: source_type.is_typescript(),
729 markup: None,
730 }
731 }
732
733 #[inline]
738 pub fn parse(mut self) -> ParserReturn<'a> {
739 let mut program = self.parse_program();
740 let mut panicked = false;
741
742 if let Some(fatal_error) = self.fatal_error.take() {
743 panicked = true;
744 self.errors.truncate(fatal_error.errors_len);
745 if !self.lexer.errors.is_empty() && self.cur_kind().is_eof() {
746 } else {
748 self.error(fatal_error.error);
749 }
750
751 program = Program::dummy(self.allocator());
752 program.source_type = self.source_type;
753 program.source_text = self.source_text;
754 }
755
756 self.check_unfinished_errors();
757
758 if let Some(overlong_error) = self.overlong_error() {
759 panicked = true;
760 self.lexer.errors.clear();
761 self.errors.clear();
762 self.error(overlong_error);
763 }
764
765 let mut is_flow_language = false;
766 let mut errors = Diagnostics::new();
767 if (!self.lexer.errors.is_empty() || !self.errors.is_empty())
769 && let Some(error) = self.flow_error()
770 {
771 is_flow_language = true;
772 errors.push(error.into_diagnostic());
773 }
774 let (module_record, mut module_record_errors) = self.module_record_builder.build();
775 if errors.len() != 1 {
776 errors
777 .reserve(self.lexer.errors.len() + self.errors.len() + module_record_errors.len());
778 errors.extend(self.lexer.errors.drain(..).map(ParserDiagnostic::into_diagnostic));
779 errors.extend(self.errors.drain(..).map(ParserDiagnostic::into_diagnostic));
780 errors.append(&mut module_record_errors);
781 }
782 let irregular_whitespaces =
783 std::mem::take(&mut self.lexer.trivia_builder.irregular_whitespaces).into_boxed_slice();
784
785 let source_type = program.source_type;
786 if source_type.is_unambiguous() {
787 if module_record.has_module_syntax {
788 program.source_type = source_type.with_module(true);
791 errors.extend(
792 self.lexer
793 .deferred_module_errors
794 .drain(..)
795 .map(ParserDiagnostic::into_diagnostic),
796 );
797 } else {
798 program.source_type = source_type.with_script(true);
801 errors.extend(
802 self.deferred_script_errors.into_iter().map(ParserDiagnostic::into_diagnostic),
803 );
804 }
805 }
806
807 let tokens =
808 if panicked { ArenaVec::new_in(&self.ast) } else { self.lexer.finalize_tokens() };
809
810 program.comments = self.lexer.trivia_builder.comments;
811
812 ParserReturn {
813 program,
814 module_record,
815 diagnostics: errors,
816 irregular_whitespaces,
817 tokens,
818 panicked,
819 is_flow_language,
820 has_legacy_literals: self.lexer.has_legacy_literals,
821 has_jsdoc_comments: self.lexer.trivia_builder.has_jsdoc_comments,
822 }
823 }
824
825 pub fn parse_expression(mut self) -> Result<Expression<'a>, Diagnostics> {
826 self.bump_any();
828 let expr = self.parse_expr();
829 if let Some(FatalError { error, .. }) = self.fatal_error.take() {
830 return Err(error.into_diagnostic().into());
831 }
832 self.check_unfinished_errors();
833 let errors = self
834 .lexer
835 .errors
836 .into_iter()
837 .chain(self.errors)
838 .map(ParserDiagnostic::into_diagnostic)
839 .collect::<Diagnostics>();
840 if !errors.is_empty() {
841 return Err(errors);
842 }
843 Ok(expr)
844 }
845
846 #[expect(clippy::cast_possible_truncation)]
847 fn parse_program(&mut self) -> Program<'a> {
848 self.token = self.lexer.first_token();
851
852 let hashbang = self.parse_hashbang();
853 self.ctx |= Context::TopLevel;
854 #[cfg(feature = "terminal-embedding")]
855 let (directives, mut statements) = self.parse_program_body_with_terminal_operand();
856 #[cfg(not(feature = "terminal-embedding"))]
857 let (directives, mut statements) =
858 self.parse_directives_and_statements(false);
859
860 if self.source_type.is_unambiguous()
865 && self.module_record_builder.has_module_syntax()
866 && !self.state.potential_await_reparse.is_empty()
867 {
868 self.reparse_potential_top_level_awaits(&mut statements);
869 }
870
871 let span = Span::new(0, self.source_text.len() as u32);
872 Program::new(
873 span,
874 self.source_type,
875 self.source_text,
876 [],
878 hashbang,
879 directives,
880 statements,
881 self,
882 )
883 }
884
885 fn reparse_potential_top_level_awaits(&mut self, statements: &mut ArenaVec<'a, Statement<'a>>) {
891 let original_tokens =
894 if self.lexer.config.tokens() { Some(self.lexer.take_tokens()) } else { None };
895
896 let original_legacy_literals = self.lexer.has_legacy_literals;
899 let original_jsdoc_comments = self.lexer.trivia_builder.has_jsdoc_comments;
900 let checkpoints = std::mem::take(&mut self.state.potential_await_reparse);
901 for (stmt_index, checkpoint) in checkpoints {
902 self.rewind(checkpoint);
904
905 let stmt = self.context_add(Context::Await, |p| {
907 p.parse_statement_list_item(StatementContext::StatementList)
908 });
909
910 if stmt_index < statements.len() {
912 statements[stmt_index] = stmt;
913 }
914 }
915
916 self.lexer.has_legacy_literals |= original_legacy_literals;
917 self.lexer.trivia_builder.has_jsdoc_comments |= original_jsdoc_comments;
918 if let Some(original_tokens) = original_tokens {
919 self.lexer.set_tokens(original_tokens);
920 }
921 }
922
923 fn default_context(source_type: SourceType, options: ParseOptions) -> Context {
924 let mut ctx = Context::default().and_ambient(source_type.is_typescript_definition());
925 if source_type.is_module() {
926 ctx = ctx.and_await(true);
928 }
929 if options.allow_return_outside_function || source_type.is_commonjs() {
932 ctx = ctx.and_return(true);
933 }
934 if source_type.is_commonjs() {
935 ctx = ctx.and_new_target(true);
936 }
937 ctx
938 }
939
940 fn flow_error(&mut self) -> Option<ParserDiagnostic<'a>> {
943 if !self.source_type.is_javascript() {
944 return None;
945 }
946 let span = self.lexer.trivia_builder.comments.first()?.span;
947 if span.source_text(self.source_text).contains("@flow") {
948 self.errors.clear();
949 Some(diagnostics::flow(span))
950 } else {
951 None
952 }
953 }
954
955 fn check_unfinished_errors(&mut self) {
956 use oxc_span::GetSpan;
957 for expr in self.state.cover_initialized_name.values() {
960 self.errors.push(diagnostics::cover_initialized_name(expr.span()));
961 }
962 }
963
964 #[cold]
967 fn overlong_error(&self) -> Option<ParserDiagnostic<'a>> {
968 if self.source_text.len() > MAX_LEN {
969 return Some(diagnostics::overlong_source());
970 }
971 None
972 }
973
974 #[inline]
975 fn alloc<T>(&self, value: T) -> ArenaBox<'a, T> {
976 ArenaBox::new_in(value, self)
977 }
978}
979
980impl<'a, C: ParserConfig> GetAllocator<'a> for ParserImpl<'a, C> {
981 #[inline]
982 fn allocator(&self) -> &'a Allocator {
983 self.ast.allocator()
984 }
985}
986
987impl<'a, C: ParserConfig> GetAstBuilder<'a> for ParserImpl<'a, C> {
988 type Builder = AstBuilder<'a>;
989
990 #[inline]
991 fn builder(&self) -> &AstBuilder<'a> {
992 &self.ast
993 }
994}
995
996#[cfg(test)]
997mod test {
998 use std::path::Path;
999
1000 use oxc_ast::ast::{CommentKind, Expression, Statement};
1001 use oxc_span::GetSpan;
1002
1003 use super::*;
1004
1005 #[test]
1006 fn parse_program_smoke_test() {
1007 let allocator = Allocator::default();
1008 let source_type = SourceType::default();
1009 let source = "";
1010 let ret = Parser::new(&allocator, source, source_type).parse();
1011 assert!(ret.program.is_empty());
1012 assert!(ret.diagnostics.is_empty());
1013 assert!(!ret.is_flow_language);
1014 }
1015
1016 #[test]
1017 fn parse_expression_smoke_test() {
1018 let allocator = Allocator::default();
1019 let source_type = SourceType::default();
1020 let source = "a";
1021 let expr = Parser::new(&allocator, source, source_type).parse_expression().unwrap();
1022 assert!(matches!(expr, Expression::Identifier(_)));
1023 }
1024
1025 #[test]
1026 fn flow_error() {
1027 let allocator = Allocator::default();
1028 let source_type = SourceType::default();
1029 let sources = [
1030 "// @flow\nasdf adsf",
1031 "/* @flow */\n asdf asdf",
1032 "/**
1033 * @flow
1034 */
1035 asdf asdf
1036 ",
1037 "/* @flow */ super;",
1038 ];
1039 for source in sources {
1040 let ret = Parser::new(&allocator, source, source_type).parse();
1041 assert!(ret.is_flow_language);
1042 assert_eq!(ret.diagnostics.len(), 1);
1043 assert_eq!(ret.diagnostics.first().unwrap().to_string(), "Flow is not supported");
1044 }
1045 }
1046
1047 #[test]
1048 fn ts_module_declaration() {
1049 let allocator = Allocator::default();
1050 let source_type = SourceType::from_path(Path::new("module.ts")).unwrap();
1051 let source = "declare module 'test'\n";
1052 let ret = Parser::new(&allocator, source, source_type).parse();
1053 assert_eq!(ret.diagnostics.len(), 0);
1054 }
1055
1056 #[test]
1057 fn directives() {
1058 let allocator = Allocator::default();
1059 let source_type = SourceType::default();
1060 let sources = [
1061 ("import x from 'foo'; 'use strict';", 2),
1062 ("export {x} from 'foo'; 'use strict';", 2),
1063 (";'use strict';", 2),
1064 ];
1065 for (source, body_length) in sources {
1066 let ret = Parser::new(&allocator, source, source_type).parse();
1067 assert!(ret.program.directives.is_empty(), "{source}");
1068 assert_eq!(ret.program.body.len(), body_length, "{source}");
1069 }
1070 }
1071
1072 #[test]
1073 fn v8_intrinsics() {
1074 let allocator = Allocator::default();
1075 let source_type = SourceType::default();
1076 {
1077 let source = "%DebugPrint('Raging against the Dying Light')";
1078 let opts = ParseOptions { allow_v8_intrinsics: true, ..ParseOptions::default() };
1079 let ret = Parser::new(&allocator, source, source_type).with_options(opts).parse();
1080 assert!(ret.diagnostics.is_empty());
1081
1082 if let Some(Statement::ExpressionStatement(expr_stmt)) = ret.program.body.first() {
1083 if let Expression::V8IntrinsicExpression(expr) = &expr_stmt.expression {
1084 assert_eq!(expr.span().source_text(source), source);
1085 } else {
1086 panic!("Expected V8IntrinsicExpression");
1087 }
1088 } else {
1089 panic!("Expected ExpressionStatement");
1090 }
1091 }
1092 {
1093 let source = "%DebugPrint(...illegalSpread)";
1094 let opts = ParseOptions { allow_v8_intrinsics: true, ..ParseOptions::default() };
1095 let ret = Parser::new(&allocator, source, source_type).with_options(opts).parse();
1096 assert_eq!(ret.diagnostics.len(), 1);
1097 assert_eq!(
1098 ret.diagnostics[0].to_string(),
1099 "V8 runtime calls cannot have spread elements as arguments"
1100 );
1101 }
1102 {
1103 let source = "%DebugPrint('~~')";
1104 let ret = Parser::new(&allocator, source, source_type).parse();
1105 assert_eq!(ret.diagnostics.len(), 1);
1106 assert_eq!(ret.diagnostics[0].to_string(), "Unexpected token");
1107 }
1108 {
1109 let source = "interface Props extends %enuProps {}";
1111 let source_type = SourceType::default().with_typescript(true);
1112 let opts = ParseOptions { allow_v8_intrinsics: true, ..ParseOptions::default() };
1114 let ret = Parser::new(&allocator, source, source_type).with_options(opts).parse();
1115 assert_eq!(ret.diagnostics.len(), 1);
1116 let ret = Parser::new(&allocator, source, source_type).parse();
1117 assert_eq!(ret.diagnostics.len(), 1);
1118 }
1119 }
1120
1121 #[test]
1122 fn comments() {
1123 let allocator = Allocator::default();
1124 let source_type = SourceType::default().with_typescript(true);
1125 let sources = [
1126 ("// line comment", CommentKind::Line),
1127 ("/* line comment */", CommentKind::SingleLineBlock),
1128 (
1129 "type Foo = ( /* Require properties which are not generated automatically. */ 'bar')",
1130 CommentKind::SingleLineBlock,
1131 ),
1132 ];
1133 for (source, kind) in sources {
1134 let ret = Parser::new(&allocator, source, source_type).parse();
1135 let comments = &ret.program.comments;
1136 assert_eq!(comments.len(), 1, "{source}");
1137 assert_eq!(comments.first().unwrap().kind, kind, "{source}");
1138 }
1139 }
1140
1141 #[test]
1142 fn hashbang() {
1143 let allocator = Allocator::default();
1144 let source_type = SourceType::default();
1145 let source = "#!/usr/bin/node\n;";
1146 let ret = Parser::new(&allocator, source, source_type).parse();
1147 assert_eq!(ret.program.hashbang.unwrap().value.as_str(), "/usr/bin/node");
1148 }
1149
1150 #[test]
1151 fn unambiguous() {
1152 let allocator = Allocator::default();
1153 let source_type = SourceType::unambiguous();
1154 assert!(source_type.is_unambiguous());
1155 let sources = ["import x from 'foo';", "export {x} from 'foo';", "import.meta"];
1156 for source in sources {
1157 let ret = Parser::new(&allocator, source, source_type).parse();
1158 assert!(ret.program.source_type.is_module());
1159 }
1160
1161 let sources = ["", "import('foo')"];
1162 for source in sources {
1163 let ret = Parser::new(&allocator, source, source_type).parse();
1164 assert!(ret.program.source_type.is_script());
1165 }
1166 }
1167
1168 #[test]
1169 fn binary_file() {
1170 let allocator = Allocator::default();
1171 let source_type = SourceType::default();
1172
1173 let ret = Parser::new(&allocator, "\u{FFFD}", source_type).parse();
1175 assert!(ret.program.is_empty());
1176 assert_eq!(ret.diagnostics.len(), 1);
1177 assert_eq!(ret.diagnostics[0].to_string(), "File appears to be binary.");
1178
1179 let ret = Parser::new(&allocator, "\"oops \u{FFFD} oops\";", source_type).parse();
1181 assert!(!ret.program.is_empty());
1182 assert!(ret.diagnostics.is_empty());
1183 }
1184
1185 #[test]
1186 fn memory_leak() {
1187 let allocator = Allocator::default();
1188 let source_type = SourceType::default();
1189 let sources = ["2n", ";'1234567890123456789012345678901234567890'"];
1190 for source in sources {
1191 let ret = Parser::new(&allocator, source, source_type).parse();
1192 assert!(!ret.program.body.is_empty());
1193 }
1194 }
1195
1196 #[cfg(target_pointer_width = "64")]
1200 #[cfg(not(miri))]
1201 #[test]
1202 fn overlong_source() {
1203 use std::{
1204 alloc::{self, Layout},
1205 ptr::NonNull,
1206 slice, str,
1207 };
1208
1209 struct ZeroedString {
1215 ptr: NonNull<u8>,
1216 }
1217
1218 impl ZeroedString {
1219 const LEN: usize = MAX_LEN + 1;
1220 const PAGE_SIZE: usize = 4096;
1221 const LAYOUT: Layout = match Layout::from_size_align(Self::LEN, Self::PAGE_SIZE) {
1222 Ok(layout) => layout,
1223 Err(_) => panic!("Failed to create layout"),
1224 };
1225
1226 fn new() -> Self {
1227 let ptr = unsafe { alloc::alloc_zeroed(Self::LAYOUT) };
1229 let Some(ptr) = NonNull::new(ptr) else {
1230 panic!("Failed to allocate {} bytes", Self::LEN);
1231 };
1232 Self { ptr }
1233 }
1234
1235 fn as_str(&self) -> &str {
1236 unsafe {
1239 str::from_utf8_unchecked(slice::from_raw_parts(self.ptr.as_ptr(), Self::LEN))
1240 }
1241 }
1242 }
1243
1244 impl Drop for ZeroedString {
1245 fn drop(&mut self) {
1246 unsafe { alloc::dealloc(self.ptr.as_ptr(), Self::LAYOUT) };
1248 }
1249 }
1250
1251 let zeroed_string = ZeroedString::new();
1253 let source_text = zeroed_string.as_str();
1254
1255 let allocator = Allocator::default();
1257 let ret = Parser::new(&allocator, source_text, SourceType::default()).parse();
1258
1259 assert!(ret.program.is_empty());
1261 assert!(ret.panicked);
1262 assert_eq!(ret.diagnostics.len(), 1);
1263 assert_eq!(
1264 ret.diagnostics.first().unwrap().to_string(),
1265 "Source length exceeds 4 GiB limit"
1266 );
1267 }
1268
1269 #[cfg(not(debug_assertions))]
1274 #[cfg(not(miri))]
1275 #[test]
1276 fn legal_length_source() {
1277 let head = "const x = 1;\n/*";
1279 let foot = "*/\nconst y = 2;\n";
1280 let mut source = "x".repeat(MAX_LEN);
1281 source.replace_range(..head.len(), head);
1282 source.replace_range(MAX_LEN - foot.len().., foot);
1283 assert_eq!(source.len(), MAX_LEN);
1284
1285 let allocator = Allocator::default();
1286 let ret = Parser::new(&allocator, &source, SourceType::default()).parse();
1287 assert!(!ret.panicked);
1288 assert!(ret.diagnostics.is_empty());
1289 assert_eq!(ret.program.body.len(), 2);
1290 }
1291}
1292
1293#[cfg(feature = "terminal-embedding")]
1294pub use embedding::terminal::PreparedExpression;