Debian Codegraph @

js/src/jsapi-tests/testIsCompilableUnit.cpp

raw
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/. */
4
5 #include "mozilla/Utf8.h" // mozilla::Utf8Unit
6
7 #include <string_view>
8
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"
16
17 static bool gIsCompilableUnitWarned = false;
18
19 BEGIN_TEST(testIsCompilableUnit) {
20 JS::SetWarningReporter(cx, WarningReporter);
21
22 // Compilable case.
23 {
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);
28 }
29
30 // Not compilable cases.
31 {
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);
36 }
37
38 {
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);
43 }
44
45 // Compilable but warned case.
46 {
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);
51 }
52
53 // Invalid UTF-8 case.
54 // This should report error with returning *true*.
55 {
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);
61 }
62
63 return true;
64 }
65
66 static void WarningReporter(JSContext* cx, JSErrorReport* report) {
67 gIsCompilableUnitWarned = true;
68 }
69 END_TEST(testIsCompilableUnit);