From 82a68f09ecf2440b22c2604fe207bbee1c5f4d3a Mon Sep 17 00:00:00 2001 From: Dylan Date: Sun, 14 Jun 2026 22:24:52 +1200 Subject: feat: Added arrays for all literal types --- src/json.cpp | 30 +++++++++++++++++++----------- src/json.h | 2 ++ src/json.hpp | 19 +++++++++++++++++++ 3 files changed, 40 insertions(+), 11 deletions(-) (limited to 'src') diff --git a/src/json.cpp b/src/json.cpp index 25779b9..9d53582 100644 --- a/src/json.cpp +++ b/src/json.cpp @@ -1,4 +1,4 @@ -#include "json.h" +#include "json.hpp" #include "tokenizer.h" #include @@ -131,19 +131,27 @@ namespace TehJSON case TokenType::LSquare: { consume(TokenType::LSquare); - std::vector vec; - while(nextTokenType() != TokenType::RSquare) + switch(nextTokenType()) { - if(nextTokenType() != TokenType::IntLit) - throw std::runtime_error("Only int arrays are supported so far"); - vec.push_back(std::stoi(consume(TokenType::IntLit).content)); - if(nextTokenType() == TokenType::Comma) - { - consume(TokenType::Comma); - } + case TokenType::IntLit: + children[childName.content].set( + readVector(TokenType::IntLit, + [](std::string x){return std::stoi(x);}));break; + case TokenType::FloatLit: + children[childName.content].set( + readVector(TokenType::FloatLit, + [](std::string x){return std::stof(x);}));break; + case TokenType::StringLit: + children[childName.content].set( + readVector( + TokenType::StringLit, [](std::string x){return x;}));break; + case TokenType::BoolLit: + children[childName.content].set( + readVector( + TokenType::BoolLit, [](std::string x){return x=="true";}));break; + default: throw std::runtime_error("Arrays can only be of literals so far"); } consume(TokenType::RSquare); - children[childName.content].set(vec); break; }; default: throw std::runtime_error("Token type is not a literal!"); diff --git a/src/json.h b/src/json.h index 0e616e3..78bcee3 100644 --- a/src/json.h +++ b/src/json.h @@ -51,6 +51,8 @@ namespace TehJSON Token consume(TokenType type); TokenType nextTokenType(); void readFromTokens(std::vector tokens); + template + std::vector readVector(TokenType type, T(*)(const std::string)); // Leaf data fields std::shared_ptr data; diff --git a/src/json.hpp b/src/json.hpp index 8ecd947..fb3a0b0 100644 --- a/src/json.hpp +++ b/src/json.hpp @@ -1,3 +1,5 @@ +#pragma once + #include "json.h" #include @@ -53,4 +55,21 @@ namespace TehJSON }; data = std::make_shared(value); } + + template + std::vector JSON::readVector(TokenType type, T(*strToT)(const std::string)) + { + std::vector vec; + while(nextTokenType() != TokenType::RSquare) + { + if(nextTokenType() != type) + throw std::runtime_error("Array must be of all the same type"); + vec.push_back(strToT(consume(type).content)); + if(nextTokenType() == TokenType::Comma) + { + consume(TokenType::Comma); + } + } + return vec; + } } -- cgit v1.2.3