From 7505574a7d108046bf7df5dd2a5e6c9d20cf8637 Mon Sep 17 00:00:00 2001 From: GriffinR Date: Wed, 18 Sep 2024 00:21:11 -0400 Subject: [PATCH 1/2] Sync tools --- Makefile | 51 +- include/characters.h | 190 + include/constants/.gitignore | 3 + include/constants/layouts.h | 341 - include/constants/map_groups.h | 472 - include/text.h | 119 +- make_tools.mk | 22 + map_data_rules.mk | 45 +- tools/aif2pcm/Makefile | 14 +- tools/aif2pcm/main.c | 103 +- tools/bin2c/Makefile | 14 +- tools/gbafix/Makefile | 13 +- tools/gbafix/gbafix.c | 46 +- tools/gbagfx/Makefile | 16 +- tools/gbagfx/convert_png.c | 8 +- tools/gbagfx/gfx.c | 275 +- tools/gbagfx/gfx.h | 29 +- tools/gbagfx/huff.c | 16 +- tools/gbagfx/jasc_pal.c | 8 +- tools/gbagfx/main.c | 97 +- tools/gbagfx/options.h | 10 + tools/jsonproc/Makefile | 16 +- tools/jsonproc/inja.hpp | 5180 +++---- tools/jsonproc/jsonproc.cpp | 17 +- tools/jsonproc/nlohmann/json.hpp | 23132 +++++++++++++++-------------- tools/mapjson/Makefile | 12 +- tools/mapjson/json11.cpp | 17 +- tools/mapjson/json11.h | 0 tools/mapjson/mapjson.cpp | 114 +- tools/mapjson/mapjson.h | 0 tools/mid2agb/Makefile | 14 +- tools/mid2agb/agb.cpp | 97 +- tools/mid2agb/main.cpp | 9 +- tools/mid2agb/midi.cpp | 10 +- tools/preproc/Makefile | 18 +- tools/preproc/asm_file.cpp | 378 +- tools/preproc/asm_file.h | 10 +- tools/preproc/c_file.cpp | 55 +- tools/preproc/c_file.h | 3 +- tools/preproc/io.cpp | 51 + tools/preproc/io.h | 8 + tools/preproc/preproc.cpp | 90 +- tools/ramscrgen/Makefile | 14 +- tools/ramscrgen/elf.cpp | 101 +- tools/ramscrgen/elf.h | 2 +- tools/ramscrgen/main.cpp | 24 +- tools/rsfont/Makefile | 14 +- tools/scaninc/Makefile | 16 +- tools/scaninc/asm_file.cpp | 3 +- tools/scaninc/scaninc.cpp | 143 +- tools/scaninc/source_file.cpp | 130 + tools/scaninc/source_file.h | 72 + 52 files changed, 16446 insertions(+), 15196 deletions(-) create mode 100644 include/characters.h create mode 100644 include/constants/.gitignore delete mode 100755 include/constants/layouts.h delete mode 100755 include/constants/map_groups.h create mode 100644 make_tools.mk mode change 100755 => 100644 tools/gbagfx/options.h mode change 100755 => 100644 tools/mapjson/Makefile mode change 100755 => 100644 tools/mapjson/json11.cpp mode change 100755 => 100644 tools/mapjson/json11.h mode change 100755 => 100644 tools/mapjson/mapjson.cpp mode change 100755 => 100644 tools/mapjson/mapjson.h create mode 100644 tools/preproc/io.cpp create mode 100644 tools/preproc/io.h create mode 100644 tools/scaninc/source_file.cpp create mode 100644 tools/scaninc/source_file.h diff --git a/Makefile b/Makefile index ed06f11e07..d09b000492 100644 --- a/Makefile +++ b/Makefile @@ -5,6 +5,9 @@ ifeq (compare,$(MAKECMDGOALS)) COMPARE := 1 endif +# Default make rule +all: rom + # don't use dkP's base_tools anymore # because the redefinition of $(CC) conflicts # with when we want to use $(CC) to preprocess files @@ -70,6 +73,10 @@ CPP := $(PREFIX)cpp LD := $(PREFIX)ld OBJCOPY := $(PREFIX)objcopy +# Variable filled out in other make files +AUTO_GEN_TARGETS := +include make_tools.mk + SHA1SUM := $(shell { command -v sha1sum || command -v shasum; } 2>/dev/null) -c GBAGFX := tools/gbagfx/gbagfx$(EXE) RSFONT := tools/rsfont/rsfont$(EXE) @@ -106,6 +113,7 @@ ELF := $(ROM:%.gba=%.elf) SYM := $(ROM:%.gba=%.sym) BUILD_DIR := build/$(BUILD_NAME) +DATA_ASM_SUBDIR = data C_SOURCES := $(wildcard src/*.c src/*/*.c src/*/*/*.c) ASM_SOURCES := $(wildcard src/*.s src/*/*.s asm/*.s data/*.s sound/*.s sound/*/*.s) @@ -151,14 +159,15 @@ ALL_BUILDS := ruby ruby_debug ruby_rev1 ruby_rev2 sapphire sapphire_debug sapphi MODERN_BUILDS := $(ALL_BUILDS:%=%_modern) # Available targets -.PHONY: all clean mostlyclean tidy tools syms $(ALL_BUILDS) +.PHONY: all clean tidy syms $(ALL_BUILDS) infoshell = $(foreach line, $(shell $1 | sed "s/ /__SPACE__/g"), $(info $(subst __SPACE__, ,$(line)))) # Build tools when building the rom # Disable dependency scanning for clean/tidy/tools ifeq (,$(filter-out all modern compare syms,$(MAKECMDGOALS))) -$(call infoshell, $(MAKE) tools) +$(call infoshell, $(MAKE) -f make_tools.mk) +$(call infoshell, $(MAKE) generated) else NODEP := 1 endif @@ -184,18 +193,19 @@ MAKEFLAGS += --no-print-directory # Create build subdirectories $(shell mkdir -p $(SUBDIRS)) -AUTO_GEN_TARGETS := +# Pretend rules that are actually flags defer to `make all` +modern: all +compare: all -all: $(ROM) +# Other rules +rom: $(ROM) ifeq ($(COMPARE),1) @$(SHA1SUM) $(BUILD_NAME).sha1 endif -compare: ; @$(MAKE) COMPARE=1 - syms: $(SYM) -mostlyclean: tidy +clean: tidy find sound/direct_sound_samples \( -iname '*.bin' \) -exec rm {} + $(RM) $(ALL_OBJECTS) find . \( -iname '*.1bpp' -o -iname '*.4bpp' -o -iname '*.8bpp' -o -iname '*.gbapal' -o -iname '*.lz' -o -iname '*.rl' \) -exec rm {} + @@ -204,31 +214,6 @@ mostlyclean: tidy find data/maps \( -iname 'connections.inc' -o -iname 'events.inc' -o -iname 'header.inc' \) -exec rm {} + rm -f $(AUTO_GEN_TARGETS) -clean: mostlyclean - $(MAKE) clean -C tools/gbagfx - $(MAKE) clean -C tools/scaninc - $(MAKE) clean -C tools/preproc - $(MAKE) clean -C tools/bin2c - $(MAKE) clean -C tools/rsfont - $(MAKE) clean -C tools/aif2pcm - $(MAKE) clean -C tools/ramscrgen - $(MAKE) clean -C tools/gbafix - $(MAKE) clean -C tools/mapjson - $(MAKE) clean -C tools/jsonproc - -tools: - @$(MAKE) -C tools/gbagfx - @$(MAKE) -C tools/scaninc - @$(MAKE) -C tools/preproc - @$(MAKE) -C tools/bin2c - @$(MAKE) -C tools/rsfont - @$(MAKE) -C tools/aif2pcm - @$(MAKE) -C tools/ramscrgen - @$(MAKE) -C tools/mid2agb - @$(MAKE) -C tools/gbafix - @$(MAKE) -C tools/mapjson - @$(MAKE) -C tools/jsonproc - tidy: $(RM) $(ALL_BUILDS:%=poke%{.gba,.elf,.map}) $(RM) $(MODERN_BUILDS:%=poke%{.gba,.elf,.map}) @@ -323,6 +308,8 @@ include override.mk include map_data_rules.mk include json_data_rules.mk +generated: $(AUTO_GEN_TARGETS) + %.1bpp: %.png ; $(GBAGFX) $< $@ $(GFX_OPTS) %.4bpp: %.png ; $(GBAGFX) $< $@ $(GFX_OPTS) %.8bpp: %.png ; $(GBAGFX) $< $@ $(GFX_OPTS) diff --git a/include/characters.h b/include/characters.h new file mode 100644 index 0000000000..78f4ecbdfd --- /dev/null +++ b/include/characters.h @@ -0,0 +1,190 @@ +#ifndef GUARD_CHARACTERS_H +#define GUARD_CHARACTERS_H + +#define CHAR_SPACE 0x00 +#define CHAR_LV 0x34 +#define CHAR_SONG_WORD_SEPARATOR 0x37 // separates words in the bard song. Not sure if it's used for anything else +#define CHAR_0 0xA1 +#define CHAR_EXCL_MARK 0xAB +#define CHAR_QUESTION_MARK 0xAC +#define CHAR_PERIOD 0xAD +#define CHAR_HYPHEN 0xAE +#define CHAR_ELLIPSIS 0xB0 +#define CHAR_DBL_QUOT_LEFT 0xB1 +#define CHAR_DBL_QUOT_RIGHT 0xB2 +#define CHAR_SGL_QUOT_LEFT 0xB3 +#define CHAR_SGL_QUOT_RIGHT 0xB4 +#define CHAR_MALE 0xB5 +#define CHAR_FEMALE 0xB6 +#define CHAR_CURRENCY 0xB7 +#define CHAR_COMMA 0xB8 +#define CHAR_MULT_SIGN 0xB9 +#define CHAR_SLASH 0xBA +#define CHAR_A 0xBB +#define CHAR_B 0xBC +#define CHAR_C 0xBD +#define CHAR_D 0xBE +#define CHAR_E 0xBF +#define CHAR_F 0xC0 +#define CHAR_G 0xC1 +#define CHAR_H 0xC2 +#define CHAR_I 0xC3 +#define CHAR_J 0xC4 +#define CHAR_K 0xC5 +#define CHAR_L 0xC6 +#define CHAR_M 0xC7 +#define CHAR_N 0xC8 +#define CHAR_O 0xC9 +#define CHAR_P 0xCA +#define CHAR_Q 0xCB +#define CHAR_R 0xCC +#define CHAR_S 0xCD +#define CHAR_T 0xCE +#define CHAR_U 0xCF +#define CHAR_V 0xD0 +#define CHAR_W 0xD1 +#define CHAR_X 0xD2 +#define CHAR_Y 0xD3 +#define CHAR_Z 0xD4 +#define CHAR_a 0xD5 +#define CHAR_b 0xD6 +#define CHAR_c 0xD7 +#define CHAR_d 0xD8 +#define CHAR_e 0xD9 +#define CHAR_f 0xDA +#define CHAR_g 0xDB +#define CHAR_h 0xDC +#define CHAR_i 0xDD +#define CHAR_j 0xDE +#define CHAR_k 0xDF +#define CHAR_l 0xE0 +#define CHAR_m 0xE1 +#define CHAR_n 0xE2 +#define CHAR_o 0xE3 +#define CHAR_p 0xE4 +#define CHAR_q 0xE5 +#define CHAR_r 0xE6 +#define CHAR_s 0xE7 +#define CHAR_t 0xE8 +#define CHAR_u 0xE9 +#define CHAR_v 0xEA +#define CHAR_w 0xEB +#define CHAR_x 0xEC +#define CHAR_y 0xED +#define CHAR_z 0xEE +#define CHAR_COLON 0xF0 +#define CHAR_PROMPT_SCROLL 0xFA // waits for button press and scrolls dialog +#define CHAR_PROMPT_CLEAR 0xFB // waits for button press and clears dialog +#define EXT_CTRL_CODE_BEGIN 0xFC // extended control code +#define PLACEHOLDER_BEGIN 0xFD // string placeholder +#define CHAR_NEWLINE 0xFE +#define EOS 0xFF // end of string + +#define TEXT_COLOR_TRANSPARENT 0x00 +#define TEXT_COLOR_DARK_GREY 0x01 +#define TEXT_COLOR_RED 0x02 +#define TEXT_COLOR_GREEN 0x03 +#define TEXT_COLOR_BLUE 0x04 +#define TEXT_COLOR_YELLOW 0x05 +#define TEXT_COLOR_CYAN 0x06 +#define TEXT_COLOR_MAGENTA 0x07 +#define TEXT_COLOR_LIGHT_GREY 0x08 +#define TEXT_COLOR_BLACK 0x09 +#define TEXT_COLOR_BLACK2 0x0A +#define TEXT_COLOR_SILVER 0x0B +#define TEXT_COLOR_WHITE 0x0C +#define TEXT_COLOR_SKY_BLUE 0x0D +#define TEXT_COLOR_LIGHT_BLUE 0x0E +#define TEXT_COLOR_WHITE2 0x0F + +#define EXT_CTRL_CODE_COLOR 0x01 +#define EXT_CTRL_CODE_HIGHLIGHT 0x02 +#define EXT_CTRL_CODE_SHADOW 0x03 +#define EXT_CTRL_CODE_COLOR_HIGHLIGHT_SHADOW 0x04 +#define EXT_CTRL_CODE_PALETTE 0x05 +#define EXT_CTRL_CODE_SIZE 0x06 +#define EXT_CTRL_CODE_RESET_SIZE 0x07 +#define EXT_CTRL_CODE_PAUSE 0x08 +#define EXT_CTRL_CODE_PAUSE_UNTIL_PRESS 0x09 +#define EXT_CTRL_CODE_WAIT_SE 0x0A +#define EXT_CTRL_CODE_PLAY_BGM 0x0B +#define EXT_CTRL_CODE_ESCAPE 0x0C +#define EXT_CTRL_CODE_SHIFT_TEXT 0x0D // nop +#define EXT_CTRL_CODE_SHIFT_DOWN 0x0E +#define EXT_CTRL_CODE_FILL_WINDOW 0x0F +#define EXT_CTRL_CODE_PLAY_SE 0x10 +#define EXT_CTRL_CODE_CLEAR 0x11 +#define EXT_CTRL_CODE_SKIP 0x12 +#define EXT_CTRL_CODE_CLEAR_TO 0x13 +#define EXT_CTRL_CODE_MIN_LETTER_SPACING 0x14 +#define EXT_CTRL_CODE_JPN 0x15 +#define EXT_CTRL_CODE_ENG 0x16 + +// Note that while all dot combinations are represented in +// the Braille font, they are not all meaningful characters. +// Only those that have direct single-character translations are listed. +#define BRAILLE_CHAR_SPACE 0x00 +#define BRAILLE_CHAR_A 0x01 +// +#define BRAILLE_CHAR_C 0x03 +#define BRAILLE_CHAR_COMMA 0x04 +#define BRAILLE_CHAR_B 0x05 +#define BRAILLE_CHAR_I 0x06 +#define BRAILLE_CHAR_F 0x07 +// +#define BRAILLE_CHAR_E 0x09 +// +#define BRAILLE_CHAR_D 0x0B +#define BRAILLE_CHAR_COLON 0x0C +#define BRAILLE_CHAR_H 0x0D +#define BRAILLE_CHAR_J 0x0E +#define BRAILLE_CHAR_G 0x0F +#define BRAILLE_CHAR_APOSTROPHE 0x10 +#define BRAILLE_CHAR_K 0x11 +#define BRAILLE_CHAR_SLASH 0x12 +#define BRAILLE_CHAR_M 0x13 +#define BRAILLE_CHAR_SEMICOLON 0x14 +#define BRAILLE_CHAR_L 0x15 +#define BRAILLE_CHAR_S 0x16 +#define BRAILLE_CHAR_P 0x17 +// +#define BRAILLE_CHAR_O 0x19 +// +#define BRAILLE_CHAR_N 0x1B +#define BRAILLE_CHAR_EXCL_MARK 0x1C +#define BRAILLE_CHAR_R 0x1D +#define BRAILLE_CHAR_T 0x1E +#define BRAILLE_CHAR_Q 0x1F +// +#define BRAILLE_CHAR_PERIOD 0x2C +// +#define BRAILLE_CHAR_W 0x2E +// +#define BRAILLE_CHAR_HYPHEN 0x30 +#define BRAILLE_CHAR_U 0x31 +// +#define BRAILLE_CHAR_X 0x33 +#define BRAILLE_CHAR_QUESTION_MARK 0x34 // Also double quote left +#define BRAILLE_CHAR_V 0x35 +// +#define BRAILLE_CHAR_DBL_QUOTE_RIGHT 0x38 +#define BRAILLE_CHAR_Z 0x39 +#define BRAILLE_CHAR_NUMBER 0x3A +#define BRAILLE_CHAR_Y 0x3B +#define BRAILLE_CHAR_PAREN 0x3C +// +#define NUM_BRAILLE_CHARS 0x40 + +// Digits must be preceded by BRAILLE_CHAR_NUMBER +#define BRAILLE_CHAR_1 BRAILLE_CHAR_A +#define BRAILLE_CHAR_2 BRAILLE_CHAR_B +#define BRAILLE_CHAR_3 BRAILLE_CHAR_C +#define BRAILLE_CHAR_4 BRAILLE_CHAR_D +#define BRAILLE_CHAR_5 BRAILLE_CHAR_E +#define BRAILLE_CHAR_6 BRAILLE_CHAR_F +#define BRAILLE_CHAR_7 BRAILLE_CHAR_G +#define BRAILLE_CHAR_8 BRAILLE_CHAR_H +#define BRAILLE_CHAR_9 BRAILLE_CHAR_I +#define BRAILLE_CHAR_0 BRAILLE_CHAR_J + +#endif // GUARD_CHARACTERS_H diff --git a/include/constants/.gitignore b/include/constants/.gitignore new file mode 100644 index 0000000000..90e7a74404 --- /dev/null +++ b/include/constants/.gitignore @@ -0,0 +1,3 @@ +# Will be moved to build/ eventually +map_groups.h +layouts.h diff --git a/include/constants/layouts.h b/include/constants/layouts.h deleted file mode 100755 index fed1ce25e3..0000000000 --- a/include/constants/layouts.h +++ /dev/null @@ -1,341 +0,0 @@ -#ifndef GUARD_CONSTANTS_LAYOUTS_H -#define GUARD_CONSTANTS_LAYOUTS_H - -// -// DO NOT MODIFY THIS FILE! It is auto-generated from data/layouts/layouts.json -// - -#define LAYOUT_PETALBURG_CITY 1 -#define LAYOUT_SLATEPORT_CITY 2 -#define LAYOUT_MAUVILLE_CITY 3 -#define LAYOUT_RUSTBORO_CITY 4 -#define LAYOUT_FORTREE_CITY 5 -#define LAYOUT_LILYCOVE_CITY 6 -#define LAYOUT_MOSSDEEP_CITY 7 -#define LAYOUT_SOOTOPOLIS_CITY 8 -#define LAYOUT_EVER_GRANDE_CITY 9 -#define LAYOUT_LITTLEROOT_TOWN 10 -#define LAYOUT_OLDALE_TOWN 11 -#define LAYOUT_DEWFORD_TOWN 12 -#define LAYOUT_LAVARIDGE_TOWN 13 -#define LAYOUT_FALLARBOR_TOWN 14 -#define LAYOUT_VERDANTURF_TOWN 15 -#define LAYOUT_PACIFIDLOG_TOWN 16 -#define LAYOUT_ROUTE101 17 -#define LAYOUT_ROUTE102 18 -#define LAYOUT_ROUTE103 19 -#define LAYOUT_ROUTE104 20 -#define LAYOUT_ROUTE105 21 -#define LAYOUT_ROUTE106 22 -#define LAYOUT_ROUTE107 23 -#define LAYOUT_ROUTE108 24 -#define LAYOUT_ROUTE109 25 -#define LAYOUT_ROUTE110 26 -#define LAYOUT_ROUTE111 27 -#define LAYOUT_ROUTE112 28 -#define LAYOUT_ROUTE113 29 -#define LAYOUT_ROUTE114 30 -#define LAYOUT_ROUTE115 31 -#define LAYOUT_ROUTE116 32 -#define LAYOUT_ROUTE117 33 -#define LAYOUT_ROUTE118 34 -#define LAYOUT_ROUTE119 35 -#define LAYOUT_ROUTE120 36 -#define LAYOUT_ROUTE121 37 -#define LAYOUT_ROUTE122 38 -#define LAYOUT_ROUTE123 39 -#define LAYOUT_ROUTE124 40 -#define LAYOUT_ROUTE125 41 -#define LAYOUT_ROUTE126 42 -#define LAYOUT_ROUTE127 43 -#define LAYOUT_ROUTE128 44 -#define LAYOUT_ROUTE129 45 -#define LAYOUT_UNREFERENCED_MAP 46 -#define LAYOUT_ROUTE131 47 -#define LAYOUT_ROUTE132 48 -#define LAYOUT_ROUTE133 49 -#define LAYOUT_ROUTE134 50 -#define LAYOUT_UNDERWATER2 51 -#define LAYOUT_UNDERWATER3 52 -#define LAYOUT_UNDERWATER4 53 -#define LAYOUT_LITTLEROOT_TOWN_BRENDANS_HOUSE_1F 54 -#define LAYOUT_LITTLEROOT_TOWN_BRENDANS_HOUSE_2F 55 -#define LAYOUT_LITTLEROOT_TOWN_MAYS_HOUSE_1F 56 -#define LAYOUT_LITTLEROOT_TOWN_MAYS_HOUSE_2F 57 -#define LAYOUT_LITTLEROOT_TOWN_PROFESSOR_BIRCHS_LAB 58 -#define LAYOUT_HOUSE1 59 -#define LAYOUT_HOUSE2 60 -#define LAYOUT_POKEMON_CENTER_1F 61 -#define LAYOUT_POKEMON_CENTER_2F 62 -#define LAYOUT_POKE_MART 63 -#define LAYOUT_HOUSE3 64 -#define LAYOUT_DEWFORD_TOWN_GYM 65 -#define LAYOUT_DEWFORD_TOWN_HALL 66 -#define LAYOUT_HOUSE4 67 -#define LAYOUT_LAVARIDGE_TOWN_HERB_SHOP 68 -#define LAYOUT_LAVARIDGE_TOWN_GYM_1F 69 -#define LAYOUT_LAVARIDGE_TOWN_GYM_B1F 70 -#define LAYOUT_LAVARIDGE_TOWN_POKEMON_CENTER_1F 71 -#define LAYOUT_CONTEST_LOBBY 72 -#define LAYOUT_CONTEST_HALL 73 -#define LAYOUT_LILYCOVE_CITY_HOUSE2 74 -#define LAYOUT_UNKNOWN_MAP_082CF564 75 -#define LAYOUT_VERDANTURF_TOWN_WANDAS_HOUSE 76 -#define LAYOUT_PACIFIDLOG_TOWN_HOUSE1 77 -#define LAYOUT_PACIFIDLOG_TOWN_HOUSE2 78 -#define LAYOUT_PETALBURG_CITY_GYM 79 -#define LAYOUT_HOUSE_WITH_BED 80 -#define LAYOUT_SLATEPORT_CITY_STERNS_SHIPYARD_1F 81 -#define LAYOUT_SLATEPORT_CITY_STERNS_SHIPYARD_2F 82 -#define LAYOUT_UNKNOWN_MAP_082D05D8 83 -#define LAYOUT_UNKNOWN_MAP_082D05FC 84 -#define LAYOUT_SLATEPORT_CITY_POKEMON_FAN_CLUB 85 -#define LAYOUT_SLATEPORT_CITY_OCEANIC_MUSEUM_1F 86 -#define LAYOUT_SLATEPORT_CITY_OCEANIC_MUSEUM_2F 87 -#define LAYOUT_HARBOR 88 -#define LAYOUT_MAUVILLE_CITY_GYM 89 -#define LAYOUT_MAUVILLE_CITY_BIKE_SHOP 90 -#define LAYOUT_MAUVILLE_CITY_GAME_CORNER 91 -#define LAYOUT_RUSTBORO_CITY_DEVON_CORP_1F 92 -#define LAYOUT_RUSTBORO_CITY_DEVON_CORP_2F 93 -#define LAYOUT_RUSTBORO_CITY_GYM 94 -#define LAYOUT_RUSTBORO_CITY_POKEMON_SCHOOL 95 -#define LAYOUT_RUSTBORO_CITY_HOUSE 96 -#define LAYOUT_RUSTBORO_CITY_HOUSE1 97 -#define LAYOUT_RUSTBORO_CITY_CUTTERS_HOUSE 98 -#define LAYOUT_FORTREE_CITY_HOUSE1 99 -#define LAYOUT_FORTREE_CITY_GYM 100 -#define LAYOUT_FORTREE_CITY_HOUSE2 101 -#define LAYOUT_ROUTE104_MR_BRINEYS_HOUSE 102 -#define LAYOUT_LILYCOVE_CITY_LILYCOVE_MUSEUM_1F 103 -#define LAYOUT_LILYCOVE_CITY_LILYCOVE_MUSEUM_2F 104 -#define LAYOUT_LILYCOVE_CITY_CONTEST_LOBBY 105 -#define LAYOUT_LILYCOVE_CITY_CONTEST_HALL 106 -#define LAYOUT_LILYCOVE_CITY_POKEMON_TRAINER_FAN_CLUB 107 -#define LAYOUT_LILYCOVE_CITY_EMPTY_MAP 108 -#define LAYOUT_MOSSDEEP_CITY_GYM 109 -#define LAYOUT_SOOTOPOLIS_CITY_GYM_1F 110 -#define LAYOUT_SOOTOPOLIS_CITY_GYM_B1F 111 -#define LAYOUT_EVER_GRANDE_CITY_SIDNEYS_ROOM 112 -#define LAYOUT_EVER_GRANDE_CITY_PHOEBES_ROOM 113 -#define LAYOUT_EVER_GRANDE_CITY_GLACIAS_ROOM 114 -#define LAYOUT_EVER_GRANDE_CITY_DRAKES_ROOM 115 -#define LAYOUT_EVER_GRANDE_CITY_CHAMPIONS_ROOM 116 -#define LAYOUT_EVER_GRANDE_CITY_SHORT_CORRIDOR 117 -#define LAYOUT_ROUTE104_PRETTY_PETAL_FLOWER_SHOP 118 -#define LAYOUT_CABLE_CAR_STATION 119 -#define LAYOUT_ROUTE114_FOSSIL_MANIACS_HOUSE 120 -#define LAYOUT_ROUTE114_FOSSIL_MANIACS_TUNNEL 121 -#define LAYOUT_ROUTE114_LANETTES_HOUSE 122 -#define LAYOUT_ROUTE116_TUNNELERS_REST_HOUSE 123 -#define LAYOUT_ROUTE117_POKEMON_DAY_CARE 124 -#define LAYOUT_ROUTE121_SAFARI_ZONE_ENTRANCE 125 -#define LAYOUT_METEOR_FALLS_1F_1R 126 -#define LAYOUT_METEOR_FALLS_1F_2R 127 -#define LAYOUT_METEOR_FALLS_B1F_1R 128 -#define LAYOUT_METEOR_FALLS_B1F_2R 129 -#define LAYOUT_RUSTURF_TUNNEL 130 -#define LAYOUT_UNDERWATER_SOOTOPOLIS_CITY 131 -#define LAYOUT_DESERT_RUINS 132 -#define LAYOUT_GRANITE_CAVE_1F 133 -#define LAYOUT_GRANITE_CAVE_B1F 134 -#define LAYOUT_GRANITE_CAVE_B2F 135 -#define LAYOUT_PETALBURG_WOODS 136 -#define LAYOUT_MT_CHIMNEY 137 -#define LAYOUT_MT_PYRE_1F 138 -#define LAYOUT_MT_PYRE_2F 139 -#define LAYOUT_MT_PYRE_3F 140 -#define LAYOUT_MT_PYRE_4F 141 -#define LAYOUT_MT_PYRE_5F 142 -#define LAYOUT_MT_PYRE_6F 143 -#define LAYOUT_AQUA_HIDEOUT_1F 144 -#define LAYOUT_AQUA_HIDEOUT_B1F 145 -#define LAYOUT_AQUA_HIDEOUT_B2F 146 -#define LAYOUT_UNDERWATER_SEAFLOOR_CAVERN 147 -#define LAYOUT_SEAFLOOR_CAVERN_ENTRANCE 148 -#define LAYOUT_SEAFLOOR_CAVERN_ROOM1 149 -#define LAYOUT_SEAFLOOR_CAVERN_ROOM2 150 -#define LAYOUT_SEAFLOOR_CAVERN_ROOM3 151 -#define LAYOUT_SEAFLOOR_CAVERN_ROOM4 152 -#define LAYOUT_SEAFLOOR_CAVERN_ROOM5 153 -#define LAYOUT_SEAFLOOR_CAVERN_ROOM6 154 -#define LAYOUT_SEAFLOOR_CAVERN_ROOM7 155 -#define LAYOUT_SEAFLOOR_CAVERN_ROOM8 156 -#define LAYOUT_SEAFLOOR_CAVERN_ROOM9 157 -#define LAYOUT_CAVE_OF_ORIGIN_ENTRANCE 158 -#define LAYOUT_CAVE_OF_ORIGIN_1F 159 -#define LAYOUT_CAVE_OF_ORIGIN_B1F 160 -#define LAYOUT_CAVE_OF_ORIGIN_B2F 161 -#define LAYOUT_CAVE_OF_ORIGIN_B3F 162 -#define LAYOUT_CAVE_OF_ORIGIN_B4F 163 -#define LAYOUT_VICTORY_ROAD_1F 164 -#define LAYOUT_SHOAL_CAVE_LOW_TIDE_ENTRANCE_ROOM 165 -#define LAYOUT_SHOAL_CAVE_LOW_TIDE_INNER_ROOM 166 -#define LAYOUT_SHOAL_CAVE_LOW_TIDE_STAIRS_ROOM 167 -#define LAYOUT_SHOAL_CAVE_LOW_TIDE_LOWER_ROOM 168 -#define LAYOUT_SHOAL_CAVE_HIGH_TIDE_ENTRANCE_ROOM 169 -#define LAYOUT_SHOAL_CAVE_HIGH_TIDE_INNER_ROOM 170 -#define LAYOUT_UNKNOWN_MAP_082E55C8 171 -#define LAYOUT_UNKNOWN_MAP_082E55EC 172 -#define LAYOUT_UNKNOWN_MAP_082E5610 173 -#define LAYOUT_UNKNOWN_MAP_082E5634 174 -#define LAYOUT_UNKNOWN_MAP_082E5658 175 -#define LAYOUT_UNKNOWN_MAP_082E567C 176 -#define LAYOUT_UNKNOWN_MAP_082E56A0 177 -#define LAYOUT_UNKNOWN_MAP_082E56C4 178 -#define LAYOUT_UNKNOWN_MAP_082E56E8 179 -#define LAYOUT_UNKNOWN_MAP_082E570C 180 -#define LAYOUT_UNKNOWN_MAP_082E5730 181 -#define LAYOUT_UNKNOWN_MAP_082E5754 182 -#define LAYOUT_UNKNOWN_MAP_082E5778 183 -#define LAYOUT_UNKNOWN_MAP_082E579C 184 -#define LAYOUT_NEW_MAUVILLE_ENTRANCE 185 -#define LAYOUT_NEW_MAUVILLE_INSIDE 186 -#define LAYOUT_ABANDONED_SHIP_DECK 187 -#define LAYOUT_ABANDONED_SHIP_CORRIDORS_1F 188 -#define LAYOUT_ABANDONED_SHIP_ROOMS_1F 189 -#define LAYOUT_ABANDONED_SHIP_CORRIDORS_B1F 190 -#define LAYOUT_ABANDONED_SHIP_ROOMS_B1F 191 -#define LAYOUT_ABANDONED_SHIP_ROOMS2_B1F 192 -#define LAYOUT_ABANDONED_SHIP_UNDERWATER1 193 -#define LAYOUT_ABANDONED_SHIP_ROOM_B1F 194 -#define LAYOUT_ABANDONED_SHIP_ROOMS2_1F 195 -#define LAYOUT_ABANDONED_SHIP_CAPTAINS_OFFICE 196 -#define LAYOUT_ABANDONED_SHIP_UNDERWATER2 197 -#define LAYOUT_SECRET_BASE_RED_CAVE1 198 -#define LAYOUT_SECRET_BASE_BROWN_CAVE1 199 -#define LAYOUT_SECRET_BASE_BLUE_CAVE1 200 -#define LAYOUT_SECRET_BASE_YELLOW_CAVE1 201 -#define LAYOUT_SECRET_BASE_TREE1 202 -#define LAYOUT_SECRET_BASE_SHRUB1 203 -#define LAYOUT_SECRET_BASE_RED_CAVE2 204 -#define LAYOUT_SECRET_BASE_BROWN_CAVE2 205 -#define LAYOUT_SECRET_BASE_BLUE_CAVE2 206 -#define LAYOUT_SECRET_BASE_YELLOW_CAVE2 207 -#define LAYOUT_SECRET_BASE_TREE2 208 -#define LAYOUT_SECRET_BASE_SHRUB2 209 -#define LAYOUT_SECRET_BASE_RED_CAVE3 210 -#define LAYOUT_SECRET_BASE_BROWN_CAVE3 211 -#define LAYOUT_SECRET_BASE_BLUE_CAVE3 212 -#define LAYOUT_SECRET_BASE_YELLOW_CAVE3 213 -#define LAYOUT_SECRET_BASE_TREE3 214 -#define LAYOUT_SECRET_BASE_SHRUB3 215 -#define LAYOUT_SECRET_BASE_RED_CAVE4 216 -#define LAYOUT_SECRET_BASE_BROWN_CAVE4 217 -#define LAYOUT_SECRET_BASE_BLUE_CAVE4 218 -#define LAYOUT_SECRET_BASE_YELLOW_CAVE4 219 -#define LAYOUT_SECRET_BASE_TREE4 220 -#define LAYOUT_SECRET_BASE_SHRUB4 221 -#define LAYOUT_SINGLE_BATTLE_COLOSSEUM 222 -#define LAYOUT_TRADE_CENTER 223 -#define LAYOUT_RECORD_CORNER 224 -#define LAYOUT_DOUBLE_BATTLE_COLOSSEUM 225 -#define LAYOUT_LINK_CONTEST_ROOM1 226 -#define LAYOUT_UNKNOWN_MAP_25_29 227 -#define LAYOUT_UNKNOWN_MAP_25_30 228 -#define LAYOUT_UNKNOWN_MAP_25_31 229 -#define LAYOUT_UNKNOWN_MAP_25_32 230 -#define LAYOUT_UNKNOWN_MAP_25_33 231 -#define LAYOUT_UNKNOWN_MAP_25_34 232 -#define LAYOUT_LINK_CONTEST_ROOM2 233 -#define LAYOUT_LINK_CONTEST_ROOM3 234 -#define LAYOUT_LINK_CONTEST_ROOM4 235 -#define LAYOUT_LINK_CONTEST_ROOM5 236 -#define LAYOUT_LINK_CONTEST_ROOM6 237 -#define LAYOUT_INSIDE_OF_TRUCK 238 -#define LAYOUT_SAFARI_ZONE_NORTHWEST 239 -#define LAYOUT_SAFARI_ZONE_NORTHEAST 240 -#define LAYOUT_SAFARI_ZONE_SOUTHWEST 241 -#define LAYOUT_SAFARI_ZONE_SOUTHEAST 242 -#define LAYOUT_UNKNOWN_MAP_082EDF30 243 -#define LAYOUT_ROUTE109_SEASHORE_HOUSE 244 -#define LAYOUT_ROUTE110_TRICK_HOUSE_ENTRANCE 245 -#define LAYOUT_ROUTE110_TRICK_HOUSE_END 246 -#define LAYOUT_ROUTE110_TRICK_HOUSE_CORRIDOR 247 -#define LAYOUT_ROUTE110_TRICK_HOUSE_PUZZLE1 248 -#define LAYOUT_ROUTE110_TRICK_HOUSE_PUZZLE2 249 -#define LAYOUT_ROUTE110_TRICK_HOUSE_PUZZLE3 250 -#define LAYOUT_ROUTE110_TRICK_HOUSE_PUZZLE4 251 -#define LAYOUT_ROUTE110_TRICK_HOUSE_PUZZLE5 252 -#define LAYOUT_ROUTE110_TRICK_HOUSE_PUZZLE6 253 -#define LAYOUT_ROUTE110_TRICK_HOUSE_PUZZLE7 254 -#define LAYOUT_ROUTE110_TRICK_HOUSE_PUZZLE8 255 -#define LAYOUT_FORTREE_CITY_DECORATION_SHOP 256 -#define LAYOUT_ROUTE110_SEASIDE_CYCLING_ROAD_ENTRACE 257 -#define LAYOUT_LILYCOVE_CITY_DEPARTMENT_STORE_1F 258 -#define LAYOUT_LILYCOVE_CITY_DEPARTMENT_STORE_2F 259 -#define LAYOUT_LILYCOVE_CITY_DEPARTMENT_STORE_3F 260 -#define LAYOUT_LILYCOVE_CITY_DEPARTMENT_STORE_4F 261 -#define LAYOUT_LILYCOVE_CITY_DEPARTMENT_STORE_5F 262 -#define LAYOUT_LILYCOVE_CITY_DEPARTMENT_STORE_ROOFTOP 263 -#define LAYOUT_ROUTE130 264 -#define LAYOUT_BATTLE_TOWER_LOBBY 265 -#define LAYOUT_BATTLE_TOWER_OUTSIDE 266 -#define LAYOUT_BATTLE_TOWER_ELEVATOR 267 -#define LAYOUT_BATTLE_TOWER_CORRIDOR 268 -#define LAYOUT_BATTLE_TOWER_BATTLE_ROOM 269 -#define LAYOUT_RUSTBORO_CITY_DEVON_CORP_3F 270 -#define LAYOUT_EVER_GRANDE_CITY_POKEMON_LEAGUE 271 -#define LAYOUT_ROUTE119_WEATHER_INSTITUTE_1F 272 -#define LAYOUT_ROUTE119_WEATHER_INSTITUTE_2F 273 -#define LAYOUT_LILYCOVE_CITY_DEPARTMENT_STORE_ELEVATOR 274 -#define LAYOUT_UNDERWATER1 275 -#define LAYOUT_MOSSDEEP_CITY_SPACE_CENTER_1F 276 -#define LAYOUT_MOSSDEEP_CITY_SPACE_CENTER_2F 277 -#define LAYOUT_SS_TIDAL_CORRIDOR 278 -#define LAYOUT_SS_TIDAL_LOWER_DECK 279 -#define LAYOUT_SS_TIDAL_ROOMS 280 -#define LAYOUT_ISLAND_CAVE 281 -#define LAYOUT_ANCIENT_TOMB 282 -#define LAYOUT_UNDERWATER_ROUTE134 283 -#define LAYOUT_UNDERWATER_SEALED_CHAMBER 284 -#define LAYOUT_SEALED_CHAMBER_OUTER_ROOM 285 -#define LAYOUT_VICTORY_ROAD_B1F 286 -#define LAYOUT_VICTORY_ROAD_B2F 287 -#define LAYOUT_ROUTE104_PROTOTYPE 288 -#define LAYOUT_GRANITE_CAVE_STEVENS_ROOM 289 -#define LAYOUT_ABANDONED_SHIP_HIDDEN_FLOOR_CORRIDORS 290 -#define LAYOUT_SOUTHERN_ISLAND_EXTERIOR 291 -#define LAYOUT_SOUTHERN_ISLAND_INTERIOR 292 -#define LAYOUT_JAGGED_PASS 293 -#define LAYOUT_FIERY_PATH 294 -#define LAYOUT_RUSTBORO_CITY_FLAT2_1F 295 -#define LAYOUT_RUSTBORO_CITY_FLAT2_2F 296 -#define LAYOUT_RUSTBORO_CITY_FLAT2_3F 297 -#define LAYOUT_SOOTOPOLIS_CITY_HOUSE8 298 -#define LAYOUT_EVER_GRANDE_CITY_HALL_OF_FAME 299 -#define LAYOUT_LILYCOVE_CITY_COVE_LILY_MOTEL_1F 300 -#define LAYOUT_LILYCOVE_CITY_COVE_LILY_MOTEL_2F 301 -#define LAYOUT_ROUTE124_DIVING_TREASURE_HUNTERS_HOUSE 302 -#define LAYOUT_MT_PYRE_EXTERIOR 303 -#define LAYOUT_MT_PYRE_SUMMIT 304 -#define LAYOUT_SEALED_CHAMBER_INNER_ROOM 305 -#define LAYOUT_MOSSDEEP_CITY_GAME_CORNER_1F 306 -#define LAYOUT_MOSSDEEP_CITY_GAME_CORNER_B1F 307 -#define LAYOUT_SOOTOPOLIS_CITY_HOUSE1 308 -#define LAYOUT_SOOTOPOLIS_CITY_HOUSE2 309 -#define LAYOUT_SOOTOPOLIS_CITY_HOUSE3 310 -#define LAYOUT_ABANDONED_SHIP_HIDDEN_FLOOR_ROOMS 311 -#define LAYOUT_SCORCHED_SLAB 312 -#define LAYOUT_UNKNOWN_MAP_082FF894 313 -#define LAYOUT_RUSTBORO_CITY_FLAT1_1F 314 -#define LAYOUT_RUSTBORO_CITY_FLAT1_2F 315 -#define LAYOUT_EVER_GRANDE_CITY_CORRIDOR4 316 -#define LAYOUT_MAGMA_HIDEOUT_1F 317 -#define LAYOUT_MAGMA_HIDEOUT_B1F 318 -#define LAYOUT_MAGMA_HIDEOUT_B2F 319 -#define LAYOUT_UNKNOWN_MAP_08302970 320 -#define LAYOUT_SKY_PILLAR_ENTRANCE 321 -#define LAYOUT_SKY_PILLAR_OUTSIDE 322 -#define LAYOUT_SKY_PILLAR_1F 323 -#define LAYOUT_SKY_PILLAR_2F 324 -#define LAYOUT_SKY_PILLAR_3F 325 -#define LAYOUT_SKY_PILLAR_4F 326 -#define LAYOUT_UNKNOWN_MAP_083041B4 327 -#define LAYOUT_MOSSDEEP_CITY_STEVENS_HOUSE 328 -#define LAYOUT_SHOAL_CAVE_LOW_TIDE_ICE_ROOM 329 -#define LAYOUT_SAFARI_ZONE_REST_HOUSE 330 -#define LAYOUT_SKY_PILLAR_5F 331 -#define LAYOUT_SKY_PILLAR_TOP 332 - -#endif // GUARD_CONSTANTS_LAYOUTS_H diff --git a/include/constants/map_groups.h b/include/constants/map_groups.h deleted file mode 100755 index bffa347ea0..0000000000 --- a/include/constants/map_groups.h +++ /dev/null @@ -1,472 +0,0 @@ -#ifndef GUARD_CONSTANTS_MAP_GROUPS_H -#define GUARD_CONSTANTS_MAP_GROUPS_H - -// -// DO NOT MODIFY THIS FILE! It is auto-generated from data/maps/map_groups.json -// - -// gMapGroup_TownsAndRoutes -#define MAP_PETALBURG_CITY (0 | (0 << 8)) -#define MAP_SLATEPORT_CITY (1 | (0 << 8)) -#define MAP_MAUVILLE_CITY (2 | (0 << 8)) -#define MAP_RUSTBORO_CITY (3 | (0 << 8)) -#define MAP_FORTREE_CITY (4 | (0 << 8)) -#define MAP_LILYCOVE_CITY (5 | (0 << 8)) -#define MAP_MOSSDEEP_CITY (6 | (0 << 8)) -#define MAP_SOOTOPOLIS_CITY (7 | (0 << 8)) -#define MAP_EVER_GRANDE_CITY (8 | (0 << 8)) -#define MAP_LITTLEROOT_TOWN (9 | (0 << 8)) -#define MAP_OLDALE_TOWN (10 | (0 << 8)) -#define MAP_DEWFORD_TOWN (11 | (0 << 8)) -#define MAP_LAVARIDGE_TOWN (12 | (0 << 8)) -#define MAP_FALLARBOR_TOWN (13 | (0 << 8)) -#define MAP_VERDANTURF_TOWN (14 | (0 << 8)) -#define MAP_PACIFIDLOG_TOWN (15 | (0 << 8)) -#define MAP_ROUTE101 (16 | (0 << 8)) -#define MAP_ROUTE102 (17 | (0 << 8)) -#define MAP_ROUTE103 (18 | (0 << 8)) -#define MAP_ROUTE104 (19 | (0 << 8)) -#define MAP_ROUTE105 (20 | (0 << 8)) -#define MAP_ROUTE106 (21 | (0 << 8)) -#define MAP_ROUTE107 (22 | (0 << 8)) -#define MAP_ROUTE108 (23 | (0 << 8)) -#define MAP_ROUTE109 (24 | (0 << 8)) -#define MAP_ROUTE110 (25 | (0 << 8)) -#define MAP_ROUTE111 (26 | (0 << 8)) -#define MAP_ROUTE112 (27 | (0 << 8)) -#define MAP_ROUTE113 (28 | (0 << 8)) -#define MAP_ROUTE114 (29 | (0 << 8)) -#define MAP_ROUTE115 (30 | (0 << 8)) -#define MAP_ROUTE116 (31 | (0 << 8)) -#define MAP_ROUTE117 (32 | (0 << 8)) -#define MAP_ROUTE118 (33 | (0 << 8)) -#define MAP_ROUTE119 (34 | (0 << 8)) -#define MAP_ROUTE120 (35 | (0 << 8)) -#define MAP_ROUTE121 (36 | (0 << 8)) -#define MAP_ROUTE122 (37 | (0 << 8)) -#define MAP_ROUTE123 (38 | (0 << 8)) -#define MAP_ROUTE124 (39 | (0 << 8)) -#define MAP_ROUTE125 (40 | (0 << 8)) -#define MAP_ROUTE126 (41 | (0 << 8)) -#define MAP_ROUTE127 (42 | (0 << 8)) -#define MAP_ROUTE128 (43 | (0 << 8)) -#define MAP_ROUTE129 (44 | (0 << 8)) -#define MAP_ROUTE130 (45 | (0 << 8)) -#define MAP_ROUTE131 (46 | (0 << 8)) -#define MAP_ROUTE132 (47 | (0 << 8)) -#define MAP_ROUTE133 (48 | (0 << 8)) -#define MAP_ROUTE134 (49 | (0 << 8)) -#define MAP_UNDERWATER1 (50 | (0 << 8)) -#define MAP_UNDERWATER2 (51 | (0 << 8)) -#define MAP_UNDERWATER3 (52 | (0 << 8)) -#define MAP_UNDERWATER4 (53 | (0 << 8)) - -// gMapGroup_IndoorLittleroot -#define MAP_LITTLEROOT_TOWN_BRENDANS_HOUSE_1F (0 | (1 << 8)) -#define MAP_LITTLEROOT_TOWN_BRENDANS_HOUSE_2F (1 | (1 << 8)) -#define MAP_LITTLEROOT_TOWN_MAYS_HOUSE_1F (2 | (1 << 8)) -#define MAP_LITTLEROOT_TOWN_MAYS_HOUSE_2F (3 | (1 << 8)) -#define MAP_LITTLEROOT_TOWN_PROFESSOR_BIRCHS_LAB (4 | (1 << 8)) - -// gMapGroup_IndoorOldale -#define MAP_OLDALE_TOWN_HOUSE1 (0 | (2 << 8)) -#define MAP_OLDALE_TOWN_HOUSE2 (1 | (2 << 8)) -#define MAP_OLDALE_TOWN_POKEMON_CENTER_1F (2 | (2 << 8)) -#define MAP_OLDALE_TOWN_POKEMON_CENTER_2F (3 | (2 << 8)) -#define MAP_OLDALE_TOWN_MART (4 | (2 << 8)) - -// gMapGroup_IndoorDewford -#define MAP_DEWFORD_TOWN_HOUSE1 (0 | (3 << 8)) -#define MAP_DEWFORD_TOWN_POKEMON_CENTER_1F (1 | (3 << 8)) -#define MAP_DEWFORD_TOWN_POKEMON_CENTER_2F (2 | (3 << 8)) -#define MAP_DEWFORD_TOWN_GYM (3 | (3 << 8)) -#define MAP_DEWFORD_TOWN_HALL (4 | (3 << 8)) -#define MAP_DEWFORD_TOWN_HOUSE2 (5 | (3 << 8)) - -// gMapGroup_IndoorLavaridge -#define MAP_LAVARIDGE_TOWN_HERB_SHOP (0 | (4 << 8)) -#define MAP_LAVARIDGE_TOWN_GYM_1F (1 | (4 << 8)) -#define MAP_LAVARIDGE_TOWN_GYM_B1F (2 | (4 << 8)) -#define MAP_LAVARIDGE_TOWN_HOUSE (3 | (4 << 8)) -#define MAP_LAVARIDGE_TOWN_MART (4 | (4 << 8)) -#define MAP_LAVARIDGE_TOWN_POKEMON_CENTER_1F (5 | (4 << 8)) -#define MAP_LAVARIDGE_TOWN_POKEMON_CENTER_2F (6 | (4 << 8)) - -// gMapGroup_IndoorFallarbor -#define MAP_FALLARBOR_TOWN_MART (0 | (5 << 8)) -#define MAP_FALLARBOR_TOWN_CONTEST_LOBBY (1 | (5 << 8)) -#define MAP_FALLARBOR_TOWN_CONTEST_HALL (2 | (5 << 8)) -#define MAP_FALLARBOR_TOWN_POKEMON_CENTER_1F (3 | (5 << 8)) -#define MAP_FALLARBOR_TOWN_POKEMON_CENTER_2F (4 | (5 << 8)) -#define MAP_FALLARBOR_TOWN_HOUSE1 (5 | (5 << 8)) -#define MAP_FALLARBOR_TOWN_HOUSE2 (6 | (5 << 8)) - -// gMapGroup_IndoorVerdanturf -#define MAP_VERDANTURF_TOWN_CONTEST_LOBBY (0 | (6 << 8)) -#define MAP_VERDANTURF_TOWN_CONTEST_HALL (1 | (6 << 8)) -#define MAP_VERDANTURF_TOWN_MART (2 | (6 << 8)) -#define MAP_VERDANTURF_TOWN_POKEMON_CENTER_1F (3 | (6 << 8)) -#define MAP_VERDANTURF_TOWN_POKEMON_CENTER_2F (4 | (6 << 8)) -#define MAP_VERDANTURF_TOWN_WANDAS_HOUSE (5 | (6 << 8)) -#define MAP_VERDANTURF_TOWN_FRIENDSHIP_RATERS_HOUSE (6 | (6 << 8)) -#define MAP_VERDANTURF_TOWN_HOUSE (7 | (6 << 8)) - -// gMapGroup_IndoorPacifidlog -#define MAP_PACIFIDLOG_TOWN_POKEMON_CENTER_1F (0 | (7 << 8)) -#define MAP_PACIFIDLOG_TOWN_POKEMON_CENTER_2F (1 | (7 << 8)) -#define MAP_PACIFIDLOG_TOWN_HOUSE1 (2 | (7 << 8)) -#define MAP_PACIFIDLOG_TOWN_HOUSE2 (3 | (7 << 8)) -#define MAP_PACIFIDLOG_TOWN_HOUSE3 (4 | (7 << 8)) -#define MAP_PACIFIDLOG_TOWN_HOUSE4 (5 | (7 << 8)) -#define MAP_PACIFIDLOG_TOWN_HOUSE5 (6 | (7 << 8)) - -// gMapGroup_IndoorPetalburg -#define MAP_PETALBURG_CITY_WALLYS_HOUSE (0 | (8 << 8)) -#define MAP_PETALBURG_CITY_GYM (1 | (8 << 8)) -#define MAP_PETALBURG_CITY_HOUSE1 (2 | (8 << 8)) -#define MAP_PETALBURG_CITY_HOUSE2 (3 | (8 << 8)) -#define MAP_PETALBURG_CITY_POKEMON_CENTER_1F (4 | (8 << 8)) -#define MAP_PETALBURG_CITY_POKEMON_CENTER_2F (5 | (8 << 8)) -#define MAP_PETALBURG_CITY_MART (6 | (8 << 8)) - -// gMapGroup_IndoorSlateport -#define MAP_SLATEPORT_CITY_STERNS_SHIPYARD_1F (0 | (9 << 8)) -#define MAP_SLATEPORT_CITY_STERNS_SHIPYARD_2F (1 | (9 << 8)) -#define MAP_SLATEPORT_CITY_CONTEST_LOBBY (2 | (9 << 8)) -#define MAP_SLATEPORT_CITY_CONTEST_HALL (3 | (9 << 8)) -#define MAP_SLATEPORT_CITY_HOUSE1 (4 | (9 << 8)) -#define MAP_SLATEPORT_CITY_POKEMON_FAN_CLUB (5 | (9 << 8)) -#define MAP_SLATEPORT_CITY_OCEANIC_MUSEUM_1F (6 | (9 << 8)) -#define MAP_SLATEPORT_CITY_OCEANIC_MUSEUM_2F (7 | (9 << 8)) -#define MAP_SLATEPORT_CITY_HARBOR (8 | (9 << 8)) -#define MAP_SLATEPORT_CITY_HOUSE2 (9 | (9 << 8)) -#define MAP_SLATEPORT_CITY_POKEMON_CENTER_1F (10 | (9 << 8)) -#define MAP_SLATEPORT_CITY_POKEMON_CENTER_2F (11 | (9 << 8)) -#define MAP_SLATEPORT_CITY_MART (12 | (9 << 8)) - -// gMapGroup_IndoorMauville -#define MAP_MAUVILLE_CITY_GYM (0 | (10 << 8)) -#define MAP_MAUVILLE_CITY_BIKE_SHOP (1 | (10 << 8)) -#define MAP_MAUVILLE_CITY_HOUSE1 (2 | (10 << 8)) -#define MAP_MAUVILLE_CITY_GAME_CORNER (3 | (10 << 8)) -#define MAP_MAUVILLE_CITY_HOUSE2 (4 | (10 << 8)) -#define MAP_MAUVILLE_CITY_POKEMON_CENTER_1F (5 | (10 << 8)) -#define MAP_MAUVILLE_CITY_POKEMON_CENTER_2F (6 | (10 << 8)) -#define MAP_MAUVILLE_CITY_MART (7 | (10 << 8)) - -// gMapGroup_IndoorRustboro -#define MAP_RUSTBORO_CITY_DEVON_CORP_1F (0 | (11 << 8)) -#define MAP_RUSTBORO_CITY_DEVON_CORP_2F (1 | (11 << 8)) -#define MAP_RUSTBORO_CITY_DEVON_CORP_3F (2 | (11 << 8)) -#define MAP_RUSTBORO_CITY_GYM (3 | (11 << 8)) -#define MAP_RUSTBORO_CITY_POKEMON_SCHOOL (4 | (11 << 8)) -#define MAP_RUSTBORO_CITY_POKEMON_CENTER_1F (5 | (11 << 8)) -#define MAP_RUSTBORO_CITY_POKEMON_CENTER_2F (6 | (11 << 8)) -#define MAP_RUSTBORO_CITY_MART (7 | (11 << 8)) -#define MAP_RUSTBORO_CITY_FLAT1_1F (8 | (11 << 8)) -#define MAP_RUSTBORO_CITY_FLAT1_2F (9 | (11 << 8)) -#define MAP_RUSTBORO_CITY_HOUSE1 (10 | (11 << 8)) -#define MAP_RUSTBORO_CITY_CUTTERS_HOUSE (11 | (11 << 8)) -#define MAP_RUSTBORO_CITY_HOUSE2 (12 | (11 << 8)) -#define MAP_RUSTBORO_CITY_FLAT2_1F (13 | (11 << 8)) -#define MAP_RUSTBORO_CITY_FLAT2_2F (14 | (11 << 8)) -#define MAP_RUSTBORO_CITY_FLAT2_3F (15 | (11 << 8)) -#define MAP_RUSTBORO_CITY_HOUSE3 (16 | (11 << 8)) - -// gMapGroup_IndoorFortree -#define MAP_FORTREE_CITY_HOUSE1 (0 | (12 << 8)) -#define MAP_FORTREE_CITY_GYM (1 | (12 << 8)) -#define MAP_FORTREE_CITY_POKEMON_CENTER_1F (2 | (12 << 8)) -#define MAP_FORTREE_CITY_POKEMON_CENTER_2F (3 | (12 << 8)) -#define MAP_FORTREE_CITY_MART (4 | (12 << 8)) -#define MAP_FORTREE_CITY_HOUSE2 (5 | (12 << 8)) -#define MAP_FORTREE_CITY_HOUSE3 (6 | (12 << 8)) -#define MAP_FORTREE_CITY_HOUSE4 (7 | (12 << 8)) -#define MAP_FORTREE_CITY_HOUSE5 (8 | (12 << 8)) -#define MAP_FORTREE_CITY_DECORATION_SHOP (9 | (12 << 8)) - -// gMapGroup_IndoorLilycove -#define MAP_LILYCOVE_CITY_COVE_LILY_MOTEL_1F (0 | (13 << 8)) -#define MAP_LILYCOVE_CITY_COVE_LILY_MOTEL_2F (1 | (13 << 8)) -#define MAP_LILYCOVE_CITY_LILYCOVE_MUSEUM_1F (2 | (13 << 8)) -#define MAP_LILYCOVE_CITY_LILYCOVE_MUSEUM_2F (3 | (13 << 8)) -#define MAP_LILYCOVE_CITY_CONTEST_LOBBY (4 | (13 << 8)) -#define MAP_LILYCOVE_CITY_CONTEST_HALL (5 | (13 << 8)) -#define MAP_LILYCOVE_CITY_POKEMON_CENTER_1F (6 | (13 << 8)) -#define MAP_LILYCOVE_CITY_POKEMON_CENTER_2F (7 | (13 << 8)) -#define MAP_LILYCOVE_CITY_UNUSED_MART (8 | (13 << 8)) -#define MAP_LILYCOVE_CITY_POKEMON_TRAINER_FAN_CLUB (9 | (13 << 8)) -#define MAP_LILYCOVE_CITY_HARBOR (10 | (13 << 8)) -#define MAP_LILYCOVE_CITY_EMPTY_MAP (11 | (13 << 8)) -#define MAP_LILYCOVE_CITY_MOVE_DELETERS_HOUSE (12 | (13 << 8)) -#define MAP_LILYCOVE_CITY_HOUSE1 (13 | (13 << 8)) -#define MAP_LILYCOVE_CITY_HOUSE2 (14 | (13 << 8)) -#define MAP_LILYCOVE_CITY_HOUSE3 (15 | (13 << 8)) -#define MAP_LILYCOVE_CITY_HOUSE4 (16 | (13 << 8)) -#define MAP_LILYCOVE_CITY_DEPARTMENT_STORE_1F (17 | (13 << 8)) -#define MAP_LILYCOVE_CITY_DEPARTMENT_STORE_2F (18 | (13 << 8)) -#define MAP_LILYCOVE_CITY_DEPARTMENT_STORE_3F (19 | (13 << 8)) -#define MAP_LILYCOVE_CITY_DEPARTMENT_STORE_4F (20 | (13 << 8)) -#define MAP_LILYCOVE_CITY_DEPARTMENT_STORE_5F (21 | (13 << 8)) -#define MAP_LILYCOVE_CITY_DEPARTMENT_STORE_ROOFTOP (22 | (13 << 8)) -#define MAP_LILYCOVE_CITY_DEPARTMENT_STORE_ELEVATOR (23 | (13 << 8)) - -// gMapGroup_IndoorMossdeep -#define MAP_MOSSDEEP_CITY_GYM (0 | (14 << 8)) -#define MAP_MOSSDEEP_CITY_HOUSE1 (1 | (14 << 8)) -#define MAP_MOSSDEEP_CITY_HOUSE2 (2 | (14 << 8)) -#define MAP_MOSSDEEP_CITY_POKEMON_CENTER_1F (3 | (14 << 8)) -#define MAP_MOSSDEEP_CITY_POKEMON_CENTER_2F (4 | (14 << 8)) -#define MAP_MOSSDEEP_CITY_MART (5 | (14 << 8)) -#define MAP_MOSSDEEP_CITY_HOUSE3 (6 | (14 << 8)) -#define MAP_MOSSDEEP_CITY_STEVENS_HOUSE (7 | (14 << 8)) -#define MAP_MOSSDEEP_CITY_HOUSE4 (8 | (14 << 8)) -#define MAP_MOSSDEEP_CITY_SPACE_CENTER_1F (9 | (14 << 8)) -#define MAP_MOSSDEEP_CITY_SPACE_CENTER_2F (10 | (14 << 8)) -#define MAP_MOSSDEEP_CITY_GAME_CORNER_1F (11 | (14 << 8)) -#define MAP_MOSSDEEP_CITY_GAME_CORNER_B1F (12 | (14 << 8)) - -// gMapGroup_IndoorSootopolis -#define MAP_SOOTOPOLIS_CITY_GYM_1F (0 | (15 << 8)) -#define MAP_SOOTOPOLIS_CITY_GYM_B1F (1 | (15 << 8)) -#define MAP_SOOTOPOLIS_CITY_POKEMON_CENTER_1F (2 | (15 << 8)) -#define MAP_SOOTOPOLIS_CITY_POKEMON_CENTER_2F (3 | (15 << 8)) -#define MAP_SOOTOPOLIS_CITY_MART (4 | (15 << 8)) -#define MAP_SOOTOPOLIS_CITY_HOUSE1 (5 | (15 << 8)) -#define MAP_SOOTOPOLIS_CITY_HOUSE2 (6 | (15 << 8)) -#define MAP_SOOTOPOLIS_CITY_HOUSE3 (7 | (15 << 8)) -#define MAP_SOOTOPOLIS_CITY_HOUSE4 (8 | (15 << 8)) -#define MAP_SOOTOPOLIS_CITY_HOUSE5 (9 | (15 << 8)) -#define MAP_SOOTOPOLIS_CITY_HOUSE6 (10 | (15 << 8)) -#define MAP_SOOTOPOLIS_CITY_HOUSE7 (11 | (15 << 8)) -#define MAP_SOOTOPOLIS_CITY_HOUSE8 (12 | (15 << 8)) - -// gMapGroup_IndoorEverGrande -#define MAP_EVER_GRANDE_CITY_SIDNEYS_ROOM (0 | (16 << 8)) -#define MAP_EVER_GRANDE_CITY_PHOEBES_ROOM (1 | (16 << 8)) -#define MAP_EVER_GRANDE_CITY_GLACIAS_ROOM (2 | (16 << 8)) -#define MAP_EVER_GRANDE_CITY_DRAKES_ROOM (3 | (16 << 8)) -#define MAP_EVER_GRANDE_CITY_CHAMPIONS_ROOM (4 | (16 << 8)) -#define MAP_EVER_GRANDE_CITY_CORRIDOR1 (5 | (16 << 8)) -#define MAP_EVER_GRANDE_CITY_CORRIDOR2 (6 | (16 << 8)) -#define MAP_EVER_GRANDE_CITY_CORRIDOR3 (7 | (16 << 8)) -#define MAP_EVER_GRANDE_CITY_CORRIDOR4 (8 | (16 << 8)) -#define MAP_EVER_GRANDE_CITY_CORRIDOR5 (9 | (16 << 8)) -#define MAP_EVER_GRANDE_CITY_POKEMON_LEAGUE (10 | (16 << 8)) -#define MAP_EVER_GRANDE_CITY_HALL_OF_FAME (11 | (16 << 8)) -#define MAP_EVER_GRANDE_CITY_POKEMON_CENTER_1F (12 | (16 << 8)) -#define MAP_EVER_GRANDE_CITY_POKEMON_CENTER_2F (13 | (16 << 8)) - -// gMapGroup_IndoorRoute104 -#define MAP_ROUTE104_MR_BRINEYS_HOUSE (0 | (17 << 8)) -#define MAP_ROUTE104_PRETTY_PETAL_FLOWER_SHOP (1 | (17 << 8)) - -// gMapGroup_IndoorRoute111 -#define MAP_ROUTE111_WINSTRATE_FAMILYS_HOUSE (0 | (18 << 8)) -#define MAP_ROUTE111_OLD_LADYS_REST_STOP (1 | (18 << 8)) - -// gMapGroup_IndoorRoute112 -#define MAP_ROUTE112_CABLE_CAR_STATION (0 | (19 << 8)) -#define MAP_MT_CHIMNEY_CABLE_CAR_STATION (1 | (19 << 8)) - -// gMapGroup_IndoorRoute114 -#define MAP_ROUTE114_FOSSIL_MANIACS_HOUSE (0 | (20 << 8)) -#define MAP_ROUTE114_FOSSIL_MANIACS_TUNNEL (1 | (20 << 8)) -#define MAP_ROUTE114_LANETTES_HOUSE (2 | (20 << 8)) - -// gMapGroup_IndoorRoute116 -#define MAP_ROUTE116_TUNNELERS_REST_HOUSE (0 | (21 << 8)) - -// gMapGroup_IndoorRoute117 -#define MAP_ROUTE117_POKEMON_DAY_CARE (0 | (22 << 8)) - -// gMapGroup_IndoorRoute121 -#define MAP_ROUTE121_SAFARI_ZONE_ENTRANCE (0 | (23 << 8)) - -// gMapGroup_Dungeons -#define MAP_METEOR_FALLS_1F_1R (0 | (24 << 8)) -#define MAP_METEOR_FALLS_1F_2R (1 | (24 << 8)) -#define MAP_METEOR_FALLS_B1F_1R (2 | (24 << 8)) -#define MAP_METEOR_FALLS_B1F_2R (3 | (24 << 8)) -#define MAP_RUSTURF_TUNNEL (4 | (24 << 8)) -#define MAP_UNDERWATER_SOOTOPOLIS_CITY (5 | (24 << 8)) -#define MAP_DESERT_RUINS (6 | (24 << 8)) -#define MAP_GRANITE_CAVE_1F (7 | (24 << 8)) -#define MAP_GRANITE_CAVE_B1F (8 | (24 << 8)) -#define MAP_GRANITE_CAVE_B2F (9 | (24 << 8)) -#define MAP_GRANITE_CAVE_STEVENS_ROOM (10 | (24 << 8)) -#define MAP_PETALBURG_WOODS (11 | (24 << 8)) -#define MAP_MT_CHIMNEY (12 | (24 << 8)) -#define MAP_JAGGED_PASS (13 | (24 << 8)) -#define MAP_FIERY_PATH (14 | (24 << 8)) -#define MAP_MT_PYRE_1F (15 | (24 << 8)) -#define MAP_MT_PYRE_2F (16 | (24 << 8)) -#define MAP_MT_PYRE_3F (17 | (24 << 8)) -#define MAP_MT_PYRE_4F (18 | (24 << 8)) -#define MAP_MT_PYRE_5F (19 | (24 << 8)) -#define MAP_MT_PYRE_6F (20 | (24 << 8)) -#define MAP_MT_PYRE_EXTERIOR (21 | (24 << 8)) -#define MAP_MT_PYRE_SUMMIT (22 | (24 << 8)) -#define MAP_AQUA_HIDEOUT_1F (23 | (24 << 8)) -#define MAP_AQUA_HIDEOUT_B1F (24 | (24 << 8)) -#define MAP_AQUA_HIDEOUT_B2F (25 | (24 << 8)) -#define MAP_UNDERWATER_SEAFLOOR_CAVERN (26 | (24 << 8)) -#define MAP_SEAFLOOR_CAVERN_ENTRANCE (27 | (24 << 8)) -#define MAP_SEAFLOOR_CAVERN_ROOM1 (28 | (24 << 8)) -#define MAP_SEAFLOOR_CAVERN_ROOM2 (29 | (24 << 8)) -#define MAP_SEAFLOOR_CAVERN_ROOM3 (30 | (24 << 8)) -#define MAP_SEAFLOOR_CAVERN_ROOM4 (31 | (24 << 8)) -#define MAP_SEAFLOOR_CAVERN_ROOM5 (32 | (24 << 8)) -#define MAP_SEAFLOOR_CAVERN_ROOM6 (33 | (24 << 8)) -#define MAP_SEAFLOOR_CAVERN_ROOM7 (34 | (24 << 8)) -#define MAP_SEAFLOOR_CAVERN_ROOM8 (35 | (24 << 8)) -#define MAP_SEAFLOOR_CAVERN_ROOM9 (36 | (24 << 8)) -#define MAP_CAVE_OF_ORIGIN_ENTRANCE (37 | (24 << 8)) -#define MAP_CAVE_OF_ORIGIN_1F (38 | (24 << 8)) -#define MAP_CAVE_OF_ORIGIN_B1F (39 | (24 << 8)) -#define MAP_CAVE_OF_ORIGIN_B2F (40 | (24 << 8)) -#define MAP_CAVE_OF_ORIGIN_B3F (41 | (24 << 8)) -#define MAP_CAVE_OF_ORIGIN_B4F (42 | (24 << 8)) -#define MAP_VICTORY_ROAD_1F (43 | (24 << 8)) -#define MAP_VICTORY_ROAD_B1F (44 | (24 << 8)) -#define MAP_VICTORY_ROAD_B2F (45 | (24 << 8)) -#define MAP_SHOAL_CAVE_LOW_TIDE_ENTRANCE_ROOM (46 | (24 << 8)) -#define MAP_SHOAL_CAVE_LOW_TIDE_INNER_ROOM (47 | (24 << 8)) -#define MAP_SHOAL_CAVE_LOW_TIDE_STAIRS_ROOM (48 | (24 << 8)) -#define MAP_SHOAL_CAVE_LOW_TIDE_LOWER_ROOM (49 | (24 << 8)) -#define MAP_SHOAL_CAVE_HIGH_TIDE_ENTRANCE_ROOM (50 | (24 << 8)) -#define MAP_SHOAL_CAVE_HIGH_TIDE_INNER_ROOM (51 | (24 << 8)) -#define MAP_NEW_MAUVILLE_ENTRANCE (52 | (24 << 8)) -#define MAP_NEW_MAUVILLE_INSIDE (53 | (24 << 8)) -#define MAP_ABANDONED_SHIP_DECK (54 | (24 << 8)) -#define MAP_ABANDONED_SHIP_CORRIDORS_1F (55 | (24 << 8)) -#define MAP_ABANDONED_SHIP_ROOMS_1F (56 | (24 << 8)) -#define MAP_ABANDONED_SHIP_CORRIDORS_B1F (57 | (24 << 8)) -#define MAP_ABANDONED_SHIP_ROOMS_B1F (58 | (24 << 8)) -#define MAP_ABANDONED_SHIP_ROOMS2_B1F (59 | (24 << 8)) -#define MAP_ABANDONED_SHIP_UNDERWATER1 (60 | (24 << 8)) -#define MAP_ABANDONED_SHIP_ROOM_B1F (61 | (24 << 8)) -#define MAP_ABANDONED_SHIP_ROOMS2_1F (62 | (24 << 8)) -#define MAP_ABANDONED_SHIP_CAPTAINS_OFFICE (63 | (24 << 8)) -#define MAP_ABANDONED_SHIP_UNDERWATER2 (64 | (24 << 8)) -#define MAP_ABANDONED_SHIP_HIDDEN_FLOOR_CORRIDORS (65 | (24 << 8)) -#define MAP_ABANDONED_SHIP_HIDDEN_FLOOR_ROOMS (66 | (24 << 8)) -#define MAP_ISLAND_CAVE (67 | (24 << 8)) -#define MAP_ANCIENT_TOMB (68 | (24 << 8)) -#define MAP_UNDERWATER_ROUTE134 (69 | (24 << 8)) -#define MAP_UNDERWATER_SEALED_CHAMBER (70 | (24 << 8)) -#define MAP_SEALED_CHAMBER_OUTER_ROOM (71 | (24 << 8)) -#define MAP_SEALED_CHAMBER_INNER_ROOM (72 | (24 << 8)) -#define MAP_SCORCHED_SLAB (73 | (24 << 8)) -#define MAP_MAGMA_HIDEOUT_1F (74 | (24 << 8)) -#define MAP_MAGMA_HIDEOUT_B1F (75 | (24 << 8)) -#define MAP_MAGMA_HIDEOUT_B2F (76 | (24 << 8)) -#define MAP_SKY_PILLAR_ENTRANCE (77 | (24 << 8)) -#define MAP_SKY_PILLAR_OUTSIDE (78 | (24 << 8)) -#define MAP_SKY_PILLAR_1F (79 | (24 << 8)) -#define MAP_SKY_PILLAR_2F (80 | (24 << 8)) -#define MAP_SKY_PILLAR_3F (81 | (24 << 8)) -#define MAP_SKY_PILLAR_4F (82 | (24 << 8)) -#define MAP_SHOAL_CAVE_LOW_TIDE_ICE_ROOM (83 | (24 << 8)) -#define MAP_SKY_PILLAR_5F (84 | (24 << 8)) -#define MAP_SKY_PILLAR_TOP (85 | (24 << 8)) - -// gMapGroup_IndoorDynamic -#define MAP_SECRET_BASE_RED_CAVE1 (0 | (25 << 8)) -#define MAP_SECRET_BASE_BROWN_CAVE1 (1 | (25 << 8)) -#define MAP_SECRET_BASE_BLUE_CAVE1 (2 | (25 << 8)) -#define MAP_SECRET_BASE_YELLOW_CAVE1 (3 | (25 << 8)) -#define MAP_SECRET_BASE_TREE1 (4 | (25 << 8)) -#define MAP_SECRET_BASE_SHRUB1 (5 | (25 << 8)) -#define MAP_SECRET_BASE_RED_CAVE2 (6 | (25 << 8)) -#define MAP_SECRET_BASE_BROWN_CAVE2 (7 | (25 << 8)) -#define MAP_SECRET_BASE_BLUE_CAVE2 (8 | (25 << 8)) -#define MAP_SECRET_BASE_YELLOW_CAVE2 (9 | (25 << 8)) -#define MAP_SECRET_BASE_TREE2 (10 | (25 << 8)) -#define MAP_SECRET_BASE_SHRUB2 (11 | (25 << 8)) -#define MAP_SECRET_BASE_RED_CAVE3 (12 | (25 << 8)) -#define MAP_SECRET_BASE_BROWN_CAVE3 (13 | (25 << 8)) -#define MAP_SECRET_BASE_BLUE_CAVE3 (14 | (25 << 8)) -#define MAP_SECRET_BASE_YELLOW_CAVE3 (15 | (25 << 8)) -#define MAP_SECRET_BASE_TREE3 (16 | (25 << 8)) -#define MAP_SECRET_BASE_SHRUB3 (17 | (25 << 8)) -#define MAP_SECRET_BASE_RED_CAVE4 (18 | (25 << 8)) -#define MAP_SECRET_BASE_BROWN_CAVE4 (19 | (25 << 8)) -#define MAP_SECRET_BASE_BLUE_CAVE4 (20 | (25 << 8)) -#define MAP_SECRET_BASE_YELLOW_CAVE4 (21 | (25 << 8)) -#define MAP_SECRET_BASE_TREE4 (22 | (25 << 8)) -#define MAP_SECRET_BASE_SHRUB4 (23 | (25 << 8)) -#define MAP_SINGLE_BATTLE_COLOSSEUM (24 | (25 << 8)) -#define MAP_TRADE_CENTER (25 | (25 << 8)) -#define MAP_RECORD_CORNER (26 | (25 << 8)) -#define MAP_DOUBLE_BATTLE_COLOSSEUM (27 | (25 << 8)) -#define MAP_LINK_CONTEST_ROOM1 (28 | (25 << 8)) -#define MAP_UNKNOWN_MAP_25_29 (29 | (25 << 8)) -#define MAP_UNKNOWN_MAP_25_30 (30 | (25 << 8)) -#define MAP_UNKNOWN_MAP_25_31 (31 | (25 << 8)) -#define MAP_UNKNOWN_MAP_25_32 (32 | (25 << 8)) -#define MAP_UNKNOWN_MAP_25_33 (33 | (25 << 8)) -#define MAP_UNKNOWN_MAP_25_34 (34 | (25 << 8)) -#define MAP_LINK_CONTEST_ROOM2 (35 | (25 << 8)) -#define MAP_LINK_CONTEST_ROOM3 (36 | (25 << 8)) -#define MAP_LINK_CONTEST_ROOM4 (37 | (25 << 8)) -#define MAP_LINK_CONTEST_ROOM5 (38 | (25 << 8)) -#define MAP_LINK_CONTEST_ROOM6 (39 | (25 << 8)) -#define MAP_INSIDE_OF_TRUCK (40 | (25 << 8)) -#define MAP_SS_TIDAL_CORRIDOR (41 | (25 << 8)) -#define MAP_SS_TIDAL_LOWER_DECK (42 | (25 << 8)) -#define MAP_SS_TIDAL_ROOMS (43 | (25 << 8)) - -// gMapGroup_SpecialArea -#define MAP_SAFARI_ZONE_NORTHWEST (0 | (26 << 8)) -#define MAP_SAFARI_ZONE_NORTHEAST (1 | (26 << 8)) -#define MAP_SAFARI_ZONE_SOUTHWEST (2 | (26 << 8)) -#define MAP_SAFARI_ZONE_SOUTHEAST (3 | (26 << 8)) -#define MAP_BATTLE_TOWER_OUTSIDE (4 | (26 << 8)) -#define MAP_BATTLE_TOWER_LOBBY (5 | (26 << 8)) -#define MAP_BATTLE_TOWER_ELEVATOR (6 | (26 << 8)) -#define MAP_BATTLE_TOWER_CORRIDOR (7 | (26 << 8)) -#define MAP_BATTLE_TOWER_BATTLE_ROOM (8 | (26 << 8)) -#define MAP_SOUTHERN_ISLAND_EXTERIOR (9 | (26 << 8)) -#define MAP_SOUTHERN_ISLAND_INTERIOR (10 | (26 << 8)) -#define MAP_SAFARI_ZONE_REST_HOUSE (11 | (26 << 8)) - -// gMapGroup_IndoorRoute104Prototype -#define MAP_ROUTE104_PROTOTYPE (0 | (27 << 8)) -#define MAP_ROUTE104_PROTOTYPE_PRETTY_PETAL_FLOWER_SHOP (1 | (27 << 8)) - -// gMapGroup_IndoorRoute109 -#define MAP_ROUTE109_SEASHORE_HOUSE (0 | (28 << 8)) - -// gMapGroup_IndoorRoute110 -#define MAP_ROUTE110_TRICK_HOUSE_ENTRANCE (0 | (29 << 8)) -#define MAP_ROUTE110_TRICK_HOUSE_END (1 | (29 << 8)) -#define MAP_ROUTE110_TRICK_HOUSE_CORRIDOR (2 | (29 << 8)) -#define MAP_ROUTE110_TRICK_HOUSE_PUZZLE1 (3 | (29 << 8)) -#define MAP_ROUTE110_TRICK_HOUSE_PUZZLE2 (4 | (29 << 8)) -#define MAP_ROUTE110_TRICK_HOUSE_PUZZLE3 (5 | (29 << 8)) -#define MAP_ROUTE110_TRICK_HOUSE_PUZZLE4 (6 | (29 << 8)) -#define MAP_ROUTE110_TRICK_HOUSE_PUZZLE5 (7 | (29 << 8)) -#define MAP_ROUTE110_TRICK_HOUSE_PUZZLE6 (8 | (29 << 8)) -#define MAP_ROUTE110_TRICK_HOUSE_PUZZLE7 (9 | (29 << 8)) -#define MAP_ROUTE110_TRICK_HOUSE_PUZZLE8 (10 | (29 << 8)) -#define MAP_ROUTE110_SEASIDE_CYCLING_ROAD_SOUTH_ENTRANCE (11 | (29 << 8)) -#define MAP_ROUTE110_SEASIDE_CYCLING_ROAD_NORTH_ENTRANCE (12 | (29 << 8)) - -// gMapGroup_IndoorRoute113 -#define MAP_ROUTE113_GLASS_WORKSHOP (0 | (30 << 8)) - -// gMapGroup_IndoorRoute123 -#define MAP_ROUTE123_BERRY_MASTERS_HOUSE (0 | (31 << 8)) - -// gMapGroup_IndoorRoute119 -#define MAP_ROUTE119_WEATHER_INSTITUTE_1F (0 | (32 << 8)) -#define MAP_ROUTE119_WEATHER_INSTITUTE_2F (1 | (32 << 8)) -#define MAP_ROUTE119_HOUSE (2 | (32 << 8)) - -// gMapGroup_IndoorRoute124 -#define MAP_ROUTE124_DIVING_TREASURE_HUNTERS_HOUSE (0 | (33 << 8)) - -#define MAP_GROUPS_COUNT 34 - -#endif // GUARD_CONSTANTS_MAP_GROUPS_H diff --git a/include/text.h b/include/text.h index f765a0e055..1f518b8632 100644 --- a/include/text.h +++ b/include/text.h @@ -1,124 +1,7 @@ #ifndef GUARD_TEXT_H #define GUARD_TEXT_H -#define CHAR_SPACE 0x00 -#define CHAR_LV 0x34 -#define CHAR_SONG_WORD_SEPARATOR 0x37 // separates words in the bard song. Not sure if it's used for anything else -#define CHAR_0 0xA1 -#define CHAR_EXCL_MARK 0xAB -#define CHAR_QUESTION_MARK 0xAC -#define CHAR_PERIOD 0xAD -#define CHAR_HYPHEN 0xAE -#define CHAR_ELLIPSIS 0xB0 -#define CHAR_DBL_QUOT_LEFT 0xB1 -#define CHAR_DBL_QUOT_RIGHT 0xB2 -#define CHAR_SGL_QUOT_LEFT 0xB3 -#define CHAR_SGL_QUOT_RIGHT 0xB4 -#define CHAR_MALE 0xB5 -#define CHAR_FEMALE 0xB6 -#define CHAR_CURRENCY 0xB7 -#define CHAR_COMMA 0xB8 -#define CHAR_MULT_SIGN 0xB9 -#define CHAR_SLASH 0xBA -#define CHAR_A 0xBB -#define CHAR_B 0xBC -#define CHAR_C 0xBD -#define CHAR_D 0xBE -#define CHAR_E 0xBF -#define CHAR_F 0xC0 -#define CHAR_G 0xC1 -#define CHAR_H 0xC2 -#define CHAR_I 0xC3 -#define CHAR_J 0xC4 -#define CHAR_K 0xC5 -#define CHAR_L 0xC6 -#define CHAR_M 0xC7 -#define CHAR_N 0xC8 -#define CHAR_O 0xC9 -#define CHAR_P 0xCA -#define CHAR_Q 0xCB -#define CHAR_R 0xCC -#define CHAR_S 0xCD -#define CHAR_T 0xCE -#define CHAR_U 0xCF -#define CHAR_V 0xD0 -#define CHAR_W 0xD1 -#define CHAR_X 0xD2 -#define CHAR_Y 0xD3 -#define CHAR_Z 0xD4 -#define CHAR_a 0xD5 -#define CHAR_b 0xD6 -#define CHAR_c 0xD7 -#define CHAR_d 0xD8 -#define CHAR_e 0xD9 -#define CHAR_f 0xDA -#define CHAR_g 0xDB -#define CHAR_h 0xDC -#define CHAR_i 0xDD -#define CHAR_j 0xDE -#define CHAR_k 0xDF -#define CHAR_l 0xE0 -#define CHAR_m 0xE1 -#define CHAR_n 0xE2 -#define CHAR_o 0xE3 -#define CHAR_p 0xE4 -#define CHAR_q 0xE5 -#define CHAR_r 0xE6 -#define CHAR_s 0xE7 -#define CHAR_t 0xE8 -#define CHAR_u 0xE9 -#define CHAR_v 0xEA -#define CHAR_w 0xEB -#define CHAR_x 0xEC -#define CHAR_y 0xED -#define CHAR_z 0xEE -#define CHAR_COLON 0xF0 -#define CHAR_PROMPT_SCROLL 0xFA // waits for button press and scrolls dialog -#define CHAR_PROMPT_CLEAR 0xFB // waits for button press and clears dialog -#define EXT_CTRL_CODE_BEGIN 0xFC // extended control code -#define PLACEHOLDER_BEGIN 0xFD // string placeholder -#define CHAR_NEWLINE 0xFE -#define EOS 0xFF // end of string - -#define TEXT_COLOR_TRANSPARENT 0x00 -#define TEXT_COLOR_DARK_GREY 0x01 -#define TEXT_COLOR_RED 0x02 -#define TEXT_COLOR_GREEN 0x03 -#define TEXT_COLOR_BLUE 0x04 -#define TEXT_COLOR_YELLOW 0x05 -#define TEXT_COLOR_CYAN 0x06 -#define TEXT_COLOR_MAGENTA 0x07 -#define TEXT_COLOR_LIGHT_GREY 0x08 -#define TEXT_COLOR_BLACK 0x09 -#define TEXT_COLOR_BLACK2 0x0A -#define TEXT_COLOR_SILVER 0x0B -#define TEXT_COLOR_WHITE 0x0C -#define TEXT_COLOR_SKY_BLUE 0x0D -#define TEXT_COLOR_LIGHT_BLUE 0x0E -#define TEXT_COLOR_WHITE2 0x0F - -#define EXT_CTRL_CODE_COLOR 0x01 -#define EXT_CTRL_CODE_HIGHLIGHT 0x02 -#define EXT_CTRL_CODE_SHADOW 0x03 -#define EXT_CTRL_CODE_COLOR_HIGHLIGHT_SHADOW 0x04 -#define EXT_CTRL_CODE_PALETTE 0x05 -#define EXT_CTRL_CODE_SIZE 0x06 -#define EXT_CTRL_CODE_RESET_SIZE 0x07 -#define EXT_CTRL_CODE_PAUSE 0x08 -#define EXT_CTRL_CODE_PAUSE_UNTIL_PRESS 0x09 -#define EXT_CTRL_CODE_WAIT_SE 0x0A -#define EXT_CTRL_CODE_PLAY_BGM 0x0B -#define EXT_CTRL_CODE_ESCAPE 0x0C -#define EXT_CTRL_CODE_SHIFT_TEXT 0x0D // nop -#define EXT_CTRL_CODE_SHIFT_DOWN 0x0E -#define EXT_CTRL_CODE_FILL_WINDOW 0x0F -#define EXT_CTRL_CODE_PLAY_SE 0x10 -#define EXT_CTRL_CODE_CLEAR 0x11 -#define EXT_CTRL_CODE_SKIP 0x12 -#define EXT_CTRL_CODE_CLEAR_TO 0x13 -#define EXT_CTRL_CODE_MIN_LETTER_SPACING 0x14 -#define EXT_CTRL_CODE_JPN 0x15 -#define EXT_CTRL_CODE_ENG 0x16 +#include "characters.h" struct WindowTemplate { diff --git a/make_tools.mk b/make_tools.mk new file mode 100644 index 0000000000..ca8e9c863a --- /dev/null +++ b/make_tools.mk @@ -0,0 +1,22 @@ +# This controls building executables in the `tools` folder. +# Can be invoked through the `Makefile` or standalone. + +MAKEFLAGS += --no-print-directory + +# Inclusive list. If you don't want a tool to be built, don't add it here. +TOOLS_DIR := tools +TOOL_NAMES := aif2pcm bin2c gbafix gbagfx jsonproc mapjson mid2agb preproc ramscrgen rsfont scaninc + +TOOLDIRS := $(TOOL_NAMES:%=$(TOOLS_DIR)/%) + +# Tool making doesnt require a pokefirered dependency scan. +RULES_NO_SCAN += tools check-tools clean-tools $(TOOLDIRS) +.PHONY: $(RULES_NO_SCAN) + +tools: $(TOOLDIRS) + +$(TOOLDIRS): + @$(MAKE) -C $@ + +clean-tools: + @$(foreach tooldir,$(TOOLDIRS),$(MAKE) clean -C $(tooldir);) diff --git a/map_data_rules.mk b/map_data_rules.mk index 89308fba17..6a7d4c96c4 100755 --- a/map_data_rules.mk +++ b/map_data_rules.mk @@ -1,31 +1,32 @@ # Map JSON data -MAPS_DIR = data/maps -LAYOUTS_DIR = data/layouts +# Inputs +MAPS_DIR = $(DATA_ASM_SUBDIR)/maps +LAYOUTS_DIR = $(DATA_ASM_SUBDIR)/layouts -MAP_DIRS := $(dir $(wildcard $(MAPS_DIR)/*/)) +# Outputs +MAPS_OUTDIR := $(MAPS_DIR) +LAYOUTS_OUTDIR := $(LAYOUTS_DIR) +INCLUDECONSTS_OUTDIR := include/constants + +AUTO_GEN_TARGETS += $(INCLUDECONSTS_OUTDIR)/map_groups.h +AUTO_GEN_TARGETS += $(INCLUDECONSTS_OUTDIR)/layouts.h + +MAP_DIRS := $(dir $(wildcard $(MAPS_DIR)/*/map.json)) MAP_CONNECTIONS := $(patsubst $(MAPS_DIR)/%/,$(MAPS_DIR)/%/connections.inc,$(MAP_DIRS)) MAP_EVENTS := $(patsubst $(MAPS_DIR)/%/,$(MAPS_DIR)/%/events.inc,$(MAP_DIRS)) MAP_HEADERS := $(patsubst $(MAPS_DIR)/%/,$(MAPS_DIR)/%/header.inc,$(MAP_DIRS)) $(BUILD_DIR)/data/maps.o: data/maps.s $(LAYOUTS_DIR)/layouts.inc $(LAYOUTS_DIR)/layouts_table.inc $(MAPS_DIR)/headers.inc $(MAPS_DIR)/groups.inc $(MAPS_DIR)/connections.inc $(MAP_CONNECTIONS) $(MAP_HEADERS) - $(PREPROC) $< charmap.txt | $(CPP) -I include | $(AS) $(ASFLAGS) -o $@ + $(PREPROC) $< charmap.txt | $(CPP) -I include -nostdinc -undef -Wno-unicode - | $(PREPROC) -ie $< charmap.txt | $(AS) $(ASFLAGS) -o $@ $(BUILD_DIR)/data/map_events.o: data/map_events.s $(MAPS_DIR)/events.inc $(MAP_EVENTS) - $(PREPROC) $< charmap.txt | $(CPP) -I include | $(AS) $(ASFLAGS) -o $@ - -$(MAPS_DIR)/%/header.inc: $(MAPS_DIR)/%/map.json - $(MAPJSON) map ruby $< $(LAYOUTS_DIR)/layouts.json -$(MAPS_DIR)/%/events.inc: $(MAPS_DIR)/%/header.inc ; -$(MAPS_DIR)/%/connections.inc: $(MAPS_DIR)/%/events.inc ; - -$(MAPS_DIR)/groups.inc: $(MAPS_DIR)/map_groups.json - $(MAPJSON) groups ruby $< -$(MAPS_DIR)/connections.inc: $(MAPS_DIR)/groups.inc ; -$(MAPS_DIR)/events.inc: $(MAPS_DIR)/connections.inc ; -$(MAPS_DIR)/headers.inc: $(MAPS_DIR)/events.inc ; -include/constants/map_groups.h: $(MAPS_DIR)/headers.inc ; - -$(LAYOUTS_DIR)/layouts.inc: $(LAYOUTS_DIR)/layouts.json - $(MAPJSON) layouts ruby $< -$(LAYOUTS_DIR)/layouts_table.inc: $(LAYOUTS_DIR)/layouts.inc ; -include/constants/layouts.h: $(LAYOUTS_DIR)/layouts_table.inc ; + $(PREPROC) $< charmap.txt | $(CPP) -I include -nostdinc -undef -Wno-unicode - | $(PREPROC) -ie $< charmap.txt | $(AS) $(ASFLAGS) -o $@ + +$(MAPS_OUTDIR)/%/header.inc $(MAPS_OUTDIR)/%/events.inc $(MAPS_OUTDIR)/%/connections.inc: $(MAPS_DIR)/%/map.json + $(MAPJSON) map ruby $< $(LAYOUTS_DIR)/layouts.json $(@D) + +$(MAPS_OUTDIR)/connections.inc $(MAPS_OUTDIR)/groups.inc $(MAPS_OUTDIR)/events.inc $(MAPS_OUTDIR)/headers.inc $(INCLUDECONSTS_OUTDIR)/map_groups.h: $(MAPS_DIR)/map_groups.json + $(MAPJSON) groups ruby $< $(MAPS_OUTDIR) $(INCLUDECONSTS_OUTDIR) + +$(LAYOUTS_OUTDIR)/layouts.inc $(LAYOUTS_OUTDIR)/layouts_table.inc $(INCLUDECONSTS_OUTDIR)/layouts.h: $(LAYOUTS_DIR)/layouts.json + $(MAPJSON) layouts ruby $< $(LAYOUTS_OUTDIR) $(INCLUDECONSTS_OUTDIR) diff --git a/tools/aif2pcm/Makefile b/tools/aif2pcm/Makefile index 790ed71f2e..dd48a87597 100644 --- a/tools/aif2pcm/Makefile +++ b/tools/aif2pcm/Makefile @@ -1,17 +1,23 @@ -CC = gcc +CC ?= gcc -CFLAGS = -Wall -Wextra -Wno-switch -Werror -std=c11 -O2 -s +CFLAGS = -Wall -Wextra -Wno-switch -Werror -std=c11 -O2 LIBS = -lm SRCS = main.c extended.c +ifeq ($(OS),Windows_NT) +EXE := .exe +else +EXE := +endif + .PHONY: all clean -all: aif2pcm +all: aif2pcm$(EXE) @: -aif2pcm: $(SRCS) +aif2pcm$(EXE): $(SRCS) $(CC) $(CFLAGS) $(SRCS) -o $@ $(LDFLAGS) $(LIBS) clean: diff --git a/tools/aif2pcm/main.c b/tools/aif2pcm/main.c index cd5ac4a505..0824b92da8 100644 --- a/tools/aif2pcm/main.c +++ b/tools/aif2pcm/main.c @@ -51,8 +51,12 @@ do \ typedef struct { unsigned long num_samples; - uint8_t *samples; + union { + uint8_t *samples8; + uint16_t *samples16; + }; uint8_t midi_note; + uint8_t sample_size; bool has_loop; unsigned long loop_offset; double sample_rate; @@ -208,11 +212,11 @@ void read_aif(struct Bytes *aif, AifData *aif_data) num_sample_frames |= (aif->data[pos++] << 8); num_sample_frames |= (uint8_t)aif->data[pos++]; - short sample_size = (aif->data[pos++] << 8); - sample_size |= (uint8_t)aif->data[pos++]; - if (sample_size != 8) + aif_data->sample_size = (aif->data[pos++] << 8); + aif_data->sample_size |= (uint8_t)aif->data[pos++]; + if (aif_data->sample_size != 8 && aif_data->sample_size != 16) { - FATAL_ERROR("sampleSize (%d) in the COMM Chunk must be 8!\n", sample_size); + FATAL_ERROR("sampleSize (%d) in the COMM Chunk must be 8 or 16!\n", aif_data->sample_size); } double sample_rate = ieee754_read_extended((uint8_t*)(aif->data + pos)); @@ -234,7 +238,7 @@ void read_aif(struct Bytes *aif, AifData *aif_data) { FATAL_ERROR("More than one MARK Chunk in file!\n"); } - + markers = calloc(num_markers, sizeof(struct Marker)); // Read each marker. @@ -285,7 +289,7 @@ void read_aif(struct Bytes *aif, AifData *aif_data) // Skip NoLooping sustain loop. pos += 4; } - + // Skip release loop, we don't need it. pos += 6; } @@ -295,11 +299,28 @@ void read_aif(struct Bytes *aif, AifData *aif_data) pos += 8; unsigned long num_samples = chunk_size - 8; - uint8_t *sample_data = (uint8_t *)malloc(num_samples * sizeof(uint8_t)); - memcpy(sample_data, &aif->data[pos], num_samples); + if (aif_data->sample_size == 8) + { + uint8_t *sample_data = (uint8_t *)malloc(num_samples * sizeof(uint8_t)); + memcpy(sample_data, &aif->data[pos], num_samples); + + aif_data->samples8 = sample_data; + aif_data->real_num_samples = num_samples; + } + else + { + uint16_t *sample_data = (uint16_t *)malloc(num_samples * sizeof(uint16_t)); + uint16_t *sample_data_swapped = (uint16_t *)malloc(num_samples * sizeof(uint16_t)); + memcpy(sample_data, &aif->data[pos], num_samples); + for (long unsigned i = 0; i < num_samples; i++) + { + sample_data_swapped[i] = __builtin_bswap16(sample_data[i]); + } - aif_data->samples = sample_data; - aif_data->real_num_samples = num_samples; + aif_data->samples16 = sample_data_swapped; + aif_data->real_num_samples = num_samples; + free(sample_data); + } pos += chunk_size - 8; } else @@ -308,12 +329,12 @@ void read_aif(struct Bytes *aif, AifData *aif_data) pos += chunk_size; } } - + if (markers) { // Resolve loop points. struct Marker *cur_marker = markers; - + // Grab loop start point. for (int i = 0; i < num_markers; i++, cur_marker++) { @@ -351,6 +372,12 @@ const int gDeltaEncodingTable[] = { -64, -49, -36, -25, -16, -9, -4, -1, }; +#define POSITIVE_DELTAS_START 0 +#define POSITIVE_DELTAS_END 8 + +#define NEGATIVE_DELTAS_START 8 +#define NEGATIVE_DELTAS_END 16 + struct Bytes *delta_decompress(struct Bytes *delta, unsigned int expected_length) { struct Bytes *pcm = malloc(sizeof(struct Bytes)); @@ -418,15 +445,32 @@ struct Bytes *delta_decompress(struct Bytes *delta, unsigned int expected_length return pcm; } +#define U8_TO_S8(value) ((value) < 128 ? (value) : (value) - 256) +#define ABS(value) ((value) >= 0 ? (value) : -(value)) + int get_delta_index(uint8_t sample, uint8_t prev_sample) { int best_error = INT_MAX; int best_index = -1; + int delta_table_start_index; + int delta_table_end_index; + int sample_signed = U8_TO_S8(sample); + int prev_sample_signed = U8_TO_S8(prev_sample); + + // if we're going up (or equal), only choose positive deltas + if (prev_sample_signed <= sample_signed) { + delta_table_start_index = POSITIVE_DELTAS_START; + delta_table_end_index = POSITIVE_DELTAS_END; + } else { + delta_table_start_index = NEGATIVE_DELTAS_START; + delta_table_end_index = NEGATIVE_DELTAS_END; + } - for (int i = 0; i < 16; i++) + for (int i = delta_table_start_index; i < delta_table_end_index; i++) { uint8_t new_sample = prev_sample + gDeltaEncodingTable[i]; - int error = sample > new_sample ? sample - new_sample : new_sample - sample; + int new_sample_signed = U8_TO_S8(new_sample); + int error = ABS(new_sample_signed - sample_signed); if (error < best_error) { @@ -527,9 +571,22 @@ do { \ void aif2pcm(const char *aif_filename, const char *pcm_filename, bool compress) { struct Bytes *aif = read_bytearray(aif_filename); - AifData aif_data = {0,0,0,0,0,0,0}; + AifData aif_data = {0}; read_aif(aif, &aif_data); + // Convert 16-bit to 8-bit if necessary + if (aif_data.sample_size == 16) + { + aif_data.real_num_samples /= 2; + uint8_t *converted_samples = malloc(aif_data.real_num_samples * sizeof(uint8_t)); + for (unsigned long i = 0; i < aif_data.real_num_samples; i++) + { + converted_samples[i] = aif_data.samples16[i] >> 8; + } + free(aif_data.samples16); + aif_data.samples8 = converted_samples; + } + int header_size = 0x10; struct Bytes *pcm; struct Bytes output = {0,0}; @@ -537,7 +594,7 @@ void aif2pcm(const char *aif_filename, const char *pcm_filename, bool compress) if (compress) { struct Bytes *input = malloc(sizeof(struct Bytes)); - input->data = aif_data.samples; + input->data = aif_data.samples8; input->length = aif_data.real_num_samples; pcm = delta_compress(input); free(input); @@ -545,7 +602,7 @@ void aif2pcm(const char *aif_filename, const char *pcm_filename, bool compress) else { pcm = malloc(sizeof(struct Bytes)); - pcm->data = aif_data.samples; + pcm->data = aif_data.samples8; pcm->length = aif_data.real_num_samples; } output.length = header_size + pcm->length; @@ -568,7 +625,7 @@ void aif2pcm(const char *aif_filename, const char *pcm_filename, bool compress) free(aif); free(pcm); free(output.data); - free(aif_data.samples); + free(aif_data.samples8); } // Reads a .pcm file containing an array of 8-bit samples and produces an .aif file. @@ -608,8 +665,8 @@ void pcm2aif(const char *pcm_filename, const char *aif_filename, uint32_t base_n pcm->data += 0x10; } - aif_data->samples = malloc(pcm->length); - memcpy(aif_data->samples, pcm->data, pcm->length); + aif_data->samples8 = malloc(pcm->length); + memcpy(aif_data->samples8, pcm->data, pcm->length); struct Bytes *aif = malloc(sizeof(struct Bytes)); aif->length = 54 + 60 + pcm->length; @@ -796,14 +853,14 @@ void pcm2aif(const char *pcm_filename, const char *aif_filename, uint32_t base_n // Sound Data Chunk soundData for (unsigned int i = 0; i < aif_data->loop_offset; i++) { - aif->data[pos++] = aif_data->samples[i]; + aif->data[pos++] = aif_data->samples8[i]; } int j = 0; for (unsigned int i = aif_data->loop_offset; i < pcm->length; i++) { int pcm_index = aif_data->loop_offset + (j++ % (pcm->length - aif_data->loop_offset)); - aif->data[pos++] = aif_data->samples[pcm_index]; + aif->data[pos++] = aif_data->samples8[pcm_index]; } aif->length = pos; diff --git a/tools/bin2c/Makefile b/tools/bin2c/Makefile index dd4e537a28..4dbfab94fe 100644 --- a/tools/bin2c/Makefile +++ b/tools/bin2c/Makefile @@ -1,15 +1,21 @@ -CC = gcc +CC ?= gcc -CFLAGS = -Wall -Wextra -Werror -std=c11 -O2 -s +CFLAGS = -Wall -Wextra -Werror -std=c11 -O2 .PHONY: all clean SRCS = bin2c.c -all: bin2c +ifeq ($(OS),Windows_NT) +EXE := .exe +else +EXE := +endif + +all: bin2c$(EXE) @: -bin2c: $(SRCS) +bin2c$(EXE): $(SRCS) $(CC) $(CFLAGS) $(SRCS) -o $@ $(LDFLAGS) clean: diff --git a/tools/gbafix/Makefile b/tools/gbafix/Makefile index 350af76cdf..efb016c97e 100644 --- a/tools/gbafix/Makefile +++ b/tools/gbafix/Makefile @@ -1,13 +1,18 @@ -CC = gcc +CC ?= gcc +.PHONY: all clean SRCS = gbafix.c -.PHONY: all clean +ifeq ($(OS),Windows_NT) +EXE := .exe +else +EXE := +endif -all: gbafix +all: gbafix$(EXE) @: -gbafix: $(SRCS) +gbafix$(EXE): $(SRCS) $(CC) $(SRCS) -o $@ $(LDFLAGS) clean: diff --git a/tools/gbafix/gbafix.c b/tools/gbafix/gbafix.c index 637023bdae..d62a9c661a 100644 --- a/tools/gbafix/gbafix.c +++ b/tools/gbafix/gbafix.c @@ -33,6 +33,7 @@ History ------- + v1.07 - added support for ELF input, (PikalaxALT) v1.06 - added output silencing, (Sierraffinity) v1.05 - added debug offset argument, (Sierraffinity) v1.04 - converted to plain C, (WinterMute) @@ -50,7 +51,7 @@ #include #include "elf.h" -#define VER "1.06" +#define VER "1.07" #define ARGV argv[arg] #define VALUE (ARGV+2) #define NUMBER strtoul(VALUE, NULL, 0) @@ -138,6 +139,7 @@ int main(int argc, char *argv[]) char *argfile = 0; FILE *infile; int silent = 0; + int schedule_pad = 0; int size,bit; @@ -172,28 +174,27 @@ int main(int argc, char *argv[]) return -1; } + uint32_t sh_offset = 0; + // read file infile = fopen(argfile, "r+b"); if (!infile) { fprintf(stderr, "Error opening input file!\n"); return -1; } - fseek(infile, 0, SEEK_SET); + fseek(infile, sh_offset, SEEK_SET); fread(&header, sizeof(header), 1, infile); // elf check - uint32_t sh_offset = 0; + Elf32_Shdr secHeader; if (memcmp(&header, ELFMAG, 4) == 0) { Elf32_Ehdr *elfHeader = (Elf32_Ehdr *)&header; fseek(infile, elfHeader->e_shoff, SEEK_SET); int i; for (i = 0; i < elfHeader->e_shnum; i++) { - Elf32_Shdr secHeader; fread(&secHeader, sizeof(Elf32_Shdr), 1, infile); - if (secHeader.sh_type == SHT_PROGBITS && secHeader.sh_addr == elfHeader->e_entry) { - fseek(infile, secHeader.sh_offset, SEEK_SET); - sh_offset = secHeader.sh_offset; - break; - } + if (secHeader.sh_type == SHT_PROGBITS && secHeader.sh_addr == elfHeader->e_entry) break; } if (i == elfHeader->e_shnum) { fprintf(stderr, "Error finding entry point!\n"); return 1; } + fseek(infile, secHeader.sh_offset, SEEK_SET); + sh_offset = secHeader.sh_offset; fread(&header, sizeof(header), 1, infile); } @@ -205,21 +206,13 @@ int main(int argc, char *argv[]) // parse command line for (arg=1; arg=0; bit--) if (size & (1<=0; bit--) if (size & (1<= 0; j -= srcBitDepth) { - unsigned char pixel = (srcByte >> j) % (1 << srcBitDepth); - - if (pixel >= (1 << destBitDepth)) - FATAL_ERROR("Image exceeds the maximum color value for a %ibpp image.\n", destBitDepth); + unsigned char pixel = ((srcByte >> j) % (1 << srcBitDepth)) % (1 << destBitDepth); *dest |= pixel << destBit; destBit -= destBitDepth; if (destBit < 0) @@ -125,7 +122,7 @@ void ReadPng(char *path, struct Image *image) free(row_pointers); fclose(fp); - if (bit_depth != image->bitDepth) + if (bit_depth != image->bitDepth && image->tilemap.data.affine == NULL) { unsigned char *src = image->pixels; @@ -133,7 +130,6 @@ void ReadPng(char *path, struct Image *image) FATAL_ERROR("Bit depth of image must be 1, 2, 4, or 8.\n"); image->pixels = ConvertBitDepth(image->pixels, bit_depth, image->bitDepth, image->width * image->height); free(src); - image->bitDepth = bit_depth; } } diff --git a/tools/gbagfx/gfx.c b/tools/gbagfx/gfx.c index f927deed9b..1dfc38e2d0 100644 --- a/tools/gbagfx/gfx.c +++ b/tools/gbagfx/gfx.c @@ -4,6 +4,7 @@ #include #include #include +#include #include "global.h" #include "gfx.h" #include "util.h" @@ -203,26 +204,188 @@ static void ConvertToTiles8Bpp(unsigned char *src, unsigned char *dest, int numT } } -void ReadImage(char *path, int tilesWidth, int bitDepth, int metatileWidth, int metatileHeight, struct Image *image, bool invertColors) +// For untiled, plain images +static void CopyPlainPixels(unsigned char *src, unsigned char *dest, int size, int dataWidth, bool invertColors) { - int tileSize = bitDepth * 8; + if (dataWidth == 0) return; + for (int i = 0; i < size; i += dataWidth) { + for (int j = dataWidth; j > 0; j--) { + unsigned char pixels = src[i + j - 1]; + *dest++ = invertColors ? ~pixels : pixels; + } + } +} + +static void DecodeAffineTilemap(unsigned char *input, unsigned char *output, unsigned char *tilemap, int tileSize, int numTiles) +{ + for (int i = 0; i < numTiles; i++) + { + memcpy(&output[i * tileSize], &input[tilemap[i] * tileSize], tileSize); + } +} + +#define REVERSE_BIT_ORDER(x) ({ \ + ((((x) >> 7) & 1) << 0) \ + | ((((x) >> 6) & 1) << 1) \ + | ((((x) >> 5) & 1) << 2) \ + | ((((x) >> 4) & 1) << 3) \ + | ((((x) >> 3) & 1) << 4) \ + | ((((x) >> 2) & 1) << 5) \ + | ((((x) >> 1) & 1) << 6) \ + | ((((x) >> 0) & 1) << 7); \ +}) + +#define SWAP_BYTES(a, b) ({ \ + unsigned char tmp = *(a); \ + *(a) = *(b); \ + *(b) = tmp; \ +}) + +#define NSWAP(x) ({ (((x) >> 4) & 0xF) | (((x) << 4) & 0xF0); }) + +#define SWAP_NYBBLES(a, b) ({ \ + unsigned char tmp = NSWAP(*(a)); \ + *(a) = NSWAP(*(b)); \ + *(b) = tmp; \ +}) + +static void VflipTile(unsigned char * tile, int bitDepth) +{ + int i; + switch (bitDepth) + { + case 1: + SWAP_BYTES(&tile[0], &tile[7]); + SWAP_BYTES(&tile[1], &tile[6]); + SWAP_BYTES(&tile[2], &tile[5]); + SWAP_BYTES(&tile[3], &tile[4]); + break; + case 4: + for (i = 0; i < 4; i++) + { + SWAP_BYTES(&tile[i + 0], &tile[i + 28]); + SWAP_BYTES(&tile[i + 4], &tile[i + 24]); + SWAP_BYTES(&tile[i + 8], &tile[i + 20]); + SWAP_BYTES(&tile[i + 12], &tile[i + 16]); + } + break; + case 8: + for (i = 0; i < 8; i++) + { + SWAP_BYTES(&tile[i + 0], &tile[i + 56]); + SWAP_BYTES(&tile[i + 8], &tile[i + 48]); + SWAP_BYTES(&tile[i + 16], &tile[i + 40]); + SWAP_BYTES(&tile[i + 24], &tile[i + 32]); + } + break; + } +} + +static void HflipTile(unsigned char * tile, int bitDepth) +{ + int i; + switch (bitDepth) + { + case 1: + for (i = 0; i < 8; i++) + tile[i] = REVERSE_BIT_ORDER(tile[i]); + break; + case 4: + for (i = 0; i < 8; i++) + { + SWAP_NYBBLES(&tile[4 * i + 0], &tile[4 * i + 3]); + SWAP_NYBBLES(&tile[4 * i + 1], &tile[4 * i + 2]); + } + break; + case 8: + for (i = 0; i < 8; i++) + { + SWAP_BYTES(&tile[8 * i + 0], &tile[8 * i + 7]); + SWAP_BYTES(&tile[8 * i + 1], &tile[8 * i + 6]); + SWAP_BYTES(&tile[8 * i + 2], &tile[8 * i + 5]); + SWAP_BYTES(&tile[8 * i + 3], &tile[8 * i + 4]); + } + break; + } +} + +static void DecodeNonAffineTilemap(unsigned char *input, unsigned char *output, struct NonAffineTile *tilemap, int tileSize, int outTileSize, int bitDepth, int numTiles) +{ + unsigned char * in_tile; + unsigned char * out_tile = output; + int effectiveBitDepth = tileSize == outTileSize ? bitDepth : 8; + for (int i = 0; i < numTiles; i++) + { + in_tile = &input[tilemap[i].index * tileSize]; + if (tileSize == outTileSize) + memcpy(out_tile, in_tile, tileSize); + else + { + for (int j = 0; j < 64; j++) + { + int shift = (j & 1) * 4; + out_tile[j] = (in_tile[j / 2] & (0xF << shift)) >> shift; + } + } + if (tilemap[i].hflip) + HflipTile(out_tile, effectiveBitDepth); + if (tilemap[i].vflip) + VflipTile(out_tile, effectiveBitDepth); + if (bitDepth == 4 && effectiveBitDepth == 8) + { + for (int j = 0; j < 64; j++) + { + out_tile[j] &= 0xF; + out_tile[j] |= (15 - tilemap[i].palno) << 4; + } + } + out_tile += outTileSize; + } +} + +static unsigned char *DecodeTilemap(unsigned char *tiles, struct Tilemap *tilemap, int *numTiles_p, bool isAffine, int tileSize, int outTileSize, int bitDepth) +{ + int mapTileSize = isAffine ? 1 : 2; + int numTiles = tilemap->size / mapTileSize; + unsigned char *decoded = calloc(numTiles, outTileSize); + if (isAffine) + DecodeAffineTilemap(tiles, decoded, tilemap->data.affine, tileSize, numTiles); + else + DecodeNonAffineTilemap(tiles, decoded, tilemap->data.non_affine, tileSize, outTileSize, bitDepth, numTiles); + free(tiles); + *numTiles_p = numTiles; + return decoded; +} + +void ReadTileImage(char *path, int tilesWidth, int metatileWidth, int metatileHeight, struct Image *image, bool invertColors) +{ + int tileSize = image->bitDepth * 8; int fileSize; unsigned char *buffer = ReadWholeFile(path, &fileSize); int numTiles = fileSize / tileSize; + if (image->tilemap.data.affine != NULL) + { + int outTileSize = (image->bitDepth == 4 && image->palette.numColors > 16) ? 64 : tileSize; + buffer = DecodeTilemap(buffer, &image->tilemap, &numTiles, image->isAffine, tileSize, outTileSize, image->bitDepth); + if (outTileSize == 64) + { + tileSize = 64; + image->bitDepth = 8; + } + } int tilesHeight = (numTiles + tilesWidth - 1) / tilesWidth; if (tilesWidth % metatileWidth != 0) - FATAL_ERROR("The width in tiles (%d) isn't a multiple of the specified metatile width (%d)", tilesWidth, metatileWidth); + FATAL_ERROR("The width in tiles (%d) isn't a multiple of the specified metatile width (%d)\n", tilesWidth, metatileWidth); if (tilesHeight % metatileHeight != 0) - FATAL_ERROR("The height in tiles (%d) isn't a multiple of the specified metatile height (%d)", tilesHeight, metatileHeight); + FATAL_ERROR("The height in tiles (%d) isn't a multiple of the specified metatile height (%d)\n", tilesHeight, metatileHeight); image->width = tilesWidth * 8; image->height = tilesHeight * 8; - image->bitDepth = bitDepth; image->pixels = calloc(tilesWidth * tilesHeight, tileSize); if (image->pixels == NULL) @@ -230,7 +393,7 @@ void ReadImage(char *path, int tilesWidth, int bitDepth, int metatileWidth, int int metatilesWide = tilesWidth / metatileWidth; - switch (bitDepth) { + switch (image->bitDepth) { case 1: ConvertFromTiles1Bpp(buffer, image->pixels, numTiles, metatilesWide, metatileWidth, metatileHeight, invertColors); break; @@ -245,9 +408,9 @@ void ReadImage(char *path, int tilesWidth, int bitDepth, int metatileWidth, int free(buffer); } -void WriteImage(char *path, int numTiles, int bitDepth, int metatileWidth, int metatileHeight, struct Image *image, bool invertColors) +void WriteTileImage(char *path, enum NumTilesMode numTilesMode, int numTiles, int metatileWidth, int metatileHeight, struct Image *image, bool invertColors) { - int tileSize = bitDepth * 8; + int tileSize = image->bitDepth * 8; if (image->width % 8 != 0) FATAL_ERROR("The width in pixels (%d) isn't a multiple of 8.\n", image->width); @@ -259,10 +422,10 @@ void WriteImage(char *path, int numTiles, int bitDepth, int metatileWidth, int m int tilesHeight = image->height / 8; if (tilesWidth % metatileWidth != 0) - FATAL_ERROR("The width in tiles (%d) isn't a multiple of the specified metatile width (%d)", tilesWidth, metatileWidth); + FATAL_ERROR("The width in tiles (%d) isn't a multiple of the specified metatile width (%d)\n", tilesWidth, metatileWidth); if (tilesHeight % metatileHeight != 0) - FATAL_ERROR("The height in tiles (%d) isn't a multiple of the specified metatile height (%d)", tilesHeight, metatileHeight); + FATAL_ERROR("The height in tiles (%d) isn't a multiple of the specified metatile height (%d)\n", tilesHeight, metatileHeight); int maxNumTiles = tilesWidth * tilesHeight; @@ -272,25 +435,96 @@ void WriteImage(char *path, int numTiles, int bitDepth, int metatileWidth, int m FATAL_ERROR("The specified number of tiles (%d) is greater than the maximum possible value (%d).\n", numTiles, maxNumTiles); int bufferSize = numTiles * tileSize; - unsigned char *buffer = malloc(bufferSize); + int maxBufferSize = maxNumTiles * tileSize; + unsigned char *buffer = malloc(maxBufferSize); if (buffer == NULL) FATAL_ERROR("Failed to allocate memory for pixels.\n"); int metatilesWide = tilesWidth / metatileWidth; - switch (bitDepth) { + switch (image->bitDepth) { case 1: - ConvertToTiles1Bpp(image->pixels, buffer, numTiles, metatilesWide, metatileWidth, metatileHeight, invertColors); + ConvertToTiles1Bpp(image->pixels, buffer, maxNumTiles, metatilesWide, metatileWidth, metatileHeight, invertColors); break; case 4: - ConvertToTiles4Bpp(image->pixels, buffer, numTiles, metatilesWide, metatileWidth, metatileHeight, invertColors); + ConvertToTiles4Bpp(image->pixels, buffer, maxNumTiles, metatilesWide, metatileWidth, metatileHeight, invertColors); break; case 8: - ConvertToTiles8Bpp(image->pixels, buffer, numTiles, metatilesWide, metatileWidth, metatileHeight, invertColors); + ConvertToTiles8Bpp(image->pixels, buffer, maxNumTiles, metatilesWide, metatileWidth, metatileHeight, invertColors); break; } + bool zeroPadded = true; + for (int i = bufferSize; i < maxBufferSize && zeroPadded; i++) { + if (buffer[i] != 0) + { + switch (numTilesMode) + { + case NUM_TILES_IGNORE: + break; + case NUM_TILES_WARN: + fprintf(stderr, "Ignoring -num_tiles %d because tile %d contains non-transparent pixels.\n", numTiles, 1 + i / tileSize); + zeroPadded = false; + break; + case NUM_TILES_ERROR: + FATAL_ERROR("Tile %d contains non-transparent pixels.\n", 1 + i / tileSize); + break; + } + } + } + + WriteWholeFile(path, buffer, zeroPadded ? bufferSize : maxBufferSize); + + free(buffer); +} + +void ReadPlainImage(char *path, int dataWidth, struct Image *image, bool invertColors) +{ + int fileSize; + unsigned char *buffer = ReadWholeFile(path, &fileSize); + + if (fileSize % dataWidth != 0) + FATAL_ERROR("The image data size (%d) isn't a multiple of the specified data width %d.\n", fileSize, dataWidth); + + // png scanlines have wasted bits if they do not align to byte boundaries. + // pngs misaligned in this way are not currently handled. + int pixelsPerByte = 8 / image->bitDepth; + if (image->width % pixelsPerByte != 0) + FATAL_ERROR("The width in pixels (%d) isn't a multiple of %d.\n", image->width, pixelsPerByte); + + int numPixels = fileSize * pixelsPerByte; + image->height = (numPixels + image->width - 1) / image->width; + image->pixels = calloc(image->width * image->height * image->bitDepth / 8, 1); + + if (image->pixels == NULL) + FATAL_ERROR("Failed to allocate memory for pixels.\n"); + + CopyPlainPixels(buffer, image->pixels, fileSize, dataWidth, invertColors); + + free(buffer); +} + +void WritePlainImage(char *path, int dataWidth, struct Image *image, bool invertColors) +{ + int bufferSize = image->width * image->height * image->bitDepth / 8; + + if (bufferSize % dataWidth != 0) + FATAL_ERROR("The image data size (%d) isn't a multiple of the specified data width %d.\n", bufferSize, dataWidth); + + // png scanlines have wasted bits if they do not align to byte boundaries. + // pngs misaligned in this way are not currently handled. + int pixelsPerByte = 8 / image->bitDepth; + if (image->width % pixelsPerByte != 0) + FATAL_ERROR("The width in pixels (%d) isn't a multiple of %d.\n", image->width, pixelsPerByte); + + unsigned char *buffer = malloc(bufferSize); + + if (buffer == NULL) + FATAL_ERROR("Failed to allocate memory for pixels.\n"); + + CopyPlainPixels(image->pixels, buffer, bufferSize, dataWidth, invertColors); + WriteWholeFile(path, buffer, bufferSize); free(buffer); @@ -298,6 +532,11 @@ void WriteImage(char *path, int numTiles, int bitDepth, int metatileWidth, int m void FreeImage(struct Image *image) { + if (image->tilemap.data.affine != NULL) + { + free(image->tilemap.data.affine); + image->tilemap.data.affine = NULL; + } free(image->pixels); image->pixels = NULL; } @@ -318,6 +557,12 @@ void ReadGbaPalette(char *path, struct Palette *palette) palette->colors[i].green = UPCONVERT_BIT_DEPTH(GET_GBA_PAL_GREEN(paletteEntry)); palette->colors[i].blue = UPCONVERT_BIT_DEPTH(GET_GBA_PAL_BLUE(paletteEntry)); } + // png can only accept 16 or 256 colors, so fill the remainder with black + if (palette->numColors > 16) + { + memset(&palette->colors[palette->numColors], 0, (256 - palette->numColors) * sizeof(struct Color)); + palette->numColors = 256; + } free(data); } diff --git a/tools/gbagfx/gfx.h b/tools/gbagfx/gfx.h index 5355ced856..1797d84dfd 100644 --- a/tools/gbagfx/gfx.h +++ b/tools/gbagfx/gfx.h @@ -17,6 +17,21 @@ struct Palette { int numColors; }; +struct NonAffineTile { + unsigned short index:10; + unsigned short hflip:1; + unsigned short vflip:1; + unsigned short palno:4; +} __attribute__((packed)); + +struct Tilemap { + union { + struct NonAffineTile *non_affine; + unsigned char *affine; + } data; + int size; +}; + struct Image { int width; int height; @@ -25,10 +40,20 @@ struct Image { bool hasPalette; struct Palette palette; bool hasTransparency; + struct Tilemap tilemap; + bool isAffine; +}; + +enum NumTilesMode { + NUM_TILES_IGNORE, + NUM_TILES_WARN, + NUM_TILES_ERROR, }; -void ReadImage(char *path, int tilesWidth, int bitDepth, int metatileWidth, int metatileHeight, struct Image *image, bool invertColors); -void WriteImage(char *path, int numTiles, int bitDepth, int metatileWidth, int metatileHeight, struct Image *image, bool invertColors); +void ReadTileImage(char *path, int tilesWidth, int metatileWidth, int metatileHeight, struct Image *image, bool invertColors); +void WriteTileImage(char *path, enum NumTilesMode numTilesMode, int numTiles, int metatileWidth, int metatileHeight, struct Image *image, bool invertColors); +void ReadPlainImage(char *path, int dataWidth, struct Image *image, bool invertColors); +void WritePlainImage(char *path, int dataWidth, struct Image *image, bool invertColors); void FreeImage(struct Image *image); void ReadGbaPalette(char *path, struct Palette *palette); void WriteGbaPalette(char *path, struct Palette *palette); diff --git a/tools/gbagfx/huff.c b/tools/gbagfx/huff.c index 143ed79be8..c6c23cbb34 100644 --- a/tools/gbagfx/huff.c +++ b/tools/gbagfx/huff.c @@ -6,21 +6,21 @@ #include "global.h" #include "huff.h" -static int cmp_tree(const void * a0, const void * b0) { +static int cmp_tree(const void *a0, const void *b0) { return ((struct HuffData *)a0)->value - ((struct HuffData *)b0)->value; } typedef int (*cmpfun)(const void *, const void *); -int msort_r(void * data, size_t count, size_t size, cmpfun cmp, void * buffer) { +int msort_r(void *data, size_t count, size_t size, cmpfun cmp, void *buffer) { /* * Out-of-place mergesort (stable sort) * Returns 1 on success, 0 on failure */ - void * leftPtr; - void * rightPtr; - void * leftEnd; - void * rightEnd; + void *leftPtr; + void *rightPtr; + void *leftEnd; + void *rightEnd; int i; switch (count) { @@ -85,8 +85,8 @@ int msort_r(void * data, size_t count, size_t size, cmpfun cmp, void * buffer) { return 1; } -int msort(void * data, size_t count, size_t size, cmpfun cmp) { - void * buffer = malloc(count * size); +int msort(void *data, size_t count, size_t size, cmpfun cmp) { + void *buffer = malloc(count * size); if (buffer == NULL) return 0; int result = msort_r(data, count, size, cmp, buffer); free(buffer); diff --git a/tools/gbagfx/jasc_pal.c b/tools/gbagfx/jasc_pal.c index e5ba9c3c2f..8d4bb137d5 100644 --- a/tools/gbagfx/jasc_pal.c +++ b/tools/gbagfx/jasc_pal.c @@ -46,10 +46,14 @@ void ReadJascPaletteLine(FILE *fp, char *line) } if (c == '\n') - FATAL_ERROR("LF line endings aren't supported.\n"); + { + line[length] = 0; + + return; + } if (c == EOF) - FATAL_ERROR("Unexpected EOF. No CRLF at end of file.\n"); + FATAL_ERROR("Unexpected EOF. No LF or CRLF at end of file.\n"); if (c == 0) FATAL_ERROR("NUL character in file.\n"); diff --git a/tools/gbagfx/main.c b/tools/gbagfx/main.c index 9579185055..98a1a1edf9 100644 --- a/tools/gbagfx/main.c +++ b/tools/gbagfx/main.c @@ -25,6 +25,9 @@ void ConvertGbaToPng(char *inputPath, char *outputPath, struct GbaToPngOptions * { struct Image image; + image.bitDepth = options->bitDepth; + image.tilemap.data.affine = NULL; + if (options->paletteFilePath != NULL) { char *paletteFileExtension = GetFileExtensionAfterDot(options->paletteFilePath); @@ -45,7 +48,24 @@ void ConvertGbaToPng(char *inputPath, char *outputPath, struct GbaToPngOptions * image.hasPalette = false; } - ReadImage(inputPath, options->width, options->bitDepth, options->metatileWidth, options->metatileHeight, &image, !image.hasPalette); + if (options->isTiled) + { + if (options->tilemapFilePath != NULL) + { + int fileSize; + image.tilemap.data.affine = ReadWholeFile(options->tilemapFilePath, &fileSize); + if (options->isAffineMap && options->bitDepth != 8) + FATAL_ERROR("affine maps are necessarily 8bpp\n"); + image.isAffine = options->isAffineMap; + image.tilemap.size = fileSize; + } + ReadTileImage(inputPath, options->width, options->metatileWidth, options->metatileHeight, &image, !image.hasPalette); + } + else + { + image.width = options->width; + ReadPlainImage(inputPath, options->dataWidth, &image, !image.hasPalette); + } image.hasTransparency = options->hasTransparency; @@ -59,10 +79,14 @@ void ConvertPngToGba(char *inputPath, char *outputPath, struct PngToGbaOptions * struct Image image; image.bitDepth = options->bitDepth; + image.tilemap.data.affine = NULL; // initialize to NULL to avoid issues in FreeImage ReadPng(inputPath, &image); - WriteImage(outputPath, options->numTiles, options->bitDepth, options->metatileWidth, options->metatileHeight, &image, !image.hasPalette); + if (options->isTiled) + WriteTileImage(outputPath, options->numTilesMode, options->numTiles, options->metatileWidth, options->metatileHeight, &image, !image.hasPalette); + else + WritePlainImage(outputPath, options->dataWidth, &image, !image.hasPalette); FreeImage(&image); } @@ -77,6 +101,10 @@ void HandleGbaToPngCommand(char *inputPath, char *outputPath, int argc, char **a options.width = 1; options.metatileWidth = 1; options.metatileHeight = 1; + options.tilemapFilePath = NULL; + options.isAffineMap = false; + options.isTiled = true; + options.dataWidth = 1; for (int i = 3; i < argc; i++) { @@ -134,6 +162,33 @@ void HandleGbaToPngCommand(char *inputPath, char *outputPath, int argc, char **a if (options.metatileHeight < 1) FATAL_ERROR("metatile height must be positive.\n"); } + else if (strcmp(option, "-tilemap") == 0) + { + if (i + 1 >= argc) + FATAL_ERROR("No tilemap value following \"-tilemap\".\n"); + i++; + options.tilemapFilePath = argv[i]; + } + else if (strcmp(option, "-affine") == 0) + { + options.isAffineMap = true; + } + else if (strcmp(option, "-plain") == 0) + { + options.isTiled = false; + } + else if (strcmp(option, "-data_width") == 0) + { + if (i + 1 >= argc) + FATAL_ERROR("No data width value following \"-data_width\".\n"); + i++; + + if (!ParseNumber(argv[i], NULL, 10, &options.dataWidth)) + FATAL_ERROR("Failed to parse data width.\n"); + + if (options.dataWidth < 1) + FATAL_ERROR("Data width must be positive.\n"); + } else { FATAL_ERROR("Unrecognized option \"%s\".\n", option); @@ -149,12 +204,16 @@ void HandleGbaToPngCommand(char *inputPath, char *outputPath, int argc, char **a void HandlePngToGbaCommand(char *inputPath, char *outputPath, int argc, char **argv) { char *outputFileExtension = GetFileExtensionAfterDot(outputPath); - int bitDepth = outputFileExtension[0] - '0'; struct PngToGbaOptions options; + options.numTilesMode = NUM_TILES_IGNORE; options.numTiles = 0; - options.bitDepth = bitDepth; + options.bitDepth = outputFileExtension[0] - '0'; options.metatileWidth = 1; options.metatileHeight = 1; + options.tilemapFilePath = NULL; + options.isAffineMap = false; + options.isTiled = true; + options.dataWidth = 1; for (int i = 3; i < argc; i++) { @@ -173,6 +232,12 @@ void HandlePngToGbaCommand(char *inputPath, char *outputPath, int argc, char **a if (options.numTiles < 1) FATAL_ERROR("Number of tiles must be positive.\n"); } + else if (strcmp(option, "-Wnum_tiles") == 0) { + options.numTilesMode = NUM_TILES_WARN; + } + else if (strcmp(option, "-Werror=num_tiles") == 0) { + options.numTilesMode = NUM_TILES_ERROR; + } else if (strcmp(option, "-mwidth") == 0) { if (i + 1 >= argc) @@ -199,6 +264,22 @@ void HandlePngToGbaCommand(char *inputPath, char *outputPath, int argc, char **a if (options.metatileHeight < 1) FATAL_ERROR("metatile height must be positive.\n"); } + else if (strcmp(option, "-plain") == 0) + { + options.isTiled = false; + } + else if (strcmp(option, "-data_width") == 0) + { + if (i + 1 >= argc) + FATAL_ERROR("No data width value following \"-data_width\".\n"); + i++; + + if (!ParseNumber(argv[i], NULL, 10, &options.dataWidth)) + FATAL_ERROR("Failed to parse data width.\n"); + + if (options.dataWidth < 1) + FATAL_ERROR("Data width must be positive.\n"); + } else { FATAL_ERROR("Unrecognized option \"%s\".\n", option); @@ -272,6 +353,7 @@ void HandleJascToGbaPaletteCommand(char *inputPath, char *outputPath, int argc, void HandleLatinFontToPngCommand(char *inputPath, char *outputPath, int argc UNUSED, char **argv UNUSED) { struct Image image; + image.tilemap.data.affine = NULL; // initialize to NULL to avoid issues in FreeImage ReadLatinFont(inputPath, &image); WritePng(outputPath, &image); @@ -282,6 +364,7 @@ void HandleLatinFontToPngCommand(char *inputPath, char *outputPath, int argc UNU void HandlePngToLatinFontCommand(char *inputPath, char *outputPath, int argc UNUSED, char **argv UNUSED) { struct Image image; + image.tilemap.data.affine = NULL; // initialize to NULL to avoid issues in FreeImage image.bitDepth = 2; @@ -294,6 +377,7 @@ void HandlePngToLatinFontCommand(char *inputPath, char *outputPath, int argc UNU void HandleHalfwidthJapaneseFontToPngCommand(char *inputPath, char *outputPath, int argc UNUSED, char **argv UNUSED) { struct Image image; + image.tilemap.data.affine = NULL; // initialize to NULL to avoid issues in FreeImage ReadHalfwidthJapaneseFont(inputPath, &image); WritePng(outputPath, &image); @@ -304,6 +388,7 @@ void HandleHalfwidthJapaneseFontToPngCommand(char *inputPath, char *outputPath, void HandlePngToHalfwidthJapaneseFontCommand(char *inputPath, char *outputPath, int argc UNUSED, char **argv UNUSED) { struct Image image; + image.tilemap.data.affine = NULL; // initialize to NULL to avoid issues in FreeImage image.bitDepth = 2; @@ -316,6 +401,7 @@ void HandlePngToHalfwidthJapaneseFontCommand(char *inputPath, char *outputPath, void HandleFullwidthJapaneseFontToPngCommand(char *inputPath, char *outputPath, int argc UNUSED, char **argv UNUSED) { struct Image image; + image.tilemap.data.affine = NULL; // initialize to NULL to avoid issues in FreeImage ReadFullwidthJapaneseFont(inputPath, &image); WritePng(outputPath, &image); @@ -326,6 +412,7 @@ void HandleFullwidthJapaneseFontToPngCommand(char *inputPath, char *outputPath, void HandlePngToFullwidthJapaneseFontCommand(char *inputPath, char *outputPath, int argc UNUSED, char **argv UNUSED) { struct Image image; + image.tilemap.data.affine = NULL; // initialize to NULL to avoid issues in FreeImage image.bitDepth = 2; @@ -360,7 +447,7 @@ void HandleLZCompressCommand(char *inputPath, char *outputPath, int argc, char * else if (strcmp(option, "-search") == 0) { if (i + 1 >= argc) - FATAL_ERROR("No size following \"-overflow\".\n"); + FATAL_ERROR("No size following \"-search\".\n"); i++; diff --git a/tools/gbagfx/options.h b/tools/gbagfx/options.h old mode 100755 new mode 100644 index 2ff3967a4d..830158b52e --- a/tools/gbagfx/options.h +++ b/tools/gbagfx/options.h @@ -4,6 +4,7 @@ #define OPTIONS_H #include +#include "gfx.h" struct GbaToPngOptions { char *paletteFilePath; @@ -12,13 +13,22 @@ struct GbaToPngOptions { int width; int metatileWidth; int metatileHeight; + char *tilemapFilePath; + bool isAffineMap; + bool isTiled; + int dataWidth; }; struct PngToGbaOptions { int numTiles; + enum NumTilesMode numTilesMode; int bitDepth; int metatileWidth; int metatileHeight; + char *tilemapFilePath; + bool isAffineMap; + bool isTiled; + int dataWidth; }; #endif // OPTIONS_H diff --git a/tools/jsonproc/Makefile b/tools/jsonproc/Makefile index bddf596836..653d585679 100755 --- a/tools/jsonproc/Makefile +++ b/tools/jsonproc/Makefile @@ -1,6 +1,6 @@ -CXX := g++ +CXX ?= g++ -CXXFLAGS := -Wall -std=c++11 -O2 +CXXFLAGS := -Wall -std=c++17 -O2 INCLUDES := -I . @@ -8,12 +8,18 @@ SRCS := jsonproc.cpp HEADERS := jsonproc.h inja.hpp nlohmann/json.hpp -.PHONY: clean all +ifeq ($(OS),Windows_NT) +EXE := .exe +else +EXE := +endif -all: jsonproc +.PHONY: all clean + +all: jsonproc$(EXE) @: -jsonproc: $(SRCS) $(HEADERS) +jsonproc$(EXE): $(SRCS) $(HEADERS) $(CXX) $(CXXFLAGS) $(INCLUDES) $(SRCS) -o $@ $(LDFLAGS) clean: diff --git a/tools/jsonproc/inja.hpp b/tools/jsonproc/inja.hpp index d5bf5bcba4..5b469745fb 100755 --- a/tools/jsonproc/inja.hpp +++ b/tools/jsonproc/inja.hpp @@ -1,1427 +1,841 @@ -// MIT License - -// Copyright (c) 2018 lbersch - -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: - -// The above copyright notice and this permission notice shall be included in all -// copies or substantial portions of the Software. - -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -// SOFTWARE. - - -// --- - - -// Copyright (c) 2009-2018 FIRST -// All rights reserved. - -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// * Neither the name of the FIRST nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. - -// THIS SOFTWARE IS PROVIDED BY FIRST AND CONTRIBUTORS``AS IS'' AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY NONINFRINGEMENT AND FITNESS FOR A PARTICULAR -// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL FIRST OR CONTRIBUTORS BE LIABLE FOR -// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#ifndef PANTOR_INJA_HPP -#define PANTOR_INJA_HPP +/* + ___ _ Version 3.3 + |_ _|_ __ (_) __ _ https://github.com/pantor/inja + | || '_ \ | |/ _` | Licensed under the MIT License . + | || | | || | (_| | + |___|_| |_|/ |\__,_| Copyright (c) 2018-2021 Lars Berscheid + |__/ +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +*/ -#include -#include -#include -#include -#include -#include -#include +#ifndef INCLUDE_INJA_INJA_HPP_ +#define INCLUDE_INJA_INJA_HPP_ #include -// #include "environment.hpp" -#ifndef PANTOR_INJA_ENVIRONMENT_HPP -#define PANTOR_INJA_ENVIRONMENT_HPP - -#include -#include -#include -#include - -#include - -// #include "config.hpp" -#ifndef PANTOR_INJA_CONFIG_HPP -#define PANTOR_INJA_CONFIG_HPP - -#include -#include - -// #include "string_view.hpp" -// Copyright 2017-2019 by Martin Moene -// -// string-view lite, a C++17-like string_view for C++98 and later. -// For more information see https://github.com/martinmoene/string-view-lite -// -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE.txt or copy at http://www.boost.org/LICENSE_1_0.txt) - - - -#ifndef NONSTD_SV_LITE_H_INCLUDED -#define NONSTD_SV_LITE_H_INCLUDED - -#define string_view_lite_MAJOR 1 -#define string_view_lite_MINOR 1 -#define string_view_lite_PATCH 0 - -#define string_view_lite_VERSION nssv_STRINGIFY(string_view_lite_MAJOR) "." nssv_STRINGIFY(string_view_lite_MINOR) "." nssv_STRINGIFY(string_view_lite_PATCH) - -#define nssv_STRINGIFY( x ) nssv_STRINGIFY_( x ) -#define nssv_STRINGIFY_( x ) #x - -// string-view lite configuration: - -#define nssv_STRING_VIEW_DEFAULT 0 -#define nssv_STRING_VIEW_NONSTD 1 -#define nssv_STRING_VIEW_STD 2 - -#if !defined( nssv_CONFIG_SELECT_STRING_VIEW ) -# define nssv_CONFIG_SELECT_STRING_VIEW ( nssv_HAVE_STD_STRING_VIEW ? nssv_STRING_VIEW_STD : nssv_STRING_VIEW_NONSTD ) -#endif - -#if defined( nssv_CONFIG_SELECT_STD_STRING_VIEW ) || defined( nssv_CONFIG_SELECT_NONSTD_STRING_VIEW ) -# error nssv_CONFIG_SELECT_STD_STRING_VIEW and nssv_CONFIG_SELECT_NONSTD_STRING_VIEW are deprecated and removed, please use nssv_CONFIG_SELECT_STRING_VIEW=nssv_STRING_VIEW_... -#endif - -#ifndef nssv_CONFIG_STD_SV_OPERATOR -# define nssv_CONFIG_STD_SV_OPERATOR 0 -#endif - -#ifndef nssv_CONFIG_USR_SV_OPERATOR -# define nssv_CONFIG_USR_SV_OPERATOR 1 -#endif - -#ifdef nssv_CONFIG_CONVERSION_STD_STRING -# define nssv_CONFIG_CONVERSION_STD_STRING_CLASS_METHODS nssv_CONFIG_CONVERSION_STD_STRING -# define nssv_CONFIG_CONVERSION_STD_STRING_FREE_FUNCTIONS nssv_CONFIG_CONVERSION_STD_STRING -#endif - -#ifndef nssv_CONFIG_CONVERSION_STD_STRING_CLASS_METHODS -# define nssv_CONFIG_CONVERSION_STD_STRING_CLASS_METHODS 1 -#endif - -#ifndef nssv_CONFIG_CONVERSION_STD_STRING_FREE_FUNCTIONS -# define nssv_CONFIG_CONVERSION_STD_STRING_FREE_FUNCTIONS 1 -#endif - -// Control presence of exception handling (try and auto discover): - -#ifndef nssv_CONFIG_NO_EXCEPTIONS -# if defined(__cpp_exceptions) || defined(__EXCEPTIONS) || defined(_CPPUNWIND) -# define nssv_CONFIG_NO_EXCEPTIONS 0 -# else -# define nssv_CONFIG_NO_EXCEPTIONS 1 -# endif -#endif - -// C++ language version detection (C++20 is speculative): -// Note: VC14.0/1900 (VS2015) lacks too much from C++14. - -#ifndef nssv_CPLUSPLUS -# if defined(_MSVC_LANG ) && !defined(__clang__) -# define nssv_CPLUSPLUS (_MSC_VER == 1900 ? 201103L : _MSVC_LANG ) -# else -# define nssv_CPLUSPLUS __cplusplus -# endif -#endif - -#define nssv_CPP98_OR_GREATER ( nssv_CPLUSPLUS >= 199711L ) -#define nssv_CPP11_OR_GREATER ( nssv_CPLUSPLUS >= 201103L ) -#define nssv_CPP11_OR_GREATER_ ( nssv_CPLUSPLUS >= 201103L ) -#define nssv_CPP14_OR_GREATER ( nssv_CPLUSPLUS >= 201402L ) -#define nssv_CPP17_OR_GREATER ( nssv_CPLUSPLUS >= 201703L ) -#define nssv_CPP20_OR_GREATER ( nssv_CPLUSPLUS >= 202000L ) - -// use C++17 std::string_view if available and requested: - -#if nssv_CPP17_OR_GREATER && defined(__has_include ) -# if __has_include( ) -# define nssv_HAVE_STD_STRING_VIEW 1 -# else -# define nssv_HAVE_STD_STRING_VIEW 0 -# endif -#else -# define nssv_HAVE_STD_STRING_VIEW 0 -#endif - -#define nssv_USES_STD_STRING_VIEW ( (nssv_CONFIG_SELECT_STRING_VIEW == nssv_STRING_VIEW_STD) || ((nssv_CONFIG_SELECT_STRING_VIEW == nssv_STRING_VIEW_DEFAULT) && nssv_HAVE_STD_STRING_VIEW) ) - -#define nssv_HAVE_STARTS_WITH ( nssv_CPP20_OR_GREATER || !nssv_USES_STD_STRING_VIEW ) -#define nssv_HAVE_ENDS_WITH nssv_HAVE_STARTS_WITH - -// -// Use C++17 std::string_view: -// - -#if nssv_USES_STD_STRING_VIEW - -#include - -// Extensions for std::string: - -#if nssv_CONFIG_CONVERSION_STD_STRING_FREE_FUNCTIONS - -namespace nonstd { - -template< class CharT, class Traits, class Allocator = std::allocator > -std::basic_string -to_string( std::basic_string_view v, Allocator const & a = Allocator() ) -{ - return std::basic_string( v.begin(), v.end(), a ); -} - -template< class CharT, class Traits, class Allocator > -std::basic_string_view -to_string_view( std::basic_string const & s ) -{ - return std::basic_string_view( s.data(), s.size() ); -} - -// Literal operators sv and _sv: - -#if nssv_CONFIG_STD_SV_OPERATOR - -using namespace std::literals::string_view_literals; - -#endif - -#if nssv_CONFIG_USR_SV_OPERATOR - -inline namespace literals { -inline namespace string_view_literals { - - -constexpr std::string_view operator "" _sv( const char* str, size_t len ) noexcept // (1) -{ - return std::string_view{ str, len }; -} - -constexpr std::u16string_view operator "" _sv( const char16_t* str, size_t len ) noexcept // (2) -{ - return std::u16string_view{ str, len }; -} - -constexpr std::u32string_view operator "" _sv( const char32_t* str, size_t len ) noexcept // (3) -{ - return std::u32string_view{ str, len }; -} - -constexpr std::wstring_view operator "" _sv( const wchar_t* str, size_t len ) noexcept // (4) -{ - return std::wstring_view{ str, len }; -} - -}} // namespace literals::string_view_literals - -#endif // nssv_CONFIG_USR_SV_OPERATOR - -} // namespace nonstd - -#endif // nssv_CONFIG_CONVERSION_STD_STRING_FREE_FUNCTIONS - -namespace nonstd { - -using std::string_view; -using std::wstring_view; -using std::u16string_view; -using std::u32string_view; -using std::basic_string_view; - -// literal "sv" and "_sv", see above - -using std::operator==; -using std::operator!=; -using std::operator<; -using std::operator<=; -using std::operator>; -using std::operator>=; - -using std::operator<<; - -} // namespace nonstd - -#else // nssv_HAVE_STD_STRING_VIEW - -// -// Before C++17: use string_view lite: -// - -// Compiler versions: -// -// MSVC++ 6.0 _MSC_VER == 1200 (Visual Studio 6.0) -// MSVC++ 7.0 _MSC_VER == 1300 (Visual Studio .NET 2002) -// MSVC++ 7.1 _MSC_VER == 1310 (Visual Studio .NET 2003) -// MSVC++ 8.0 _MSC_VER == 1400 (Visual Studio 2005) -// MSVC++ 9.0 _MSC_VER == 1500 (Visual Studio 2008) -// MSVC++ 10.0 _MSC_VER == 1600 (Visual Studio 2010) -// MSVC++ 11.0 _MSC_VER == 1700 (Visual Studio 2012) -// MSVC++ 12.0 _MSC_VER == 1800 (Visual Studio 2013) -// MSVC++ 14.0 _MSC_VER == 1900 (Visual Studio 2015) -// MSVC++ 14.1 _MSC_VER >= 1910 (Visual Studio 2017) - -#if defined(_MSC_VER ) && !defined(__clang__) -# define nssv_COMPILER_MSVC_VER (_MSC_VER ) -# define nssv_COMPILER_MSVC_VERSION (_MSC_VER / 10 - 10 * ( 5 + (_MSC_VER < 1900 ) ) ) -#else -# define nssv_COMPILER_MSVC_VER 0 -# define nssv_COMPILER_MSVC_VERSION 0 -#endif - -#define nssv_COMPILER_VERSION( major, minor, patch ) (10 * ( 10 * major + minor) + patch) - -#if defined(__clang__) -# define nssv_COMPILER_CLANG_VERSION nssv_COMPILER_VERSION(__clang_major__, __clang_minor__, __clang_patchlevel__) +namespace inja { +#ifndef INJA_DATA_TYPE +using json = nlohmann::json; #else -# define nssv_COMPILER_CLANG_VERSION 0 +using json = INJA_DATA_TYPE; #endif +} // namespace inja -#if defined(__GNUC__) && !defined(__clang__) -# define nssv_COMPILER_GNUC_VERSION nssv_COMPILER_VERSION(__GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__) -#else -# define nssv_COMPILER_GNUC_VERSION 0 +#if (defined(__cpp_exceptions) || defined(__EXCEPTIONS) || defined(_CPPUNWIND)) && !defined(INJA_NOEXCEPTION) +#ifndef INJA_THROW +#define INJA_THROW(exception) throw exception #endif - -// half-open range [lo..hi): -#define nssv_BETWEEN( v, lo, hi ) ( (lo) <= (v) && (v) < (hi) ) - -// Presence of language and library features: - -#ifdef _HAS_CPP0X -# define nssv_HAS_CPP0X _HAS_CPP0X #else -# define nssv_HAS_CPP0X 0 -#endif - -// Unless defined otherwise below, consider VC14 as C++11 for variant-lite: - -#if nssv_COMPILER_MSVC_VER >= 1900 -# undef nssv_CPP11_OR_GREATER -# define nssv_CPP11_OR_GREATER 1 +#include +#ifndef INJA_THROW +#define INJA_THROW(exception) \ + std::abort(); \ + std::ignore = exception #endif - -#define nssv_CPP11_90 (nssv_CPP11_OR_GREATER_ || nssv_COMPILER_MSVC_VER >= 1500) -#define nssv_CPP11_100 (nssv_CPP11_OR_GREATER_ || nssv_COMPILER_MSVC_VER >= 1600) -#define nssv_CPP11_110 (nssv_CPP11_OR_GREATER_ || nssv_COMPILER_MSVC_VER >= 1700) -#define nssv_CPP11_120 (nssv_CPP11_OR_GREATER_ || nssv_COMPILER_MSVC_VER >= 1800) -#define nssv_CPP11_140 (nssv_CPP11_OR_GREATER_ || nssv_COMPILER_MSVC_VER >= 1900) -#define nssv_CPP11_141 (nssv_CPP11_OR_GREATER_ || nssv_COMPILER_MSVC_VER >= 1910) - -#define nssv_CPP14_000 (nssv_CPP14_OR_GREATER) -#define nssv_CPP17_000 (nssv_CPP17_OR_GREATER) - -// Presence of C++11 language features: - -#define nssv_HAVE_CONSTEXPR_11 nssv_CPP11_140 -#define nssv_HAVE_EXPLICIT_CONVERSION nssv_CPP11_140 -#define nssv_HAVE_INLINE_NAMESPACE nssv_CPP11_140 -#define nssv_HAVE_NOEXCEPT nssv_CPP11_140 -#define nssv_HAVE_NULLPTR nssv_CPP11_100 -#define nssv_HAVE_REF_QUALIFIER nssv_CPP11_140 -#define nssv_HAVE_UNICODE_LITERALS nssv_CPP11_140 -#define nssv_HAVE_USER_DEFINED_LITERALS nssv_CPP11_140 -#define nssv_HAVE_WCHAR16_T nssv_CPP11_100 -#define nssv_HAVE_WCHAR32_T nssv_CPP11_100 - -#if ! ( ( nssv_CPP11 && nssv_COMPILER_CLANG_VERSION ) || nssv_BETWEEN( nssv_COMPILER_CLANG_VERSION, 300, 400 ) ) -# define nssv_HAVE_STD_DEFINED_LITERALS nssv_CPP11_140 -#endif - -// Presence of C++14 language features: - -#define nssv_HAVE_CONSTEXPR_14 nssv_CPP14_000 - -// Presence of C++17 language features: - -#define nssv_HAVE_NODISCARD nssv_CPP17_000 - -// Presence of C++ library features: - -#define nssv_HAVE_STD_HASH nssv_CPP11_120 - -// C++ feature usage: - -#if nssv_HAVE_CONSTEXPR_11 -# define nssv_constexpr constexpr -#else -# define nssv_constexpr /*constexpr*/ +#ifndef INJA_NOEXCEPTION +#define INJA_NOEXCEPTION #endif - -#if nssv_HAVE_CONSTEXPR_14 -# define nssv_constexpr14 constexpr -#else -# define nssv_constexpr14 /*constexpr*/ #endif -#if nssv_HAVE_EXPLICIT_CONVERSION -# define nssv_explicit explicit -#else -# define nssv_explicit /*explicit*/ -#endif +// #include "environment.hpp" +#ifndef INCLUDE_INJA_ENVIRONMENT_HPP_ +#define INCLUDE_INJA_ENVIRONMENT_HPP_ -#if nssv_HAVE_INLINE_NAMESPACE -# define nssv_inline_ns inline -#else -# define nssv_inline_ns /*inline*/ -#endif +#include +#include +#include +#include +#include +#include -#if nssv_HAVE_NOEXCEPT -# define nssv_noexcept noexcept -#else -# define nssv_noexcept /*noexcept*/ -#endif +// #include "config.hpp" +#ifndef INCLUDE_INJA_CONFIG_HPP_ +#define INCLUDE_INJA_CONFIG_HPP_ -//#if nssv_HAVE_REF_QUALIFIER -//# define nssv_ref_qual & -//# define nssv_refref_qual && -//#else -//# define nssv_ref_qual /*&*/ -//# define nssv_refref_qual /*&&*/ -//#endif +#include +#include -#if nssv_HAVE_NULLPTR -# define nssv_nullptr nullptr -#else -# define nssv_nullptr NULL -#endif +// #include "template.hpp" +#ifndef INCLUDE_INJA_TEMPLATE_HPP_ +#define INCLUDE_INJA_TEMPLATE_HPP_ -#if nssv_HAVE_NODISCARD -# define nssv_nodiscard [[nodiscard]] -#else -# define nssv_nodiscard /*[[nodiscard]]*/ -#endif +#include +#include +#include +#include -// Additional includes: +// #include "node.hpp" +#ifndef INCLUDE_INJA_NODE_HPP_ +#define INCLUDE_INJA_NODE_HPP_ -#include -#include -#include -#include -#include -#include // std::char_traits<> +#include +#include +#include -#if ! nssv_CONFIG_NO_EXCEPTIONS -# include -#endif +// #include "function_storage.hpp" +#ifndef INCLUDE_INJA_FUNCTION_STORAGE_HPP_ +#define INCLUDE_INJA_FUNCTION_STORAGE_HPP_ -#if nssv_CPP11_OR_GREATER -# include -#endif +#include +#include -// Clang, GNUC, MSVC warning suppression macros: - -#if defined(__clang__) -# pragma clang diagnostic ignored "-Wreserved-user-defined-literal" -# pragma clang diagnostic push -# pragma clang diagnostic ignored "-Wuser-defined-literals" -#elif defined(__GNUC__) -# pragma GCC diagnostic push -# pragma GCC diagnostic ignored "-Wliteral-suffix" -#endif // __clang__ - -#if nssv_COMPILER_MSVC_VERSION >= 140 -# define nssv_SUPPRESS_MSGSL_WARNING(expr) [[gsl::suppress(expr)]] -# define nssv_SUPPRESS_MSVC_WARNING(code, descr) __pragma(warning(suppress: code) ) -# define nssv_DISABLE_MSVC_WARNINGS(codes) __pragma(warning(push)) __pragma(warning(disable: codes)) -#else -# define nssv_SUPPRESS_MSGSL_WARNING(expr) -# define nssv_SUPPRESS_MSVC_WARNING(code, descr) -# define nssv_DISABLE_MSVC_WARNINGS(codes) -#endif +namespace inja { -#if defined(__clang__) -# define nssv_RESTORE_WARNINGS() _Pragma("clang diagnostic pop") -#elif defined(__GNUC__) -# define nssv_RESTORE_WARNINGS() _Pragma("GCC diagnostic pop") -#elif nssv_COMPILER_MSVC_VERSION >= 140 -# define nssv_RESTORE_WARNINGS() __pragma(warning(pop )) -#else -# define nssv_RESTORE_WARNINGS() -#endif +using Arguments = std::vector; +using CallbackFunction = std::function; +using VoidCallbackFunction = std::function; -// Suppress the following MSVC (GSL) warnings: -// - C4455, non-gsl : 'operator ""sv': literal suffix identifiers that do not -// start with an underscore are reserved -// - C26472, gsl::t.1 : don't use a static_cast for arithmetic conversions; -// use brace initialization, gsl::narrow_cast or gsl::narow -// - C26481: gsl::b.1 : don't use pointer arithmetic. Use span instead - -nssv_DISABLE_MSVC_WARNINGS( 4455 26481 26472 ) -//nssv_DISABLE_CLANG_WARNINGS( "-Wuser-defined-literals" ) -//nssv_DISABLE_GNUC_WARNINGS( -Wliteral-suffix ) - -namespace nonstd { namespace sv_lite { - -template -< - class CharT, - class Traits = std::char_traits -> -class basic_string_view; - -// -// basic_string_view: -// - -template -< - class CharT, - class Traits /* = std::char_traits */ -> -class basic_string_view -{ +/*! + * \brief Class for builtin functions and user-defined callbacks. + */ +class FunctionStorage { public: - // Member types: - - typedef Traits traits_type; - typedef CharT value_type; - - typedef CharT * pointer; - typedef CharT const * const_pointer; - typedef CharT & reference; - typedef CharT const & const_reference; - - typedef const_pointer iterator; - typedef const_pointer const_iterator; - typedef std::reverse_iterator< const_iterator > reverse_iterator; - typedef std::reverse_iterator< const_iterator > const_reverse_iterator; - - typedef std::size_t size_type; - typedef std::ptrdiff_t difference_type; - - // 24.4.2.1 Construction and assignment: - - nssv_constexpr basic_string_view() nssv_noexcept - : data_( nssv_nullptr ) - , size_( 0 ) - {} - -#if nssv_CPP11_OR_GREATER - nssv_constexpr basic_string_view( basic_string_view const & other ) nssv_noexcept = default; -#else - nssv_constexpr basic_string_view( basic_string_view const & other ) nssv_noexcept - : data_( other.data_) - , size_( other.size_) - {} -#endif - - nssv_constexpr basic_string_view( CharT const * s, size_type count ) - : data_( s ) - , size_( count ) - {} - - nssv_constexpr basic_string_view( CharT const * s) - : data_( s ) - , size_( Traits::length(s) ) - {} - - // Assignment: - -#if nssv_CPP11_OR_GREATER - nssv_constexpr14 basic_string_view & operator=( basic_string_view const & other ) nssv_noexcept = default; -#else - nssv_constexpr14 basic_string_view & operator=( basic_string_view const & other ) nssv_noexcept - { - data_ = other.data_; - size_ = other.size_; - return *this; - } -#endif - - // 24.4.2.2 Iterator support: - - nssv_constexpr const_iterator begin() const nssv_noexcept { return data_; } - nssv_constexpr const_iterator end() const nssv_noexcept { return data_ + size_; } - - nssv_constexpr const_iterator cbegin() const nssv_noexcept { return begin(); } - nssv_constexpr const_iterator cend() const nssv_noexcept { return end(); } - - nssv_constexpr const_reverse_iterator rbegin() const nssv_noexcept { return const_reverse_iterator( end() ); } - nssv_constexpr const_reverse_iterator rend() const nssv_noexcept { return const_reverse_iterator( begin() ); } - - nssv_constexpr const_reverse_iterator crbegin() const nssv_noexcept { return rbegin(); } - nssv_constexpr const_reverse_iterator crend() const nssv_noexcept { return rend(); } - - // 24.4.2.3 Capacity: - - nssv_constexpr size_type size() const nssv_noexcept { return size_; } - nssv_constexpr size_type length() const nssv_noexcept { return size_; } - nssv_constexpr size_type max_size() const nssv_noexcept { return (std::numeric_limits< size_type >::max)(); } - - // since C++20 - nssv_nodiscard nssv_constexpr bool empty() const nssv_noexcept - { - return 0 == size_; - } - - // 24.4.2.4 Element access: - - nssv_constexpr const_reference operator[]( size_type pos ) const - { - return data_at( pos ); - } - - nssv_constexpr14 const_reference at( size_type pos ) const - { -#if nssv_CONFIG_NO_EXCEPTIONS - assert( pos < size() ); -#else - if ( pos >= size() ) - { - throw std::out_of_range("nonst::string_view::at()"); - } -#endif - return data_at( pos ); - } - - nssv_constexpr const_reference front() const { return data_at( 0 ); } - nssv_constexpr const_reference back() const { return data_at( size() - 1 ); } - - nssv_constexpr const_pointer data() const nssv_noexcept { return data_; } - - // 24.4.2.5 Modifiers: - - nssv_constexpr14 void remove_prefix( size_type n ) - { - assert( n <= size() ); - data_ += n; - size_ -= n; - } - - nssv_constexpr14 void remove_suffix( size_type n ) - { - assert( n <= size() ); - size_ -= n; - } - - nssv_constexpr14 void swap( basic_string_view & other ) nssv_noexcept - { - using std::swap; - swap( data_, other.data_ ); - swap( size_, other.size_ ); - } - - // 24.4.2.6 String operations: - - size_type copy( CharT * dest, size_type n, size_type pos = 0 ) const - { -#if nssv_CONFIG_NO_EXCEPTIONS - assert( pos <= size() ); -#else - if ( pos > size() ) - { - throw std::out_of_range("nonst::string_view::copy()"); - } -#endif - const size_type rlen = (std::min)( n, size() - pos ); - - (void) Traits::copy( dest, data() + pos, rlen ); - - return rlen; - } - - nssv_constexpr14 basic_string_view substr( size_type pos = 0, size_type n = npos ) const - { -#if nssv_CONFIG_NO_EXCEPTIONS - assert( pos <= size() ); -#else - if ( pos > size() ) - { - throw std::out_of_range("nonst::string_view::substr()"); - } -#endif - return basic_string_view( data() + pos, (std::min)( n, size() - pos ) ); - } - - // compare(), 6x: - - nssv_constexpr14 int compare( basic_string_view other ) const nssv_noexcept // (1) - { - if ( const int result = Traits::compare( data(), other.data(), (std::min)( size(), other.size() ) ) ) - return result; - - return size() == other.size() ? 0 : size() < other.size() ? -1 : 1; - } - - nssv_constexpr int compare( size_type pos1, size_type n1, basic_string_view other ) const // (2) - { - return substr( pos1, n1 ).compare( other ); - } - - nssv_constexpr int compare( size_type pos1, size_type n1, basic_string_view other, size_type pos2, size_type n2 ) const // (3) - { - return substr( pos1, n1 ).compare( other.substr( pos2, n2 ) ); - } - - nssv_constexpr int compare( CharT const * s ) const // (4) - { - return compare( basic_string_view( s ) ); - } - - nssv_constexpr int compare( size_type pos1, size_type n1, CharT const * s ) const // (5) - { - return substr( pos1, n1 ).compare( basic_string_view( s ) ); - } - - nssv_constexpr int compare( size_type pos1, size_type n1, CharT const * s, size_type n2 ) const // (6) - { - return substr( pos1, n1 ).compare( basic_string_view( s, n2 ) ); - } - - // 24.4.2.7 Searching: - - // starts_with(), 3x, since C++20: - - nssv_constexpr bool starts_with( basic_string_view v ) const nssv_noexcept // (1) - { - return size() >= v.size() && compare( 0, v.size(), v ) == 0; - } - - nssv_constexpr bool starts_with( CharT c ) const nssv_noexcept // (2) - { - return starts_with( basic_string_view( &c, 1 ) ); - } - - nssv_constexpr bool starts_with( CharT const * s ) const // (3) - { - return starts_with( basic_string_view( s ) ); - } - - // ends_with(), 3x, since C++20: - - nssv_constexpr bool ends_with( basic_string_view v ) const nssv_noexcept // (1) - { - return size() >= v.size() && compare( size() - v.size(), npos, v ) == 0; - } - - nssv_constexpr bool ends_with( CharT c ) const nssv_noexcept // (2) - { - return ends_with( basic_string_view( &c, 1 ) ); - } + enum class Operation { + Not, + And, + Or, + In, + Equal, + NotEqual, + Greater, + GreaterEqual, + Less, + LessEqual, + Add, + Subtract, + Multiplication, + Division, + Power, + Modulo, + AtId, + At, + Default, + DivisibleBy, + Even, + Exists, + ExistsInObject, + First, + Float, + Int, + IsArray, + IsBoolean, + IsFloat, + IsInteger, + IsNumber, + IsObject, + IsString, + Last, + Length, + Lower, + Max, + Min, + Odd, + Range, + Round, + Sort, + Upper, + Super, + Join, + Callback, + ParenLeft, + ParenRight, + None, + }; - nssv_constexpr bool ends_with( CharT const * s ) const // (3) - { - return ends_with( basic_string_view( s ) ); - } + struct FunctionData { + explicit FunctionData(const Operation& op, const CallbackFunction& cb = CallbackFunction {}): operation(op), callback(cb) {} + const Operation operation; + const CallbackFunction callback; + }; - // find(), 4x: +private: + const int VARIADIC {-1}; + + std::map, FunctionData> function_storage = { + {std::make_pair("at", 2), FunctionData {Operation::At}}, + {std::make_pair("default", 2), FunctionData {Operation::Default}}, + {std::make_pair("divisibleBy", 2), FunctionData {Operation::DivisibleBy}}, + {std::make_pair("even", 1), FunctionData {Operation::Even}}, + {std::make_pair("exists", 1), FunctionData {Operation::Exists}}, + {std::make_pair("existsIn", 2), FunctionData {Operation::ExistsInObject}}, + {std::make_pair("first", 1), FunctionData {Operation::First}}, + {std::make_pair("float", 1), FunctionData {Operation::Float}}, + {std::make_pair("int", 1), FunctionData {Operation::Int}}, + {std::make_pair("isArray", 1), FunctionData {Operation::IsArray}}, + {std::make_pair("isBoolean", 1), FunctionData {Operation::IsBoolean}}, + {std::make_pair("isFloat", 1), FunctionData {Operation::IsFloat}}, + {std::make_pair("isInteger", 1), FunctionData {Operation::IsInteger}}, + {std::make_pair("isNumber", 1), FunctionData {Operation::IsNumber}}, + {std::make_pair("isObject", 1), FunctionData {Operation::IsObject}}, + {std::make_pair("isString", 1), FunctionData {Operation::IsString}}, + {std::make_pair("last", 1), FunctionData {Operation::Last}}, + {std::make_pair("length", 1), FunctionData {Operation::Length}}, + {std::make_pair("lower", 1), FunctionData {Operation::Lower}}, + {std::make_pair("max", 1), FunctionData {Operation::Max}}, + {std::make_pair("min", 1), FunctionData {Operation::Min}}, + {std::make_pair("odd", 1), FunctionData {Operation::Odd}}, + {std::make_pair("range", 1), FunctionData {Operation::Range}}, + {std::make_pair("round", 2), FunctionData {Operation::Round}}, + {std::make_pair("sort", 1), FunctionData {Operation::Sort}}, + {std::make_pair("upper", 1), FunctionData {Operation::Upper}}, + {std::make_pair("super", 0), FunctionData {Operation::Super}}, + {std::make_pair("super", 1), FunctionData {Operation::Super}}, + {std::make_pair("join", 2), FunctionData {Operation::Join}}, + }; - nssv_constexpr14 size_type find( basic_string_view v, size_type pos = 0 ) const nssv_noexcept // (1) - { - return assert( v.size() == 0 || v.data() != nssv_nullptr ) - , pos >= size() - ? npos - : to_pos( std::search( cbegin() + pos, cend(), v.cbegin(), v.cend(), Traits::eq ) ); - } +public: + void add_builtin(std::string_view name, int num_args, Operation op) { + function_storage.emplace(std::make_pair(static_cast(name), num_args), FunctionData {op}); + } - nssv_constexpr14 size_type find( CharT c, size_type pos = 0 ) const nssv_noexcept // (2) - { - return find( basic_string_view( &c, 1 ), pos ); - } + void add_callback(std::string_view name, int num_args, const CallbackFunction& callback) { + function_storage.emplace(std::make_pair(static_cast(name), num_args), FunctionData {Operation::Callback, callback}); + } - nssv_constexpr14 size_type find( CharT const * s, size_type pos, size_type n ) const // (3) - { - return find( basic_string_view( s, n ), pos ); - } + FunctionData find_function(std::string_view name, int num_args) const { + auto it = function_storage.find(std::make_pair(static_cast(name), num_args)); + if (it != function_storage.end()) { + return it->second; - nssv_constexpr14 size_type find( CharT const * s, size_type pos = 0 ) const // (4) - { - return find( basic_string_view( s ), pos ); + // Find variadic function + } else if (num_args > 0) { + it = function_storage.find(std::make_pair(static_cast(name), VARIADIC)); + if (it != function_storage.end()) { + return it->second; + } } - // rfind(), 4x: - - nssv_constexpr14 size_type rfind( basic_string_view v, size_type pos = npos ) const nssv_noexcept // (1) - { - if ( size() < v.size() ) - return npos; + return FunctionData {Operation::None}; + } +}; - if ( v.empty() ) - return (std::min)( size(), pos ); +} // namespace inja - const_iterator last = cbegin() + (std::min)( size() - v.size(), pos ) + v.size(); - const_iterator result = std::find_end( cbegin(), last, v.cbegin(), v.cend(), Traits::eq ); +#endif // INCLUDE_INJA_FUNCTION_STORAGE_HPP_ - return result != last ? size_type( result - cbegin() ) : npos; - } +// #include "utils.hpp" +#ifndef INCLUDE_INJA_UTILS_HPP_ +#define INCLUDE_INJA_UTILS_HPP_ - nssv_constexpr14 size_type rfind( CharT c, size_type pos = npos ) const nssv_noexcept // (2) - { - return rfind( basic_string_view( &c, 1 ), pos ); - } +#include +#include +#include +#include +#include - nssv_constexpr14 size_type rfind( CharT const * s, size_type pos, size_type n ) const // (3) - { - return rfind( basic_string_view( s, n ), pos ); - } +// #include "exceptions.hpp" +#ifndef INCLUDE_INJA_EXCEPTIONS_HPP_ +#define INCLUDE_INJA_EXCEPTIONS_HPP_ - nssv_constexpr14 size_type rfind( CharT const * s, size_type pos = npos ) const // (4) - { - return rfind( basic_string_view( s ), pos ); - } +#include +#include - // find_first_of(), 4x: +namespace inja { - nssv_constexpr size_type find_first_of( basic_string_view v, size_type pos = 0 ) const nssv_noexcept // (1) - { - return pos >= size() - ? npos - : to_pos( std::find_first_of( cbegin() + pos, cend(), v.cbegin(), v.cend(), Traits::eq ) ); - } +struct SourceLocation { + size_t line; + size_t column; +}; - nssv_constexpr size_type find_first_of( CharT c, size_type pos = 0 ) const nssv_noexcept // (2) - { - return find_first_of( basic_string_view( &c, 1 ), pos ); - } +struct InjaError : public std::runtime_error { + const std::string type; + const std::string message; - nssv_constexpr size_type find_first_of( CharT const * s, size_type pos, size_type n ) const // (3) - { - return find_first_of( basic_string_view( s, n ), pos ); - } + const SourceLocation location; - nssv_constexpr size_type find_first_of( CharT const * s, size_type pos = 0 ) const // (4) - { - return find_first_of( basic_string_view( s ), pos ); - } + explicit InjaError(const std::string& type, const std::string& message) + : std::runtime_error("[inja.exception." + type + "] " + message), type(type), message(message), location({0, 0}) {} - // find_last_of(), 4x: + explicit InjaError(const std::string& type, const std::string& message, SourceLocation location) + : std::runtime_error("[inja.exception." + type + "] (at " + std::to_string(location.line) + ":" + std::to_string(location.column) + ") " + message), + type(type), message(message), location(location) {} +}; - nssv_constexpr size_type find_last_of( basic_string_view v, size_type pos = npos ) const nssv_noexcept // (1) - { - return empty() - ? npos - : pos >= size() - ? find_last_of( v, size() - 1 ) - : to_pos( std::find_first_of( const_reverse_iterator( cbegin() + pos + 1 ), crend(), v.cbegin(), v.cend(), Traits::eq ) ); - } +struct ParserError : public InjaError { + explicit ParserError(const std::string& message, SourceLocation location): InjaError("parser_error", message, location) {} +}; - nssv_constexpr size_type find_last_of( CharT c, size_type pos = npos ) const nssv_noexcept // (2) - { - return find_last_of( basic_string_view( &c, 1 ), pos ); - } +struct RenderError : public InjaError { + explicit RenderError(const std::string& message, SourceLocation location): InjaError("render_error", message, location) {} +}; - nssv_constexpr size_type find_last_of( CharT const * s, size_type pos, size_type count ) const // (3) - { - return find_last_of( basic_string_view( s, count ), pos ); - } +struct FileError : public InjaError { + explicit FileError(const std::string& message): InjaError("file_error", message) {} + explicit FileError(const std::string& message, SourceLocation location): InjaError("file_error", message, location) {} +}; - nssv_constexpr size_type find_last_of( CharT const * s, size_type pos = npos ) const // (4) - { - return find_last_of( basic_string_view( s ), pos ); - } +struct DataError : public InjaError { + explicit DataError(const std::string& message, SourceLocation location): InjaError("data_error", message, location) {} +}; - // find_first_not_of(), 4x: +} // namespace inja - nssv_constexpr size_type find_first_not_of( basic_string_view v, size_type pos = 0 ) const nssv_noexcept // (1) - { - return pos >= size() - ? npos - : to_pos( std::find_if( cbegin() + pos, cend(), not_in_view( v ) ) ); - } +#endif // INCLUDE_INJA_EXCEPTIONS_HPP_ - nssv_constexpr size_type find_first_not_of( CharT c, size_type pos = 0 ) const nssv_noexcept // (2) - { - return find_first_not_of( basic_string_view( &c, 1 ), pos ); - } - nssv_constexpr size_type find_first_not_of( CharT const * s, size_type pos, size_type count ) const // (3) - { - return find_first_not_of( basic_string_view( s, count ), pos ); - } +namespace inja { - nssv_constexpr size_type find_first_not_of( CharT const * s, size_type pos = 0 ) const // (4) - { - return find_first_not_of( basic_string_view( s ), pos ); - } +namespace string_view { +inline std::string_view slice(std::string_view view, size_t start, size_t end) { + start = std::min(start, view.size()); + end = std::min(std::max(start, end), view.size()); + return view.substr(start, end - start); +} - // find_last_not_of(), 4x: +inline std::pair split(std::string_view view, char Separator) { + size_t idx = view.find(Separator); + if (idx == std::string_view::npos) { + return std::make_pair(view, std::string_view()); + } + return std::make_pair(slice(view, 0, idx), slice(view, idx + 1, std::string_view::npos)); +} - nssv_constexpr size_type find_last_not_of( basic_string_view v, size_type pos = npos ) const nssv_noexcept // (1) - { - return empty() - ? npos - : pos >= size() - ? find_last_not_of( v, size() - 1 ) - : to_pos( std::find_if( const_reverse_iterator( cbegin() + pos + 1 ), crend(), not_in_view( v ) ) ); - } +inline bool starts_with(std::string_view view, std::string_view prefix) { + return (view.size() >= prefix.size() && view.compare(0, prefix.size(), prefix) == 0); +} +} // namespace string_view - nssv_constexpr size_type find_last_not_of( CharT c, size_type pos = npos ) const nssv_noexcept // (2) - { - return find_last_not_of( basic_string_view( &c, 1 ), pos ); - } +inline SourceLocation get_source_location(std::string_view content, size_t pos) { + // Get line and offset position (starts at 1:1) + auto sliced = string_view::slice(content, 0, pos); + std::size_t last_newline = sliced.rfind("\n"); - nssv_constexpr size_type find_last_not_of( CharT const * s, size_type pos, size_type count ) const // (3) - { - return find_last_not_of( basic_string_view( s, count ), pos ); - } + if (last_newline == std::string_view::npos) { + return {1, sliced.length() + 1}; + } - nssv_constexpr size_type find_last_not_of( CharT const * s, size_type pos = npos ) const // (4) - { - return find_last_not_of( basic_string_view( s ), pos ); + // Count newlines + size_t count_lines = 0; + size_t search_start = 0; + while (search_start <= sliced.size()) { + search_start = sliced.find("\n", search_start) + 1; + if (search_start == 0) { + break; } + count_lines += 1; + } - // Constants: - -#if nssv_CPP17_OR_GREATER - static nssv_constexpr size_type npos = size_type(-1); -#elif nssv_CPP11_OR_GREATER - enum : size_type { npos = size_type(-1) }; -#else - enum { npos = size_type(-1) }; -#endif - -private: - struct not_in_view - { - const basic_string_view v; - - nssv_constexpr not_in_view( basic_string_view v ) : v( v ) {} + return {count_lines + 1, sliced.length() - last_newline}; +} - nssv_constexpr bool operator()( CharT c ) const - { - return npos == v.find_first_of( c ); - } - }; +inline void replace_substring(std::string& s, const std::string& f, const std::string& t) { + if (f.empty()) { + return; + } + for (auto pos = s.find(f); // find first occurrence of f + pos != std::string::npos; // make sure f was found + s.replace(pos, f.size(), t), // replace with t, and + pos = s.find(f, pos + t.size())) // find next occurrence of f + {} +} - nssv_constexpr size_type to_pos( const_iterator it ) const - { - return it == cend() ? npos : size_type( it - cbegin() ); - } +} // namespace inja - nssv_constexpr size_type to_pos( const_reverse_iterator it ) const - { - return it == crend() ? npos : size_type( crend() - it - 1 ); - } +#endif // INCLUDE_INJA_UTILS_HPP_ - nssv_constexpr const_reference data_at( size_type pos ) const - { -#if nssv_BETWEEN( nssv_COMPILER_GNUC_VERSION, 1, 500 ) - return data_[pos]; -#else - return assert( pos < size() ), data_[pos]; -#endif - } -private: - const_pointer data_; - size_type size_; +namespace inja { +class NodeVisitor; +class BlockNode; +class TextNode; +class ExpressionNode; +class LiteralNode; +class DataNode; +class FunctionNode; +class ExpressionListNode; +class StatementNode; +class ForStatementNode; +class ForArrayStatementNode; +class ForObjectStatementNode; +class IfStatementNode; +class IncludeStatementNode; +class ExtendsStatementNode; +class BlockStatementNode; +class SetStatementNode; + +class NodeVisitor { public: -#if nssv_CONFIG_CONVERSION_STD_STRING_CLASS_METHODS + virtual ~NodeVisitor() = default; + + virtual void visit(const BlockNode& node) = 0; + virtual void visit(const TextNode& node) = 0; + virtual void visit(const ExpressionNode& node) = 0; + virtual void visit(const LiteralNode& node) = 0; + virtual void visit(const DataNode& node) = 0; + virtual void visit(const FunctionNode& node) = 0; + virtual void visit(const ExpressionListNode& node) = 0; + virtual void visit(const StatementNode& node) = 0; + virtual void visit(const ForStatementNode& node) = 0; + virtual void visit(const ForArrayStatementNode& node) = 0; + virtual void visit(const ForObjectStatementNode& node) = 0; + virtual void visit(const IfStatementNode& node) = 0; + virtual void visit(const IncludeStatementNode& node) = 0; + virtual void visit(const ExtendsStatementNode& node) = 0; + virtual void visit(const BlockStatementNode& node) = 0; + virtual void visit(const SetStatementNode& node) = 0; +}; - template< class Allocator > - basic_string_view( std::basic_string const & s ) nssv_noexcept - : data_( s.data() ) - , size_( s.size() ) - {} +/*! + * \brief Base node class for the abstract syntax tree (AST). + */ +class AstNode { +public: + virtual void accept(NodeVisitor& v) const = 0; -#if nssv_HAVE_EXPLICIT_CONVERSION + size_t pos; - template< class Allocator > - explicit operator std::basic_string() const - { - return to_string( Allocator() ); - } + AstNode(size_t pos): pos(pos) {} + virtual ~AstNode() {} +}; -#endif // nssv_HAVE_EXPLICIT_CONVERSION +class BlockNode : public AstNode { +public: + std::vector> nodes; -#if nssv_CPP11_OR_GREATER + explicit BlockNode(): AstNode(0) {} - template< class Allocator = std::allocator > - std::basic_string - to_string( Allocator const & a = Allocator() ) const - { - return std::basic_string( begin(), end(), a ); - } + void accept(NodeVisitor& v) const { + v.visit(*this); + } +}; -#else +class TextNode : public AstNode { +public: + const size_t length; - std::basic_string - to_string() const - { - return std::basic_string( begin(), end() ); - } + explicit TextNode(size_t pos, size_t length): AstNode(pos), length(length) {} - template< class Allocator > - std::basic_string - to_string( Allocator const & a ) const - { - return std::basic_string( begin(), end(), a ); - } + void accept(NodeVisitor& v) const { + v.visit(*this); + } +}; -#endif // nssv_CPP11_OR_GREATER +class ExpressionNode : public AstNode { +public: + explicit ExpressionNode(size_t pos): AstNode(pos) {} -#endif // nssv_CONFIG_CONVERSION_STD_STRING_CLASS_METHODS + void accept(NodeVisitor& v) const { + v.visit(*this); + } }; -// -// Non-member functions: -// - -// 24.4.3 Non-member comparison functions: -// lexicographically compare two string views (function template): - -template< class CharT, class Traits > -nssv_constexpr bool operator== ( - basic_string_view lhs, - basic_string_view rhs ) nssv_noexcept -{ return lhs.compare( rhs ) == 0 ; } - -template< class CharT, class Traits > -nssv_constexpr bool operator!= ( - basic_string_view lhs, - basic_string_view rhs ) nssv_noexcept -{ return lhs.compare( rhs ) != 0 ; } - -template< class CharT, class Traits > -nssv_constexpr bool operator< ( - basic_string_view lhs, - basic_string_view rhs ) nssv_noexcept -{ return lhs.compare( rhs ) < 0 ; } - -template< class CharT, class Traits > -nssv_constexpr bool operator<= ( - basic_string_view lhs, - basic_string_view rhs ) nssv_noexcept -{ return lhs.compare( rhs ) <= 0 ; } - -template< class CharT, class Traits > -nssv_constexpr bool operator> ( - basic_string_view lhs, - basic_string_view rhs ) nssv_noexcept -{ return lhs.compare( rhs ) > 0 ; } - -template< class CharT, class Traits > -nssv_constexpr bool operator>= ( - basic_string_view lhs, - basic_string_view rhs ) nssv_noexcept -{ return lhs.compare( rhs ) >= 0 ; } - -// Let S be basic_string_view, and sv be an instance of S. -// Implementations shall provide sufficient additional overloads marked -// constexpr and noexcept so that an object t with an implicit conversion -// to S can be compared according to Table 67. - -#if nssv_CPP11_OR_GREATER && ! nssv_BETWEEN( nssv_COMPILER_MSVC_VERSION, 100, 141 ) - -#define nssv_BASIC_STRING_VIEW_I(T,U) typename std::decay< basic_string_view >::type - -#if nssv_BETWEEN( nssv_COMPILER_MSVC_VERSION, 140, 150 ) -# define nssv_MSVC_ORDER(x) , int=x -#else -# define nssv_MSVC_ORDER(x) /*, int=x*/ -#endif - -// == - -template< class CharT, class Traits nssv_MSVC_ORDER(1) > -nssv_constexpr bool operator==( - basic_string_view lhs, - nssv_BASIC_STRING_VIEW_I(CharT, Traits) rhs ) nssv_noexcept -{ return lhs.compare( rhs ) == 0; } - -template< class CharT, class Traits nssv_MSVC_ORDER(2) > -nssv_constexpr bool operator==( - nssv_BASIC_STRING_VIEW_I(CharT, Traits) lhs, - basic_string_view rhs ) nssv_noexcept -{ return lhs.size() == rhs.size() && lhs.compare( rhs ) == 0; } - -// != - -template< class CharT, class Traits nssv_MSVC_ORDER(1) > -nssv_constexpr bool operator!= ( - basic_string_view < CharT, Traits > lhs, - nssv_BASIC_STRING_VIEW_I( CharT, Traits ) rhs ) nssv_noexcept -{ return lhs.size() != rhs.size() || lhs.compare( rhs ) != 0 ; } - -template< class CharT, class Traits nssv_MSVC_ORDER(2) > -nssv_constexpr bool operator!= ( - nssv_BASIC_STRING_VIEW_I( CharT, Traits ) lhs, - basic_string_view < CharT, Traits > rhs ) nssv_noexcept -{ return lhs.compare( rhs ) != 0 ; } - -// < - -template< class CharT, class Traits nssv_MSVC_ORDER(1) > -nssv_constexpr bool operator< ( - basic_string_view < CharT, Traits > lhs, - nssv_BASIC_STRING_VIEW_I( CharT, Traits ) rhs ) nssv_noexcept -{ return lhs.compare( rhs ) < 0 ; } - -template< class CharT, class Traits nssv_MSVC_ORDER(2) > -nssv_constexpr bool operator< ( - nssv_BASIC_STRING_VIEW_I( CharT, Traits ) lhs, - basic_string_view < CharT, Traits > rhs ) nssv_noexcept -{ return lhs.compare( rhs ) < 0 ; } - -// <= - -template< class CharT, class Traits nssv_MSVC_ORDER(1) > -nssv_constexpr bool operator<= ( - basic_string_view < CharT, Traits > lhs, - nssv_BASIC_STRING_VIEW_I( CharT, Traits ) rhs ) nssv_noexcept -{ return lhs.compare( rhs ) <= 0 ; } - -template< class CharT, class Traits nssv_MSVC_ORDER(2) > -nssv_constexpr bool operator<= ( - nssv_BASIC_STRING_VIEW_I( CharT, Traits ) lhs, - basic_string_view < CharT, Traits > rhs ) nssv_noexcept -{ return lhs.compare( rhs ) <= 0 ; } - -// > - -template< class CharT, class Traits nssv_MSVC_ORDER(1) > -nssv_constexpr bool operator> ( - basic_string_view < CharT, Traits > lhs, - nssv_BASIC_STRING_VIEW_I( CharT, Traits ) rhs ) nssv_noexcept -{ return lhs.compare( rhs ) > 0 ; } - -template< class CharT, class Traits nssv_MSVC_ORDER(2) > -nssv_constexpr bool operator> ( - nssv_BASIC_STRING_VIEW_I( CharT, Traits ) lhs, - basic_string_view < CharT, Traits > rhs ) nssv_noexcept -{ return lhs.compare( rhs ) > 0 ; } - -// >= - -template< class CharT, class Traits nssv_MSVC_ORDER(1) > -nssv_constexpr bool operator>= ( - basic_string_view < CharT, Traits > lhs, - nssv_BASIC_STRING_VIEW_I( CharT, Traits ) rhs ) nssv_noexcept -{ return lhs.compare( rhs ) >= 0 ; } - -template< class CharT, class Traits nssv_MSVC_ORDER(2) > -nssv_constexpr bool operator>= ( - nssv_BASIC_STRING_VIEW_I( CharT, Traits ) lhs, - basic_string_view < CharT, Traits > rhs ) nssv_noexcept -{ return lhs.compare( rhs ) >= 0 ; } - -#undef nssv_MSVC_ORDER -#undef nssv_BASIC_STRING_VIEW_I - -#endif // nssv_CPP11_OR_GREATER - -// 24.4.4 Inserters and extractors: - -namespace detail { - -template< class Stream > -void write_padding( Stream & os, std::streamsize n ) -{ - for ( std::streamsize i = 0; i < n; ++i ) - os.rdbuf()->sputc( os.fill() ); -} +class LiteralNode : public ExpressionNode { +public: + const json value; -template< class Stream, class View > -Stream & write_to_stream( Stream & os, View const & sv ) -{ - typename Stream::sentry sentry( os ); + explicit LiteralNode(std::string_view data_text, size_t pos): ExpressionNode(pos), value(json::parse(data_text)) {} - if ( !os ) - return os; + void accept(NodeVisitor& v) const { + v.visit(*this); + } +}; - const std::streamsize length = static_cast( sv.length() ); +class DataNode : public ExpressionNode { +public: + const std::string name; + const json::json_pointer ptr; + + static std::string convert_dot_to_ptr(std::string_view ptr_name) { + std::string result; + do { + std::string_view part; + std::tie(part, ptr_name) = string_view::split(ptr_name, '.'); + result.push_back('/'); + result.append(part.begin(), part.end()); + } while (!ptr_name.empty()); + return result; + } - // Whether, and how, to pad: - const bool pad = ( length < os.width() ); - const bool left_pad = pad && ( os.flags() & std::ios_base::adjustfield ) == std::ios_base::right; + explicit DataNode(std::string_view ptr_name, size_t pos): ExpressionNode(pos), name(ptr_name), ptr(json::json_pointer(convert_dot_to_ptr(ptr_name))) {} - if ( left_pad ) - write_padding( os, os.width() - length ); + void accept(NodeVisitor& v) const { + v.visit(*this); + } +}; - // Write span characters: - os.rdbuf()->sputn( sv.begin(), length ); +class FunctionNode : public ExpressionNode { + using Op = FunctionStorage::Operation; - if ( pad && !left_pad ) - write_padding( os, os.width() - length ); +public: + enum class Associativity { + Left, + Right, + }; - // Reset output stream width: - os.width( 0 ); + unsigned int precedence; + Associativity associativity; + + Op operation; + + std::string name; + int number_args; // Should also be negative -> -1 for unknown number + std::vector> arguments; + CallbackFunction callback; + + explicit FunctionNode(std::string_view name, size_t pos) + : ExpressionNode(pos), precedence(8), associativity(Associativity::Left), operation(Op::Callback), name(name), number_args(1) {} + explicit FunctionNode(Op operation, size_t pos): ExpressionNode(pos), operation(operation), number_args(1) { + switch (operation) { + case Op::Not: { + number_args = 1; + precedence = 4; + associativity = Associativity::Left; + } break; + case Op::And: { + number_args = 2; + precedence = 1; + associativity = Associativity::Left; + } break; + case Op::Or: { + number_args = 2; + precedence = 1; + associativity = Associativity::Left; + } break; + case Op::In: { + number_args = 2; + precedence = 2; + associativity = Associativity::Left; + } break; + case Op::Equal: { + number_args = 2; + precedence = 2; + associativity = Associativity::Left; + } break; + case Op::NotEqual: { + number_args = 2; + precedence = 2; + associativity = Associativity::Left; + } break; + case Op::Greater: { + number_args = 2; + precedence = 2; + associativity = Associativity::Left; + } break; + case Op::GreaterEqual: { + number_args = 2; + precedence = 2; + associativity = Associativity::Left; + } break; + case Op::Less: { + number_args = 2; + precedence = 2; + associativity = Associativity::Left; + } break; + case Op::LessEqual: { + number_args = 2; + precedence = 2; + associativity = Associativity::Left; + } break; + case Op::Add: { + number_args = 2; + precedence = 3; + associativity = Associativity::Left; + } break; + case Op::Subtract: { + number_args = 2; + precedence = 3; + associativity = Associativity::Left; + } break; + case Op::Multiplication: { + number_args = 2; + precedence = 4; + associativity = Associativity::Left; + } break; + case Op::Division: { + number_args = 2; + precedence = 4; + associativity = Associativity::Left; + } break; + case Op::Power: { + number_args = 2; + precedence = 5; + associativity = Associativity::Right; + } break; + case Op::Modulo: { + number_args = 2; + precedence = 4; + associativity = Associativity::Left; + } break; + case Op::AtId: { + number_args = 2; + precedence = 8; + associativity = Associativity::Left; + } break; + default: { + precedence = 1; + associativity = Associativity::Left; + } + } + } - return os; -} + void accept(NodeVisitor& v) const { + v.visit(*this); + } +}; -} // namespace detail +class ExpressionListNode : public AstNode { +public: + std::shared_ptr root; -template< class CharT, class Traits > -std::basic_ostream & -operator<<( - std::basic_ostream& os, - basic_string_view sv ) -{ - return detail::write_to_stream( os, sv ); -} + explicit ExpressionListNode(): AstNode(0) {} + explicit ExpressionListNode(size_t pos): AstNode(pos) {} -// Several typedefs for common character types are provided: + void accept(NodeVisitor& v) const { + v.visit(*this); + } +}; -typedef basic_string_view string_view; -typedef basic_string_view wstring_view; -#if nssv_HAVE_WCHAR16_T -typedef basic_string_view u16string_view; -typedef basic_string_view u32string_view; -#endif +class StatementNode : public AstNode { +public: + StatementNode(size_t pos): AstNode(pos) {} -}} // namespace nonstd::sv_lite + virtual void accept(NodeVisitor& v) const = 0; +}; -// -// 24.4.6 Suffix for basic_string_view literals: -// +class ForStatementNode : public StatementNode { +public: + ExpressionListNode condition; + BlockNode body; + BlockNode* const parent; -#if nssv_HAVE_USER_DEFINED_LITERALS + ForStatementNode(BlockNode* const parent, size_t pos): StatementNode(pos), parent(parent) {} -namespace nonstd { -nssv_inline_ns namespace literals { -nssv_inline_ns namespace string_view_literals { + virtual void accept(NodeVisitor& v) const = 0; +}; -#if nssv_CONFIG_STD_SV_OPERATOR && nssv_HAVE_STD_DEFINED_LITERALS +class ForArrayStatementNode : public ForStatementNode { +public: + const std::string value; -nssv_constexpr nonstd::sv_lite::string_view operator "" sv( const char* str, size_t len ) nssv_noexcept // (1) -{ - return nonstd::sv_lite::string_view{ str, len }; -} + explicit ForArrayStatementNode(const std::string& value, BlockNode* const parent, size_t pos): ForStatementNode(parent, pos), value(value) {} -nssv_constexpr nonstd::sv_lite::u16string_view operator "" sv( const char16_t* str, size_t len ) nssv_noexcept // (2) -{ - return nonstd::sv_lite::u16string_view{ str, len }; -} + void accept(NodeVisitor& v) const { + v.visit(*this); + } +}; -nssv_constexpr nonstd::sv_lite::u32string_view operator "" sv( const char32_t* str, size_t len ) nssv_noexcept // (3) -{ - return nonstd::sv_lite::u32string_view{ str, len }; -} +class ForObjectStatementNode : public ForStatementNode { +public: + const std::string key; + const std::string value; -nssv_constexpr nonstd::sv_lite::wstring_view operator "" sv( const wchar_t* str, size_t len ) nssv_noexcept // (4) -{ - return nonstd::sv_lite::wstring_view{ str, len }; -} + explicit ForObjectStatementNode(const std::string& key, const std::string& value, BlockNode* const parent, size_t pos) + : ForStatementNode(parent, pos), key(key), value(value) {} -#endif // nssv_CONFIG_STD_SV_OPERATOR && nssv_HAVE_STD_DEFINED_LITERALS + void accept(NodeVisitor& v) const { + v.visit(*this); + } +}; -#if nssv_CONFIG_USR_SV_OPERATOR +class IfStatementNode : public StatementNode { +public: + ExpressionListNode condition; + BlockNode true_statement; + BlockNode false_statement; + BlockNode* const parent; -nssv_constexpr nonstd::sv_lite::string_view operator "" _sv( const char* str, size_t len ) nssv_noexcept // (1) -{ - return nonstd::sv_lite::string_view{ str, len }; -} + const bool is_nested; + bool has_false_statement {false}; -nssv_constexpr nonstd::sv_lite::u16string_view operator "" _sv( const char16_t* str, size_t len ) nssv_noexcept // (2) -{ - return nonstd::sv_lite::u16string_view{ str, len }; -} + explicit IfStatementNode(BlockNode* const parent, size_t pos): StatementNode(pos), parent(parent), is_nested(false) {} + explicit IfStatementNode(bool is_nested, BlockNode* const parent, size_t pos): StatementNode(pos), parent(parent), is_nested(is_nested) {} -nssv_constexpr nonstd::sv_lite::u32string_view operator "" _sv( const char32_t* str, size_t len ) nssv_noexcept // (3) -{ - return nonstd::sv_lite::u32string_view{ str, len }; -} + void accept(NodeVisitor& v) const { + v.visit(*this); + } +}; -nssv_constexpr nonstd::sv_lite::wstring_view operator "" _sv( const wchar_t* str, size_t len ) nssv_noexcept // (4) -{ - return nonstd::sv_lite::wstring_view{ str, len }; -} +class IncludeStatementNode : public StatementNode { +public: + const std::string file; -#endif // nssv_CONFIG_USR_SV_OPERATOR + explicit IncludeStatementNode(const std::string& file, size_t pos): StatementNode(pos), file(file) {} -}}} // namespace nonstd::literals::string_view_literals + void accept(NodeVisitor& v) const { + v.visit(*this); + } +}; -#endif +class ExtendsStatementNode : public StatementNode { +public: + const std::string file; -// -// Extensions for std::string: -// + explicit ExtendsStatementNode(const std::string& file, size_t pos): StatementNode(pos), file(file) {} -#if nssv_CONFIG_CONVERSION_STD_STRING_FREE_FUNCTIONS + void accept(NodeVisitor& v) const { + v.visit(*this); + }; +}; -namespace nonstd { -namespace sv_lite { +class BlockStatementNode : public StatementNode { +public: + const std::string name; + BlockNode block; + BlockNode* const parent; -// Exclude MSVC 14 (19.00): it yields ambiguous to_string(): + explicit BlockStatementNode(BlockNode* const parent, const std::string& name, size_t pos): StatementNode(pos), name(name), parent(parent) {} -#if nssv_CPP11_OR_GREATER && nssv_COMPILER_MSVC_VERSION != 140 + void accept(NodeVisitor& v) const { + v.visit(*this); + }; +}; -template< class CharT, class Traits, class Allocator = std::allocator > -std::basic_string -to_string( basic_string_view v, Allocator const & a = Allocator() ) -{ - return std::basic_string( v.begin(), v.end(), a ); -} +class SetStatementNode : public StatementNode { +public: + const std::string key; + ExpressionListNode expression; -#else + explicit SetStatementNode(const std::string& key, size_t pos): StatementNode(pos), key(key) {} -template< class CharT, class Traits > -std::basic_string -to_string( basic_string_view v ) -{ - return std::basic_string( v.begin(), v.end() ); -} + void accept(NodeVisitor& v) const { + v.visit(*this); + } +}; -template< class CharT, class Traits, class Allocator > -std::basic_string -to_string( basic_string_view v, Allocator const & a ) -{ - return std::basic_string( v.begin(), v.end(), a ); -} +} // namespace inja -#endif // nssv_CPP11_OR_GREATER +#endif // INCLUDE_INJA_NODE_HPP_ -template< class CharT, class Traits, class Allocator > -basic_string_view -to_string_view( std::basic_string const & s ) -{ - return basic_string_view( s.data(), s.size() ); -} +// #include "statistics.hpp" +#ifndef INCLUDE_INJA_STATISTICS_HPP_ +#define INCLUDE_INJA_STATISTICS_HPP_ -}} // namespace nonstd::sv_lite +// #include "node.hpp" -#endif // nssv_CONFIG_CONVERSION_STD_STRING_FREE_FUNCTIONS -// -// make types and algorithms available in namespace nonstd: -// +namespace inja { -namespace nonstd { +/*! + * \brief A class for counting statistics on a Template. + */ +class StatisticsVisitor : public NodeVisitor { + void visit(const BlockNode& node) { + for (auto& n : node.nodes) { + n->accept(*this); + } + } -using sv_lite::basic_string_view; -using sv_lite::string_view; -using sv_lite::wstring_view; + void visit(const TextNode&) {} + void visit(const ExpressionNode&) {} + void visit(const LiteralNode&) {} -#if nssv_HAVE_WCHAR16_T -using sv_lite::u16string_view; -#endif -#if nssv_HAVE_WCHAR32_T -using sv_lite::u32string_view; -#endif + void visit(const DataNode&) { + variable_counter += 1; + } -// literal "sv" + void visit(const FunctionNode& node) { + for (auto& n : node.arguments) { + n->accept(*this); + } + } -using sv_lite::operator==; -using sv_lite::operator!=; -using sv_lite::operator<; -using sv_lite::operator<=; -using sv_lite::operator>; -using sv_lite::operator>=; + void visit(const ExpressionListNode& node) { + node.root->accept(*this); + } -using sv_lite::operator<<; + void visit(const StatementNode&) {} + void visit(const ForStatementNode&) {} -#if nssv_CONFIG_CONVERSION_STD_STRING_FREE_FUNCTIONS -using sv_lite::to_string; -using sv_lite::to_string_view; -#endif + void visit(const ForArrayStatementNode& node) { + node.condition.accept(*this); + node.body.accept(*this); + } -} // namespace nonstd + void visit(const ForObjectStatementNode& node) { + node.condition.accept(*this); + node.body.accept(*this); + } -// 24.4.5 Hash support (C++11): + void visit(const IfStatementNode& node) { + node.condition.accept(*this); + node.true_statement.accept(*this); + node.false_statement.accept(*this); + } -// Note: The hash value of a string view object is equal to the hash value of -// the corresponding string object. + void visit(const IncludeStatementNode&) {} -#if nssv_HAVE_STD_HASH + void visit(const ExtendsStatementNode&) {} -#include + void visit(const BlockStatementNode& node) { + node.block.accept(*this); + } -namespace std { + void visit(const SetStatementNode&) {} -template<> -struct hash< nonstd::string_view > -{ public: - std::size_t operator()( nonstd::string_view v ) const nssv_noexcept - { - return std::hash()( std::string( v.data(), v.size() ) ); - } -}; + unsigned int variable_counter; -template<> -struct hash< nonstd::wstring_view > -{ -public: - std::size_t operator()( nonstd::wstring_view v ) const nssv_noexcept - { - return std::hash()( std::wstring( v.data(), v.size() ) ); - } + explicit StatisticsVisitor(): variable_counter(0) {} }; -template<> -struct hash< nonstd::u16string_view > -{ -public: - std::size_t operator()( nonstd::u16string_view v ) const nssv_noexcept - { - return std::hash()( std::u16string( v.data(), v.size() ) ); - } -}; +} // namespace inja -template<> -struct hash< nonstd::u32string_view > -{ -public: - std::size_t operator()( nonstd::u32string_view v ) const nssv_noexcept - { - return std::hash()( std::u32string( v.data(), v.size() ) ); - } -}; +#endif // INCLUDE_INJA_STATISTICS_HPP_ -} // namespace std -#endif // nssv_HAVE_STD_HASH +namespace inja { -nssv_RESTORE_WARNINGS() +/*! + * \brief The main inja Template. + */ +struct Template { + BlockNode root; + std::string content; + std::map> block_storage; -#endif // nssv_HAVE_STD_STRING_VIEW -#endif // NONSTD_SV_LITE_H_INCLUDED + explicit Template() {} + explicit Template(const std::string& content): content(content) {} + /// Return number of variables (total number, not distinct ones) in the template + int count_variables() { + auto statistic_visitor = StatisticsVisitor(); + root.accept(statistic_visitor); + return statistic_visitor.variable_counter; + } +}; +using TemplateStorage = std::map; -namespace inja { +} // namespace inja -enum class ElementNotation { - Dot, - Pointer -}; +#endif // INCLUDE_INJA_TEMPLATE_HPP_ + + +namespace inja { /*! * \brief Class for lexer configuration. */ struct LexerConfig { std::string statement_open {"{%"}; + std::string statement_open_no_lstrip {"{%+"}; + std::string statement_open_force_lstrip {"{%-"}; std::string statement_close {"%}"}; + std::string statement_close_force_rstrip {"-%}"}; std::string line_statement {"##"}; std::string expression_open {"{{"}; + std::string expression_open_force_lstrip {"{{-"}; std::string expression_close {"}}"}; + std::string expression_close_force_rstrip {"-}}"}; std::string comment_open {"{#"}; + std::string comment_open_force_lstrip {"{#-"}; std::string comment_close {"#}"}; + std::string comment_close_force_rstrip {"-#}"}; std::string open_chars {"#{"}; bool trim_blocks {false}; @@ -1435,12 +849,24 @@ struct LexerConfig { if (open_chars.find(statement_open[0]) == std::string::npos) { open_chars += statement_open[0]; } + if (open_chars.find(statement_open_no_lstrip[0]) == std::string::npos) { + open_chars += statement_open_no_lstrip[0]; + } + if (open_chars.find(statement_open_force_lstrip[0]) == std::string::npos) { + open_chars += statement_open_force_lstrip[0]; + } if (open_chars.find(expression_open[0]) == std::string::npos) { open_chars += expression_open[0]; } + if (open_chars.find(expression_open_force_lstrip[0]) == std::string::npos) { + open_chars += expression_open_force_lstrip[0]; + } if (open_chars.find(comment_open[0]) == std::string::npos) { open_chars += comment_open[0]; } + if (open_chars.find(comment_open_force_lstrip[0]) == std::string::npos) { + open_chars += comment_open_force_lstrip[0]; + } } }; @@ -1448,245 +874,43 @@ struct LexerConfig { * \brief Class for parser configuration. */ struct ParserConfig { - ElementNotation notation {ElementNotation::Dot}; -}; - -} - -#endif // PANTOR_INJA_CONFIG_HPP - -// #include "function_storage.hpp" -#ifndef PANTOR_INJA_FUNCTION_STORAGE_HPP -#define PANTOR_INJA_FUNCTION_STORAGE_HPP - -#include - -// #include "bytecode.hpp" -#ifndef PANTOR_INJA_BYTECODE_HPP -#define PANTOR_INJA_BYTECODE_HPP - -#include -#include - -#include - -// #include "string_view.hpp" - - - -namespace inja { - -using json = nlohmann::json; - - -struct Bytecode { - enum class Op : uint8_t { - Nop, - // print StringRef (always immediate) - PrintText, - // print value - PrintValue, - // push value onto stack (always immediate) - Push, - - // builtin functions - // result is pushed to stack - // args specify number of arguments - // all functions can take their "last" argument either immediate - // or popped off stack (e.g. if immediate, it's like the immediate was - // just pushed to the stack) - Not, - And, - Or, - In, - Equal, - Greater, - GreaterEqual, - Less, - LessEqual, - At, - Different, - DivisibleBy, - Even, - First, - Float, - Int, - Last, - Length, - Lower, - Max, - Min, - Odd, - Range, - Result, - Round, - Sort, - Upper, - Exists, - ExistsInObject, - IsBoolean, - IsNumber, - IsInteger, - IsFloat, - IsObject, - IsArray, - IsString, - Default, - - // include another template - // value is the template name - Include, - - // callback function - // str is the function name (this means it cannot be a lookup) - // args specify number of arguments - // as with builtin functions, "last" argument can be immediate - Callback, - - // unconditional jump - // args is the index of the bytecode to jump to. - Jump, - - // conditional jump - // value popped off stack is checked for truthyness - // if false, args is the index of the bytecode to jump to. - // if true, no action is taken (falls through) - ConditionalJump, - - // start loop - // value popped off stack is what is iterated over - // args is index of bytecode after end loop (jumped to if iterable is - // empty) - // immediate value is key name (for maps) - // str is value name - StartLoop, - - // end a loop - // args is index of the first bytecode in the loop body - EndLoop, - }; - - enum Flag { - // location of value for value-taking ops (mask) - ValueMask = 0x03, - // pop value off stack - ValuePop = 0x00, - // value is immediate rather than on stack - ValueImmediate = 0x01, - // lookup immediate str (dot notation) - ValueLookupDot = 0x02, - // lookup immediate str (json pointer notation) - ValueLookupPointer = 0x03, - }; + bool search_included_templates_in_files {true}; - Op op {Op::Nop}; - uint32_t args: 30; - uint32_t flags: 2; - - json value; - std::string str; - - Bytecode(): args(0), flags(0) {} - explicit Bytecode(Op op, unsigned int args = 0): op(op), args(args), flags(0) {} - explicit Bytecode(Op op, nonstd::string_view str, unsigned int flags): op(op), args(0), flags(flags), str(str) {} - explicit Bytecode(Op op, json&& value, unsigned int flags): op(op), args(0), flags(flags), value(std::move(value)) {} + std::function include_callback; }; -} // namespace inja - -#endif // PANTOR_INJA_BYTECODE_HPP - -// #include "string_view.hpp" - - - -namespace inja { - -using namespace nlohmann; - -using Arguments = std::vector; -using CallbackFunction = std::function; - /*! - * \brief Class for builtin functions and user-defined callbacks. + * \brief Class for render configuration. */ -class FunctionStorage { - public: - void add_builtin(nonstd::string_view name, unsigned int num_args, Bytecode::Op op) { - auto& data = get_or_new(name, num_args); - data.op = op; - } - - void add_callback(nonstd::string_view name, unsigned int num_args, const CallbackFunction& function) { - auto& data = get_or_new(name, num_args); - data.function = function; - } - - Bytecode::Op find_builtin(nonstd::string_view name, unsigned int num_args) const { - if (auto ptr = get(name, num_args)) { - return ptr->op; - } - return Bytecode::Op::Nop; - } - - CallbackFunction find_callback(nonstd::string_view name, unsigned int num_args) const { - if (auto ptr = get(name, num_args)) { - return ptr->function; - } - return nullptr; - } - - private: - struct FunctionData { - unsigned int num_args {0}; - Bytecode::Op op {Bytecode::Op::Nop}; // for builtins - CallbackFunction function; // for callbacks - }; - - FunctionData& get_or_new(nonstd::string_view name, unsigned int num_args) { - auto &vec = m_map[static_cast(name)]; - for (auto &i: vec) { - if (i.num_args == num_args) return i; - } - vec.emplace_back(); - vec.back().num_args = num_args; - return vec.back(); - } - - const FunctionData* get(nonstd::string_view name, unsigned int num_args) const { - auto it = m_map.find(static_cast(name)); - if (it == m_map.end()) return nullptr; - for (auto &&i: it->second) { - if (i.num_args == num_args) return &i; - } - return nullptr; - } - - std::map> m_map; +struct RenderConfig { + bool throw_at_missing_includes {true}; }; -} +} // namespace inja + +#endif // INCLUDE_INJA_CONFIG_HPP_ -#endif // PANTOR_INJA_FUNCTION_STORAGE_HPP +// #include "function_storage.hpp" // #include "parser.hpp" -#ifndef PANTOR_INJA_PARSER_HPP -#define PANTOR_INJA_PARSER_HPP +#ifndef INCLUDE_INJA_PARSER_HPP_ +#define INCLUDE_INJA_PARSER_HPP_ #include +#include #include -#include +#include #include -// #include "bytecode.hpp" - // #include "config.hpp" +// #include "exceptions.hpp" + // #include "function_storage.hpp" // #include "lexer.hpp" -#ifndef PANTOR_INJA_LEXER_HPP -#define PANTOR_INJA_LEXER_HPP +#ifndef INCLUDE_INJA_LEXER_HPP_ +#define INCLUDE_INJA_LEXER_HPP_ #include #include @@ -1694,130 +918,81 @@ class FunctionStorage { // #include "config.hpp" // #include "token.hpp" -#ifndef PANTOR_INJA_TOKEN_HPP -#define PANTOR_INJA_TOKEN_HPP +#ifndef INCLUDE_INJA_TOKEN_HPP_ +#define INCLUDE_INJA_TOKEN_HPP_ #include - -// #include "string_view.hpp" - - +#include namespace inja { /*! - * \brief Helper-class for the inja Parser. + * \brief Helper-class for the inja Lexer. */ struct Token { enum class Kind { Text, - ExpressionOpen, // {{ - ExpressionClose, // }} - LineStatementOpen, // ## - LineStatementClose, // \n - StatementOpen, // {% - StatementClose, // %} - CommentOpen, // {# - CommentClose, // #} - Id, // this, this.foo - Number, // 1, 2, -1, 5.2, -5.3 - String, // "this" - Comma, // , - Colon, // : - LeftParen, // ( - RightParen, // ) - LeftBracket, // [ - RightBracket, // ] - LeftBrace, // { - RightBrace, // } - Equal, // == - GreaterThan, // > - GreaterEqual, // >= - LessThan, // < - LessEqual, // <= - NotEqual, // != + ExpressionOpen, // {{ + ExpressionClose, // }} + LineStatementOpen, // ## + LineStatementClose, // \n + StatementOpen, // {% + StatementClose, // %} + CommentOpen, // {# + CommentClose, // #} + Id, // this, this.foo + Number, // 1, 2, -1, 5.2, -5.3 + String, // "this" + Plus, // + + Minus, // - + Times, // * + Slash, // / + Percent, // % + Power, // ^ + Comma, // , + Dot, // . + Colon, // : + LeftParen, // ( + RightParen, // ) + LeftBracket, // [ + RightBracket, // ] + LeftBrace, // { + RightBrace, // } + Equal, // == + NotEqual, // != + GreaterThan, // > + GreaterEqual, // >= + LessThan, // < + LessEqual, // <= Unknown, - Eof - } kind {Kind::Unknown}; + Eof, + }; - nonstd::string_view text; + Kind kind {Kind::Unknown}; + std::string_view text; - constexpr Token() = default; - constexpr Token(Kind kind, nonstd::string_view text): kind(kind), text(text) {} + explicit constexpr Token() = default; + explicit constexpr Token(Kind kind, std::string_view text): kind(kind), text(text) {} std::string describe() const { switch (kind) { - case Kind::Text: - return ""; - case Kind::LineStatementClose: - return ""; - case Kind::Eof: - return ""; - default: - return static_cast(text); + case Kind::Text: + return ""; + case Kind::LineStatementClose: + return ""; + case Kind::Eof: + return ""; + default: + return static_cast(text); } } }; -} +} // namespace inja -#endif // PANTOR_INJA_TOKEN_HPP +#endif // INCLUDE_INJA_TOKEN_HPP_ // #include "utils.hpp" -#ifndef PANTOR_INJA_UTILS_HPP -#define PANTOR_INJA_UTILS_HPP - -#include -#include -#include -#include -#include - -// #include "string_view.hpp" - - - -namespace inja { - -inline void inja_throw(const std::string& type, const std::string& message) { - throw std::runtime_error("[inja.exception." + type + "] " + message); -} - -inline std::ifstream open_file_or_throw(const std::string& path) { - std::ifstream file; - file.exceptions(std::ifstream::failbit | std::ifstream::badbit); - try { - file.open(path); - } catch(const std::ios_base::failure& e) { - inja_throw("file_error", "failed accessing file at '" + path + "'"); - } - return file; -} - -namespace string_view { - inline nonstd::string_view slice(nonstd::string_view view, size_t start, size_t end) { - start = std::min(start, view.size()); - end = std::min(std::max(start, end), view.size()); - return view.substr(start, end - start); // StringRef(Data + Start, End - Start); - } - - inline std::pair split(nonstd::string_view view, char Separator) { - size_t idx = view.find(Separator); - if (idx == nonstd::string_view::npos) { - return std::make_pair(view, nonstd::string_view()); - } - return std::make_pair(slice(view, 0, idx), slice(view, idx + 1, nonstd::string_view::npos)); - } - - inline bool starts_with(nonstd::string_view view, nonstd::string_view prefix) { - return (view.size() >= prefix.size() && view.compare(0, prefix.size(), prefix) == 0); - } -} // namespace string - -} // namespace inja - -#endif // PANTOR_INJA_UTILS_HPP - namespace inja { @@ -1829,236 +1004,190 @@ class Lexer { enum class State { Text, ExpressionStart, + ExpressionStartForceLstrip, ExpressionBody, LineStart, LineBody, StatementStart, + StatementStartNoLstrip, + StatementStartForceLstrip, StatementBody, CommentStart, - CommentBody - } m_state; - - const LexerConfig& m_config; - nonstd::string_view m_in; - size_t m_tok_start; - size_t m_pos; - - public: - explicit Lexer(const LexerConfig& config) : m_config(config) {} - - void start(nonstd::string_view in) { - m_in = in; - m_tok_start = 0; - m_pos = 0; - m_state = State::Text; - } - - Token scan() { - m_tok_start = m_pos; - - again: - if (m_tok_start >= m_in.size()) return make_token(Token::Kind::Eof); + CommentStartForceLstrip, + CommentBody, + }; - switch (m_state) { - default: - case State::Text: { - // fast-scan to first open character - size_t open_start = m_in.substr(m_pos).find_first_of(m_config.open_chars); - if (open_start == nonstd::string_view::npos) { - // didn't find open, return remaining text as text token - m_pos = m_in.size(); - return make_token(Token::Kind::Text); - } - m_pos += open_start; - - // try to match one of the opening sequences, and get the close - nonstd::string_view open_str = m_in.substr(m_pos); - bool must_lstrip = false; - if (inja::string_view::starts_with(open_str, m_config.expression_open)) { - m_state = State::ExpressionStart; - } else if (inja::string_view::starts_with(open_str, m_config.statement_open)) { - m_state = State::StatementStart; - must_lstrip = m_config.lstrip_blocks; - } else if (inja::string_view::starts_with(open_str, m_config.comment_open)) { - m_state = State::CommentStart; - must_lstrip = m_config.lstrip_blocks; - } else if ((m_pos == 0 || m_in[m_pos - 1] == '\n') && - inja::string_view::starts_with(open_str, m_config.line_statement)) { - m_state = State::LineStart; - } else { - m_pos += 1; // wasn't actually an opening sequence - goto again; - } + enum class MinusState { + Operator, + Number, + }; - nonstd::string_view text = string_view::slice(m_in, m_tok_start, m_pos); - if (must_lstrip) - text = clear_final_line_if_whitespace(text); - - if (text.empty()) goto again; // don't generate empty token - return Token(Token::Kind::Text, text); - } - case State::ExpressionStart: { - m_state = State::ExpressionBody; - m_pos += m_config.expression_open.size(); - return make_token(Token::Kind::ExpressionOpen); - } - case State::LineStart: { - m_state = State::LineBody; - m_pos += m_config.line_statement.size(); - return make_token(Token::Kind::LineStatementOpen); - } - case State::StatementStart: { - m_state = State::StatementBody; - m_pos += m_config.statement_open.size(); - return make_token(Token::Kind::StatementOpen); - } - case State::CommentStart: { - m_state = State::CommentBody; - m_pos += m_config.comment_open.size(); - return make_token(Token::Kind::CommentOpen); - } - case State::ExpressionBody: - return scan_body(m_config.expression_close, Token::Kind::ExpressionClose); - case State::LineBody: - return scan_body("\n", Token::Kind::LineStatementClose); - case State::StatementBody: - return scan_body(m_config.statement_close, Token::Kind::StatementClose, m_config.trim_blocks); - case State::CommentBody: { - // fast-scan to comment close - size_t end = m_in.substr(m_pos).find(m_config.comment_close); - if (end == nonstd::string_view::npos) { - m_pos = m_in.size(); - return make_token(Token::Kind::Eof); - } - // return the entire comment in the close token - m_state = State::Text; - m_pos += end + m_config.comment_close.size(); - Token tok = make_token(Token::Kind::CommentClose); - if (m_config.trim_blocks) - skip_newline(); - return tok; - } - } - } + const LexerConfig& config; - const LexerConfig& get_config() const { return m_config; } + State state; + MinusState minus_state; + std::string_view m_in; + size_t tok_start; + size_t pos; - private: - Token scan_body(nonstd::string_view close, Token::Kind closeKind, bool trim = false) { + Token scan_body(std::string_view close, Token::Kind closeKind, std::string_view close_trim = std::string_view(), bool trim = false) { again: // skip whitespace (except for \n as it might be a close) - if (m_tok_start >= m_in.size()) return make_token(Token::Kind::Eof); - char ch = m_in[m_tok_start]; + if (tok_start >= m_in.size()) { + return make_token(Token::Kind::Eof); + } + const char ch = m_in[tok_start]; if (ch == ' ' || ch == '\t' || ch == '\r') { - m_tok_start += 1; + tok_start += 1; goto again; } // check for close - if (inja::string_view::starts_with(m_in.substr(m_tok_start), close)) { - m_state = State::Text; - m_pos = m_tok_start + close.size(); - Token tok = make_token(closeKind); - if (trim) - skip_newline(); + if (!close_trim.empty() && inja::string_view::starts_with(m_in.substr(tok_start), close_trim)) { + state = State::Text; + pos = tok_start + close_trim.size(); + const Token tok = make_token(closeKind); + skip_whitespaces_and_newlines(); + return tok; + } + + if (inja::string_view::starts_with(m_in.substr(tok_start), close)) { + state = State::Text; + pos = tok_start + close.size(); + const Token tok = make_token(closeKind); + if (trim) { + skip_whitespaces_and_first_newline(); + } return tok; } // skip \n if (ch == '\n') { - m_tok_start += 1; + tok_start += 1; goto again; } - m_pos = m_tok_start + 1; - if (std::isalpha(ch)) return scan_id(); + pos = tok_start + 1; + if (std::isalpha(ch)) { + minus_state = MinusState::Operator; + return scan_id(); + } + + const MinusState current_minus_state = minus_state; + if (minus_state == MinusState::Operator) { + minus_state = MinusState::Number; + } + switch (ch) { - case ',': - return make_token(Token::Kind::Comma); - case ':': - return make_token(Token::Kind::Colon); - case '(': - return make_token(Token::Kind::LeftParen); - case ')': - return make_token(Token::Kind::RightParen); - case '[': - return make_token(Token::Kind::LeftBracket); - case ']': - return make_token(Token::Kind::RightBracket); - case '{': - return make_token(Token::Kind::LeftBrace); - case '}': - return make_token(Token::Kind::RightBrace); - case '>': - if (m_pos < m_in.size() && m_in[m_pos] == '=') { - m_pos += 1; - return make_token(Token::Kind::GreaterEqual); - } - return make_token(Token::Kind::GreaterThan); - case '<': - if (m_pos < m_in.size() && m_in[m_pos] == '=') { - m_pos += 1; - return make_token(Token::Kind::LessEqual); - } - return make_token(Token::Kind::LessThan); - case '=': - if (m_pos < m_in.size() && m_in[m_pos] == '=') { - m_pos += 1; - return make_token(Token::Kind::Equal); - } - return make_token(Token::Kind::Unknown); - case '!': - if (m_pos < m_in.size() && m_in[m_pos] == '=') { - m_pos += 1; - return make_token(Token::Kind::NotEqual); - } - return make_token(Token::Kind::Unknown); - case '\"': - return scan_string(); - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - case '-': - return scan_number(); - case '_': - return scan_id(); - default: - return make_token(Token::Kind::Unknown); + case '+': + return make_token(Token::Kind::Plus); + case '-': + if (current_minus_state == MinusState::Operator) { + return make_token(Token::Kind::Minus); + } + return scan_number(); + case '*': + return make_token(Token::Kind::Times); + case '/': + return make_token(Token::Kind::Slash); + case '^': + return make_token(Token::Kind::Power); + case '%': + return make_token(Token::Kind::Percent); + case '.': + return make_token(Token::Kind::Dot); + case ',': + return make_token(Token::Kind::Comma); + case ':': + return make_token(Token::Kind::Colon); + case '(': + return make_token(Token::Kind::LeftParen); + case ')': + minus_state = MinusState::Operator; + return make_token(Token::Kind::RightParen); + case '[': + return make_token(Token::Kind::LeftBracket); + case ']': + minus_state = MinusState::Operator; + return make_token(Token::Kind::RightBracket); + case '{': + return make_token(Token::Kind::LeftBrace); + case '}': + minus_state = MinusState::Operator; + return make_token(Token::Kind::RightBrace); + case '>': + if (pos < m_in.size() && m_in[pos] == '=') { + pos += 1; + return make_token(Token::Kind::GreaterEqual); + } + return make_token(Token::Kind::GreaterThan); + case '<': + if (pos < m_in.size() && m_in[pos] == '=') { + pos += 1; + return make_token(Token::Kind::LessEqual); + } + return make_token(Token::Kind::LessThan); + case '=': + if (pos < m_in.size() && m_in[pos] == '=') { + pos += 1; + return make_token(Token::Kind::Equal); + } + return make_token(Token::Kind::Unknown); + case '!': + if (pos < m_in.size() && m_in[pos] == '=') { + pos += 1; + return make_token(Token::Kind::NotEqual); + } + return make_token(Token::Kind::Unknown); + case '\"': + return scan_string(); + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + minus_state = MinusState::Operator; + return scan_number(); + case '_': + case '@': + case '$': + minus_state = MinusState::Operator; + return scan_id(); + default: + return make_token(Token::Kind::Unknown); } } Token scan_id() { for (;;) { - if (m_pos >= m_in.size()) { + if (pos >= m_in.size()) { break; } - char ch = m_in[m_pos]; + const char ch = m_in[pos]; if (!std::isalnum(ch) && ch != '.' && ch != '/' && ch != '_' && ch != '-') { break; } - m_pos += 1; + pos += 1; } return make_token(Token::Kind::Id); } Token scan_number() { for (;;) { - if (m_pos >= m_in.size()) { + if (pos >= m_in.size()) { break; } - char ch = m_in[m_pos]; + const char ch = m_in[pos]; // be very permissive in lexer (we'll catch errors when conversion happens) - if (!std::isdigit(ch) && ch != '.' && ch != 'e' && ch != 'E' && ch != '+' && ch != '-') { + if (!(std::isdigit(ch) || ch == '.' || ch == 'e' || ch == 'E' || (ch == '+' && (pos == 0 || m_in[pos-1] == 'e' || m_in[pos-1] == 'E')) || (ch == '-' && (pos == 0 || m_in[pos-1] == 'e' || m_in[pos-1] == 'E')))) { break; } - m_pos += 1; + pos += 1; } return make_token(Token::Kind::Number); } @@ -2066,11 +1195,13 @@ class Lexer { Token scan_string() { bool escape {false}; for (;;) { - if (m_pos >= m_in.size()) break; - char ch = m_in[m_pos++]; + if (pos >= m_in.size()) { + break; + } + const char ch = m_in[pos++]; if (ch == '\\') { escape = true; - } else if (!escape && ch == m_in[m_tok_start]) { + } else if (!escape && ch == m_in[tok_start]) { break; } else { escape = false; @@ -2080,1353 +1211,1606 @@ class Lexer { } Token make_token(Token::Kind kind) const { - return Token(kind, string_view::slice(m_in, m_tok_start, m_pos)); + return Token(kind, string_view::slice(m_in, tok_start, pos)); + } + + void skip_whitespaces_and_newlines() { + if (pos < m_in.size()) { + while (pos < m_in.size() && (m_in[pos] == ' ' || m_in[pos] == '\t' || m_in[pos] == '\n' || m_in[pos] == '\r')) { + pos += 1; + } + } } - void skip_newline() { - if (m_pos < m_in.size()) { - char ch = m_in[m_pos]; - if (ch == '\n') - m_pos += 1; - else if (ch == '\r') { - m_pos += 1; - if (m_pos < m_in.size() && m_in[m_pos] == '\n') - m_pos += 1; + void skip_whitespaces_and_first_newline() { + if (pos < m_in.size()) { + while (pos < m_in.size() && (m_in[pos] == ' ' || m_in[pos] == '\t')) { + pos += 1; + } + } + + if (pos < m_in.size()) { + const char ch = m_in[pos]; + if (ch == '\n') { + pos += 1; + } else if (ch == '\r') { + pos += 1; + if (pos < m_in.size() && m_in[pos] == '\n') { + pos += 1; + } } } } - static nonstd::string_view clear_final_line_if_whitespace(nonstd::string_view text) - { - nonstd::string_view result = text; + static std::string_view clear_final_line_if_whitespace(std::string_view text) { + std::string_view result = text; while (!result.empty()) { - char ch = result.back(); - if (ch == ' ' || ch == '\t') - result.remove_suffix(1); - else if (ch == '\n' || ch == '\r') + const char ch = result.back(); + if (ch == ' ' || ch == '\t') { + result.remove_suffix(1); + } else if (ch == '\n' || ch == '\r') { break; - else + } else { return text; + } } return result; } -}; -} +public: + explicit Lexer(const LexerConfig& config): config(config), state(State::Text), minus_state(MinusState::Number) {} -#endif // PANTOR_INJA_LEXER_HPP + SourceLocation current_position() const { + return get_source_location(m_in, tok_start); + } -// #include "template.hpp" -#ifndef PANTOR_INJA_TEMPLATE_HPP -#define PANTOR_INJA_TEMPLATE_HPP + void start(std::string_view input) { + m_in = input; + tok_start = 0; + pos = 0; + state = State::Text; + minus_state = MinusState::Number; -#include -#include -#include + // Consume byte order mark (BOM) for UTF-8 + if (inja::string_view::starts_with(m_in, "\xEF\xBB\xBF")) { + m_in = m_in.substr(3); + } + } -// #include "bytecode.hpp" + Token scan() { + tok_start = pos; + again: + if (tok_start >= m_in.size()) { + return make_token(Token::Kind::Eof); + } + + switch (state) { + default: + case State::Text: { + // fast-scan to first open character + const size_t open_start = m_in.substr(pos).find_first_of(config.open_chars); + if (open_start == std::string_view::npos) { + // didn't find open, return remaining text as text token + pos = m_in.size(); + return make_token(Token::Kind::Text); + } + pos += open_start; + + // try to match one of the opening sequences, and get the close + std::string_view open_str = m_in.substr(pos); + bool must_lstrip = false; + if (inja::string_view::starts_with(open_str, config.expression_open)) { + if (inja::string_view::starts_with(open_str, config.expression_open_force_lstrip)) { + state = State::ExpressionStartForceLstrip; + must_lstrip = true; + } else { + state = State::ExpressionStart; + } + } else if (inja::string_view::starts_with(open_str, config.statement_open)) { + if (inja::string_view::starts_with(open_str, config.statement_open_no_lstrip)) { + state = State::StatementStartNoLstrip; + } else if (inja::string_view::starts_with(open_str, config.statement_open_force_lstrip)) { + state = State::StatementStartForceLstrip; + must_lstrip = true; + } else { + state = State::StatementStart; + must_lstrip = config.lstrip_blocks; + } + } else if (inja::string_view::starts_with(open_str, config.comment_open)) { + if (inja::string_view::starts_with(open_str, config.comment_open_force_lstrip)) { + state = State::CommentStartForceLstrip; + must_lstrip = true; + } else { + state = State::CommentStart; + must_lstrip = config.lstrip_blocks; + } + } else if ((pos == 0 || m_in[pos - 1] == '\n') && inja::string_view::starts_with(open_str, config.line_statement)) { + state = State::LineStart; + } else { + pos += 1; // wasn't actually an opening sequence + goto again; + } + std::string_view text = string_view::slice(m_in, tok_start, pos); + if (must_lstrip) { + text = clear_final_line_if_whitespace(text); + } -namespace inja { + if (text.empty()) { + goto again; // don't generate empty token + } + return Token(Token::Kind::Text, text); + } + case State::ExpressionStart: { + state = State::ExpressionBody; + pos += config.expression_open.size(); + return make_token(Token::Kind::ExpressionOpen); + } + case State::ExpressionStartForceLstrip: { + state = State::ExpressionBody; + pos += config.expression_open_force_lstrip.size(); + return make_token(Token::Kind::ExpressionOpen); + } + case State::LineStart: { + state = State::LineBody; + pos += config.line_statement.size(); + return make_token(Token::Kind::LineStatementOpen); + } + case State::StatementStart: { + state = State::StatementBody; + pos += config.statement_open.size(); + return make_token(Token::Kind::StatementOpen); + } + case State::StatementStartNoLstrip: { + state = State::StatementBody; + pos += config.statement_open_no_lstrip.size(); + return make_token(Token::Kind::StatementOpen); + } + case State::StatementStartForceLstrip: { + state = State::StatementBody; + pos += config.statement_open_force_lstrip.size(); + return make_token(Token::Kind::StatementOpen); + } + case State::CommentStart: { + state = State::CommentBody; + pos += config.comment_open.size(); + return make_token(Token::Kind::CommentOpen); + } + case State::CommentStartForceLstrip: { + state = State::CommentBody; + pos += config.comment_open_force_lstrip.size(); + return make_token(Token::Kind::CommentOpen); + } + case State::ExpressionBody: + return scan_body(config.expression_close, Token::Kind::ExpressionClose, config.expression_close_force_rstrip); + case State::LineBody: + return scan_body("\n", Token::Kind::LineStatementClose); + case State::StatementBody: + return scan_body(config.statement_close, Token::Kind::StatementClose, config.statement_close_force_rstrip, config.trim_blocks); + case State::CommentBody: { + // fast-scan to comment close + const size_t end = m_in.substr(pos).find(config.comment_close); + if (end == std::string_view::npos) { + pos = m_in.size(); + return make_token(Token::Kind::Eof); + } -/*! - * \brief The main inja Template. - */ -struct Template { - std::vector bytecodes; - std::string content; + // Check for trim pattern + const bool must_rstrip = inja::string_view::starts_with(m_in.substr(pos + end - 1), config.comment_close_force_rstrip); + + // return the entire comment in the close token + state = State::Text; + pos += end + config.comment_close.size(); + Token tok = make_token(Token::Kind::CommentClose); + + if (must_rstrip || config.trim_blocks) { + skip_whitespaces_and_first_newline(); + } + return tok; + } + } + } + + const LexerConfig& get_config() const { + return config; + } }; -using TemplateStorage = std::map; +} // namespace inja -} +#endif // INCLUDE_INJA_LEXER_HPP_ -#endif // PANTOR_INJA_TEMPLATE_HPP +// #include "node.hpp" + +// #include "template.hpp" // #include "token.hpp" // #include "utils.hpp" -#include - - namespace inja { -class ParserStatic { - ParserStatic() { - functions.add_builtin("at", 2, Bytecode::Op::At); - functions.add_builtin("default", 2, Bytecode::Op::Default); - functions.add_builtin("divisibleBy", 2, Bytecode::Op::DivisibleBy); - functions.add_builtin("even", 1, Bytecode::Op::Even); - functions.add_builtin("first", 1, Bytecode::Op::First); - functions.add_builtin("float", 1, Bytecode::Op::Float); - functions.add_builtin("int", 1, Bytecode::Op::Int); - functions.add_builtin("last", 1, Bytecode::Op::Last); - functions.add_builtin("length", 1, Bytecode::Op::Length); - functions.add_builtin("lower", 1, Bytecode::Op::Lower); - functions.add_builtin("max", 1, Bytecode::Op::Max); - functions.add_builtin("min", 1, Bytecode::Op::Min); - functions.add_builtin("odd", 1, Bytecode::Op::Odd); - functions.add_builtin("range", 1, Bytecode::Op::Range); - functions.add_builtin("round", 2, Bytecode::Op::Round); - functions.add_builtin("sort", 1, Bytecode::Op::Sort); - functions.add_builtin("upper", 1, Bytecode::Op::Upper); - functions.add_builtin("exists", 1, Bytecode::Op::Exists); - functions.add_builtin("existsIn", 2, Bytecode::Op::ExistsInObject); - functions.add_builtin("isBoolean", 1, Bytecode::Op::IsBoolean); - functions.add_builtin("isNumber", 1, Bytecode::Op::IsNumber); - functions.add_builtin("isInteger", 1, Bytecode::Op::IsInteger); - functions.add_builtin("isFloat", 1, Bytecode::Op::IsFloat); - functions.add_builtin("isObject", 1, Bytecode::Op::IsObject); - functions.add_builtin("isArray", 1, Bytecode::Op::IsArray); - functions.add_builtin("isString", 1, Bytecode::Op::IsString); - } - - public: - ParserStatic(const ParserStatic&) = delete; - ParserStatic& operator=(const ParserStatic&) = delete; - - static const ParserStatic& get_instance() { - static ParserStatic inst; - return inst; - } - - FunctionStorage functions; -}; - /*! * \brief Class for parsing an inja Template. */ class Parser { - public: - explicit Parser(const ParserConfig& parser_config, const LexerConfig& lexer_config, TemplateStorage& included_templates): m_config(parser_config), m_lexer(lexer_config), m_included_templates(included_templates), m_static(ParserStatic::get_instance()) { } - - bool parse_expression(Template& tmpl) { - if (!parse_expression_and(tmpl)) return false; - if (m_tok.kind != Token::Kind::Id || m_tok.text != static_cast("or")) return true; - get_next_token(); - if (!parse_expression_and(tmpl)) return false; - append_function(tmpl, Bytecode::Op::Or, 2); - return true; - } + const ParserConfig& config; - bool parse_expression_and(Template& tmpl) { - if (!parse_expression_not(tmpl)) return false; - if (m_tok.kind != Token::Kind::Id || m_tok.text != static_cast("and")) return true; - get_next_token(); - if (!parse_expression_not(tmpl)) return false; - append_function(tmpl, Bytecode::Op::And, 2); - return true; + Lexer lexer; + TemplateStorage& template_storage; + const FunctionStorage& function_storage; + + Token tok, peek_tok; + bool have_peek_tok {false}; + + size_t current_paren_level {0}; + size_t current_bracket_level {0}; + size_t current_brace_level {0}; + + std::string_view literal_start; + + BlockNode* current_block {nullptr}; + ExpressionListNode* current_expression_list {nullptr}; + std::stack> function_stack; + std::vector> arguments; + + std::stack> operator_stack; + std::stack if_statement_stack; + std::stack for_statement_stack; + std::stack block_statement_stack; + + inline void throw_parser_error(const std::string& message) const { + INJA_THROW(ParserError(message, lexer.current_position())); } - bool parse_expression_not(Template& tmpl) { - if (m_tok.kind == Token::Kind::Id && m_tok.text == static_cast("not")) { - get_next_token(); - if (!parse_expression_not(tmpl)) return false; - append_function(tmpl, Bytecode::Op::Not, 1); - return true; + inline void get_next_token() { + if (have_peek_tok) { + tok = peek_tok; + have_peek_tok = false; } else { - return parse_expression_comparison(tmpl); + tok = lexer.scan(); } } - bool parse_expression_comparison(Template& tmpl) { - if (!parse_expression_datum(tmpl)) return false; - Bytecode::Op op; - switch (m_tok.kind) { - case Token::Kind::Id: - if (m_tok.text == static_cast("in")) - op = Bytecode::Op::In; - else - return true; - break; - case Token::Kind::Equal: - op = Bytecode::Op::Equal; - break; - case Token::Kind::GreaterThan: - op = Bytecode::Op::Greater; - break; - case Token::Kind::LessThan: - op = Bytecode::Op::Less; - break; - case Token::Kind::LessEqual: - op = Bytecode::Op::LessEqual; - break; - case Token::Kind::GreaterEqual: - op = Bytecode::Op::GreaterEqual; - break; - case Token::Kind::NotEqual: - op = Bytecode::Op::Different; - break; - default: - return true; + inline void get_peek_token() { + if (!have_peek_tok) { + peek_tok = lexer.scan(); + have_peek_tok = true; } - get_next_token(); - if (!parse_expression_datum(tmpl)) return false; - append_function(tmpl, op, 2); - return true; } - bool parse_expression_datum(Template& tmpl) { - nonstd::string_view json_first; - size_t bracket_level = 0; - size_t brace_level = 0; + inline void add_literal(const char* content_ptr) { + std::string_view data_text(literal_start.data(), tok.text.data() - literal_start.data() + tok.text.size()); + arguments.emplace_back(std::make_shared(data_text, data_text.data() - content_ptr)); + } - for (;;) { - switch (m_tok.kind) { - case Token::Kind::LeftParen: { - get_next_token(); - if (!parse_expression(tmpl)) return false; - if (m_tok.kind != Token::Kind::RightParen) { - inja_throw("parser_error", "unmatched '('"); + inline void add_operator() { + auto function = operator_stack.top(); + operator_stack.pop(); + + for (int i = 0; i < function->number_args; ++i) { + function->arguments.insert(function->arguments.begin(), arguments.back()); + arguments.pop_back(); + } + arguments.emplace_back(function); + } + + void add_to_template_storage(std::string_view path, std::string& template_name) { + if (template_storage.find(template_name) != template_storage.end()) { + return; + } + + std::string original_path = static_cast(path); + std::string original_name = template_name; + + if (config.search_included_templates_in_files) { + // Build the relative path + template_name = original_path + original_name; + if (template_name.compare(0, 2, "./") == 0) { + template_name.erase(0, 2); + } + + if (template_storage.find(template_name) == template_storage.end()) { + // Load file + std::ifstream file; + file.open(template_name); + if (!file.fail()) { + std::string text((std::istreambuf_iterator(file)), std::istreambuf_iterator()); + + auto include_template = Template(text); + template_storage.emplace(template_name, include_template); + parse_into_template(template_storage[template_name], template_name); + return; + } else if (!config.include_callback) { + INJA_THROW(FileError("failed accessing file at '" + template_name + "'")); + } + } + } + + // Try include callback + if (config.include_callback) { + auto include_template = config.include_callback(original_path, original_name); + template_storage.emplace(template_name, include_template); + } + } + + std::string parse_filename(const Token& tok) const { + if (tok.kind != Token::Kind::String) { + throw_parser_error("expected string, got '" + tok.describe() + "'"); + } + + if (tok.text.length() < 2) { + throw_parser_error("expected filename, got '" + static_cast(tok.text) + "'"); + } + + // Remove first and last character "" + return std::string {tok.text.substr(1, tok.text.length() - 2)}; + } + + bool parse_expression(Template& tmpl, Token::Kind closing) { + while (tok.kind != closing && tok.kind != Token::Kind::Eof) { + // Literals + switch (tok.kind) { + case Token::Kind::String: { + if (current_brace_level == 0 && current_bracket_level == 0) { + literal_start = tok.text; + add_literal(tmpl.content.c_str()); + } + } break; + case Token::Kind::Number: { + if (current_brace_level == 0 && current_bracket_level == 0) { + literal_start = tok.text; + add_literal(tmpl.content.c_str()); + } + } break; + case Token::Kind::LeftBracket: { + if (current_brace_level == 0 && current_bracket_level == 0) { + literal_start = tok.text; + } + current_bracket_level += 1; + } break; + case Token::Kind::LeftBrace: { + if (current_brace_level == 0 && current_bracket_level == 0) { + literal_start = tok.text; + } + current_brace_level += 1; + } break; + case Token::Kind::RightBracket: { + if (current_bracket_level == 0) { + throw_parser_error("unexpected ']'"); + } + + current_bracket_level -= 1; + if (current_brace_level == 0 && current_bracket_level == 0) { + add_literal(tmpl.content.c_str()); + } + } break; + case Token::Kind::RightBrace: { + if (current_brace_level == 0) { + throw_parser_error("unexpected '}'"); + } + + current_brace_level -= 1; + if (current_brace_level == 0 && current_bracket_level == 0) { + add_literal(tmpl.content.c_str()); + } + } break; + case Token::Kind::Id: { + get_peek_token(); + + // Data Literal + if (tok.text == static_cast("true") || tok.text == static_cast("false") || + tok.text == static_cast("null")) { + if (current_brace_level == 0 && current_bracket_level == 0) { + literal_start = tok.text; + add_literal(tmpl.content.c_str()); } - get_next_token(); - return true; + + // Operator + } else if (tok.text == "and" || tok.text == "or" || tok.text == "in" || tok.text == "not") { + goto parse_operator; + + // Functions + } else if (peek_tok.kind == Token::Kind::LeftParen) { + operator_stack.emplace(std::make_shared(static_cast(tok.text), tok.text.data() - tmpl.content.c_str())); + function_stack.emplace(operator_stack.top().get(), current_paren_level); + + // Variables + } else { + arguments.emplace_back(std::make_shared(static_cast(tok.text), tok.text.data() - tmpl.content.c_str())); } - case Token::Kind::Id: - get_peek_token(); - if (m_peek_tok.kind == Token::Kind::LeftParen) { - // function call, parse arguments - Token func_token = m_tok; - get_next_token(); // id - get_next_token(); // leftParen - unsigned int num_args = 0; - if (m_tok.kind == Token::Kind::RightParen) { - // no args - get_next_token(); - } else { - for (;;) { - if (!parse_expression(tmpl)) { - inja_throw("parser_error", "expected expression, got '" + m_tok.describe() + "'"); - } - num_args += 1; - if (m_tok.kind == Token::Kind::RightParen) { - get_next_token(); - break; - } - if (m_tok.kind != Token::Kind::Comma) { - inja_throw("parser_error", "expected ')' or ',', got '" + m_tok.describe() + "'"); - } - get_next_token(); - } - } - - auto op = m_static.functions.find_builtin(func_token.text, num_args); - - if (op != Bytecode::Op::Nop) { - // swap arguments for default(); see comment in RenderTo() - if (op == Bytecode::Op::Default) - std::swap(tmpl.bytecodes.back(), *(tmpl.bytecodes.rbegin() + 1)); - append_function(tmpl, op, num_args); - return true; - } else { - append_callback(tmpl, func_token.text, num_args); - return true; - } - } else if (m_tok.text == static_cast("true") || - m_tok.text == static_cast("false") || - m_tok.text == static_cast("null")) { - // true, false, null are json literals - if (brace_level == 0 && bracket_level == 0) { - json_first = m_tok.text; - goto returnJson; - } - break; + + // Operators + } break; + case Token::Kind::Equal: + case Token::Kind::NotEqual: + case Token::Kind::GreaterThan: + case Token::Kind::GreaterEqual: + case Token::Kind::LessThan: + case Token::Kind::LessEqual: + case Token::Kind::Plus: + case Token::Kind::Minus: + case Token::Kind::Times: + case Token::Kind::Slash: + case Token::Kind::Power: + case Token::Kind::Percent: + case Token::Kind::Dot: { + + parse_operator: + FunctionStorage::Operation operation; + switch (tok.kind) { + case Token::Kind::Id: { + if (tok.text == "and") { + operation = FunctionStorage::Operation::And; + } else if (tok.text == "or") { + operation = FunctionStorage::Operation::Or; + } else if (tok.text == "in") { + operation = FunctionStorage::Operation::In; + } else if (tok.text == "not") { + operation = FunctionStorage::Operation::Not; } else { - // normal literal (json read) - tmpl.bytecodes.emplace_back( - Bytecode::Op::Push, m_tok.text, - m_config.notation == ElementNotation::Pointer ? Bytecode::Flag::ValueLookupPointer : Bytecode::Flag::ValueLookupDot); - get_next_token(); - return true; - } - // json passthrough - case Token::Kind::Number: - case Token::Kind::String: - if (brace_level == 0 && bracket_level == 0) { - json_first = m_tok.text; - goto returnJson; + throw_parser_error("unknown operator in parser."); } - break; - case Token::Kind::Comma: - case Token::Kind::Colon: - if (brace_level == 0 && bracket_level == 0) { - inja_throw("parser_error", "unexpected token '" + m_tok.describe() + "'"); - } - break; - case Token::Kind::LeftBracket: - if (brace_level == 0 && bracket_level == 0) { - json_first = m_tok.text; - } - bracket_level += 1; - break; - case Token::Kind::LeftBrace: - if (brace_level == 0 && bracket_level == 0) { - json_first = m_tok.text; + } break; + case Token::Kind::Equal: { + operation = FunctionStorage::Operation::Equal; + } break; + case Token::Kind::NotEqual: { + operation = FunctionStorage::Operation::NotEqual; + } break; + case Token::Kind::GreaterThan: { + operation = FunctionStorage::Operation::Greater; + } break; + case Token::Kind::GreaterEqual: { + operation = FunctionStorage::Operation::GreaterEqual; + } break; + case Token::Kind::LessThan: { + operation = FunctionStorage::Operation::Less; + } break; + case Token::Kind::LessEqual: { + operation = FunctionStorage::Operation::LessEqual; + } break; + case Token::Kind::Plus: { + operation = FunctionStorage::Operation::Add; + } break; + case Token::Kind::Minus: { + operation = FunctionStorage::Operation::Subtract; + } break; + case Token::Kind::Times: { + operation = FunctionStorage::Operation::Multiplication; + } break; + case Token::Kind::Slash: { + operation = FunctionStorage::Operation::Division; + } break; + case Token::Kind::Power: { + operation = FunctionStorage::Operation::Power; + } break; + case Token::Kind::Percent: { + operation = FunctionStorage::Operation::Modulo; + } break; + case Token::Kind::Dot: { + operation = FunctionStorage::Operation::AtId; + } break; + default: { + throw_parser_error("unknown operator in parser."); + } + } + auto function_node = std::make_shared(operation, tok.text.data() - tmpl.content.c_str()); + + while (!operator_stack.empty() && + ((operator_stack.top()->precedence > function_node->precedence) || + (operator_stack.top()->precedence == function_node->precedence && function_node->associativity == FunctionNode::Associativity::Left)) && + (operator_stack.top()->operation != FunctionStorage::Operation::ParenLeft)) { + add_operator(); + } + + operator_stack.emplace(function_node); + } break; + case Token::Kind::Comma: { + if (current_brace_level == 0 && current_bracket_level == 0) { + if (function_stack.empty()) { + throw_parser_error("unexpected ','"); } - brace_level += 1; - break; - case Token::Kind::RightBracket: - if (bracket_level == 0) { - inja_throw("parser_error", "unexpected ']'"); + + function_stack.top().first->number_args += 1; + } + } break; + case Token::Kind::Colon: { + if (current_brace_level == 0 && current_bracket_level == 0) { + throw_parser_error("unexpected ':'"); + } + } break; + case Token::Kind::LeftParen: { + current_paren_level += 1; + operator_stack.emplace(std::make_shared(FunctionStorage::Operation::ParenLeft, tok.text.data() - tmpl.content.c_str())); + + get_peek_token(); + if (peek_tok.kind == Token::Kind::RightParen) { + if (!function_stack.empty() && function_stack.top().second == current_paren_level - 1) { + function_stack.top().first->number_args = 0; } - --bracket_level; - if (brace_level == 0 && bracket_level == 0) goto returnJson; - break; - case Token::Kind::RightBrace: - if (brace_level == 0) { - inja_throw("parser_error", "unexpected '}'"); + } + } break; + case Token::Kind::RightParen: { + current_paren_level -= 1; + while (!operator_stack.empty() && operator_stack.top()->operation != FunctionStorage::Operation::ParenLeft) { + add_operator(); + } + + if (!operator_stack.empty() && operator_stack.top()->operation == FunctionStorage::Operation::ParenLeft) { + operator_stack.pop(); + } + + if (!function_stack.empty() && function_stack.top().second == current_paren_level) { + auto func = function_stack.top().first; + auto function_data = function_storage.find_function(func->name, func->number_args); + if (function_data.operation == FunctionStorage::Operation::None) { + throw_parser_error("unknown function " + func->name); } - --brace_level; - if (brace_level == 0 && bracket_level == 0) goto returnJson; - break; - default: - if (brace_level != 0) { - inja_throw("parser_error", "unmatched '{'"); + func->operation = function_data.operation; + if (function_data.operation == FunctionStorage::Operation::Callback) { + func->callback = function_data.callback; } - if (bracket_level != 0) { - inja_throw("parser_error", "unmatched '['"); + + if (operator_stack.empty()) { + throw_parser_error("internal error at function " + func->name); } - return false; + + add_operator(); + function_stack.pop(); + } + } + default: + break; } get_next_token(); } - returnJson: - // bridge across all intermediate tokens - nonstd::string_view json_text(json_first.data(), m_tok.text.data() - json_first.data() + m_tok.text.size()); - tmpl.bytecodes.emplace_back(Bytecode::Op::Push, json::parse(json_text), Bytecode::Flag::ValueImmediate); - get_next_token(); + while (!operator_stack.empty()) { + add_operator(); + } + + if (arguments.size() == 1) { + current_expression_list->root = arguments[0]; + arguments = {}; + } else if (arguments.size() > 1) { + throw_parser_error("malformed expression"); + } + return true; } - bool parse_statement(Template& tmpl, nonstd::string_view path) { - if (m_tok.kind != Token::Kind::Id) return false; + bool parse_statement(Template& tmpl, Token::Kind closing, std::string_view path) { + if (tok.kind != Token::Kind::Id) { + return false; + } - if (m_tok.text == static_cast("if")) { + if (tok.text == static_cast("if")) { get_next_token(); - // evaluate expression - if (!parse_expression(tmpl)) return false; - - // start a new if block on if stack - m_if_stack.emplace_back(tmpl.bytecodes.size()); + auto if_statement_node = std::make_shared(current_block, tok.text.data() - tmpl.content.c_str()); + current_block->nodes.emplace_back(if_statement_node); + if_statement_stack.emplace(if_statement_node.get()); + current_block = &if_statement_node->true_statement; + current_expression_list = &if_statement_node->condition; - // conditional jump; destination will be filled in by else or endif - tmpl.bytecodes.emplace_back(Bytecode::Op::ConditionalJump); - } else if (m_tok.text == static_cast("endif")) { - if (m_if_stack.empty()) { - inja_throw("parser_error", "endif without matching if"); + if (!parse_expression(tmpl, closing)) { + return false; } - auto& if_data = m_if_stack.back(); + } else if (tok.text == static_cast("else")) { + if (if_statement_stack.empty()) { + throw_parser_error("else without matching if"); + } + auto& if_statement_data = if_statement_stack.top(); get_next_token(); - // previous conditional jump jumps here - if (if_data.prev_cond_jump != std::numeric_limits::max()) { - tmpl.bytecodes[if_data.prev_cond_jump].args = tmpl.bytecodes.size(); + if_statement_data->has_false_statement = true; + current_block = &if_statement_data->false_statement; + + // Chained else if + if (tok.kind == Token::Kind::Id && tok.text == static_cast("if")) { + get_next_token(); + + auto if_statement_node = std::make_shared(true, current_block, tok.text.data() - tmpl.content.c_str()); + current_block->nodes.emplace_back(if_statement_node); + if_statement_stack.emplace(if_statement_node.get()); + current_block = &if_statement_node->true_statement; + current_expression_list = &if_statement_node->condition; + + if (!parse_expression(tmpl, closing)) { + return false; + } + } + } else if (tok.text == static_cast("endif")) { + if (if_statement_stack.empty()) { + throw_parser_error("endif without matching if"); } - // update all previous unconditional jumps to here - for (unsigned int i: if_data.uncond_jumps) { - tmpl.bytecodes[i].args = tmpl.bytecodes.size(); + // Nested if statements + while (if_statement_stack.top()->is_nested) { + if_statement_stack.pop(); } - // pop if stack - m_if_stack.pop_back(); - } else if (m_tok.text == static_cast("else")) { - if (m_if_stack.empty()) - inja_throw("parser_error", "else without matching if"); - auto& if_data = m_if_stack.back(); + auto& if_statement_data = if_statement_stack.top(); get_next_token(); - // end previous block with unconditional jump to endif; destination will be - // filled in by endif - if_data.uncond_jumps.push_back(tmpl.bytecodes.size()); - tmpl.bytecodes.emplace_back(Bytecode::Op::Jump); - - // previous conditional jump jumps here - tmpl.bytecodes[if_data.prev_cond_jump].args = tmpl.bytecodes.size(); - if_data.prev_cond_jump = std::numeric_limits::max(); + current_block = if_statement_data->parent; + if_statement_stack.pop(); + } else if (tok.text == static_cast("block")) { + get_next_token(); - // chained else if - if (m_tok.kind == Token::Kind::Id && m_tok.text == static_cast("if")) { - get_next_token(); + if (tok.kind != Token::Kind::Id) { + throw_parser_error("expected block name, got '" + tok.describe() + "'"); + } - // evaluate expression - if (!parse_expression(tmpl)) return false; + const std::string block_name = static_cast(tok.text); - // update "previous jump" - if_data.prev_cond_jump = tmpl.bytecodes.size(); + auto block_statement_node = std::make_shared(current_block, block_name, tok.text.data() - tmpl.content.c_str()); + current_block->nodes.emplace_back(block_statement_node); + block_statement_stack.emplace(block_statement_node.get()); + current_block = &block_statement_node->block; + auto success = tmpl.block_storage.emplace(block_name, block_statement_node); + if (!success.second) { + throw_parser_error("block with the name '" + block_name + "' does already exist"); + } - // conditional jump; destination will be filled in by else or endif - tmpl.bytecodes.emplace_back(Bytecode::Op::ConditionalJump); + get_next_token(); + } else if (tok.text == static_cast("endblock")) { + if (block_statement_stack.empty()) { + throw_parser_error("endblock without matching block"); } - } else if (m_tok.text == static_cast("for")) { + + auto& block_statement_data = block_statement_stack.top(); + get_next_token(); + + current_block = block_statement_data->parent; + block_statement_stack.pop(); + } else if (tok.text == static_cast("for")) { get_next_token(); // options: for a in arr; for a, b in obj - if (m_tok.kind != Token::Kind::Id) - inja_throw("parser_error", "expected id, got '" + m_tok.describe() + "'"); - Token value_token = m_tok; + if (tok.kind != Token::Kind::Id) { + throw_parser_error("expected id, got '" + tok.describe() + "'"); + } + + Token value_token = tok; get_next_token(); - Token key_token; - if (m_tok.kind == Token::Kind::Comma) { + // Object type + std::shared_ptr for_statement_node; + if (tok.kind == Token::Kind::Comma) { get_next_token(); - if (m_tok.kind != Token::Kind::Id) - inja_throw("parser_error", "expected id, got '" + m_tok.describe() + "'"); - key_token = std::move(value_token); - value_token = m_tok; + if (tok.kind != Token::Kind::Id) { + throw_parser_error("expected id, got '" + tok.describe() + "'"); + } + + Token key_token = std::move(value_token); + value_token = tok; get_next_token(); - } - if (m_tok.kind != Token::Kind::Id || m_tok.text != static_cast("in")) - inja_throw("parser_error", - "expected 'in', got '" + m_tok.describe() + "'"); - get_next_token(); + for_statement_node = std::make_shared(static_cast(key_token.text), static_cast(value_token.text), + current_block, tok.text.data() - tmpl.content.c_str()); - if (!parse_expression(tmpl)) return false; + // Array type + } else { + for_statement_node = + std::make_shared(static_cast(value_token.text), current_block, tok.text.data() - tmpl.content.c_str()); + } - m_loop_stack.push_back(tmpl.bytecodes.size()); + current_block->nodes.emplace_back(for_statement_node); + for_statement_stack.emplace(for_statement_node.get()); + current_block = &for_statement_node->body; + current_expression_list = &for_statement_node->condition; - tmpl.bytecodes.emplace_back(Bytecode::Op::StartLoop); - if (!key_token.text.empty()) { - tmpl.bytecodes.back().value = key_token.text; + if (tok.kind != Token::Kind::Id || tok.text != static_cast("in")) { + throw_parser_error("expected 'in', got '" + tok.describe() + "'"); } - tmpl.bytecodes.back().str = static_cast(value_token.text); - } else if (m_tok.text == static_cast("endfor")) { get_next_token(); - if (m_loop_stack.empty()) { - inja_throw("parser_error", "endfor without matching for"); + + if (!parse_expression(tmpl, closing)) { + return false; + } + } else if (tok.text == static_cast("endfor")) { + if (for_statement_stack.empty()) { + throw_parser_error("endfor without matching for"); } - // update loop with EndLoop index (for empty case) - tmpl.bytecodes[m_loop_stack.back()].args = tmpl.bytecodes.size(); + auto& for_statement_data = for_statement_stack.top(); + get_next_token(); - tmpl.bytecodes.emplace_back(Bytecode::Op::EndLoop); - tmpl.bytecodes.back().args = m_loop_stack.back() + 1; // loop body - m_loop_stack.pop_back(); - } else if (m_tok.text == static_cast("include")) { + current_block = for_statement_data->parent; + for_statement_stack.pop(); + } else if (tok.text == static_cast("include")) { get_next_token(); - if (m_tok.kind != Token::Kind::String) { - inja_throw("parser_error", "expected string, got '" + m_tok.describe() + "'"); - } + std::string template_name = parse_filename(tok); + add_to_template_storage(path, template_name); - // build the relative path - json json_name = json::parse(m_tok.text); - std::string pathname = static_cast(path); - pathname += json_name.get_ref(); - if (pathname.compare(0, 2, "./") == 0) { - pathname.erase(0, 2); - } - // sys::path::remove_dots(pathname, true, sys::path::Style::posix); + current_block->nodes.emplace_back(std::make_shared(template_name, tok.text.data() - tmpl.content.c_str())); - if (m_included_templates.find(pathname) == m_included_templates.end()) { - Template include_template = parse_template(pathname); - m_included_templates.emplace(pathname, include_template); - } + get_next_token(); + } else if (tok.text == static_cast("extends")) { + get_next_token(); + + std::string template_name = parse_filename(tok); + add_to_template_storage(path, template_name); - // generate a reference bytecode - tmpl.bytecodes.emplace_back(Bytecode::Op::Include, json(pathname), Bytecode::Flag::ValueImmediate); + current_block->nodes.emplace_back(std::make_shared(template_name, tok.text.data() - tmpl.content.c_str())); get_next_token(); - } else { - return false; - } - return true; - } + } else if (tok.text == static_cast("set")) { + get_next_token(); - void append_function(Template& tmpl, Bytecode::Op op, unsigned int num_args) { - // we can merge with back-to-back push - if (!tmpl.bytecodes.empty()) { - Bytecode& last = tmpl.bytecodes.back(); - if (last.op == Bytecode::Op::Push) { - last.op = op; - last.args = num_args; - return; + if (tok.kind != Token::Kind::Id) { + throw_parser_error("expected variable name, got '" + tok.describe() + "'"); } - } - // otherwise just add it to the end - tmpl.bytecodes.emplace_back(op, num_args); - } + std::string key = static_cast(tok.text); + get_next_token(); - void append_callback(Template& tmpl, nonstd::string_view name, unsigned int num_args) { - // we can merge with back-to-back push value (not lookup) - if (!tmpl.bytecodes.empty()) { - Bytecode& last = tmpl.bytecodes.back(); - if (last.op == Bytecode::Op::Push && - (last.flags & Bytecode::Flag::ValueMask) == Bytecode::Flag::ValueImmediate) { - last.op = Bytecode::Op::Callback; - last.args = num_args; - last.str = static_cast(name); - return; + auto set_statement_node = std::make_shared(key, tok.text.data() - tmpl.content.c_str()); + current_block->nodes.emplace_back(set_statement_node); + current_expression_list = &set_statement_node->expression; + + if (tok.text != static_cast("=")) { + throw_parser_error("expected '=', got '" + tok.describe() + "'"); } - } + get_next_token(); - // otherwise just add it to the end - tmpl.bytecodes.emplace_back(Bytecode::Op::Callback, num_args); - tmpl.bytecodes.back().str = static_cast(name); + if (!parse_expression(tmpl, closing)) { + return false; + } + } else { + return false; + } + return true; } - void parse_into(Template& tmpl, nonstd::string_view path) { - m_lexer.start(tmpl.content); + void parse_into(Template& tmpl, std::string_view path) { + lexer.start(tmpl.content); + current_block = &tmpl.root; for (;;) { get_next_token(); - switch (m_tok.kind) { - case Token::Kind::Eof: - if (!m_if_stack.empty()) inja_throw("parser_error", "unmatched if"); - if (!m_loop_stack.empty()) inja_throw("parser_error", "unmatched for"); - return; - case Token::Kind::Text: - tmpl.bytecodes.emplace_back(Bytecode::Op::PrintText, m_tok.text, 0u); - break; - case Token::Kind::StatementOpen: - get_next_token(); - if (!parse_statement(tmpl, path)) { - inja_throw("parser_error", "expected statement, got '" + m_tok.describe() + "'"); - } - if (m_tok.kind != Token::Kind::StatementClose) { - inja_throw("parser_error", "expected statement close, got '" + m_tok.describe() + "'"); - } - break; - case Token::Kind::LineStatementOpen: - get_next_token(); - parse_statement(tmpl, path); - if (m_tok.kind != Token::Kind::LineStatementClose && - m_tok.kind != Token::Kind::Eof) { - inja_throw("parser_error", "expected line statement close, got '" + m_tok.describe() + "'"); - } - break; - case Token::Kind::ExpressionOpen: - get_next_token(); - if (!parse_expression(tmpl)) { - inja_throw("parser_error", "expected expression, got '" + m_tok.describe() + "'"); - } - append_function(tmpl, Bytecode::Op::PrintValue, 1); - if (m_tok.kind != Token::Kind::ExpressionClose) { - inja_throw("parser_error", "expected expression close, got '" + m_tok.describe() + "'"); - } - break; - case Token::Kind::CommentOpen: - get_next_token(); - if (m_tok.kind != Token::Kind::CommentClose) { - inja_throw("parser_error", "expected comment close, got '" + m_tok.describe() + "'"); - } - break; - default: - inja_throw("parser_error", "unexpected token '" + m_tok.describe() + "'"); - break; + switch (tok.kind) { + case Token::Kind::Eof: { + if (!if_statement_stack.empty()) { + throw_parser_error("unmatched if"); + } + if (!for_statement_stack.empty()) { + throw_parser_error("unmatched for"); + } + } + return; + case Token::Kind::Text: { + current_block->nodes.emplace_back(std::make_shared(tok.text.data() - tmpl.content.c_str(), tok.text.size())); + } break; + case Token::Kind::StatementOpen: { + get_next_token(); + if (!parse_statement(tmpl, Token::Kind::StatementClose, path)) { + throw_parser_error("expected statement, got '" + tok.describe() + "'"); + } + if (tok.kind != Token::Kind::StatementClose) { + throw_parser_error("expected statement close, got '" + tok.describe() + "'"); + } + } break; + case Token::Kind::LineStatementOpen: { + get_next_token(); + if (!parse_statement(tmpl, Token::Kind::LineStatementClose, path)) { + throw_parser_error("expected statement, got '" + tok.describe() + "'"); + } + if (tok.kind != Token::Kind::LineStatementClose && tok.kind != Token::Kind::Eof) { + throw_parser_error("expected line statement close, got '" + tok.describe() + "'"); + } + } break; + case Token::Kind::ExpressionOpen: { + get_next_token(); + + auto expression_list_node = std::make_shared(tok.text.data() - tmpl.content.c_str()); + current_block->nodes.emplace_back(expression_list_node); + current_expression_list = expression_list_node.get(); + + if (!parse_expression(tmpl, Token::Kind::ExpressionClose)) { + throw_parser_error("expected expression, got '" + tok.describe() + "'"); + } + + if (tok.kind != Token::Kind::ExpressionClose) { + throw_parser_error("expected expression close, got '" + tok.describe() + "'"); + } + } break; + case Token::Kind::CommentOpen: { + get_next_token(); + if (tok.kind != Token::Kind::CommentClose) { + throw_parser_error("expected comment close, got '" + tok.describe() + "'"); + } + } break; + default: { + throw_parser_error("unexpected token '" + tok.describe() + "'"); + } break; } } } - Template parse(nonstd::string_view input, nonstd::string_view path) { - Template result; - result.content = static_cast(input); +public: + explicit Parser(const ParserConfig& parser_config, const LexerConfig& lexer_config, TemplateStorage& template_storage, + const FunctionStorage& function_storage) + : config(parser_config), lexer(lexer_config), template_storage(template_storage), function_storage(function_storage) {} + + Template parse(std::string_view input, std::string_view path) { + auto result = Template(static_cast(input)); parse_into(result, path); return result; } - Template parse(nonstd::string_view input) { + Template parse(std::string_view input) { return parse(input, "./"); } - Template parse_template(nonstd::string_view filename) { - Template result; - result.content = load_file(filename); + void parse_into_template(Template& tmpl, std::string_view filename) { + std::string_view path = filename.substr(0, filename.find_last_of("/\\") + 1); - nonstd::string_view path = filename.substr(0, filename.find_last_of("/\\") + 1); - // StringRef path = sys::path::parent_path(filename); - Parser(m_config, m_lexer.get_config(), m_included_templates).parse_into(result, path); - return result; + // StringRef path = sys::path::parent_path(filename); + auto sub_parser = Parser(config, lexer.get_config(), template_storage, function_storage); + sub_parser.parse_into(tmpl, path); } - std::string load_file(nonstd::string_view filename) { - std::ifstream file = open_file_or_throw(static_cast(filename)); + std::string load_file(const std::string& filename) { + std::ifstream file; + file.open(filename); + if (file.fail()) { + INJA_THROW(FileError("failed accessing file at '" + filename + "'")); + } std::string text((std::istreambuf_iterator(file)), std::istreambuf_iterator()); return text; } +}; - private: - const ParserConfig& m_config; - Lexer m_lexer; - Token m_tok; - Token m_peek_tok; - bool m_have_peek_tok {false}; - TemplateStorage& m_included_templates; - const ParserStatic& m_static; - - struct IfData { - unsigned int prev_cond_jump; - std::vector uncond_jumps; - - explicit IfData(unsigned int condJump): prev_cond_jump(condJump) {} - }; +} // namespace inja - std::vector m_if_stack; - std::vector m_loop_stack; +#endif // INCLUDE_INJA_PARSER_HPP_ - void get_next_token() { - if (m_have_peek_tok) { - m_tok = m_peek_tok; - m_have_peek_tok = false; - } else { - m_tok = m_lexer.scan(); - } - } +// #include "renderer.hpp" +#ifndef INCLUDE_INJA_RENDERER_HPP_ +#define INCLUDE_INJA_RENDERER_HPP_ - void get_peek_token() { - if (!m_have_peek_tok) { - m_peek_tok = m_lexer.scan(); - m_have_peek_tok = true; - } - } -}; +#include +#include +#include +#include +#include -} // namespace inja +// #include "config.hpp" -#endif // PANTOR_INJA_PARSER_HPP +// #include "exceptions.hpp" -// #include "polyfill.hpp" -#ifndef PANTOR_INJA_POLYFILL_HPP -#define PANTOR_INJA_POLYFILL_HPP +// #include "node.hpp" +// #include "template.hpp" -#if __cplusplus < 201402L +// #include "utils.hpp" -#include -#include -#include -#include +namespace inja { -namespace stdinja { - template struct _Unique_if { - typedef std::unique_ptr _Single_object; - }; +/*! + * \brief Class for rendering a Template with data. + */ +class Renderer : public NodeVisitor { + using Op = FunctionStorage::Operation; - template struct _Unique_if { - typedef std::unique_ptr _Unknown_bound; - }; + const RenderConfig config; + const TemplateStorage& template_storage; + const FunctionStorage& function_storage; - template struct _Unique_if { - typedef void _Known_bound; - }; + const Template* current_template; + size_t current_level {0}; + std::vector template_stack; + std::vector block_statement_stack; - template - typename _Unique_if::_Single_object - make_unique(Args&&... args) { - return std::unique_ptr(new T(std::forward(args)...)); - } + const json* data_input; + std::ostream* output_stream; - template - typename _Unique_if::_Unknown_bound - make_unique(size_t n) { - typedef typename std::remove_extent::type U; - return std::unique_ptr(new U[n]()); - } + json additional_data; + json* current_loop_data = &additional_data["loop"]; - template - typename _Unique_if::_Known_bound - make_unique(Args&&...) = delete; -} + std::vector> data_tmp_stack; + std::stack data_eval_stack; + std::stack not_found_stack; -#else + bool break_rendering {false}; -namespace stdinja = std; + static bool truthy(const json* data) { + if (data->is_boolean()) { + return data->get(); + } else if (data->is_number()) { + return (*data != 0); + } else if (data->is_null()) { + return false; + } + return !data->empty(); + } -#endif // memory */ + void print_data(const std::shared_ptr value) { + if (value->is_string()) { + *output_stream << value->get_ref(); + } else if (value->is_number_integer()) { + *output_stream << value->get(); + } else if (value->is_null()) { + } else { + *output_stream << value->dump(); + } + } + const std::shared_ptr eval_expression_list(const ExpressionListNode& expression_list) { + if (!expression_list.root) { + throw_renderer_error("empty expression", expression_list); + } -#endif // PANTOR_INJA_POLYFILL_HPP + expression_list.root->accept(*this); -// #include "renderer.hpp" -#ifndef PANTOR_INJA_RENDERER_HPP -#define PANTOR_INJA_RENDERER_HPP + if (data_eval_stack.empty()) { + throw_renderer_error("empty expression", expression_list); + } else if (data_eval_stack.size() != 1) { + throw_renderer_error("malformed expression", expression_list); + } -#include -#include -#include -#include -#include + const auto result = data_eval_stack.top(); + data_eval_stack.pop(); -#include + if (!result) { + if (not_found_stack.empty()) { + throw_renderer_error("expression could not be evaluated", expression_list); + } -// #include "bytecode.hpp" + auto node = not_found_stack.top(); + not_found_stack.pop(); -// #include "template.hpp" + throw_renderer_error("variable '" + static_cast(node->name) + "' not found", *node); + } + return std::make_shared(*result); + } -// #include "utils.hpp" + void throw_renderer_error(const std::string& message, const AstNode& node) { + SourceLocation loc = get_source_location(current_template->content, node.pos); + INJA_THROW(RenderError(message, loc)); + } + void make_result(const json&& result) { + auto result_ptr = std::make_shared(result); + data_tmp_stack.push_back(result_ptr); + data_eval_stack.push(result_ptr.get()); + } + template std::array get_arguments(const FunctionNode& node) { + if (node.arguments.size() < N_start + N) { + throw_renderer_error("function needs " + std::to_string(N_start + N) + " variables, but has only found " + std::to_string(node.arguments.size()), node); + } -namespace inja { + for (size_t i = N_start; i < N_start + N; i += 1) { + node.arguments[i]->accept(*this); + } -inline nonstd::string_view convert_dot_to_json_pointer(nonstd::string_view dot, std::string& out) { - out.clear(); - do { - nonstd::string_view part; - std::tie(part, dot) = string_view::split(dot, '.'); - out.push_back('/'); - out.append(part.begin(), part.end()); - } while (!dot.empty()); - return nonstd::string_view(out.data(), out.size()); -} + if (data_eval_stack.size() < N) { + throw_renderer_error("function needs " + std::to_string(N) + " variables, but has only found " + std::to_string(data_eval_stack.size()), node); + } -/*! - * \brief Class for rendering a Template with data. - */ -class Renderer { - std::vector& get_args(const Bytecode& bc) { - m_tmp_args.clear(); + std::array result; + for (size_t i = 0; i < N; i += 1) { + result[N - i - 1] = data_eval_stack.top(); + data_eval_stack.pop(); - bool has_imm = ((bc.flags & Bytecode::Flag::ValueMask) != Bytecode::Flag::ValuePop); + if (!result[N - i - 1]) { + const auto data_node = not_found_stack.top(); + not_found_stack.pop(); - // get args from stack - unsigned int pop_args = bc.args; - if (has_imm) { - pop_args -= 1; + if (throw_not_found) { + throw_renderer_error("variable '" + static_cast(data_node->name) + "' not found", *data_node); + } + } } + return result; + } - for (auto i = std::prev(m_stack.end(), pop_args); i != m_stack.end(); i++) { - m_tmp_args.push_back(&(*i)); + template Arguments get_argument_vector(const FunctionNode& node) { + const size_t N = node.arguments.size(); + for (auto a : node.arguments) { + a->accept(*this); } - // get immediate arg - if (has_imm) { - m_tmp_args.push_back(get_imm(bc)); + if (data_eval_stack.size() < N) { + throw_renderer_error("function needs " + std::to_string(N) + " variables, but has only found " + std::to_string(data_eval_stack.size()), node); } - return m_tmp_args; - } + Arguments result {N}; + for (size_t i = 0; i < N; i += 1) { + result[N - i - 1] = data_eval_stack.top(); + data_eval_stack.pop(); - void pop_args(const Bytecode& bc) { - unsigned int popArgs = bc.args; - if ((bc.flags & Bytecode::Flag::ValueMask) != Bytecode::Flag::ValuePop) { - popArgs -= 1; - } - for (unsigned int i = 0; i < popArgs; ++i) { - m_stack.pop_back(); + if (!result[N - i - 1]) { + const auto data_node = not_found_stack.top(); + not_found_stack.pop(); + + if (throw_not_found) { + throw_renderer_error("variable '" + static_cast(data_node->name) + "' not found", *data_node); + } + } } + return result; } - const json* get_imm(const Bytecode& bc) { - std::string ptr_buffer; - nonstd::string_view ptr; - switch (bc.flags & Bytecode::Flag::ValueMask) { - case Bytecode::Flag::ValuePop: - return nullptr; - case Bytecode::Flag::ValueImmediate: - return &bc.value; - case Bytecode::Flag::ValueLookupDot: - ptr = convert_dot_to_json_pointer(bc.str, ptr_buffer); - break; - case Bytecode::Flag::ValueLookupPointer: - ptr_buffer += '/'; - ptr_buffer += bc.str; - ptr = ptr_buffer; + void visit(const BlockNode& node) { + for (auto& n : node.nodes) { + n->accept(*this); + + if (break_rendering) { break; - } - try { - return &m_data->at(json::json_pointer(ptr.data())); - } catch (std::exception&) { - // try to evaluate as a no-argument callback - if (auto callback = m_callbacks.find_callback(bc.str, 0)) { - std::vector arguments {}; - m_tmp_val = callback(arguments); - return &m_tmp_val; } - inja_throw("render_error", "variable '" + static_cast(bc.str) + "' not found"); - return nullptr; } } - bool truthy(const json& var) const { - if (var.empty()) { - return false; - } else if (var.is_number()) { - return (var != 0); - } else if (var.is_string()) { - return !var.empty(); - } - - try { - return var.get(); - } catch (json::type_error& e) { - inja_throw("json_error", e.what()); - throw; - } + void visit(const TextNode& node) { + output_stream->write(current_template->content.c_str() + node.pos, node.length); } - void update_loop_data() { - LoopLevel& level = m_loop_stack.back(); + void visit(const ExpressionNode&) {} - if (level.loop_type == LoopLevel::Type::Array) { - level.data[static_cast(level.value_name)] = level.values.at(level.index); // *level.it; - auto& loopData = level.data["loop"]; - loopData["index"] = level.index; - loopData["index1"] = level.index + 1; - loopData["is_first"] = (level.index == 0); - loopData["is_last"] = (level.index == level.size - 1); + void visit(const LiteralNode& node) { + data_eval_stack.push(&node.value); + } + + void visit(const DataNode& node) { + if (additional_data.contains(node.ptr)) { + data_eval_stack.push(&(additional_data[node.ptr])); + } else if (data_input->contains(node.ptr)) { + data_eval_stack.push(&(*data_input)[node.ptr]); } else { - level.data[static_cast(level.key_name)] = level.map_it->first; - level.data[static_cast(level.value_name)] = *level.map_it->second; + // Try to evaluate as a no-argument callback + const auto function_data = function_storage.find_function(node.name, 0); + if (function_data.operation == FunctionStorage::Operation::Callback) { + Arguments empty_args {}; + const auto value = std::make_shared(function_data.callback(empty_args)); + data_tmp_stack.push_back(value); + data_eval_stack.push(value.get()); + } else { + data_eval_stack.push(nullptr); + not_found_stack.emplace(&node); + } } } - const TemplateStorage& m_included_templates; - const FunctionStorage& m_callbacks; - - std::vector m_stack; + void visit(const FunctionNode& node) { + switch (node.operation) { + case Op::Not: { + const auto args = get_arguments<1>(node); + make_result(!truthy(args[0])); + } break; + case Op::And: { + make_result(truthy(get_arguments<1, 0>(node)[0]) && truthy(get_arguments<1, 1>(node)[0])); + } break; + case Op::Or: { + make_result(truthy(get_arguments<1, 0>(node)[0]) || truthy(get_arguments<1, 1>(node)[0])); + } break; + case Op::In: { + const auto args = get_arguments<2>(node); + make_result(std::find(args[1]->begin(), args[1]->end(), *args[0]) != args[1]->end()); + } break; + case Op::Equal: { + const auto args = get_arguments<2>(node); + make_result(*args[0] == *args[1]); + } break; + case Op::NotEqual: { + const auto args = get_arguments<2>(node); + make_result(*args[0] != *args[1]); + } break; + case Op::Greater: { + const auto args = get_arguments<2>(node); + make_result(*args[0] > *args[1]); + } break; + case Op::GreaterEqual: { + const auto args = get_arguments<2>(node); + make_result(*args[0] >= *args[1]); + } break; + case Op::Less: { + const auto args = get_arguments<2>(node); + make_result(*args[0] < *args[1]); + } break; + case Op::LessEqual: { + const auto args = get_arguments<2>(node); + make_result(*args[0] <= *args[1]); + } break; + case Op::Add: { + const auto args = get_arguments<2>(node); + if (args[0]->is_string() && args[1]->is_string()) { + make_result(args[0]->get_ref() + args[1]->get_ref()); + } else if (args[0]->is_number_integer() && args[1]->is_number_integer()) { + make_result(args[0]->get() + args[1]->get()); + } else { + make_result(args[0]->get() + args[1]->get()); + } + } break; + case Op::Subtract: { + const auto args = get_arguments<2>(node); + if (args[0]->is_number_integer() && args[1]->is_number_integer()) { + make_result(args[0]->get() - args[1]->get()); + } else { + make_result(args[0]->get() - args[1]->get()); + } + } break; + case Op::Multiplication: { + const auto args = get_arguments<2>(node); + if (args[0]->is_number_integer() && args[1]->is_number_integer()) { + make_result(args[0]->get() * args[1]->get()); + } else { + make_result(args[0]->get() * args[1]->get()); + } + } break; + case Op::Division: { + const auto args = get_arguments<2>(node); + if (args[1]->get() == 0) { + throw_renderer_error("division by zero", node); + } + make_result(args[0]->get() / args[1]->get()); + } break; + case Op::Power: { + const auto args = get_arguments<2>(node); + if (args[0]->is_number_integer() && args[1]->get() >= 0) { + int result = static_cast(std::pow(args[0]->get(), args[1]->get())); + make_result(result); + } else { + double result = std::pow(args[0]->get(), args[1]->get()); + make_result(result); + } + } break; + case Op::Modulo: { + const auto args = get_arguments<2>(node); + make_result(args[0]->get() % args[1]->get()); + } break; + case Op::AtId: { + const auto container = get_arguments<1, 0, false>(node)[0]; + node.arguments[1]->accept(*this); + if (not_found_stack.empty()) { + throw_renderer_error("could not find element with given name", node); + } + const auto id_node = not_found_stack.top(); + not_found_stack.pop(); + data_eval_stack.pop(); + data_eval_stack.push(&container->at(id_node->name)); + } break; + case Op::At: { + const auto args = get_arguments<2>(node); + if (args[0]->is_object()) { + data_eval_stack.push(&args[0]->at(args[1]->get())); + } else { + data_eval_stack.push(&args[0]->at(args[1]->get())); + } + } break; + case Op::Default: { + const auto test_arg = get_arguments<1, 0, false>(node)[0]; + data_eval_stack.push(test_arg ? test_arg : get_arguments<1, 1>(node)[0]); + } break; + case Op::DivisibleBy: { + const auto args = get_arguments<2>(node); + const int divisor = args[1]->get(); + make_result((divisor != 0) && (args[0]->get() % divisor == 0)); + } break; + case Op::Even: { + make_result(get_arguments<1>(node)[0]->get() % 2 == 0); + } break; + case Op::Exists: { + auto&& name = get_arguments<1>(node)[0]->get_ref(); + make_result(data_input->contains(json::json_pointer(DataNode::convert_dot_to_ptr(name)))); + } break; + case Op::ExistsInObject: { + const auto args = get_arguments<2>(node); + auto&& name = args[1]->get_ref(); + make_result(args[0]->find(name) != args[0]->end()); + } break; + case Op::First: { + const auto result = &get_arguments<1>(node)[0]->front(); + data_eval_stack.push(result); + } break; + case Op::Float: { + make_result(std::stod(get_arguments<1>(node)[0]->get_ref())); + } break; + case Op::Int: { + make_result(std::stoi(get_arguments<1>(node)[0]->get_ref())); + } break; + case Op::Last: { + const auto result = &get_arguments<1>(node)[0]->back(); + data_eval_stack.push(result); + } break; + case Op::Length: { + const auto val = get_arguments<1>(node)[0]; + if (val->is_string()) { + make_result(val->get_ref().length()); + } else { + make_result(val->size()); + } + } break; + case Op::Lower: { + std::string result = get_arguments<1>(node)[0]->get(); + std::transform(result.begin(), result.end(), result.begin(), ::tolower); + make_result(std::move(result)); + } break; + case Op::Max: { + const auto args = get_arguments<1>(node); + const auto result = std::max_element(args[0]->begin(), args[0]->end()); + data_eval_stack.push(&(*result)); + } break; + case Op::Min: { + const auto args = get_arguments<1>(node); + const auto result = std::min_element(args[0]->begin(), args[0]->end()); + data_eval_stack.push(&(*result)); + } break; + case Op::Odd: { + make_result(get_arguments<1>(node)[0]->get() % 2 != 0); + } break; + case Op::Range: { + std::vector result(get_arguments<1>(node)[0]->get()); + std::iota(result.begin(), result.end(), 0); + make_result(std::move(result)); + } break; + case Op::Round: { + const auto args = get_arguments<2>(node); + const int precision = args[1]->get(); + const double result = std::round(args[0]->get() * std::pow(10.0, precision)) / std::pow(10.0, precision); + if (precision == 0) { + make_result(int(result)); + } else { + make_result(result); + } + } break; + case Op::Sort: { + auto result_ptr = std::make_shared(get_arguments<1>(node)[0]->get>()); + std::sort(result_ptr->begin(), result_ptr->end()); + data_tmp_stack.push_back(result_ptr); + data_eval_stack.push(result_ptr.get()); + } break; + case Op::Upper: { + std::string result = get_arguments<1>(node)[0]->get(); + std::transform(result.begin(), result.end(), result.begin(), ::toupper); + make_result(std::move(result)); + } break; + case Op::IsBoolean: { + make_result(get_arguments<1>(node)[0]->is_boolean()); + } break; + case Op::IsNumber: { + make_result(get_arguments<1>(node)[0]->is_number()); + } break; + case Op::IsInteger: { + make_result(get_arguments<1>(node)[0]->is_number_integer()); + } break; + case Op::IsFloat: { + make_result(get_arguments<1>(node)[0]->is_number_float()); + } break; + case Op::IsObject: { + make_result(get_arguments<1>(node)[0]->is_object()); + } break; + case Op::IsArray: { + make_result(get_arguments<1>(node)[0]->is_array()); + } break; + case Op::IsString: { + make_result(get_arguments<1>(node)[0]->is_string()); + } break; + case Op::Callback: { + auto args = get_argument_vector(node); + make_result(node.callback(args)); + } break; + case Op::Super: { + const auto args = get_argument_vector(node); + const size_t old_level = current_level; + const size_t level_diff = (args.size() == 1) ? args[0]->get() : 1; + const size_t level = current_level + level_diff; + + if (block_statement_stack.empty()) { + throw_renderer_error("super() call is not within a block", node); + } + if (level < 1 || level > template_stack.size() - 1) { + throw_renderer_error("level of super() call does not match parent templates (between 1 and " + std::to_string(template_stack.size() - 1) + ")", node); + } - struct LoopLevel { - enum class Type { Map, Array }; + const auto current_block_statement = block_statement_stack.back(); + const Template* new_template = template_stack.at(level); + const Template* old_template = current_template; + const auto block_it = new_template->block_storage.find(current_block_statement->name); + if (block_it != new_template->block_storage.end()) { + current_template = new_template; + current_level = level; + block_it->second->block.accept(*this); + current_level = old_level; + current_template = old_template; + } else { + throw_renderer_error("could not find block with name '" + current_block_statement->name + "'", node); + } + make_result(nullptr); + } break; + case Op::Join: { + const auto args = get_arguments<2>(node); + const auto separator = args[1]->get(); + std::ostringstream os; + std::string sep; + for (const auto& value : *args[0]) { + os << sep; + if (value.is_string()) { + os << value.get(); // otherwise the value is surrounded with "" + } else { + os << value.dump(); + } + sep = separator; + } + make_result(os.str()); + } break; + case Op::ParenLeft: + case Op::ParenRight: + case Op::None: + break; + } + } - Type loop_type; - nonstd::string_view key_name; // variable name for keys - nonstd::string_view value_name; // variable name for values - json data; // data with loop info added + void visit(const ExpressionListNode& node) { + print_data(eval_expression_list(node)); + } - json values; // values to iterate over + void visit(const StatementNode&) {} - // loop over list - size_t index; // current list index - size_t size; // length of list + void visit(const ForStatementNode&) {} - // loop over map - using KeyValue = std::pair; - using MapValues = std::vector; - MapValues map_values; // values to iterate over - MapValues::iterator map_it; // iterator over values + void visit(const ForArrayStatementNode& node) { + const auto result = eval_expression_list(node.condition); + if (!result->is_array()) { + throw_renderer_error("object must be an array", node); + } - }; + if (!current_loop_data->empty()) { + auto tmp = *current_loop_data; // Because of clang-3 + (*current_loop_data)["parent"] = std::move(tmp); + } - std::vector m_loop_stack; - const json* m_data; + size_t index = 0; + (*current_loop_data)["is_first"] = true; + (*current_loop_data)["is_last"] = (result->size() <= 1); + for (auto it = result->begin(); it != result->end(); ++it) { + additional_data[static_cast(node.value)] = *it; - std::vector m_tmp_args; - json m_tmp_val; + (*current_loop_data)["index"] = index; + (*current_loop_data)["index1"] = index + 1; + if (index == 1) { + (*current_loop_data)["is_first"] = false; + } + if (index == result->size() - 1) { + (*current_loop_data)["is_last"] = true; + } + node.body.accept(*this); + ++index; + } - public: - Renderer(const TemplateStorage& included_templates, const FunctionStorage& callbacks): m_included_templates(included_templates), m_callbacks(callbacks) { - m_stack.reserve(16); - m_tmp_args.reserve(4); - m_loop_stack.reserve(16); + additional_data[static_cast(node.value)].clear(); + if (!(*current_loop_data)["parent"].empty()) { + const auto tmp = (*current_loop_data)["parent"]; + *current_loop_data = std::move(tmp); + } else { + current_loop_data = &additional_data["loop"]; + } } - void render_to(std::ostream& os, const Template& tmpl, const json& data) { - m_data = &data; + void visit(const ForObjectStatementNode& node) { + const auto result = eval_expression_list(node.condition); + if (!result->is_object()) { + throw_renderer_error("object must be an object", node); + } - for (size_t i = 0; i < tmpl.bytecodes.size(); ++i) { - const auto& bc = tmpl.bytecodes[i]; + if (!current_loop_data->empty()) { + (*current_loop_data)["parent"] = std::move(*current_loop_data); + } - switch (bc.op) { - case Bytecode::Op::Nop: { - break; - } - case Bytecode::Op::PrintText: { - os << bc.str; - break; - } - case Bytecode::Op::PrintValue: { - const json& val = *get_args(bc)[0]; - if (val.is_string()) { - os << val.get_ref(); - } else { - os << val.dump(); - } - pop_args(bc); - break; - } - case Bytecode::Op::Push: { - m_stack.emplace_back(*get_imm(bc)); - break; - } - case Bytecode::Op::Upper: { - auto result = get_args(bc)[0]->get(); - std::transform(result.begin(), result.end(), result.begin(), ::toupper); - pop_args(bc); - m_stack.emplace_back(std::move(result)); - break; - } - case Bytecode::Op::Lower: { - auto result = get_args(bc)[0]->get(); - std::transform(result.begin(), result.end(), result.begin(), ::tolower); - pop_args(bc); - m_stack.emplace_back(std::move(result)); - break; - } - case Bytecode::Op::Range: { - int number = get_args(bc)[0]->get(); - std::vector result(number); - std::iota(std::begin(result), std::end(result), 0); - pop_args(bc); - m_stack.emplace_back(std::move(result)); - break; - } - case Bytecode::Op::Length: { - const json& val = *get_args(bc)[0]; + size_t index = 0; + (*current_loop_data)["is_first"] = true; + (*current_loop_data)["is_last"] = (result->size() <= 1); + for (auto it = result->begin(); it != result->end(); ++it) { + additional_data[static_cast(node.key)] = it.key(); + additional_data[static_cast(node.value)] = it.value(); - int result; - if (val.is_string()) { - result = val.get_ref().length(); - } else { - result = val.size(); - } + (*current_loop_data)["index"] = index; + (*current_loop_data)["index1"] = index + 1; + if (index == 1) { + (*current_loop_data)["is_first"] = false; + } + if (index == result->size() - 1) { + (*current_loop_data)["is_last"] = true; + } - pop_args(bc); - m_stack.emplace_back(result); - break; - } - case Bytecode::Op::Sort: { - auto result = get_args(bc)[0]->get>(); - std::sort(result.begin(), result.end()); - pop_args(bc); - m_stack.emplace_back(std::move(result)); - break; - } - case Bytecode::Op::At: { - auto args = get_args(bc); - auto result = args[0]->at(args[1]->get()); - pop_args(bc); - m_stack.emplace_back(result); - break; - } - case Bytecode::Op::First: { - auto result = get_args(bc)[0]->front(); - pop_args(bc); - m_stack.emplace_back(result); - break; - } - case Bytecode::Op::Last: { - auto result = get_args(bc)[0]->back(); - pop_args(bc); - m_stack.emplace_back(result); - break; - } - case Bytecode::Op::Round: { - auto args = get_args(bc); - double number = args[0]->get(); - int precision = args[1]->get(); - pop_args(bc); - m_stack.emplace_back(std::round(number * std::pow(10.0, precision)) / std::pow(10.0, precision)); - break; - } - case Bytecode::Op::DivisibleBy: { - auto args = get_args(bc); - int number = args[0]->get(); - int divisor = args[1]->get(); - pop_args(bc); - m_stack.emplace_back((divisor != 0) && (number % divisor == 0)); - break; - } - case Bytecode::Op::Odd: { - int number = get_args(bc)[0]->get(); - pop_args(bc); - m_stack.emplace_back(number % 2 != 0); - break; - } - case Bytecode::Op::Even: { - int number = get_args(bc)[0]->get(); - pop_args(bc); - m_stack.emplace_back(number % 2 == 0); - break; - } - case Bytecode::Op::Max: { - auto args = get_args(bc); - auto result = *std::max_element(args[0]->begin(), args[0]->end()); - pop_args(bc); - m_stack.emplace_back(std::move(result)); - break; - } - case Bytecode::Op::Min: { - auto args = get_args(bc); - auto result = *std::min_element(args[0]->begin(), args[0]->end()); - pop_args(bc); - m_stack.emplace_back(std::move(result)); - break; - } - case Bytecode::Op::Not: { - bool result = !truthy(*get_args(bc)[0]); - pop_args(bc); - m_stack.emplace_back(result); - break; - } - case Bytecode::Op::And: { - auto args = get_args(bc); - bool result = truthy(*args[0]) && truthy(*args[1]); - pop_args(bc); - m_stack.emplace_back(result); - break; - } - case Bytecode::Op::Or: { - auto args = get_args(bc); - bool result = truthy(*args[0]) || truthy(*args[1]); - pop_args(bc); - m_stack.emplace_back(result); - break; - } - case Bytecode::Op::In: { - auto args = get_args(bc); - bool result = std::find(args[1]->begin(), args[1]->end(), *args[0]) != - args[1]->end(); - pop_args(bc); - m_stack.emplace_back(result); - break; - } - case Bytecode::Op::Equal: { - auto args = get_args(bc); - bool result = (*args[0] == *args[1]); - pop_args(bc); - m_stack.emplace_back(result); - break; - } - case Bytecode::Op::Greater: { - auto args = get_args(bc); - bool result = (*args[0] > *args[1]); - pop_args(bc); - m_stack.emplace_back(result); - break; - } - case Bytecode::Op::Less: { - auto args = get_args(bc); - bool result = (*args[0] < *args[1]); - pop_args(bc); - m_stack.emplace_back(result); - break; - } - case Bytecode::Op::GreaterEqual: { - auto args = get_args(bc); - bool result = (*args[0] >= *args[1]); - pop_args(bc); - m_stack.emplace_back(result); - break; - } - case Bytecode::Op::LessEqual: { - auto args = get_args(bc); - bool result = (*args[0] <= *args[1]); - pop_args(bc); - m_stack.emplace_back(result); - break; - } - case Bytecode::Op::Different: { - auto args = get_args(bc); - bool result = (*args[0] != *args[1]); - pop_args(bc); - m_stack.emplace_back(result); - break; - } - case Bytecode::Op::Float: { - double result = - std::stod(get_args(bc)[0]->get_ref()); - pop_args(bc); - m_stack.emplace_back(result); - break; - } - case Bytecode::Op::Int: { - int result = std::stoi(get_args(bc)[0]->get_ref()); - pop_args(bc); - m_stack.emplace_back(result); - break; - } - case Bytecode::Op::Exists: { - auto&& name = get_args(bc)[0]->get_ref(); - bool result = (data.find(name) != data.end()); - pop_args(bc); - m_stack.emplace_back(result); - break; - } - case Bytecode::Op::ExistsInObject: { - auto args = get_args(bc); - auto&& name = args[1]->get_ref(); - bool result = (args[0]->find(name) != args[0]->end()); - pop_args(bc); - m_stack.emplace_back(result); - break; - } - case Bytecode::Op::IsBoolean: { - bool result = get_args(bc)[0]->is_boolean(); - pop_args(bc); - m_stack.emplace_back(result); - break; - } - case Bytecode::Op::IsNumber: { - bool result = get_args(bc)[0]->is_number(); - pop_args(bc); - m_stack.emplace_back(result); - break; - } - case Bytecode::Op::IsInteger: { - bool result = get_args(bc)[0]->is_number_integer(); - pop_args(bc); - m_stack.emplace_back(result); - break; - } - case Bytecode::Op::IsFloat: { - bool result = get_args(bc)[0]->is_number_float(); - pop_args(bc); - m_stack.emplace_back(result); - break; - } - case Bytecode::Op::IsObject: { - bool result = get_args(bc)[0]->is_object(); - pop_args(bc); - m_stack.emplace_back(result); - break; - } - case Bytecode::Op::IsArray: { - bool result = get_args(bc)[0]->is_array(); - pop_args(bc); - m_stack.emplace_back(result); - break; - } - case Bytecode::Op::IsString: { - bool result = get_args(bc)[0]->is_string(); - pop_args(bc); - m_stack.emplace_back(result); - break; - } - case Bytecode::Op::Default: { - // default needs to be a bit "magic"; we can't evaluate the first - // argument during the push operation, so we swap the arguments during - // the parse phase so the second argument is pushed on the stack and - // the first argument is in the immediate - try { - const json* imm = get_imm(bc); - // if no exception was raised, replace the stack value with it - m_stack.back() = *imm; - } catch (std::exception&) { - // couldn't read immediate, just leave the stack as is - } - break; - } - case Bytecode::Op::Include: - Renderer(m_included_templates, m_callbacks).render_to(os, m_included_templates.find(get_imm(bc)->get_ref())->second, *m_data); - break; - case Bytecode::Op::Callback: { - auto callback = m_callbacks.find_callback(bc.str, bc.args); - if (!callback) { - inja_throw("render_error", "function '" + static_cast(bc.str) + "' (" + std::to_string(static_cast(bc.args)) + ") not found"); - } - json result = callback(get_args(bc)); - pop_args(bc); - m_stack.emplace_back(std::move(result)); - break; - } - case Bytecode::Op::Jump: { - i = bc.args - 1; // -1 due to ++i in loop - break; - } - case Bytecode::Op::ConditionalJump: { - if (!truthy(m_stack.back())) { - i = bc.args - 1; // -1 due to ++i in loop - } - m_stack.pop_back(); - break; - } - case Bytecode::Op::StartLoop: { - // jump past loop body if empty - if (m_stack.back().empty()) { - m_stack.pop_back(); - i = bc.args; // ++i in loop will take it past EndLoop - break; - } + node.body.accept(*this); + ++index; + } - m_loop_stack.emplace_back(); - LoopLevel& level = m_loop_stack.back(); - level.value_name = bc.str; - level.values = std::move(m_stack.back()); - level.data = (*m_data); - m_stack.pop_back(); - - if (bc.value.is_string()) { - // map iterator - if (!level.values.is_object()) { - m_loop_stack.pop_back(); - inja_throw("render_error", "for key, value requires object"); - } - level.loop_type = LoopLevel::Type::Map; - level.key_name = bc.value.get_ref(); - - // sort by key - for (auto it = level.values.begin(), end = level.values.end(); it != end; ++it) { - level.map_values.emplace_back(it.key(), &it.value()); - } - std::sort(level.map_values.begin(), level.map_values.end(), [](const LoopLevel::KeyValue& a, const LoopLevel::KeyValue& b) { return a.first < b.first; }); - level.map_it = level.map_values.begin(); - } else { - if (!level.values.is_array()) { - m_loop_stack.pop_back(); - inja_throw("render_error", "type must be array"); - } - - // list iterator - level.loop_type = LoopLevel::Type::Array; - level.index = 0; - level.size = level.values.size(); - } + additional_data[static_cast(node.key)].clear(); + additional_data[static_cast(node.value)].clear(); + if (!(*current_loop_data)["parent"].empty()) { + *current_loop_data = std::move((*current_loop_data)["parent"]); + } else { + current_loop_data = &additional_data["loop"]; + } + } - // provide parent access in nested loop - auto parent_loop_it = level.data.find("loop"); - if (parent_loop_it != level.data.end()) { - json loop_copy = *parent_loop_it; - (*parent_loop_it)["parent"] = std::move(loop_copy); - } + void visit(const IfStatementNode& node) { + const auto result = eval_expression_list(node.condition); + if (truthy(result.get())) { + node.true_statement.accept(*this); + } else if (node.has_false_statement) { + node.false_statement.accept(*this); + } + } - // set "current" data to loop data - m_data = &level.data; - update_loop_data(); - break; - } - case Bytecode::Op::EndLoop: { - if (m_loop_stack.empty()) { - inja_throw("render_error", "unexpected state in renderer"); - } - LoopLevel& level = m_loop_stack.back(); + void visit(const IncludeStatementNode& node) { + auto sub_renderer = Renderer(config, template_storage, function_storage); + const auto included_template_it = template_storage.find(node.file); + if (included_template_it != template_storage.end()) { + sub_renderer.render_to(*output_stream, included_template_it->second, *data_input, &additional_data); + } else if (config.throw_at_missing_includes) { + throw_renderer_error("include '" + node.file + "' not found", node); + } + } - bool done; - if (level.loop_type == LoopLevel::Type::Array) { - level.index += 1; - done = (level.index == level.values.size()); - } else { - level.map_it += 1; - done = (level.map_it == level.map_values.end()); - } + void visit(const ExtendsStatementNode& node) { + const auto included_template_it = template_storage.find(node.file); + if (included_template_it != template_storage.end()) { + const Template* parent_template = &included_template_it->second; + render_to(*output_stream, *parent_template, *data_input, &additional_data); + break_rendering = true; + } else if (config.throw_at_missing_includes) { + throw_renderer_error("extends '" + node.file + "' not found", node); + } + } - if (done) { - m_loop_stack.pop_back(); - // set "current" data to outer loop data or main data as appropriate - if (!m_loop_stack.empty()) { - m_data = &m_loop_stack.back().data; - } else { - m_data = &data; - } - break; - } + void visit(const BlockStatementNode& node) { + const size_t old_level = current_level; + current_level = 0; + current_template = template_stack.front(); + const auto block_it = current_template->block_storage.find(node.name); + if (block_it != current_template->block_storage.end()) { + block_statement_stack.emplace_back(&node); + block_it->second->block.accept(*this); + block_statement_stack.pop_back(); + } + current_level = old_level; + current_template = template_stack.back(); + } - update_loop_data(); + void visit(const SetStatementNode& node) { + std::string ptr = node.key; + replace_substring(ptr, ".", "/"); + ptr = "/" + ptr; + additional_data[json::json_pointer(ptr)] = *eval_expression_list(node.expression); + } - // jump back to start of loop - i = bc.args - 1; // -1 due to ++i in loop - break; - } - default: { - inja_throw("render_error", "unknown op in renderer: " + std::to_string(static_cast(bc.op))); - } - } +public: + Renderer(const RenderConfig& config, const TemplateStorage& template_storage, const FunctionStorage& function_storage) + : config(config), template_storage(template_storage), function_storage(function_storage) {} + + void render_to(std::ostream& os, const Template& tmpl, const json& data, json* loop_data = nullptr) { + output_stream = &os; + current_template = &tmpl; + data_input = &data; + if (loop_data) { + additional_data = *loop_data; + current_loop_data = &additional_data["loop"]; } + + template_stack.emplace_back(current_template); + current_template->root.accept(*this); + + data_tmp_stack.clear(); } }; -} // namespace inja +} // namespace inja -#endif // PANTOR_INJA_RENDERER_HPP - -// #include "string_view.hpp" +#endif // INCLUDE_INJA_RENDERER_HPP_ // #include "template.hpp" // #include "utils.hpp" - namespace inja { -using namespace nlohmann; - /*! * \brief Class for changing the configuration. */ class Environment { - class Impl { - public: - std::string input_path; - std::string output_path; - - LexerConfig lexer_config; - ParserConfig parser_config; + std::string input_path; + std::string output_path; - FunctionStorage callbacks; - TemplateStorage included_templates; - }; + LexerConfig lexer_config; + ParserConfig parser_config; + RenderConfig render_config; - std::unique_ptr m_impl; + FunctionStorage function_storage; + TemplateStorage template_storage; - public: - Environment(): Environment("") { } +public: + Environment(): Environment("") {} - explicit Environment(const std::string& global_path): m_impl(stdinja::make_unique()) { - m_impl->input_path = global_path; - m_impl->output_path = global_path; - } + explicit Environment(const std::string& global_path): input_path(global_path), output_path(global_path) {} - explicit Environment(const std::string& input_path, const std::string& output_path): m_impl(stdinja::make_unique()) { - m_impl->input_path = input_path; - m_impl->output_path = output_path; - } + Environment(const std::string& input_path, const std::string& output_path): input_path(input_path), output_path(output_path) {} /// Sets the opener and closer for template statements void set_statement(const std::string& open, const std::string& close) { - m_impl->lexer_config.statement_open = open; - m_impl->lexer_config.statement_close = close; - m_impl->lexer_config.update_open_chars(); + lexer_config.statement_open = open; + lexer_config.statement_open_no_lstrip = open + "+"; + lexer_config.statement_open_force_lstrip = open + "-"; + lexer_config.statement_close = close; + lexer_config.statement_close_force_rstrip = "-" + close; + lexer_config.update_open_chars(); } /// Sets the opener for template line statements void set_line_statement(const std::string& open) { - m_impl->lexer_config.line_statement = open; - m_impl->lexer_config.update_open_chars(); + lexer_config.line_statement = open; + lexer_config.update_open_chars(); } /// Sets the opener and closer for template expressions void set_expression(const std::string& open, const std::string& close) { - m_impl->lexer_config.expression_open = open; - m_impl->lexer_config.expression_close = close; - m_impl->lexer_config.update_open_chars(); + lexer_config.expression_open = open; + lexer_config.expression_open_force_lstrip = open + "-"; + lexer_config.expression_close = close; + lexer_config.expression_close_force_rstrip = "-" + close; + lexer_config.update_open_chars(); } /// Sets the opener and closer for template comments void set_comment(const std::string& open, const std::string& close) { - m_impl->lexer_config.comment_open = open; - m_impl->lexer_config.comment_close = close; - m_impl->lexer_config.update_open_chars(); + lexer_config.comment_open = open; + lexer_config.comment_open_force_lstrip = open + "-"; + lexer_config.comment_close = close; + lexer_config.comment_close_force_rstrip = "-" + close; + lexer_config.update_open_chars(); } /// Sets whether to remove the first newline after a block void set_trim_blocks(bool trim_blocks) { - m_impl->lexer_config.trim_blocks = trim_blocks; + lexer_config.trim_blocks = trim_blocks; } /// Sets whether to strip the spaces and tabs from the start of a line to a block void set_lstrip_blocks(bool lstrip_blocks) { - m_impl->lexer_config.lstrip_blocks = lstrip_blocks; + lexer_config.lstrip_blocks = lstrip_blocks; } /// Sets the element notation syntax - void set_element_notation(ElementNotation notation) { - m_impl->parser_config.notation = notation; + void set_search_included_templates_in_files(bool search_in_files) { + parser_config.search_included_templates_in_files = search_in_files; } + /// Sets whether a missing include will throw an error + void set_throw_at_missing_includes(bool will_throw) { + render_config.throw_at_missing_includes = will_throw; + } - Template parse(nonstd::string_view input) { - Parser parser(m_impl->parser_config, m_impl->lexer_config, m_impl->included_templates); + Template parse(std::string_view input) { + Parser parser(parser_config, lexer_config, template_storage, function_storage); return parser.parse(input); } Template parse_template(const std::string& filename) { - Parser parser(m_impl->parser_config, m_impl->lexer_config, m_impl->included_templates); - return parser.parse_template(m_impl->input_path + static_cast(filename)); - } + Parser parser(parser_config, lexer_config, template_storage, function_storage); + auto result = Template(parser.load_file(input_path + static_cast(filename))); + parser.parse_into_template(result, input_path + static_cast(filename)); + return result; + } + + Template parse_file(const std::string& filename) { + return parse_template(filename); + } - std::string render(nonstd::string_view input, const json& data) { + std::string render(std::string_view input, const json& data) { return render(parse(input), data); } @@ -3437,55 +2821,85 @@ class Environment { } std::string render_file(const std::string& filename, const json& data) { - return render(parse_template(filename), data); - } + return render(parse_template(filename), data); + } std::string render_file_with_json_file(const std::string& filename, const std::string& filename_data) { - const json data = load_json(filename_data); - return render_file(filename, data); - } + const json data = load_json(filename_data); + return render_file(filename, data); + } void write(const std::string& filename, const json& data, const std::string& filename_out) { - std::ofstream file(m_impl->output_path + filename_out); - file << render_file(filename, data); - file.close(); - } + std::ofstream file(output_path + filename_out); + file << render_file(filename, data); + file.close(); + } void write(const Template& temp, const json& data, const std::string& filename_out) { - std::ofstream file(m_impl->output_path + filename_out); - file << render(temp, data); - file.close(); - } + std::ofstream file(output_path + filename_out); + file << render(temp, data); + file.close(); + } - void write_with_json_file(const std::string& filename, const std::string& filename_data, const std::string& filename_out) { - const json data = load_json(filename_data); - write(filename, data, filename_out); - } + void write_with_json_file(const std::string& filename, const std::string& filename_data, const std::string& filename_out) { + const json data = load_json(filename_data); + write(filename, data, filename_out); + } - void write_with_json_file(const Template& temp, const std::string& filename_data, const std::string& filename_out) { - const json data = load_json(filename_data); - write(temp, data, filename_out); - } + void write_with_json_file(const Template& temp, const std::string& filename_data, const std::string& filename_out) { + const json data = load_json(filename_data); + write(temp, data, filename_out); + } std::ostream& render_to(std::ostream& os, const Template& tmpl, const json& data) { - Renderer(m_impl->included_templates, m_impl->callbacks).render_to(os, tmpl, data); + Renderer(render_config, template_storage, function_storage).render_to(os, tmpl, data); return os; } std::string load_file(const std::string& filename) { - Parser parser(m_impl->parser_config, m_impl->lexer_config, m_impl->included_templates); - return parser.load_file(m_impl->input_path + filename); - } + Parser parser(parser_config, lexer_config, template_storage, function_storage); + return parser.load_file(input_path + filename); + } json load_json(const std::string& filename) { - std::ifstream file = open_file_or_throw(m_impl->input_path + filename); - json j; - file >> j; - return j; + std::ifstream file; + file.open(input_path + filename); + if (file.fail()) { + INJA_THROW(FileError("failed accessing file at '" + input_path + filename + "'")); } - void add_callback(const std::string& name, unsigned int numArgs, const CallbackFunction& callback) { - m_impl->callbacks.add_callback(name, numArgs, callback); + return json::parse(std::istreambuf_iterator(file), std::istreambuf_iterator()); + } + + /*! + @brief Adds a variadic callback + */ + void add_callback(const std::string& name, const CallbackFunction& callback) { + add_callback(name, -1, callback); + } + + /*! + @brief Adds a variadic void callback + */ + void add_void_callback(const std::string& name, const VoidCallbackFunction& callback) { + add_void_callback(name, -1, callback); + } + + /*! + @brief Adds a callback with given number or arguments + */ + void add_callback(const std::string& name, int num_args, const CallbackFunction& callback) { + function_storage.add_callback(name, num_args, callback); + } + + /*! + @brief Adds a void callback with given number or arguments + */ + void add_void_callback(const std::string& name, int num_args, const VoidCallbackFunction& callback) { + function_storage.add_callback(name, num_args, [callback](Arguments& args) { + callback(args); + return json(); + }); } /** Includes a template with a given name into the environment. @@ -3493,37 +2907,43 @@ class Environment { * include "" syntax. */ void include_template(const std::string& name, const Template& tmpl) { - m_impl->included_templates[name] = tmpl; + template_storage[name] = tmpl; + } + + /*! + @brief Sets a function that is called when an included file is not found + */ + void set_include_callback(const std::function& callback) { + parser_config.include_callback = callback; } }; /*! @brief render with default settings to a string */ -inline std::string render(nonstd::string_view input, const json& data) { +inline std::string render(std::string_view input, const json& data) { return Environment().render(input, data); } /*! @brief render with default settings to the given output stream */ -inline void render_to(std::ostream& os, nonstd::string_view input, const json& data) { +inline void render_to(std::ostream& os, std::string_view input, const json& data) { Environment env; env.render_to(os, env.parse(input), data); } -} - -#endif // PANTOR_INJA_ENVIRONMENT_HPP +} // namespace inja -// #include "string_view.hpp" +#endif // INCLUDE_INJA_ENVIRONMENT_HPP_ -// #include "template.hpp" +// #include "exceptions.hpp" // #include "parser.hpp" // #include "renderer.hpp" +// #include "template.hpp" -#endif // PANTOR_INJA_HPP +#endif // INCLUDE_INJA_INJA_HPP_ diff --git a/tools/jsonproc/jsonproc.cpp b/tools/jsonproc/jsonproc.cpp index 2977fff848..68b1c73ba4 100755 --- a/tools/jsonproc/jsonproc.cpp +++ b/tools/jsonproc/jsonproc.cpp @@ -1,4 +1,6 @@ // jsonproc.cpp +// jsonproc converts JSON data to an output file based on an Inja template. +// https://github.com/pantor/inja #include "jsonproc.h" @@ -8,7 +10,7 @@ using std::string; using std::to_string; #include -using std::remove_if; +using std::replace_if; #include using namespace inja; @@ -112,11 +114,16 @@ int main(int argc, char *argv[]) }); env.add_callback("cleanString", 1, [](Arguments& args) { - string badChars = ".'{} \n\t-_\u00e9"; string str = args.at(0)->get(); - str.erase(remove_if(str.begin(), str.end(), [&badChars](const char &c) { - return badChars.find(c) != std::string::npos; - }), str.end()); + for (unsigned int i = 0; i < str.length(); i++) { + // This code is not Unicode aware, so UTF-8 is not easily parsable without introducing + // another library. Just filter out any non-alphanumeric characters for now. + // TODO: proper Unicode string normalization + if ((i == 0 && isdigit(str[i])) + || !isalnum(str[i])) { + str[i] = '_'; + } + } return str; }); diff --git a/tools/jsonproc/nlohmann/json.hpp b/tools/jsonproc/nlohmann/json.hpp index 5003a4fa2d..33a91164c7 100755 --- a/tools/jsonproc/nlohmann/json.hpp +++ b/tools/jsonproc/nlohmann/json.hpp @@ -1,12 +1,12 @@ /* __ _____ _____ _____ __| | __| | | | JSON for Modern C++ -| | |__ | | | | | | version 3.6.1 +| | |__ | | | | | | version 3.10.5 |_____|_____|_____|_|___| https://github.com/nlohmann/json Licensed under the MIT License . SPDX-License-Identifier: MIT -Copyright (c) 2013-2019 Niels Lohmann . +Copyright (c) 2013-2022 Niels Lohmann . Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -27,20 +27,29 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/****************************************************************************\ + * Note on documentation: The source files contain links to the online * + * documentation of the public API at https://json.nlohmann.me. This URL * + * contains the most recent documentation and should also be applicable to * + * previous versions; documentation for deprecated functions is not * + * removed, but marked deprecated. See "Generate documentation" section in * + * file doc/README.md. * +\****************************************************************************/ + #ifndef INCLUDE_NLOHMANN_JSON_HPP_ #define INCLUDE_NLOHMANN_JSON_HPP_ #define NLOHMANN_JSON_VERSION_MAJOR 3 -#define NLOHMANN_JSON_VERSION_MINOR 6 -#define NLOHMANN_JSON_VERSION_PATCH 1 +#define NLOHMANN_JSON_VERSION_MINOR 10 +#define NLOHMANN_JSON_VERSION_PATCH 5 #include // all_of, find, for_each -#include // assert -#include // and, not, or #include // nullptr_t, ptrdiff_t, size_t #include // hash, less #include // initializer_list -#include // istream, ostream +#ifndef JSON_NO_IO + #include // istream, ostream +#endif // JSON_NO_IO #include // random_access_iterator_tag #include // unique_ptr #include // accumulate @@ -51,6 +60,7 @@ SOFTWARE. // #include +#include #include // #include @@ -58,7 +68,6 @@ SOFTWARE. #include // transform #include // array -#include // and, not #include // forward_list #include // inserter, front_inserter, end #include // map @@ -75,5425 +84,6348 @@ SOFTWARE. #include // exception #include // runtime_error #include // to_string +#include // vector -// #include +// #include +#include // array #include // size_t +#include // uint8_t +#include // string namespace nlohmann { namespace detail { -/// struct to capture the start position of the current token -struct position_t -{ - /// the total number of characters read - std::size_t chars_read_total = 0; - /// the number of characters read in the current line - std::size_t chars_read_current_line = 0; - /// the number of lines read - std::size_t lines_read = 0; - - /// conversion to size_t to preserve SAX interface - constexpr operator size_t() const - { - return chars_read_total; - } -}; - -} // namespace detail -} // namespace nlohmann - - -namespace nlohmann -{ -namespace detail -{ -//////////////// -// exceptions // -//////////////// +/////////////////////////// +// JSON type enumeration // +/////////////////////////// /*! -@brief general exception of the @ref basic_json class - -This class is an extension of `std::exception` objects with a member @a id for -exception ids. It is used as the base class for all exceptions thrown by the -@ref basic_json class. This class can hence be used as "wildcard" to catch -exceptions. +@brief the JSON type enumeration -Subclasses: -- @ref parse_error for exceptions indicating a parse error -- @ref invalid_iterator for exceptions indicating errors with iterators -- @ref type_error for exceptions indicating executing a member function with - a wrong type -- @ref out_of_range for exceptions indicating access out of the defined range -- @ref other_error for exceptions indicating other library errors +This enumeration collects the different JSON types. It is internally used to +distinguish the stored values, and the functions @ref basic_json::is_null(), +@ref basic_json::is_object(), @ref basic_json::is_array(), +@ref basic_json::is_string(), @ref basic_json::is_boolean(), +@ref basic_json::is_number() (with @ref basic_json::is_number_integer(), +@ref basic_json::is_number_unsigned(), and @ref basic_json::is_number_float()), +@ref basic_json::is_discarded(), @ref basic_json::is_primitive(), and +@ref basic_json::is_structured() rely on it. -@internal -@note To have nothrow-copy-constructible exceptions, we internally use - `std::runtime_error` which can cope with arbitrary-length error messages. - Intermediate strings are built with static functions and then passed to - the actual constructor. -@endinternal +@note There are three enumeration entries (number_integer, number_unsigned, and +number_float), because the library distinguishes these three types for numbers: +@ref basic_json::number_unsigned_t is used for unsigned integers, +@ref basic_json::number_integer_t is used for signed integers, and +@ref basic_json::number_float_t is used for floating-point numbers or to +approximate integers which do not fit in the limits of their respective type. -@liveexample{The following code shows how arbitrary library exceptions can be -caught.,exception} +@sa see @ref basic_json::basic_json(const value_t value_type) -- create a JSON +value with the default value for a given type -@since version 3.0.0 +@since version 1.0.0 */ -class exception : public std::exception +enum class value_t : std::uint8_t { - public: - /// returns the explanatory string - const char* what() const noexcept override - { - return m.what(); - } - - /// the id of the exception - const int id; - - protected: - exception(int id_, const char* what_arg) : id(id_), m(what_arg) {} - - static std::string name(const std::string& ename, int id_) - { - return "[json.exception." + ename + "." + std::to_string(id_) + "] "; - } - - private: - /// an exception object as storage for error messages - std::runtime_error m; + null, ///< null value + object, ///< object (unordered set of name/value pairs) + array, ///< array (ordered collection of values) + string, ///< string value + boolean, ///< boolean value + number_integer, ///< number value (signed integer) + number_unsigned, ///< number value (unsigned integer) + number_float, ///< number value (floating-point) + binary, ///< binary array (ordered collection of bytes) + discarded ///< discarded by the parser callback function }; /*! -@brief exception indicating a parse error - -This exception is thrown by the library when a parse error occurs. Parse errors -can occur during the deserialization of JSON text, CBOR, MessagePack, as well -as when using JSON Patch. - -Member @a byte holds the byte index of the last read character in the input -file. - -Exceptions have ids 1xx. - -name / id | example message | description ------------------------------- | --------------- | ------------------------- -json.exception.parse_error.101 | parse error at 2: unexpected end of input; expected string literal | This error indicates a syntax error while deserializing a JSON text. The error message describes that an unexpected token (character) was encountered, and the member @a byte indicates the error position. -json.exception.parse_error.102 | parse error at 14: missing or wrong low surrogate | JSON uses the `\uxxxx` format to describe Unicode characters. Code points above above 0xFFFF are split into two `\uxxxx` entries ("surrogate pairs"). This error indicates that the surrogate pair is incomplete or contains an invalid code point. -json.exception.parse_error.103 | parse error: code points above 0x10FFFF are invalid | Unicode supports code points up to 0x10FFFF. Code points above 0x10FFFF are invalid. -json.exception.parse_error.104 | parse error: JSON patch must be an array of objects | [RFC 6902](https://tools.ietf.org/html/rfc6902) requires a JSON Patch document to be a JSON document that represents an array of objects. -json.exception.parse_error.105 | parse error: operation must have string member 'op' | An operation of a JSON Patch document must contain exactly one "op" member, whose value indicates the operation to perform. Its value must be one of "add", "remove", "replace", "move", "copy", or "test"; other values are errors. -json.exception.parse_error.106 | parse error: array index '01' must not begin with '0' | An array index in a JSON Pointer ([RFC 6901](https://tools.ietf.org/html/rfc6901)) may be `0` or any number without a leading `0`. -json.exception.parse_error.107 | parse error: JSON pointer must be empty or begin with '/' - was: 'foo' | A JSON Pointer must be a Unicode string containing a sequence of zero or more reference tokens, each prefixed by a `/` character. -json.exception.parse_error.108 | parse error: escape character '~' must be followed with '0' or '1' | In a JSON Pointer, only `~0` and `~1` are valid escape sequences. -json.exception.parse_error.109 | parse error: array index 'one' is not a number | A JSON Pointer array index must be a number. -json.exception.parse_error.110 | parse error at 1: cannot read 2 bytes from vector | When parsing CBOR or MessagePack, the byte vector ends before the complete value has been read. -json.exception.parse_error.112 | parse error at 1: error reading CBOR; last byte: 0xF8 | Not all types of CBOR or MessagePack are supported. This exception occurs if an unsupported byte was read. -json.exception.parse_error.113 | parse error at 2: expected a CBOR string; last byte: 0x98 | While parsing a map key, a value that is not a string has been read. -json.exception.parse_error.114 | parse error: Unsupported BSON record type 0x0F | The parsing of the corresponding BSON record type is not implemented (yet). - -@note For an input with n bytes, 1 is the index of the first character and n+1 - is the index of the terminating null byte or the end of file. This also - holds true when reading a byte vector (CBOR or MessagePack). - -@liveexample{The following code shows how a `parse_error` exception can be -caught.,parse_error} - -@sa - @ref exception for the base class of the library exceptions -@sa - @ref invalid_iterator for exceptions indicating errors with iterators -@sa - @ref type_error for exceptions indicating executing a member function with - a wrong type -@sa - @ref out_of_range for exceptions indicating access out of the defined range -@sa - @ref other_error for exceptions indicating other library errors - -@since version 3.0.0 -*/ -class parse_error : public exception -{ - public: - /*! - @brief create a parse error exception - @param[in] id_ the id of the exception - @param[in] pos the position where the error occurred (or with - chars_read_total=0 if the position cannot be - determined) - @param[in] what_arg the explanatory string - @return parse_error object - */ - static parse_error create(int id_, const position_t& pos, const std::string& what_arg) - { - std::string w = exception::name("parse_error", id_) + "parse error" + - position_string(pos) + ": " + what_arg; - return parse_error(id_, pos.chars_read_total, w.c_str()); - } - - static parse_error create(int id_, std::size_t byte_, const std::string& what_arg) - { - std::string w = exception::name("parse_error", id_) + "parse error" + - (byte_ != 0 ? (" at byte " + std::to_string(byte_)) : "") + - ": " + what_arg; - return parse_error(id_, byte_, w.c_str()); - } - - /*! - @brief byte index of the parse error - - The byte index of the last read character in the input file. - - @note For an input with n bytes, 1 is the index of the first character and - n+1 is the index of the terminating null byte or the end of file. - This also holds true when reading a byte vector (CBOR or MessagePack). - */ - const std::size_t byte; - - private: - parse_error(int id_, std::size_t byte_, const char* what_arg) - : exception(id_, what_arg), byte(byte_) {} +@brief comparison operator for JSON types - static std::string position_string(const position_t& pos) - { - return " at line " + std::to_string(pos.lines_read + 1) + - ", column " + std::to_string(pos.chars_read_current_line); - } -}; +Returns an ordering that is similar to Python: +- order: null < boolean < number < object < array < string < binary +- furthermore, each type is not smaller than itself +- discarded values are not comparable +- binary is represented as a b"" string in python and directly comparable to a + string; however, making a binary array directly comparable with a string would + be surprising behavior in a JSON file. -/*! -@brief exception indicating errors with iterators - -This exception is thrown if iterators passed to a library function do not match -the expected semantics. - -Exceptions have ids 2xx. - -name / id | example message | description ------------------------------------ | --------------- | ------------------------- -json.exception.invalid_iterator.201 | iterators are not compatible | The iterators passed to constructor @ref basic_json(InputIT first, InputIT last) are not compatible, meaning they do not belong to the same container. Therefore, the range (@a first, @a last) is invalid. -json.exception.invalid_iterator.202 | iterator does not fit current value | In an erase or insert function, the passed iterator @a pos does not belong to the JSON value for which the function was called. It hence does not define a valid position for the deletion/insertion. -json.exception.invalid_iterator.203 | iterators do not fit current value | Either iterator passed to function @ref erase(IteratorType first, IteratorType last) does not belong to the JSON value from which values shall be erased. It hence does not define a valid range to delete values from. -json.exception.invalid_iterator.204 | iterators out of range | When an iterator range for a primitive type (number, boolean, or string) is passed to a constructor or an erase function, this range has to be exactly (@ref begin(), @ref end()), because this is the only way the single stored value is expressed. All other ranges are invalid. -json.exception.invalid_iterator.205 | iterator out of range | When an iterator for a primitive type (number, boolean, or string) is passed to an erase function, the iterator has to be the @ref begin() iterator, because it is the only way to address the stored value. All other iterators are invalid. -json.exception.invalid_iterator.206 | cannot construct with iterators from null | The iterators passed to constructor @ref basic_json(InputIT first, InputIT last) belong to a JSON null value and hence to not define a valid range. -json.exception.invalid_iterator.207 | cannot use key() for non-object iterators | The key() member function can only be used on iterators belonging to a JSON object, because other types do not have a concept of a key. -json.exception.invalid_iterator.208 | cannot use operator[] for object iterators | The operator[] to specify a concrete offset cannot be used on iterators belonging to a JSON object, because JSON objects are unordered. -json.exception.invalid_iterator.209 | cannot use offsets with object iterators | The offset operators (+, -, +=, -=) cannot be used on iterators belonging to a JSON object, because JSON objects are unordered. -json.exception.invalid_iterator.210 | iterators do not fit | The iterator range passed to the insert function are not compatible, meaning they do not belong to the same container. Therefore, the range (@a first, @a last) is invalid. -json.exception.invalid_iterator.211 | passed iterators may not belong to container | The iterator range passed to the insert function must not be a subrange of the container to insert to. -json.exception.invalid_iterator.212 | cannot compare iterators of different containers | When two iterators are compared, they must belong to the same container. -json.exception.invalid_iterator.213 | cannot compare order of object iterators | The order of object iterators cannot be compared, because JSON objects are unordered. -json.exception.invalid_iterator.214 | cannot get value | Cannot get value for iterator: Either the iterator belongs to a null value or it is an iterator to a primitive type (number, boolean, or string), but the iterator is different to @ref begin(). - -@liveexample{The following code shows how an `invalid_iterator` exception can be -caught.,invalid_iterator} - -@sa - @ref exception for the base class of the library exceptions -@sa - @ref parse_error for exceptions indicating a parse error -@sa - @ref type_error for exceptions indicating executing a member function with - a wrong type -@sa - @ref out_of_range for exceptions indicating access out of the defined range -@sa - @ref other_error for exceptions indicating other library errors - -@since version 3.0.0 +@since version 1.0.0 */ -class invalid_iterator : public exception +inline bool operator<(const value_t lhs, const value_t rhs) noexcept { - public: - static invalid_iterator create(int id_, const std::string& what_arg) - { - std::string w = exception::name("invalid_iterator", id_) + what_arg; - return invalid_iterator(id_, w.c_str()); - } + static constexpr std::array order = {{ + 0 /* null */, 3 /* object */, 4 /* array */, 5 /* string */, + 1 /* boolean */, 2 /* integer */, 2 /* unsigned */, 2 /* float */, + 6 /* binary */ + } + }; - private: - invalid_iterator(int id_, const char* what_arg) - : exception(id_, what_arg) {} -}; + const auto l_index = static_cast(lhs); + const auto r_index = static_cast(rhs); + return l_index < order.size() && r_index < order.size() && order[l_index] < order[r_index]; +} +} // namespace detail +} // namespace nlohmann -/*! -@brief exception indicating executing a member function with a wrong type - -This exception is thrown in case of a type error; that is, a library function is -executed on a JSON value whose type does not match the expected semantics. - -Exceptions have ids 3xx. - -name / id | example message | description ------------------------------ | --------------- | ------------------------- -json.exception.type_error.301 | cannot create object from initializer list | To create an object from an initializer list, the initializer list must consist only of a list of pairs whose first element is a string. When this constraint is violated, an array is created instead. -json.exception.type_error.302 | type must be object, but is array | During implicit or explicit value conversion, the JSON type must be compatible to the target type. For instance, a JSON string can only be converted into string types, but not into numbers or boolean types. -json.exception.type_error.303 | incompatible ReferenceType for get_ref, actual type is object | To retrieve a reference to a value stored in a @ref basic_json object with @ref get_ref, the type of the reference must match the value type. For instance, for a JSON array, the @a ReferenceType must be @ref array_t &. -json.exception.type_error.304 | cannot use at() with string | The @ref at() member functions can only be executed for certain JSON types. -json.exception.type_error.305 | cannot use operator[] with string | The @ref operator[] member functions can only be executed for certain JSON types. -json.exception.type_error.306 | cannot use value() with string | The @ref value() member functions can only be executed for certain JSON types. -json.exception.type_error.307 | cannot use erase() with string | The @ref erase() member functions can only be executed for certain JSON types. -json.exception.type_error.308 | cannot use push_back() with string | The @ref push_back() and @ref operator+= member functions can only be executed for certain JSON types. -json.exception.type_error.309 | cannot use insert() with | The @ref insert() member functions can only be executed for certain JSON types. -json.exception.type_error.310 | cannot use swap() with number | The @ref swap() member functions can only be executed for certain JSON types. -json.exception.type_error.311 | cannot use emplace_back() with string | The @ref emplace_back() member function can only be executed for certain JSON types. -json.exception.type_error.312 | cannot use update() with string | The @ref update() member functions can only be executed for certain JSON types. -json.exception.type_error.313 | invalid value to unflatten | The @ref unflatten function converts an object whose keys are JSON Pointers back into an arbitrary nested JSON value. The JSON Pointers must not overlap, because then the resulting value would not be well defined. -json.exception.type_error.314 | only objects can be unflattened | The @ref unflatten function only works for an object whose keys are JSON Pointers. -json.exception.type_error.315 | values in object must be primitive | The @ref unflatten function only works for an object whose keys are JSON Pointers and whose values are primitive. -json.exception.type_error.316 | invalid UTF-8 byte at index 10: 0x7E | The @ref dump function only works with UTF-8 encoded strings; that is, if you assign a `std::string` to a JSON value, make sure it is UTF-8 encoded. | -json.exception.type_error.317 | JSON value cannot be serialized to requested format | The dynamic type of the object cannot be represented in the requested serialization format (e.g. a raw `true` or `null` JSON object cannot be serialized to BSON) | - -@liveexample{The following code shows how a `type_error` exception can be -caught.,type_error} - -@sa - @ref exception for the base class of the library exceptions -@sa - @ref parse_error for exceptions indicating a parse error -@sa - @ref invalid_iterator for exceptions indicating errors with iterators -@sa - @ref out_of_range for exceptions indicating access out of the defined range -@sa - @ref other_error for exceptions indicating other library errors - -@since version 3.0.0 -*/ -class type_error : public exception -{ - public: - static type_error create(int id_, const std::string& what_arg) - { - std::string w = exception::name("type_error", id_) + what_arg; - return type_error(id_, w.c_str()); - } +// #include - private: - type_error(int id_, const char* what_arg) : exception(id_, what_arg) {} -}; -/*! -@brief exception indicating access out of the defined range - -This exception is thrown in case a library function is called on an input -parameter that exceeds the expected range, for instance in case of array -indices or nonexisting object keys. - -Exceptions have ids 4xx. - -name / id | example message | description -------------------------------- | --------------- | ------------------------- -json.exception.out_of_range.401 | array index 3 is out of range | The provided array index @a i is larger than @a size-1. -json.exception.out_of_range.402 | array index '-' (3) is out of range | The special array index `-` in a JSON Pointer never describes a valid element of the array, but the index past the end. That is, it can only be used to add elements at this position, but not to read it. -json.exception.out_of_range.403 | key 'foo' not found | The provided key was not found in the JSON object. -json.exception.out_of_range.404 | unresolved reference token 'foo' | A reference token in a JSON Pointer could not be resolved. -json.exception.out_of_range.405 | JSON pointer has no parent | The JSON Patch operations 'remove' and 'add' can not be applied to the root element of the JSON value. -json.exception.out_of_range.406 | number overflow parsing '10E1000' | A parsed number could not be stored as without changing it to NaN or INF. -json.exception.out_of_range.407 | number overflow serializing '9223372036854775808' | UBJSON and BSON only support integer numbers up to 9223372036854775807. | -json.exception.out_of_range.408 | excessive array size: 8658170730974374167 | The size (following `#`) of an UBJSON array or object exceeds the maximal capacity. | -json.exception.out_of_range.409 | BSON key cannot contain code point U+0000 (at byte 2) | Key identifiers to be serialized to BSON cannot contain code point U+0000, since the key is stored as zero-terminated c-string | - -@liveexample{The following code shows how an `out_of_range` exception can be -caught.,out_of_range} - -@sa - @ref exception for the base class of the library exceptions -@sa - @ref parse_error for exceptions indicating a parse error -@sa - @ref invalid_iterator for exceptions indicating errors with iterators -@sa - @ref type_error for exceptions indicating executing a member function with - a wrong type -@sa - @ref other_error for exceptions indicating other library errors - -@since version 3.0.0 -*/ -class out_of_range : public exception -{ - public: - static out_of_range create(int id_, const std::string& what_arg) - { - std::string w = exception::name("out_of_range", id_) + what_arg; - return out_of_range(id_, w.c_str()); - } +#include +// #include - private: - out_of_range(int id_, const char* what_arg) : exception(id_, what_arg) {} -}; -/*! -@brief exception indicating other library errors +#include // declval, pair +// #include -This exception is thrown in case of errors that cannot be classified with the -other exception types. -Exceptions have ids 5xx. +/* Hedley - https://nemequ.github.io/hedley + * Created by Evan Nemerson + * + * To the extent possible under law, the author(s) have dedicated all + * copyright and related and neighboring rights to this software to + * the public domain worldwide. This software is distributed without + * any warranty. + * + * For details, see . + * SPDX-License-Identifier: CC0-1.0 + */ -name / id | example message | description ------------------------------- | --------------- | ------------------------- -json.exception.other_error.501 | unsuccessful: {"op":"test","path":"/baz", "value":"bar"} | A JSON Patch operation 'test' failed. The unsuccessful operation is also printed. +#if !defined(JSON_HEDLEY_VERSION) || (JSON_HEDLEY_VERSION < 15) +#if defined(JSON_HEDLEY_VERSION) + #undef JSON_HEDLEY_VERSION +#endif +#define JSON_HEDLEY_VERSION 15 -@sa - @ref exception for the base class of the library exceptions -@sa - @ref parse_error for exceptions indicating a parse error -@sa - @ref invalid_iterator for exceptions indicating errors with iterators -@sa - @ref type_error for exceptions indicating executing a member function with - a wrong type -@sa - @ref out_of_range for exceptions indicating access out of the defined range +#if defined(JSON_HEDLEY_STRINGIFY_EX) + #undef JSON_HEDLEY_STRINGIFY_EX +#endif +#define JSON_HEDLEY_STRINGIFY_EX(x) #x -@liveexample{The following code shows how an `other_error` exception can be -caught.,other_error} +#if defined(JSON_HEDLEY_STRINGIFY) + #undef JSON_HEDLEY_STRINGIFY +#endif +#define JSON_HEDLEY_STRINGIFY(x) JSON_HEDLEY_STRINGIFY_EX(x) -@since version 3.0.0 -*/ -class other_error : public exception -{ - public: - static other_error create(int id_, const std::string& what_arg) - { - std::string w = exception::name("other_error", id_) + what_arg; - return other_error(id_, w.c_str()); - } +#if defined(JSON_HEDLEY_CONCAT_EX) + #undef JSON_HEDLEY_CONCAT_EX +#endif +#define JSON_HEDLEY_CONCAT_EX(a,b) a##b - private: - other_error(int id_, const char* what_arg) : exception(id_, what_arg) {} -}; -} // namespace detail -} // namespace nlohmann +#if defined(JSON_HEDLEY_CONCAT) + #undef JSON_HEDLEY_CONCAT +#endif +#define JSON_HEDLEY_CONCAT(a,b) JSON_HEDLEY_CONCAT_EX(a,b) -// #include +#if defined(JSON_HEDLEY_CONCAT3_EX) + #undef JSON_HEDLEY_CONCAT3_EX +#endif +#define JSON_HEDLEY_CONCAT3_EX(a,b,c) a##b##c +#if defined(JSON_HEDLEY_CONCAT3) + #undef JSON_HEDLEY_CONCAT3 +#endif +#define JSON_HEDLEY_CONCAT3(a,b,c) JSON_HEDLEY_CONCAT3_EX(a,b,c) -#include // pair +#if defined(JSON_HEDLEY_VERSION_ENCODE) + #undef JSON_HEDLEY_VERSION_ENCODE +#endif +#define JSON_HEDLEY_VERSION_ENCODE(major,minor,revision) (((major) * 1000000) + ((minor) * 1000) + (revision)) -// This file contains all internal macro definitions -// You MUST include macro_unscope.hpp at the end of json.hpp to undef all of them +#if defined(JSON_HEDLEY_VERSION_DECODE_MAJOR) + #undef JSON_HEDLEY_VERSION_DECODE_MAJOR +#endif +#define JSON_HEDLEY_VERSION_DECODE_MAJOR(version) ((version) / 1000000) -// exclude unsupported compilers -#if !defined(JSON_SKIP_UNSUPPORTED_COMPILER_CHECK) - #if defined(__clang__) - #if (__clang_major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__) < 30400 - #error "unsupported Clang version - see https://github.com/nlohmann/json#supported-compilers" - #endif - #elif defined(__GNUC__) && !(defined(__ICC) || defined(__INTEL_COMPILER)) - #if (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) < 40800 - #error "unsupported GCC version - see https://github.com/nlohmann/json#supported-compilers" - #endif - #endif +#if defined(JSON_HEDLEY_VERSION_DECODE_MINOR) + #undef JSON_HEDLEY_VERSION_DECODE_MINOR #endif +#define JSON_HEDLEY_VERSION_DECODE_MINOR(version) (((version) % 1000000) / 1000) -// disable float-equal warnings on GCC/clang -#if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__) - #pragma GCC diagnostic push - #pragma GCC diagnostic ignored "-Wfloat-equal" +#if defined(JSON_HEDLEY_VERSION_DECODE_REVISION) + #undef JSON_HEDLEY_VERSION_DECODE_REVISION #endif +#define JSON_HEDLEY_VERSION_DECODE_REVISION(version) ((version) % 1000) -// disable documentation warnings on clang -#if defined(__clang__) - #pragma GCC diagnostic push - #pragma GCC diagnostic ignored "-Wdocumentation" +#if defined(JSON_HEDLEY_GNUC_VERSION) + #undef JSON_HEDLEY_GNUC_VERSION +#endif +#if defined(__GNUC__) && defined(__GNUC_PATCHLEVEL__) + #define JSON_HEDLEY_GNUC_VERSION JSON_HEDLEY_VERSION_ENCODE(__GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__) +#elif defined(__GNUC__) + #define JSON_HEDLEY_GNUC_VERSION JSON_HEDLEY_VERSION_ENCODE(__GNUC__, __GNUC_MINOR__, 0) #endif -// allow for portable deprecation warnings -#if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__) - #define JSON_DEPRECATED __attribute__((deprecated)) -#elif defined(_MSC_VER) - #define JSON_DEPRECATED __declspec(deprecated) +#if defined(JSON_HEDLEY_GNUC_VERSION_CHECK) + #undef JSON_HEDLEY_GNUC_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_GNUC_VERSION) + #define JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_GNUC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) #else - #define JSON_DEPRECATED + #define JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) (0) #endif -// allow for portable nodiscard warnings -#if defined(__has_cpp_attribute) - #if __has_cpp_attribute(nodiscard) - #define JSON_NODISCARD [[nodiscard]] - #elif __has_cpp_attribute(gnu::warn_unused_result) - #define JSON_NODISCARD [[gnu::warn_unused_result]] - #else - #define JSON_NODISCARD - #endif -#else - #define JSON_NODISCARD +#if defined(JSON_HEDLEY_MSVC_VERSION) + #undef JSON_HEDLEY_MSVC_VERSION +#endif +#if defined(_MSC_FULL_VER) && (_MSC_FULL_VER >= 140000000) && !defined(__ICL) + #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_FULL_VER / 10000000, (_MSC_FULL_VER % 10000000) / 100000, (_MSC_FULL_VER % 100000) / 100) +#elif defined(_MSC_FULL_VER) && !defined(__ICL) + #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_FULL_VER / 1000000, (_MSC_FULL_VER % 1000000) / 10000, (_MSC_FULL_VER % 10000) / 10) +#elif defined(_MSC_VER) && !defined(__ICL) + #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_VER / 100, _MSC_VER % 100, 0) #endif -// allow to disable exceptions -#if (defined(__cpp_exceptions) || defined(__EXCEPTIONS) || defined(_CPPUNWIND)) && !defined(JSON_NOEXCEPTION) - #define JSON_THROW(exception) throw exception - #define JSON_TRY try - #define JSON_CATCH(exception) catch(exception) - #define JSON_INTERNAL_CATCH(exception) catch(exception) +#if defined(JSON_HEDLEY_MSVC_VERSION_CHECK) + #undef JSON_HEDLEY_MSVC_VERSION_CHECK +#endif +#if !defined(JSON_HEDLEY_MSVC_VERSION) + #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (0) +#elif defined(_MSC_VER) && (_MSC_VER >= 1400) + #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_FULL_VER >= ((major * 10000000) + (minor * 100000) + (patch))) +#elif defined(_MSC_VER) && (_MSC_VER >= 1200) + #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_FULL_VER >= ((major * 1000000) + (minor * 10000) + (patch))) #else - #include - #define JSON_THROW(exception) std::abort() - #define JSON_TRY if(true) - #define JSON_CATCH(exception) if(false) - #define JSON_INTERNAL_CATCH(exception) if(false) + #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_VER >= ((major * 100) + (minor))) #endif -// override exception macros -#if defined(JSON_THROW_USER) - #undef JSON_THROW - #define JSON_THROW JSON_THROW_USER +#if defined(JSON_HEDLEY_INTEL_VERSION) + #undef JSON_HEDLEY_INTEL_VERSION #endif -#if defined(JSON_TRY_USER) - #undef JSON_TRY - #define JSON_TRY JSON_TRY_USER +#if defined(__INTEL_COMPILER) && defined(__INTEL_COMPILER_UPDATE) && !defined(__ICL) + #define JSON_HEDLEY_INTEL_VERSION JSON_HEDLEY_VERSION_ENCODE(__INTEL_COMPILER / 100, __INTEL_COMPILER % 100, __INTEL_COMPILER_UPDATE) +#elif defined(__INTEL_COMPILER) && !defined(__ICL) + #define JSON_HEDLEY_INTEL_VERSION JSON_HEDLEY_VERSION_ENCODE(__INTEL_COMPILER / 100, __INTEL_COMPILER % 100, 0) #endif -#if defined(JSON_CATCH_USER) - #undef JSON_CATCH - #define JSON_CATCH JSON_CATCH_USER - #undef JSON_INTERNAL_CATCH - #define JSON_INTERNAL_CATCH JSON_CATCH_USER + +#if defined(JSON_HEDLEY_INTEL_VERSION_CHECK) + #undef JSON_HEDLEY_INTEL_VERSION_CHECK #endif -#if defined(JSON_INTERNAL_CATCH_USER) - #undef JSON_INTERNAL_CATCH - #define JSON_INTERNAL_CATCH JSON_INTERNAL_CATCH_USER +#if defined(JSON_HEDLEY_INTEL_VERSION) + #define JSON_HEDLEY_INTEL_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_INTEL_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_INTEL_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_INTEL_CL_VERSION) + #undef JSON_HEDLEY_INTEL_CL_VERSION +#endif +#if defined(__INTEL_COMPILER) && defined(__INTEL_COMPILER_UPDATE) && defined(__ICL) + #define JSON_HEDLEY_INTEL_CL_VERSION JSON_HEDLEY_VERSION_ENCODE(__INTEL_COMPILER, __INTEL_COMPILER_UPDATE, 0) #endif -// manual branch prediction -#if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__) - #define JSON_LIKELY(x) __builtin_expect(x, 1) - #define JSON_UNLIKELY(x) __builtin_expect(x, 0) +#if defined(JSON_HEDLEY_INTEL_CL_VERSION_CHECK) + #undef JSON_HEDLEY_INTEL_CL_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_INTEL_CL_VERSION) + #define JSON_HEDLEY_INTEL_CL_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_INTEL_CL_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) #else - #define JSON_LIKELY(x) x - #define JSON_UNLIKELY(x) x + #define JSON_HEDLEY_INTEL_CL_VERSION_CHECK(major,minor,patch) (0) #endif -// C++ language standard detection -#if (defined(__cplusplus) && __cplusplus >= 201703L) || (defined(_HAS_CXX17) && _HAS_CXX17 == 1) // fix for issue #464 - #define JSON_HAS_CPP_17 - #define JSON_HAS_CPP_14 -#elif (defined(__cplusplus) && __cplusplus >= 201402L) || (defined(_HAS_CXX14) && _HAS_CXX14 == 1) - #define JSON_HAS_CPP_14 +#if defined(JSON_HEDLEY_PGI_VERSION) + #undef JSON_HEDLEY_PGI_VERSION +#endif +#if defined(__PGI) && defined(__PGIC__) && defined(__PGIC_MINOR__) && defined(__PGIC_PATCHLEVEL__) + #define JSON_HEDLEY_PGI_VERSION JSON_HEDLEY_VERSION_ENCODE(__PGIC__, __PGIC_MINOR__, __PGIC_PATCHLEVEL__) #endif -/*! -@brief macro to briefly define a mapping between an enum and JSON -@def NLOHMANN_JSON_SERIALIZE_ENUM -@since version 3.4.0 -*/ -#define NLOHMANN_JSON_SERIALIZE_ENUM(ENUM_TYPE, ...) \ - template \ - inline void to_json(BasicJsonType& j, const ENUM_TYPE& e) \ - { \ - static_assert(std::is_enum::value, #ENUM_TYPE " must be an enum!"); \ - static const std::pair m[] = __VA_ARGS__; \ - auto it = std::find_if(std::begin(m), std::end(m), \ - [e](const std::pair& ej_pair) -> bool \ - { \ - return ej_pair.first == e; \ - }); \ - j = ((it != std::end(m)) ? it : std::begin(m))->second; \ - } \ - template \ - inline void from_json(const BasicJsonType& j, ENUM_TYPE& e) \ - { \ - static_assert(std::is_enum::value, #ENUM_TYPE " must be an enum!"); \ - static const std::pair m[] = __VA_ARGS__; \ - auto it = std::find_if(std::begin(m), std::end(m), \ - [j](const std::pair& ej_pair) -> bool \ - { \ - return ej_pair.second == j; \ - }); \ - e = ((it != std::end(m)) ? it : std::begin(m))->first; \ - } +#if defined(JSON_HEDLEY_PGI_VERSION_CHECK) + #undef JSON_HEDLEY_PGI_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_PGI_VERSION) + #define JSON_HEDLEY_PGI_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_PGI_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_PGI_VERSION_CHECK(major,minor,patch) (0) +#endif -// Ugly macros to avoid uglier copy-paste when specializing basic_json. They -// may be removed in the future once the class is split. +#if defined(JSON_HEDLEY_SUNPRO_VERSION) + #undef JSON_HEDLEY_SUNPRO_VERSION +#endif +#if defined(__SUNPRO_C) && (__SUNPRO_C > 0x1000) + #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((((__SUNPRO_C >> 16) & 0xf) * 10) + ((__SUNPRO_C >> 12) & 0xf), (((__SUNPRO_C >> 8) & 0xf) * 10) + ((__SUNPRO_C >> 4) & 0xf), (__SUNPRO_C & 0xf) * 10) +#elif defined(__SUNPRO_C) + #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((__SUNPRO_C >> 8) & 0xf, (__SUNPRO_C >> 4) & 0xf, (__SUNPRO_C) & 0xf) +#elif defined(__SUNPRO_CC) && (__SUNPRO_CC > 0x1000) + #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((((__SUNPRO_CC >> 16) & 0xf) * 10) + ((__SUNPRO_CC >> 12) & 0xf), (((__SUNPRO_CC >> 8) & 0xf) * 10) + ((__SUNPRO_CC >> 4) & 0xf), (__SUNPRO_CC & 0xf) * 10) +#elif defined(__SUNPRO_CC) + #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((__SUNPRO_CC >> 8) & 0xf, (__SUNPRO_CC >> 4) & 0xf, (__SUNPRO_CC) & 0xf) +#endif -#define NLOHMANN_BASIC_JSON_TPL_DECLARATION \ - template class ObjectType, \ - template class ArrayType, \ - class StringType, class BooleanType, class NumberIntegerType, \ - class NumberUnsignedType, class NumberFloatType, \ - template class AllocatorType, \ - template class JSONSerializer> +#if defined(JSON_HEDLEY_SUNPRO_VERSION_CHECK) + #undef JSON_HEDLEY_SUNPRO_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_SUNPRO_VERSION) + #define JSON_HEDLEY_SUNPRO_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_SUNPRO_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_SUNPRO_VERSION_CHECK(major,minor,patch) (0) +#endif -#define NLOHMANN_BASIC_JSON_TPL \ - basic_json +#if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION) + #undef JSON_HEDLEY_EMSCRIPTEN_VERSION +#endif +#if defined(__EMSCRIPTEN__) + #define JSON_HEDLEY_EMSCRIPTEN_VERSION JSON_HEDLEY_VERSION_ENCODE(__EMSCRIPTEN_major__, __EMSCRIPTEN_minor__, __EMSCRIPTEN_tiny__) +#endif -// #include +#if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK) + #undef JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION) + #define JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_EMSCRIPTEN_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK(major,minor,patch) (0) +#endif +#if defined(JSON_HEDLEY_ARM_VERSION) + #undef JSON_HEDLEY_ARM_VERSION +#endif +#if defined(__CC_ARM) && defined(__ARMCOMPILER_VERSION) + #define JSON_HEDLEY_ARM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ARMCOMPILER_VERSION / 1000000, (__ARMCOMPILER_VERSION % 1000000) / 10000, (__ARMCOMPILER_VERSION % 10000) / 100) +#elif defined(__CC_ARM) && defined(__ARMCC_VERSION) + #define JSON_HEDLEY_ARM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ARMCC_VERSION / 1000000, (__ARMCC_VERSION % 1000000) / 10000, (__ARMCC_VERSION % 10000) / 100) +#endif -#include // not -#include // size_t -#include // conditional, enable_if, false_type, integral_constant, is_constructible, is_integral, is_same, remove_cv, remove_reference, true_type +#if defined(JSON_HEDLEY_ARM_VERSION_CHECK) + #undef JSON_HEDLEY_ARM_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_ARM_VERSION) + #define JSON_HEDLEY_ARM_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_ARM_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_ARM_VERSION_CHECK(major,minor,patch) (0) +#endif -namespace nlohmann -{ -namespace detail -{ -// alias templates to reduce boilerplate -template -using enable_if_t = typename std::enable_if::type; +#if defined(JSON_HEDLEY_IBM_VERSION) + #undef JSON_HEDLEY_IBM_VERSION +#endif +#if defined(__ibmxl__) + #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ibmxl_version__, __ibmxl_release__, __ibmxl_modification__) +#elif defined(__xlC__) && defined(__xlC_ver__) + #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__xlC__ >> 8, __xlC__ & 0xff, (__xlC_ver__ >> 8) & 0xff) +#elif defined(__xlC__) + #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__xlC__ >> 8, __xlC__ & 0xff, 0) +#endif -template -using uncvref_t = typename std::remove_cv::type>::type; +#if defined(JSON_HEDLEY_IBM_VERSION_CHECK) + #undef JSON_HEDLEY_IBM_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_IBM_VERSION) + #define JSON_HEDLEY_IBM_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_IBM_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_IBM_VERSION_CHECK(major,minor,patch) (0) +#endif -// implementation of C++14 index_sequence and affiliates -// source: https://stackoverflow.com/a/32223343 -template -struct index_sequence -{ - using type = index_sequence; - using value_type = std::size_t; - static constexpr std::size_t size() noexcept - { - return sizeof...(Ints); - } -}; +#if defined(JSON_HEDLEY_TI_VERSION) + #undef JSON_HEDLEY_TI_VERSION +#endif +#if \ + defined(__TI_COMPILER_VERSION__) && \ + ( \ + defined(__TMS470__) || defined(__TI_ARM__) || \ + defined(__MSP430__) || \ + defined(__TMS320C2000__) \ + ) +#if (__TI_COMPILER_VERSION__ >= 16000000) + #define JSON_HEDLEY_TI_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) +#endif +#endif -template -struct merge_and_renumber; +#if defined(JSON_HEDLEY_TI_VERSION_CHECK) + #undef JSON_HEDLEY_TI_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TI_VERSION) + #define JSON_HEDLEY_TI_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TI_VERSION_CHECK(major,minor,patch) (0) +#endif -template -struct merge_and_renumber, index_sequence> - : index_sequence < I1..., (sizeof...(I1) + I2)... > {}; +#if defined(JSON_HEDLEY_TI_CL2000_VERSION) + #undef JSON_HEDLEY_TI_CL2000_VERSION +#endif +#if defined(__TI_COMPILER_VERSION__) && defined(__TMS320C2000__) + #define JSON_HEDLEY_TI_CL2000_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) +#endif -template -struct make_index_sequence - : merge_and_renumber < typename make_index_sequence < N / 2 >::type, - typename make_index_sequence < N - N / 2 >::type > {}; +#if defined(JSON_HEDLEY_TI_CL2000_VERSION_CHECK) + #undef JSON_HEDLEY_TI_CL2000_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TI_CL2000_VERSION) + #define JSON_HEDLEY_TI_CL2000_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL2000_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TI_CL2000_VERSION_CHECK(major,minor,patch) (0) +#endif -template<> struct make_index_sequence<0> : index_sequence<> {}; -template<> struct make_index_sequence<1> : index_sequence<0> {}; +#if defined(JSON_HEDLEY_TI_CL430_VERSION) + #undef JSON_HEDLEY_TI_CL430_VERSION +#endif +#if defined(__TI_COMPILER_VERSION__) && defined(__MSP430__) + #define JSON_HEDLEY_TI_CL430_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) +#endif -template -using index_sequence_for = make_index_sequence; +#if defined(JSON_HEDLEY_TI_CL430_VERSION_CHECK) + #undef JSON_HEDLEY_TI_CL430_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TI_CL430_VERSION) + #define JSON_HEDLEY_TI_CL430_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL430_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TI_CL430_VERSION_CHECK(major,minor,patch) (0) +#endif -// dispatch utility (taken from ranges-v3) -template struct priority_tag : priority_tag < N - 1 > {}; -template<> struct priority_tag<0> {}; +#if defined(JSON_HEDLEY_TI_ARMCL_VERSION) + #undef JSON_HEDLEY_TI_ARMCL_VERSION +#endif +#if defined(__TI_COMPILER_VERSION__) && (defined(__TMS470__) || defined(__TI_ARM__)) + #define JSON_HEDLEY_TI_ARMCL_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) +#endif -// taken from ranges-v3 -template -struct static_const -{ - static constexpr T value{}; -}; +#if defined(JSON_HEDLEY_TI_ARMCL_VERSION_CHECK) + #undef JSON_HEDLEY_TI_ARMCL_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TI_ARMCL_VERSION) + #define JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_ARMCL_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(major,minor,patch) (0) +#endif -template -constexpr T static_const::value; -} // namespace detail -} // namespace nlohmann +#if defined(JSON_HEDLEY_TI_CL6X_VERSION) + #undef JSON_HEDLEY_TI_CL6X_VERSION +#endif +#if defined(__TI_COMPILER_VERSION__) && defined(__TMS320C6X__) + #define JSON_HEDLEY_TI_CL6X_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) +#endif -// #include +#if defined(JSON_HEDLEY_TI_CL6X_VERSION_CHECK) + #undef JSON_HEDLEY_TI_CL6X_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TI_CL6X_VERSION) + #define JSON_HEDLEY_TI_CL6X_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL6X_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TI_CL6X_VERSION_CHECK(major,minor,patch) (0) +#endif +#if defined(JSON_HEDLEY_TI_CL7X_VERSION) + #undef JSON_HEDLEY_TI_CL7X_VERSION +#endif +#if defined(__TI_COMPILER_VERSION__) && defined(__C7000__) + #define JSON_HEDLEY_TI_CL7X_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) +#endif -#include // not -#include // numeric_limits -#include // false_type, is_constructible, is_integral, is_same, true_type -#include // declval +#if defined(JSON_HEDLEY_TI_CL7X_VERSION_CHECK) + #undef JSON_HEDLEY_TI_CL7X_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TI_CL7X_VERSION) + #define JSON_HEDLEY_TI_CL7X_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL7X_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TI_CL7X_VERSION_CHECK(major,minor,patch) (0) +#endif -// #include +#if defined(JSON_HEDLEY_TI_CLPRU_VERSION) + #undef JSON_HEDLEY_TI_CLPRU_VERSION +#endif +#if defined(__TI_COMPILER_VERSION__) && defined(__PRU__) + #define JSON_HEDLEY_TI_CLPRU_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) +#endif +#if defined(JSON_HEDLEY_TI_CLPRU_VERSION_CHECK) + #undef JSON_HEDLEY_TI_CLPRU_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TI_CLPRU_VERSION) + #define JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CLPRU_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(major,minor,patch) (0) +#endif -#include // random_access_iterator_tag +#if defined(JSON_HEDLEY_CRAY_VERSION) + #undef JSON_HEDLEY_CRAY_VERSION +#endif +#if defined(_CRAYC) + #if defined(_RELEASE_PATCHLEVEL) + #define JSON_HEDLEY_CRAY_VERSION JSON_HEDLEY_VERSION_ENCODE(_RELEASE_MAJOR, _RELEASE_MINOR, _RELEASE_PATCHLEVEL) + #else + #define JSON_HEDLEY_CRAY_VERSION JSON_HEDLEY_VERSION_ENCODE(_RELEASE_MAJOR, _RELEASE_MINOR, 0) + #endif +#endif -// #include +#if defined(JSON_HEDLEY_CRAY_VERSION_CHECK) + #undef JSON_HEDLEY_CRAY_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_CRAY_VERSION) + #define JSON_HEDLEY_CRAY_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_CRAY_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_CRAY_VERSION_CHECK(major,minor,patch) (0) +#endif +#if defined(JSON_HEDLEY_IAR_VERSION) + #undef JSON_HEDLEY_IAR_VERSION +#endif +#if defined(__IAR_SYSTEMS_ICC__) + #if __VER__ > 1000 + #define JSON_HEDLEY_IAR_VERSION JSON_HEDLEY_VERSION_ENCODE((__VER__ / 1000000), ((__VER__ / 1000) % 1000), (__VER__ % 1000)) + #else + #define JSON_HEDLEY_IAR_VERSION JSON_HEDLEY_VERSION_ENCODE(__VER__ / 100, __VER__ % 100, 0) + #endif +#endif -namespace nlohmann -{ -namespace detail -{ -template struct make_void -{ - using type = void; -}; -template using void_t = typename make_void::type; -} // namespace detail -} // namespace nlohmann +#if defined(JSON_HEDLEY_IAR_VERSION_CHECK) + #undef JSON_HEDLEY_IAR_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_IAR_VERSION) + #define JSON_HEDLEY_IAR_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_IAR_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_IAR_VERSION_CHECK(major,minor,patch) (0) +#endif -// #include +#if defined(JSON_HEDLEY_TINYC_VERSION) + #undef JSON_HEDLEY_TINYC_VERSION +#endif +#if defined(__TINYC__) + #define JSON_HEDLEY_TINYC_VERSION JSON_HEDLEY_VERSION_ENCODE(__TINYC__ / 1000, (__TINYC__ / 100) % 10, __TINYC__ % 100) +#endif +#if defined(JSON_HEDLEY_TINYC_VERSION_CHECK) + #undef JSON_HEDLEY_TINYC_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TINYC_VERSION) + #define JSON_HEDLEY_TINYC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TINYC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TINYC_VERSION_CHECK(major,minor,patch) (0) +#endif -namespace nlohmann -{ -namespace detail -{ -template -struct iterator_types {}; +#if defined(JSON_HEDLEY_DMC_VERSION) + #undef JSON_HEDLEY_DMC_VERSION +#endif +#if defined(__DMC__) + #define JSON_HEDLEY_DMC_VERSION JSON_HEDLEY_VERSION_ENCODE(__DMC__ >> 8, (__DMC__ >> 4) & 0xf, __DMC__ & 0xf) +#endif -template -struct iterator_types < - It, - void_t> -{ - using difference_type = typename It::difference_type; - using value_type = typename It::value_type; - using pointer = typename It::pointer; - using reference = typename It::reference; - using iterator_category = typename It::iterator_category; -}; +#if defined(JSON_HEDLEY_DMC_VERSION_CHECK) + #undef JSON_HEDLEY_DMC_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_DMC_VERSION) + #define JSON_HEDLEY_DMC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_DMC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_DMC_VERSION_CHECK(major,minor,patch) (0) +#endif -// This is required as some compilers implement std::iterator_traits in a way that -// doesn't work with SFINAE. See https://github.com/nlohmann/json/issues/1341. -template -struct iterator_traits -{ -}; +#if defined(JSON_HEDLEY_COMPCERT_VERSION) + #undef JSON_HEDLEY_COMPCERT_VERSION +#endif +#if defined(__COMPCERT_VERSION__) + #define JSON_HEDLEY_COMPCERT_VERSION JSON_HEDLEY_VERSION_ENCODE(__COMPCERT_VERSION__ / 10000, (__COMPCERT_VERSION__ / 100) % 100, __COMPCERT_VERSION__ % 100) +#endif -template -struct iterator_traits < T, enable_if_t < !std::is_pointer::value >> - : iterator_types -{ -}; +#if defined(JSON_HEDLEY_COMPCERT_VERSION_CHECK) + #undef JSON_HEDLEY_COMPCERT_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_COMPCERT_VERSION) + #define JSON_HEDLEY_COMPCERT_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_COMPCERT_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_COMPCERT_VERSION_CHECK(major,minor,patch) (0) +#endif -template -struct iterator_traits::value>> -{ - using iterator_category = std::random_access_iterator_tag; - using value_type = T; - using difference_type = ptrdiff_t; - using pointer = T*; - using reference = T&; -}; -} // namespace detail -} // namespace nlohmann +#if defined(JSON_HEDLEY_PELLES_VERSION) + #undef JSON_HEDLEY_PELLES_VERSION +#endif +#if defined(__POCC__) + #define JSON_HEDLEY_PELLES_VERSION JSON_HEDLEY_VERSION_ENCODE(__POCC__ / 100, __POCC__ % 100, 0) +#endif -// #include +#if defined(JSON_HEDLEY_PELLES_VERSION_CHECK) + #undef JSON_HEDLEY_PELLES_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_PELLES_VERSION) + #define JSON_HEDLEY_PELLES_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_PELLES_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_PELLES_VERSION_CHECK(major,minor,patch) (0) +#endif -// #include +#if defined(JSON_HEDLEY_MCST_LCC_VERSION) + #undef JSON_HEDLEY_MCST_LCC_VERSION +#endif +#if defined(__LCC__) && defined(__LCC_MINOR__) + #define JSON_HEDLEY_MCST_LCC_VERSION JSON_HEDLEY_VERSION_ENCODE(__LCC__ / 100, __LCC__ % 100, __LCC_MINOR__) +#endif -// #include +#if defined(JSON_HEDLEY_MCST_LCC_VERSION_CHECK) + #undef JSON_HEDLEY_MCST_LCC_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_MCST_LCC_VERSION) + #define JSON_HEDLEY_MCST_LCC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_MCST_LCC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_MCST_LCC_VERSION_CHECK(major,minor,patch) (0) +#endif +#if defined(JSON_HEDLEY_GCC_VERSION) + #undef JSON_HEDLEY_GCC_VERSION +#endif +#if \ + defined(JSON_HEDLEY_GNUC_VERSION) && \ + !defined(__clang__) && \ + !defined(JSON_HEDLEY_INTEL_VERSION) && \ + !defined(JSON_HEDLEY_PGI_VERSION) && \ + !defined(JSON_HEDLEY_ARM_VERSION) && \ + !defined(JSON_HEDLEY_CRAY_VERSION) && \ + !defined(JSON_HEDLEY_TI_VERSION) && \ + !defined(JSON_HEDLEY_TI_ARMCL_VERSION) && \ + !defined(JSON_HEDLEY_TI_CL430_VERSION) && \ + !defined(JSON_HEDLEY_TI_CL2000_VERSION) && \ + !defined(JSON_HEDLEY_TI_CL6X_VERSION) && \ + !defined(JSON_HEDLEY_TI_CL7X_VERSION) && \ + !defined(JSON_HEDLEY_TI_CLPRU_VERSION) && \ + !defined(__COMPCERT__) && \ + !defined(JSON_HEDLEY_MCST_LCC_VERSION) + #define JSON_HEDLEY_GCC_VERSION JSON_HEDLEY_GNUC_VERSION +#endif -#include +#if defined(JSON_HEDLEY_GCC_VERSION_CHECK) + #undef JSON_HEDLEY_GCC_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_GCC_VERSION) + #define JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_GCC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) (0) +#endif -// #include +#if defined(JSON_HEDLEY_HAS_ATTRIBUTE) + #undef JSON_HEDLEY_HAS_ATTRIBUTE +#endif +#if \ + defined(__has_attribute) && \ + ( \ + (!defined(JSON_HEDLEY_IAR_VERSION) || JSON_HEDLEY_IAR_VERSION_CHECK(8,5,9)) \ + ) +# define JSON_HEDLEY_HAS_ATTRIBUTE(attribute) __has_attribute(attribute) +#else +# define JSON_HEDLEY_HAS_ATTRIBUTE(attribute) (0) +#endif +#if defined(JSON_HEDLEY_GNUC_HAS_ATTRIBUTE) + #undef JSON_HEDLEY_GNUC_HAS_ATTRIBUTE +#endif +#if defined(__has_attribute) + #define JSON_HEDLEY_GNUC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_HAS_ATTRIBUTE(attribute) +#else + #define JSON_HEDLEY_GNUC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) +#endif -// http://en.cppreference.com/w/cpp/experimental/is_detected -namespace nlohmann -{ -namespace detail -{ -struct nonesuch -{ - nonesuch() = delete; - ~nonesuch() = delete; - nonesuch(nonesuch const&) = delete; - nonesuch(nonesuch const&&) = delete; - void operator=(nonesuch const&) = delete; - void operator=(nonesuch&&) = delete; -}; +#if defined(JSON_HEDLEY_GCC_HAS_ATTRIBUTE) + #undef JSON_HEDLEY_GCC_HAS_ATTRIBUTE +#endif +#if defined(__has_attribute) + #define JSON_HEDLEY_GCC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_HAS_ATTRIBUTE(attribute) +#else + #define JSON_HEDLEY_GCC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif -template class Op, - class... Args> -struct detector -{ - using value_t = std::false_type; - using type = Default; -}; +#if defined(JSON_HEDLEY_HAS_CPP_ATTRIBUTE) + #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE +#endif +#if \ + defined(__has_cpp_attribute) && \ + defined(__cplusplus) && \ + (!defined(JSON_HEDLEY_SUNPRO_VERSION) || JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0)) + #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute) __has_cpp_attribute(attribute) +#else + #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute) (0) +#endif -template class Op, class... Args> -struct detector>, Op, Args...> -{ - using value_t = std::true_type; - using type = Op; -}; +#if defined(JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS) + #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS +#endif +#if !defined(__cplusplus) || !defined(__has_cpp_attribute) + #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) (0) +#elif \ + !defined(JSON_HEDLEY_PGI_VERSION) && \ + !defined(JSON_HEDLEY_IAR_VERSION) && \ + (!defined(JSON_HEDLEY_SUNPRO_VERSION) || JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0)) && \ + (!defined(JSON_HEDLEY_MSVC_VERSION) || JSON_HEDLEY_MSVC_VERSION_CHECK(19,20,0)) + #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) JSON_HEDLEY_HAS_CPP_ATTRIBUTE(ns::attribute) +#else + #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) (0) +#endif -template