Skip to content

Commit

Permalink
JSON: Add simple printing and creation (#6265)
Browse files Browse the repository at this point in the history
  • Loading branch information
kripken committed Feb 1, 2024
1 parent 2b3a2e8 commit 5526027
Show file tree
Hide file tree
Showing 5 changed files with 63 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/support/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ set(support_SOURCES
dfa_minimization.cpp
file.cpp
istring.cpp
json.cpp
path.cpp
safe_integer.cpp
threads.cpp
Expand Down
43 changes: 43 additions & 0 deletions src/support/json.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
/*
* Copyright 2024 WebAssembly Community Group participants
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

#include "support/json.h"

namespace json {

void Value::stringify(std::ostream& os, bool pretty) {
if (isString()) {
// TODO: escaping
os << '"' << getCString() << '"';
} else if (isArray()) {
os << '[';
auto first = true;
for (auto& item : getArray()) {
if (first) {
first = false;
} else {
// TODO pretty whitespace
os << ',';
}
item->stringify(os, pretty);
}
os << ']';
} else {
WASM_UNREACHABLE("TODO: stringify all of JSON");
}
}

} // namespace json
2 changes: 2 additions & 0 deletions src/support/json.h
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,8 @@ struct Value {
Ref& operator[](IString x) { return (*this->get())[x]; }
};

template<typename T> static Ref make(T t) { return Ref(new Value(t)); }

enum Type {
String = 0,
Number = 1,
Expand Down
1 change: 1 addition & 0 deletions test/gtest/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ include_directories(../../src/wasm)
set(unittest_SOURCES
cfg.cpp
dfa_minimization.cpp
json.cpp
lattices.cpp
possible-contents.cpp
printing.cpp
Expand Down
16 changes: 16 additions & 0 deletions test/gtest/json.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
#include "support/json.h"
#include "gtest/gtest.h"

using JSONTest = ::testing::Test;

TEST_F(JSONTest, Stringify) {
// TODO: change the API to not require a copy
auto input = "[\"hello\",\"world\"]";
auto* copy = strdup(input);
json::Value value;
value.parse(copy);
std::stringstream ss;
value.stringify(ss);
EXPECT_EQ(ss.str(), input);
free(copy);
}

0 comments on commit 5526027

Please sign in to comment.