Cascaded Neurosymbolic Code Generation for Niche DSLs: Preserving Chain-of-Thought in Grammar-Constrained Decoding
Abstract
1. Introduction
1.1. Contributions
- 1.
- Think-Then-Constrain Decoding: Rather than applying an “all-or-nothing” Grammar-Constrained Decoding (GCD) mask from the first token, which physically prevents models from utilizing <think> reasoning blocks and causes semantic collapse, our approach temporarily suspends the finite-state machine (FSM) mask to allow unconstrained semantic planning, activating it strictly for the code generation block.
- 2.
- Deterministic Syntax Repair: Standard automated program repair methods are probabilistic, asking the LLM to “guess” the syntax again upon failure, which traps small models in hallucination loops on niche DSLs. Instead, our method acts as a deterministic syntax repair engine: if an initial draft fails, we preserve the successful semantic blueprint (the <think> block) and use the FSM mask to forcefully align that exact intent into correct syntax.
- 3.
- Compiler-Routed Optimistic Bypassing: Most compiler-guided frameworks use compilers as textual prompt feedback or delayed reinforcement learning rewards. In contrast, our architecture utilizes the native compiler as a structural router. It allows the system to attempt a fast, unconstrained generation path, triggering the computationally heavy FSM masking overhead only when the compiler detects a structural hallucination.
- We identify and empirically demonstrate the “Semantic–Syntax Trade-off” in modern reasoning LLMs, showing how strict Grammar-Constrained Decoding disrupts Chain-of-Thought planning and induces semantic dead-ends in niche DSLs.
- We present a novel Dual-Phase Cascaded Framework that implements Optimistic Bypassing: By preserving unconstrained reasoning from a failed draft and using it to guide a strict GCD fallback, our architecture effectively utilizes the symbolic grammar as a localized syntax repair engine.
- We construct and openly release a comprehensive benchmark dataset comprising 100 natural language to MiniZinc constraint programming tasks of varying complexities.
- We conduct a rigorous empirical evaluation using a metric, scored by a strict semantic LLM judge and native compiler. Our results demonstrate that the dual-phase “think-then-constrain” approach significantly outperforms zero-shot, pure few-shot, and pure GCD baselines for unseen DSL code generation.
1.2. Structure of the Paper
2. Previous Work
3. Methodology
3.1. In-Context Symbolic Grounding
3.2. Phase 1: Unconstrained Reasoning and Optimistic Bypassing
- 1.
- Syntactic Gate: A fast Context-Free Grammar parser (e.g., Lark) verifies that the generated string perfectly conforms to the EBNF structure.
- 2.
- Semantic Gate: The draft is passed to the native DSL compiler in type-checking mode. Because the compiler evaluates the code globally, it instantly flags any type mismatches, uninitialized variables, or invalid operator overloads.
3.3. Phase 2: Grammar-Constrained Syntax Repair
3.4. Algorithmic Formalization
| Algorithm 1 Dual-Phase Cascaded Neurosymbolic Generation |
|
4. Empirical Evaluation
4.1. Benchmark Dataset Construction
- (i)
- Basic declarations and simple constraints: e.g., finding integers within bounds or strict equality.
- (ii)
- Complex arithmetic and aggregations: e.g., modulo operations, division, and compound mathematical limits.
- (iii)
- Advanced data structures (arrays and sets): e.g., declaring arrays of specific sizes, subset domains, and applying the sum() aggregator.
- (iv)
- Logical expressions and implications: e.g., boolean logic, either/or constraints, and strict implications (if/then).
- (v)
- Optimization: e.g., constrained minimization or maximization objectives.

