LCOV - code coverage report
Current view: top level - source/scriptinterface - JSON.cpp (source / functions) Hit Total Coverage
Test: 0 A.D. test coverage report Lines: 40 49 81.6 %
Date: 2026-12-03 01:19:39 Functions: 5 5 100.0 %

          Line data    Source code
       1             : /* Copyright (C) 2026 Wildfire Games.
       2             :  * This file is part of 0 A.D.
       3             :  *
       4             :  * 0 A.D. is free software: you can redistribute it and/or modify
       5             :  * it under the terms of the GNU General Public License as published by
       6             :  * the Free Software Foundation, either version 2 of the License, or
       7             :  * (at your option) any later version.
       8             :  *
       9             :  * 0 A.D. is distributed in the hope that it will be useful,
      10             :  * but WITHOUT ANY WARRANTY; without even the implied warranty of
      11             :  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
      12             :  * GNU General Public License for more details.
      13             :  *
      14             :  * You should have received a copy of the GNU General Public License
      15             :  * along with 0 A.D.  If not, see <http://www.gnu.org/licenses/>.
      16             :  */
      17             : 
      18             : #include "precompiled.h"
      19             : 
      20             : #include "JSON.h"
      21             : 
      22             : #include "lib/file/vfs/vfs_path.h"
      23             : #include "lib/status.h"
      24             : #include "lib/utf8.h"
      25             : #include "ps/CLogger.h"
      26             : #include "ps/CStr.h"
      27             : #include "ps/Errors.h"
      28             : #include "ps/Filesystem.h"
      29             : #include "scriptinterface/FunctionWrapper.h"
      30             : #include "scriptinterface/Exceptions.h"
      31             : #include "scriptinterface/Request.h"
      32             : 
      33             : #include <js/Exception.h>
      34             : #include <js/JSON.h>
      35             : #include <js/RootingAPI.h>
      36             : #include <js/Value.h>
      37             : #include <sstream>
      38             : #include <string>
      39             : 
      40        1533 : bool Script::ParseJSON(const Script::Request& rq, const std::string& string_utf8, JS::MutableHandleValue out)
      41             : {
      42        1533 :     std::wstring attrsW = wstring_from_utf8(string_utf8);
      43        3066 :     std::u16string string(attrsW.begin(), attrsW.end());
      44        1533 :     if (JS_ParseJSON(rq.cx, string.c_str(), static_cast<std::uint32_t>(string.size()), out))
      45             :         return true;
      46             : 
      47           5 :     Script::Exception::CatchPending(rq);
      48             :     return false;
      49        3055 : }
      50             : 
      51        1452 : void Script::ReadJSONFile(const Script::Request& rq, const VfsPath& path, JS::MutableHandleValue out)
      52             : {
      53        1452 :     if (!VfsFileExists(path))
      54             :     {
      55           0 :         LOGERROR("File '{}' does not exist", path.string8());
      56           0 :         return;
      57             :     }
      58             : 
      59        1452 :     CVFSFile file;
      60             : 
      61        1452 :     PSRETURN ret = file.Load(g_VFS, path);
      62             : 
      63        1452 :     if (ret != PSRETURN_OK)
      64             :     {
      65           0 :         LOGERROR("Failed to load file '{}': {}", path.string8(), GetErrorString(ret));
      66           0 :         return;
      67             :     }
      68             : 
      69        1452 :     std::string content(file.DecodeUTF8()); // assume it's UTF-8
      70             : 
      71        1452 :     if (!ParseJSON(rq, content, out))
      72           0 :         LOGERROR("Failed to parse '{}'", path.string8());
      73        1452 : }
      74             : 
      75             : namespace
      76             : {
      77           0 : struct Stringifier
      78             : {
      79           9 :     static bool callback(const char16_t* buf, std::uint32_t len, void* data)
      80             :     {
      81           9 :         std::u16string str(buf, buf+len);
      82          18 :         std::wstring strw(str.begin(), str.end());
      83             : 
      84           9 :         Status err; // ignore Unicode errors
      85          18 :         static_cast<Stringifier*>(data)->stream << utf8_from_wstring(strw, &err);
      86           9 :         return true;
      87          17 :     }
      88             : 
      89             :     std::stringstream stream;
      90             : };
      91             : } // anonymous namespace
      92             : 
      93             : // JS_Stringify takes a mutable object because ToJSON may arbitrarily mutate the value.
      94             : // TODO: it'd be nice to have a non-mutable variant.
      95           1 : std::string Script::StringifyJSON(const Script::Request& rq, JS::MutableHandleValue obj, bool indent)
      96             : {
      97           1 :     Stringifier str;
      98           1 :     JS::RootedValue indentVal(rq.cx, indent ? JS::Int32Value(2) : JS::UndefinedValue());
      99           1 :     if (!JS_Stringify(rq.cx, obj, nullptr, indentVal, &Stringifier::callback, &str))
     100             :     {
     101           0 :         Script::Exception::CatchPending(rq);
     102           0 :         return std::string();
     103             :     }
     104             : 
     105           1 :     return str.stream.str();
     106           1 : }
     107             : 
     108             : 
     109          21 : std::string Script::ToString(const Script::Request& rq, JS::MutableHandleValue obj, bool pretty)
     110             : {
     111          21 :     if (obj.isUndefined())
     112           0 :         return "(void 0)";
     113             : 
     114             :     // Try to stringify as JSON if possible
     115             :     // (TODO: this is maybe a bad idea since it'll drop 'undefined' values silently)
     116          21 :     if (pretty)
     117             :     {
     118           9 :         Stringifier str;
     119           9 :         JS::RootedValue indentVal(rq.cx, JS::Int32Value(2));
     120             : 
     121           9 :         if (JS_Stringify(rq.cx, obj, nullptr, indentVal, &Stringifier::callback, &str))
     122           8 :             return str.stream.str();
     123             : 
     124             :         // Drop exceptions raised by cyclic values before trying something else
     125           1 :         JS_ClearPendingException(rq.cx);
     126           9 :     }
     127             : 
     128             :     // Caller didn't want pretty output, or JSON conversion failed (e.g. due to cycles),
     129             :     // so fall back to obj.toSource()
     130             : 
     131          13 :     std::wstring source = L"(error)";
     132          13 :     Script::Function::Call(rq, obj, "toSource", source);
     133          13 :     return utf8_from_wstring(source);
     134          21 : }

Generated by: LCOV version 1.16