");
- }
-
- // Append position
- buffer.Append(" at position ");
- buffer.Append(_position);
-
- return buffer.ToString();
- }
- }
-}
diff --git a/src/Flee.NetStandard20/Parsing/grammatica-1.5.alpha2/PerCederberg.Grammatica.Runtime.RE/StringElement.cs b/src/Flee.NetStandard20/Parsing/grammatica-1.5.alpha2/PerCederberg.Grammatica.Runtime.RE/StringElement.cs
deleted file mode 100644
index d578e6f..0000000
--- a/src/Flee.NetStandard20/Parsing/grammatica-1.5.alpha2/PerCederberg.Grammatica.Runtime.RE/StringElement.cs
+++ /dev/null
@@ -1,71 +0,0 @@
-using System;
-using System.Collections;
-using System.Collections.Generic;
-using System.IO;
-using System.Diagnostics;
-
-
-namespace Flee.Parsing.grammatica_1._5.alpha2.PerCederberg.Grammatica.Runtime.RE
-{
- /**
- * A regular expression string element. This element only matches
- * an exact string. Once created, the string element is immutable.
- */
- internal class StringElement : Element
- {
- private readonly string _value;
- public StringElement(char c)
- : this(c.ToString())
- {
- }
-
- public StringElement(string str)
- {
- _value = str;
- }
-
- public string GetString()
- {
- return _value;
- }
-
- public override object Clone()
- {
- return this;
- }
-
- public override int Match(Matcher m,
- ReaderBuffer buffer,
- int start,
- int skip)
- {
- if (skip != 0)
- {
- return -1;
- }
- for (int i = 0; i < _value.Length; i++)
- {
- var c = buffer.Peek(start + i);
- if (c < 0)
- {
- m.SetReadEndOfString();
- return -1;
- }
- if (m.IsCaseInsensitive())
- {
- c = (int)Char.ToLower((char)c);
- }
- if (c != (int)_value[i])
- {
- return -1;
- }
- }
- return _value.Length;
- }
-
- public override void PrintTo(TextWriter output, string indent)
- {
- output.WriteLine(indent + "'" + _value + "'");
- }
- }
-}
diff --git a/src/Flee.NetStandard20/Parsing/grammatica-1.5.alpha2/PerCederberg.Grammatica.Runtime/Automaton.cs b/src/Flee.NetStandard20/Parsing/grammatica-1.5.alpha2/PerCederberg.Grammatica.Runtime/Automaton.cs
deleted file mode 100644
index 63f6452..0000000
--- a/src/Flee.NetStandard20/Parsing/grammatica-1.5.alpha2/PerCederberg.Grammatica.Runtime/Automaton.cs
+++ /dev/null
@@ -1,116 +0,0 @@
-using System;
-using System.Collections;
-using System.Collections.Generic;
-using System.Diagnostics;
-
-namespace Flee.Parsing.grammatica_1._5.alpha2.PerCederberg.Grammatica.Runtime
-{
- internal class Automaton
- {
- private object _value;
- private readonly AutomatonTree _tree = new AutomatonTree();
-
- public Automaton()
- {
- }
-
- public void AddMatch(string str, bool caseInsensitive, object value)
- {
- if (str.Length == 0)
- {
- this._value = value;
- }
- else
- {
- var state = _tree.Find(str[0], caseInsensitive);
- if (state == null)
- {
- state = new Automaton();
- state.AddMatch(str.Substring(1), caseInsensitive, value);
- _tree.Add(str[0], caseInsensitive, state);
- }
- else
- {
- state.AddMatch(str.Substring(1), caseInsensitive, value);
- }
- }
- }
-
- public object MatchFrom(LookAheadReader input, int pos, bool caseInsensitive)
- {
-
- object result = null;
- Automaton state = null;
- int c = 0;
-
- c = input.Peek(pos);
- if (_tree != null && c >= 0)
- {
- state = _tree.Find(Convert.ToChar(c), caseInsensitive);
- if (state != null)
- {
- result = state.MatchFrom(input, pos + 1, caseInsensitive);
- }
- }
- return result ?? _value;
- }
- }
-
- // * An automaton state transition tree. This class contains a
- // * binary search tree for the automaton transitions from one state
- // * to another. All transitions are linked to a single character.
- internal class AutomatonTree
- {
- private char _value;
- private Automaton _state;
- private AutomatonTree _left;
- private AutomatonTree _right;
-
- public AutomatonTree()
- {
- }
-
- public Automaton Find(char c, bool lowerCase)
- {
- if (lowerCase)
- {
- c = Char.ToLower(c);
- }
- if (_value == (char)0 || _value == c)
- {
- return _state;
- }
- else if (_value > c)
- {
- return _left.Find(c, false);
- }
- else
- {
- return _right.Find(c, false);
- }
- }
-
- public void Add(char c, bool lowerCase, Automaton state)
- {
- if (lowerCase)
- {
- c = Char.ToLower(c);
- }
- if (_value == (char)0)
- {
- this._value = c;
- this._state = state;
- this._left = new AutomatonTree();
- this._right = new AutomatonTree();
- }
- else if (_value > c)
- {
- _left.Add(c, false, state);
- }
- else
- {
- _right.Add(c, false, state);
- }
- }
- }
-}
diff --git a/src/Flee.NetStandard20/Parsing/grammatica-1.5.alpha2/PerCederberg.Grammatica.Runtime/LookAheadSet.cs b/src/Flee.NetStandard20/Parsing/grammatica-1.5.alpha2/PerCederberg.Grammatica.Runtime/LookAheadSet.cs
deleted file mode 100644
index 392f2da..0000000
--- a/src/Flee.NetStandard20/Parsing/grammatica-1.5.alpha2/PerCederberg.Grammatica.Runtime/LookAheadSet.cs
+++ /dev/null
@@ -1,592 +0,0 @@
-using System;
-using System.Collections;
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.Text;
-
-namespace Flee.Parsing.grammatica_1._5.alpha2.PerCederberg.Grammatica.Runtime
-{
- /*
- * A token look-ahead set. This class contains a set of token id
- * sequences. All sequences in the set are limited in length, so
- * that no single sequence is longer than a maximum value. This
- * class also filters out duplicates. Each token sequence also
- * contains a repeat flag, allowing the look-ahead set to contain
- * information about possible infinite repetitions of certain
- * sequences. That information is important when conflicts arise
- * between two look-ahead sets, as such a conflict cannot be
- * resolved if the conflicting sequences can be repeated (would
- * cause infinite loop).
- */
- internal class LookAheadSet
- {
- private readonly ArrayList _elements = new ArrayList();
- private readonly int _maxLength;
-
- public LookAheadSet(int maxLength)
- {
- this._maxLength = maxLength;
- }
-
- public LookAheadSet(int maxLength, LookAheadSet set)
- : this(maxLength)
- {
-
- AddAll(set);
- }
-
- public int Size()
- {
- return _elements.Count;
- }
-
- public int GetMinLength()
- {
- int min = -1;
-
- for (int i = 0; i < _elements.Count; i++)
- {
- var seq = (Sequence)_elements[i];
- if (min < 0 || seq.Length() < min)
- {
- min = seq.Length();
- }
- }
- return (min < 0) ? 0 : min;
- }
-
- public int GetMaxLength()
- {
- int max = 0;
- for (int i = 0; i < _elements.Count; i++)
- {
- var seq = (Sequence)_elements[i];
- if (seq.Length() > max)
- {
- max = seq.Length();
- }
- }
- return max;
- }
-
- public int[] GetInitialTokens()
- {
- ArrayList list = new ArrayList();
- int i;
- for (i = 0; i < _elements.Count; i++)
- {
- var token = ((Sequence)_elements[i]).GetToken(0);
- if (token != null && !list.Contains(token))
- {
- list.Add(token);
- }
- }
- var result = new int[list.Count];
- for (i = 0; i < list.Count; i++)
- {
- result[i] = (int)list[i];
- }
- return result;
- }
-
- public bool IsRepetitive()
- {
- for (int i = 0; i < _elements.Count; i++)
- {
- var seq = (Sequence)_elements[i];
- if (seq.IsRepetitive())
- {
- return true;
- }
- }
- return false;
- }
-
- public bool IsNext(Parser parser)
- {
- for (int i = 0; i < _elements.Count; i++)
- {
- var seq = (Sequence)_elements[i];
- if (seq.IsNext(parser))
- {
- return true;
- }
- }
- return false;
- }
-
- public bool IsNext(Parser parser, int length)
- {
- for (int i = 0; i < _elements.Count; i++)
- {
- var seq = (Sequence)_elements[i];
- if (seq.IsNext(parser, length))
- {
- return true;
- }
- }
- return false;
- }
-
- public bool IsOverlap(LookAheadSet set)
- {
- for (int i = 0; i < _elements.Count; i++)
- {
- if (set.IsOverlap((Sequence)_elements[i]))
- {
- return true;
- }
- }
- return false;
- }
-
- private bool IsOverlap(Sequence seq)
- {
- for (int i = 0; i < _elements.Count; i++)
- {
- var elem = (Sequence)_elements[i];
- if (seq.StartsWith(elem) || elem.StartsWith(seq))
- {
- return true;
- }
- }
- return false;
- }
-
- private bool Contains(Sequence elem)
- {
- return FindSequence(elem) != null;
- }
-
- public bool Intersects(LookAheadSet set)
- {
- for (int i = 0; i < _elements.Count; i++)
- {
- if (set.Contains((Sequence)_elements[i]))
- {
- return true;
- }
- }
- return false;
- }
-
- private Sequence FindSequence(Sequence elem)
- {
- for (int i = 0; i < _elements.Count; i++)
- {
- if (_elements[i].Equals(elem))
- {
- return (Sequence)_elements[i];
- }
- }
- return null;
- }
-
- private void Add(Sequence seq)
- {
- if (seq.Length() > _maxLength)
- {
- seq = new Sequence(_maxLength, seq);
- }
- if (!Contains(seq))
- {
- _elements.Add(seq);
- }
- }
-
- public void Add(int token)
- {
- Add(new Sequence(false, token));
- }
-
- public void AddAll(LookAheadSet set)
- {
- for (int i = 0; i < set._elements.Count; i++)
- {
- Add((Sequence)set._elements[i]);
- }
- }
-
- public void AddEmpty()
- {
- Add(new Sequence());
- }
-
- private void Remove(Sequence seq)
- {
- _elements.Remove(seq);
- }
-
- public void RemoveAll(LookAheadSet set)
- {
- for (int i = 0; i < set._elements.Count; i++)
- {
- Remove((Sequence)set._elements[i]);
- }
- }
-
- public LookAheadSet CreateNextSet(int token)
- {
- LookAheadSet result = new LookAheadSet(_maxLength - 1);
- for (int i = 0; i < _elements.Count; i++)
- {
- var seq = (Sequence)_elements[i];
- var value = seq.GetToken(0);
- if (value != null && token == (int)value)
- {
- result.Add(seq.Subsequence(1));
- }
- }
- return result;
- }
-
- public LookAheadSet CreateIntersection(LookAheadSet set)
- {
- LookAheadSet result = new LookAheadSet(_maxLength);
- for (int i = 0; i < _elements.Count; i++)
- {
- var seq1 = (Sequence)_elements[i];
- var seq2 = set.FindSequence(seq1);
- if (seq2 != null && seq1.IsRepetitive())
- {
- result.Add(seq2);
- }
- else if (seq2 != null)
- {
- result.Add(seq1);
- }
- }
- return result;
- }
-
- public LookAheadSet CreateCombination(LookAheadSet set)
- {
- LookAheadSet result = new LookAheadSet(_maxLength);
-
- // Handle special cases
- if (this.Size() <= 0)
- {
- return set;
- }
- else if (set.Size() <= 0)
- {
- return this;
- }
-
- // Create combinations
- for (int i = 0; i < _elements.Count; i++)
- {
- var first = (Sequence)_elements[i];
- if (first.Length() >= _maxLength)
- {
- result.Add(first);
- }
- else if (first.Length() <= 0)
- {
- result.AddAll(set);
- }
- else
- {
- for (int j = 0; j < set._elements.Count; j++)
- {
- var second = (Sequence)set._elements[j];
- result.Add(first.Concat(_maxLength, second));
- }
- }
- }
- return result;
- }
-
- public LookAheadSet CreateOverlaps(LookAheadSet set)
- {
- LookAheadSet result = new LookAheadSet(_maxLength);
-
- for (int i = 0; i < _elements.Count; i++)
- {
- var seq = (Sequence)_elements[i];
- if (set.IsOverlap(seq))
- {
- result.Add(seq);
- }
- }
- return result;
- }
-
- public LookAheadSet CreateFilter(LookAheadSet set)
- {
- LookAheadSet result = new LookAheadSet(_maxLength);
-
- // Handle special cases
- if (this.Size() <= 0 || set.Size() <= 0)
- {
- return this;
- }
-
- // Create combinations
- for (int i = 0; i < _elements.Count; i++)
- {
- var first = (Sequence)_elements[i];
- for (int j = 0; j < set._elements.Count; j++)
- {
- var second = (Sequence)set._elements[j];
- if (first.StartsWith(second))
- {
- result.Add(first.Subsequence(second.Length()));
- }
- }
- }
- return result;
- }
-
- public LookAheadSet CreateRepetitive()
- {
- LookAheadSet result = new LookAheadSet(_maxLength);
-
- for (int i = 0; i < _elements.Count; i++)
- {
- var seq = (Sequence)_elements[i];
- if (seq.IsRepetitive())
- {
- result.Add(seq);
- }
- else
- {
- result.Add(new Sequence(true, seq));
- }
- }
- return result;
- }
-
- public override string ToString()
- {
- return ToString(null);
- }
-
- public string ToString(Tokenizer tokenizer)
- {
- StringBuilder buffer = new StringBuilder();
-
- buffer.Append("{");
- for (int i = 0; i < _elements.Count; i++)
- {
- var seq = (Sequence)_elements[i];
- buffer.Append("\n ");
- buffer.Append(seq.ToString(tokenizer));
- }
- buffer.Append("\n}");
- return buffer.ToString();
- }
-
- private class Sequence
- {
- private bool _repeat;
- private readonly ArrayList _tokens;
-
- public Sequence()
- {
- this._repeat = false;
- this._tokens = new ArrayList(0);
- }
-
- public Sequence(bool repeat, int token)
- {
- _repeat = false;
- _tokens = new ArrayList(1);
- _tokens.Add(token);
- }
-
- public Sequence(int length, Sequence seq)
- {
- this._repeat = seq._repeat;
- this._tokens = new ArrayList(length);
- if (seq.Length() < length)
- {
- length = seq.Length();
- }
- for (int i = 0; i < length; i++)
- {
- _tokens.Add(seq._tokens[i]);
- }
- }
-
- public Sequence(bool repeat, Sequence seq)
- {
- this._repeat = repeat;
- this._tokens = seq._tokens;
- }
-
- public int Length()
- {
- return _tokens.Count;
- }
-
- public object GetToken(int pos)
- {
- if (pos >= 0 && pos < _tokens.Count)
- {
- return _tokens[pos];
- }
- else
- {
- return null;
- }
- }
-
- public override bool Equals(object obj)
- {
- if (obj is Sequence)
- {
- return Equals((Sequence)obj);
- }
- else
- {
- return false;
- }
- }
-
- public bool Equals(Sequence seq)
- {
- if (_tokens.Count != seq._tokens.Count)
- {
- return false;
- }
- for (int i = 0; i < _tokens.Count; i++)
- {
- if (!_tokens[i].Equals(seq._tokens[i]))
- {
- return false;
- }
- }
- return true;
- }
-
- public override int GetHashCode()
- {
- return _tokens.Count.GetHashCode();
- }
-
- public bool StartsWith(Sequence seq)
- {
- if (Length() < seq.Length())
- {
- return false;
- }
- for (int i = 0; i < seq._tokens.Count; i++)
- {
- if (!_tokens[i].Equals(seq._tokens[i]))
- {
- return false;
- }
- }
- return true;
- }
-
- public bool IsRepetitive()
- {
- return _repeat;
- }
-
- public bool IsNext(Parser parser)
- {
- for (int i = 0; i < _tokens.Count; i++)
- {
- var id = (int)_tokens[i];
- var token = parser.PeekToken(i);
- if (token == null || token.Id != id)
- {
- return false;
- }
- }
- return true;
- }
-
- public bool IsNext(Parser parser, int length)
- {
- if (length > _tokens.Count)
- {
- length = _tokens.Count;
- }
- for (int i = 0; i < length; i++)
- {
- var id = (int)_tokens[i];
- var token = parser.PeekToken(i);
- if (token == null || token.Id != id)
- {
- return false;
- }
- }
- return true;
- }
-
- public override string ToString()
- {
- return ToString(null);
- }
-
- public string ToString(Tokenizer tokenizer)
- {
- StringBuilder buffer = new StringBuilder();
-
- if (tokenizer == null)
- {
- buffer.Append(_tokens.ToString());
- }
- else
- {
- buffer.Append("[");
- for (int i = 0; i < _tokens.Count; i++)
- {
- var id = (int)_tokens[i];
- var str = tokenizer.GetPatternDescription(id);
- if (i > 0)
- {
- buffer.Append(" ");
- }
- buffer.Append(str);
- }
- buffer.Append("]");
- }
- if (_repeat)
- {
- buffer.Append(" *");
- }
- return buffer.ToString();
- }
-
- public Sequence Concat(int length, Sequence seq)
- {
- Sequence res = new Sequence(length, this);
-
- if (seq._repeat)
- {
- res._repeat = true;
- }
- length -= this.Length();
- if (length > seq.Length())
- {
- res._tokens.AddRange(seq._tokens);
- }
- else
- {
- for (int i = 0; i < length; i++)
- {
- res._tokens.Add(seq._tokens[i]);
- }
- }
- return res;
- }
-
- public Sequence Subsequence(int start)
- {
- Sequence res = new Sequence(Length(), this);
-
- while (start > 0 && res._tokens.Count > 0)
- {
- res._tokens.RemoveAt(0);
- start--;
- }
- return res;
- }
- }
- }
-}
diff --git a/src/Flee.NetStandard20/Parsing/grammatica-1.5.alpha2/PerCederberg.Grammatica.Runtime/ParseException.cs b/src/Flee.NetStandard20/Parsing/grammatica-1.5.alpha2/PerCederberg.Grammatica.Runtime/ParseException.cs
deleted file mode 100644
index ed6351e..0000000
--- a/src/Flee.NetStandard20/Parsing/grammatica-1.5.alpha2/PerCederberg.Grammatica.Runtime/ParseException.cs
+++ /dev/null
@@ -1,254 +0,0 @@
-using System;
-using System.Collections;
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.Text;
-using Flee.Resources;
-
-namespace Flee.Parsing.grammatica_1._5.alpha2.PerCederberg.Grammatica.Runtime
-{
- /**
- * A parse exception.
- */
- public class ParseException : Exception
- {
- public enum ErrorType
- {
-
- /**
- * The internal error type is only used to signal an error
- * that is a result of a bug in the parser or tokenizer
- * code.
- */
- INTERNAL,
-
- /**
- * The I/O error type is used for stream I/O errors.
- */
- IO,
-
- /**
- * The unexpected end of file error type is used when end
- * of file is encountered instead of a valid token.
- */
- UNEXPECTED_EOF,
-
- /**
- * The unexpected character error type is used when a
- * character is read that isn't handled by one of the
- * token patterns.
- */
- UNEXPECTED_CHAR,
-
- /**
- * The unexpected token error type is used when another
- * token than the expected one is encountered.
- */
- UNEXPECTED_TOKEN,
-
- /**
- * The invalid token error type is used when a token
- * pattern with an error message is matched. The
- * additional information provided should contain the
- * error message.
- */
- INVALID_TOKEN,
-
- /**
- * The analysis error type is used when an error is
- * encountered in the analysis. The additional information
- * provided should contain the error message.
- */
- ANALYSIS
- }
-
- private readonly ErrorType _type;
- private readonly string _info;
- private readonly ArrayList _details;
- private readonly int _line;
- private readonly int _column;
-
-
- ///
- /// Creates a new parse exception.
- ///
- ///
- ///
- ///
- ///
- public ParseException(ErrorType type,
- string info,
- int line,
- int column)
- : this(type, info, null, line, column)
- {
- }
-
- ///
- /// Creates a new parse exception. This constructor is only
- /// used to supply the detailed information array, which is
- /// only used for expected token errors. The list then contains
- /// descriptions of the expected tokens.
- ///
- ///
- ///
- ///
- ///
- ///
- public ParseException(ErrorType type,
- string info,
- ArrayList details,
- int line,
- int column)
- {
-
- this._type = type;
- this._info = info;
- this._details = details;
- this._line = line;
- this._column = column;
- }
-
-
- public ErrorType Type => _type;
-
- public ErrorType GetErrorType()
- {
- return Type;
- }
-
- public string Info => _info;
-
- public string GetInfo()
- {
- return Info;
- }
-
- public ArrayList Details => new ArrayList(_details);
-
- public ArrayList GetDetails()
- {
- return Details;
- }
-
- public int Line => _line;
-
- public int GetLine()
- {
- return Line;
- }
-
- public int Column => _column;
-
- public int GetColumn()
- {
- return _column;
- }
-
- public override string Message
- {
- get
- {
- StringBuilder buffer = new StringBuilder();
-
- // Add error description
- buffer.Append(ErrorMessage);
-
- // Add line and column
- if (_line > 0 && _column > 0)
- {
- buffer.Append(", on line: ");
- buffer.Append(_line);
- buffer.Append(" column: ");
- buffer.Append(_column);
- }
-
- return buffer.ToString();
- }
- }
-
- public string GetMessage()
- {
- return Message;
- }
-
- public string ErrorMessage
- {
- get
- {
- StringBuilder buffer = new StringBuilder();
-
- // Add type and info
- switch (_type)
- {
- case ErrorType.IO:
- buffer.Append("I/O error: ");
- buffer.Append(_info);
- break;
- case ErrorType.UNEXPECTED_EOF:
- buffer.Append("unexpected end of file");
- break;
- case ErrorType.UNEXPECTED_CHAR:
- buffer.Append("unexpected character '");
- buffer.Append(_info);
- buffer.Append("'");
- break;
- case ErrorType.UNEXPECTED_TOKEN:
- buffer.Append("unexpected token ");
- buffer.Append(_info);
- if (_details != null)
- {
- buffer.Append(", expected ");
- if (_details.Count > 1)
- {
- buffer.Append("one of ");
- }
- buffer.Append(GetMessageDetails());
- }
- break;
- case ErrorType.INVALID_TOKEN:
- buffer.Append(_info);
- break;
- case ErrorType.ANALYSIS:
- buffer.Append(_info);
- break;
- default:
- buffer.Append("internal error");
- if (_info != null)
- {
- buffer.Append(": ");
- buffer.Append(_info);
- }
- break;
- }
-
- return buffer.ToString();
- }
- }
-
- public string GetErrorMessage()
- {
- return ErrorMessage;
- }
-
- private string GetMessageDetails()
- {
- StringBuilder buffer = new StringBuilder();
-
- for (int i = 0; i < _details.Count; i++)
- {
- if (i > 0)
- {
- buffer.Append(", ");
- if (i + 1 == _details.Count)
- {
- buffer.Append("or ");
- }
- }
- buffer.Append(_details[i]);
- }
-
- return buffer.ToString();
- }
- }
-}
diff --git a/src/Flee.NetStandard20/Parsing/grammatica-1.5.alpha2/PerCederberg.Grammatica.Runtime/Production.cs b/src/Flee.NetStandard20/Parsing/grammatica-1.5.alpha2/PerCederberg.Grammatica.Runtime/Production.cs
deleted file mode 100644
index a2c564d..0000000
--- a/src/Flee.NetStandard20/Parsing/grammatica-1.5.alpha2/PerCederberg.Grammatica.Runtime/Production.cs
+++ /dev/null
@@ -1,74 +0,0 @@
-using System;
-using System.Collections;
-using System.Collections.Generic;
-using System.Diagnostics;
-using Flee.Parsing.grammatica_1._5.alpha2.PerCederberg.Grammatica.Runtime;
-
-namespace Flee.Parsing.grammatica_1._5.alpha2.PerCederberg.Grammatica.Runtime
-{
-
- /**
- * A production node. This class represents a grammar production
- * (i.e. a list of child nodes) in a parse tree. The productions
- * are created by a parser, that adds children a according to a
- * set of production patterns (i.e. grammar rules).
- */
- internal class Production : Node
- {
- private readonly ProductionPattern _pattern;
- private readonly ArrayList _children;
-
- public Production(ProductionPattern pattern)
- {
- this._pattern = pattern;
- this._children = new ArrayList();
- }
-
- public override int Id => _pattern.Id;
-
- public override string Name => _pattern.Name;
-
- public override int Count => _children.Count;
-
- public override Node this[int index]
- {
- get
- {
- if (index < 0 || index >= _children.Count)
- {
- return null;
- }
- else
- {
- return (Node)_children[index];
- }
- }
- }
-
- public void AddChild(Node child)
- {
- if (child != null)
- {
- child.SetParent(this);
- _children.Add(child);
- }
- }
-
- public ProductionPattern Pattern => _pattern;
-
- public ProductionPattern GetPattern()
- {
- return Pattern;
- }
-
- internal override bool IsHidden()
- {
- return _pattern.Synthetic;
- }
-
- public override string ToString()
- {
- return _pattern.Name + '(' + _pattern.Id + ')';
- }
- }
-}
diff --git a/src/Flee.NetStandard20/Parsing/grammatica-1.5.alpha2/PerCederberg.Grammatica.Runtime/ProductionPattern.cs b/src/Flee.NetStandard20/Parsing/grammatica-1.5.alpha2/PerCederberg.Grammatica.Runtime/ProductionPattern.cs
deleted file mode 100644
index 3d17c97..0000000
--- a/src/Flee.NetStandard20/Parsing/grammatica-1.5.alpha2/PerCederberg.Grammatica.Runtime/ProductionPattern.cs
+++ /dev/null
@@ -1,216 +0,0 @@
-using System;
-using System.Collections;
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.Text;
-
-
-namespace Flee.Parsing.grammatica_1._5.alpha2.PerCederberg.Grammatica.Runtime
-{
-
- /**
- * A production pattern. This class represents a set of production
- * alternatives that together forms a single production. A
- * production pattern is identified by an integer id and a name,
- * both provided upon creation. The pattern id is used for
- * referencing the production pattern from production pattern
- * elements.
- */
- internal class ProductionPattern
- {
-
- private readonly int _id;
- private readonly string _name;
- private bool _synthetic;
- private readonly ArrayList _alternatives;
- private int _defaultAlt;
- private LookAheadSet _lookAhead;
-
- public ProductionPattern(int id, string name)
- {
- this._id = id;
- this._name = name;
- this._synthetic = false;
- this._alternatives = new ArrayList();
- this._defaultAlt = -1;
- this._lookAhead = null;
- }
- public int Id => _id;
-
- public int GetId()
- {
- return Id;
- }
-
- public string Name => _name;
-
- public string GetName()
- {
- return Name;
- }
-
- public bool Synthetic
- {
- get
- {
- return _synthetic;
- }
- set
- {
- _synthetic = value;
- }
- }
-
- public bool IsSyntetic()
- {
- return Synthetic;
- }
-
- public void SetSyntetic(bool synthetic)
- {
- Synthetic = synthetic;
- }
-
- internal LookAheadSet LookAhead
- {
- get
- {
- return _lookAhead;
- }
- set
- {
- _lookAhead = value;
- }
- }
-
- internal ProductionPatternAlternative DefaultAlternative
- {
- get
- {
- if (_defaultAlt >= 0)
- {
- object obj = _alternatives[_defaultAlt];
- return (ProductionPatternAlternative)obj;
- }
- else
- {
- return null;
- }
- }
- set
- {
- _defaultAlt = 0;
- for (int i = 0; i < _alternatives.Count; i++)
- {
- if (_alternatives[i] == value)
- {
- _defaultAlt = i;
- }
- }
- }
- }
-
- public int Count => _alternatives.Count;
-
- public int GetAlternativeCount()
- {
- return Count;
- }
-
- public ProductionPatternAlternative this[int index] => (ProductionPatternAlternative)_alternatives[index];
-
- public ProductionPatternAlternative GetAlternative(int pos)
- {
- return this[pos];
- }
-
- public bool IsLeftRecursive()
- {
- ProductionPatternAlternative alt;
-
- for (int i = 0; i < _alternatives.Count; i++)
- {
- alt = (ProductionPatternAlternative)_alternatives[i];
- if (alt.IsLeftRecursive())
- {
- return true;
- }
- }
- return false;
- }
-
- public bool IsRightRecursive()
- {
- ProductionPatternAlternative alt;
-
- for (int i = 0; i < _alternatives.Count; i++)
- {
- alt = (ProductionPatternAlternative)_alternatives[i];
- if (alt.IsRightRecursive())
- {
- return true;
- }
- }
- return false;
- }
-
- public bool IsMatchingEmpty()
- {
- ProductionPatternAlternative alt;
-
- for (int i = 0; i < _alternatives.Count; i++)
- {
- alt = (ProductionPatternAlternative)_alternatives[i];
- if (alt.IsMatchingEmpty())
- {
- return true;
- }
- }
- return false;
- }
-
- public void AddAlternative(ProductionPatternAlternative alt)
- {
- if (_alternatives.Contains(alt))
- {
- throw new ParserCreationException(
- ParserCreationException.ErrorType.INVALID_PRODUCTION,
- _name,
- "two identical alternatives exist");
- }
- alt.SetPattern(this);
- _alternatives.Add(alt);
- }
-
- public override string ToString()
- {
- StringBuilder buffer = new StringBuilder();
- StringBuilder indent = new StringBuilder();
- int i;
-
- buffer.Append(_name);
- buffer.Append("(");
- buffer.Append(_id);
- buffer.Append(") ");
- for (i = 0; i < buffer.Length; i++)
- {
- indent.Append(" ");
- }
- for (i = 0; i < _alternatives.Count; i++)
- {
- if (i == 0)
- {
- buffer.Append("= ");
- }
- else
- {
- buffer.Append("\n");
- buffer.Append(indent);
- buffer.Append("| ");
- }
- buffer.Append(_alternatives[i]);
- }
- return buffer.ToString();
- }
- }
-}
diff --git a/src/Flee.NetStandard20/Parsing/grammatica-1.5.alpha2/PerCederberg.Grammatica.Runtime/ProductionPatternAlternative.cs b/src/Flee.NetStandard20/Parsing/grammatica-1.5.alpha2/PerCederberg.Grammatica.Runtime/ProductionPatternAlternative.cs
deleted file mode 100644
index a2eb4a3..0000000
--- a/src/Flee.NetStandard20/Parsing/grammatica-1.5.alpha2/PerCederberg.Grammatica.Runtime/ProductionPatternAlternative.cs
+++ /dev/null
@@ -1,213 +0,0 @@
-using System;
-using System.Collections;
-using System.Collections.Generic;
-using System.Text;
-
-namespace Flee.Parsing.grammatica_1._5.alpha2.PerCederberg.Grammatica.Runtime
-{
-
- /**
- * A production pattern alternative. This class represents a list of
- * production pattern elements. In order to provide productions that
- * cannot be represented with the element occurance counters, multiple
- * alternatives must be created and added to the same production
- * pattern. A production pattern alternative is always contained
- * within a production pattern.
- */
- internal class ProductionPatternAlternative
- {
- private ProductionPattern _pattern;
- private readonly ArrayList _elements = new ArrayList();
- private LookAheadSet _lookAhead = null;
-
- public ProductionPatternAlternative()
- {
- }
-
- public ProductionPattern Pattern => _pattern;
-
- public ProductionPattern GetPattern()
- {
- return Pattern;
- }
-
- internal LookAheadSet LookAhead
- {
- get
- {
- return _lookAhead;
- }
- set
- {
- _lookAhead = value;
- }
- }
-
- public int Count => _elements.Count;
-
- public int GetElementCount()
- {
- return Count;
- }
-
- public ProductionPatternElement this[int index] => (ProductionPatternElement)_elements[index];
-
- public ProductionPatternElement GetElement(int pos)
- {
- return this[pos];
- }
-
- public bool IsLeftRecursive()
- {
- for (int i = 0; i < _elements.Count; i++)
- {
- var elem = (ProductionPatternElement)_elements[i];
- if (elem.Id == _pattern.Id)
- {
- return true;
- }
- else if (elem.MinCount > 0)
- {
- break;
- }
- }
- return false;
- }
-
- public bool IsRightRecursive()
- {
- for (int i = _elements.Count - 1; i >= 0; i--)
- {
- var elem = (ProductionPatternElement)_elements[i];
- if (elem.Id == _pattern.Id)
- {
- return true;
- }
- else if (elem.MinCount > 0)
- {
- break;
- }
- }
- return false;
- }
-
- public bool IsMatchingEmpty()
- {
- return GetMinElementCount() == 0;
- }
-
- internal void SetPattern(ProductionPattern pattern)
- {
- this._pattern = pattern;
- }
-
- public int GetMinElementCount()
- {
- int min = 0;
-
- for (int i = 0; i < _elements.Count; i++)
- {
- var elem = (ProductionPatternElement)_elements[i];
- min += elem.MinCount;
- }
- return min;
- }
-
- public int GetMaxElementCount()
- {
- int max = 0;
-
- for (int i = 0; i < _elements.Count; i++)
- {
- var elem = (ProductionPatternElement)_elements[i];
- if (elem.MaxCount >= Int32.MaxValue)
- {
- return Int32.MaxValue;
- }
- else
- {
- max += elem.MaxCount;
- }
- }
- return max;
- }
-
- public void AddToken(int id, int min, int max)
- {
- AddElement(new ProductionPatternElement(true, id, min, max));
- }
-
- public void AddProduction(int id, int min, int max)
- {
- AddElement(new ProductionPatternElement(false, id, min, max));
- }
-
- public void AddElement(ProductionPatternElement elem)
- {
- _elements.Add(elem);
- }
-
- public void AddElement(ProductionPatternElement elem,
- int min,
- int max)
- {
-
- if (elem.IsToken())
- {
- AddToken(elem.Id, min, max);
- }
- else
- {
- AddProduction(elem.Id, min, max);
- }
- }
-
- public override bool Equals(object obj)
- {
- if (obj is ProductionPatternAlternative)
- {
- return Equals((ProductionPatternAlternative)obj);
- }
- else
- {
- return false;
- }
- }
-
- public bool Equals(ProductionPatternAlternative alt)
- {
- if (_elements.Count != alt._elements.Count)
- {
- return false;
- }
- for (int i = 0; i < _elements.Count; i++)
- {
- if (!_elements[i].Equals(alt._elements[i]))
- {
- return false;
- }
- }
- return true;
- }
-
- public override int GetHashCode()
- {
- return _elements.Count.GetHashCode();
- }
-
- public override string ToString()
- {
- StringBuilder buffer = new StringBuilder();
-
- for (int i = 0; i < _elements.Count; i++)
- {
- if (i > 0)
- {
- buffer.Append(" ");
- }
- buffer.Append(_elements[i]);
- }
- return buffer.ToString();
- }
- }
-}
diff --git a/src/Flee.NetStandard20/Parsing/grammatica-1.5.alpha2/PerCederberg.Grammatica.Runtime/ReaderBuffer.cs b/src/Flee.NetStandard20/Parsing/grammatica-1.5.alpha2/PerCederberg.Grammatica.Runtime/ReaderBuffer.cs
deleted file mode 100644
index f267066..0000000
--- a/src/Flee.NetStandard20/Parsing/grammatica-1.5.alpha2/PerCederberg.Grammatica.Runtime/ReaderBuffer.cs
+++ /dev/null
@@ -1,187 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-
-namespace Flee.Parsing.grammatica_1._5.alpha2.PerCederberg.Grammatica.Runtime
-{
- /**
- * A character buffer that automatically reads from an input source
- * stream when needed. This class keeps track of the current position
- * in the buffer and its line and column number in the original input
- * source. It allows unlimited look-ahead of characters in the input,
- * reading and buffering the required data internally. As the
- * position is advanced, the buffer content prior to the current
- * position is subject to removal to make space for reading new
- * content. A few characters before the current position are always
- * kept to enable boundary condition checks.
- */
- internal class ReaderBuffer
- {
- public const int BlockSize = 1024;
- private char[] _buffer = new char[BlockSize * 4];
- private int _pos = 0;
- private int _length = 0;
- private TextReader _input;
- private int _line = 1;
- private int _column = 1;
-
- public ReaderBuffer(TextReader input)
- {
- this._input = input;
- }
- public void Dispose()
- {
- _buffer = null;
- _pos = 0;
- _length = 0;
- if (_input != null)
- {
- try
- {
- _input.Close();
- }
- catch (Exception)
- {
- // Do nothing
- }
- _input = null;
- }
- }
-
- public int Position => _pos;
- public int LineNumber => _line;
- public int ColumnNumber => _column;
- public int Length => _length;
-
- public string Substring(int index, int length)
- {
- return new string(_buffer, index, length);
- }
-
- public override string ToString()
- {
- return new string(_buffer, 0, _length);
- }
-
- public int Peek(int offset)
- {
- int index = _pos + offset;
-
- // Avoid most calls to EnsureBuffered(), since we are in a
- // performance hotspot here. This check is not exhaustive,
- // but only present here to speed things up.
- if (index >= _length)
- {
- EnsureBuffered(offset + 1);
- index = _pos + offset;
- }
- return (index >= _length) ? -1 : _buffer[index];
- }
-
- public string Read(int offset)
- {
- EnsureBuffered(offset + 1);
- if (_pos >= _length)
- {
- return null;
- }
- else
- {
- var count = _length - _pos;
- if (count > offset)
- {
- count = offset;
- }
- UpdateLineColumnNumbers(count);
- var result = new string(_buffer, _pos, count);
- _pos += count;
- if (_input == null && _pos >= _length)
- {
- Dispose();
- }
- return result;
- }
- }
-
- private void UpdateLineColumnNumbers(int offset)
- {
- for (int i = 0; i < offset; i++)
- {
- if (_buffer[_pos + i] == '\n')
- {
- _line++;
- _column = 1;
- }
- else
- {
- _column++;
- }
- }
- }
-
- private void EnsureBuffered(int offset)
- {
- // Check for end of stream or already read characters
- if (_input == null || _pos + offset < _length)
- {
- return;
- }
-
- // Remove (almost all) old characters from buffer
- if (_pos > BlockSize)
- {
- _length -= (_pos - 16);
- Array.Copy(_buffer, _pos - 16, _buffer, 0, _length);
- _pos = 16;
- }
-
- // Calculate number of characters to read
- var size = _pos + offset - _length + 1;
- if (size % BlockSize != 0)
- {
- size = (1 + size / BlockSize) * BlockSize;
- }
- EnsureCapacity(_length + size);
-
- // Read characters
- try
- {
- while (_input != null && size > 0)
- {
- var readSize = _input.Read(_buffer, _length, size);
- if (readSize > 0)
- {
- _length += readSize;
- size -= readSize;
- }
- else
- {
- _input.Close();
- _input = null;
- }
- }
- }
- catch (IOException e)
- {
- _input = null;
- throw e;
- }
- }
-
- private void EnsureCapacity(int size)
- {
- if (_buffer.Length >= size)
- {
- return;
- }
- if (size % BlockSize != 0)
- {
- size = (1 + size / BlockSize) * BlockSize;
- }
- Array.Resize(ref _buffer, size);
- }
- }
-}
diff --git a/src/Flee.NetStandard20/Parsing/grammatica-1.5.alpha2/PerCederberg.Grammatica.Runtime/Token.cs b/src/Flee.NetStandard20/Parsing/grammatica-1.5.alpha2/PerCederberg.Grammatica.Runtime/Token.cs
deleted file mode 100644
index 9c46e7c..0000000
--- a/src/Flee.NetStandard20/Parsing/grammatica-1.5.alpha2/PerCederberg.Grammatica.Runtime/Token.cs
+++ /dev/null
@@ -1,172 +0,0 @@
-using System;
-using System.Collections;
-using System.Collections.Generic;
-using System.Text;
-using System.Diagnostics;
-
-namespace Flee.Parsing.grammatica_1._5.alpha2.PerCederberg.Grammatica.Runtime
-{
- /**
- * A token node. This class represents a token (i.e. a set of adjacent
- * characters) in a parse tree. The tokens are created by a tokenizer,
- * that groups characters together into tokens according to a set of
- * token patterns.
- */
- internal class Token : Node
- {
- private readonly TokenPattern _pattern;
- private readonly string _image;
- private readonly int _startLine;
- private readonly int _startColumn;
- private readonly int _endLine;
- private readonly int _endColumn;
- private Token _previous = null;
- private Token _next = null;
-
- public Token(TokenPattern pattern, string image, int line, int col)
- {
- this._pattern = pattern;
- this._image = image;
- this._startLine = line;
- this._startColumn = col;
- this._endLine = line;
- this._endColumn = col + image.Length - 1;
- for (int pos = 0; image.IndexOf('\n', pos) >= 0;)
- {
- pos = image.IndexOf('\n', pos) + 1;
- this._endLine++;
- _endColumn = image.Length - pos;
- }
- }
-
- public override int Id => _pattern.Id;
-
- public override string Name => _pattern.Name;
-
- public override int StartLine => _startLine;
-
- public override int StartColumn => _startColumn;
-
- public override int EndLine => _endLine;
-
- public override int EndColumn => _endColumn;
-
- public string Image => _image;
-
- public string GetImage()
- {
- return Image;
- }
-
- internal TokenPattern Pattern => _pattern;
- public Token Previous
- {
- get
- {
- return _previous;
- }
- set
- {
- if (_previous != null)
- {
- _previous._next = null;
- }
- _previous = value;
- if (_previous != null)
- {
- _previous._next = this;
- }
- }
- }
-
- public Token GetPreviousToken()
- {
- return Previous;
- }
-
- public Token Next
- {
- get
- {
- return _next;
- }
- set
- {
- if (_next != null)
- {
- _next._previous = null;
- }
- _next = value;
- if (_next != null)
- {
- _next._previous = this;
- }
- }
- }
-
- public Token GetNextToken()
- {
- return Next;
- }
-
- public override string ToString()
- {
- StringBuilder buffer = new StringBuilder();
- int newline = _image.IndexOf('\n');
-
- buffer.Append(_pattern.Name);
- buffer.Append("(");
- buffer.Append(_pattern.Id);
- buffer.Append("): \"");
- if (newline >= 0)
- {
- if (newline > 0 && _image[newline - 1] == '\r')
- {
- newline--;
- }
- buffer.Append(_image.Substring(0, newline));
- buffer.Append("(...)");
- }
- else
- {
- buffer.Append(_image);
- }
- buffer.Append("\", line: ");
- buffer.Append(_startLine);
- buffer.Append(", col: ");
- buffer.Append(_startColumn);
-
- return buffer.ToString();
- }
-
- public string ToShortString()
- {
- StringBuilder buffer = new StringBuilder();
- int newline = _image.IndexOf('\n');
-
- buffer.Append('"');
- if (newline >= 0)
- {
- if (newline > 0 && _image[newline - 1] == '\r')
- {
- newline--;
- }
- buffer.Append(_image.Substring(0, newline));
- buffer.Append("(...)");
- }
- else
- {
- buffer.Append(_image);
- }
- buffer.Append('"');
- if (_pattern.Type == TokenPattern.PatternType.REGEXP)
- {
- buffer.Append(" <");
- buffer.Append(_pattern.Name);
- buffer.Append(">");
- }
-
- return buffer.ToString();
- }
- }
-}
diff --git a/src/Flee.NetStandard20/Parsing/grammatica-1.5.alpha2/PerCederberg.Grammatica.Runtime/TokenMatch.cs b/src/Flee.NetStandard20/Parsing/grammatica-1.5.alpha2/PerCederberg.Grammatica.Runtime/TokenMatch.cs
deleted file mode 100644
index 6a100d2..0000000
--- a/src/Flee.NetStandard20/Parsing/grammatica-1.5.alpha2/PerCederberg.Grammatica.Runtime/TokenMatch.cs
+++ /dev/null
@@ -1,37 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-
-namespace Flee.Parsing.grammatica_1._5.alpha2.PerCederberg.Grammatica.Runtime
-{
- /**
- * The token match status. This class contains logic to ensure that
- * only the longest match is considered.
- */
- internal class TokenMatch
- {
- private int _length = 0;
- private TokenPattern _pattern = null;
-
- public void Clear()
- {
- _length = 0;
- _pattern = null;
- }
-
- public int Length => _length;
-
- public TokenPattern Pattern => _pattern;
-
- public void Update(int length, TokenPattern pattern)
- {
- if (this._length < length)
- {
- this._length = length;
- this._pattern = pattern;
- }
- }
- }
-}
diff --git a/src/Flee.NetStandard20/Parsing/grammatica-1.5.alpha2/PerCederberg.Grammatica.Runtime/TokenNFA.cs b/src/Flee.NetStandard20/Parsing/grammatica-1.5.alpha2/PerCederberg.Grammatica.Runtime/TokenNFA.cs
deleted file mode 100644
index 2aec91c..0000000
--- a/src/Flee.NetStandard20/Parsing/grammatica-1.5.alpha2/PerCederberg.Grammatica.Runtime/TokenNFA.cs
+++ /dev/null
@@ -1,831 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-
-namespace Flee.Parsing.grammatica_1._5.alpha2.PerCederberg.Grammatica.Runtime
-{
- /**
- * A non-deterministic finite state automaton (NFA) for matching
- * tokens. It supports both fixed strings and simple regular
- * expressions, but should perform similar to a DFA due to highly
- * optimized data structures and tuning. The memory footprint during
- * matching should be near zero, since no heap memory is allocated
- * unless the pre-allocated queues need to be enlarged. The NFA also
- * does not use recursion, but iterates in a loop instead.
- */
- internal class TokenNFA
- {
- private readonly NFAState[] _initialChar = new NFAState[128];
- private readonly NFAState _initial = new NFAState();
- private readonly NFAStateQueue _queue = new NFAStateQueue();
-
- public void AddTextMatch(string str, bool ignoreCase, TokenPattern value)
- {
- NFAState state;
- char ch = str[0];
-
- if (ch < 128 && !ignoreCase)
- {
- state = _initialChar[ch];
- if (state == null)
- {
- state = _initialChar[ch] = new NFAState();
- }
- }
- else
- {
- state = _initial.AddOut(ch, ignoreCase, null);
- }
- for (int i = 1; i < str.Length; i++)
- {
- state = state.AddOut(str[i], ignoreCase, null);
- }
- state.Value = value;
- }
-
- public void AddRegExpMatch(string pattern,
- bool ignoreCase,
- TokenPattern value)
- {
- TokenRegExpParser parser = new TokenRegExpParser(pattern, ignoreCase);
- string debug = "DFA regexp; " + parser.GetDebugInfo();
-
- var isAscii = parser.Start.IsAsciiOutgoing();
- for (int i = 0; isAscii && i < 128; i++)
- {
- bool match = false;
- for (int j = 0; j < parser.Start.Outgoing.Length; j++)
- {
- if (parser.Start.Outgoing[j].Match((char)i))
- {
- if (match)
- {
- isAscii = false;
- break;
- }
- match = true;
- }
- }
- if (match && _initialChar[i] != null)
- {
- isAscii = false;
- }
- }
- if (parser.Start.Incoming.Length > 0)
- {
- _initial.AddOut(new NFAEpsilonTransition(parser.Start));
- debug += ", uses initial epsilon";
- }
- else if (isAscii && !ignoreCase)
- {
- for (int i = 0; isAscii && i < 128; i++)
- {
- for (int j = 0; j < parser.Start.Outgoing.Length; j++)
- {
- if (parser.Start.Outgoing[j].Match((char)i))
- {
- _initialChar[i] = parser.Start.Outgoing[j].State;
- }
- }
- }
- debug += ", uses ASCII lookup";
- }
- else
- {
- parser.Start.MergeInto(_initial);
- debug += ", uses initial state";
- }
- parser.End.Value = value;
- value.DebugInfo = debug;
- }
-
- public int Match(ReaderBuffer buffer, TokenMatch match)
- {
- int length = 0;
- int pos = 1;
- NFAState state;
-
- // The first step of the match loop has been unrolled and
- // optimized for performance below.
- this._queue.Clear();
- var peekChar = buffer.Peek(0);
- if (0 <= peekChar && peekChar < 128)
- {
- state = this._initialChar[peekChar];
- if (state != null)
- {
- this._queue.AddLast(state);
- }
- }
- if (peekChar >= 0)
- {
- this._initial.MatchTransitions((char)peekChar, this._queue, true);
- }
- this._queue.MarkEnd();
- peekChar = buffer.Peek(1);
-
- // The remaining match loop processes all subsequent states
- while (!this._queue.Empty)
- {
- if (this._queue.Marked)
- {
- pos++;
- peekChar = buffer.Peek(pos);
- this._queue.MarkEnd();
- }
- state = this._queue.RemoveFirst();
- if (state.Value != null)
- {
- match.Update(pos, state.Value);
- }
- if (peekChar >= 0)
- {
- state.MatchTransitions((char)peekChar, this._queue, false);
- }
- }
- return length;
- }
- }
-
-
- /**
- * An NFA state. The NFA consists of a series of states, each
- * having zero or more transitions to other states.
- */
- internal class NFAState
- {
- internal TokenPattern Value = null;
- internal NFATransition[] Incoming = new NFATransition[0];
- internal NFATransition[] Outgoing = new NFATransition[0];
- internal bool EpsilonOut = false;
-
- public bool HasTransitions()
- {
- return Incoming.Length > 0 || Outgoing.Length > 0;
- }
- public bool IsAsciiOutgoing()
- {
- for (int i = 0; i < Outgoing.Length; i++)
- {
- if (!Outgoing[i].IsAscii())
- {
- return false;
- }
- }
- return true;
- }
-
- public void AddIn(NFATransition trans)
- {
- Array.Resize(ref Incoming, Incoming.Length + 1);
- Incoming[Incoming.Length - 1] = trans;
- }
-
- public NFAState AddOut(char ch, bool ignoreCase, NFAState state)
- {
- if (ignoreCase)
- {
- if (state == null)
- {
- state = new NFAState();
- }
- AddOut(new NFACharTransition(Char.ToLower(ch), state));
- AddOut(new NFACharTransition(Char.ToUpper(ch), state));
- return state;
- }
- else
- {
- if (state == null)
- {
- state = FindUniqueCharTransition(ch);
- if (state != null)
- {
- return state;
- }
- state = new NFAState();
- }
- return AddOut(new NFACharTransition(ch, state));
- }
- }
-
- public NFAState AddOut(NFATransition trans)
- {
- Array.Resize(ref Outgoing, Outgoing.Length + 1);
- Outgoing[Outgoing.Length - 1] = trans;
- if (trans is NFAEpsilonTransition)
- {
- EpsilonOut = true;
- }
- return trans.State;
- }
-
- public void MergeInto(NFAState state)
- {
- for (int i = 0; i < Incoming.Length; i++)
- {
- state.AddIn(Incoming[i]);
- Incoming[i].State = state;
- }
- Incoming = null;
- for (int i = 0; i < Outgoing.Length; i++)
- {
- state.AddOut(Outgoing[i]);
- }
- Outgoing = null;
- }
-
- private NFAState FindUniqueCharTransition(char ch)
- {
- NFATransition res = null;
- NFATransition trans;
-
- for (int i = 0; i < Outgoing.Length; i++)
- {
- trans = Outgoing[i];
- if (trans.Match(ch) && trans is NFACharTransition)
- {
- if (res != null)
- {
- return null;
- }
- res = trans;
- }
- }
- for (int i = 0; res != null && i < Outgoing.Length; i++)
- {
- trans = Outgoing[i];
- if (trans != res && trans.State == res.State)
- {
- return null;
- }
- }
- return res?.State;
- }
-
- public void MatchTransitions(char ch, NFAStateQueue queue, bool initial)
- {
- for (int i = 0; i < Outgoing.Length; i++)
- {
- var trans = Outgoing[i];
- var target = trans.State;
- if (initial && trans is NFAEpsilonTransition)
- {
- target.MatchTransitions(ch, queue, true);
- }
- else if (trans.Match(ch))
- {
- queue.AddLast(target);
- if (target.EpsilonOut)
- {
- target.MatchEmpty(queue);
- }
- }
- }
- }
-
- public void MatchEmpty(NFAStateQueue queue)
- {
- for (int i = 0; i < Outgoing.Length; i++)
- {
- var trans = Outgoing[i];
- if (trans is NFAEpsilonTransition)
- {
- var target = trans.State;
- queue.AddLast(target);
- if (target.EpsilonOut)
- {
- target.MatchEmpty(queue);
- }
- }
- }
- }
- }
-
-
- /**
- * An NFA state transition. A transition checks a single
- * character of input an determines if it is a match. If a match
- * is encountered, the NFA should move forward to the transition
- * state.
- */
- internal abstract class NFATransition
- {
-
- internal NFAState State;
-
- protected NFATransition(NFAState state)
- {
- this.State = state;
- this.State.AddIn(this);
- }
-
- public abstract bool IsAscii();
-
- public abstract bool Match(char ch);
-
- public abstract NFATransition Copy(NFAState state);
- }
-
-
- /**
- * The special epsilon transition. This transition matches the
- * empty input, i.e. it is an automatic transition that doesn't
- * read any input. As such, it returns false in the match method
- * and is handled specially everywhere.
- */
- internal class NFAEpsilonTransition : NFATransition
- {
- public NFAEpsilonTransition(NFAState state) : base(state)
- {
- }
-
- public override bool IsAscii()
- {
- return false;
- }
-
- public override bool Match(char ch)
- {
- return false;
- }
-
- public override NFATransition Copy(NFAState state)
- {
- return new NFAEpsilonTransition(state);
- }
- }
-
-
- /**
- * A single character match transition.
- */
- internal class NFACharTransition : NFATransition
- {
- private readonly char _match;
-
- public NFACharTransition(char match, NFAState state) : base(state)
- {
- _match = match;
- }
-
- public override bool IsAscii()
- {
- return 0 <= _match && _match < 128;
- }
-
- public override bool Match(char ch)
- {
- return this._match == ch;
- }
-
- public override NFATransition Copy(NFAState state)
- {
- return new NFACharTransition(_match, state);
- }
- }
-
-
- /**
- * A character range match transition. Used for user-defined
- * character sets in regular expressions.
- */
- internal class NFACharRangeTransition : NFATransition
- {
-
- protected bool Inverse;
- protected bool IgnoreCase;
-
- private object[] _contents = new object[0];
-
- public NFACharRangeTransition(bool inverse,
- bool ignoreCase,
- NFAState state) : base(state)
- {
- this.Inverse = inverse;
- this.IgnoreCase = ignoreCase;
- }
-
- public override bool IsAscii()
- {
- if (Inverse)
- {
- return false;
- }
- for (int i = 0; i < _contents.Length; i++)
- {
- var obj = _contents[i];
- if (obj is char)
- {
- var c = (char)obj;
- if (c < 0 || 128 <= c)
- {
- return false;
- }
- }
- else if (obj is Range)
- {
- if (!((Range)obj).IsAscii())
- {
- return false;
- }
- }
- }
- return true;
- }
-
- public void AddCharacter(char c)
- {
- if (IgnoreCase)
- {
- c = Char.ToLower(c);
- }
- AddContent(c);
- }
-
- public void AddRange(char min, char max)
- {
- if (IgnoreCase)
- {
- min = Char.ToLower(min);
- max = Char.ToLower(max);
- }
- AddContent(new Range(min, max));
- }
-
- private void AddContent(Object obj)
- {
- Array.Resize(ref _contents, _contents.Length + 1);
- _contents[_contents.Length - 1] = obj;
- }
-
- public override bool Match(char ch)
- {
- object obj;
- char c;
- Range r;
-
- if (IgnoreCase)
- {
- ch = Char.ToLower(ch);
- }
- for (int i = 0; i < _contents.Length; i++)
- {
- obj = _contents[i];
- if (obj is char)
- {
- c = (char)obj;
- if (c == ch)
- {
- return !Inverse;
- }
- }
- else if (obj is Range)
- {
- r = (Range)obj;
- if (r.Inside(ch))
- {
- return !Inverse;
- }
- }
- }
- return Inverse;
- }
-
- public override NFATransition Copy(NFAState state)
- {
- var copy = new NFACharRangeTransition(Inverse, IgnoreCase, state) { _contents = _contents };
- return copy;
- }
-
- private class Range
- {
- private readonly char _min;
- private readonly char _max;
-
- public Range(char min, char max)
- {
- this._min = min;
- this._max = max;
- }
-
- public bool IsAscii()
- {
- return 0 <= _min && _min < 128 &&
- 0 <= _max && _max < 128;
- }
-
- public bool Inside(char c)
- {
- return _min <= c && c <= _max;
- }
- }
- }
-
-
- /**
- * The dot ('.') character set transition. This transition
- * matches a single character that is not equal to a newline
- * character.
- */
- internal class NFADotTransition : NFATransition
- {
- public NFADotTransition(NFAState state) : base(state)
- {
- }
-
- public override bool IsAscii()
- {
- return false;
- }
-
- public override bool Match(char ch)
- {
- switch (ch)
- {
- case '\n':
- case '\r':
- case '\u0085':
- case '\u2028':
- case '\u2029':
- return false;
- default:
- return true;
- }
- }
-
- public override NFATransition Copy(NFAState state)
- {
- return new NFADotTransition(state);
- }
- }
-
-
- /**
- * The digit character set transition. This transition matches a
- * single numeric character.
- */
- internal class NFADigitTransition : NFATransition
- {
- public NFADigitTransition(NFAState state) : base(state)
- {
- }
-
- public override bool IsAscii()
- {
- return true;
- }
-
- public override bool Match(char ch)
- {
- return '0' <= ch && ch <= '9';
- }
-
- public override NFATransition Copy(NFAState state)
- {
- return new NFADigitTransition(state);
- }
- }
-
-
- /**
- * The non-digit character set transition. This transition
- * matches a single non-numeric character.
- */
- internal class NFANonDigitTransition : NFATransition
- {
- public NFANonDigitTransition(NFAState state) : base(state)
- {
- }
-
- public override bool IsAscii()
- {
- return false;
- }
-
- public override bool Match(char ch)
- {
- return ch < '0' || '9' < ch;
- }
-
- public override NFATransition Copy(NFAState state)
- {
- return new NFANonDigitTransition(state);
- }
- }
-
- /**
- * The whitespace character set transition. This transition
- * matches a single whitespace character.
- */
- internal class NFAWhitespaceTransition : NFATransition
- {
- public NFAWhitespaceTransition(NFAState state) : base(state)
- {
- }
-
- public override bool IsAscii()
- {
- return true;
- }
-
- public override bool Match(char ch)
- {
- switch (ch)
- {
- case ' ':
- case '\t':
- case '\n':
- case '\f':
- case '\r':
- case (char)11:
- return true;
- default:
- return false;
- }
- }
-
- public override NFATransition Copy(NFAState state)
- {
- return new NFAWhitespaceTransition(state);
- }
- }
-
-
- /**
- * The non-whitespace character set transition. This transition
- * matches a single non-whitespace character.
- */
- internal class NFANonWhitespaceTransition : NFATransition
- {
-
- public NFANonWhitespaceTransition(NFAState state) : base(state)
- {
- }
-
- public override bool IsAscii()
- {
- return false;
- }
-
- public override bool Match(char ch)
- {
- switch (ch)
- {
- case ' ':
- case '\t':
- case '\n':
- case '\f':
- case '\r':
- case (char)11:
- return false;
- default:
- return true;
- }
- }
-
- public override NFATransition Copy(NFAState state)
- {
- return new NFANonWhitespaceTransition(state);
- }
- }
-
-
- /**
- * The word character set transition. This transition matches a
- * single word character.
- */
- internal class NFAWordTransition : NFATransition
- {
-
- public NFAWordTransition(NFAState state) : base(state)
- {
- }
-
- public override bool IsAscii()
- {
- return true;
- }
-
-
- public override bool Match(char ch)
- {
- return ('a' <= ch && ch <= 'z')
- || ('A' <= ch && ch <= 'Z')
- || ('0' <= ch && ch <= '9')
- || ch == '_';
- }
-
- public override NFATransition Copy(NFAState state)
- {
- return new NFAWordTransition(state);
- }
- }
-
-
- /**
- * The non-word character set transition. This transition matches
- * a single non-word character.
- */
- internal class NFANonWordTransition : NFATransition
- {
- public NFANonWordTransition(NFAState state) : base(state)
- {
- }
-
- public override bool IsAscii()
- {
- return false;
- }
-
- public override bool Match(char ch)
- {
- bool word = ('a' <= ch && ch <= 'z')
- || ('A' <= ch && ch <= 'Z')
- || ('0' <= ch && ch <= '9')
- || ch == '_';
- return !word;
- }
-
- public override NFATransition Copy(NFAState state)
- {
- return new NFANonWordTransition(state);
- }
- }
-
-
- /**
- * An NFA state queue. This queue is used during processing to
- * keep track of the current and subsequent NFA states. The
- * current state is read from the beginning of the queue, and new
- * states are added at the end. A marker index is used to
- * separate the current from the subsequent states.
- *
- * The queue implementation is optimized for quick removal at the
- * beginning and addition at the end. It will attempt to use a
- * fixed-size array to store the whole queue, and moves the data
- * in this array only when absolutely needed. The array is also
- * enlarged automatically if too many states are being processed
- * at a single time.
- */
- internal class NFAStateQueue
- {
-
- private NFAState[] _queue = new NFAState[2048];
-
- private int _first = 0;
-
- private int _last = 0;
-
- private int _mark = 0;
-
- public bool Empty => (_last <= _first);
-
- public bool Marked => _first == _mark;
-
- public void Clear()
- {
- _first = 0;
- _last = 0;
- _mark = 0;
- }
-
- public void MarkEnd()
- {
- _mark = _last;
- }
-
- public NFAState RemoveFirst()
- {
- if (_first < _last)
- {
- _first++;
- return _queue[_first - 1];
- }
- else
- {
- return null;
- }
- }
-
- public void AddLast(NFAState state)
- {
- if (_last >= _queue.Length)
- {
- if (_first <= 0)
- {
- Array.Resize(ref _queue, _queue.Length * 2);
- }
- else
- {
- Array.Copy(_queue, _first, _queue, 0, _last - _first);
- _last -= _first;
- _mark -= _first;
- _first = 0;
- }
- }
- _queue[_last++] = state;
- }
- }
-}
diff --git a/src/Flee.NetStandard20/Parsing/grammatica-1.5.alpha2/PerCederberg.Grammatica.Runtime/TokenPattern.cs b/src/Flee.NetStandard20/Parsing/grammatica-1.5.alpha2/PerCederberg.Grammatica.Runtime/TokenPattern.cs
deleted file mode 100644
index 5276cf8..0000000
--- a/src/Flee.NetStandard20/Parsing/grammatica-1.5.alpha2/PerCederberg.Grammatica.Runtime/TokenPattern.cs
+++ /dev/null
@@ -1,307 +0,0 @@
-using System;
-using System.Collections;
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.Text;
-
-namespace Flee.Parsing.grammatica_1._5.alpha2.PerCederberg.Grammatica.Runtime
-{
- /**
- * A token pattern. This class contains the definition of a token
- * (i.e. it's pattern), and allows testing a string against this
- * pattern. A token pattern is uniquely identified by an integer id,
- * that must be provided upon creation.
- *
-
- */
- internal class TokenPattern
- {
- public enum PatternType
- {
-
- /**
- * The string pattern type is used for tokens that only
- * match an exact string.
- */
- STRING,
-
- /**
- * The regular expression pattern type is used for tokens
- * that match a regular expression.
- */
- REGEXP
- }
-
- private int _id;
- private string _name;
- private PatternType _type;
- private string _pattern;
- private bool _error;
- private string _errorMessage;
- private bool _ignore;
- private string _ignoreMessage;
- private string _debugInfo;
-
- public TokenPattern(int id,
- string name,
- PatternType type,
- string pattern)
- {
-
- this._id = id;
- this._name = name;
- this._type = type;
- this._pattern = pattern;
- }
-
- public int Id
- {
- get
- {
- return _id;
- }
- set { _id = value; }
- }
-
- public int GetId()
- {
- return _id;
- }
-
- public string Name
- {
- get
- {
- return _name;
- }
- set { _name = value; }
- }
-
- public string GetName()
- {
- return _name;
- }
-
- public PatternType Type
- {
- get
- {
- return _type;
- }
- set { _type = value; }
- }
-
- public PatternType GetPatternType()
- {
- return _type;
- }
-
- public string Pattern
- {
- get
- {
- return _pattern;
- }
- set { _pattern = value; }
- }
-
- public string GetPattern()
- {
- return _pattern;
- }
-
- public bool Error
- {
- get
- {
- return _error;
- }
- set
- {
- _error = value;
- if (_error && _errorMessage == null)
- {
- _errorMessage = "unrecognized token found";
- }
- }
- }
-
- public string ErrorMessage
- {
- get
- {
- return _errorMessage;
- }
- set
- {
- _error = true;
- _errorMessage = value;
- }
- }
-
- public bool IsError()
- {
- return Error;
- }
-
- public string GetErrorMessage()
- {
- return ErrorMessage;
- }
-
- public void SetError()
- {
- Error = true;
- }
-
- public void SetError(string message)
- {
- ErrorMessage = message;
- }
-
- public bool Ignore
- {
- get
- {
- return _ignore;
- }
- set
- {
- _ignore = value;
- }
- }
-
- public string IgnoreMessage
- {
- get
- {
- return _ignoreMessage;
- }
- set
- {
- _ignore = true;
- _ignoreMessage = value;
- }
- }
-
- public bool IsIgnore()
- {
- return Ignore;
- }
-
- public string GetIgnoreMessage()
- {
- return IgnoreMessage;
- }
-
-
- public void SetIgnore()
- {
- Ignore = true;
- }
-
-
- public void SetIgnore(string message)
- {
- IgnoreMessage = message;
- }
-
- public string DebugInfo
- {
- get
- {
- return _debugInfo;
- }
- set
- {
- _debugInfo = value;
- }
- }
-
- public override string ToString()
- {
- StringBuilder buffer = new StringBuilder();
-
- buffer.Append(_name);
- buffer.Append(" (");
- buffer.Append(_id);
- buffer.Append("): ");
- switch (_type)
- {
- case PatternType.STRING:
- buffer.Append("\"");
- buffer.Append(_pattern);
- buffer.Append("\"");
- break;
- case PatternType.REGEXP:
- buffer.Append("<<");
- buffer.Append(_pattern);
- buffer.Append(">>");
- break;
- }
- if (_error)
- {
- buffer.Append(" ERROR: \"");
- buffer.Append(_errorMessage);
- buffer.Append("\"");
- }
- if (_ignore)
- {
- buffer.Append(" IGNORE");
- if (_ignoreMessage != null)
- {
- buffer.Append(": \"");
- buffer.Append(_ignoreMessage);
- buffer.Append("\"");
- }
- }
- if (_debugInfo != null)
- {
- buffer.Append("\n ");
- buffer.Append(_debugInfo);
- }
- return buffer.ToString();
- }
-
- public string ToShortString()
- {
- StringBuilder buffer = new StringBuilder();
- int newline = _pattern.IndexOf('\n');
-
- if (_type == PatternType.STRING)
- {
- buffer.Append("\"");
- if (newline >= 0)
- {
- if (newline > 0 && _pattern[newline - 1] == '\r')
- {
- newline--;
- }
- buffer.Append(_pattern.Substring(0, newline));
- buffer.Append("(...)");
- }
- else
- {
- buffer.Append(_pattern);
- }
- buffer.Append("\"");
- }
- else
- {
- buffer.Append("<");
- buffer.Append(_name);
- buffer.Append(">");
- }
-
- return buffer.ToString();
- }
-
- public void SetData(int id, string name, PatternType type, string pattern)
- {
- Id = id;
- Name = name;
- Type = type;
- Pattern = pattern;
- }
- }
-}
diff --git a/src/Flee.NetStandard20/Parsing/grammatica-1.5.alpha2/PerCederberg.Grammatica.Runtime/TokenRegExpParser.cs b/src/Flee.NetStandard20/Parsing/grammatica-1.5.alpha2/PerCederberg.Grammatica.Runtime/TokenRegExpParser.cs
deleted file mode 100644
index 0a32150..0000000
--- a/src/Flee.NetStandard20/Parsing/grammatica-1.5.alpha2/PerCederberg.Grammatica.Runtime/TokenRegExpParser.cs
+++ /dev/null
@@ -1,550 +0,0 @@
-using System;
-using System.Collections;
-using System.Collections.Generic;
-using System.Globalization;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-using Flee.Parsing.grammatica_1._5.alpha2.PerCederberg.Grammatica.Runtime.RE;
-
-namespace Flee.Parsing.grammatica_1._5.alpha2.PerCederberg.Grammatica.Runtime
-{
- /**
- * A regular expression parser. The parser creates an NFA for the
- * regular expression having a single start and acceptance states.
- */
- internal class TokenRegExpParser
- {
- private readonly string _pattern;
- private readonly bool _ignoreCase;
- private int _pos;
- internal NFAState Start = new NFAState();
- internal NFAState End;
- private int _stateCount;
- private int _transitionCount;
- private int _epsilonCount;
-
- public TokenRegExpParser(string pattern) : this(pattern, false)
- {
- }
-
- public TokenRegExpParser(string pattern, bool ignoreCase)
- {
- this._pattern = pattern;
- this._ignoreCase = ignoreCase;
- this._pos = 0;
- this.End = ParseExpr(Start);
- if (_pos < pattern.Length)
- {
- throw new RegExpException(
- RegExpException.ErrorType.UNEXPECTED_CHARACTER,
- _pos,
- pattern);
- }
- }
-
- public string GetDebugInfo()
- {
- if (_stateCount == 0)
- {
- UpdateStats(Start, new Hashtable());
- }
- return _stateCount + " states, " +
- _transitionCount + " transitions, " +
- _epsilonCount + " epsilons";
- }
-
- private void UpdateStats(NFAState state, Hashtable visited)
- {
- if (!visited.ContainsKey(state))
- {
- visited.Add(state, state);
- _stateCount++;
- for (int i = 0; i < state.Outgoing.Length; i++)
- {
- _transitionCount++;
- if (state.Outgoing[i] is NFAEpsilonTransition)
- {
- _epsilonCount++;
- }
- UpdateStats(state.Outgoing[i].State, visited);
- }
- }
- }
-
- private NFAState ParseExpr(NFAState start)
- {
- NFAState end = new NFAState();
- do
- {
- if (PeekChar(0) == '|')
- {
- ReadChar('|');
- }
- var subStart = new NFAState();
- var subEnd = ParseTerm(subStart);
- if (subStart.Incoming.Length == 0)
- {
- subStart.MergeInto(start);
- }
- else
- {
- start.AddOut(new NFAEpsilonTransition(subStart));
- }
- if (subEnd.Outgoing.Length == 0 ||
- (!end.HasTransitions() && PeekChar(0) != '|'))
- {
- subEnd.MergeInto(end);
- }
- else
- {
- subEnd.AddOut(new NFAEpsilonTransition(end));
- }
- } while (PeekChar(0) == '|');
- return end;
- }
-
- private NFAState ParseTerm(NFAState start)
- {
- var end = ParseFact(start);
- while (true)
- {
- switch (PeekChar(0))
- {
- case -1:
- case ')':
- case ']':
- case '{':
- case '}':
- case '?':
- case '+':
- case '|':
- return end;
- default:
- end = ParseFact(end);
- break;
- }
- }
- }
-
- private NFAState ParseFact(NFAState start)
- {
- NFAState placeholder = new NFAState();
-
- var end = ParseAtom(placeholder);
- switch (PeekChar(0))
- {
- case '?':
- case '*':
- case '+':
- case '{':
- end = ParseAtomModifier(placeholder, end);
- break;
- }
- if (placeholder.Incoming.Length > 0 && start.Outgoing.Length > 0)
- {
- start.AddOut(new NFAEpsilonTransition(placeholder));
- return end;
- }
- else
- {
- placeholder.MergeInto(start);
- return (end == placeholder) ? start : end;
- }
- }
-
- private NFAState ParseAtom(NFAState start)
- {
- NFAState end;
-
- switch (PeekChar(0))
- {
- case '.':
- ReadChar('.');
- return start.AddOut(new NFADotTransition(new NFAState()));
- case '(':
- ReadChar('(');
- end = ParseExpr(start);
- ReadChar(')');
- return end;
- case '[':
- ReadChar('[');
- end = ParseCharSet(start);
- ReadChar(']');
- return end;
- case -1:
- case ')':
- case ']':
- case '{':
- case '}':
- case '?':
- case '*':
- case '+':
- case '|':
- throw new RegExpException(
- RegExpException.ErrorType.UNEXPECTED_CHARACTER,
- _pos,
- _pattern);
- default:
- return ParseChar(start);
- }
- }
-
- private NFAState ParseAtomModifier(NFAState start, NFAState end)
- {
- int min = 0;
- int max = -1;
- int firstPos = _pos;
-
- // Read min and max
- switch (ReadChar())
- {
- case '?':
- min = 0;
- max = 1;
- break;
- case '*':
- min = 0;
- max = -1;
- break;
- case '+':
- min = 1;
- max = -1;
- break;
- case '{':
- min = ReadNumber();
- max = min;
- if (PeekChar(0) == ',')
- {
- ReadChar(',');
- max = -1;
- if (PeekChar(0) != '}')
- {
- max = ReadNumber();
- }
- }
- ReadChar('}');
- if (max == 0 || (max > 0 && min > max))
- {
- throw new RegExpException(
- RegExpException.ErrorType.INVALID_REPEAT_COUNT,
- firstPos,
- _pattern);
- }
- break;
- default:
- throw new RegExpException(
- RegExpException.ErrorType.UNEXPECTED_CHARACTER,
- _pos - 1,
- _pattern);
- }
-
- // Read possessive or reluctant modifiers
- if (PeekChar(0) == '?')
- {
- throw new RegExpException(
- RegExpException.ErrorType.UNSUPPORTED_SPECIAL_CHARACTER,
- _pos,
- _pattern);
- }
- else if (PeekChar(0) == '+')
- {
- throw new RegExpException(
- RegExpException.ErrorType.UNSUPPORTED_SPECIAL_CHARACTER,
- _pos,
- _pattern);
- }
-
- // Handle supported repeaters
- if (min == 0 && max == 1)
- {
- return start.AddOut(new NFAEpsilonTransition(end));
- }
- else if (min == 0 && max == -1)
- {
- if (end.Outgoing.Length == 0)
- {
- end.MergeInto(start);
- }
- else
- {
- end.AddOut(new NFAEpsilonTransition(start));
- }
- return start;
- }
- else if (min == 1 && max == -1)
- {
- if (start.Outgoing.Length == 1 &&
- end.Outgoing.Length == 0 &&
- end.Incoming.Length == 1 &&
- start.Outgoing[0] == end.Incoming[0])
- {
-
- end.AddOut(start.Outgoing[0].Copy(end));
- }
- else
- {
- end.AddOut(new NFAEpsilonTransition(start));
- }
- return end;
- }
- else
- {
- throw new RegExpException(
- RegExpException.ErrorType.INVALID_REPEAT_COUNT,
- firstPos,
- _pattern);
- }
- }
-
- private NFAState ParseCharSet(NFAState start)
- {
- NFAState end = new NFAState();
- NFACharRangeTransition range;
-
- if (PeekChar(0) == '^')
- {
- ReadChar('^');
- range = new NFACharRangeTransition(true, _ignoreCase, end);
- }
- else
- {
- range = new NFACharRangeTransition(false, _ignoreCase, end);
- }
- start.AddOut(range);
- while (PeekChar(0) > 0)
- {
- var min = (char)PeekChar(0);
- switch (min)
- {
- case ']':
- return end;
- case '\\':
- range.AddCharacter(ReadEscapeChar());
- break;
- default:
- ReadChar(min);
- if (PeekChar(0) == '-' &&
- PeekChar(1) > 0 &&
- PeekChar(1) != ']')
- {
-
- ReadChar('-');
- var max = ReadChar();
- range.AddRange(min, max);
- }
- else
- {
- range.AddCharacter(min);
- }
- break;
- }
- }
- return end;
- }
-
- private NFAState ParseChar(NFAState start)
- {
- switch (PeekChar(0))
- {
- case '\\':
- return ParseEscapeChar(start);
- case '^':
- case '$':
- throw new RegExpException(
- RegExpException.ErrorType.UNSUPPORTED_SPECIAL_CHARACTER,
- _pos,
- _pattern);
- default:
- return start.AddOut(ReadChar(), _ignoreCase, new NFAState());
- }
- }
-
- private NFAState ParseEscapeChar(NFAState start)
- {
- NFAState end = new NFAState();
-
- if (PeekChar(0) == '\\' && PeekChar(1) > 0)
- {
- switch ((char)PeekChar(1))
- {
- case 'd':
- ReadChar();
- ReadChar();
- return start.AddOut(new NFADigitTransition(end));
- case 'D':
- ReadChar();
- ReadChar();
- return start.AddOut(new NFANonDigitTransition(end));
- case 's':
- ReadChar();
- ReadChar();
- return start.AddOut(new NFAWhitespaceTransition(end));
- case 'S':
- ReadChar();
- ReadChar();
- return start.AddOut(new NFANonWhitespaceTransition(end));
- case 'w':
- ReadChar();
- ReadChar();
- return start.AddOut(new NFAWordTransition(end));
- case 'W':
- ReadChar();
- ReadChar();
- return start.AddOut(new NFANonWordTransition(end));
- }
- }
- return start.AddOut(ReadEscapeChar(), _ignoreCase, end);
- }
-
- private char ReadEscapeChar()
- {
- string str;
- int value;
-
- ReadChar('\\');
- var c = ReadChar();
- switch (c)
- {
- case '0':
- c = ReadChar();
- if (c < '0' || c > '3')
- {
- throw new RegExpException(
- RegExpException.ErrorType.UNSUPPORTED_ESCAPE_CHARACTER,
- _pos - 3,
- _pattern);
- }
- value = c - '0';
- c = (char)PeekChar(0);
- if ('0' <= c && c <= '7')
- {
- value *= 8;
- value += ReadChar() - '0';
- c = (char)PeekChar(0);
- if ('0' <= c && c <= '7')
- {
- value *= 8;
- value += ReadChar() - '0';
- }
- }
- return (char)value;
- case 'x':
- str = ReadChar().ToString() + ReadChar().ToString();
- try
- {
- value = Int32.Parse(str, NumberStyles.AllowHexSpecifier);
- return (char)value;
- }
- catch (FormatException)
- {
- throw new RegExpException(
- RegExpException.ErrorType.UNSUPPORTED_ESCAPE_CHARACTER,
- _pos - str.Length - 2,
- _pattern);
- }
- case 'u':
- str = ReadChar().ToString() +
- ReadChar().ToString() +
- ReadChar().ToString() +
- ReadChar().ToString();
- try
- {
- value = Int32.Parse(str, NumberStyles.AllowHexSpecifier);
- return (char)value;
- }
- catch (FormatException)
- {
- throw new RegExpException(
- RegExpException.ErrorType.UNSUPPORTED_ESCAPE_CHARACTER,
- _pos - str.Length - 2,
- _pattern);
- }
- case 't':
- return '\t';
- case 'n':
- return '\n';
- case 'r':
- return '\r';
- case 'f':
- return '\f';
- case 'a':
- return '\u0007';
- case 'e':
- return '\u001B';
- default:
- if (('A' <= c && c <= 'Z') || ('a' <= c && c <= 'z'))
- {
- throw new RegExpException(
- RegExpException.ErrorType.UNSUPPORTED_ESCAPE_CHARACTER,
- _pos - 2,
- _pattern);
- }
- return c;
- }
- }
-
- private int ReadNumber()
- {
- StringBuilder buf = new StringBuilder();
- int c;
-
- c = PeekChar(0);
- while ('0' <= c && c <= '9')
- {
- buf.Append(ReadChar());
- c = PeekChar(0);
- }
- if (buf.Length <= 0)
- {
- throw new RegExpException(
- RegExpException.ErrorType.UNEXPECTED_CHARACTER,
- _pos,
- _pattern);
- }
- return Int32.Parse(buf.ToString());
- }
-
- private char ReadChar()
- {
- int c = PeekChar(0);
-
- if (c < 0)
- {
- throw new RegExpException(
- RegExpException.ErrorType.UNTERMINATED_PATTERN,
- _pos,
- _pattern);
- }
- else
- {
- _pos++;
- return (char)c;
- }
- }
-
- private char ReadChar(char c)
- {
- if (c != ReadChar())
- {
- throw new RegExpException(
- RegExpException.ErrorType.UNEXPECTED_CHARACTER,
- _pos - 1,
- _pattern);
- }
- return c;
- }
-
- private int PeekChar(int count)
- {
- if (_pos + count < _pattern.Length)
- {
- return _pattern[_pos + count];
- }
- else
- {
- return -1;
- }
- }
- }
-}
diff --git a/src/Flee.NetStandard20/PublicTypes/ExpressionImports.cs b/src/Flee.NetStandard20/PublicTypes/ExpressionImports.cs
deleted file mode 100644
index ef6d4e7..0000000
--- a/src/Flee.NetStandard20/PublicTypes/ExpressionImports.cs
+++ /dev/null
@@ -1,200 +0,0 @@
-using System;
-using System.Collections;
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.Reflection;
-using Flee.InternalTypes;
-using Flee.PublicTypes;
-using Flee.Resources;
-
-namespace Flee.PublicTypes
-{
- public sealed class ExpressionImports
- {
-
- private static Dictionary OurBuiltinTypeMap = CreateBuiltinTypeMap();
- private NamespaceImport MyRootImport;
- private TypeImport MyOwnerImport;
-
- private ExpressionContext MyContext;
- internal ExpressionImports()
- {
- MyRootImport = new NamespaceImport("true");
- }
-
- private static Dictionary CreateBuiltinTypeMap()
- {
- Dictionary map = new Dictionary(StringComparer.OrdinalIgnoreCase);
-
- map.Add("boolean", typeof(bool));
- map.Add("byte", typeof(byte));
- map.Add("sbyte", typeof(sbyte));
- map.Add("short", typeof(short));
- map.Add("ushort", typeof(UInt16));
- map.Add("int", typeof(Int32));
- map.Add("uint", typeof(UInt32));
- map.Add("long", typeof(long));
- map.Add("ulong", typeof(ulong));
- map.Add("single", typeof(float));
- map.Add("double", typeof(double));
- map.Add("decimal", typeof(decimal));
- map.Add("char", typeof(char));
- map.Add("object", typeof(object));
- map.Add("string", typeof(string));
-
- return map;
- }
-
- #region "Methods - Non public"
- internal void SetContext(ExpressionContext context)
- {
- MyContext = context;
- MyRootImport.SetContext(context);
- }
-
- internal ExpressionImports Clone()
- {
- ExpressionImports copy = new ExpressionImports();
-
- copy.MyRootImport = (NamespaceImport)MyRootImport.Clone();
- copy.MyOwnerImport = MyOwnerImport;
-
- return copy;
- }
-
- internal void ImportOwner(Type ownerType)
- {
- MyOwnerImport = new TypeImport(ownerType, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static, false);
- MyOwnerImport.SetContext(MyContext);
- }
-
- internal bool HasNamespace(string ns)
- {
- NamespaceImport import = MyRootImport.FindImport(ns) as NamespaceImport;
- return (import != null);
- }
-
- internal NamespaceImport GetImport(string ns)
- {
- if (ns.Length == 0)
- {
- return MyRootImport;
- }
-
- NamespaceImport import = MyRootImport.FindImport(ns) as NamespaceImport;
-
- if (import == null)
- {
- import = new NamespaceImport(ns);
- MyRootImport.Add(import);
- }
-
- return import;
- }
-
- internal MemberInfo[] FindOwnerMembers(string memberName, System.Reflection.MemberTypes memberType)
- {
- return MyOwnerImport.FindMembers(memberName, memberType);
- }
-
- internal Type FindType(string[] typeNameParts)
- {
- string[] namespaces = new string[typeNameParts.Length - 1];
- string typeName = typeNameParts[typeNameParts.Length - 1];
-
- System.Array.Copy(typeNameParts, namespaces, namespaces.Length);
- ImportBase currentImport = MyRootImport;
-
- foreach (string ns in namespaces)
- {
- currentImport = currentImport.FindImport(ns);
- if (currentImport == null)
- {
- break; // TODO: might not be correct. Was : Exit For
- }
- }
-
- return currentImport?.FindType(typeName);
- }
-
- static internal Type GetBuiltinType(string name)
- {
- Type t = null;
-
- if (OurBuiltinTypeMap.TryGetValue(name, out t) == true)
- {
- return t;
- }
- else
- {
- return null;
- }
- }
- #endregion
-
- #region "Methods - Public"
- public void AddType(Type t, string ns)
- {
- Utility.AssertNotNull(t, "t");
- Utility.AssertNotNull(ns, "namespace");
-
- MyContext.AssertTypeIsAccessible(t);
-
- NamespaceImport import = this.GetImport(ns);
- import.Add(new TypeImport(t, BindingFlags.Public | BindingFlags.Static, false));
- }
-
- public void AddType(Type t)
- {
- this.AddType(t, string.Empty);
- }
-
- public void AddMethod(string methodName, Type t, string ns)
- {
- Utility.AssertNotNull(methodName, "methodName");
- Utility.AssertNotNull(t, "t");
- Utility.AssertNotNull(ns, "namespace");
-
- MethodInfo mi = t.GetMethod(methodName, BindingFlags.Public | BindingFlags.Static | BindingFlags.IgnoreCase);
-
- if (mi == null)
- {
- string msg = Utility.GetGeneralErrorMessage(GeneralErrorResourceKeys.CouldNotFindPublicStaticMethodOnType, methodName, t.Name);
- throw new ArgumentException(msg);
- }
-
- this.AddMethod(mi, ns);
- }
-
- public void AddMethod(MethodInfo mi, string ns)
- {
- Utility.AssertNotNull(mi, "mi");
- Utility.AssertNotNull(ns, "namespace");
-
- MyContext.AssertTypeIsAccessible(mi.ReflectedType);
-
- if (mi.IsStatic == false | mi.IsPublic == false)
- {
- string msg = Utility.GetGeneralErrorMessage(GeneralErrorResourceKeys.OnlyPublicStaticMethodsCanBeImported);
- throw new ArgumentException(msg);
- }
-
- NamespaceImport import = this.GetImport(ns);
- import.Add(new MethodImport(mi));
- }
-
- public void ImportBuiltinTypes()
- {
- foreach (KeyValuePair pair in OurBuiltinTypeMap)
- {
- this.AddType(pair.Value, pair.Key);
- }
- }
- #endregion
-
- #region "Properties - Public"
- public NamespaceImport RootImport => MyRootImport;
-
- #endregion
- }
-}
diff --git a/src/Flee.NetStandard20/PublicTypes/ExpressionOptions.cs b/src/Flee.NetStandard20/PublicTypes/ExpressionOptions.cs
deleted file mode 100644
index efb166d..0000000
--- a/src/Flee.NetStandard20/PublicTypes/ExpressionOptions.cs
+++ /dev/null
@@ -1,212 +0,0 @@
-using System;
-using System.Collections;
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.Reflection.Emit;
-using System.Reflection;
-using System.Globalization;
-using Flee.InternalTypes;
-
-
-namespace Flee.PublicTypes
-{
- public sealed class ExpressionOptions
- {
-
- private PropertyDictionary _myProperties;
- private Type _myOwnerType;
- private readonly ExpressionContext _myOwner;
- internal event EventHandler CaseSensitiveChanged;
-
- internal ExpressionOptions(ExpressionContext owner)
- {
- _myOwner = owner;
- _myProperties = new PropertyDictionary();
-
- this.InitializeProperties();
- }
-
- #region "Methods - Private"
-
- private void InitializeProperties()
- {
- this.StringComparison = System.StringComparison.Ordinal;
- this.OwnerMemberAccess = BindingFlags.Public;
-
- _myProperties.SetToDefault("CaseSensitive");
- _myProperties.SetToDefault("Checked");
- _myProperties.SetToDefault("EmitToAssembly");
- _myProperties.SetToDefault("ResultType");
- _myProperties.SetToDefault("IsGeneric");
- _myProperties.SetToDefault("IntegersAsDoubles");
- _myProperties.SetValue("ParseCulture", CultureInfo.CurrentCulture);
- this.SetParseCulture(this.ParseCulture);
- _myProperties.SetValue("RealLiteralDataType", RealLiteralDataType.Double);
- }
-
- private void SetParseCulture(CultureInfo ci)
- {
- ExpressionParserOptions po = _myOwner.ParserOptions;
- po.DecimalSeparator = Convert.ToChar(ci.NumberFormat.NumberDecimalSeparator);
- po.FunctionArgumentSeparator = Convert.ToChar(ci.TextInfo.ListSeparator);
- po.DateTimeFormat = ci.DateTimeFormat.ShortDatePattern;
- }
-
- #endregion
-
- #region "Methods - Internal"
-
- internal ExpressionOptions Clone()
- {
- ExpressionOptions clonedOptions = (ExpressionOptions)this.MemberwiseClone();
- clonedOptions._myProperties = _myProperties.Clone();
- return clonedOptions;
- }
-
- internal bool IsOwnerType(Type t)
- {
- return this._myOwnerType.IsAssignableFrom(t);
- }
-
- internal void SetOwnerType(Type ownerType)
- {
- _myOwnerType = ownerType;
- }
-
- #endregion
-
- #region "Properties - Public"
- public Type ResultType
- {
- get { return _myProperties.GetValue("ResultType"); }
- set
- {
- Utility.AssertNotNull(value, "value");
- _myProperties.SetValue("ResultType", value);
- }
- }
-
- public bool Checked
- {
- get { return _myProperties.GetValue("Checked"); }
- set { _myProperties.SetValue("Checked", value); }
- }
-
- public StringComparison StringComparison
- {
- get { return _myProperties.GetValue("StringComparison"); }
- set { _myProperties.SetValue("StringComparison", value); }
- }
-
- public bool EmitToAssembly
- {
- get { return _myProperties.GetValue("EmitToAssembly"); }
- set { _myProperties.SetValue("EmitToAssembly", value); }
- }
-
- public BindingFlags OwnerMemberAccess
- {
- get { return _myProperties.GetValue("OwnerMemberAccess"); }
- set { _myProperties.SetValue("OwnerMemberAccess", value); }
- }
-
- public bool CaseSensitive
- {
- get { return _myProperties.GetValue("CaseSensitive"); }
- set
- {
- if (this.CaseSensitive != value)
- {
- _myProperties.SetValue("CaseSensitive", value);
- if (CaseSensitiveChanged != null)
- {
- CaseSensitiveChanged(this, EventArgs.Empty);
- }
- }
- }
- }
-
- public bool IntegersAsDoubles
- {
- get { return _myProperties.GetValue("IntegersAsDoubles"); }
- set { _myProperties.SetValue("IntegersAsDoubles", value); }
- }
-
- public CultureInfo ParseCulture
- {
- get { return _myProperties.GetValue("ParseCulture"); }
- set
- {
- Utility.AssertNotNull(value, "ParseCulture");
- if ((value.LCID != this.ParseCulture.LCID))
- {
- _myProperties.SetValue("ParseCulture", value);
- this.SetParseCulture(value);
- _myOwner.ParserOptions.RecreateParser();
- }
- }
- }
-
- public RealLiteralDataType RealLiteralDataType
- {
- get { return _myProperties.GetValue("RealLiteralDataType"); }
- set { _myProperties.SetValue("RealLiteralDataType", value); }
- }
- #endregion
-
- #region "Properties - Non Public"
- internal IEqualityComparer StringComparer
- {
- get
- {
- if (this.CaseSensitive == true)
- {
- return System.StringComparer.Ordinal;
- }
- else
- {
- return System.StringComparer.OrdinalIgnoreCase;
- }
- }
- }
-
- internal MemberFilter MemberFilter
- {
- get
- {
- if (this.CaseSensitive == true)
- {
- return Type.FilterName;
- }
- else
- {
- return Type.FilterNameIgnoreCase;
- }
- }
- }
-
- internal StringComparison MemberStringComparison
- {
- get
- {
- if (this.CaseSensitive == true)
- {
- return System.StringComparison.Ordinal;
- }
- else
- {
- return System.StringComparison.OrdinalIgnoreCase;
- }
- }
- }
-
- internal Type OwnerType => _myOwnerType;
-
- internal bool IsGeneric
- {
- get { return _myProperties.GetValue("IsGeneric"); }
- set { _myProperties.SetValue("IsGeneric", value); }
- }
- #endregion
- }
-}
diff --git a/src/Flee.NetStandard20/PublicTypes/ExpressionParserOptions.cs b/src/Flee.NetStandard20/PublicTypes/ExpressionParserOptions.cs
deleted file mode 100644
index 467dcde..0000000
--- a/src/Flee.NetStandard20/PublicTypes/ExpressionParserOptions.cs
+++ /dev/null
@@ -1,104 +0,0 @@
-using System;
-using System.Collections;
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.Globalization;
-using Flee.InternalTypes;
-using Flee.PublicTypes;
-
-namespace Flee.PublicTypes
-{
- public class ExpressionParserOptions
- {
- private PropertyDictionary _myProperties;
- private readonly ExpressionContext _myOwner;
- private readonly CultureInfo _myParseCulture;
-
- private NumberStyles NumberStyles = NumberStyles.AllowDecimalPoint | NumberStyles.AllowExponent | NumberStyles.None;
- internal ExpressionParserOptions(ExpressionContext owner)
- {
- _myOwner = owner;
- _myProperties = new PropertyDictionary();
- _myParseCulture = (CultureInfo)CultureInfo.InvariantCulture.Clone();
- this.InitializeProperties();
- }
-
- #region "Methods - Public"
-
- public void RecreateParser()
- {
- _myOwner.RecreateParser();
- }
-
- #endregion
-
- #region "Methods - Internal"
-
- internal ExpressionParserOptions Clone()
- {
- ExpressionParserOptions copy = (ExpressionParserOptions)this.MemberwiseClone();
- copy._myProperties = _myProperties.Clone();
- return copy;
- }
-
- internal double ParseDouble(string image)
- {
- return double.Parse(image, NumberStyles, _myParseCulture);
- }
-
- internal float ParseSingle(string image)
- {
- return float.Parse(image, NumberStyles, _myParseCulture);
- }
-
- internal decimal ParseDecimal(string image)
- {
- return decimal.Parse(image, NumberStyles, _myParseCulture);
- }
- #endregion
-
- #region "Methods - Private"
-
- private void InitializeProperties()
- {
- this.DateTimeFormat = "dd/MM/yyyy";
- this.RequireDigitsBeforeDecimalPoint = false;
- this.DecimalSeparator = '.';
- this.FunctionArgumentSeparator = ',';
- }
-
- #endregion
-
- #region "Properties - Public"
-
- public string DateTimeFormat
- {
- get { return _myProperties.GetValue("DateTimeFormat"); }
- set { _myProperties.SetValue("DateTimeFormat", value); }
- }
-
- public bool RequireDigitsBeforeDecimalPoint
- {
- get { return _myProperties.GetValue("RequireDigitsBeforeDecimalPoint"); }
- set { _myProperties.SetValue("RequireDigitsBeforeDecimalPoint", value); }
- }
-
- public char DecimalSeparator
- {
- get { return _myProperties.GetValue("DecimalSeparator"); }
- set
- {
- _myProperties.SetValue("DecimalSeparator", value);
- _myParseCulture.NumberFormat.NumberDecimalSeparator = value.ToString();
- }
- }
-
- public char FunctionArgumentSeparator
- {
- get { return _myProperties.GetValue("FunctionArgumentSeparator"); }
- set { _myProperties.SetValue("FunctionArgumentSeparator", value); }
- }
-
- #endregion
- }
-}
diff --git a/src/Flee.NetStandard20/PublicTypes/VariableCollection.cs b/src/Flee.NetStandard20/PublicTypes/VariableCollection.cs
deleted file mode 100644
index 51ab01e..0000000
--- a/src/Flee.NetStandard20/PublicTypes/VariableCollection.cs
+++ /dev/null
@@ -1,406 +0,0 @@
-using Flee.InternalTypes;
-using Flee.Resources;
-using System;
-using System.Collections.Generic;
-using System.ComponentModel;
-using System.Reflection;
-
-namespace Flee.PublicTypes
-{
- ///
- ///
- ///
- public sealed class VariableCollection : IDictionary
- {
- private IDictionary _myVariables;
- private readonly ExpressionContext _myContext;
-
- public event EventHandler ResolveVariableType;
-
- public event EventHandler ResolveVariableValue;
-
- public event EventHandler ResolveFunction;
-
- public event EventHandler InvokeFunction;
-
- internal VariableCollection(ExpressionContext context)
- {
- _myContext = context;
- this.CreateDictionary();
- this.HookOptions();
- }
-
- #region "Methods - Non Public"
-
- private void HookOptions()
- {
- _myContext.Options.CaseSensitiveChanged += OnOptionsCaseSensitiveChanged;
- }
-
- private void CreateDictionary()
- {
- _myVariables = new Dictionary(_myContext.Options.StringComparer);
- }
-
- private void OnOptionsCaseSensitiveChanged(object sender, EventArgs e)
- {
- this.CreateDictionary();
- }
-
- internal void Copy(VariableCollection dest)
- {
- dest.CreateDictionary();
- dest.HookOptions();
-
- foreach (KeyValuePair pair in _myVariables)
- {
- IVariable copyVariable = pair.Value.Clone();
- dest._myVariables.Add(pair.Key, copyVariable);
- }
- }
-
- internal void DefineVariableInternal(string name, Type variableType, object variableValue)
- {
- Utility.AssertNotNull(variableType, "variableType");
-
- if (_myVariables.ContainsKey(name) == true)
- {
- string msg = Utility.GetGeneralErrorMessage(GeneralErrorResourceKeys.VariableWithNameAlreadyDefined, name);
- throw new ArgumentException(msg);
- }
-
- IVariable v = this.CreateVariable(variableType, variableValue);
- _myVariables.Add(name, v);
- }
-
- internal Type GetVariableTypeInternal(string name)
- {
- IVariable value = null;
- bool success = _myVariables.TryGetValue(name, out value);
-
- if (success == true)
- {
- return value.VariableType;
- }
-
- ResolveVariableTypeEventArgs args = new ResolveVariableTypeEventArgs(name);
- ResolveVariableType?.Invoke(this, args);
-
- return args.VariableType;
- }
-
- private IVariable GetVariable(string name, bool throwOnNotFound)
- {
- IVariable value = null;
- bool success = _myVariables.TryGetValue(name, out value);
-
- if (success == false & throwOnNotFound == true)
- {
- string msg = Utility.GetGeneralErrorMessage(GeneralErrorResourceKeys.UndefinedVariable, name);
- throw new ArgumentException(msg);
- }
- else
- {
- return value;
- }
- }
-
- private IVariable CreateVariable(Type variableValueType, object variableValue)
- {
- Type variableType = default(Type);
-
- // Is the variable value an expression?
- IExpression expression = variableValue as IExpression;
- ExpressionOptions options = null;
-
- if (expression != null)
- {
- options = expression.Context.Options;
- // Get its result type
- variableValueType = options.ResultType;
-
- // Create a variable that wraps the expression
-
- if (options.IsGeneric == false)
- {
- variableType = typeof(DynamicExpressionVariable<>);
- }
- else
- {
- variableType = typeof(GenericExpressionVariable<>);
- }
- }
- else
- {
- // Create a variable for a regular value
- _myContext.AssertTypeIsAccessible(variableValueType);
- variableType = typeof(GenericVariable<>);
- }
-
- // Create the generic variable instance
- variableType = variableType.MakeGenericType(variableValueType);
- IVariable v = (IVariable)Activator.CreateInstance(variableType);
-
- return v;
- }
-
- internal Type ResolveOnDemandFunction(string name, Type[] argumentTypes)
- {
- ResolveFunctionEventArgs args = new ResolveFunctionEventArgs(name, argumentTypes);
- ResolveFunction?.Invoke(this, args);
- return args.ReturnType;
- }
-
- private static T ReturnGenericValue(object value)
- {
- if (value == null)
- {
- return default(T);
- }
- else
- {
- return (T)value;
- }
- }
-
- private static void ValidateSetValueType(Type requiredType, object value)
- {
- if (value == null)
- {
- // Can always assign null value
- return;
- }
-
- Type valueType = value.GetType();
-
- if (requiredType.IsAssignableFrom(valueType) == false)
- {
- string msg = Utility.GetGeneralErrorMessage(GeneralErrorResourceKeys.VariableValueNotAssignableToType, valueType.Name, requiredType.Name);
- throw new ArgumentException(msg);
- }
- }
-
- internal static MethodInfo GetVariableLoadMethod(Type variableType)
- {
- MethodInfo mi = typeof(VariableCollection).GetMethod("GetVariableValueInternal", BindingFlags.Public | BindingFlags.Instance);
- mi = mi.MakeGenericMethod(variableType);
- return mi;
- }
-
- internal static MethodInfo GetFunctionInvokeMethod(Type returnType)
- {
- MethodInfo mi = typeof(VariableCollection).GetMethod("GetFunctionResultInternal", BindingFlags.Public | BindingFlags.Instance);
- mi = mi.MakeGenericMethod(returnType);
- return mi;
- }
-
- internal static MethodInfo GetVirtualPropertyLoadMethod(Type returnType)
- {
- MethodInfo mi = typeof(VariableCollection).GetMethod("GetVirtualPropertyValueInternal", BindingFlags.Public | BindingFlags.Instance);
- mi = mi.MakeGenericMethod(returnType);
- return mi;
- }
-
- private Dictionary GetNameValueDictionary()
- {
- Dictionary dict = new Dictionary();
-
- foreach (KeyValuePair pair in _myVariables)
- {
- dict.Add(pair.Key, pair.Value.ValueAsObject);
- }
-
- return dict;
- }
-
- #endregion "Methods - Non Public"
-
- #region "Methods - Public"
-
- public Type GetVariableType(string name)
- {
- IVariable v = this.GetVariable(name, true);
- return v.VariableType;
- }
-
- public void DefineVariable(string name, Type variableType)
- {
- this.DefineVariableInternal(name, variableType, null);
- }
-
- public T GetVariableValueInternal(string name)
- {
- if (_myVariables.TryGetValue(name, out IVariable variable))
- {
- if (variable is IGenericVariable generic)
- {
- return (T)generic.GetValue();
- }
- }
-
- GenericVariable result = new GenericVariable();
- GenericVariable