4.2. Experimental Setup and Baselines
- Baseline 1: Zero-Shot Autoregressive
- Baseline 2: One-Shot (Unconstrained)
- Baseline 3: One-Shot (GCD Only)
- Baseline 4: One-Shot (CoT + Always GCD)
- Proposed Method: Dual-Phase Cascaded GCD
4.3. Evaluation Metrics: and Automated Semantic Judging
- 1.
- Syntactic Gate: The generated string must be successfully parsed by the formal Lark CFG parser, verifying absolute structural compliance. This ensures syntactic validity: The code mathematically conforms to the raw derivation rules of the Context-Free Grammar (EBNF), regardless of whether the variables are declared or typed correctly.
- 2.
- Semantic Compiler Gate: The code is passed to the native MiniZinc compiler using the –model-check-only flag). This ensures compiler validity (static semantics): The code is not only syntactically valid but also adheres to the formal domain rules of the language (e.g., proper scoping, no uninitialized variables, correct type matching between booleans and integers). It represents code that is legally executable by the system. This deterministic check instantly rejects uninitialized variables, out-of-bounds array accesses, and semantic type mismatches.
- 3.
- Functional Intent Gate (LLM-as-a-Judge): Because code can compile perfectly but fail to solve the requested problem, we implement a strict semantic judge. This addresses dynamic semantics: While static semantic validity ensures the code means something legal, dynamic semantic validity ensures it means exactly what the user intended (e.g., maximizing a variable instead of minimizing it). For this purpose, we employ a larger, independent local model (Qwen3.5) via Ollama and prompted with a highly strict CoT evaluation rubric. The judge compares the generated code against the golden solution from the benchmark, analyzing variable mapping, constraint logic, and optimization directions. The judge returns a normalized score between and ; a candidate is only marked as successful if it achieves a score of . This threshold was empirically selected to act as a strict, high-confidence filter. It safely absorbs the minor fractional noise inherent to the neural evaluation of stylistic differences, while remaining high enough to rigorously reject any code that violates the functional intent of the prompt. To ensure the LLM-as-a-judge operates deterministically, the judging model (Qwen3.5) is queried with the decoding temperature strictly set to (greedy decoding). Furthermore, to minimize the inherent variance of neural evaluation, the judge does not evaluate the generated code in isolation. Instead, it is provided with the verified golden solution from the benchmark and prompted with a strict rubric to act as a direct equivalence checker. This grounds the LLM’s evaluation and ensures the scores are highly stable and reproducible across runs.
4.4. Results and Discussion
| Method | pass@1 | pass@3 | pass@5 | |||
|---|---|---|---|---|---|---|
| Zero-Shot | 11.0 | +263.6% | 21.0 | +223.8% | 29.0 | +165.5% |
| One-Shot (No GCD) | 12.0 | +233.3% | 15.0 | +353.3% | 16.0 | +381.2% |
| One-Shot (GCD Only) | 11.0 | +263.6% | 17.0 | +300.0% | 22.0 | +250.0% |
| One-Shot (CoT + GCD) | 36.0 | +11.1% | 64.0 | +6.2% | 71.0 | +8.5% |
| Dual-Phase (Proposed) | 40.0 | - | 68.0 | - | 77.0 | - |
4.4.1. The Semantic Collapse of Strict GCD
4.4.2. Unconstrained Reasoning vs. Zero-Shot Pre-Training
4.4.3. The Efficacy of the Dual-Phase Architecture
4.4.4. Scaling with Sampling Diversity ()
4.4.5. Computational Overhead and the Small-Model Paradox
4.4.6. Internal Routing Analytics and the Value of Optimistic Bypassing
4.4.7. Categorization of Persistent Errors
- Pure Syntax Errors: These occur when the model hallucinates invalid tokens, misplaced punctuation, or undefined operators, resulting in a failure at our first evaluation gate (the CFG parser), while the unconstrained baselines suffer notably from these errors, the Phase 2 Grammar-Constrained Decoding (GCD) fallback in our proposed architecture largely eliminates them.
- Structural/Schema Errors: These denote code that is syntactically well-formed but violates the formal typing or scoping rules of the domain, failing our second gate (the native MiniZinc compiler check). In our qualitative analysis, these predominantly manifest as Deep Nesting Fatigue: When generating deeply nested Abstract Syntax Trees (e.g., complex recursive constraints or logical implications), the LLM’s attention mechanism occasionally degrades. The model loses track of variable scopes or strict type requirements, resulting in structurally illegal operations (e.g., assigning an array to a scalar value) that the FSM allows but the compiler rightfully rejects.
- Semantic Logic Errors: These represent candidate models that compile perfectly but fail to execute the user’s specific functional intent, thereby failing our third gate (the semantic LLM-as-a-judge). Our analysis identified two primary drivers for these failures:
- ‑
- Semantic Drift in Ambiguous Contexts: While the GCD engine tracks ambiguous grammars by allowing the union of valid tokens, the LLM itself occasionally struggles to resolve this ambiguity functionally. The model may select a syntactically valid but unintended derivation path (e.g., applying an arithmetic operator instead of a logical one), producing code that works but solves the wrong problem.
- ‑
- Implicit Type Coercion/Logical Hallucinations: The model occasionally generates constraints that exploit native compiler allowances. For instance, MiniZinc allows certain implicit type coercions (e.g., evaluating a boolean as an integer). If the LLM generates a constraint exploiting this, it bypasses the compiler’s safety check but represents a fundamental logical failure in translating the specific data types requested in the natural language prompt.
- 1.
- The Eradication of Syntax Errors and Regex Artifacts:
- 2.
- The GCD Schema Explosion and CoT Rescue:
- 3.
- Shifting the Frontier to Semantic Logic:
4.4.8. Effectiveness by Difficulty
4.4.9. Effectiveness by Task Category
5. Conclusions and Future Work
5.1. Limitations and Threats to Validity
5.2. Future Research Directions
Author Contributions
Funding
Institutional Review Board Statement
Informed Consent Statement
Data Availability Statement
Acknowledgments
Conflicts of Interest
References
- Shafee, S.; Bessani, A.; Ferreira, P.M. Evaluation of LLM-based chatbots for OSINT-based Cyber Threat Awareness. Expert Syst. Appl. 2025, 261, 125509. [Google Scholar] [CrossRef] [Scilit]
- Chen, M.; Tworek, J.; Jun, H.; Yuan, Q.; Pinto, H.P.d.O.; Kaplan, J.; Edwards, H.; Burda, Y.; Joseph, N.; Brockman, G.; et al. Evaluating Large Language Models Trained on Code. arXiv 2021, arXiv:2107.03374. [Google Scholar]
- Rozière, B.; Gehring, J.; Gloeckle, F.; Sootla, S.; Gat, I.; Tan, X.E.; Adi, Y.; Liu, J.; Sauvestre, R.; Remez, T.; et al. Code Llama: Open Foundation Models for Code. arXiv 2023, arXiv:2308.12950. [Google Scholar]
- Nethercote, N.; Stuckey, P.J.; Becket, R.; Brand, S.; Duck, G.J.; Tack, G. MiniZinc: Towards a Standard CP Modelling Language. In Principles and Practice of Constraint Programming—CP 2007; Bessière, C., Ed.; Springer: Berlin/Heidelberg, Germany, 2007; pp. 529–543. [Google Scholar] [CrossRef] [Scilit]
- Poesia, G.; Polozov, A.; Le, V.; Tiwari, A.; Soares, G.; Meek, C.; Gulwani, S. Synchromesh: Reliable Code Generation from Pre-trained Language Models. In Proceedings of the International Conference on Learning Representations ICLR 2022, Virtual, 25–29 April 2022. [Google Scholar]
- Willard, B.T.; Louf, R. Efficient Guided Generation for Large Language Models. arXiv 2023, arXiv:2307.09702. [Google Scholar]
- Wei, J.; Wang, X.; Schuurmans, D.; Bosma, M.; Ichter, B.; Xia, F.; Chi, E.; Le, Q.V.; Zhou, D. Chain of Thought Prompting Elicits Reasoning in Large Language Models. In Proceedings of the Advances in Neural Information Processing Systems, New Orleans, LA, USA, 28 November–9 December 2022. [Google Scholar]
- Yao, S.; Yu, D.; Zhao, J.; Shafran, I.; Griffiths, T.L.; Cao, Y.; Narasimhan, K.R. Tree of Thoughts: Deliberate Problem Solving with Large Language Models. In Proceedings of the Thirty-Seventh Conference on Neural Information Processing Systems, New Orleans, LA, USA, 10–16 December 2023. [Google Scholar]
- Xue, T.; Li, X.; Azim, T.; Smirnov, R.; Yu, J.; Sadrieh, A.; Pahlavan, B. Multi-Programming Language Ensemble for Code Generation in Large Language Model. arXiv 2024, arXiv:2409.0411. [Google Scholar]
- Sarker, L.; Downing, M.; Desai, A.; Bultan, T. Assessing, Exploiting, and Mitigating Syntactic Robustness Failures in LLM-Based Code Generation. arXiv 2026, arXiv:2404.01535. [Google Scholar] [CrossRef] [Scilit]
- Liang, Q.; Zhang, Z.; Sun, Z.; Lin, Z.; Luo, Q.; Xiao, Y.; Chen, Y.; Zhang, Y.; Zhang, H.; Zhang, L.; et al. Grammar-Based Code Representation: Is It a Worthy Pursuit for LLMs? In Findings of the Association for Computational Linguistics: ACL 2025; Che, W., Nabende, J., Shutova, E., Pilehvar, M.T., Eds.; Association for Computational Linguistics: Vienna, Austria, 2025; pp. 15640–15653. [Google Scholar] [CrossRef] [Scilit]
- Thakur, S.; Ahmad, B.; Fan, Z.; Pearce, H.; Tan, B.; Karri, R.; Dolan-Gavitt, B.; Garg, S. Benchmarking Large Language Models for Automated Verilog RTL Code Generation. In Proceedings of the 2023 Design, Automation & Test in Europe Conference & Exhibition (DATE), Antwerp, Belgium, 17–19 April 2023; pp. 1–6. [Google Scholar] [CrossRef] [Scilit]
- Thakur, S.; Ahmad, B.; Pearce, H.; Tan, B.; Dolan-Gavitt, B.; Karri, R.; Garg, S. VeriGen: A Large Language Model for Verilog Code Generation. Acm Trans. Des. Autom. Electron. Syst. 2024, 29, 46. [Google Scholar] [CrossRef] [Scilit]
- Bassamzadeh, N.; Methani, C. A Comparative Study of DSL Code Generation: Fine-Tuning vs. Optimized Retrieval Augmentation. arXiv 2024, arXiv:2407.02742. [Google Scholar] [CrossRef] [Scilit]
- Fu, D.J.; Gupta, A.; Councilman, A.; Grove, D.; Wang, Y.X.; Adve, V. SLMFix: Leveraging Small Language Models for Error Fixing with Reinforcement Learning. arXiv 2025, arXiv:2511.19422. [Google Scholar] [CrossRef] [Scilit]
- Delgado, D.; Burgueño, L.; Clarisó, R. A framework for assessing the capabilities of code generation of constraint domain-specific languages with large language models. J. Syst. Softw. 2026, 238, 112871. [Google Scholar] [CrossRef] [Scilit]
- Shen, D.; Chen, X.; Wang, C.; Sen, K.; Song, D. Benchmarking Language Models for Code Syntax Understanding. In Proceedings of the Conference on Empirical Methods in Natural Language Processing; Association for Computational Linguistics: Abu Dhabi, United Arab Emirates, 2022. [Google Scholar]
- Song, Y.; Rajput, P.; Sun, T.; Ezzini, S.; Bissyandé, T.F.; Klein, J. Empirical Study for Structured Output Control in LLMs for Software Engineering. arXiv 2026, arXiv:2606.09395. [Google Scholar] [CrossRef] [Scilit]
- Mora, F.; Wong, J.; Lepe, H.; Bhatia, S.; Elmaaroufi, K.; Varghese, G.; Gonzalez, J.; Polgreen, E.; Seshia, S.A. Synthetic Programming Elicitation for Text-to-Code in Very Low-Resource Programming and Formal Languages. In Advances in Neural Information Processing Systems 37; Curran Associates Inc.: Red Hook, NY, USA, 2024. [Google Scholar]
- Gao, M.; Zhao, J.; Lin, Z.; Ding, W.; Hou, X.; Feng, Y.; Li, C.; Guo, M. AutoVCoder: A Systematic Framework for Automated Verilog Code Generation using LLMs. In Proceedings of the 2024 IEEE 42nd International Conference on Computer Design (ICCD), Milan, Italy, 18–20 November 2024; pp. 162–169. [Google Scholar]
- Lu, Y.; Liu, S.; Zhang, Q.; Xie, Z. RTLLM: An Open-Source Benchmark for Design RTL Generation with Large Language Model. In Proceedings of the 2024 29th Asia and South Pacific Design Automation Conference (ASP-DAC); IEEE Press: Piscataway, NJ, USA, 2023; pp. 722–727. [Google Scholar]
- Geng, S.; Josifoski, M.; Peyrard, M.; West, R. Grammar-Constrained Decoding for Structured NLP Tasks without Finetuning. In Proceedings of the 2023 Conference on Empirical Methods in Natural Language Processing; Bouamor, H., Pino, J., Bali, K., Eds.; Association for Computational Linguistics: Singapore, 2023; pp. 10932–10952. [Google Scholar] [CrossRef] [Scilit]
- Park, K.; Wang, J.; Berg-Kirkpatrick, T.; Polikarpova, N.; D’ Antoni, L. Grammar-Aligned Decoding. In Advances in Neural Information Processing Systems; Globerson, A., Mackey, L., Belgrave, D., Fan, A., Paquet, U., Tomczak, J., Zhang, C., Eds.; Curran Associates, Inc.: Red Hook, NY, USA, 2024; Volume 37, pp. 24547–24568. [Google Scholar] [CrossRef] [Scilit]
- Wen, H.; Zhu, Y.; Liu, C.; Ren, X.; Du, W.; Yan, M. Fixing Function-Level Code Generation Errors for Foundation Large Language Models. arXiv 2025, arXiv:2409.00676. [Google Scholar] [CrossRef] [Scilit]
- Liu, C.; Bao, X.; Zhang, H.; Zhang, N.; Hu, H.; Zhang, X.; Yan, M. Guiding ChatGPT for Better Code Generation: An Empirical Study. In Proceedings of the 2024 IEEE International Conference on Software Analysis, Evolution and Reengineering (SANER), Rovaniemi, Finland, 12–15 March 2024; pp. 102–113. [Google Scholar] [CrossRef] [Scilit]
- Albinhassan, M.; Madhyastha, P.; Russo, A. SEM-CTRL: Semantically Controlled Decoding. Transactions on Machine Learning Research. 2026. Available online: https://openreview.net/forum?id=ICUHKhOISN (accessed on 10 June 2026).
- Chen, X.; Lin, M.; Schärli, N.; Zhou, D. Teaching Large Language Models to Self-Debug. In Proceedings of the the Twelfth International Conference on Learning Representations; ICLR: Vienna, Austria, 7–11 May 2024. [Google Scholar]
- Shinn, N.; Cassano, F.; Gopinath, A.; Narasimhan, K.; Yao, S. Reflexion: Language agents with verbal reinforcement learning. In Advances in Neural Information Processing Systems; Oh, A., Naumann, T., Globerson, A., Saenko, K., Hardt, M., Levine, S., Eds.; Curran Associates, Inc.: New York, NY, USA, 2023; Volume 36, pp. 8634–8652. [Google Scholar]





