diff --git a/.clang-format b/.clang-format new file mode 100644 index 0000000..f26a6a7 --- /dev/null +++ b/.clang-format @@ -0,0 +1,143 @@ +--- +# Language: Cpp +BasedOnStyle: WebKit +BreakBeforeBraces: WebKit +AccessModifierOffset: -4 +AlignAfterOpenBracket: DontAlign +AlignArrayOfStructures: Left +AlignConsecutiveAssignments: false +AlignConsecutiveBitFields: false +AlignConsecutiveDeclarations: false +AlignConsecutiveMacros: false +AlignEscapedNewlines: Right +AlignOperands: DontAlign +AlignTrailingComments: + Kind: Always + OverEmptyLines: 0 +AllowAllArgumentsOnNextLine: true +AllowAllParametersOfDeclarationOnNextLine: true +AllowShortBlocksOnASingleLine: Empty +AllowShortCaseLabelsOnASingleLine: false +AllowShortEnumsOnASingleLine: false +AllowShortFunctionsOnASingleLine: All +AllowShortIfStatementsOnASingleLine: AllIfsAndElse +AllowShortLambdasOnASingleLine: All +AllowShortLoopsOnASingleLine: true +AlwaysBreakAfterDefinitionReturnType: None +AlwaysBreakAfterReturnType: None +AlwaysBreakBeforeMultilineStrings: false +AlwaysBreakTemplateDeclarations: true +BinPackArguments: true +BinPackParameters: false +BitFieldColonSpacing: Both +BreakAfterAttributes: Never +BreakArrays: true +BreakBeforeBinaryOperators: All +BreakBeforeConceptDeclarations: Allowed +BreakBeforeInlineASMColon: OnlyMultiline +BreakBeforeTernaryOperators: true +BreakConstructorInitializers: BeforeColon +BreakInheritanceList: AfterComma +BreakStringLiterals: true +ColumnLimit: 110 +CommentPragmas: "" +CompactNamespaces: false +ConstructorInitializerIndentWidth: 4 +ContinuationIndentWidth: 4 +Cpp11BracedListStyle: true +DerivePointerAlignment: false +DisableFormat: false +EmptyLineAfterAccessModifier: Never +EmptyLineBeforeAccessModifier: LogicalBlock +ExperimentalAutoDetectBinPacking: false +FixNamespaceComments: true +IncludeBlocks: Preserve +IncludeIsMainRegex: "" +IncludeIsMainSourceRegex: "" +IndentAccessModifiers: false +IndentCaseBlocks: false +IndentCaseLabels: false +IndentExternBlock: NoIndent +IndentGotoLabels: false +IndentPPDirectives: AfterHash +IndentRequiresClause: true +IndentWidth: 4 +IndentWrappedFunctionNames: false +InsertBraces: false +InsertNewlineAtEOF: true +InsertTrailingCommas: None +IntegerLiteralSeparator: + Binary: 0 + BinaryMinDigits: 0 + Decimal: 0 + DecimalMinDigits: 0 + Hex: 0 + HexMinDigits: 0 +KeepEmptyLinesAtTheStartOfBlocks: true +LambdaBodyIndentation: Signature +LineEnding: DeriveLF +MacroBlockBegin: "" +MacroBlockEnd: "" +MaxEmptyLinesToKeep: 1 +NamespaceIndentation: Inner +PPIndentWidth: -1 +PackConstructorInitializers: CurrentLine +PenaltyBreakAssignment: 2 +PenaltyBreakBeforeFirstCallParameter: 19 +PenaltyBreakComment: 300 +PenaltyBreakFirstLessLess: 120 +PenaltyBreakOpenParenthesis: 0 +PenaltyBreakString: 1000 +PenaltyBreakTemplateDeclaration: 10 +PenaltyExcessCharacter: 1000000 +PenaltyIndentedWhitespace: 0 +PenaltyReturnTypeOnItsOwnLine: 60 +PointerAlignment: Left +QualifierAlignment: Leave +ReferenceAlignment: Pointer +ReflowComments: true +RemoveBracesLLVM: false +RemoveSemicolon: false +RequiresClausePosition: OwnLine +RequiresExpressionIndentation: OuterScope +SeparateDefinitionBlocks: Leave +ShortNamespaceLines: 1 +SortIncludes: CaseSensitive +SortUsingDeclarations: LexicographicNumeric +SpaceAfterCStyleCast: false +SpaceAfterLogicalNot: false +SpaceAfterTemplateKeyword: true +SpaceAroundPointerQualifiers: Default +SpaceBeforeAssignmentOperators: true +SpaceBeforeCaseColon: false +SpaceBeforeCpp11BracedList: false +SpaceBeforeCtorInitializerColon: true +SpaceBeforeInheritanceColon: true +SpaceBeforeParens: ControlStatements +SpaceBeforeParensOptions: + AfterControlStatements: true + AfterForeachMacros: true + AfterFunctionDeclarationName: false + AfterFunctionDefinitionName: false + AfterIfMacros: true + AfterOverloadedOperator: false + AfterRequiresInClause: false + AfterRequiresInExpression: false + BeforeNonEmptyParentheses: false +SpaceBeforeRangeBasedForLoopColon: true +SpaceBeforeSquareBrackets: false +SpaceInEmptyBlock: false +SpaceInEmptyParentheses: false +SpacesBeforeTrailingComments: 1 +SpacesInAngles: Never +SpacesInCStyleCastParentheses: false +SpacesInConditionalStatement: false +SpacesInContainerLiterals: true +SpacesInLineCommentPrefix: + Minimum: 1 + Maximum: -1 +SpacesInParentheses: false +SpacesInSquareBrackets: false +Standard: Latest +TabWidth: 8 +UseTab: Never diff --git a/bindings/cpp/include/kdlpp.h b/bindings/cpp/include/kdlpp.h index 29b795a..479ebd8 100644 --- a/bindings/cpp/include/kdlpp.h +++ b/bindings/cpp/include/kdlpp.h @@ -37,6 +37,7 @@ template concept _arithmetic = std::is_arithmetic_v; class TypeError : public std::exception { const char* m_msg; + public: TypeError() : m_msg{"kdlpp type error"} {} TypeError(const char* msg) : m_msg{msg} {} @@ -46,6 +47,7 @@ class TypeError : public std::exception { // Exception thrown on regular KDL parsing errors class KDLPP_EXPORT ParseError : public std::exception { std::string m_msg; + public: ParseError(kdl_str const& msg); ParseError(std::string msg) : m_msg{std::move(msg)} {} @@ -55,13 +57,13 @@ class KDLPP_EXPORT ParseError : public std::exception { // Exception thrown on KDL emitter errors (should never occur) class EmitterError : public std::exception { std::string m_msg; + public: EmitterError(std::string msg) : m_msg{std::move(msg)} {} EmitterError() : EmitterError{"The KDL emitter encountered an error"} {} const char* what() const noexcept { return m_msg.c_str(); } }; - // Ways in which a KDL number may be represented in C/C++ enum NumberRepresentation { Integer = 0, @@ -117,14 +119,16 @@ class KDLPP_EXPORT Number { explicit operator kdl_number() const; }; -template concept _into_number = requires (T t) { Number{t}; }; +template concept _into_number = requires(T t) { Number{t}; }; // Mixin class HasTypeAnnotation { std::optional m_type_annotation; + protected: HasTypeAnnotation() = default; HasTypeAnnotation(std::u8string_view t) : m_type_annotation{t} {} + public: const std::optional& type_annotation() const { return m_type_annotation; } @@ -133,10 +137,7 @@ class HasTypeAnnotation { m_type_annotation = std::u8string{type_annotation}; } - void remove_type_annotation() - { - m_type_annotation.reset(); - } + void remove_type_annotation() { m_type_annotation.reset(); } bool operator==(const HasTypeAnnotation&) const = default; bool operator!=(const HasTypeAnnotation&) const = default; @@ -165,11 +166,7 @@ class KDLPP_EXPORT Value : public HasTypeAnnotation { Value(Number n) : m_value{std::move(n)} {} Value(_into_number auto n) : m_value{Number{n}} {} - Value(std::u8string_view type_annotation, bool b) - : HasTypeAnnotation{type_annotation}, - m_value{b} - { - } + Value(std::u8string_view type_annotation, bool b) : HasTypeAnnotation{type_annotation}, m_value{b} {} Value(std::u8string_view type_annotation, std::u8string_view s) : HasTypeAnnotation{type_annotation}, m_value{std::u8string{s}} @@ -240,30 +237,30 @@ class KDLPP_EXPORT Value : public HasTypeAnnotation { void set_to_null() { m_value = std::monostate{}; } - Type type() const noexcept - { - return static_cast(m_value.index()); - } + Type type() const noexcept { return static_cast(m_value.index()); } // Return the content as a fundamental type, u8string, or u8string_view, // if this object contains the right type. template T as() const { - return std::visit([](auto const& v) -> T { - using V = std::decay_t; - if constexpr (std::is_same_v) { - return v; - } else if constexpr (std::is_same_v) { - return v; - } else if constexpr (std::is_arithmetic_v && std::is_same_v) { - return v.template as(); - } else if constexpr (std::is_same_v && std::is_same_v) { - return T{v}; - } else { - throw TypeError("incompatible types"); - } - }, m_value); + return std::visit( + [](auto const& v) -> T { + using V = std::decay_t; + if constexpr (std::is_same_v) { + return v; + } else if constexpr (std::is_same_v) { + return v; + } else if constexpr (std::is_arithmetic_v && std::is_same_v) { + return v.template as(); + } else if constexpr (std::is_same_v + && std::is_same_v) { + return T{v}; + } else { + throw TypeError("incompatible types"); + } + }, + m_value); } explicit operator kdl_value() const; @@ -288,9 +285,9 @@ class Node : public HasTypeAnnotation { { } Node(std::u8string_view name, - std::vector args, - std::map> properties, - std::vector children) + std::vector args, + std::map> properties, + std::vector children) : m_name{name}, m_args{std::move(args)}, m_properties{std::move(properties)}, @@ -298,10 +295,10 @@ class Node : public HasTypeAnnotation { { } Node(std::u8string_view type_annotation, - std::u8string_view name, - std::vector args, - std::map> properties, - std::vector children) + std::u8string_view name, + std::vector args, + std::map> properties, + std::vector children) : HasTypeAnnotation{type_annotation}, m_name{name}, m_args{std::move(args)}, @@ -329,7 +326,7 @@ class KDLPP_EXPORT Document { std::vector m_nodes; public: - static Document read_from(kdl_parser *parser); + static Document read_from(kdl_parser* parser); Document() = default; Document(Document const&) = default; diff --git a/bindings/cpp/src/kdlpp.cpp b/bindings/cpp/src/kdlpp.cpp index b2459f5..d8c4bf7 100644 --- a/bindings/cpp/src/kdlpp.cpp +++ b/bindings/cpp/src/kdlpp.cpp @@ -1,5 +1,5 @@ -#include #include +#include namespace kdl { @@ -17,8 +17,7 @@ namespace { std::variant kdl_number_to_variant(kdl_number const& n) { - switch (n.type) - { + switch (n.type) { case KDL_NUMBER_TYPE_INTEGER: return n.integer; case KDL_NUMBER_TYPE_FLOATING_POINT: @@ -32,8 +31,7 @@ namespace { std::variant kdl_value_to_variant(kdl_value const& val) { - switch (val.type) - { + switch (val.type) { case KDL_TYPE_NULL: return std::monostate{}; case KDL_TYPE_BOOLEAN: @@ -51,9 +49,9 @@ namespace { { for (const auto& node : nodes) { if (node.type_annotation().has_value()) { - if (!kdl_emit_node_with_type(emitter, - to_kdl_str(*node.type_annotation()), - to_kdl_str(node.name()))) throw EmitterError{}; + if (!kdl_emit_node_with_type( + emitter, to_kdl_str(*node.type_annotation()), to_kdl_str(node.name()))) + throw EmitterError{}; } else { if (!kdl_emit_node(emitter, to_kdl_str(node.name()))) throw EmitterError{}; } @@ -63,8 +61,7 @@ namespace { if (!kdl_emit_arg(emitter, &v)) throw EmitterError{}; } - for (const auto& [key, value] : node.properties()) - { + for (const auto& [key, value] : node.properties()) { auto v = (kdl_value)value; if (!kdl_emit_property(emitter, to_kdl_str(key), &v)) throw EmitterError{}; } @@ -79,20 +76,15 @@ namespace { } // namespace -ParseError::ParseError(kdl_str const& msg) - : m_msg{msg.data, msg.len} -{ -} +ParseError::ParseError(kdl_str const& msg) : m_msg{msg.data, msg.len} {} -Number::Number(kdl_number const& n) - : m_value{kdl_number_to_variant(n)} -{ -} +Number::Number(kdl_number const& n) : m_value{kdl_number_to_variant(n)} {} Number::operator kdl_number() const { kdl_number result; - std::visit([&result](const auto& n) { + std::visit( + [&result](const auto& n) { using T = std::decay_t; if constexpr (std::is_same_v) { result.type = KDL_NUMBER_TYPE_INTEGER; @@ -106,12 +98,12 @@ Number::operator kdl_number() const } else { throw std::logic_error("incomplete visit"); } - }, m_value); + }, + m_value); return result; } -Value::Value(kdl_value const& val) - : m_value(kdl_value_to_variant(val)) +Value::Value(kdl_value const& val) : m_value(kdl_value_to_variant(val)) { if (val.type_annotation.data != nullptr) { set_type_annotation(to_u8string_view(val.type_annotation)); @@ -135,7 +127,8 @@ Value Value::from_string(std::u8string_view s) Value::operator kdl_value() const { kdl_value result; - std::visit([&result](const auto& v) { + std::visit( + [&result](const auto& v) { using T = std::decay_t; if constexpr (std::is_same_v) { result.type = KDL_TYPE_BOOLEAN; @@ -149,16 +142,17 @@ Value::operator kdl_value() const } else { result.type = KDL_TYPE_NULL; } - }, m_value); + }, + m_value); if (type_annotation().has_value()) { result.type_annotation = to_kdl_str(*type_annotation()); } else { - result.type_annotation = { nullptr, 0 }; + result.type_annotation = {nullptr, 0}; } return result; } -Document Document::read_from(kdl_parser *parser) +Document Document::read_from(kdl_parser* parser) { Document doc; auto* node_list = &doc.nodes(); @@ -199,8 +193,7 @@ Document Document::read_from(kdl_parser *parser) current_node->args().emplace_back(Value{ev->value}); break; case KDL_EVENT_PROPERTY: - current_node->properties()[std::u8string{to_u8string_view(ev->name)}] - = Value{ev->value}; + current_node->properties()[std::u8string{to_u8string_view(ev->name)}] = Value{ev->value}; break; default: throw std::logic_error("Invalid event from kdl_parser"); @@ -220,16 +213,12 @@ std::u8string Document::to_string() const Document parse(std::u8string_view kdl_text) { - kdl_str text = { - reinterpret_cast(kdl_text.data()), - kdl_text.size() - }; - kdl_parser *parser = kdl_create_string_parser(text, KDL_DEFAULTS); + kdl_str text = {reinterpret_cast(kdl_text.data()), kdl_text.size()}; + kdl_parser* parser = kdl_create_string_parser(text, KDL_DEFAULTS); if (parser == nullptr) throw std::runtime_error("Error initializing the KDL parser"); auto doc = Document::read_from(parser); kdl_destroy_parser(parser); return doc; } - } // namespace kdl diff --git a/bindings/cpp/tests/kdlpp_test.cpp b/bindings/cpp/tests/kdlpp_test.cpp index 29e5bae..9937d6c 100644 --- a/bindings/cpp/tests/kdlpp_test.cpp +++ b/bindings/cpp/tests/kdlpp_test.cpp @@ -2,8 +2,8 @@ #include "test_util.h" -#include #include +#include static void test_cycle() { @@ -19,12 +19,14 @@ static void test_cycle() static void test_constructing() { + // clang-format off auto doc = kdl::Document{ kdl::Node{u8"foo", {u8"bar", 123}, {}, {}}, kdl::Node{u8"test", u8"baz", {}, {{u8"prop", 1.5}}, { kdl::Node{u8"child node"} }} }; + // clang-format on auto expected = u8"foo \"bar\" 123\n" u8"(test)baz prop=1.5 {\n" u8" \"child node\"\n" @@ -71,6 +73,7 @@ static void test_reading_demo() static void test_writing_demo() { + // clang-format off // begin kdlpp writing demo auto doc = kdl::Document{ kdl::Node{u8"node1", {u8"argument 1", 2, {}}, @@ -97,6 +100,7 @@ static void test_writing_demo() ASSERT(doc.to_string() == expected); // end kdlpp writing demo + // clang-format off } void TEST_MAIN() diff --git a/include/kdl/common.h b/include/kdl/common.h index 9d2ffa9..50d8402 100644 --- a/include/kdl/common.h +++ b/include/kdl/common.h @@ -1,8 +1,8 @@ #ifndef KDL_COMMON_H_ #define KDL_COMMON_H_ -#include #include "common-macros.h" +#include #ifdef __cplusplus extern "C" { @@ -10,19 +10,19 @@ extern "C" { // Parameter for kdl_escape - which characters should be escaped, and which should not? enum kdl_escape_mode { - KDL_ESCAPE_MINIMAL = 0, // Only escape what *must* be escaped - KDL_ESCAPE_CONTROL = 0x10, // Escape ASCII control characters - KDL_ESCAPE_NEWLINE = 0x20, // Escape newline characters - KDL_ESCAPE_TAB = 0x40, // Escape tabs - KDL_ESCAPE_ASCII_MODE =0x170, // Escape all non-ASCII charscters + KDL_ESCAPE_MINIMAL = 0, // Only escape what *must* be escaped + KDL_ESCAPE_CONTROL = 0x10, // Escape ASCII control characters + KDL_ESCAPE_NEWLINE = 0x20, // Escape newline characters + KDL_ESCAPE_TAB = 0x40, // Escape tabs + KDL_ESCAPE_ASCII_MODE = 0x170, // Escape all non-ASCII charscters // "Sensible" default: escape tabs, newlines, and other control characters, but leave // unicode intact KDL_ESCAPE_DEFAULT = KDL_ESCAPE_CONTROL | KDL_ESCAPE_NEWLINE | KDL_ESCAPE_TAB }; // Function pointers used to interface with external IO -typedef size_t (*kdl_read_func)(void *user_data, char *buf, size_t bufsize); -typedef size_t (*kdl_write_func)(void *user_data, char const *data, size_t nbytes); +typedef size_t (*kdl_read_func)(void* user_data, char* buf, size_t bufsize); +typedef size_t (*kdl_write_func)(void* user_data, char const* data, size_t nbytes); typedef struct kdl_str kdl_str; typedef struct kdl_owned_string kdl_owned_string; @@ -31,35 +31,35 @@ typedef enum kdl_escape_mode kdl_escape_mode; // A reference to a string, like Rust's str or C++'s std::u8string_view // Need not be nul-terminated! struct kdl_str { - char const *data; // Data pointer - NULL means no string + char const* data; // Data pointer - NULL means no string size_t len; // Length of the string - 0 means empty string }; // An owned string. Should be destroyed using kdl_free_string // Owned strings are nul-terminated. struct kdl_owned_string { - char *data; + char* data; size_t len; }; // Get a reference to an owned string -KDL_EXPORT_INLINE kdl_str kdl_borrow_str(kdl_owned_string const *str) +KDL_EXPORT_INLINE kdl_str kdl_borrow_str(kdl_owned_string const* str) { - kdl_str result = { str->data, str->len }; + kdl_str result = {str->data, str->len}; return result; } // Create a kdl_str from a nul-terminated C string -KDL_EXPORT kdl_str kdl_str_from_cstr(char const *s); +KDL_EXPORT kdl_str kdl_str_from_cstr(char const* s); // Create an owned string with the same content as another string -KDL_NODISCARD KDL_EXPORT kdl_owned_string kdl_clone_str(kdl_str const *s); +KDL_NODISCARD KDL_EXPORT kdl_owned_string kdl_clone_str(kdl_str const* s); // Free the memory associated with an owned string, and set the pointer to NULL -KDL_EXPORT void kdl_free_string(kdl_owned_string *s); +KDL_EXPORT void kdl_free_string(kdl_owned_string* s); // Escape special characters in a string according to KDL string rules -KDL_NODISCARD KDL_EXPORT kdl_owned_string kdl_escape(kdl_str const *s, kdl_escape_mode mode); +KDL_NODISCARD KDL_EXPORT kdl_owned_string kdl_escape(kdl_str const* s, kdl_escape_mode mode); // Resolve backslash escape sequences -KDL_NODISCARD KDL_EXPORT kdl_owned_string kdl_unescape(kdl_str const *s); +KDL_NODISCARD KDL_EXPORT kdl_owned_string kdl_unescape(kdl_str const* s); #ifdef __cplusplus } diff --git a/include/kdl/emitter.h b/include/kdl/emitter.h index 1f4223e..04e0e4c 100644 --- a/include/kdl/emitter.h +++ b/include/kdl/emitter.h @@ -32,40 +32,41 @@ struct kdl_float_printing_options { // Formatting options for a kdl_emitter struct kdl_emitter_options { - int indent; // Number of spaces to indent child nodes by - kdl_escape_mode escape_mode; // How to escape strings + int indent; // Number of spaces to indent child nodes by + kdl_escape_mode escape_mode; // How to escape strings kdl_identifier_emission_mode identifier_mode; // How to quote identifiers - kdl_float_printing_options float_mode; // How to print floating point numbers + kdl_float_printing_options float_mode; // How to print floating point numbers }; KDL_EXPORT extern const kdl_emitter_options KDL_DEFAULT_EMITTER_OPTIONS; // Create an emitter than writes into an internal buffer -KDL_NODISCARD KDL_EXPORT kdl_emitter *kdl_create_buffering_emitter(kdl_emitter_options const *opt); +KDL_NODISCARD KDL_EXPORT kdl_emitter* kdl_create_buffering_emitter(kdl_emitter_options const* opt); // Create an emitter that writes by calling a user-supplied function -KDL_NODISCARD KDL_EXPORT kdl_emitter *kdl_create_stream_emitter(kdl_write_func write_func, void *user_data, kdl_emitter_options const *opt); +KDL_NODISCARD KDL_EXPORT kdl_emitter* kdl_create_stream_emitter( + kdl_write_func write_func, void* user_data, kdl_emitter_options const* opt); // Destroy an emitter -KDL_EXPORT void kdl_destroy_emitter(kdl_emitter *emitter); +KDL_EXPORT void kdl_destroy_emitter(kdl_emitter* emitter); // Write a node tag -KDL_EXPORT bool kdl_emit_node(kdl_emitter *emitter, kdl_str name); +KDL_EXPORT bool kdl_emit_node(kdl_emitter* emitter, kdl_str name); // Write a node tag including a type annotation -KDL_EXPORT bool kdl_emit_node_with_type(kdl_emitter *emitter, kdl_str type, kdl_str name); +KDL_EXPORT bool kdl_emit_node_with_type(kdl_emitter* emitter, kdl_str type, kdl_str name); // Write an argument for a node -KDL_EXPORT bool kdl_emit_arg(kdl_emitter *emitter, kdl_value const *value); +KDL_EXPORT bool kdl_emit_arg(kdl_emitter* emitter, kdl_value const* value); // Write a property for a node -KDL_EXPORT bool kdl_emit_property(kdl_emitter *emitter, kdl_str name, kdl_value const *value); +KDL_EXPORT bool kdl_emit_property(kdl_emitter* emitter, kdl_str name, kdl_value const* value); // Start a list of children for the previous node ('{') -KDL_EXPORT bool kdl_start_emitting_children(kdl_emitter *emitter); +KDL_EXPORT bool kdl_start_emitting_children(kdl_emitter* emitter); // End the list of children ('}') -KDL_EXPORT bool kdl_finish_emitting_children(kdl_emitter *emitter); +KDL_EXPORT bool kdl_finish_emitting_children(kdl_emitter* emitter); // Finish - write a final newline if required -KDL_EXPORT bool kdl_emit_end(kdl_emitter *emitter); +KDL_EXPORT bool kdl_emit_end(kdl_emitter* emitter); // Get a reference to the current emitter buffer // This string is invalidated on any call to kdl_emit_* -KDL_EXPORT kdl_str kdl_get_emitter_buffer(kdl_emitter *emitter); +KDL_EXPORT kdl_str kdl_get_emitter_buffer(kdl_emitter* emitter); #ifdef __cplusplus } diff --git a/include/kdl/kdl.h b/include/kdl/kdl.h index 490367d..992f1c2 100644 --- a/include/kdl/kdl.h +++ b/include/kdl/kdl.h @@ -2,8 +2,8 @@ #define KDL_H_ #include "common.h" +#include "emitter.h" #include "parser.h" #include "tokenizer.h" -#include "emitter.h" #endif // KDL_H_ diff --git a/include/kdl/parser.h b/include/kdl/parser.h index 3135c68..8e30778 100644 --- a/include/kdl/parser.h +++ b/include/kdl/parser.h @@ -25,8 +25,8 @@ enum kdl_event { // Parser configuration enum kdl_parse_option { - KDL_DEFAULTS = 0, // Nothing special - KDL_EMIT_COMMENTS = 1 // Emit comments (default: don't) + KDL_DEFAULTS = 0, // Nothing special + KDL_EMIT_COMMENTS = 1 // Emit comments (default: don't) }; typedef enum kdl_event kdl_event; @@ -42,16 +42,17 @@ struct kdl_event_data { }; // Create a parser that reads from a string -KDL_NODISCARD KDL_EXPORT kdl_parser *kdl_create_string_parser(kdl_str doc, kdl_parse_option opt); +KDL_NODISCARD KDL_EXPORT kdl_parser* kdl_create_string_parser(kdl_str doc, kdl_parse_option opt); // Create a parser that reads data by calling a user-supplied function -KDL_NODISCARD KDL_EXPORT kdl_parser *kdl_create_stream_parser(kdl_read_func read_func, void *user_data, kdl_parse_option opt); +KDL_NODISCARD KDL_EXPORT kdl_parser* kdl_create_stream_parser( + kdl_read_func read_func, void* user_data, kdl_parse_option opt); // Destroy a parser -KDL_EXPORT void kdl_destroy_parser(kdl_parser *parser); +KDL_EXPORT void kdl_destroy_parser(kdl_parser* parser); // Get the next parse event // Returns a pointer to an event structure. The structure (including all strings it contains!) is // invalidated on the next call. -KDL_EXPORT kdl_event_data *kdl_parser_next_event(kdl_parser *parser); +KDL_EXPORT kdl_event_data* kdl_parser_next_event(kdl_parser* parser); #ifdef __cplusplus } diff --git a/include/kdl/tokenizer.h b/include/kdl/tokenizer.h index 4eb9d60..bc300f1 100644 --- a/include/kdl/tokenizer.h +++ b/include/kdl/tokenizer.h @@ -9,9 +9,9 @@ extern "C" { // Return code for the tokenizer enum kdl_tokenizer_status { - KDL_TOKENIZER_OK, // ok: token returned - KDL_TOKENIZER_EOF, // regular end of file - KDL_TOKENIZER_ERROR // error + KDL_TOKENIZER_OK, // ok: token returned + KDL_TOKENIZER_EOF, // regular end of file + KDL_TOKENIZER_ERROR // error }; // Type of token @@ -45,14 +45,14 @@ struct kdl_token { }; // Create a tokenizer that reads from a string -KDL_NODISCARD KDL_EXPORT kdl_tokenizer *kdl_create_string_tokenizer(kdl_str doc); +KDL_NODISCARD KDL_EXPORT kdl_tokenizer* kdl_create_string_tokenizer(kdl_str doc); // Create a tokenizer that reads data by calling a user-supplied function -KDL_NODISCARD KDL_EXPORT kdl_tokenizer *kdl_create_stream_tokenizer(kdl_read_func read_func, void *user_data); +KDL_NODISCARD KDL_EXPORT kdl_tokenizer* kdl_create_stream_tokenizer(kdl_read_func read_func, void* user_data); // Destroy a tokenizer -KDL_EXPORT void kdl_destroy_tokenizer(kdl_tokenizer *tokenizer); +KDL_EXPORT void kdl_destroy_tokenizer(kdl_tokenizer* tokenizer); // Get the next token and write it to a user-supplied structure (or return an error) -KDL_EXPORT kdl_tokenizer_status kdl_pop_token(kdl_tokenizer *tokenizer, kdl_token *dest); +KDL_EXPORT kdl_tokenizer_status kdl_pop_token(kdl_tokenizer* tokenizer, kdl_token* dest); #ifdef __cplusplus } // extern "C" diff --git a/src/bigint.c b/src/bigint.c index 6503fd1..266f9bc 100644 --- a/src/bigint.c +++ b/src/bigint.c @@ -8,31 +8,28 @@ #define DIGIT_BITMASK ((uint64_t)0xFFFFFFFFUL) #define HIGH_DIGIT_BITMASK (DIGIT_BITMASK << DIGIT_BITS) -_kdl_ubigint *_kdl_ubigint_new(uint32_t initial_value) +_kdl_ubigint* _kdl_ubigint_new(uint32_t initial_value) { - _kdl_ubigint *i = malloc(sizeof(_kdl_ubigint) + sizeof(uint32_t)); + _kdl_ubigint* i = malloc(sizeof(_kdl_ubigint) + sizeof(uint32_t)); if (i == NULL) return NULL; i->n_digits = 1; i->num[0] = initial_value; return i; } -_kdl_ubigint *_kdl_ubigint_dup(_kdl_ubigint const *value) +_kdl_ubigint* _kdl_ubigint_dup(_kdl_ubigint const* value) { size_t size = sizeof(_kdl_ubigint) + value->n_digits * sizeof(uint32_t); - _kdl_ubigint *i = malloc(size); + _kdl_ubigint* i = malloc(size); if (i == NULL) return NULL; memcpy(i, value, size); return i; } -void _kdl_ubigint_free(_kdl_ubigint *i) -{ - free(i); -} +void _kdl_ubigint_free(_kdl_ubigint* i) { free(i); } // a += b -_kdl_ubigint *_kdl_ubigint_add_inplace(_kdl_ubigint *a, unsigned int b) +_kdl_ubigint* _kdl_ubigint_add_inplace(_kdl_ubigint* a, unsigned int b) { uint64_t carry = b; for (size_t i = 0; i < a->n_digits; ++i) { @@ -42,17 +39,16 @@ _kdl_ubigint *_kdl_ubigint_add_inplace(_kdl_ubigint *a, unsigned int b) } if (carry != 0) { // overflow - a = reallocf(a, - sizeof(_kdl_ubigint) + (++a->n_digits) * sizeof(uint32_t)); + a = reallocf(a, sizeof(_kdl_ubigint) + (++a->n_digits) * sizeof(uint32_t)); if (a != NULL) { a->num[a->n_digits - 1] = (uint32_t)(carry & DIGIT_BITMASK); } } - return a; + return a; } // a *= b -_kdl_ubigint *_kdl_ubigint_multiply_inplace(_kdl_ubigint *a, unsigned int b) +_kdl_ubigint* _kdl_ubigint_multiply_inplace(_kdl_ubigint* a, unsigned int b) { uint32_t carry = 0; for (size_t i = 0; i < a->n_digits; ++i) { @@ -64,8 +60,7 @@ _kdl_ubigint *_kdl_ubigint_multiply_inplace(_kdl_ubigint *a, unsigned int b) } if (carry != 0) { // overflow - a = reallocf(a, - sizeof(_kdl_ubigint) + (++a->n_digits) * sizeof(uint32_t)); + a = reallocf(a, sizeof(_kdl_ubigint) + (++a->n_digits) * sizeof(uint32_t)); if (a != NULL) { a->num[a->n_digits - 1] = carry; } @@ -73,7 +68,7 @@ _kdl_ubigint *_kdl_ubigint_multiply_inplace(_kdl_ubigint *a, unsigned int b) return a; } -uint32_t _kdl_ubigint_divide_inplace(_kdl_ubigint *a, uint32_t b) +uint32_t _kdl_ubigint_divide_inplace(_kdl_ubigint* a, uint32_t b) { uint64_t rem = 0; for (int i = (int)a->n_digits - 1; i >= 0; --i) { @@ -86,7 +81,7 @@ uint32_t _kdl_ubigint_divide_inplace(_kdl_ubigint *a, uint32_t b) return (uint32_t)rem; } -bool _kdl_ubigint_as_long_long(_kdl_ubigint *i, long long *dest) +bool _kdl_ubigint_as_long_long(_kdl_ubigint* i, long long* dest) { // does it fit? size_t digits_per_long_long = sizeof(long long) / sizeof(uint32_t); @@ -104,20 +99,17 @@ bool _kdl_ubigint_as_long_long(_kdl_ubigint *i, long long *dest) return true; } -kdl_owned_string _kdl_ubigint_as_string(_kdl_ubigint *i) -{ - return _kdl_ubigint_as_string_sgn(+1, i); -} +kdl_owned_string _kdl_ubigint_as_string(_kdl_ubigint* i) { return _kdl_ubigint_as_string_sgn(+1, i); } -kdl_owned_string _kdl_ubigint_as_string_sgn(int sign, _kdl_ubigint *i) +kdl_owned_string _kdl_ubigint_as_string_sgn(int sign, _kdl_ubigint* i) { i = _kdl_ubigint_dup(i); if (i == NULL) goto error; size_t max_digits = i->n_digits * 10; // max 10 decimal digits per 32 bits - char *buf = malloc(max_digits); + char* buf = malloc(max_digits); if (buf == NULL) goto error; - char *p = buf; + char* p = buf; // write the number backwards while (i->n_digits > 1 || i->num[0] != 0) { uint32_t digit = _kdl_ubigint_divide_inplace(i, 10); @@ -127,15 +119,15 @@ kdl_owned_string _kdl_ubigint_as_string_sgn(int sign, _kdl_ubigint *i) // flip the number and add the sign size_t len = p - buf; if (sign < 0) ++len; - char *buf2 = malloc(len + 1); + char* buf2 = malloc(len + 1); if (buf2 == NULL) goto error; - char *p2 = buf2; + char* p2 = buf2; if (sign < 0) *(p2++) = '-'; while (p > buf) *(p2++) = *(--p); *p2 = '\0'; free(buf); - return (kdl_owned_string){ buf2, len }; + return (kdl_owned_string){buf2, len}; error: - return (kdl_owned_string){ NULL, 0 }; + return (kdl_owned_string){NULL, 0}; } diff --git a/src/bigint.h b/src/bigint.h index 0471dc7..db73ac9 100644 --- a/src/bigint.h +++ b/src/bigint.h @@ -17,25 +17,25 @@ struct _kdl_ubigint { typedef struct _kdl_ubigint _kdl_ubigint; // Create a new big int object -_kdl_ubigint *_kdl_ubigint_new(uint32_t initial_value); +_kdl_ubigint* _kdl_ubigint_new(uint32_t initial_value); // Copy a big int -_kdl_ubigint *_kdl_ubigint_dup(_kdl_ubigint const *value); +_kdl_ubigint* _kdl_ubigint_dup(_kdl_ubigint const* value); // Destroy a big int -void _kdl_ubigint_free(_kdl_ubigint *i); +void _kdl_ubigint_free(_kdl_ubigint* i); // a += b -_kdl_ubigint *_kdl_ubigint_add_inplace(_kdl_ubigint *a, uint32_t b); +_kdl_ubigint* _kdl_ubigint_add_inplace(_kdl_ubigint* a, uint32_t b); // a *= b -_kdl_ubigint *_kdl_ubigint_multiply_inplace(_kdl_ubigint *a, uint32_t b); +_kdl_ubigint* _kdl_ubigint_multiply_inplace(_kdl_ubigint* a, uint32_t b); // a /= b (returns: remainder) -uint32_t _kdl_ubigint_divide_inplace(_kdl_ubigint *a, uint32_t b); +uint32_t _kdl_ubigint_divide_inplace(_kdl_ubigint* a, uint32_t b); // Convert to long long, if possible (return true on success) -bool _kdl_ubigint_as_long_long(_kdl_ubigint *i, long long *dest); +bool _kdl_ubigint_as_long_long(_kdl_ubigint* i, long long* dest); // Format decimal representation as string -kdl_owned_string _kdl_ubigint_as_string(_kdl_ubigint *i); +kdl_owned_string _kdl_ubigint_as_string(_kdl_ubigint* i); // Format decimal representation, starting with a sign // sign: -1 or +1 -kdl_owned_string _kdl_ubigint_as_string_sgn(int sign, _kdl_ubigint *i); +kdl_owned_string _kdl_ubigint_as_string_sgn(int sign, _kdl_ubigint* i); #endif // KDL_INTERNAL_BIGINT_H_ diff --git a/src/compat.c b/src/compat.c index d8af4b1..4a64291 100644 --- a/src/compat.c +++ b/src/compat.c @@ -3,9 +3,9 @@ #include #if !defined(HAVE_REALLOCF) -void *reallocf(void *ptr, size_t size) +void* reallocf(void* ptr, size_t size) { - void *new_ptr = realloc(ptr, size); + void* new_ptr = realloc(ptr, size); if (new_ptr == NULL) { free(ptr); } diff --git a/src/compat.h b/src/compat.h index b700537..794f8df 100644 --- a/src/compat.h +++ b/src/compat.h @@ -2,16 +2,16 @@ #define KDL_INTERNAL_COMPAT_H_ #if defined(__cplusplus) -#define _fallthrough_ [[fallthrough]] +# define _fallthrough_ [[fallthrough]] #elif defined(__GNUC__) && __GNUC__ >= 7 -#define _fallthrough_ __attribute__((fallthrough)) +# define _fallthrough_ __attribute__((fallthrough)) #else -#define _fallthrough_ +# define _fallthrough_ #endif #if !defined(HAVE_REALLOCF) -#include -void *reallocf(void *ptr, size_t size); +# include +void* reallocf(void* ptr, size_t size); #endif #endif // KDL_INTERNAL_COMPAT_H_ diff --git a/src/emitter.c b/src/emitter.c index d9c40de..7c53a66 100644 --- a/src/emitter.c +++ b/src/emitter.c @@ -1,7 +1,7 @@ #include "kdl/emitter.h" -#include "str.h" #include "grammar.h" +#include "str.h" #include "utf8.h" #include @@ -13,38 +13,33 @@ const kdl_emitter_options KDL_DEFAULT_EMITTER_OPTIONS = { .indent = 4, .escape_mode = KDL_ESCAPE_DEFAULT, .identifier_mode = KDL_PREFER_BARE_IDENTIFIERS, - .float_mode = { - .always_write_decimal_point = false, - .always_write_decimal_point_or_exponent = true, - .capital_e = false, - .exponent_plus = false, - .plus = false, - .min_exponent = 4 - } + .float_mode = {.always_write_decimal_point = false, + .always_write_decimal_point_or_exponent = true, + .capital_e = false, + .exponent_plus = false, + .plus = false, + .min_exponent = 4} }; -struct _kdl_emitter -{ +struct _kdl_emitter { kdl_emitter_options opt; kdl_write_func write_func; - void *write_user_data; + void* write_user_data; int depth; bool start_of_line; _kdl_write_buffer buf; }; -static size_t _buffer_write_func(void *user_data, char const *data, size_t nbytes) +static size_t _buffer_write_func(void* user_data, char const* data, size_t nbytes) { - _kdl_write_buffer *buf = (_kdl_write_buffer*)user_data; - if (_kdl_buf_push_chars(buf, data, nbytes)) - return nbytes; - else - return 0; + _kdl_write_buffer* buf = (_kdl_write_buffer*)user_data; + if (_kdl_buf_push_chars(buf, data, nbytes)) return nbytes; + else return 0; } -kdl_emitter *kdl_create_buffering_emitter(kdl_emitter_options const *opt) +kdl_emitter* kdl_create_buffering_emitter(kdl_emitter_options const* opt) { - kdl_emitter *self = malloc(sizeof(kdl_emitter)); + kdl_emitter* self = malloc(sizeof(kdl_emitter)); if (self == NULL) return NULL; self->opt = *opt; self->write_func = &_buffer_write_func; @@ -59,20 +54,21 @@ kdl_emitter *kdl_create_buffering_emitter(kdl_emitter_options const *opt) return self; } -kdl_emitter *kdl_create_stream_emitter(kdl_write_func write_func, void *user_data, kdl_emitter_options const *opt) +kdl_emitter* kdl_create_stream_emitter( + kdl_write_func write_func, void* user_data, kdl_emitter_options const* opt) { - kdl_emitter *self = malloc(sizeof(kdl_emitter)); + kdl_emitter* self = malloc(sizeof(kdl_emitter)); if (self == NULL) return NULL; self->opt = *opt; self->write_func = write_func; self->write_user_data = user_data; self->depth = 0; self->start_of_line = true; - self->buf = (_kdl_write_buffer){ NULL, 0, 0 }; + self->buf = (_kdl_write_buffer){NULL, 0, 0}; return self; } -void kdl_destroy_emitter(kdl_emitter *self) +void kdl_destroy_emitter(kdl_emitter* self) { (void)kdl_emit_end(self); if (self->buf.buf != NULL) { @@ -81,7 +77,7 @@ void kdl_destroy_emitter(kdl_emitter *self) free(self); } -static bool _emit_str(kdl_emitter *self, kdl_str s) +static bool _emit_str(kdl_emitter* self, kdl_str s) { kdl_owned_string escaped = kdl_escape(&s, self->opt.escape_mode); bool ok = self->write_func(self->write_user_data, "\"", 1) == 1 @@ -91,7 +87,7 @@ static bool _emit_str(kdl_emitter *self, kdl_str s) return ok; } -static kdl_owned_string _float_to_string(double f, kdl_float_printing_options const *opts) +static kdl_owned_string _float_to_string(double f, kdl_float_printing_options const* opts) { bool negative = f < 0.0; f = fabs(f); @@ -206,7 +202,7 @@ static kdl_owned_string _float_to_string(double f, kdl_float_printing_options co return _kdl_buf_to_string(&buf); } -static bool _emit_number(kdl_emitter *self, kdl_number const *n) +static bool _emit_number(kdl_emitter* self, kdl_number const* n) { char int_buf[32]; int int_len = 0; @@ -223,13 +219,12 @@ static bool _emit_number(kdl_emitter *self, kdl_number const *n) kdl_free_string(&float_str); return ok; case KDL_NUMBER_TYPE_STRING_ENCODED: - return self->write_func(self->write_user_data, n->string.data, n->string.len) - == n->string.len; + return self->write_func(self->write_user_data, n->string.data, n->string.len) == n->string.len; } return false; } -static bool _emit_identifier(kdl_emitter *self, kdl_str name) +static bool _emit_identifier(kdl_emitter* self, kdl_str name) { bool bare = true; if (self->opt.identifier_mode == KDL_QUOTE_ALL_IDENTIFIERS) { @@ -241,8 +236,7 @@ static bool _emit_identifier(kdl_emitter *self, kdl_str name) kdl_str tail = name; bool first = true; while (KDL_UTF8_OK == _kdl_pop_codepoint(&tail, &c)) { - if ((first && !_kdl_is_id_start(c)) - || !_kdl_is_id(c) + if ((first && !_kdl_is_id_start(c)) || !_kdl_is_id(c) || (self->opt.identifier_mode == KDL_ASCII_IDENTIFIERS && c >= 0x7f)) { bare = false; break; @@ -258,15 +252,15 @@ static bool _emit_identifier(kdl_emitter *self, kdl_str name) } } -#define _write_string_literal_ok(self, s) (self->write_func(self->write_user_data, ("" s ""), sizeof(s)-1) == sizeof(s)-1) +#define _write_string_literal_ok(self, s) \ + (self->write_func(self->write_user_data, ("" s ""), sizeof(s) - 1) == sizeof(s) - 1) -static bool _emit_value(kdl_emitter *self, kdl_value const* v) +static bool _emit_value(kdl_emitter* self, kdl_value const* v) { - if (v->type_annotation.data != NULL) - { - if (!(_write_string_literal_ok(self, "(") - && _emit_identifier(self, v->type_annotation) - && _write_string_literal_ok(self, ")"))) + if (v->type_annotation.data != NULL) { + if (!(_write_string_literal_ok(self, "(") // + && _emit_identifier(self, v->type_annotation) // + && _write_string_literal_ok(self, ")"))) return false; } switch (v->type) { @@ -286,7 +280,7 @@ static bool _emit_value(kdl_emitter *self, kdl_value const* v) return false; } -static bool _emit_node_preamble(kdl_emitter *self) +static bool _emit_node_preamble(kdl_emitter* self) { if (!self->start_of_line) { if (!_write_string_literal_ok(self, "\n")) return false; @@ -302,42 +296,41 @@ static bool _emit_node_preamble(kdl_emitter *self) return true; } -bool kdl_emit_node(kdl_emitter *self, kdl_str name) +bool kdl_emit_node(kdl_emitter* self, kdl_str name) { return _emit_node_preamble(self) && _emit_identifier(self, name); } -bool kdl_emit_node_with_type(kdl_emitter *self, kdl_str type, kdl_str name) +bool kdl_emit_node_with_type(kdl_emitter* self, kdl_str type, kdl_str name) { - return _emit_node_preamble(self) - && _write_string_literal_ok(self, "(") - && _emit_identifier(self, type) - && _write_string_literal_ok(self, ")") + return _emit_node_preamble(self) // + && _write_string_literal_ok(self, "(") // + && _emit_identifier(self, type) // + && _write_string_literal_ok(self, ")") // && _emit_identifier(self, name); } -bool kdl_emit_arg(kdl_emitter *self, kdl_value const *value) +bool kdl_emit_arg(kdl_emitter* self, kdl_value const* value) { - return _write_string_literal_ok(self, " ") - && _emit_value(self, value); + return _write_string_literal_ok(self, " ") && _emit_value(self, value); } -bool kdl_emit_property(kdl_emitter *self, kdl_str name, kdl_value const *value) +bool kdl_emit_property(kdl_emitter* self, kdl_str name, kdl_value const* value) { - return (_write_string_literal_ok(self, " ")) - && _emit_identifier(self, name) - && _write_string_literal_ok(self, "=") + return (_write_string_literal_ok(self, " ")) // + && _emit_identifier(self, name) // + && _write_string_literal_ok(self, "=") // && _emit_value(self, value); } -bool kdl_start_emitting_children(kdl_emitter *self) +bool kdl_start_emitting_children(kdl_emitter* self) { self->start_of_line = true; ++self->depth; return (_write_string_literal_ok(self, " {\n")); } -bool kdl_finish_emitting_children(kdl_emitter *self) +bool kdl_finish_emitting_children(kdl_emitter* self) { if (self->depth == 0) return false; --self->depth; @@ -346,7 +339,7 @@ bool kdl_finish_emitting_children(kdl_emitter *self) return (_write_string_literal_ok(self, "}\n")); } -bool kdl_emit_end(kdl_emitter *self) +bool kdl_emit_end(kdl_emitter* self) { while (self->depth != 0) { if (!kdl_finish_emitting_children(self)) return false; @@ -358,7 +351,4 @@ bool kdl_emit_end(kdl_emitter *self) return true; } -kdl_str kdl_get_emitter_buffer(kdl_emitter *self) -{ - return (kdl_str){ self->buf.buf, self->buf.str_len }; -} +kdl_str kdl_get_emitter_buffer(kdl_emitter* self) { return (kdl_str){self->buf.buf, self->buf.str_len}; } diff --git a/src/grammar.h b/src/grammar.h index 8d1a28a..78f9447 100644 --- a/src/grammar.h +++ b/src/grammar.h @@ -1,6 +1,9 @@ #ifndef KDL_INTERNAL_GRAMMAR_H_ #define KDL_INTERNAL_GRAMMAR_H_ +#include +#include + bool _kdl_is_whitespace(uint32_t c); bool _kdl_is_newline(uint32_t c); bool _kdl_is_id(uint32_t c); diff --git a/src/parser.c b/src/parser.c index 2a039fd..13edef6 100644 --- a/src/parser.c +++ b/src/parser.c @@ -2,15 +2,16 @@ #include "kdl/common.h" #include "kdl/tokenizer.h" -#include "compat.h" #include "bigint.h" +#include "compat.h" +#include +#include #include #include -#include -#include -#define _str_equals_literal(k, l) ((k).len == (sizeof(l "") - 1) && 0 == memcmp(("" l), (k).data, (sizeof(l) - 1))) +#define _str_equals_literal(k, l) \ + ((k).len == (sizeof(l "") - 1) && 0 == memcmp(("" l), (k).data, (sizeof(l) - 1))) enum _kdl_parser_state { // Basic states @@ -23,14 +24,15 @@ enum _kdl_parser_state { PARSER_FLAG_TYPE_ANNOTATION_ENDED = 0x800, PARSER_FLAG_IN_PROPERTY = 0x1000, // Bitmask for testing the state - PARSER_MASK_WHITESPACE_BANNED = PARSER_FLAG_TYPE_ANNOTATION_START - | PARSER_FLAG_TYPE_ANNOTATION_END - | PARSER_FLAG_TYPE_ANNOTATION_ENDED - | PARSER_FLAG_IN_PROPERTY + PARSER_MASK_WHITESPACE_BANNED = // + PARSER_FLAG_TYPE_ANNOTATION_START // + | PARSER_FLAG_TYPE_ANNOTATION_END // + | PARSER_FLAG_TYPE_ANNOTATION_ENDED // + | PARSER_FLAG_IN_PROPERTY }; struct _kdl_parser { - kdl_tokenizer *tokenizer; + kdl_tokenizer* tokenizer; kdl_parse_option opt; int depth; int slashdash_depth; @@ -43,22 +45,20 @@ struct _kdl_parser { bool have_next_token; }; - -static void _init_kdl_parser(kdl_parser *self) +static void _init_kdl_parser(kdl_parser* self) { self->depth = 0; self->slashdash_depth = -1; self->state = PARSER_OUTSIDE_NODE; - self->tmp_string_type = (kdl_owned_string){ NULL, 0 }; - self->tmp_string_key = (kdl_owned_string){ NULL, 0 }; - self->tmp_string_value = (kdl_owned_string){ NULL, 0 }; + self->tmp_string_type = (kdl_owned_string){NULL, 0}; + self->tmp_string_key = (kdl_owned_string){NULL, 0}; + self->tmp_string_value = (kdl_owned_string){NULL, 0}; self->have_next_token = false; } - -kdl_parser *kdl_create_string_parser(kdl_str doc, kdl_parse_option opt) +kdl_parser* kdl_create_string_parser(kdl_str doc, kdl_parse_option opt) { - kdl_parser *self = malloc(sizeof(kdl_parser)); + kdl_parser* self = malloc(sizeof(kdl_parser)); if (self != NULL) { _init_kdl_parser(self); self->tokenizer = kdl_create_string_tokenizer(doc); @@ -67,10 +67,9 @@ kdl_parser *kdl_create_string_parser(kdl_str doc, kdl_parse_option opt) return self; } - -kdl_parser *kdl_create_stream_parser(kdl_read_func read_func, void *user_data, kdl_parse_option opt) +kdl_parser* kdl_create_stream_parser(kdl_read_func read_func, void* user_data, kdl_parse_option opt) { - kdl_parser *self = malloc(sizeof(kdl_parser)); + kdl_parser* self = malloc(sizeof(kdl_parser)); if (self != NULL) { _init_kdl_parser(self); self->tokenizer = kdl_create_stream_tokenizer(read_func, user_data); @@ -79,8 +78,7 @@ kdl_parser *kdl_create_stream_parser(kdl_read_func read_func, void *user_data, k return self; } - -void kdl_destroy_parser(kdl_parser *self) +void kdl_destroy_parser(kdl_parser* self) { kdl_destroy_tokenizer(self->tokenizer); kdl_free_string(&self->tmp_string_type); @@ -89,43 +87,43 @@ void kdl_destroy_parser(kdl_parser *self) free(self); } -static void _reset_event(kdl_parser *self) +static void _reset_event(kdl_parser* self) { - self->event.name = (kdl_str){ NULL, 0 }; + self->event.name = (kdl_str){NULL, 0}; self->event.value.type = KDL_TYPE_NULL; - self->event.value.type_annotation = (kdl_str){ NULL, 0 }; + self->event.value.type_annotation = (kdl_str){NULL, 0}; } -static void _set_parse_error(kdl_parser *self, char const *message) +static void _set_parse_error(kdl_parser* self, char const* message) { self->event.event = KDL_EVENT_PARSE_ERROR; self->event.value.type = KDL_TYPE_STRING; - self->event.value.string = (kdl_str){ message, strlen(message) }; + self->event.value.string = (kdl_str){message, strlen(message)}; } -static void _set_comment_event(kdl_parser *self, kdl_token const *token) +static void _set_comment_event(kdl_parser* self, kdl_token const* token) { self->event.event = KDL_EVENT_COMMENT; self->event.value.type = KDL_TYPE_STRING; self->event.value.string = token->value; } -static kdl_event_data *_next_node(kdl_parser *self, kdl_token *token); -static kdl_event_data *_next_event_in_node(kdl_parser *self, kdl_token *token); -static kdl_event_data *_apply_slashdash(kdl_parser *self); -static bool _parse_value(kdl_token const *token, kdl_value *val, kdl_owned_string *s); -static bool _parse_number(kdl_str number, kdl_value *val, kdl_owned_string *s); -static bool _parse_decimal_number(kdl_str number, kdl_value *val, kdl_owned_string *s); -static bool _parse_decimal_integer(kdl_str number, kdl_value *val, kdl_owned_string *s); -static bool _parse_decimal_float(kdl_str number, kdl_value *val, kdl_owned_string *s); -static bool _parse_hex_number(kdl_str number, kdl_value *val, kdl_owned_string *s); -static bool _parse_octal_number(kdl_str number, kdl_value *val, kdl_owned_string *s); -static bool _parse_binary_number(kdl_str number, kdl_value *val, kdl_owned_string *s); - -kdl_event_data *kdl_parser_next_event(kdl_parser *self) +static kdl_event_data* _next_node(kdl_parser* self, kdl_token* token); +static kdl_event_data* _next_event_in_node(kdl_parser* self, kdl_token* token); +static kdl_event_data* _apply_slashdash(kdl_parser* self); +static bool _parse_value(kdl_token const* token, kdl_value* val, kdl_owned_string* s); +static bool _parse_number(kdl_str number, kdl_value* val, kdl_owned_string* s); +static bool _parse_decimal_number(kdl_str number, kdl_value* val, kdl_owned_string* s); +static bool _parse_decimal_integer(kdl_str number, kdl_value* val, kdl_owned_string* s); +static bool _parse_decimal_float(kdl_str number, kdl_value* val, kdl_owned_string* s); +static bool _parse_hex_number(kdl_str number, kdl_value* val, kdl_owned_string* s); +static bool _parse_octal_number(kdl_str number, kdl_value* val, kdl_owned_string* s); +static bool _parse_binary_number(kdl_str number, kdl_value* val, kdl_owned_string* s); + +kdl_event_data* kdl_parser_next_event(kdl_parser* self) { kdl_token token; - kdl_event_data *ev; + kdl_event_data* ev; _reset_event(self); @@ -216,7 +214,7 @@ kdl_event_data *kdl_parser_next_event(kdl_parser *self) } } -static kdl_event_data *_apply_slashdash(kdl_parser *self) +static kdl_event_data* _apply_slashdash(kdl_parser* self) { if (self->slashdash_depth >= 0) { // slashdash is active @@ -237,11 +235,10 @@ static kdl_event_data *_apply_slashdash(kdl_parser *self) } } - -static kdl_event_data *_next_node(kdl_parser *self, kdl_token *token) +static kdl_event_data* _next_node(kdl_parser* self, kdl_token* token) { kdl_value tmp_val; - kdl_event_data *ev; + kdl_event_data* ev; if (self->state & PARSER_FLAG_TYPE_ANNOTATION_START) { switch (token->type) { @@ -254,8 +251,8 @@ static kdl_event_data *_next_node(kdl_parser *self, kdl_token *token) } if (tmp_val.type == KDL_TYPE_STRING) { // We're good, this is an identifier - self->state = (self->state & ~PARSER_FLAG_TYPE_ANNOTATION_START) - | PARSER_FLAG_TYPE_ANNOTATION_END; + self->state + = (self->state & ~PARSER_FLAG_TYPE_ANNOTATION_START) | PARSER_FLAG_TYPE_ANNOTATION_END; self->event.value.type_annotation = tmp_val.string; return NULL; } else { @@ -269,7 +266,8 @@ static kdl_event_data *_next_node(kdl_parser *self, kdl_token *token) } else if (self->state & PARSER_FLAG_TYPE_ANNOTATION_END) { switch (token->type) { case KDL_TOKEN_END_TYPE: - self->state = (self->state & ~PARSER_FLAG_TYPE_ANNOTATION_END) | PARSER_FLAG_TYPE_ANNOTATION_ENDED; + self->state + = (self->state & ~PARSER_FLAG_TYPE_ANNOTATION_END) | PARSER_FLAG_TYPE_ANNOTATION_ENDED; return NULL; default: _set_parse_error(self, "Unexpected token, expected ')'"); @@ -335,10 +333,9 @@ static kdl_event_data *_next_node(kdl_parser *self, kdl_token *token) } } - -static kdl_event_data *_next_event_in_node(kdl_parser *self, kdl_token *token) +static kdl_event_data* _next_event_in_node(kdl_parser* self, kdl_token* token) { - kdl_event_data *ev; + kdl_event_data* ev; bool is_property = false; if (self->state & PARSER_FLAG_LINE_CONT) { @@ -366,8 +363,8 @@ static kdl_event_data *_next_event_in_node(kdl_parser *self, kdl_token *token) } if (tmp_val.type == KDL_TYPE_STRING) { // We're good, this is an identifier - self->state = (self->state & ~PARSER_FLAG_TYPE_ANNOTATION_START) - | PARSER_FLAG_TYPE_ANNOTATION_END; + self->state + = (self->state & ~PARSER_FLAG_TYPE_ANNOTATION_START) | PARSER_FLAG_TYPE_ANNOTATION_END; self->event.value.type_annotation = tmp_val.string; return NULL; } else { @@ -381,7 +378,8 @@ static kdl_event_data *_next_event_in_node(kdl_parser *self, kdl_token *token) } else if (self->state & PARSER_FLAG_TYPE_ANNOTATION_END) { switch (token->type) { case KDL_TOKEN_END_TYPE: - self->state = (self->state & ~PARSER_FLAG_TYPE_ANNOTATION_END) | PARSER_FLAG_TYPE_ANNOTATION_ENDED; + self->state + = (self->state & ~PARSER_FLAG_TYPE_ANNOTATION_END) | PARSER_FLAG_TYPE_ANNOTATION_ENDED; return NULL; default: _set_parse_error(self, "Unexpected token, expected ')'"); @@ -414,9 +412,8 @@ static kdl_event_data *_next_event_in_node(kdl_parser *self, kdl_token *token) } case KDL_TOKEN_WORD: case KDL_TOKEN_STRING: - case KDL_TOKEN_RAW_STRING: - { - kdl_owned_string tmp_str = { NULL, 0 }; + case KDL_TOKEN_RAW_STRING: { + kdl_owned_string tmp_str = {NULL, 0}; // either a property key, or a property value, or an argument if (self->event.name.data == NULL && self->event.value.type_annotation.data == NULL) { // the call to kdl_pop_token will invalidate the old token's value - clone it @@ -429,8 +426,7 @@ static kdl_event_data *_next_event_in_node(kdl_parser *self, kdl_token *token) case KDL_TOKENIZER_EOF: break; // all good case KDL_TOKENIZER_OK: - if (self->next_token.type == KDL_TOKEN_EQUALS) - is_property = true; + if (self->next_token.type == KDL_TOKEN_EQUALS) is_property = true; else // process this token next time self->have_next_token = true; @@ -515,7 +511,7 @@ static kdl_event_data *_next_event_in_node(kdl_parser *self, kdl_token *token) } } -static bool _parse_value(kdl_token const *token, kdl_value *val, kdl_owned_string *s) +static bool _parse_value(kdl_token const* token, kdl_value* val, kdl_owned_string* s) { kdl_free_string(s); @@ -556,8 +552,7 @@ static bool _parse_value(kdl_token const *token, kdl_value *val, kdl_owned_strin if ((first_char == '+' || first_char == '-') && token->value.len >= 2) first_char = token->value.data[1]; if (first_char >= '0' && first_char <= '9') { - // first character after sign is a digit, this value should be interpreted - // as a number + // first character after sign is a digit, this value should be interpreted as a number return _parse_number(token->value, val, s); } } @@ -571,7 +566,7 @@ static bool _parse_value(kdl_token const *token, kdl_value *val, kdl_owned_strin } } -static bool _parse_number(kdl_str number, kdl_value *val, kdl_owned_string *s) +static bool _parse_number(kdl_str number, kdl_value* val, kdl_owned_string* s) { kdl_str orig_number = number; if (number.len >= 1) { @@ -600,7 +595,7 @@ static bool _parse_number(kdl_str number, kdl_value *val, kdl_owned_string *s) return _parse_decimal_number(orig_number, val, s); } -static bool _parse_decimal_number(kdl_str number, kdl_value *val, kdl_owned_string *s) +static bool _parse_decimal_number(kdl_str number, kdl_value* val, kdl_owned_string* s) { // Check this is an integer or a decimal for (size_t i = 0; i < number.len; ++i) { @@ -614,10 +609,10 @@ static bool _parse_decimal_number(kdl_str number, kdl_value *val, kdl_owned_stri return _parse_decimal_integer(number, val, s); } -static bool _parse_decimal_integer(kdl_str number, kdl_value *val, kdl_owned_string *s) +static bool _parse_decimal_integer(kdl_str number, kdl_value* val, kdl_owned_string* s) { bool negative = false; - _kdl_ubigint *n = _kdl_ubigint_new(0); + _kdl_ubigint* n = _kdl_ubigint_new(0); if (n == NULL) return false; size_t i = 0; // index into number-string @@ -668,7 +663,7 @@ static bool _parse_decimal_integer(kdl_str number, kdl_value *val, kdl_owned_str return false; } -static bool _parse_decimal_float(kdl_str number, kdl_value *val, kdl_owned_string *s) +static bool _parse_decimal_float(kdl_str number, kdl_value* val, kdl_owned_string* s) { bool negative = false; int digits_before_decimal = 0; @@ -704,19 +699,19 @@ static bool _parse_decimal_float(kdl_str number, kdl_value *val, kdl_owned_strin char c = number.data[i]; if (c == '.' && state == before_decimal) { state = after_decimal_nodigit; - if (number.len - i <= 1 || number.data[i+1] == '_') return false; + if (number.len - i <= 1 || number.data[i + 1] == '_') return false; } else if ((c == 'e' || c == 'E') && state != exponent && state != after_decimal_nodigit) { state = exponent_nodigit; if (i + 1 < number.len) { // handle exponent sign - switch (number.data[i+1]) { + switch (number.data[i + 1]) { case '-': exponent_negative = true; _fallthrough_; case '+': ++i; } - if (number.len - i <= 1 || number.data[i+1] == '_') return false; + if (number.len - i <= 1 || number.data[i + 1] == '_') return false; } } else if (c >= '0' && c <= '9') { // digit! @@ -747,7 +742,8 @@ static bool _parse_decimal_float(kdl_str number, kdl_value *val, kdl_owned_strin } // rough heuristic for numbers that fit into a double exactly - if (digits_before_decimal + digits_after_decimal <= 15 && explicit_exponent < 285 && explicit_exponent > -285) { + if (digits_before_decimal + digits_after_decimal <= 15 && explicit_exponent < 285 + && explicit_exponent > -285) { // "strip zeros" while (decimal_mantissa % 10 == 0 && digits_after_decimal > 0) { decimal_mantissa /= 10; @@ -771,9 +767,9 @@ static bool _parse_decimal_float(kdl_str number, kdl_value *val, kdl_owned_strin } else { // Remove all underscores and the initial plus *s = kdl_clone_str(&number); - char const *p1 = number.data; - char const *end = number.data + number.len; - char *p2 = s->data; + char const* p1 = number.data; + char const* end = number.data + number.len; + char* p2 = s->data; s->len = 0; if (p1 != end && *p1 == '+') ++p1; while (p1 != end) { @@ -793,11 +789,10 @@ static bool _parse_decimal_float(kdl_str number, kdl_value *val, kdl_owned_strin } } - -static bool _parse_hex_number(kdl_str number, kdl_value *val, kdl_owned_string *s) +static bool _parse_hex_number(kdl_str number, kdl_value* val, kdl_owned_string* s) { bool negative = false; - _kdl_ubigint *n = _kdl_ubigint_new(0); + _kdl_ubigint* n = _kdl_ubigint_new(0); if (n == NULL) return false; size_t i = 0; // index into number-string @@ -813,9 +808,7 @@ static bool _parse_hex_number(kdl_str number, kdl_value *val, kdl_owned_string * } } - if (number.len - i < 3 || number.data[i] != '0' - || number.data[i+1] != 'x' - || number.data[i+2] == '_') + if (number.len - i < 3 || number.data[i] != '0' || number.data[i + 1] != 'x' || number.data[i + 2] == '_') goto error; i += 2; @@ -856,11 +849,10 @@ static bool _parse_hex_number(kdl_str number, kdl_value *val, kdl_owned_string * return false; } - -static bool _parse_octal_number(kdl_str number, kdl_value *val, kdl_owned_string *s) +static bool _parse_octal_number(kdl_str number, kdl_value* val, kdl_owned_string* s) { bool negative = false; - _kdl_ubigint *n = _kdl_ubigint_new(0); + _kdl_ubigint* n = _kdl_ubigint_new(0); if (n == NULL) return false; size_t i = 0; // index into number-string @@ -876,9 +868,7 @@ static bool _parse_octal_number(kdl_str number, kdl_value *val, kdl_owned_string } } - if (number.len - i < 3 || number.data[i] != '0' - || number.data[i+1] != 'o' - || number.data[i+2] == '_') + if (number.len - i < 3 || number.data[i] != '0' || number.data[i + 1] != 'o' || number.data[i + 2] == '_') goto error; i += 2; @@ -916,11 +906,10 @@ static bool _parse_octal_number(kdl_str number, kdl_value *val, kdl_owned_string return false; } - -static bool _parse_binary_number(kdl_str number, kdl_value *val, kdl_owned_string *s) +static bool _parse_binary_number(kdl_str number, kdl_value* val, kdl_owned_string* s) { bool negative = false; - _kdl_ubigint *n = _kdl_ubigint_new(0); + _kdl_ubigint* n = _kdl_ubigint_new(0); if (n == NULL) return false; size_t i = 0; // index into number-string @@ -936,9 +925,7 @@ static bool _parse_binary_number(kdl_str number, kdl_value *val, kdl_owned_strin } } - if (number.len - i < 3 || number.data[i] != '0' - || number.data[i+1] != 'b' - || number.data[i+2] == '_') + if (number.len - i < 3 || number.data[i] != '0' || number.data[i + 1] != 'b' || number.data[i + 2] == '_') goto error; i += 2; @@ -975,5 +962,3 @@ static bool _parse_binary_number(kdl_str number, kdl_value *val, kdl_owned_strin _kdl_ubigint_free(n); return false; } - - diff --git a/src/str.c b/src/str.c index 2b7f8a3..6924c89 100644 --- a/src/str.c +++ b/src/str.c @@ -1,7 +1,7 @@ -#include "kdl/common.h" #include "str.h" -#include "utf8.h" #include "compat.h" +#include "kdl/common.h" +#include "utf8.h" #include #include @@ -9,20 +9,17 @@ // No buffering in Debug mode to find more bugs #ifdef KDL_DEBUG -# define MIN_BUFFER_SIZE 1 -# define BUFFER_SIZE_INCREMENT 1 +# define MIN_BUFFER_SIZE 1 +# define BUFFER_SIZE_INCREMENT 1 #else -# define BUFFER_SIZE_INCREMENT 1024 +# define BUFFER_SIZE_INCREMENT 1024 #endif -KDL_EXPORT extern inline kdl_str kdl_borrow_str(kdl_owned_string const *str); +KDL_EXPORT extern inline kdl_str kdl_borrow_str(kdl_owned_string const* str); -kdl_str kdl_str_from_cstr(char const *s) -{ - return (kdl_str){ s, strlen(s) }; -} +kdl_str kdl_str_from_cstr(char const* s) { return (kdl_str){s, strlen(s)}; } -kdl_owned_string kdl_clone_str(kdl_str const *s) +kdl_owned_string kdl_clone_str(kdl_str const* s) { kdl_owned_string result; result.data = malloc(s->len + 1); @@ -36,7 +33,7 @@ kdl_owned_string kdl_clone_str(kdl_str const *s) return result; } -void kdl_free_string(kdl_owned_string *s) +void kdl_free_string(kdl_owned_string* s) { if (s->data != NULL) { free(s->data); @@ -47,14 +44,10 @@ void kdl_free_string(kdl_owned_string *s) _kdl_write_buffer _kdl_new_write_buffer(size_t initial_size) { - return (_kdl_write_buffer){ - .buf = malloc(initial_size), - .buf_len = initial_size, - .str_len = 0 - }; + return (_kdl_write_buffer){.buf = malloc(initial_size), .buf_len = initial_size, .str_len = 0}; } -void _kdl_free_write_buffer(_kdl_write_buffer *buf) +void _kdl_free_write_buffer(_kdl_write_buffer* buf) { free(buf->buf); buf->buf = NULL; @@ -62,7 +55,7 @@ void _kdl_free_write_buffer(_kdl_write_buffer *buf) buf->str_len = 0; } -bool _kdl_buf_push_chars(_kdl_write_buffer *buf, char const *s, size_t count) +bool _kdl_buf_push_chars(_kdl_write_buffer* buf, char const* s, size_t count) { if (buf->buf_len - buf->str_len < count) { size_t increment = BUFFER_SIZE_INCREMENT >= count ? BUFFER_SIZE_INCREMENT : count; @@ -77,12 +70,9 @@ bool _kdl_buf_push_chars(_kdl_write_buffer *buf, char const *s, size_t count) return true; } -bool _kdl_buf_push_char(_kdl_write_buffer *buf, char c) -{ - return _kdl_buf_push_chars(buf, &c, 1); -} +bool _kdl_buf_push_char(_kdl_write_buffer* buf, char c) { return _kdl_buf_push_chars(buf, &c, 1); } -bool _kdl_buf_push_codepoint(_kdl_write_buffer *buf, uint32_t c) +bool _kdl_buf_push_codepoint(_kdl_write_buffer* buf, uint32_t c) { // 4 is the maximum length of a character in UTF-8 if (buf->buf_len - buf->str_len < 4) { @@ -102,9 +92,9 @@ bool _kdl_buf_push_codepoint(_kdl_write_buffer *buf, uint32_t c) } } -kdl_owned_string _kdl_buf_to_string(_kdl_write_buffer *buf) +kdl_owned_string _kdl_buf_to_string(_kdl_write_buffer* buf) { - kdl_owned_string s = { reallocf(buf->buf, buf->str_len + 1), buf->str_len }; + kdl_owned_string s = {reallocf(buf->buf, buf->str_len + 1), buf->str_len}; if (s.data == NULL) s.len = 0; buf->buf = NULL; buf->buf_len = 0; @@ -113,7 +103,7 @@ kdl_owned_string _kdl_buf_to_string(_kdl_write_buffer *buf) return s; } -kdl_owned_string kdl_escape(kdl_str const *s, kdl_escape_mode mode) +kdl_owned_string kdl_escape(kdl_str const* s, kdl_escape_mode mode) { kdl_owned_string result; kdl_str unescaped = *s; @@ -125,7 +115,7 @@ kdl_owned_string kdl_escape(kdl_str const *s, kdl_escape_mode mode) uint32_t c; while (true) { - char const *orig_char = unescaped.data; + char const* orig_char = unescaped.data; switch (_kdl_pop_codepoint(&unescaped, &c)) { case KDL_UTF8_EOF: goto esc_eof; @@ -139,7 +129,7 @@ kdl_owned_string kdl_escape(kdl_str const *s, kdl_escape_mode mode) if (!_kdl_buf_push_chars(&buf, "\\n", 2)) goto esc_error; } else if (c == 0x0D && (mode & KDL_ESCAPE_NEWLINE)) { if (!_kdl_buf_push_chars(&buf, "\\r", 2)) goto esc_error; - } else if (c == 0x09 && (mode & KDL_ESCAPE_TAB)) { + } else if (c == 0x09 && (mode & KDL_ESCAPE_TAB)) { if (!_kdl_buf_push_chars(&buf, "\\t", 2)) goto esc_error; } else if (c == 0x5C) { if (!_kdl_buf_push_chars(&buf, "\\\\", 2)) goto esc_error; @@ -149,14 +139,11 @@ kdl_owned_string kdl_escape(kdl_str const *s, kdl_escape_mode mode) if (!_kdl_buf_push_chars(&buf, "\\b", 2)) goto esc_error; } else if (c == 0x0C && (mode & KDL_ESCAPE_NEWLINE)) { if (!_kdl_buf_push_chars(&buf, "\\f", 2)) goto esc_error; - } else if ( - ((mode & KDL_ESCAPE_CONTROL) - && ((c < 0x20 && c != 0x0A && c != 0x0D && c != 0x09 && c != 0x0C) - || c == 0x7F /* DEL */)) - || ((mode & KDL_ESCAPE_NEWLINE) - && (c == 0x85 || c == 0x2028 || c == 0x2029)) - || ((mode & KDL_ESCAPE_ASCII_MODE) == KDL_ESCAPE_ASCII_MODE - && c >= 0x7f)) { + } else if (((mode & KDL_ESCAPE_CONTROL) + && ((c < 0x20 && c != 0x0A && c != 0x0D && c != 0x09 && c != 0x0C) + || c == 0x7F /* DEL */)) + || ((mode & KDL_ESCAPE_NEWLINE) && (c == 0x85 || c == 0x2028 || c == 0x2029)) + || ((mode & KDL_ESCAPE_ASCII_MODE) == KDL_ESCAPE_ASCII_MODE && c >= 0x7f)) { // \u escape char u_esc_buf[11]; int count = snprintf(u_esc_buf, 11, "\\u{%x}", (unsigned int)c); @@ -176,11 +163,11 @@ kdl_owned_string kdl_escape(kdl_str const *s, kdl_escape_mode mode) esc_error: _kdl_free_write_buffer(&buf); - result = (kdl_owned_string){ NULL, 0 }; + result = (kdl_owned_string){NULL, 0}; return result; } -kdl_owned_string kdl_unescape(kdl_str const *s) +kdl_owned_string kdl_unescape(kdl_str const* s) { kdl_owned_string result; kdl_str escaped = *s; @@ -190,8 +177,8 @@ kdl_owned_string kdl_unescape(kdl_str const *s) _kdl_write_buffer buf = _kdl_new_write_buffer(2 * orig_len); if (buf.buf == NULL) goto unesc_error; - char const *p = s->data; - char const *end = p + s->len; + char const* p = s->data; + char const* end = p + s->len; while (p != end) { if (*p == '\\') { @@ -235,7 +222,7 @@ kdl_owned_string kdl_unescape(kdl_str const *s) if (++p == end || *(p++) != '{') goto unesc_error; // parse hex c = 0; - for (;;++p) { + for (;; ++p) { if (p == end) goto unesc_error; else if (*p == '}') break; else if (*p >= '0' && *p <= '9') c = (c << 4) + (*p - '0'); @@ -254,7 +241,7 @@ kdl_owned_string kdl_unescape(kdl_str const *s) } } - char const *start = p; + char const* start = p; while (p != end && *p != '\\') ++p; // copy everything until the backslash if (!_kdl_buf_push_chars(&buf, start, (p - start))) goto unesc_error; @@ -264,6 +251,6 @@ kdl_owned_string kdl_unescape(kdl_str const *s) unesc_error: _kdl_free_write_buffer(&buf); - result = (kdl_owned_string){ NULL, 0 }; + result = (kdl_owned_string){NULL, 0}; return result; } diff --git a/src/str.h b/src/str.h index 1b089fc..a3a3f62 100644 --- a/src/str.h +++ b/src/str.h @@ -3,12 +3,12 @@ #include "kdl/common.h" -#include -#include #include +#include +#include struct _kdl_write_buffer { - char *buf; + char* buf; size_t buf_len; size_t str_len; }; @@ -16,10 +16,10 @@ struct _kdl_write_buffer { typedef struct _kdl_write_buffer _kdl_write_buffer; _kdl_write_buffer _kdl_new_write_buffer(size_t initial_size); -bool _kdl_buf_push_chars(_kdl_write_buffer *buf, char const *s, size_t count); -bool _kdl_buf_push_char(_kdl_write_buffer *buf, char c); -bool _kdl_buf_push_codepoint(_kdl_write_buffer *buf, uint32_t c); -kdl_owned_string _kdl_buf_to_string(_kdl_write_buffer *buf); -void _kdl_free_write_buffer(_kdl_write_buffer *buf); +bool _kdl_buf_push_chars(_kdl_write_buffer* buf, char const* s, size_t count); +bool _kdl_buf_push_char(_kdl_write_buffer* buf, char c); +bool _kdl_buf_push_codepoint(_kdl_write_buffer* buf, uint32_t c); +kdl_owned_string _kdl_buf_to_string(_kdl_write_buffer* buf); +void _kdl_free_write_buffer(_kdl_write_buffer* buf); #endif // KDL_INTERNAL_STR_H_ diff --git a/src/tokenizer.c b/src/tokenizer.c index 6756014..3b8689a 100644 --- a/src/tokenizer.c +++ b/src/tokenizer.c @@ -1,31 +1,31 @@ #include "kdl/tokenizer.h" -#include "utf8.h" #include "grammar.h" +#include "utf8.h" -#include #include +#include #include // No buffering in Debug mode to find more bugs #ifdef KDL_DEBUG -# define MIN_BUFFER_SIZE 1 -# define BUFFER_SIZE_INCREMENT 1 +# define MIN_BUFFER_SIZE 1 +# define BUFFER_SIZE_INCREMENT 1 #else -# define MIN_BUFFER_SIZE 1024 -# define BUFFER_SIZE_INCREMENT 4096 +# define MIN_BUFFER_SIZE 1024 +# define BUFFER_SIZE_INCREMENT 4096 #endif struct _kdl_tokenizer { kdl_str document; kdl_read_func read_func; - void *read_user_data; - char *buffer; + void* read_user_data; + char* buffer; size_t buffer_size; }; -kdl_tokenizer *kdl_create_string_tokenizer(kdl_str doc) +kdl_tokenizer* kdl_create_string_tokenizer(kdl_str doc) { - kdl_tokenizer *self = malloc(sizeof(kdl_tokenizer)); + kdl_tokenizer* self = malloc(sizeof(kdl_tokenizer)); if (self != NULL) { self->document = doc; self->read_func = NULL; @@ -36,11 +36,11 @@ kdl_tokenizer *kdl_create_string_tokenizer(kdl_str doc) return self; } -kdl_tokenizer *kdl_create_stream_tokenizer(kdl_read_func read_func, void *user_data) +kdl_tokenizer* kdl_create_stream_tokenizer(kdl_read_func read_func, void* user_data) { - kdl_tokenizer *self = malloc(sizeof(kdl_tokenizer)); + kdl_tokenizer* self = malloc(sizeof(kdl_tokenizer)); if (self != NULL) { - self->document = (kdl_str){ .data = NULL, .len = 0 }; + self->document = (kdl_str){.data = NULL, .len = 0}; self->read_func = read_func; self->read_user_data = user_data; self->buffer = NULL; @@ -49,7 +49,7 @@ kdl_tokenizer *kdl_create_stream_tokenizer(kdl_read_func read_func, void *user_d return self; } -void kdl_destroy_tokenizer(kdl_tokenizer *tokenizer) +void kdl_destroy_tokenizer(kdl_tokenizer* tokenizer) { if (tokenizer->buffer != NULL) { free(tokenizer->buffer); @@ -57,7 +57,7 @@ void kdl_destroy_tokenizer(kdl_tokenizer *tokenizer) free(tokenizer); } -static size_t _refill_tokenizer(kdl_tokenizer *self) +static size_t _refill_tokenizer(kdl_tokenizer* self) { if (self->read_func == NULL) return 0; @@ -77,7 +77,7 @@ static size_t _refill_tokenizer(kdl_tokenizer *self) if (len_available < MIN_BUFFER_SIZE) { // Need more room size_t new_buf_size = self->buffer_size + BUFFER_SIZE_INCREMENT; - char *new_buffer = realloc(self->buffer, new_buf_size); + char* new_buffer = realloc(self->buffer, new_buf_size); if (new_buffer == NULL) { return 0; } else { @@ -87,7 +87,7 @@ static size_t _refill_tokenizer(kdl_tokenizer *self) len_available = self->buffer_size - self->document.len; } } - char *end = self->buffer + self->document.len; + char* end = self->buffer + self->document.len; size_t read_count = self->read_func(self->read_user_data, end, len_available); self->document.len += read_count; @@ -96,66 +96,59 @@ static size_t _refill_tokenizer(kdl_tokenizer *self) bool _kdl_is_whitespace(uint32_t c) { - return - c == 0x0009 || // Character Tabulation - c == 0x0020 || // Space - c == 0x00A0 || // No-Break Space - c == 0x1680 || // Ogham Space Mark - c == 0x2000 || // En Quad - c == 0x2001 || // Em Quad - c == 0x2002 || // En Space - c == 0x2003 || // Em Space - c == 0x2004 || // Three-Per-Em Space - c == 0x2005 || // Four-Per-Em Space - c == 0x2006 || // Six-Per-Em Space - c == 0x2007 || // Figure Space - c == 0x2008 || // Punctuation Space - c == 0x2009 || // Thin Space - c == 0x200A || // Hair Space - c == 0x202F || // Narrow No-Break Space - c == 0x205F || // Medium Mathematical Space - c == 0x3000; // Ideographic Space + return c == 0x0009 || // Character Tabulation + c == 0x0020 || // Space + c == 0x00A0 || // No-Break Space + c == 0x1680 || // Ogham Space Mark + c == 0x2000 || // En Quad + c == 0x2001 || // Em Quad + c == 0x2002 || // En Space + c == 0x2003 || // Em Space + c == 0x2004 || // Three-Per-Em Space + c == 0x2005 || // Four-Per-Em Space + c == 0x2006 || // Six-Per-Em Space + c == 0x2007 || // Figure Space + c == 0x2008 || // Punctuation Space + c == 0x2009 || // Thin Space + c == 0x200A || // Hair Space + c == 0x202F || // Narrow No-Break Space + c == 0x205F || // Medium Mathematical Space + c == 0x3000; // Ideographic Space } bool _kdl_is_newline(uint32_t c) { - return - c == 0x000D || // CR Carriage Return - c == 0x000A || // LF Line Feed - c == 0x0085 || // NEL Next Line - c == 0x000C || // FF Form Feed - c == 0x2028 || // LS Line Separator - c == 0x2029; // PS Paragraph Separator + return c == 0x000D || // CR Carriage Return + c == 0x000A || // LF Line Feed + c == 0x0085 || // NEL Next Line + c == 0x000C || // FF Form Feed + c == 0x2028 || // LS Line Separator + c == 0x2029; // PS Paragraph Separator } bool _kdl_is_id(uint32_t c) { - return c > 0x20 && c <= 0x10FFFF && - c != '\\' && c != '/' && c != '(' && c != ')' && c != '{' && - c != '}' && c != '<' && c != '>' && c != ';' && c != '[' && - c != ']' && c != '=' && c != ',' && c != '"' && - !_kdl_is_whitespace(c) && !_kdl_is_newline(c); + return c > 0x20 && c <= 0x10FFFF // + && c != '\\' && c != '/' && c != '(' && c != ')' && c != '{' && c != '}' && c != '<' && c != '>' + && c != ';' && c != '[' && c != ']' && c != '=' && c != ',' && c != '"' && !_kdl_is_whitespace(c) + && !_kdl_is_newline(c); } -bool _kdl_is_id_start(uint32_t c) -{ - return _kdl_is_id(c) && (c < '0' || c > '9'); -} +bool _kdl_is_id_start(uint32_t c) { return _kdl_is_id(c) && (c < '0' || c > '9'); } bool _kdl_is_end_of_word(uint32_t c) { - // is this character something that could terminate an identifier (or - // number) in some situation? - return _kdl_is_whitespace(c) || _kdl_is_newline(c) || - c == ';' || c == ')' || c == '}' || c == '/' || c == '\\' || c == '='; + // is this character something that could terminate an identifier (or number) in some situation? + return _kdl_is_whitespace(c) || _kdl_is_newline(c) // + || c == ';' || c == ')' || c == '}' || c == '/' || c == '\\' || c == '='; } -static inline kdl_utf8_status _tok_get_char(kdl_tokenizer *self, - char const **cur, char const **next, uint32_t *codepoint) +static inline kdl_utf8_status _tok_get_char( + kdl_tokenizer* self, char const** cur, char const** next, uint32_t* codepoint) { while (true) { ptrdiff_t offset; - kdl_str s = { *cur, self->document.len - (*cur - self->document.data) }; + kdl_str s = {*cur, self->document.len - (*cur - self->document.data)}; kdl_utf8_status status = _kdl_pop_codepoint(&s, codepoint); switch (status) { case KDL_UTF8_OK: @@ -180,22 +173,22 @@ static inline kdl_utf8_status _tok_get_char(kdl_tokenizer *self, } } -static inline void _update_doc_ptr(kdl_tokenizer *self, char const *new_ptr) +static inline void _update_doc_ptr(kdl_tokenizer* self, char const* new_ptr) { self->document.len -= (new_ptr - self->document.data); self->document.data = new_ptr; } -static kdl_tokenizer_status _pop_word(kdl_tokenizer *self, kdl_token *dest); -static kdl_tokenizer_status _pop_comment(kdl_tokenizer *self, kdl_token *dest); -static kdl_tokenizer_status _pop_string(kdl_tokenizer *self, kdl_token *dest); -static kdl_tokenizer_status _pop_raw_string(kdl_tokenizer *self, kdl_token *dest); +static kdl_tokenizer_status _pop_word(kdl_tokenizer* self, kdl_token* dest); +static kdl_tokenizer_status _pop_comment(kdl_tokenizer* self, kdl_token* dest); +static kdl_tokenizer_status _pop_string(kdl_tokenizer* self, kdl_token* dest); +static kdl_tokenizer_status _pop_raw_string(kdl_tokenizer* self, kdl_token* dest); -kdl_tokenizer_status kdl_pop_token(kdl_tokenizer *self, kdl_token *dest) +kdl_tokenizer_status kdl_pop_token(kdl_tokenizer* self, kdl_token* dest) { uint32_t c = 0; - char const *cur = self->document.data; - char const *next = NULL; + char const* cur = self->document.data; + char const* next = NULL; while (true) { switch (_tok_get_char(self, &cur, &next, &c)) { @@ -212,8 +205,7 @@ kdl_tokenizer_status kdl_pop_token(kdl_tokenizer *self, kdl_token *dest) // find whitespace run size_t ws_start_offset = cur - self->document.data; cur = next; - while (_tok_get_char(self, &cur, &next, &c) == KDL_UTF8_OK - && _kdl_is_whitespace(c)) { + while (_tok_get_char(self, &cur, &next, &c) == KDL_UTF8_OK && _kdl_is_whitespace(c)) { // accept whitespace character cur = next; } @@ -227,15 +219,13 @@ kdl_tokenizer_status kdl_pop_token(kdl_tokenizer *self, kdl_token *dest) // end of line // special treatment for CRLF if (c == '\r') { - char const *nnext; + char const* nnext; uint32_t c2; - bool is_crlf = _tok_get_char(self, &next, &nnext, &c2) - == KDL_UTF8_OK && c2 == '\n'; + bool is_crlf = _tok_get_char(self, &next, &nnext, &c2) == KDL_UTF8_OK && c2 == '\n'; // cur has been invalidated by _tok_get_char // but we know '\r' takes 1 byte cur = next - 1; - if (is_crlf) - next = nnext; + if (is_crlf) next = nnext; } dest->type = KDL_TOKEN_NEWLINE; dest->value.data = cur; @@ -301,8 +291,7 @@ kdl_tokenizer_status kdl_pop_token(kdl_tokenizer *self, kdl_token *dest) if (c == 'r') { // this *could* be a raw string kdl_tokenizer_status rstring_status = _pop_raw_string(self, dest); - if (rstring_status == KDL_TOKENIZER_OK) - return KDL_TOKENIZER_OK; + if (rstring_status == KDL_TOKENIZER_OK) return KDL_TOKENIZER_OK; // else: parse this as an identifier instead (which may also fail) } // start of an identfier, number, bool, or null @@ -313,11 +302,11 @@ kdl_tokenizer_status kdl_pop_token(kdl_tokenizer *self, kdl_token *dest) } } -static kdl_tokenizer_status _pop_word(kdl_tokenizer *self, kdl_token *dest) +static kdl_tokenizer_status _pop_word(kdl_tokenizer* self, kdl_token* dest) { uint32_t c = 0; - char const *cur = self->document.data; - char const *next = NULL; + char const* cur = self->document.data; + char const* next = NULL; while (true) { switch (_tok_get_char(self, &cur, &next, &c)) { @@ -347,12 +336,12 @@ static kdl_tokenizer_status _pop_word(kdl_tokenizer *self, kdl_token *dest) return KDL_TOKENIZER_OK; } -static kdl_tokenizer_status _pop_comment(kdl_tokenizer *self, kdl_token *dest) +static kdl_tokenizer_status _pop_comment(kdl_tokenizer* self, kdl_token* dest) { uint32_t c1 = 0; uint32_t c2 = 0; - char const *cur = self->document.data; - char const *next = NULL; + char const* cur = self->document.data; + char const* next = NULL; if (_tok_get_char(self, &cur, &next, &c1) != KDL_UTF8_OK) return KDL_TOKENIZER_ERROR; cur = next; if (_tok_get_char(self, &cur, &next, &c2) != KDL_UTF8_OK) return KDL_TOKENIZER_ERROR; @@ -400,7 +389,7 @@ static kdl_tokenizer_status _pop_comment(kdl_tokenizer *self, kdl_token *dest) case KDL_UTF8_OK: break; case KDL_UTF8_EOF: // EOF in a comment is an error - default: // error + default: // error return KDL_TOKENIZER_ERROR; } @@ -428,13 +417,12 @@ static kdl_tokenizer_status _pop_comment(kdl_tokenizer *self, kdl_token *dest) } } -static kdl_tokenizer_status _pop_string(kdl_tokenizer *self, kdl_token *dest) +static kdl_tokenizer_status _pop_string(kdl_tokenizer* self, kdl_token* dest) { uint32_t c = 0; - char const *cur = self->document.data; - char const *next = NULL; - if (_tok_get_char(self, &cur, &next, &c) != KDL_UTF8_OK || c != '"') - return KDL_TOKENIZER_ERROR; + char const* cur = self->document.data; + char const* next = NULL; + if (_tok_get_char(self, &cur, &next, &c) != KDL_UTF8_OK || c != '"') return KDL_TOKENIZER_ERROR; // eat the initial quote _update_doc_ptr(self, next); @@ -447,7 +435,7 @@ static kdl_tokenizer_status _pop_string(kdl_tokenizer *self, kdl_token *dest) case KDL_UTF8_OK: break; case KDL_UTF8_EOF: // eof in a string is an error - default: // error + default: // error return KDL_TOKENIZER_ERROR; } @@ -470,13 +458,12 @@ static kdl_tokenizer_status _pop_string(kdl_tokenizer *self, kdl_token *dest) return KDL_TOKENIZER_OK; } -static kdl_tokenizer_status _pop_raw_string(kdl_tokenizer *self, kdl_token *dest) +static kdl_tokenizer_status _pop_raw_string(kdl_tokenizer* self, kdl_token* dest) { uint32_t c = 0; - char const *cur = self->document.data; - char const *next = NULL; - if (_tok_get_char(self, &cur, &next, &c) != KDL_UTF8_OK || c != 'r') - return KDL_TOKENIZER_ERROR; + char const* cur = self->document.data; + char const* next = NULL; + if (_tok_get_char(self, &cur, &next, &c) != KDL_UTF8_OK || c != 'r') return KDL_TOKENIZER_ERROR; cur = next; // Get all hashes, and the initial quote @@ -486,7 +473,7 @@ static kdl_tokenizer_status _pop_raw_string(kdl_tokenizer *self, kdl_token *dest case KDL_UTF8_OK: break; case KDL_UTF8_EOF: // eof in a string is an error - default: // error + default: // error return KDL_TOKENIZER_ERROR; } @@ -510,7 +497,7 @@ static kdl_tokenizer_status _pop_raw_string(kdl_tokenizer *self, kdl_token *dest case KDL_UTF8_OK: break; case KDL_UTF8_EOF: // eof in a string is an error - default: // error + default: // error return KDL_TOKENIZER_ERROR; } @@ -539,4 +526,3 @@ static kdl_tokenizer_status _pop_raw_string(kdl_tokenizer *self, kdl_token *dest dest->type = KDL_TOKEN_RAW_STRING; return KDL_TOKENIZER_OK; } - diff --git a/src/utf8.c b/src/utf8.c index 5a74521..59b4bb6 100644 --- a/src/utf8.c +++ b/src/utf8.c @@ -2,12 +2,9 @@ #include "utf8.h" -inline static bool _is_utf8_continuation(int c) -{ - return (c & 0xc0) == 0x80; -} +inline static bool _is_utf8_continuation(int c) { return (c & 0xc0) == 0x80; } -kdl_utf8_status _kdl_pop_codepoint(kdl_str *str, uint32_t *codepoint) +kdl_utf8_status _kdl_pop_codepoint(kdl_str* str, uint32_t* codepoint) { if (str->len < 1) { return KDL_UTF8_EOF; @@ -52,7 +49,8 @@ kdl_utf8_status _kdl_pop_codepoint(kdl_str *str, uint32_t *codepoint) if (str->len < 4) { // Incomplete UTF-8 sequence return KDL_UTF8_INCOMPLETE; - } else if (!_is_utf8_continuation(s[1]) || !_is_utf8_continuation(s[2]) || !_is_utf8_continuation(s[3])) { + } else if (!_is_utf8_continuation(s[1]) || !_is_utf8_continuation(s[2]) + || !_is_utf8_continuation(s[3])) { // Invalid UTF-8 sequence return KDL_UTF8_DECODE_ERROR; } @@ -65,9 +63,9 @@ kdl_utf8_status _kdl_pop_codepoint(kdl_str *str, uint32_t *codepoint) } } -int _kdl_push_codepoint(uint32_t codepoint, char *buf) +int _kdl_push_codepoint(uint32_t codepoint, char* buf) { - char *p = buf; + char* p = buf; if (codepoint <= 0x7f) { // ASCII *(p++) = (char)codepoint; diff --git a/src/utf8.h b/src/utf8.h index 72ff96e..f642628 100644 --- a/src/utf8.h +++ b/src/utf8.h @@ -1,8 +1,8 @@ #ifndef KDL_INTERNAL_UTF8_H_ #define KDL_INTERNAL_UTF8_H_ -#include #include +#include #include "kdl/common.h" @@ -14,7 +14,7 @@ enum kdl_utf8_status { }; typedef enum kdl_utf8_status kdl_utf8_status; -kdl_utf8_status _kdl_pop_codepoint(kdl_str *str, uint32_t *codepoint); -int _kdl_push_codepoint(uint32_t codepoint, char *buf); +kdl_utf8_status _kdl_pop_codepoint(kdl_str* str, uint32_t* codepoint); +int _kdl_push_codepoint(uint32_t codepoint, char* buf); #endif // KDL_INTERNAL_UTF8_H_ diff --git a/src/utils/ckdl-cat-main.c b/src/utils/ckdl-cat-main.c index 29158c2..20b1305 100644 --- a/src/utils/ckdl-cat-main.c +++ b/src/utils/ckdl-cat-main.c @@ -1,18 +1,18 @@ #include "ckdl-cat.h" +#include #include #include -#include -static void print_usage(char const *argv0, FILE *fp) +static void print_usage(char const* argv0, FILE* fp) { fprintf(fp, "Usage: %s [-h]\n\n", argv0); fprintf(fp, " -h Print usage information\n"); } -int main(int argc, char **argv) +int main(int argc, char** argv) { - FILE *in = stdin; + FILE* in = stdin; char const* argv0 = argv[0]; bool opts_ended = false; @@ -20,7 +20,7 @@ int main(int argc, char **argv) ++argv; if (!opts_ended && **argv == '-') { // options - for (char const *p = *argv+1; *p; ++p) { + for (char const* p = *argv + 1; *p; ++p) { if (*p == 'h') { print_usage(argv0, stdout); return 0; @@ -32,11 +32,10 @@ int main(int argc, char **argv) } } } else { - char const *fn = *argv; + char const* fn = *argv; in = fopen(fn, "r"); if (in == NULL) { - fprintf(stderr, "Error opening file \"%s\": %s\n", - fn, strerror(errno)); + fprintf(stderr, "Error opening file \"%s\": %s\n", fn, strerror(errno)); return 1; } } diff --git a/src/utils/ckdl-cat.c b/src/utils/ckdl-cat.c index a802484..d8bf68e 100644 --- a/src/utils/ckdl-cat.c +++ b/src/utils/ckdl-cat.c @@ -1,12 +1,12 @@ -#include #include "ckdl-cat.h" +#include -#include #include +#include #include -static size_t read_func(void *user_data, char *buf, size_t bufsize); -static size_t write_func(void *user_data, char const *data, size_t nbytes); +static size_t read_func(void* user_data, char* buf, size_t bufsize); +static size_t write_func(void* user_data, char const* data, size_t nbytes); struct proplist { struct prop { @@ -14,28 +14,28 @@ struct proplist { kdl_value value; kdl_owned_string val_str; kdl_owned_string type_str; - } *props; + }* props; size_t count; size_t size; }; -static void proplist_clear(struct proplist *pl); -static void proplist_append(struct proplist *pl, kdl_str name, kdl_value const* value); -static KDL_NODISCARD bool proplist_emit(kdl_emitter *emitter, struct proplist *pl); +static void proplist_clear(struct proplist* pl); +static void proplist_append(struct proplist* pl, kdl_str name, kdl_value const* value); +static KDL_NODISCARD bool proplist_emit(kdl_emitter* emitter, struct proplist* pl); -static bool kdl_cat_impl(kdl_parser *parser, kdl_emitter *emitter); +static bool kdl_cat_impl(kdl_parser* parser, kdl_emitter* emitter); -bool kdl_cat_file_to_file(FILE *in, FILE *out) +bool kdl_cat_file_to_file(FILE* in, FILE* out) { return kdl_cat_file_to_file_opt(in, out, &KDL_DEFAULT_EMITTER_OPTIONS); } -bool kdl_cat_file_to_file_opt(FILE *in, FILE *out, kdl_emitter_options const *opt) +bool kdl_cat_file_to_file_opt(FILE* in, FILE* out, kdl_emitter_options const* opt) { bool ok = true; - kdl_parser *parser = kdl_create_stream_parser(&read_func, (void*)in, KDL_DEFAULTS); - kdl_emitter *emitter = kdl_create_stream_emitter(&write_func, (void*)out, opt); + kdl_parser* parser = kdl_create_stream_parser(&read_func, (void*)in, KDL_DEFAULTS); + kdl_emitter* emitter = kdl_create_stream_emitter(&write_func, (void*)out, opt); if (parser == NULL || emitter == NULL) { ok = false; @@ -48,17 +48,17 @@ bool kdl_cat_file_to_file_opt(FILE *in, FILE *out, kdl_emitter_options const *op return ok; } -kdl_owned_string kdl_cat_file_to_string(FILE *in) +kdl_owned_string kdl_cat_file_to_string(FILE* in) { return kdl_cat_file_to_string_opt(in, &KDL_DEFAULT_EMITTER_OPTIONS); } -kdl_owned_string kdl_cat_file_to_string_opt(FILE *in, kdl_emitter_options const *opt) +kdl_owned_string kdl_cat_file_to_string_opt(FILE* in, kdl_emitter_options const* opt) { - kdl_owned_string result = { NULL, 0 }; + kdl_owned_string result = {NULL, 0}; - kdl_parser *parser = kdl_create_stream_parser(&read_func, (void*)in, KDL_DEFAULTS); - kdl_emitter *emitter = kdl_create_buffering_emitter(opt); + kdl_parser* parser = kdl_create_stream_parser(&read_func, (void*)in, KDL_DEFAULTS); + kdl_emitter* emitter = kdl_create_buffering_emitter(opt); bool ok = true; if (parser == NULL || emitter == NULL) { @@ -77,14 +77,14 @@ kdl_owned_string kdl_cat_file_to_string_opt(FILE *in, kdl_emitter_options const return result; } -static bool kdl_cat_impl(kdl_parser *parser, kdl_emitter *emitter) +static bool kdl_cat_impl(kdl_parser* parser, kdl_emitter* emitter) { // state bool in_node_list = true; - struct proplist props = { NULL, 0, 0 }; + struct proplist props = {NULL, 0, 0}; while (true) { - kdl_event_data *ev = kdl_parser_next_event(parser); + kdl_event_data* ev = kdl_parser_next_event(parser); switch (ev->event) { case KDL_EVENT_EOF: if (!kdl_emit_end(emitter)) return false; @@ -127,30 +127,30 @@ static bool kdl_cat_impl(kdl_parser *parser, kdl_emitter *emitter) } } -static size_t read_func(void *user_data, char *buf, size_t bufsize) +static size_t read_func(void* user_data, char* buf, size_t bufsize) { - FILE *fp = (FILE *)user_data; + FILE* fp = (FILE*)user_data; return fread(buf, 1, bufsize, fp); } -static size_t write_func(void *user_data, char const *data, size_t nbytes) +static size_t write_func(void* user_data, char const* data, size_t nbytes) { - FILE *fp = (FILE *)user_data; + FILE* fp = (FILE*)user_data; return fwrite(data, 1, nbytes, fp); } -static void free_prop(struct prop *p) +static void free_prop(struct prop* p) { kdl_free_string(&p->name); kdl_free_string(&p->type_str); kdl_free_string(&p->val_str); } -static void proplist_clear(struct proplist *pl) +static void proplist_clear(struct proplist* pl) { if (pl->props != NULL) { for (size_t i = 0; i < pl->count; ++i) { - struct prop *p = &pl->props[i]; + struct prop* p = &pl->props[i]; free_prop(p); } free(pl->props); @@ -160,18 +160,18 @@ static void proplist_clear(struct proplist *pl) pl->size = 0; } -static void proplist_append(struct proplist *pl, kdl_str name, kdl_value const* value) +static void proplist_append(struct proplist* pl, kdl_str name, kdl_value const* value) { if (pl->size <= pl->count) { pl->size = pl->count + 10; - struct prop *props = realloc(pl->props, pl->size * sizeof(struct prop)); + struct prop* props = realloc(pl->props, pl->size * sizeof(struct prop)); if (props != NULL) { pl->props = props; } else { return; } } - struct prop *p = &pl->props[pl->count++]; + struct prop* p = &pl->props[pl->count++]; p->name = kdl_clone_str(&name); p->value = *value; @@ -180,38 +180,37 @@ static void proplist_append(struct proplist *pl, kdl_str name, kdl_value const* p->type_str = kdl_clone_str(&p->value.type_annotation); p->value.type_annotation = kdl_borrow_str(&p->type_str); } else { - p->type_str = (kdl_owned_string){ NULL, 0 }; + p->type_str = (kdl_owned_string){NULL, 0}; } // clone string value (if needed) if (p->value.type == KDL_TYPE_STRING) { p->val_str = kdl_clone_str(&p->value.string); p->value.string = kdl_borrow_str(&p->val_str); - } else if (p->value.type == KDL_TYPE_NUMBER - && p->value.number.type == KDL_NUMBER_TYPE_STRING_ENCODED) { + } else if (p->value.type == KDL_TYPE_NUMBER && p->value.number.type == KDL_NUMBER_TYPE_STRING_ENCODED) { p->val_str = kdl_clone_str(&p->value.number.string); p->value.number.string = kdl_borrow_str(&p->val_str); } else { - p->val_str = (kdl_owned_string){ NULL, 0 }; + p->val_str = (kdl_owned_string){NULL, 0}; } } -static struct prop *overwriting_merge(struct prop *out, - struct prop *left, struct prop *right, struct prop *end); +static struct prop* overwriting_merge( + struct prop* out, struct prop* left, struct prop* right, struct prop* end); -static bool proplist_emit(kdl_emitter *emitter, struct proplist *pl) +static bool proplist_emit(kdl_emitter* emitter, struct proplist* pl) { // We need to emit the properties without duplicates, in lexical order // do a merge sort which overwrites duplicates - struct prop *props = pl->props; - struct prop *dest = malloc(sizeof(struct prop) * pl->count); + struct prop* props = pl->props; + struct prop* dest = malloc(sizeof(struct prop) * pl->count); if (dest == NULL) { return false; } size_t count = pl->count; for (size_t wnd = 1; wnd < count; wnd *= 2) { - struct prop *out_end = dest; + struct prop* out_end = dest; for (size_t i = 0; i < count; i += 2 * wnd) { size_t r = i + wnd; size_t e = r + wnd; @@ -226,7 +225,7 @@ static bool proplist_emit(kdl_emitter *emitter, struct proplist *pl) ++out_end; } } - struct prop *tmp = dest; + struct prop* tmp = dest; dest = props; props = tmp; } @@ -236,7 +235,7 @@ static bool proplist_emit(kdl_emitter *emitter, struct proplist *pl) free(dest); for (size_t i = 0; i < count; ++i) { - struct prop *p = &props[i]; + struct prop* p = &props[i]; if (p->name.data != NULL) if (!kdl_emit_property(emitter, kdl_borrow_str(&p->name), &p->value)) return false; } @@ -244,7 +243,7 @@ static bool proplist_emit(kdl_emitter *emitter, struct proplist *pl) return true; } -static int kdl_str_cmp(kdl_owned_string const *s1, kdl_owned_string const *s2) +static int kdl_str_cmp(kdl_owned_string const* s1, kdl_owned_string const* s2) { // sort NULL at the end if (s1->data == NULL) return 1; @@ -257,13 +256,13 @@ static int kdl_str_cmp(kdl_owned_string const *s1, kdl_owned_string const *s2) return cmp; } -static struct prop *overwriting_merge(struct prop *out, - struct prop *left, struct prop *right, struct prop *end) +static struct prop* overwriting_merge( + struct prop* out, struct prop* left, struct prop* right, struct prop* end) { - struct prop *boundary = right; - struct prop *prev = NULL; + struct prop* boundary = right; + struct prop* prev = NULL; while (left < boundary || right < end) { - struct prop *next_item; + struct prop* next_item; if (left >= boundary) { next_item = right++; } else if (right >= end) { diff --git a/src/utils/ckdl-cat.h b/src/utils/ckdl-cat.h index f79c521..ee06f05 100644 --- a/src/utils/ckdl-cat.h +++ b/src/utils/ckdl-cat.h @@ -4,12 +4,12 @@ #include #include -#include #include +#include -bool kdl_cat_file_to_file(FILE *in, FILE *out); -bool kdl_cat_file_to_file_opt(FILE *in, FILE *out, kdl_emitter_options const *opt); -kdl_owned_string kdl_cat_file_to_string(FILE *in); -kdl_owned_string kdl_cat_file_to_string_opt(FILE *in, kdl_emitter_options const *opt); +bool kdl_cat_file_to_file(FILE* in, FILE* out); +bool kdl_cat_file_to_file_opt(FILE* in, FILE* out, kdl_emitter_options const* opt); +kdl_owned_string kdl_cat_file_to_string(FILE* in); +kdl_owned_string kdl_cat_file_to_string_opt(FILE* in, kdl_emitter_options const* opt); #endif // CKDL_CAT_H_ diff --git a/src/utils/ckdl-parse-events.c b/src/utils/ckdl-parse-events.c index 0572516..54b89a4 100644 --- a/src/utils/ckdl-parse-events.c +++ b/src/utils/ckdl-parse-events.c @@ -1,33 +1,32 @@ #include -#include -#include #include #include +#include +#include -static size_t read_func(void *user_data, char *buf, size_t bufsize) +static size_t read_func(void* user_data, char* buf, size_t bufsize) { - FILE *fp = (FILE*) user_data; + FILE* fp = (FILE*)user_data; return fread(buf, 1, bufsize, fp); } -static size_t write_func(void *user_data, char const *data, size_t nbytes) +static size_t write_func(void* user_data, char const* data, size_t nbytes) { (void)user_data; return fwrite(data, 1, nbytes, stdout); } -void print_usage(char const *argv0, FILE *fp) +void print_usage(char const* argv0, FILE* fp) { fprintf(fp, "Usage: %s [-h] [-c]\n\n", argv0); fprintf(fp, " -h Print usage information\n"); fprintf(fp, " -c Emit comments\n"); } - -int main(int argc, char **argv) +int main(int argc, char** argv) { - FILE *in = stdin; + FILE* in = stdin; char const* argv0 = argv[0]; kdl_parse_option parse_opts = KDL_DEFAULTS; bool opts_ended = false; @@ -36,7 +35,7 @@ int main(int argc, char **argv) ++argv; if (!opts_ended && **argv == '-') { // options - for (char const *p = *argv+1; *p; ++p) { + for (char const* p = *argv + 1; *p; ++p) { if (*p == 'h') { print_usage(argv0, stdout); return 0; @@ -50,18 +49,17 @@ int main(int argc, char **argv) } } } else { - char const *fn = *argv; + char const* fn = *argv; in = fopen(fn, "r"); if (in == NULL) { - fprintf(stderr, "Error opening file \"%s\": %s\n", - fn, strerror(errno)); + fprintf(stderr, "Error opening file \"%s\": %s\n", fn, strerror(errno)); return 1; } } } - kdl_parser *parser = kdl_create_stream_parser(&read_func, (void*)in, parse_opts); - kdl_emitter *emitter = kdl_create_stream_emitter(&write_func, NULL, &KDL_DEFAULT_EMITTER_OPTIONS); + kdl_parser* parser = kdl_create_stream_parser(&read_func, (void*)in, parse_opts); + kdl_emitter* emitter = kdl_create_stream_emitter(&write_func, NULL, &KDL_DEFAULT_EMITTER_OPTIONS); if (parser == NULL || emitter == NULL) { fprintf(stderr, "Initialization error\n"); @@ -69,16 +67,16 @@ int main(int argc, char **argv) } // constants - kdl_str const slashdash_type_str = (kdl_str){ "commented-out", 13 }; - kdl_str const value_str = (kdl_str){ "value", 5 }; - kdl_str const name_str = (kdl_str){ "name", 4 }; + kdl_str const slashdash_type_str = (kdl_str){"commented-out", 13}; + kdl_str const value_str = (kdl_str){"value", 5}; + kdl_str const name_str = (kdl_str){"name", 4}; bool have_error = false; bool eof = false; bool slashdash = false; while (1) { - kdl_event_data *event = kdl_parser_next_event(parser); - char const *event_name = NULL; + kdl_event_data* event = kdl_parser_next_event(parser); + char const* event_name = NULL; if (event->event == KDL_EVENT_COMMENT) { // regular comment @@ -124,17 +122,15 @@ int main(int argc, char **argv) (void)kdl_emit_node(emitter, event_name_str); } if (event->name.data != NULL) { - kdl_value name_val = (kdl_value) { - .type = KDL_TYPE_STRING, - .type_annotation = { NULL, 0 }, - .string = event->name + kdl_value name_val = (kdl_value){ + .type = KDL_TYPE_STRING, .type_annotation = {NULL, 0}, + .string = event->name }; (void)kdl_emit_property(emitter, name_str, &name_val); } (void)kdl_emit_property(emitter, value_str, &event->value); - if (have_error || eof) break; } diff --git a/src/utils/ckdl-tokenize.c b/src/utils/ckdl-tokenize.c index 8d0c925..e61b5f2 100644 --- a/src/utils/ckdl-tokenize.c +++ b/src/utils/ckdl-tokenize.c @@ -1,36 +1,35 @@ #include -#include -#include #include #include +#include +#include -static size_t read_func(void *user_data, char *buf, size_t bufsize) +static size_t read_func(void* user_data, char* buf, size_t bufsize) { - FILE *fp = (FILE*) user_data; + FILE* fp = (FILE*)user_data; return fread(buf, 1, bufsize, fp); } -static size_t write_func(void *user_data, char const *data, size_t nbytes) +static size_t write_func(void* user_data, char const* data, size_t nbytes) { (void)user_data; return fwrite(data, 1, nbytes, stdout); } -int main(int argc, char **argv) +int main(int argc, char** argv) { - FILE *in = NULL; + FILE* in = NULL; if (argc == 1) { in = stdin; } else if (argc == 2) { - char const *fn = argv[1]; + char const* fn = argv[1]; if (strcmp(fn, "-") == 0) { in = stdin; } else { in = fopen(fn, "r"); if (in == NULL) { - fprintf(stderr, "Error opening file \"%s\": %s\n", - fn, strerror(errno)); + fprintf(stderr, "Error opening file \"%s\": %s\n", fn, strerror(errno)); return 1; } } @@ -39,8 +38,8 @@ int main(int argc, char **argv) return 2; } - kdl_tokenizer *tokenizer = kdl_create_stream_tokenizer(&read_func, (void*)in); - kdl_emitter *emitter = kdl_create_stream_emitter(&write_func, NULL, &KDL_DEFAULT_EMITTER_OPTIONS); + kdl_tokenizer* tokenizer = kdl_create_stream_tokenizer(&read_func, (void*)in); + kdl_emitter* emitter = kdl_create_stream_emitter(&write_func, NULL, &KDL_DEFAULT_EMITTER_OPTIONS); if (tokenizer == NULL || emitter == NULL) { fprintf(stderr, "Initialization error\n"); @@ -60,7 +59,7 @@ int main(int argc, char **argv) break; } - char const *token_type_name = NULL; + char const* token_type_name = NULL; switch (token.type) { case KDL_TOKEN_START_TYPE: token_type_name = "KDL_TOKEN_START_TYPE"; @@ -118,10 +117,7 @@ int main(int argc, char **argv) } (void)kdl_emit_node(emitter, kdl_str_from_cstr(token_type_name)); - kdl_value val = (kdl_value){ - .type = KDL_TYPE_STRING, - .string = token.value - }; + kdl_value val = (kdl_value){.type = KDL_TYPE_STRING, .string = token.value}; (void)kdl_emit_arg(emitter, &val); } diff --git a/tests/emitter_test.c b/tests/emitter_test.c index 87ee45a..82089c9 100644 --- a/tests/emitter_test.c +++ b/tests/emitter_test.c @@ -2,23 +2,22 @@ #include "test_util.h" -#include #include +#include static void test_basics(void) { kdl_emitter_options emitter_opt = KDL_DEFAULT_EMITTER_OPTIONS; emitter_opt.indent = 3; emitter_opt.float_mode.always_write_decimal_point_or_exponent = false; - kdl_emitter *emitter = kdl_create_buffering_emitter(&emitter_opt); + kdl_emitter* emitter = kdl_create_buffering_emitter(&emitter_opt); - char const *expected = - "\xf0\x9f\x92\xa9\n" - "node2 {\n" - " \"first child\" 1 a=\"b\"\n" - " (ta)second-child\n" - "}\n" - "node3\n"; + char const* expected = "\xf0\x9f\x92\xa9\n" + "node2 {\n" + " \"first child\" 1 a=\"b\"\n" + " (ta)second-child\n" + "}\n" + "node3\n"; kdl_str expected_str = kdl_str_from_cstr(expected); ASSERT(kdl_emit_node(emitter, kdl_str_from_cstr("\xf0\x9f\x92\xa9"))); @@ -27,11 +26,8 @@ static void test_basics(void) ASSERT(kdl_emit_node(emitter, kdl_str_from_cstr("first child"))); kdl_value v; v.type = KDL_TYPE_NUMBER; - v.type_annotation = (kdl_str){ NULL, 0 }; - v.number = (kdl_number) { - .type = KDL_NUMBER_TYPE_FLOATING_POINT, - .floating_point = 1.0 - }; + v.type_annotation = (kdl_str){NULL, 0}; + v.number = (kdl_number){.type = KDL_NUMBER_TYPE_FLOATING_POINT, .floating_point = 1.0}; ASSERT(kdl_emit_arg(emitter, &v)); v.type = KDL_TYPE_STRING; v.string = kdl_str_from_cstr("b"); @@ -50,35 +46,25 @@ static void test_basics(void) static void test_data_types(void) { - kdl_emitter *emitter = kdl_create_buffering_emitter(&KDL_DEFAULT_EMITTER_OPTIONS); + kdl_emitter* emitter = kdl_create_buffering_emitter(&KDL_DEFAULT_EMITTER_OPTIONS); ASSERT(emitter); ASSERT(kdl_emit_node(emitter, kdl_str_from_cstr("-"))); - ASSERT(kdl_emit_arg(emitter, &(kdl_value){ - .type = KDL_TYPE_NUMBER, - .number = (kdl_number){ .type = KDL_NUMBER_TYPE_INTEGER, .integer = -100 } - })); - ASSERT(kdl_emit_arg(emitter, &(kdl_value){ - .type = KDL_TYPE_STRING, - .string = kdl_str_from_cstr("abc") - })); - ASSERT(kdl_emit_arg(emitter, &(kdl_value){ - .type = KDL_TYPE_BOOLEAN, - .boolean = true - })); - ASSERT(kdl_emit_arg(emitter, &(kdl_value){ - .type = KDL_TYPE_BOOLEAN, - .boolean = false - })); - ASSERT(kdl_emit_arg(emitter, &(kdl_value){ - .type = KDL_TYPE_NULL + ASSERT(kdl_emit_arg(emitter, + &(kdl_value){ + .type = KDL_TYPE_NUMBER, + .number = (kdl_number){.type = KDL_NUMBER_TYPE_INTEGER, .integer = -100} })); + ASSERT(kdl_emit_arg(emitter, &(kdl_value){.type = KDL_TYPE_STRING, .string = kdl_str_from_cstr("abc")})); + ASSERT(kdl_emit_arg(emitter, &(kdl_value){.type = KDL_TYPE_BOOLEAN, .boolean = true})); + ASSERT(kdl_emit_arg(emitter, &(kdl_value){.type = KDL_TYPE_BOOLEAN, .boolean = false})); + ASSERT(kdl_emit_arg(emitter, &(kdl_value){.type = KDL_TYPE_NULL})); ASSERT(kdl_emit_end(emitter)); kdl_str result = kdl_get_emitter_buffer(emitter); - char const *expected = "- -100 \"abc\" true false null\n"; + char const* expected = "- -100 \"abc\" true false null\n"; kdl_str expected_str = kdl_str_from_cstr(expected); ASSERT(expected_str.len == result.len); ASSERT(memcmp(result.data, expected_str.data, result.len) == 0); diff --git a/tests/example_doc_test.c b/tests/example_doc_test.c index e856210..fee1195 100644 --- a/tests/example_doc_test.c +++ b/tests/example_doc_test.c @@ -1,38 +1,38 @@ -#include "test_util.h" #include "fs_util.h" +#include "test_util.h" #include "ckdl-cat.h" // Std C +#include #include -#include #include -#include +#include // UNIX and Windows-specific file APIs #if defined(CHDIR_IN_UNISTD_H) -#include +# include #elif defined(CHDIR_IN_DIRECT_H) -#include +# include #endif #include #include -static int strcmp_p(void const *s1, void const *s2) +static int strcmp_p(void const* s1, void const* s2) { - char const *const *s1_ = (char const *const *)s1; - char const *const *s2_ = (char const *const *)s2; + char const* const* s1_ = (char const* const*)s1; + char const* const* s2_ = (char const* const*)s2; return strcmp(*s1_, *s2_); } struct test_case { - char const *input_path; - char const *ground_truth_path; + char const* input_path; + char const* ground_truth_path; bool ignore_output; }; -static void do_test_case(void *user_data) +static void do_test_case(void* user_data) { // configure float output to match kdl4j's test suite kdl_emitter_options test_opts = KDL_DEFAULT_EMITTER_OPTIONS; @@ -40,8 +40,8 @@ static void do_test_case(void *user_data) test_opts.float_mode.always_write_decimal_point = true; test_opts.float_mode.exponent_plus = true; - struct test_case *tc = (struct test_case *)user_data; - FILE *in = fopen(tc->input_path, "r"); + struct test_case* tc = (struct test_case*)user_data; + FILE* in = fopen(tc->input_path, "r"); ASSERT(in != NULL); kdl_owned_string s = kdl_cat_file_to_string_opt(in, &test_opts); if (tc->ground_truth_path == NULL) { @@ -50,14 +50,13 @@ static void do_test_case(void *user_data) } else { // should parse with no issue ASSERT2(s.data != NULL, "Parsing should not fail"); - if (!tc->ignore_output) - { + if (!tc->ignore_output) { // compare results - FILE *gt_fp = fopen(tc->ground_truth_path, "r"); + FILE* gt_fp = fopen(tc->ground_truth_path, "r"); fseek(gt_fp, 0, SEEK_END); long filelen = ftell(gt_fp); fseek(gt_fp, 0, SEEK_SET); - char *buf = malloc(filelen + 1); + char* buf = malloc(filelen + 1); // fread is guaranteed to read the max, but due to Windows CRLF // translation this may be less than the file length. // We actually *want* CRLF translation here in order to compare @@ -78,7 +77,7 @@ static void do_test_case(void *user_data) void TEST_MAIN(void) { // figure out where the test data is - char const *test_cases_root; + char const* test_cases_root; if (test_argc() == 2) { test_cases_root = test_arg(1); } else { @@ -86,13 +85,12 @@ void TEST_MAIN(void) } // prepare the list of fuzzy test cases (don't compare output) - char *excl_buf = strdup(FUZZY_KDL_TESTS); + char* excl_buf = strdup(FUZZY_KDL_TESTS); size_t n_fuzzy = 0; if (*excl_buf) ++n_fuzzy; - for (char *p = excl_buf; *p; ++p) - if (*p == ':') - ++n_fuzzy; - char **fuzzy_test_cases = malloc(n_fuzzy * sizeof(char *)); + for (char* p = excl_buf; *p; ++p) + if (*p == ':') ++n_fuzzy; + char** fuzzy_test_cases = malloc(n_fuzzy * sizeof(char*)); fuzzy_test_cases[0] = excl_buf; for (char *p = excl_buf, **e = &fuzzy_test_cases[1]; *p; ++p) { if (*p == ':') { @@ -105,18 +103,18 @@ void TEST_MAIN(void) // get file names size_t l = strlen(test_cases_root); - if (test_cases_root[l-1] == '/') --l; - char *input_dir = malloc(l + 16); - char *expected_kdl_fn = malloc(l + 500); + if (test_cases_root[l - 1] == '/') --l; + char* input_dir = malloc(l + 16); + char* expected_kdl_fn = malloc(l + 500); memcpy(input_dir, test_cases_root, l); memcpy(expected_kdl_fn, test_cases_root, l); strncpy(input_dir + l, "/input", 16); strncpy(expected_kdl_fn + l, "/expected_kdl/", 500); size_t expected_kdl_dirname_len = strlen(expected_kdl_fn); - char *expected_basename_ptr = expected_kdl_fn + expected_kdl_dirname_len; + char* expected_basename_ptr = expected_kdl_fn + expected_kdl_dirname_len; size_t expected_basename_avail = (l + 500) - expected_kdl_dirname_len; - char **filenames; + char** filenames; size_t n_files; get_files_in_dir(input_dir, &filenames, &n_files, true); diff --git a/tests/fs_util.c b/tests/fs_util.c index 64018bc..3912ca6 100644 --- a/tests/fs_util.c +++ b/tests/fs_util.c @@ -1,87 +1,87 @@ #include "fs_util.h" #if defined(HAVE_DIRENT) -# include +# include #elif defined(HAVE_WIN32_FILE_API) // MSVC generates warnings in Windows.h, which, frankly, is just embarrassing -# ifdef _MSC_VER -# pragma warning(push, 0) -# endif -# include -# ifdef _MSC_VER -# pragma warning(pop) -# endif +# ifdef _MSC_VER +# pragma warning(push, 0) +# endif +# include +# ifdef _MSC_VER +# pragma warning(pop) +# endif #endif +#include #include #include -#include #include #if defined(HAVE_DIRENT) -#include +# include -static inline bool is_regular_file(DIR *d, struct dirent *de) +static inline bool is_regular_file(DIR* d, struct dirent* de) { struct stat st; int dfd; -#ifdef HAVE_DIRENT_D_TYPE +# ifdef HAVE_DIRENT_D_TYPE switch (de->d_type) { case DT_REG: return true; case DT_UNKNOWN: -#endif +# endif // must stat dfd = dirfd(d); fstatat(dfd, de->d_name, &st, AT_SYMLINK_NOFOLLOW); return (st.st_mode & S_IFREG) != 0; -#ifdef HAVE_DIRENT_D_TYPE +# ifdef HAVE_DIRENT_D_TYPE default: return false; } -#endif +# endif } #elif defined(HAVE_WIN32_FILE_API) -static inline BOOL is_regular_file(WIN32_FIND_DATAA const *find_data) +static inline BOOL is_regular_file(WIN32_FIND_DATAA const* find_data) { return (find_data->dwFileAttributes & (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_DEVICE)) == 0; } #endif -void get_files_in_dir(char const *dir_path, char ***filelist, size_t *n_files, bool regular_only) +void get_files_in_dir(char const* dir_path, char*** filelist, size_t* n_files, bool regular_only) { size_t list_buf_len = 4096; - char *list_buf = malloc(list_buf_len); + char* list_buf = malloc(list_buf_len); if (list_buf == NULL) goto error; - char *list_ptr = list_buf; - char *list_buf_tmp; + char* list_ptr = list_buf; + char* list_buf_tmp; size_t count = 0; #if defined(HAVE_DIRENT) - DIR *dir_p = opendir(dir_path); + DIR* dir_p = opendir(dir_path); if (dir_p == NULL) goto error; - struct dirent *de; + struct dirent* de; while ((de = readdir(dir_p)) != NULL) { if (!regular_only || is_regular_file(dir_p, de)) { - char const *fn = de->d_name; + char const* fn = de->d_name; #elif defined(HAVE_WIN32_FILE_API) WIN32_FIND_DATAA find_data; // prepare a glob pattern for FindFile size_t dir_path_len = strlen(dir_path); - char *glob = malloc(dir_path_len + 3); + char* glob = malloc(dir_path_len + 3); if (glob == NULL) goto error; memcpy(glob, dir_path, dir_path_len); memcpy(glob + dir_path_len, "/*", 3); HANDLE h_find = FindFirstFileA(glob, &find_data); while (h_find != INVALID_HANDLE_VALUE) { if (!regular_only || is_regular_file(&find_data)) { - char const *fn = find_data.cFileName; + char const* fn = find_data.cFileName; #endif // HAVE_DIRENT / HAVE_WIN32_FILE_API @@ -138,10 +138,11 @@ void get_files_in_dir(char const *dir_path, char ***filelist, size_t *n_files, b memmove(list_ptr, list_buf, data_len); // Write the array - char **list = (char**)list_buf; + char** list = (char**)list_buf; for (size_t i = 0; i < count; ++i) { list[i] = list_ptr; - while (*(list_ptr++) != 0); + while (*(list_ptr++) != 0) + ; } // Return it diff --git a/tests/fs_util.h b/tests/fs_util.h index 6e22a84..4b87be1 100644 --- a/tests/fs_util.h +++ b/tests/fs_util.h @@ -4,6 +4,6 @@ #include #include -void get_files_in_dir(char const *dir_path, char ***filelist, size_t *n_files, bool regular_only); +void get_files_in_dir(char const* dir_path, char*** filelist, size_t* n_files, bool regular_only); #endif // KDL_TEST_FS_UTIL_H_ diff --git a/tests/parser_test.c b/tests/parser_test.c index 3da8c03..19538a3 100644 --- a/tests/parser_test.c +++ b/tests/parser_test.c @@ -6,19 +6,18 @@ static void test_basics(void) { - char const *const kdl_text = - "node1 key=0x123 \"gar\xc3\xa7on\" ;" - "node2 \\ // COMMENT\n" - " \"gar\\u{e7}on\"\n" - "node3 { (t)child1; child2\n" - "child3 }"; - char const *const garcon = "gar\xc3\xa7on"; + char const* const kdl_text = "node1 key=0x123 \"gar\xc3\xa7on\" ;" + "node2 \\ // COMMENT\n" + " \"gar\\u{e7}on\"\n" + "node3 { (t)child1; child2\n" + "child3 }"; + char const* const garcon = "gar\xc3\xa7on"; kdl_str doc = kdl_str_from_cstr(kdl_text); - kdl_parser *parser = kdl_create_string_parser(doc, 0); + kdl_parser* parser = kdl_create_string_parser(doc, 0); // test all events - kdl_event_data *ev; + kdl_event_data* ev; ev = kdl_parser_next_event(parser); ASSERT(ev->event == KDL_EVENT_START_NODE); @@ -104,16 +103,15 @@ static void test_basics(void) static void test_slashdash(void) { - char const *const kdl_text = - "node1 /-key=0x123\n" - "/- node2 { (t)child1; child2; child3 }\n" - "node3"; + char const* const kdl_text = "node1 /-key=0x123\n" + "/- node2 { (t)child1; child2; child3 }\n" + "node3"; kdl_str doc = kdl_str_from_cstr(kdl_text); - kdl_parser *parser = kdl_create_string_parser(doc, 0); + kdl_parser* parser = kdl_create_string_parser(doc, 0); // test all events - kdl_event_data *ev; + kdl_event_data* ev; ev = kdl_parser_next_event(parser); ASSERT(ev->event == KDL_EVENT_START_NODE); @@ -192,14 +190,13 @@ static void test_slashdash(void) static void test_unbalanced_brace(void) { - char const *const kdl_text = - "node1 {"; + char const* const kdl_text = "node1 {"; kdl_str doc = kdl_str_from_cstr(kdl_text); - kdl_parser *parser = kdl_create_string_parser(doc, 0); + kdl_parser* parser = kdl_create_string_parser(doc, 0); // test all events - kdl_event_data *ev; + kdl_event_data* ev; ev = kdl_parser_next_event(parser); ASSERT(ev->event == KDL_EVENT_START_NODE); @@ -212,14 +209,13 @@ static void test_unbalanced_brace(void) static void test_identifier_arg(void) { - char const *const kdl_text = - "node1 \"arg1\" arg2"; + char const* const kdl_text = "node1 \"arg1\" arg2"; kdl_str doc = kdl_str_from_cstr(kdl_text); - kdl_parser *parser = kdl_create_string_parser(doc, 0); + kdl_parser* parser = kdl_create_string_parser(doc, 0); // test all events - kdl_event_data *ev; + kdl_event_data* ev; ev = kdl_parser_next_event(parser); ASSERT(ev->event == KDL_EVENT_START_NODE); @@ -235,14 +231,13 @@ static void test_identifier_arg(void) static void test_number_type(void) { - char const *const kdl_text = - "node1; (12)node2;"; + char const* const kdl_text = "node1; (12)node2;"; kdl_str doc = kdl_str_from_cstr(kdl_text); - kdl_parser *parser = kdl_create_string_parser(doc, 0); + kdl_parser* parser = kdl_create_string_parser(doc, 0); // test all events - kdl_event_data *ev; + kdl_event_data* ev; ev = kdl_parser_next_event(parser); ASSERT(ev->event == KDL_EVENT_START_NODE); @@ -264,4 +259,3 @@ void TEST_MAIN(void) run_test("Parser: arg can't be identifier", &test_identifier_arg); run_test("Parser: type can't be number", &test_number_type); } - diff --git a/tests/test_util.c b/tests/test_util.c index f43659c..4f6dbfa 100644 --- a/tests/test_util.c +++ b/tests/test_util.c @@ -1,14 +1,14 @@ #include "test_util.h" -#include #include +#include #include static jmp_buf run_test_env; static bool run_test_active = false; static int failures = 0; -void assert_true(bool assertion, char const *assertion_s, char const *context) +void assert_true(bool assertion, char const* assertion_s, char const* context) { if (assertion) { return; @@ -29,12 +29,9 @@ static void _call_noarg_test(void* func_ptr_ptr) func(); } -void run_test(char const *name, void (*func)(void)) -{ - run_test_d(name, _call_noarg_test, (void*)(&func)); -} +void run_test(char const* name, void (*func)(void)) { run_test_d(name, _call_noarg_test, (void*)(&func)); } -void run_test_d(char const *name, void (*func)(void *), void *user_data) +void run_test_d(char const* name, void (*func)(void*), void* user_data) { fprintf(stderr, "TEST %s\n", name); run_test_active = true; @@ -54,22 +51,16 @@ void run_test_d(char const *name, void (*func)(void *), void *user_data) } static int ARGC; -static char const *const *ARGV; +static char const* const* ARGV; -int test_argc(void) -{ - return ARGC; -} +int test_argc(void) { return ARGC; } -char const *test_arg(int idx) -{ - return ARGV[idx]; -} +char const* test_arg(int idx) { return ARGV[idx]; } -int main(int argc, char **argv) +int main(int argc, char** argv) { ARGC = argc; - ARGV = (char const *const *)argv; + ARGV = (char const* const*)argv; TEST_MAIN(); if (failures != 0) { fprintf(stderr, "\n--- %d tests failed ---\n", failures); diff --git a/tests/test_util.h b/tests/test_util.h index 53aca16..abd32ab 100644 --- a/tests/test_util.h +++ b/tests/test_util.h @@ -9,15 +9,15 @@ extern "C" { #define _stringify(a) _stringify_2(a) #define _stringify_2(a) #a -#define ASSERT(q) assert_true((q), #q, __FILE__ "(" _stringify(__LINE__) ")") -#define ASSERT2(q, msg) assert_true((q), msg, __FILE__ "(" _stringify(__LINE__) ")") -void assert_true(bool assertion, char const *assertion_s, char const *context); +#define ASSERT(q) assert_true((q), #q, __FILE__ "(" _stringify(__LINE__) ")") +#define ASSERT2(q, msg) assert_true((q), msg, __FILE__ "(" _stringify(__LINE__) ")") +void assert_true(bool assertion, char const* assertion_s, char const* context); -void run_test(char const *name, void (*func)(void)); -void run_test_d(char const *name, void (*func)(void *), void *user_data); +void run_test(char const* name, void (*func)(void)); +void run_test_d(char const* name, void (*func)(void*), void* user_data); int test_argc(void); -char const *test_arg(int idx); +char const* test_arg(int idx); extern void TEST_MAIN(void); diff --git a/tests/utf8_test.c b/tests/utf8_test.c index 0134bde..8bd6c86 100644 --- a/tests/utf8_test.c +++ b/tests/utf8_test.c @@ -2,8 +2,8 @@ #include "test_util.h" -#include #include +#include static char ASCII_IN[] = "abcd1234"; static uint32_t ASCII_OUT[] = {0x61, 0x62, 0x63, 0x64, 0x31, 0x32, 0x33, 0x34}; @@ -14,14 +14,16 @@ static uint32_t ASCII_CONTROL_OUT[] = {0x20, 0xa, 0x0, 0x9, 0x7}; static char LATIN1_IN[] = "\xc3\xa5ngstr\xc3\xb6m"; static uint32_t LATIN1_OUT[] = {0xe5, 0x6e, 0x67, 0x73, 0x74, 0x72, 0xf6, 0x6d}; -static char RUSSIAN_IN[] = "\xd0\x94. \xd0\x98. \xd0\x9c\xd0\xb5\xd0\xbd\xd0\xb4\xd0\xb5\xd0\xbb\xd0\xb5\xd0\xb5\xd0\xb2"; -static uint32_t RUSSIAN_OUT[] = {0x414, 0x2e, 0x20, 0x418, 0x2e, 0x20, 0x41c, 0x435, 0x43d, 0x434, 0x435, 0x43b, 0x435, 0x435, 0x432}; +static char RUSSIAN_IN[] + = "\xd0\x94. \xd0\x98. \xd0\x9c\xd0\xb5\xd0\xbd\xd0\xb4\xd0\xb5\xd0\xbb\xd0\xb5\xd0\xb5\xd0\xb2"; +static uint32_t RUSSIAN_OUT[] + = {0x414, 0x2e, 0x20, 0x418, 0x2e, 0x20, 0x41c, 0x435, 0x43d, 0x434, 0x435, 0x43b, 0x435, 0x435, 0x432}; static char EMOJI_IN[] = "\xf0\x9f\x90\xb1\xf0\x9f\xa7\xb6"; static uint32_t EMOJI_OUT[] = {0x1f431, 0x1f9f6}; // Examples with characters missing or incorrect high bits -static char const *INVALID[] = { +static char const* INVALID[] = { "\xc3\xe4", "\xc3\x24", "\xe8\x0f\xaf", @@ -30,29 +32,28 @@ static char const *INVALID[] = { "\xe8\x8f\xef", "\xf0\x1f\x92\xa9", "\xf0\x9f\xd2\xa9", - "\xf0\x9f\x92\xe9" + "\xf0\x9f\x92\xe9", }; -static char const *INCOMPLETE[] = { +static char const* INCOMPLETE[] = { "\xc3", "\xe8", "\xe8\x8f", - "\xf0\x9f\x92" + "\xf0\x9f\x92", }; +#define ASSERT_UTF8_STRING(in, out) \ + assert_utf8_string(in, sizeof(in) / sizeof(char) - 1, out, sizeof(out) / sizeof(uint32_t)) -#define ASSERT_UTF8_STRING(in,out) assert_utf8_string(in, sizeof(in)/sizeof(char) - 1, out, sizeof(out)/sizeof(uint32_t)) - -void assert_utf8_string(char const *in_ptr, size_t in_len, uint32_t const *out_ptr, size_t out_len) +void assert_utf8_string(char const* in_ptr, size_t in_len, uint32_t const* out_ptr, size_t out_len) { uint32_t codepoint; kdl_str s = {in_ptr, in_len}; - char *buf = malloc(in_len + 1); + char* buf = malloc(in_len + 1); buf[in_len] = -1; - char *buf_end = buf; + char* buf_end = buf; - for (size_t i = 0; i < out_len; ++i) - { + for (size_t i = 0; i < out_len; ++i) { ASSERT(KDL_UTF8_OK == _kdl_pop_codepoint(&s, &codepoint)); ASSERT(codepoint == out_ptr[i]); buf_end += _kdl_push_codepoint(codepoint, buf_end); @@ -76,10 +77,7 @@ static void test_utf8_bmp(void) ASSERT_UTF8_STRING(RUSSIAN_IN, RUSSIAN_OUT); } -static void test_utf8_emoji(void) -{ - ASSERT_UTF8_STRING(EMOJI_IN, EMOJI_OUT); -} +static void test_utf8_emoji(void) { ASSERT_UTF8_STRING(EMOJI_IN, EMOJI_OUT); } static void test_utf8_invalid(void) { @@ -107,5 +105,5 @@ void TEST_MAIN(void) run_test("UTF8: BMP", &test_utf8_bmp); run_test("UTF8: Emoji", &test_utf8_emoji); run_test("UTF8: Invalid", &test_utf8_invalid); - run_test("UTF8: Incomplete",&test_utf8_incomplete); + run_test("UTF8: Incomplete", &test_utf8_incomplete); }