internal TObject BuildObject <TObject>(string inputString, string rootLabel, int maxRewriteIterations = 100000) { var database = new TermDatabase(); var result = _parser.ParseToAst(inputString); if (!result.Succeed) { throw new Exception(string.Join(Environment.NewLine, result.Errors)); } database.Writer.StoreStatements(result.Statements); database.ExecuteRewriteRules(maxRewriteIterations); var statementList = database.Reader.ReadStatementsForLabel(rootLabel); if (statementList == default || statementList.Statements.Count == 0) { return(default);
public void ShouldLoadAndApplyRewriteRules() { // Arrange var parseResult = _parser.ParseToAst("root: a(1); a(1) => a(2); a(2) => a(3);"); if (!parseResult.Succeed) { throw new Exception(parseResult.Errors.First()); } // Act _termDatabase.Writer.StoreStatements(parseResult.Statements); _termDatabase.ExecuteRewriteRules(); // Assert var s = _termDatabase.Reader.ReadStatementsForLabel("root"); Assert.NotNull(s); Assert.Single(s.Statements); Assert.True(StringComparer.InvariantCulture.Equals("root: a(3);", s.Statements.Single().ToSourceCode())); }
static void Main() { var input = "0; 0 => inc(0);"; // Parse input var parser = new TrlParser(); var parseResult = parser.ParseToAst(input); if (!parseResult.Succeed) { Console.WriteLine("Syntax error."); return; } // Execute substitutions var termDatabase = new TermDatabase(); termDatabase.Writer.StoreStatements(parseResult.Statements); // Track changes termDatabase.Writer.SetTermReplacementObserver(replacement => { var originalTerm = replacement.OriginalRootTerm.ToSourceCode(termDatabase); var newTerm = replacement.NewRootTerm.ToSourceCode(termDatabase); Console.WriteLine($"{replacement.RewriteIteration}> Replaced {originalTerm} with {newTerm}"); }); // Execute the rewrite rules termDatabase.ExecuteRewriteRules(4); // Print output Console.WriteLine(); Console.WriteLine("Output:"); var output = termDatabase.Reader.ReadCurrentFrame(); Console.WriteLine(output.ToSourceCode(true)); }