Click here to Skip to main content
Click here to Skip to main content

Implementing Programming Languages Using C# 4.0

By , 12 Jul 2012
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace Diggins.Jigsaw
{
    public class ParserState
    {
        public string input;
        public int pos;
        public List<Node> nodes = new List<Node>();
        private Dictionary<int, Dictionary<Rule, Node>> cache = new Dictionary<int,Dictionary<Rule, Node>>();

        public string Current
        {
            get { return input.Substring(pos); }
        }
        public ParserState Clone()
        {
            return new ParserState { 
                input = input, 
                pos = pos, 
                nodes = new List<Node>(nodes) };
        }
        public void Assign(ParserState state)
        {
            input = state.input; 
            pos = state.pos; 
            nodes = state.nodes;
        }
        public void RestoreAfter(Action action)
        {
            var state = Clone(); 
            action(); 
            Assign(state);
        }
        public override string ToString()
        {
            return String.Format("{0}/{1}", pos, input.Length);
        }
        public void CacheResult(Rule rule, int pos, Node node)
        {
            if (!cache.ContainsKey(pos)) 
                cache.Add(pos, new Dictionary<Rule, Node>());
            var tmp = cache[pos];
            if (!tmp.ContainsKey(rule))
                tmp.Add(rule, node);
        }
        public bool GetCachedResult(NodeRule rule, out Node node)
        {
            node = null;
            if (!cache.ContainsKey(pos))
                return false;
            if (cache[pos].ContainsKey(rule))
            {
                node = cache[pos][rule];
                return true;
            }
            return false;
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of use and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The MIT License

About the Author

Christopher Diggins
Software Developer Autodesk
Canada Canada
Member
This article was written by Christopher Diggins, a computer science nerd who currently works at Autodesk as an SDK specialist.

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130516.1 | Last Updated 12 Jul 2012
Article Copyright 2011 by Christopher Diggins
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid