From 7ccc1ae0c9271e296a22684a9f23e0f567ec635b Mon Sep 17 00:00:00 2001 From: NeilKleistGao Date: Thu, 9 Jan 2025 11:03:18 +0800 Subject: [PATCH] WIP: Add parser structure --- Src/Parser/ParseResults.cs | 20 ++++++++++++--- Src/Parser/Parser.cs | 50 +++++++++++++++++++++++++++++++++++--- 2 files changed, 63 insertions(+), 7 deletions(-) diff --git a/Src/Parser/ParseResults.cs b/Src/Parser/ParseResults.cs index e167793..b138be2 100644 --- a/Src/Parser/ParseResults.cs +++ b/Src/Parser/ParseResults.cs @@ -19,19 +19,31 @@ public TRes Evaluate(TEnv env) { } } - public abstract class Literal: IEvaluatable { - protected T Value; - + public abstract class Literal: IEvaluatable { public TRes Evaluate(TEnv env) { throw new NotImplementedException(); } } + public class IntLiteral : Literal { + public int Value { get; set; } + } + + public class NumberLiteral : Literal { + public double Value { get; set; } + } + + // TODO: more literals + public abstract class Symbol: IEvaluatable { private string name; public TRes Evaluate(TEnv env) { throw new NotImplementedException(); } + + public Symbol(string name) { + this.name = name; + } } -} // namespace Marionette.Parser \ No newline at end of file +} // namespace Marionette.Parser diff --git a/Src/Parser/Parser.cs b/Src/Parser/Parser.cs index 5e431fc..cb102c9 100644 --- a/Src/Parser/Parser.cs +++ b/Src/Parser/Parser.cs @@ -1,11 +1,55 @@ +using System; +using System.Collections; + namespace Marionette.Parser { - public class Parser { + public class Parser : IEnumerator> { private string code; private Utils.Position position; + private int pointer = -1; + + public delegate ResultList ListAllocator(IEvaluatable[] subterms); + + public delegate Literal LiteralAllocator(string text); + + public delegate Symbol SymbolAllocator(string name); - public Parser(string code) { + private ListAllocator allocateList; + private LiteralAllocator allocateLiteral; + private SymbolAllocator allocateSymbol; + + private IEvaluatable? curResult = null; + + public Parser(string code, ListAllocator allocateList, LiteralAllocator allocateLiteral, SymbolAllocator allocateSymbol) { this.code = code; - this.position = new Utils.Position(0, 1); + this.allocateList = allocateList; + this.allocateLiteral = allocateLiteral; + this.allocateSymbol = allocateSymbol; + position = new Utils.Position(0, 1); + } + + private IEvaluatable Parse() { + throw new NotImplementedException(); + } + + public IEvaluatable Current => curResult ?? (curResult = Parse()); + + object IEnumerator.Current => curResult ?? (curResult = Parse()); + + public void Dispose() {} + + public bool MoveNext() { + if (pointer >= code.Length) { + return false; + } + else { + curResult = Parse(); + return true; + } + } + + public void Reset() { + position = new Utils.Position(0, 1); + pointer = -1; } } } // namespace Marionette.Parser