Distribute and run LLMs with a single file.
C++ cross-platformggufllama-cpplocal-ailocal-inferencelocal-llmopen-source-aisingle-file-executablespeech-to-text
Add support for JSON parameters to new server
Justine Tunneyd7c8e33da0cc
diff --git a/llamafile/server/BUILD.mk b/llamafile/server/BUILD.mkindex 576bc0bd..9809182b 100644--- a/llamafile/server/BUILD.mk+++ b/llamafile/server/BUILD.mk@@ -23,9 +23,15 @@ o/$(MODE)/llamafile/server/main: \$(LLAMAFILE_SERVER_OBJS): llamafile/server/BUILD.mk$(LLAMAFILE_SERVER_OBJS): private CCFLAGS += -O+o/$(MODE)/llamafile/server/fastjson_test: \+ o/$(MODE)/llamafile/server/fastjson_test.o \+ o/$(MODE)/llamafile/server/fastjson.o \+ o/$(MODE)/double-conversion/double-conversion.a \+o/$(MODE)/llamafile/server/json_test: \o/$(MODE)/llamafile/server/json_test.o \o/$(MODE)/llamafile/server/json.o \+ o/$(MODE)/llamafile/server/hextoint.o \o/$(MODE)/double-conversion/double-conversion.a \.PHONY: o/$(MODE)/llamafile/serverdiff --git a/llamafile/server/client.h b/llamafile/server/client.hindex 5da84bb7..612e6aa5 100644--- a/llamafile/server/client.h+++ b/llamafile/server/client.h@@ -36,6 +36,8 @@#define HeaderEqualCase(H, S) \SlicesEqualCase(S, strlen(S), HeaderData(H), HeaderLength(H))+struct EmbeddingParams;+struct Cleanup{Cleanup* next;@@ -85,4 +87,5 @@ struct Clientbool dispatch() __wur;bool tokenize() __wur;bool embedding() __wur;+ bool get_embedding_params(EmbeddingParams*);};diff --git a/llamafile/server/embedding.cpp b/llamafile/server/embedding.cppindex 685190d1..22181627 100644--- a/llamafile/server/embedding.cpp+++ b/llamafile/server/embedding.cpp@@ -24,10 +24,19 @@#include "llama.cpp/llama.h"+#include "fastjson.h"#include "json.h"#include "log.h"#include "utils.h"+struct EmbeddingParams+{+ bool add_special;+ bool parse_special;+ ctl::string_view prompt;+ ctl::string content;+};+extern llama_model* g_model;void@@ -78,40 +87,66 @@ cleanup_llama_context(void* arg)llama_free((llama_context*)arg);}-bool-Client::embedding()+void+cleanup_embedding_params(void* arg){- if (msg.method != kHttpGet && msg.method != kHttpPost)- return send_error(405);+ delete (EmbeddingParams*)arg;+}- if (!read_payload())- return false;+bool+Client::get_embedding_params(EmbeddingParams* params)+{+ params->add_special = atob(or_empty(param("add_special")), true);+ params->parse_special = atob(or_empty(param("parse_special")), false);// get prompt//// 1. Allow GET "/tokenize?prompt=foo"- // 2. Allow POST "prompt=foo" (application/x-www-form-urlencoded)+ // 2. Allow POST {"content": "foo"} (application/json)+ // 3. Allow POST "prompt=foo" (application/x-www-form-urlencoded)// 3. Allow POST "foo" (text/plain)//- ctl::string_view input;ctl::optional<ctl::string_view> prompt = param("prompt");if (prompt.has_value()) {- input = prompt.value();+ params->prompt = prompt.value();} else if (HasHeader(kHttpContentType)) {if (IsMimeType(HeaderData(kHttpContentType),HeaderLength(kHttpContentType),"text/plain")) {- input = payload;+ params->prompt = payload;+ } else if (IsMimeType(HeaderData(kHttpContentType),+ HeaderLength(kHttpContentType),+ "application/json")) {+ ctl::pair<Json::Status, Json> json = Json::parse(payload);+ if (json.first != Json::success)+ return send_error(400, Json::StatusToString(json.first));+ if (!json.second["content"].isString())+ return send_error(400, "JSON missing \"content\" key");+ params->content = ctl::move(json.second["content"].getString());+ params->prompt = params->content;} else {return send_error(501, "Content Type Not Implemented");}} else {- input = payload;+ params->prompt = payload;}+ return true;+}- // get optional parameters- bool add_special = atob(or_empty(param("add_special")), true);- bool parse_special = atob(or_empty(param("parse_special")), false);+bool+Client::embedding()+{+ if (msg.method != kHttpGet && msg.method != kHttpPost)+ return send_error(405);++ if (!read_payload())+ return false;++ // get parameters+ auto params = new EmbeddingParams;+ defer_cleanup(cleanup_embedding_params, params);+ if (!get_embedding_params(params))+ return false;// setup statisticsrusage rustart = {};@@ -119,15 +154,15 @@ Client::embedding()timespec started = timespec_real();// turn text into tokens- auto toks = new ctl::vector<llama_token>(input.size() + 16);+ auto toks = new ctl::vector<llama_token>(params->prompt.size() + 16);defer_cleanup(cleanup_token_vector, toks);int count = llama_tokenize(g_model,- input.data(),- input.size(),+ params->prompt.data(),+ params->prompt.size(),&(*toks)[0],toks->size(),- add_special,- parse_special);+ params->add_special,+ params->parse_special);if (count < 0) {LOG("llama_tokenize failed");return send_error(405);@@ -193,10 +228,10 @@ Client::embedding()char* p = obuf.p;p = stpcpy(p, "{\r\n");p = stpcpy(p, " \"add_special\": ");- p = encode_bool(p, add_special);+ p = encode_bool(p, params->add_special);p = stpcpy(p, ",\n");p = stpcpy(p, " \"parse_special\": ");- p = encode_bool(p, parse_special);+ p = encode_bool(p, params->parse_special);p = stpcpy(p, ",\n");p = stpcpy(p, " \"tokens_provided\": ");p = encode_json(p, toks->size());diff --git a/llamafile/server/fastjson.cpp b/llamafile/server/fastjson.cppnew file mode 100644index 00000000..fd5603cb--- /dev/null+++ b/llamafile/server/fastjson.cpp@@ -0,0 +1,181 @@+// -*- mode:c++;indent-tabs-mode:nil;c-basic-offset:4;coding:utf-8 -*-+// vi: set et ft=cpp ts=4 sts=4 sw=4 fenc=utf-8 :vi+//+// Copyright 2024 Mozilla Foundation+//+// 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 "fastjson.h"++#include <cosmo.h>+#include <ctl/string.h>+#include <net/http/escape.h>++#include "double-conversion/double-to-string.h"+#include "double-conversion/utils.h"++static const char kEscapeLiteral[128] = {+ 9, 9, 9, 9, 9, 9, 9, 9, 9, 1, 2, 9, 4, 3, 9, 9, // 0x00+ 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, // 0x10+ 0, 0, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 6, // 0x20+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9, 9, 0, // 0x30+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0x40+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, // 0x50+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0x60+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, // 0x70+};++static const double_conversion::DoubleToStringConverter kDoubleToJson(+ double_conversion::DoubleToStringConverter::UNIQUE_ZERO |+ double_conversion::DoubleToStringConverter::EMIT_POSITIVE_EXPONENT_SIGN,+ "1e5000",+ "null",+ 'e',+ -6,+ 21,+ 6,+ 0);++char*+encode_bool(char* p, bool x) noexcept+{+ return stpcpy(p, x ? "true" : "false");+}++char*+encode_json(char* p, int x) noexcept+{+ return FormatInt32(p, x);+}++char*+encode_json(char* p, long x) noexcept+{+ return FormatInt64(p, x);+}++char*+encode_json(char* p, unsigned x) noexcept+{+ return FormatUint32(p, x);+}++char*+encode_json(char* p, unsigned long x) noexcept+{+ return FormatUint64(p, x);+}++char*+encode_json(char* p, float x) noexcept+{+ double_conversion::StringBuilder b(p, 256);+ kDoubleToJson.ToShortestSingle(x, &b);+ b.Finalize();+ return p + strlen(p);+}++char*+encode_json(char* p, double x) noexcept+{+ double_conversion::StringBuilder b(p, 256);+ kDoubleToJson.ToShortest(x, &b);+ b.Finalize();+ return p + strlen(p);+}++char*+encode_json(char* p, const ctl::string_view s) noexcept+{+ *p++ = '"';+ p = encode_js_string_literal(p, s);+ *p++ = '"';+ *p = 0;+ return p;+}++char*+encode_js_string_literal(char* p, const ctl::string_view s) noexcept+{+ uint64_t w;+ size_t i, j, m;+ wint_t x, a, b;+ for (size_t i = 0; i < s.size();) {+ x = s[i++] & 255;+ if (x >= 0300) {+ a = ThomPikeByte(x);+ m = ThomPikeLen(x) - 1;+ if (i + m <= s.size()) {+ for (j = 0;;) {+ b = s[i + j] & 0xff;+ if (!ThomPikeCont(b))+ break;+ a = ThomPikeMerge(a, b);+ if (++j == m) {+ x = a;+ i += j;+ break;+ }+ }+ }+ }+ switch (0 <= x && x <= 127 ? kEscapeLiteral[x] : 9) {+ case 0:+ *p++ = x;+ break;+ case 1:+ *p++ = '\\';+ *p++ = 't';+ break;+ case 2:+ *p++ = '\\';+ *p++ = 'n';+ break;+ case 3:+ *p++ = '\\';+ *p++ = 'r';+ break;+ case 4:+ *p++ = '\\';+ *p++ = 'f';+ break;+ case 5:+ *p++ = '\\';+ *p++ = '\\';+ break;+ case 6:+ *p++ = '\\';+ *p++ = '/';+ break;+ case 7:+ *p++ = '\\';+ *p++ = '"';+ break;+ case 9:+ w = EncodeUtf16(x);+ do {+ *p++ = '\\';+ *p++ = 'u';+ *p++ = "0123456789abcdef"[(w & 0xF000) >> 014];+ *p++ = "0123456789abcdef"[(w & 0x0F00) >> 010];+ *p++ = "0123456789abcdef"[(w & 0x00F0) >> 004];+ *p++ = "0123456789abcdef"[(w & 0x000F) >> 000];+ } while ((w >>= 16));+ break;+ default:+ __builtin_unreachable();+ }+ }+ *p = 0;+ return p;+}diff --git a/llamafile/server/fastjson.h b/llamafile/server/fastjson.hnew file mode 100644index 00000000..0bee2b0c--- /dev/null+++ b/llamafile/server/fastjson.h@@ -0,0 +1,46 @@+// -*- mode:c++;indent-tabs-mode:nil;c-basic-offset:4;coding:utf-8 -*-+// vi: set et ft=cpp ts=4 sts=4 sw=4 fenc=utf-8 :vi+//+// Copyright 2024 Mozilla Foundation+//+// 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.++#pragma once+#include <ctl/string_view.h>++char*+encode_bool(char*, bool) noexcept;++char*+encode_json(char*, int) noexcept;++char*+encode_json(char*, long) noexcept;++char*+encode_json(char*, float) noexcept;++char*+encode_json(char*, double) noexcept;++char*+encode_json(char*, unsigned) noexcept;++char*+encode_json(char*, unsigned long) noexcept;++char*+encode_json(char*, const ctl::string_view) noexcept;++char*+encode_js_string_literal(char*, const ctl::string_view) noexcept;diff --git a/llamafile/server/fastjson_test.cpp b/llamafile/server/fastjson_test.cppnew file mode 100644index 00000000..ef99870b--- /dev/null+++ b/llamafile/server/fastjson_test.cpp@@ -0,0 +1,128 @@+// -*- mode:c++;indent-tabs-mode:nil;c-basic-offset:4;coding:utf-8 -*-+// vi: set et ft=cpp ts=4 sts=4 sw=4 fenc=utf-8 :vi+//+// Copyright 2024 Mozilla Foundation+//+// 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 "fastjson.h"++#include <ctl/string.h>+#include <limits.h>+#include <math.h>+#include <stdio.h>++using namespace ctl;++string+encode_json(int x) noexcept+{+ char buf[12];+ return { buf, (size_t)(encode_json(buf, x) - buf) };+}++string+encode_json(long x) noexcept+{+ char buf[21];+ return { buf, (size_t)(encode_json(buf, x) - buf) };+}++string+encode_json(double x) noexcept+{+ char buf[128];+ return { buf, (size_t)(encode_json(buf, x) - buf) };+}++string+encode_json(unsigned x) noexcept+{+ char buf[128];+ return { buf, (size_t)(encode_json(buf, x) - buf) };+}++string+encode_json(unsigned long x) noexcept+{+ char buf[128];+ return { buf, (size_t)(encode_json(buf, x) - buf) };+}++string+encode_json(const string_view x) noexcept+{+ char buf[128];+ return { buf, (size_t)(encode_json(buf, x) - buf) };+}++string+encode_js_string_literal(const string_view x) noexcept+{+ char buf[256]; // this isn't secure (no guard page)+ return { buf, (size_t)(encode_json(buf, x) - buf) };+}++int+main(int argc, char* argv[])+{++ if (encode_json(0) != "0")+ return 1;+ if (encode_json(INT_MAX) != "2147483647")+ return 2;+ if (encode_json(INT_MIN) != "-2147483648")+ return 3;+ if (encode_json(UINT_MAX) != "4294967295")+ return 4;+ if (encode_json(LONG_MAX) != "9223372036854775807")+ return 5;+ if (encode_json(LONG_MIN) != "-9223372036854775808")+ return 6;+ if (encode_json(ULONG_MAX) != "18446744073709551615")+ return 7;++ if (encode_json("") != "\"\"")+ return 8;+ if (encode_json(string_view("\0\1", 2)) != "\"\\u0000\\u0001\"")+ return 9;+ if (encode_json("\n\"\\\t") != "\"\\n\\\"\\\\\\t\"")+ return 10;+ if (encode_json("'") != "\"\\u0027\"")+ return 11;+ if (encode_json("µ") != "\"\\u00b5\"")+ return 12;+ if (encode_json("𐌰") != "\"\\ud800\\udf30\"")+ return 13;++ if (encode_json(3.) != "3")+ return 14;+ if (encode_json(3.14) != "3.14")+ return 15;+ if (encode_json(1e+100) != "1e+100")+ return 16;+ if (encode_json(1e-100) != "1e-100")+ return 17;+ if (encode_json(+INFINITY) != "1e5000")+ return 18;+ if (encode_json(-INFINITY) != "-1e5000")+ return 19;+ if (encode_json(+NAN) != "null")+ return 20;+ if (encode_json(-NAN) != "null")+ return 21;+ if (encode_json(1e-300) != "1e-300")+ return 21;++ return 0;+}diff --git a/llamafile/server/json.cpp b/llamafile/server/json.cppindex 4e62c4d0..d74c364c 100644--- a/llamafile/server/json.cpp+++ b/llamafile/server/json.cpp@@ -16,13 +16,69 @@// limitations under the License.#include "json.h"+#include "utils.h"#include <cosmo.h>-#include <ctl/string.h>-#include <net/http/escape.h>+#include <stdckdint.h>#include "double-conversion/double-to-string.h"-#include "double-conversion/utils.h"+#include "double-conversion/string-to-double.h"++#define KEY 1+#define COMMA 2+#define COLON 4+#define ARRAY 8+#define OBJECT 16+#define DEPTH 20++#define ASCII 0+#define C0 1+#define DQUOTE 2+#define BACKSLASH 3+#define UTF8_2 4+#define UTF8_3 5+#define UTF8_4 6+#define C1 7+#define UTF8_3_E0 8+#define UTF8_3_ED 9+#define UTF8_4_F0 10+#define BADUTF8 11+#define EVILUTF8 12++static const char kJsonStr[256] = {+ 1, 1, 1, 1, 1, 1, 1, 1, // 0000 ascii (0)+ 1, 1, 1, 1, 1, 1, 1, 1, // 0010+ 1, 1, 1, 1, 1, 1, 1, 1, // 0020 c0 (1)+ 1, 1, 1, 1, 1, 1, 1, 1, // 0030+ 0, 0, 2, 0, 0, 0, 0, 0, // 0040 dquote (2)+ 0, 0, 0, 0, 0, 0, 0, 0, // 0050+ 0, 0, 0, 0, 0, 0, 0, 0, // 0060+ 0, 0, 0, 0, 0, 0, 0, 0, // 0070+ 0, 0, 0, 0, 0, 0, 0, 0, // 0100+ 0, 0, 0, 0, 0, 0, 0, 0, // 0110+ 0, 0, 0, 0, 0, 0, 0, 0, // 0120+ 0, 0, 0, 0, 3, 0, 0, 0, // 0130 backslash (3)+ 0, 0, 0, 0, 0, 0, 0, 0, // 0140+ 0, 0, 0, 0, 0, 0, 0, 0, // 0150+ 0, 0, 0, 0, 0, 0, 0, 0, // 0160+ 0, 0, 0, 0, 0, 0, 0, 0, // 0170+ 7, 7, 7, 7, 7, 7, 7, 7, // 0200 c1 (8)+ 7, 7, 7, 7, 7, 7, 7, 7, // 0210+ 7, 7, 7, 7, 7, 7, 7, 7, // 0220+ 7, 7, 7, 7, 7, 7, 7, 7, // 0230+ 11, 11, 11, 11, 11, 11, 11, 11, // 0240 latin1 (4)+ 11, 11, 11, 11, 11, 11, 11, 11, // 0250+ 11, 11, 11, 11, 11, 11, 11, 11, // 0260+ 11, 11, 11, 11, 11, 11, 11, 11, // 0270+ 12, 12, 4, 4, 4, 4, 4, 4, // 0300 utf8-2 (5)+ 4, 4, 4, 4, 4, 4, 4, 4, // 0310+ 4, 4, 4, 4, 4, 4, 4, 4, // 0320 utf8-2+ 4, 4, 4, 4, 4, 4, 4, 4, // 0330+ 8, 5, 5, 5, 5, 5, 5, 5, // 0340 utf8-3 (6)+ 5, 5, 5, 5, 5, 9, 5, 5, // 0350+ 10, 6, 6, 6, 6, 11, 11, 11, // 0360 utf8-4 (7)+ 11, 11, 11, 11, 11, 11, 11, 11, // 0370+};static const char kEscapeLiteral[128] = {9, 9, 9, 9, 9, 9, 9, 9, 9, 1, 2, 9, 4, 3, 9, 9, // 0x00@@ -46,71 +102,519 @@ static const double_conversion::DoubleToStringConverter kDoubleToJson(6,0);-char*-encode_bool(char* p, bool x) noexcept+static const double_conversion::StringToDoubleConverter kJsonToDouble(+ double_conversion::StringToDoubleConverter::ALLOW_CASE_INSENSITIVITY |+ double_conversion::StringToDoubleConverter::ALLOW_LEADING_SPACES |+ double_conversion::StringToDoubleConverter::ALLOW_TRAILING_JUNK |+ double_conversion::StringToDoubleConverter::ALLOW_TRAILING_SPACES,+ 0.0,+ 1.0,+ "Infinity",+ "NaN");++static double+StringToDouble(const char* s, size_t n, int* out_processed)+{+ if (n == -1ull)+ n = strlen(s);+ int processed;+ double res = kJsonToDouble.StringToDouble(s, n, &processed);+ if (out_processed)+ *out_processed = processed;+ return res;+}++void+Json::clear()+{+ switch (type_) {+ case String:+ string_value.~string();+ break;+ case Array:+ array_value.~vector();+ break;+ case Object:+ object_value.~map();+ break;+ default:+ break;+ }+ type_ = Null;+}++Json::Json(const Json& other) : type_(other.type_)+{+ switch (type_) {+ case Null:+ break;+ case Bool:+ bool_value = other.bool_value;+ break;+ case Long:+ long_value = other.long_value;+ break;+ case Ulong:+ ulong_value = other.ulong_value;+ break;+ case Float:+ float_value = other.float_value;+ break;+ case Double:+ double_value = other.double_value;+ break;+ case String:+ new (&string_value) ctl::string(other.string_value);+ break;+ case Array:+ new (&array_value) ctl::vector<Json>(other.array_value);+ break;+ case Object:+ new (&object_value) ctl::map<ctl::string, Json>(other.object_value);+ break;+ default:+ __builtin_trap();+ }+}++Json&+Json::operator=(const Json& other)+{+ if (this != &other) {+ clear();+ type_ = other.type_;+ switch (type_) {+ case Null:+ break;+ case Bool:+ bool_value = other.bool_value;+ break;+ case Long:+ long_value = other.long_value;+ break;+ case Ulong:+ ulong_value = other.ulong_value;+ break;+ case Float:+ float_value = other.float_value;+ break;+ case Double:+ double_value = other.double_value;+ break;+ case String:+ new (&string_value) ctl::string(other.string_value);+ break;+ case Array:+ new (&array_value) ctl::vector<Json>(other.array_value);+ break;+ case Object:+ new (&object_value)+ ctl::map<ctl::string, Json>(other.object_value);+ break;+ default:+ __builtin_trap();+ }+ }+ return *this;+}++Json::Json(Json&& other) noexcept : type_(other.type_)+{+ switch (type_) {+ case Null:+ break;+ case Bool:+ bool_value = other.bool_value;+ break;+ case Long:+ long_value = other.long_value;+ break;+ case Ulong:+ ulong_value = other.ulong_value;+ break;+ case Float:+ float_value = other.float_value;+ break;+ case Double:+ double_value = other.double_value;+ break;+ case String:+ new (&string_value) ctl::string(ctl::move(other.string_value));+ break;+ case Array:+ new (&array_value) ctl::vector<Json>(ctl::move(other.array_value));+ break;+ case Object:+ new (&object_value)+ ctl::map<ctl::string, Json>(ctl::move(other.object_value));+ break;+ default:+ __builtin_trap();+ }+ other.type_ = Null;+}++Json&+Json::operator=(Json&& other) noexcept+{+ if (this != &other) {+ clear();+ type_ = other.type_;+ switch (type_) {+ case Null:+ break;+ case Bool:+ bool_value = other.bool_value;+ break;+ case Long:+ long_value = other.long_value;+ break;+ case Ulong:+ ulong_value = other.ulong_value;+ break;+ case Float:+ float_value = other.float_value;+ break;+ case Double:+ double_value = other.double_value;+ break;+ case String:+ new (&string_value) ctl::string(ctl::move(other.string_value));+ break;+ case Array:+ new (&array_value)+ ctl::vector<Json>(ctl::move(other.array_value));+ break;+ case Object:+ new (&object_value)+ ctl::map<ctl::string, Json>(ctl::move(other.object_value));+ break;+ default:+ __builtin_trap();+ }+ other.type_ = Null;+ }+ return *this;+}++double+Json::getNumber() const+{+ switch (type_) {+ case Null:+ return 0;+ case Bool:+ return bool_value;+ case Long:+ return long_value;+ case Ulong:+ return ulong_value;+ case Float:+ return float_value;+ case Double:+ return double_value;+ default:+ __builtin_trap();+ }+}++long+Json::getLong() const+{+ if (!isLong())+ __builtin_trap();+ return long_value;+}++unsigned long+Json::getUlong() const+{+ if (!isUlong())+ __builtin_trap();+ return ulong_value;+}++bool+Json::getBool() const+{+ if (!isBool())+ __builtin_trap();+ return bool_value;+}++float+Json::getFloat() const+{+ if (!isFloat())+ __builtin_trap();+ return float_value;+}++double+Json::getDouble() const+{+ if (!isDouble())+ __builtin_trap();+ return double_value;+}++ctl::string&+Json::getString()+{+ if (!isString())+ __builtin_trap();+ return string_value;+}++ctl::vector<Json>&+Json::getArray()+{+ if (!isArray())+ __builtin_trap();+ return array_value;+}++ctl::map<ctl::string, Json>&+Json::getObject()+{+ if (!isObject())+ __builtin_trap();+ return object_value;+}++void+Json::setNull()+{+ clear();+ type_ = Null;+}++void+Json::setBool(bool value)+{+ clear();+ type_ = Bool;+ bool_value = value;+}++void+Json::setFloat(float value)+{+ clear();+ type_ = Float;+ float_value = value;+}++void+Json::setLong(long value)+{+ clear();+ type_ = Long;+ long_value = value;+}++void+Json::setUlong(unsigned long value){- return stpcpy(p, x ? "true" : "false");+ clear();+ type_ = Ulong;+ ulong_value = value;}-char*-encode_json(char* p, int x) noexcept+void+Json::setDouble(double value){- return FormatInt32(p, x);+ clear();+ type_ = Double;+ double_value = value;}-char*-encode_json(char* p, long x) noexcept+void+Json::setString(const char* value){- return FormatInt64(p, x);+ clear();+ type_ = String;+ new (&string_value) ctl::string(value);}-char*-encode_json(char* p, unsigned x) noexcept+void+Json::setString(ctl::string&& value){- return FormatUint32(p, x);+ clear();+ type_ = String;+ new (&string_value) ctl::string(ctl::move(value));}-char*-encode_json(char* p, unsigned long x) noexcept+void+Json::setString(const ctl::string& value){- return FormatUint64(p, x);+ clear();+ type_ = String;+ new (&string_value) ctl::string(value);}-char*-encode_json(char* p, float x) noexcept+void+Json::setString(const ctl::string_view& value){- double_conversion::StringBuilder b(p, 256);- kDoubleToJson.ToShortestSingle(x, &b);- b.Finalize();- return p + strlen(p);+ clear();+ type_ = String;+ new (&string_value) ctl::string_view(value);}-char*-encode_json(char* p, double x) noexcept+void+Json::setArray(){- double_conversion::StringBuilder b(p, 256);- kDoubleToJson.ToShortest(x, &b);- b.Finalize();- return p + strlen(p);+ clear();+ type_ = Array;+ new (&array_value) ctl::vector<Json>();}-char*-encode_json(char* p, const ctl::string_view s) noexcept+void+Json::setObject(){- *p++ = '"';- p = encode_js_string_literal(p, s);- *p++ = '"';- *p = 0;- return p;+ clear();+ type_ = Object;+ new (&object_value) ctl::map<ctl::string, Json>();}-char*-encode_js_string_literal(char* p, const ctl::string_view s) noexcept+Json&+Json::operator[](size_t index) noexcept+{+ if (type_ != Array) {+ clear();+ setArray();+ }+ if (index >= array_value.size()) {+ array_value.resize(index + 1);+ }+ return array_value[index];+}++Json&+Json::operator[](const ctl::string& key) noexcept+{+ if (type_ != Object) {+ clear();+ setObject();+ }+ return object_value[key];+}++ctl::string+Json::toString(bool pretty) const noexcept+{+ ctl::string b;+ marshal(b, pretty, 0);+ return b;+}++void+Json::marshal(ctl::string& b, bool pretty, int indent) const noexcept+{+ switch (type_) {+ case Null:+ b += "null";+ break;+ case String:+ stringify(b, string_value);+ break;+ case Bool:+ b += bool_value ? "true" : "false";+ break;+ case Long: {+ char buf[21];+ b.append(buf, FormatInt64(buf, long_value) - buf);+ break;+ }+ case Ulong: {+ char buf[21];+ b.append(buf, FormatUint64(buf, ulong_value) - buf);+ break;+ }+ case Float: {+ char buf[128];+ double_conversion::StringBuilder db(buf, 128);+ kDoubleToJson.ToShortestSingle(float_value, &db);+ db.Finalize();+ b += buf;+ break;+ }+ case Double: {+ char buf[128];+ double_conversion::StringBuilder db(buf, 128);+ kDoubleToJson.ToShortest(double_value, &db);+ db.Finalize();+ b += buf;+ break;+ }+ case Array: {+ bool once = false;+ b += '[';+ for (auto i = array_value.begin(); i != array_value.end(); ++i) {+ if (once) {+ b += ',';+ if (pretty)+ b += ' ';+ } else {+ once = true;+ }+ i->marshal(b, pretty, indent);+ }+ b += ']';+ break;+ }+ case Object: {+ bool once = false;+ b += '{';+ for (auto i = object_value.begin(); i != object_value.end(); ++i) {+ if (once) {+ b += ',';+ } else {+ once = true;+ }+ if (pretty && object_value.size() > 1) {+ b += '\n';+ ++indent;+ for (int j = 0; j < indent; ++j)+ b += " ";+ }+ stringify(b, i->first);+ b += ':';+ if (pretty)+ b += ' ';+ i->second.marshal(b, pretty, indent);+ if (pretty && object_value.size() > 1)+ --indent;+ }+ if (pretty && object_value.size() > 1) {+ b += '\n';+ for (int j = 0; j < indent; ++j)+ b += " ";+ ++indent;+ }+ b += '}';+ break;+ }+ default:+ __builtin_trap();+ }+}++void+Json::stringify(ctl::string& b, const ctl::string_view& s) noexcept+{+ b += '"';+ serialize(b, s);+ b += '"';+}++void+Json::serialize(ctl::string& sb, const ctl::string_view& s) noexcept{uint64_t w;size_t i, j, m;wint_t x, a, b;- for (size_t i = 0; i < s.size();) {+ for (i = 0; i < s.size();) {x = s[i++] & 255;if (x >= 0300) {a = ThomPikeByte(x);@@ -131,51 +635,576 @@ encode_js_string_literal(char* p, const ctl::string_view s) noexcept}switch (0 <= x && x <= 127 ? kEscapeLiteral[x] : 9) {case 0:- *p++ = x;+ sb += x;break;case 1:- *p++ = '\\';- *p++ = 't';+ sb += "\\t";break;case 2:- *p++ = '\\';- *p++ = 'n';+ sb += "\\n";break;case 3:- *p++ = '\\';- *p++ = 'r';+ sb += "\\r";break;case 4:- *p++ = '\\';- *p++ = 'f';+ sb += "\\f";break;case 5:- *p++ = '\\';- *p++ = '\\';+ sb += "\\\\";break;case 6:- *p++ = '\\';- *p++ = '/';+ sb += "\\/";break;case 7:- *p++ = '\\';- *p++ = '"';+ sb += "\\\"";break;case 9:w = EncodeUtf16(x);do {- *p++ = '\\';- *p++ = 'u';- *p++ = "0123456789abcdef"[(w & 0xF000) >> 014];- *p++ = "0123456789abcdef"[(w & 0x0F00) >> 010];- *p++ = "0123456789abcdef"[(w & 0x00F0) >> 004];- *p++ = "0123456789abcdef"[(w & 0x000F) >> 000];+ char esc[6];+ esc[0] = '\\';+ esc[1] = 'u';+ esc[2] = "0123456789abcdef"[(w & 0xF000) >> 014];+ esc[3] = "0123456789abcdef"[(w & 0x0F00) >> 010];+ esc[4] = "0123456789abcdef"[(w & 0x00F0) >> 004];+ esc[5] = "0123456789abcdef"[(w & 0x000F) >> 000];+ sb.append(esc, 6);} while ((w >>= 16));break;default:+ __builtin_trap();+ }+ }+}++Json::Status+Json::parse(Json& json, const char*& p, const char* e, int context, int depth)+{+ long x;+ char w[4];+ const char* a;+ int A, B, C, D, c, d, i, u;+ if (!depth)+ return depth_exceeded;+ for (a = p, d = +1; p < e;) {+ switch ((c = *p++ & 255)) {+ case ' ': // spaces+ case '\n':+ case '\r':+ case '\t':+ a = p;+ break;++ case ',': // present in list and object+ if (context & COMMA) {+ context = 0;+ a = p;+ break;+ } else {+ return unexpected_comma;+ }++ case ':': // present only in object after key+ if (context & COLON) {+ context = 0;+ a = p;+ break;+ } else {+ return unexpected_colon;+ }++ case 'n': // null+ if (context & (KEY | COLON | COMMA))+ goto OnColonCommaKey;+ if (p + 3 <= e && READ32LE(p - 1) == READ32LE("null")) {+ json.setNull();+ p += 3;+ return success;+ } else {+ return illegal_character;+ }++ case 'f': // false+ if (context & (KEY | COLON | COMMA))+ goto OnColonCommaKey;+ if (p + 4 <= e && READ32LE(p) == READ32LE("alse")) {+ json.setBool(true);+ p += 4;+ return success;+ } else {+ return illegal_character;+ }++ case 't': // true+ if (context & (KEY | COLON | COMMA))+ goto OnColonCommaKey;+ if (p + 3 <= e && READ32LE(p - 1) == READ32LE("true")) {+ json.setBool(true);+ p += 3;+ return success;+ } else {+ return illegal_character;+ }++ default:+ return illegal_character;++ OnColonCommaKey:+ if (context & KEY)+ return object_key_must_be_string;+ OnColonComma:+ if (context & COLON)+ return missing_colon;+ return missing_comma;++ case '-': // negative+ if (context & (COLON | COMMA | KEY))+ goto OnColonCommaKey;+ if (p < e && isdigit(*p)) {+ d = -1;+ break;+ } else {+ return bad_negative;+ }++ case '0': // zero or number+ if (context & (COLON | COMMA | KEY))+ goto OnColonCommaKey;+ if (p < e) {+ if (*p == '.') {+ if (p + 1 == e || !isdigit(p[1]))+ return bad_double;+ goto UseDubble;+ } else if (*p == 'e' || *p == 'E') {+ goto UseDubble;+ } else if (isdigit(*p)) {+ return unexpected_octal;+ }+ }+ json.setLong(0);+ return success;++ case '1' ... '9': // integer+ if (context & (COLON | COMMA | KEY))+ goto OnColonCommaKey;+ for (x = (c - '0') * d; p < e; ++p) {+ c = *p & 255;+ if (isdigit(c)) {+ if (ckd_mul(&x, x, 10) ||+ ckd_add(&x, x, (c - '0') * d)) {+ goto UseDubble;+ }+ } else if (c == '.') {+ if (p + 1 == e || !isdigit(p[1]))+ return bad_double;+ goto UseDubble;+ } else if (c == 'e' || c == 'E') {+ goto UseDubble;+ } else {+ break;+ }+ }+ json.setLong(x);+ return success;++ UseDubble: // number+ json.setDouble(StringToDouble(a, e - a, &c));+ if (c <= 0)+ return bad_double;+ if (a + c < e && (a[c] == 'e' || a[c] == 'E'))+ return bad_exponent;+ p = a + c;+ return success;++ case '[': { // Array+ if (context & (COLON | COMMA | KEY))+ goto OnColonCommaKey;+ json.setArray();+ Json value;+ for (context = ARRAY, i = 0;;) {+ Status status = parse(value, p, e, context, depth - 1);+ if (status == absent_value)+ return success;+ if (status != success)+ return status;+ json.getArray().emplace_back(ctl::move(value));+ context = ARRAY | COMMA;+ }+ }++ case ']':+ if (context & ARRAY)+ return absent_value;+ return unexpected_end_of_array;++ case '}':+ if (context & OBJECT)+ return absent_value;+ return unexpected_end_of_object;++ case '{': { // Object+ if (context & (COLON | COMMA | KEY))+ goto OnColonCommaKey;+ json.setObject();+ context = KEY | OBJECT;+ Json key, value;+ for (;;) {+ Status status = parse(key, p, e, context, depth - 1);+ if (status == absent_value)+ return success;+ if (status != success)+ return status;+ status = parse(value, p, e, COLON, depth - 1);+ if (status == absent_value)+ return object_missing_value;+ if (status != success)+ return status;+ json[key.getString()] = ctl::move(value);+ context = KEY | COMMA | OBJECT;+ }+ }++ case '"': { // string+ ctl::string b;+ if (context & (COLON | COMMA))+ goto OnColonComma;+ for (;;) {+ if (p >= e)+ return unexpected_end_of_string;+ switch (kJsonStr[(c = *p++ & 255)]) {++ case ASCII:+ b += c;+ break;++ case DQUOTE:+ json.setString(ctl::move(b));+ return success;++ case BACKSLASH:+ if (p >= e)+ return unexpected_end_of_string;+ switch ((c = *p++ & 255)) {+ case '"':+ case '/':+ case '\\':+ b += c;+ break;+ case 'b':+ b += '\b';+ break;+ case 'f':+ b += '\f';+ break;+ case 'n':+ b += '\n';+ break;+ case 'r':+ b += '\r';+ break;+ case 't':+ b += '\t';+ break;+ case 'x':+ if (p + 2 <= e && //+ (A = kHexToInt[p[0] & 255]) !=+ -1 && // HEX+ (B = kHexToInt[p[1] & 255]) != -1) { //+ c = A << 4 | B;+ if (!(0x20 <= c && c <= 0x7E))+ return hex_escape_not_printable;+ p += 2;+ b += c;+ break;+ } else {+ return invalid_hex_escape;+ }+ case 'u':+ if (p + 4 <= e && //+ (A = kHexToInt[p[0] & 255]) != -1 && //+ (B = kHexToInt[p[1] & 255]) !=+ -1 && // UCS-2+ (C = kHexToInt[p[2] & 255]) != -1 && //+ (D = kHexToInt[p[3] & 255]) != -1) { //+ c = A << 12 | B << 8 | C << 4 | D;+ if (!IsSurrogate(c)) {+ p += 4;+ } else if (IsHighSurrogate(c)) {+ if (p + 4 + 6 <= e && //+ p[4] == '\\' && //+ p[5] == 'u' && //+ (A = kHexToInt[p[6] & 255]) !=+ -1 && // UTF-16+ (B = kHexToInt[p[7] & 255]) !=+ -1 && //+ (C = kHexToInt[p[8] & 255]) !=+ -1 && //+ (D = kHexToInt[p[9] & 255]) !=+ -1) { //+ u =+ A << 12 | B << 8 | C << 4 | D;+ if (IsLowSurrogate(u)) {+ p += 4 + 6;+ c = MergeUtf16(c, u);+ } else {+ goto BadUnicode;+ }+ } else {+ goto BadUnicode;+ }+ } else {+ goto BadUnicode;+ }+ // UTF-8+ EncodeUtf8:+ if (c <= 0x7f) {+ w[0] = c;+ i = 1;+ } else if (c <= 0x7ff) {+ w[0] = 0300 | (c >> 6);+ w[1] = 0200 | (c & 077);+ i = 2;+ } else if (c <= 0xffff) {+ if (IsSurrogate(c)) {+ ReplacementCharacter:+ c = 0xfffd;+ }+ w[0] = 0340 | (c >> 12);+ w[1] = 0200 | ((c >> 6) & 077);+ w[2] = 0200 | (c & 077);+ i = 3;+ } else if (~(c >> 18) & 007) {+ w[0] = 0360 | (c >> 18);+ w[1] = 0200 | ((c >> 12) & 077);+ w[2] = 0200 | ((c >> 6) & 077);+ w[3] = 0200 | (c & 077);+ i = 4;+ } else {+ goto ReplacementCharacter;+ }+ b.append(w, i);+ } else {+ return invalid_unicode_escape;+ BadUnicode:+ // Echo invalid \uXXXX sequences+ // Rather than corrupting UTF-8!+ b += "\\u";+ }+ break;+ default:+ return invalid_escape_character;+ }+ break;++ case UTF8_2:+ if (p < e && //+ (p[0] & 0300) == 0200) { //+ c = (c & 037) << 6 | //+ (p[0] & 077); //+ p += 1;+ goto EncodeUtf8;+ } else {+ return malformed_utf8;+ }++ case UTF8_3_E0:+ if (p + 2 <= e && //+ (p[0] & 0377) < 0240 && //+ (p[0] & 0300) == 0200 && //+ (p[1] & 0300) == 0200) {+ return overlong_utf8_0x7ff;+ }+ // fallthrough++ case UTF8_3:+ ThreeUtf8:+ if (p + 2 <= e && //+ (p[0] & 0300) == 0200 && //+ (p[1] & 0300) == 0200) { //+ c = (c & 017) << 12 | //+ (p[0] & 077) << 6 | //+ (p[1] & 077); //+ p += 2;+ goto EncodeUtf8;+ } else {+ return malformed_utf8;+ }++ case UTF8_3_ED:+ if (p + 2 <= e && //+ (p[0] & 0377) >= 0240) { //+ if (p + 5 <= e && //+ (p[0] & 0377) >= 0256 && //+ (p[1] & 0300) == 0200 && //+ (p[2] & 0377) == 0355 && //+ (p[3] & 0377) >= 0260 && //+ (p[4] & 0300) == 0200) { //+ A = (0355 & 017) << 12 | // CESU-8+ (p[0] & 077) << 6 | //+ (p[1] & 077); //+ B = (0355 & 017) << 12 | //+ (p[3] & 077) << 6 | //+ (p[4] & 077); //+ c = ((A - 0xDB80) << 10) + //+ ((B - 0xDC00) + 0x10000); //+ goto EncodeUtf8;+ } else if ((p[0] & 0300) == 0200 && //+ (p[1] & 0300) == 0200) { //+ return utf16_surrogate_in_utf8;+ } else {+ return malformed_utf8;+ }+ }+ goto ThreeUtf8;++ case UTF8_4_F0:+ if (p + 3 <= e && (p[0] & 0377) < 0220 &&+ (((uint32_t)(p[+2] & 0377) << 030 |+ (uint32_t)(p[+1] & 0377) << 020 |+ (uint32_t)(p[+0] & 0377) << 010 |+ (uint32_t)(p[-1] & 0377) << 000) &+ 0xC0C0C000) == 0x80808000) {+ return overlong_utf8_0xffff;+ }+ // fallthrough+ case UTF8_4:+ if (p + 3 <= e && //+ ((A = ((uint32_t)(p[+2] & 0377) << 030 | //+ (uint32_t)(p[+1] & 0377) << 020 | //+ (uint32_t)(p[+0] & 0377) << 010 | //+ (uint32_t)(p[-1] & 0377) << 000)) & //+ 0xC0C0C000) == 0x80808000) { //+ A = (A & 7) << 18 | //+ (A & (077 << 010)) << (12 - 010) | //+ (A & (077 << 020)) >> -(6 - 020) | //+ (A & (077 << 030)) >> 030; //+ if (A <= 0x10FFFF) {+ c = A;+ p += 3;+ goto EncodeUtf8;+ } else {+ return utf8_exceeds_utf16_range;+ }+ } else {+ return malformed_utf8;+ }++ case EVILUTF8:+ if (p < e && (p[0] & 0300) == 0200)+ return overlong_ascii;+ // fallthrough+ case BADUTF8:+ return illegal_utf8_character;+ case C0:+ return non_del_c0_control_code_in_string;+ case C1:+ return c1_control_code_in_string;+ default:+ __builtin_unreachable();+ }+ }__builtin_unreachable();+ }}}- *p = 0;- return p;+ if (depth == DEPTH)+ return absent_value;+ return unexpected_eof;+}++ctl::pair<Json::Status, Json>+Json::parse(const ctl::string_view& s)+{+ Json::Status s2;+ ctl::pair<Json::Status, Json> res;+ const char* p = s.data();+ const char* e = s.data() + s.size();+ res.first = parse(res.second, p, e, 0, DEPTH);+ if (res.first == Json::success) {+ if (!res.second.isObject() && !res.second.isArray()) {+ res.first = json_payload_should_be_object_or_array;+ } else {+ s2 = parse(res.second, p, e, 0, DEPTH);+ if (s2 != absent_value)+ res.first = trailing_content;+ }+ }+ return res;+}++const char*+Json::StatusToString(Json::Status status)+{+ switch (status) {+ case success:+ return "success";+ case bad_double:+ return "bad_double";+ case absent_value:+ return "absent_value";+ case bad_negative:+ return "bad_negative";+ case bad_exponent:+ return "bad_exponent";+ case missing_comma:+ return "missing_comma";+ case missing_colon:+ return "missing_colon";+ case malformed_utf8:+ return "malformed_utf8";+ case depth_exceeded:+ return "depth_exceeded";+ case stack_overflow:+ return "stack_overflow";+ case unexpected_eof:+ return "unexpected_eof";+ case overlong_ascii:+ return "overlong_ascii";+ case unexpected_comma:+ return "unexpected_comma";+ case unexpected_colon:+ return "unexpected_colon";+ case unexpected_octal:+ return "unexpected_octal";+ case trailing_content:+ return "trailing_content";+ case illegal_character:+ return "illegal_character";+ case invalid_hex_escape:+ return "invalid_hex_escape";+ case overlong_utf8_0x7ff:+ return "overlong_utf8_0x7ff";+ case overlong_utf8_0xffff:+ return "overlong_utf8_0xffff";+ case object_missing_value:+ return "object_missing_value";+ case illegal_utf8_character:+ return "illegal_utf8_character";+ case invalid_unicode_escape:+ return "invalid_unicode_escape";+ case utf16_surrogate_in_utf8:+ return "utf16_surrogate_in_utf8";+ case unexpected_end_of_array:+ return "unexpected_end_of_array";+ case hex_escape_not_printable:+ return "hex_escape_not_printable";+ case invalid_escape_character:+ return "invalid_escape_character";+ case utf8_exceeds_utf16_range:+ return "utf8_exceeds_utf16_range";+ case unexpected_end_of_string:+ return "unexpected_end_of_string";+ case unexpected_end_of_object:+ return "unexpected_end_of_object";+ case object_key_must_be_string:+ return "object_key_must_be_string";+ case c1_control_code_in_string:+ return "c1_control_code_in_string";+ case non_del_c0_control_code_in_string:+ return "non_del_c0_control_code_in_string";+ case json_payload_should_be_object_or_array:+ return "json_payload_should_be_object_or_array";+ default:+ __builtin_trap();+ }}diff --git a/llamafile/server/json.h b/llamafile/server/json.hindex 0bee2b0c..1f332bce 100644--- a/llamafile/server/json.h+++ b/llamafile/server/json.h@@ -16,31 +16,238 @@// limitations under the License.#pragma once-#include <ctl/string_view.h>+#include <ctl/map.h>+#include <ctl/string.h>+#include <ctl/vector.h>-char*-encode_bool(char*, bool) noexcept;+class Json+{+ public:+ enum Type+ {+ Null,+ Bool,+ Long,+ Ulong,+ Float,+ Double,+ String,+ Array,+ Object+ };-char*-encode_json(char*, int) noexcept;+ enum Status+ {+ success,+ bad_double,+ absent_value,+ bad_negative,+ bad_exponent,+ missing_comma,+ missing_colon,+ malformed_utf8,+ depth_exceeded,+ stack_overflow,+ unexpected_eof,+ overlong_ascii,+ unexpected_comma,+ unexpected_colon,+ unexpected_octal,+ trailing_content,+ illegal_character,+ invalid_hex_escape,+ overlong_utf8_0x7ff,+ overlong_utf8_0xffff,+ object_missing_value,+ illegal_utf8_character,+ invalid_unicode_escape,+ utf16_surrogate_in_utf8,+ unexpected_end_of_array,+ hex_escape_not_printable,+ invalid_escape_character,+ utf8_exceeds_utf16_range,+ unexpected_end_of_string,+ unexpected_end_of_object,+ object_key_must_be_string,+ c1_control_code_in_string,+ non_del_c0_control_code_in_string,+ json_payload_should_be_object_or_array,+ };-char*-encode_json(char*, long) noexcept;+ private:+ Type type_;+ union+ {+ bool bool_value;+ long long_value;+ float float_value;+ double double_value;+ ctl::string string_value;+ unsigned long ulong_value;+ ctl::vector<Json> array_value;+ ctl::map<ctl::string, Json> object_value;+ };-char*-encode_json(char*, float) noexcept;+ public:+ static const char* StatusToString(Status);+ static ctl::pair<Status, Json> parse(const ctl::string_view&);-char*-encode_json(char*, double) noexcept;+ Json(const Json&);+ Json(Json&&) noexcept;-char*-encode_json(char*, unsigned) noexcept;+ ~Json()+ {+ clear();+ }-char*-encode_json(char*, unsigned long) noexcept;+ Json(const nullptr_t = nullptr) : type_(Null)+ {+ }-char*-encode_json(char*, const ctl::string_view) noexcept;+ Json(bool value) : type_(Bool), bool_value(value)+ {+ }-char*-encode_js_string_literal(char*, const ctl::string_view) noexcept;+ Json(float value) : type_(Float), float_value(value)+ {+ }++ Json(double value) : type_(Double), double_value(value)+ {+ }++ Json(int value) : type_(Long), long_value(value)+ {+ }++ Json(long value) : type_(Long), long_value(value)+ {+ }++ Json(unsigned value) : type_(Ulong), ulong_value(value)+ {+ }++ Json(unsigned long value) : type_(Ulong), ulong_value(value)+ {+ }++ Json(const char* value) : type_(String), string_value(value)+ {+ }++ Json(ctl::string&& value) : type_(String), string_value(ctl::move(value))+ {+ }++ Json(const ctl::string& value) : type_(String), string_value(value)+ {+ }++ Json(const ctl::string_view& value) : type_(String), string_value(value)+ {+ }++ Type getType() const+ {+ return type_;+ }++ bool isNull() const+ {+ return type_ == Null;+ }++ bool isBool() const+ {+ return type_ == Bool;+ }++ bool isNumber() const+ {+ return isFloat() || isDouble() || isInteger();+ }++ bool isInteger() const+ {+ return isLong() || isUlong();+ }++ bool isLong() const+ {+ return type_ == Long;+ }++ bool isUlong() const+ {+ return type_ == Ulong;+ }++ bool isFloat() const+ {+ return type_ == Float;+ }++ bool isDouble() const+ {+ return type_ == Double;+ }++ bool isString() const+ {+ return type_ == String;+ }++ bool isArray() const+ {+ return type_ == Array;+ }++ bool isObject() const+ {+ return type_ == Object;+ }++ bool getBool() const;+ long getLong() const;+ float getFloat() const;+ double getDouble() const;+ double getNumber() const;+ unsigned long getUlong() const;+ ctl::string& getString();+ ctl::vector<Json>& getArray();+ ctl::map<ctl::string, Json>& getObject();++ void setNull();+ void setBool(bool);+ void setLong(long);+ void setFloat(float);+ void setDouble(double);+ void setString(const char*);+ void setUlong(unsigned long);+ void setString(ctl::string&&);+ void setString(const ctl::string&);+ void setString(const ctl::string_view&);+ void setArray();+ void setObject();++ ctl::string toString(bool pretty = false) const noexcept;++ Json& operator=(const Json&);+ Json& operator=(Json&&) noexcept;++ Json& operator[](size_t) noexcept;+ Json& operator[](const ctl::string&) noexcept;++ operator ctl::string() const noexcept+ {+ return toString();+ }++ private:+ void clear();+ void marshal(ctl::string&, bool, int) const noexcept;+ static void stringify(ctl::string&, const ctl::string_view&) noexcept;+ static void serialize(ctl::string&, const ctl::string_view&) noexcept;+ static Status parse(Json&, const char*&, const char*, int, int);+};diff --git a/llamafile/server/json_test.cpp b/llamafile/server/json_test.cppindex cf9d6647..c418b49d 100644--- a/llamafile/server/json_test.cpp+++ b/llamafile/server/json_test.cpp@@ -17,112 +17,386 @@#include "json.h"-#include <ctl/string.h>-#include <limits.h>-#include <math.h>+#include <cosmo.h>#include <stdio.h>+#include <stdlib.h>-using namespace ctl;+#include "llamafile/macros.h"-string-encode_json(int x) noexcept+static const char kHuge[] = R"([+ "JSON Test Pattern pass1",+ {"object with 1 member":["array with 1 element"]},+ {},+ [],+ -42,+ true,+ false,+ null,+ {+ "integer": 1234567890,+ "real": -9876.543210,+ "e": 0.123456789e-12,+ "E": 1.234567890E+34,+ "": 23456789012E66,+ "zero": 0,+ "one": 1,+ "space": " ",+ "quote": "\"",+ "backslash": "\\",+ "controls": "\b\f\n\r\t",+ "slash": "/ & \/",+ "alpha": "abcdefghijklmnopqrstuvwyz",+ "ALPHA": "ABCDEFGHIJKLMNOPQRSTUVWYZ",+ "digit": "0123456789",+ "0123456789": "digit",+ "special": "`1~!@#$%^&*()_+-={':[,]}|;.</>?",+ "hex": "\u0123\u4567\u89AB\uCDEF\uabcd\uef4A",+ "true": true,+ "false": false,+ "null": null,+ "array":[ ],+ "object":{ },+ "address": "50 St. James Street",+ "url": "http://www.JSON.org/",+ "comment": "// /* <!-- --",+ "# -- --> */": " ",+ " s p a c e d " :[1,2 , 3++,++4 , 5 , 6 ,7 ],"compact":[1,2,3,4,5,6,7],+ "jsontext": "{\"object with 1 member\":[\"array with 1 element\"]}",+ "quotes": "" \u0022 %22 0x22 034 "",+ "\/\\\"\uCAFE\uBABE\uAB98\uFCDE\ubcda\uef4A\b\f\n\r\t`1~!@#$%^&*()_+-=[]{}|;:',./<>?"+: "A key can be any string"+ },+ 0.5 ,98.6+,+99.44+,++1066,+1e1,+0.1e1,+1e-1,+1e00,2e+00,2e-00+,"rosebud"])";++#define BENCH(ITERATIONS, WORK_PER_RUN, CODE) \+ do { \+ struct timespec start = timespec_real(); \+ for (int __i = 0; __i < ITERATIONS; ++__i) { \+ asm volatile("" ::: "memory"); \+ CODE; \+ } \+ long long work = (WORK_PER_RUN) * (ITERATIONS); \+ double nanos = \+ (timespec_tonanos(timespec_sub(timespec_real(), start)) + work - \+ 1) / \+ (double)work; \+ printf("%10g ns %2dx %s\n", nanos, (ITERATIONS), #CODE); \+ } while (0)++void+object_test(){- char buf[12];- return { buf, (size_t)(encode_json(buf, x) - buf) };+ Json obj;+ obj["content"] = "hello";+ if (obj.toString() != "{\"content\":\"hello\"}")+ exit(1);}-string-encode_json(long x) noexcept+void+deep_test(){- char buf[21];- return { buf, (size_t)(encode_json(buf, x) - buf) };+ Json A1;+ A1[0] = 0;+ A1[1] = 10;+ A1[2] = 20;+ A1[3] = 3.14;+ A1[4] = 40;+ Json A2;+ A2[0] = ctl::move(A1);+ Json A3;+ A3[0] = ctl::move(A2);+ Json obj;+ obj["content"] = ctl::move(A3);+ if (obj.toString() != "{\"content\":[[[0,10,20,3.14,40]]]}")+ exit(2);}-string-encode_json(double x) noexcept+void+parse_test(){- char buf[128];- return { buf, (size_t)(encode_json(buf, x) - buf) };+ ctl::pair<Json::Status, Json> res =+ Json::parse("{ \"content\":[[[0,10,20,3.14,40]]]}");+ if (res.first != Json::success)+ exit(3);+ if (res.second.toString() != "{\"content\":[[[0,10,20,3.14,40]]]}")+ exit(4);+ if (res.second.toString(true) !=+ R"({"content": [[[0, 10, 20, 3.14, 40]]]})")+ exit(5);+ res = Json::parse("{ \"a\": 1, \"b\": [2, 3]}");+ if (res.second.toString(false) != R"({"a":1,"b":[2,3]})")+ exit(6);+ if (res.second.toString(true) !=+ R"({+ "a": 1,+ "b": [2, 3]+})")+ exit(7);}-string-encode_json(unsigned x) noexcept+static const struct{- char buf[128];- return { buf, (size_t)(encode_json(buf, x) - buf) };-}+ ctl::string before;+ ctl::string after;+} kRoundTrip[] = {++ // valid utf16 sequences+ { " [\"\\u0020\"] ", "[\" \"]" },+ { " [\"\\u00A0\"] ", "[\"\\u00a0\"]" },++ // when we encounter invalid utf16 sequences+ // we turn them into ascii+ { "[\"\\uDFAA\"]", "[\"\\\\uDFAA\"]" },+ { " [\"\\uDd1e\\uD834\"] ", "[\"\\\\uDd1e\\\\uD834\"]" },+ { " [\"\\ud800abc\"] ", "[\"\\\\ud800abc\"]" },+ { " [\"\\ud800\"] ", "[\"\\\\ud800\"]" },+ { " [\"\\uD800\\uD800\\n\"] ", "[\"\\\\uD800\\\\uD800\\n\"]" },+ { " [\"\\uDd1ea\"] ", "[\"\\\\uDd1ea\"]" },+ { " [\"\\uD800\\n\"] ", "[\"\\\\uD800\\n\"]" },-string-encode_json(unsigned long x) noexcept+ // underflow and overflow+ { " [123.456e-789] ", "[0]" },+ { " [0."+ "4e0066999999999999999999999999999999999999999999999999999999999999999999"+ "9999999999999999999999999999999999999999999999999969999999006] ",+ "[1e5000]" },+ { " [1.5e+9999] ", "[1e5000]" },+ { " [-1.5e+9999] ", "[-1e5000]" },+ { " [-123123123123123123123123123123] ", "[-1.2312312312312312e+29]" },+};++// https://github.com/nst/JSONTestSuite/+static const struct{- char buf[128];- return { buf, (size_t)(encode_json(buf, x) - buf) };+ Json::Status error;+ ctl::string json;+} kJsonTestSuite[] = {+ { Json::absent_value, "" },+ { Json::json_payload_should_be_object_or_array, "null" },+ { Json::trailing_content, "[] []" },+ { Json::illegal_character, "[nan]" },+ { Json::bad_negative, "[-nan]" },+ { Json::illegal_character, "[+NaN]" },+ { Json::trailing_content,+ "{\"Extra value after close\": true} \"misplaced quoted value\"" },+ { Json::illegal_character, "{\"Illegal expression\": 1 + 2}" },+ { Json::illegal_character, "{\"Illegal invocation\": alert()}" },+ { Json::unexpected_octal, "{\"Numbers cannot have leading zeroes\": 013}" },+ { Json::illegal_character, "{\"Numbers cannot be hex\": 0x14}" },+ { Json::hex_escape_not_printable, "[\"Illegal backslash escape: \\x15\"]" },+ { Json::illegal_character, "[\\naked]" },+ { Json::invalid_escape_character, "[\"Illegal backslash escape: \\017\"]" },+ { Json::depth_exceeded,+ "[[[[[[[[[[[[[[[[[[[[\"Too deep\"]]]]]]]]]]]]]]]]]]]]" },+ { Json::missing_colon, "{\"Missing colon\" null}" },+ { Json::json_payload_should_be_object_or_array,+ "\"A JSON payload should be an object or array, not a string.\"" },+ { Json::unexpected_colon, "{\"Double colon\":: null}" },+ { Json::unexpected_comma, "{\"Comma instead of colon\", null}" },+ { Json::unexpected_colon, "[\"Colon instead of comma\": false]" },+ { Json::illegal_character, "[\"Bad value\", truth]" },+ { Json::illegal_character, "[\'single quote\']" },+ { Json::non_del_c0_control_code_in_string,+ "[\"\ttab\tcharacter\tin\tstring\t\"]" },+ { Json::invalid_escape_character,+ "[\"tab\\ character\\ in\\ string\\ \"]" },+ { Json::non_del_c0_control_code_in_string, "[\"line\nbreak\"]" },+ { Json::invalid_escape_character, "[\"line\\\nbreak\"]" },+ { Json::bad_exponent, "[0e]" },+ { Json::unexpected_eof, "[\"Unclosed array\"" },+ { Json::bad_exponent, "[0e+]" },+ { Json::bad_exponent, "[0e+-1]" },+ { Json::unexpected_eof, "{\"Comma instead if closing brace\": true," },+ { Json::unexpected_end_of_object, "[\"mismatch\"}" },+ { Json::illegal_character, "{unquoted_key: \"keys must be quoted\"}" },+ { Json::unexpected_end_of_array, "[\"extra comma\",]" },+ { Json::unexpected_comma, "[\"double extra comma\",,]" },+ { Json::unexpected_comma, "[ , \"<-- missing value\"]" },+ { Json::trailing_content, "[\"Comma after the close\"]," },+ { Json::trailing_content, "[\"Extra close\"]]" },+ { Json::unexpected_end_of_object, "{\"Extra comma\": true,}" },+ { Json::unexpected_eof, " {\"a\" " },+ { Json::unexpected_eof, " {\"a\": " },+ { Json::unexpected_colon, " {:\"b\" " },+ { Json::illegal_character, " {\"a\" b} " },+ { Json::illegal_character, " {key: 'value'} " },+ { Json::object_key_must_be_string, " {\"a\":\"a\" 123} " },+ { Json::illegal_character, " \x7b\xf0\x9f\x87\xa8\xf0\x9f\x87\xad\x7d " },+ { Json::object_key_must_be_string, " {[: \"x\"} " },+ { Json::illegal_character, " [1.8011670033376514H-308] " },+ { Json::illegal_character, " [1.2a-3] " },+ { Json::illegal_character, " [.123] " },+ { Json::bad_exponent, " [1e\xe5] " },+ { Json::bad_exponent, " [1ea] " },+ { Json::illegal_character, " [-1x] " },+ { Json::bad_negative, " [-.123] " },+ { Json::bad_negative, " [-foo] " },+ { Json::bad_negative, " [-Infinity] " },+ { Json::illegal_character, " \x5b\x30\xe5\x5d " },+ { Json::illegal_character, " \x5b\x31\x65\x31\xe5\x5d " },+ { Json::illegal_character, " \x5b\x31\x32\x33\xe5\x5d " },+ { Json::missing_comma,+ " \x5b\x2d\x31\x32\x33\x2e\x31\x32\x33\x66\x6f\x6f\x5d " },+ { Json::bad_exponent, " [0e+-1] " },+ { Json::illegal_character, " [Infinity] " },+ { Json::illegal_character, " [0x42] " },+ { Json::illegal_character, " [0x1] " },+ { Json::illegal_character, " [1+2] " },+ { Json::illegal_character, " \x5b\xef\xbc\x91\x5d " },+ { Json::illegal_character, " [NaN] " },+ { Json::illegal_character, " [Inf] " },+ { Json::bad_double, " [9.e+] " },+ { Json::bad_exponent, " [1eE2] " },+ { Json::bad_exponent, " [1e0e] " },+ { Json::bad_exponent, " [1.0e-] " },+ { Json::bad_exponent, " [1.0e+] " },+ { Json::bad_exponent, " [0e] " },+ { Json::bad_exponent, " [0e+] " },+ { Json::bad_exponent, " [0E] " },+ { Json::bad_exponent, " [0E+] " },+ { Json::bad_exponent, " [0.3e] " },+ { Json::bad_exponent, " [0.3e+] " },+ { Json::illegal_character, " [0.1.2] " },+ { Json::illegal_character, " [.2e-3] " },+ { Json::illegal_character, " [.-1] " },+ { Json::bad_negative, " [-NaN] " },+ { Json::illegal_character, " [+Inf] " },+ { Json::illegal_character, " [+1] " },+ { Json::illegal_character, " [++1234] " },+ { Json::illegal_character, " [tru] " },+ { Json::illegal_character, " [nul] " },+ { Json::illegal_character, " [fals] " },+ { Json::unexpected_eof, " [{} " },+ { Json::unexpected_eof, "\n[1,\n1\n,1 " },+ { Json::unexpected_eof, " [1, " },+ { Json::unexpected_eof, " [\"\" " },+ { Json::illegal_character, " [* " },+ { Json::non_del_c0_control_code_in_string,+ " \x5b\x22\x0b\x61\x22\x5c\x66\x5d " },+ { Json::unexpected_eof, "[\"a\",\n4\n,1,1 " },+ { Json::unexpected_colon, " [1:2] " },+ { Json::illegal_character, " \x5b\xff\x5d " },+ { Json::illegal_character, " \x5b\x78 " },+ { Json::unexpected_eof, " [\"x\" " },+ { Json::unexpected_colon, " [\"\": 1] " },+ { Json::illegal_character, " [a\xe5] " },+ { Json::unexpected_comma, " {\"x\", null} " },+ { Json::illegal_character, " [\"x\", truth] " },+ { Json::json_payload_should_be_object_or_array, " 123\x00 "s },+ { Json::illegal_character, "\x00"s },+ { Json::trailing_content, "\n[\"x\"]]" },+ { Json::unexpected_octal, " [012] " },+ { Json::unexpected_octal, " [-012] " },+ { Json::missing_comma, " [1 000.0] " },+ { Json::unexpected_octal, " [-01] " },+ { Json::bad_negative, " [- 1] " },+ { Json::bad_negative, " [-] " },+ { Json::illegal_utf8_character, " {\"\xb9\":\"0\",} " },+ { Json::unexpected_colon, " {\"x\"::\"b\"} " },+ { Json::unexpected_comma, " [1,,] " },+ { Json::unexpected_end_of_array, " [1,] " },+ { Json::unexpected_comma, " [1,,2] " },+ { Json::unexpected_comma, " [,1] " },+ { Json::missing_comma, " [ 3[ 4]] " },+ { Json::missing_comma, " [1 true] " },+ { Json::missing_comma, " [\"a\" \"b\"] " },+ { Json::bad_negative, " [--2.] " },+ { Json::bad_double, " [1.] " },+ { Json::bad_double, " [2.e3] " },+ { Json::bad_double, " [2.e-3] " },+ { Json::bad_double, " [2.e+3] " },+ { Json::bad_double, " [0.e1] " },+ { Json::bad_double, " [-2.] " },+ { Json::illegal_character, " \xef\xbb\xbf{} " },+ { Json::illegal_character, " [\x00\"\x00\xe9\x00\"\x00]\x00 "s },+ { Json::illegal_character, " \x00[\x00\"\x00\xe9\x00\"\x00] "s },+ { Json::malformed_utf8, " [\"\xe0\xff\"] " },+ { Json::illegal_utf8_character, " [\"\xfc\x80\x80\x80\x80\x80\"] " },+ { Json::illegal_utf8_character, " [\"\xfc\x83\xbf\xbf\xbf\xbf\"] " },+ { Json::overlong_ascii, " [\"\xc0\xaf\"] " },+ { Json::utf8_exceeds_utf16_range, " [\"\xf4\xbf\xbf\xbf\"] " },+ { Json::c1_control_code_in_string, " [\"\x81\"] " },+ { Json::malformed_utf8, " [\"\xe9\"] " },+ { Json::illegal_utf8_character, " [\"\xff\"] " },+ { Json::success, kHuge },+ { Json::success,+ R"([[[[[[[[[[[[[[[[[[["Not too deep"]]]]]]]]]]]]]]]]]]])" },+ { Json::success, R"({+ "JSON Test Pattern pass3": {+ "The outermost value": "must be an object or array.",+ "In this test": "It is an object."+ }}+)" },+};-string-encode_json(const string_view x) noexcept+void+round_trip_test(){- char buf[128];- return { buf, (size_t)(encode_json(buf, x) - buf) };+ for (size_t i = 0; i < ARRAYLEN(kRoundTrip); ++i) {+ ctl::pair<Json::Status, Json> res = Json::parse(kRoundTrip[i].before);+ if (res.first != Json::success) {+ printf("error: Json::parse returned Json::%s but wanted Json::%s: "+ "%`'s\n",+ Json::StatusToString(res.first),+ Json::StatusToString(Json::success),+ kRoundTrip[i].before.c_str());+ exit(10);+ }+ if (res.second.toString() != kRoundTrip[i].after) {+ printf("error: Json::parse(%`'s).toString() was %`'s but should "+ "have been %`'s\n",+ kRoundTrip[i].before.c_str(),+ res.second.toString().c_str(),+ kRoundTrip[i].after.c_str());+ exit(11);+ }+ }}-string-encode_js_string_literal(const string_view x) noexcept+void+json_test_suite(){- char buf[256]; // this isn't secure (no guard page)- return { buf, (size_t)(encode_json(buf, x) - buf) };+ for (size_t i = 0; i < ARRAYLEN(kJsonTestSuite); ++i) {+ ctl::pair<Json::Status, Json> res = Json::parse(kJsonTestSuite[i].json);+ if (res.first != kJsonTestSuite[i].error) {+ printf("error: Json::parse returned Json::%s but wanted Json::%s: "+ "%`'s\n",+ Json::StatusToString(res.first),+ Json::StatusToString(kJsonTestSuite[i].error),+ kJsonTestSuite[i].json.c_str());+ exit(12);+ }+ }}int-main(int argc, char* argv[])+main(){+ object_test();+ deep_test();+ parse_test();+ round_trip_test();++ BENCH(2000, 1, object_test());+ BENCH(2000, 1, deep_test());+ BENCH(2000, 1, parse_test());+ BENCH(2000, 1, round_trip_test());+ BENCH(2000, 1, json_test_suite());- if (encode_json(0) != "0")- return 1;- if (encode_json(INT_MAX) != "2147483647")- return 2;- if (encode_json(INT_MIN) != "-2147483648")- return 3;- if (encode_json(UINT_MAX) != "4294967295")- return 4;- if (encode_json(LONG_MAX) != "9223372036854775807")- return 5;- if (encode_json(LONG_MIN) != "-9223372036854775808")- return 6;- if (encode_json(ULONG_MAX) != "18446744073709551615")- return 7;-- if (encode_json("") != "\"\"")- return 8;- if (encode_json(string_view("\0\1", 2)) != "\"\\u0000\\u0001\"")- return 9;- if (encode_json("\n\"\\\t") != "\"\\n\\\"\\\\\\t\"")- return 10;- if (encode_json("'") != "\"\\u0027\"")- return 11;- if (encode_json("µ") != "\"\\u00b5\"")- return 12;- if (encode_json("𐌰") != "\"\\ud800\\udf30\"")- return 13;-- if (encode_json(3.) != "3")- return 14;- if (encode_json(3.14) != "3.14")- return 15;- if (encode_json(1e+100) != "1e+100")- return 16;- if (encode_json(1e-100) != "1e-100")- return 17;- if (encode_json(+INFINITY) != "1e5000")- return 18;- if (encode_json(-INFINITY) != "-1e5000")- return 19;- if (encode_json(+NAN) != "null")- return 20;- if (encode_json(-NAN) != "null")- return 21;- if (encode_json(1e-300) != "1e-300")- return 21;-- return 0;+ CheckForMemoryLeaks();}diff --git a/llamafile/server/main.cpp b/llamafile/server/main.cppindex 40f2c1ae..119921d2 100644--- a/llamafile/server/main.cpp+++ b/llamafile/server/main.cpp@@ -22,7 +22,6 @@#include "llamafile/llamafile.h"#include "llamafile/version.h"-#include "json.h"#include "log.h"#include "server.h"#include "signals.h"diff --git a/llamafile/server/tokenize.cpp b/llamafile/server/tokenize.cppindex fe3d8c46..e697ecac 100644--- a/llamafile/server/tokenize.cpp+++ b/llamafile/server/tokenize.cpp@@ -23,7 +23,7 @@#include "llama.cpp/llama.h"-#include "json.h"+#include "fastjson.h"#include "log.h"#include "utils.h"