1 /* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
5 #include "mozilla/Utf8.h" // mozilla::Utf8Unit
9 #include "js/CompilationAndEvaluation.h" // JS_Utf8BufferIsCompilableUnit
10 #include "js/ErrorReport.h" // JSErrorReport
11 #include "js/GlobalObject.h" // JS::CurrentGlobalOrNull
12 #include "js/RootingAPI.h" // JS::Rooted
13 #include "js/SourceText.h" // JS::SourceText, JS::SourceOwnership
14 #include "js/Warnings.h" // JS::SetWarningReporter
15 #include "jsapi-tests/tests.h"
17 static bool gIsCompilableUnitWarned
= false;
19 BEGIN_TEST(testIsCompilableUnit
) {
20 JS::SetWarningReporter(cx
, WarningReporter
);
24 static constexpr std::string_view src
= "1";
25 CHECK(JS_Utf8BufferIsCompilableUnit(cx
, global
, src
.data(), src
.length()));
26 CHECK(!JS_IsExceptionPending(cx
));
27 CHECK(!gIsCompilableUnitWarned
);
30 // Not compilable cases.
32 static constexpr std::string_view src
= "1 + ";
33 CHECK(!JS_Utf8BufferIsCompilableUnit(cx
, global
, src
.data(), src
.length()));
34 CHECK(!JS_IsExceptionPending(cx
));
35 CHECK(!gIsCompilableUnitWarned
);
39 static constexpr std::string_view src
= "() =>";
40 CHECK(!JS_Utf8BufferIsCompilableUnit(cx
, global
, src
.data(), src
.length()));
41 CHECK(!JS_IsExceptionPending(cx
));
42 CHECK(!gIsCompilableUnitWarned
);
45 // Compilable but warned case.
47 static constexpr std::string_view src
= "() => { return; unreachable(); }";
48 CHECK(JS_Utf8BufferIsCompilableUnit(cx
, global
, src
.data(), src
.length()));
49 CHECK(!JS_IsExceptionPending(cx
));
50 CHECK(!gIsCompilableUnitWarned
);
53 // Invalid UTF-8 case.
54 // This should report error with returning *true*.
56 static constexpr std::string_view src
= "\x80";
57 CHECK(JS_Utf8BufferIsCompilableUnit(cx
, global
, src
.data(), src
.length()));
58 CHECK(JS_IsExceptionPending(cx
));
59 CHECK(!gIsCompilableUnitWarned
);
60 JS_ClearPendingException(cx
);
66 static void WarningReporter(JSContext
* cx
, JSErrorReport
* report
) {
67 gIsCompilableUnitWarned
= true;
69 END_TEST(testIsCompilableUnit
);