pjson 2.0.0
A small, owning JSON value for C++11
Loading...
Searching...
No Matches
pjson_parser.h
1// SPDX-FileCopyrightText: 2026 ByteDance Ltd. and/or its affiliates
2// SPDX-License-Identifier: Apache-2.0
3#ifndef PRAVEENJSON_PARSER_H
4#define PRAVEENJSON_PARSER_H
5
6#include "pjson.h"
7
8namespace ByteDance {
9 struct pJsonParserImpl;
10 /// Configured, reusable JSON parser for DOM and SAX input.
11 ///
12 /// The parser depends on the pjson DOM, while pjson itself has no parser
13 /// dependency. A parser borrows its allocator, owns a copy of its options,
14 /// and keeps no mutable per-call state, so it may be reused for many inputs.
15 class PJSON_API pJsonParser {
16 public:
17 /// Bounds parsing work and selects duplicate-key and number policies.
18 struct PJSON_API Options {
19 /// Controls how repeated object member names are handled.
21 RejectDuplicateKeys, ///< Fail when a name occurs more than once.
22 KeepFirstDuplicate, ///< Retain the first value and discard later values.
23 KeepLastDuplicate ///< Replace an earlier value with the last value.
24 };
25 /// Controls numeric tokens that cannot be represented exactly.
27 RejectUnrepresentableNumbers, ///< Reject range overflow and nonzero underflow.
28 AllowLossyNumbers ///< Store the nearest finite double when possible.
29 };
30
31 int maxDepth; ///< Nesting limit; non-positive means one level.
32 size_t maxNodes; ///< Maximum values processed; zero is unlimited.
33 size_t maxInputBytes; ///< Maximum input bytes; zero is unlimited.
34 DuplicateKeyPolicy duplicateKeys; ///< Duplicate object-name policy.
35 NumberPolicy numberPolicy; ///< Unrepresentable-number policy.
36 /// Selects strict defaults and bounded parser resources.
37 Options();
38 };
39
40 /// Structured result for DOM and SAX parsing.
41 struct PJSON_API Error {
42 /// Stable categories for programmatic parse-failure handling.
43 enum Code {
44 None = 0, ///< Parsing succeeded.
45 Syntax, ///< The input violates JSON grammar.
46 InvalidEncoding, ///< UTF-8 or an escaped Unicode value is invalid.
47 DuplicateKey, ///< A repeated object name was rejected.
48 NumberRange, ///< A number is outside the configured representation policy.
49 DepthLimit, ///< Nesting exceeded the effective depth limit.
50 InputLimit, ///< Input exceeded maxInputBytes.
51 NodeLimit, ///< Values processed exceeded maxNodes.
52 AllocationFailure, ///< Parser, DOM, or callback allocation failed.
53 StreamError, ///< Reading from the input stream failed.
54 CallbackError, ///< A SAX callback cancelled or threw.
55 InvalidArgument ///< The caller supplied an invalid argument.
56 };
57
58 bool ok; ///< True when the most recent parse succeeded.
59 Code code; ///< Stable machine-facing result category.
60 size_t offset; ///< Zero-based input byte offset.
61 size_t line; ///< One-based source line.
62 size_t column; ///< One-based byte column.
63 std::string message; ///< Human-readable diagnostic; wording is not stable.
64 /// Constructs the successful start-of-input state.
65 Error();
66 };
67
68 /// Event sink for non-owning SAX parsing.
69 struct PJSON_API SaxHandler {
70 /// Enables destruction through a handler base pointer.
71 virtual ~SaxHandler();
72 /// Receives null; return false to cancel.
73 virtual bool onNull();
74 /// Receives a boolean; return false to cancel.
75 virtual bool onBool(bool aValue);
76 /// Receives a signed integer; return false to cancel.
77 virtual bool onInt(int64_t aValue);
78 /// Receives an unsigned integer above the signed range; return false to cancel.
79 virtual bool onUInt(uint64_t aValue);
80 /// Receives a floating-point number; return false to cancel.
81 virtual bool onDouble(double aValue);
82 /// Receives a borrowed decoded string; return false to cancel.
83 virtual bool onString(const std::string& aValue);
84 /// Marks the beginning of an array; return false to cancel.
85 virtual bool onStartArray();
86 /// Marks the end of an array; return false to cancel.
87 virtual bool onEndArray();
88 /// Marks the beginning of an object; return false to cancel.
89 virtual bool onStartObject();
90 /// Receives a borrowed decoded key; return false to cancel.
91 virtual bool onKey(const std::string& aKey);
92 /// Marks the end of an object; return false to cancel.
93 virtual bool onEndObject();
94 };
95
96 /// Uses the default DOM allocator and default parser options.
97 explicit pJsonParser(const Options& aOptions = Options());
98 /// Uses borrowed aAllocator, which must outlive this parser and its DOM results.
99 explicit pJsonParser(pjson::Allocator& aAllocator, const Options& aOptions = Options());
100 /// Releases the private parser configuration.
102 /// Copies the parser configuration while borrowing the same allocator.
103 pJsonParser(const pJsonParser& aOther);
104 /// Transfers parser configuration and leaves aOther usable with defaults.
105 pJsonParser(pJsonParser&& aOther) noexcept;
106 /// Copies parser configuration while borrowing aOther's allocator.
108 /// Transfers parser configuration and leaves aOther usable with defaults.
109 pJsonParser& operator=(pJsonParser&& aOther) noexcept;
110
111 /// Returns the immutable options used by every parse call.
112 const Options& options() const noexcept;
113 /// Returns the allocator used for DOM results.
114 pjson::Allocator& allocator() const noexcept;
115
116 /// Parses one string document by value; failure returns JSON null.
117 pjson parse(const std::string& aInput) const;
118 /// Parses one exact byte span by value; failure returns JSON null.
119 pjson parse(const char* aInput, size_t aSize) const;
120 /// Parses one string document and resets/reports aError.
121 pjson parse(const std::string& aInput, Error& aError) const;
122 /// Parses one exact byte span and resets/reports aError.
123 pjson parse(const char* aInput, size_t aSize, Error& aError) const;
124 /// Buffers and parses one stream document by value.
125 pjson parseStream(std::istream& aInput) const;
126 /// Buffers and parses one stream document and resets/reports aError.
127 pjson parseStream(std::istream& aInput, Error& aError) const;
128
129 /// Emits events for one string document.
130 bool parseSax(const std::string& aInput, SaxHandler& aHandler) const;
131 /// Emits events for one exact byte span.
132 bool parseSax(const char* aInput, size_t aSize, SaxHandler& aHandler) const;
133 /// Emits string-document events and resets/reports aError.
134 bool parseSax(const std::string& aInput, SaxHandler& aHandler, Error& aError) const;
135 /// Emits byte-span events and resets/reports aError.
136 bool parseSax(const char* aInput, size_t aSize, SaxHandler& aHandler, Error& aError) const;
137 /// Incrementally emits events from a stream.
138 bool parseSaxStream(std::istream& aInput, SaxHandler& aHandler) const;
139 /// Incrementally emits events from a stream and resets/reports aError.
140 bool parseSaxStream(std::istream& aInput, SaxHandler& aHandler, Error& aError) const;
141
142 private:
143 pJsonParserImpl* _impl;
144 };
145} // namespace ByteDance
146
147#endif // PRAVEENJSON_PARSER_H
Configured, reusable JSON parser for DOM and SAX input.
pJsonParser & operator=(const pJsonParser &aOther)
Copies parser configuration while borrowing aOther's allocator.
pJsonParser(const pJsonParser &aOther)
Copies the parser configuration while borrowing the same allocator.
pJsonParser(pjson::Allocator &aAllocator, const Options &aOptions=Options())
Uses borrowed aAllocator, which must outlive this parser and its DOM results.
pJsonParser(pJsonParser &&aOther) noexcept
Transfers parser configuration and leaves aOther usable with defaults.
const Options & options() const noexcept
Returns the immutable options used by every parse call.
pJsonParser & operator=(pJsonParser &&aOther) noexcept
Transfers parser configuration and leaves aOther usable with defaults.
~pJsonParser()
Releases the private parser configuration.
pJsonParser(const Options &aOptions=Options())
Uses the default DOM allocator and default parser options.
Owning, mutable JSON value with deep-copy semantics.
Definition pjson.h:68
Namespace containing the pjson public API.
Definition pjson.h:58
Structured result for DOM and SAX parsing.
size_t column
One-based byte column.
bool ok
True when the most recent parse succeeded.
std::string message
Human-readable diagnostic; wording is not stable. Constructs the successful start-of-input state.
size_t offset
Zero-based input byte offset.
size_t line
One-based source line.
Code code
Stable machine-facing result category.
Code
Stable categories for programmatic parse-failure handling.
@ Syntax
The input violates JSON grammar.
@ InputLimit
Input exceeded maxInputBytes.
@ CallbackError
A SAX callback cancelled or threw.
@ DepthLimit
Nesting exceeded the effective depth limit.
@ NodeLimit
Values processed exceeded maxNodes.
@ StreamError
Reading from the input stream failed.
@ InvalidEncoding
UTF-8 or an escaped Unicode value is invalid.
@ AllocationFailure
Parser, DOM, or callback allocation failed.
@ DuplicateKey
A repeated object name was rejected.
@ NumberRange
A number is outside the configured representation policy.
Bounds parsing work and selects duplicate-key and number policies.
NumberPolicy
Controls numeric tokens that cannot be represented exactly.
@ RejectUnrepresentableNumbers
Reject range overflow and nonzero underflow.
NumberPolicy numberPolicy
Unrepresentable-number policy. Selects strict defaults and bounded parser resources.
size_t maxNodes
Maximum values processed; zero is unlimited.
int maxDepth
Nesting limit; non-positive means one level.
size_t maxInputBytes
Maximum input bytes; zero is unlimited.
DuplicateKeyPolicy
Controls how repeated object member names are handled.
@ KeepFirstDuplicate
Retain the first value and discard later values.
@ RejectDuplicateKeys
Fail when a name occurs more than once.
DuplicateKeyPolicy duplicateKeys
Duplicate object-name policy.
Event sink for non-owning SAX parsing.
virtual bool onBool(bool aValue)
Receives a boolean; return false to cancel.
virtual bool onKey(const std::string &aKey)
Receives a borrowed decoded key; return false to cancel.
virtual bool onNull()
Receives null; return false to cancel.
virtual bool onUInt(uint64_t aValue)
Receives an unsigned integer above the signed range; return false to cancel.
virtual bool onEndArray()
Marks the end of an array; return false to cancel.
virtual ~SaxHandler()
Enables destruction through a handler base pointer.
virtual bool onStartArray()
Marks the beginning of an array; return false to cancel.
virtual bool onInt(int64_t aValue)
Receives a signed integer; return false to cancel.
virtual bool onStartObject()
Marks the beginning of an object; return false to cancel.
virtual bool onString(const std::string &aValue)
Receives a borrowed decoded string; return false to cancel.
virtual bool onEndObject()
Marks the end of an object; return false to cancel.
virtual bool onDouble(double aValue)
Receives a floating-point number; return false to cancel.
Runtime allocator for persistent DOM storage.
Definition pjson.h:101