| Method | Mean Time (s) | Time Std (s) | Mean Tokens | Tokens Std |
|---|---|---|---|---|
| Zero-Shot | 0.93 | 0.56 | 34.2 | 19.7 |
| One-Shot (No GCD) | 5.70 | 8.59 | 223.8 | 338.5 |
| One-Shot (GCD Only) | 2.44 | 0.26 | 30.4 | 7.9 |
| One-Shot (CoT + GCD) | 7.56 | 7.11 | 232.8 | 279.9 |
| Dual-Phase (Proposed) | 8.10 | 8.37 | 258.0 | 328.3 |
| Routing Metric | Rate (%) |
|---|---|
| Phase 2 Trigger Rate () | 81.6% |
| Conditional Success Rate () | 36.3% |
Disclaimer/Publisher’s Note: The statements, opinions and data contained in all publications are solely those of the individual author(s) and contributor(s) and not of MDPI and/or the editor(s). MDPI and/or the editor(s) disclaim responsibility for any injury to people or property resulting from any ideas, methods, instructions or products referred to in the content. |
© 2026 by the authors. Licensee MDPI, Basel, Switzerland. This article is an open access article distributed under the terms and conditions of the Creative Commons Attribution (CC BY) license.
Share and Cite
Ruiz-Torrubiano, R.; Buckchash, H.; Paudel, S.; Dhungana, D. Cascaded Neurosymbolic Code Generation for Niche DSLs: Preserving Chain-of-Thought in Grammar-Constrained Decoding. Software 2026, 5, 33. https://doi.org/10.3390/software5030033
Ruiz-Torrubiano R, Buckchash H, Paudel S, Dhungana D. Cascaded Neurosymbolic Code Generation for Niche DSLs: Preserving Chain-of-Thought in Grammar-Constrained Decoding. Software. 2026; 5(3):33. https://doi.org/10.3390/software5030033
Chicago/Turabian StyleRuiz-Torrubiano, Rubén, Himanshu Buckchash, Sarita Paudel, and Deepak Dhungana. 2026. "Cascaded Neurosymbolic Code Generation for Niche DSLs: Preserving Chain-of-Thought in Grammar-Constrained Decoding" Software 5, no. 3: 33. https://doi.org/10.3390/software5030033
APA StyleRuiz-Torrubiano, R., Buckchash, H., Paudel, S., & Dhungana, D. (2026). Cascaded Neurosymbolic Code Generation for Niche DSLs: Preserving Chain-of-Thought in Grammar-Constrained Decoding. Software, 5(3), 33. https://doi.org/10.3390/software5030033

