Click here to Skip to main content
13,868,202 members
Click here to Skip to main content

Tagged as

Stats

83.9K views
2.4K downloads
92 bookmarked
Posted 19 Sep 2012
Licenced CPOL

Yet Another Math Parser (YAMP)

, 30 Sep 2012
Constructing a fast math parser using Reflection to do numerics like Matlab.
YAMP
YAMPCompare
LLMathParser
MathFormula
MathParser
MathParserNet
Exceptions
MathParserTK
YAMPCompare.pidb
YAMPConsole
YAMPConsole.pidb
Exceptions
Expressions
Functions
ArgumentFunctions
LinearAlgebra
LogicFunctions
Spectroscopy
StandardFunctions
Trigonometric
Interfaces
Numerics
Decompositions
Integration
Interpolations
ODE
Optimization
Others
Solvers
Operators
AssigmentOperators
BinaryOperators
DotOperators
LogicOperators
UnaryOperators
Values
YAMP.csproj.user
YAMP.pidb
YAMP.csproj.user
YAMP.pidb
using System;
using System.Text;
using System.Collections;
using System.Globalization;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Reflection;

namespace YAMP
{
	class Tokens
	{
		#region Members

        IDictionary<string, Operator> operators;
        IDictionary<Regex, Expression> expressions;
        IDictionary<string, FunctionDelegate> functions;
        IDictionary<string, Value> constants;
        IDictionary<string, Value> variables;

        IDictionary<string, FunctionDelegate> o_functions;
        IDictionary<string, Value> o_constants;

		IDictionary<string, string> sanatizers;
		
		#endregion

        #region Fields

        static readonly NumberFormatInfo numFormat = new CultureInfo("en-us").NumberFormat;

        #endregion

        #region ctor

        Tokens ()
		{
            operators = new Dictionary<string, Operator>();
            expressions = new Dictionary<Regex, Expression>();
            functions = new Dictionary<string, FunctionDelegate>();
            constants = new Dictionary<string, Value>();
            o_functions = new Dictionary<string, FunctionDelegate>();
            o_constants = new Dictionary<string, Value>();
            variables = new Dictionary<string, Value>();
			sanatizers = new Dictionary<string, string>();
		}
		
		#endregion
		
		#region Properties

        public IDictionary<string, Value> Variables
		{
			get { return variables; }
		}

		public IDictionary<string, string> Sanatizers
		{
			get { return sanatizers; }
		}
		
		#endregion
		
		#region Register tokens
		
		void RegisterTokens()
		{
			var assembly = Assembly.GetExecutingAssembly();
			var types = assembly.GetTypes();
			var ir = typeof(IRegisterToken).Name;
			var fu = typeof(IFunction).Name;
			var mycst = new Constants();
			var props = mycst.GetType().GetProperties();
			
			foreach(var type in types)
			{
                if (type.IsAbstract)
                    continue;

				if(type.GetInterface(ir) != null)
					(type.GetConstructor(Type.EmptyTypes).Invoke(null) as IRegisterToken).RegisterToken();
				
				if(type.GetInterface(fu) != null)
					AddFunction(type.Name.Replace("Function", string.Empty), (type.GetConstructor(Type.EmptyTypes).Invoke(null) as IFunction).Perform, false);
			}
			
			foreach(var prop in props)
				AddConstant(prop.Name, prop.GetValue(mycst, null) as Value, false);

			sanatizers.Add("++", "+");
			sanatizers.Add("--", "+");
			sanatizers.Add("+-", "-");
			sanatizers.Add("-+", "-");
			sanatizers.Add("//", "*");
			sanatizers.Add("**", "*");
			sanatizers.Add("^*", "^");
			sanatizers.Add("*^", "^");
			sanatizers.Add("*/", "/");
			sanatizers.Add("/*", "/");
		}
		
		#endregion
		
		#region Add elements
		
		public void AddOperator(string pattern, Operator op)
		{
			operators.Add(pattern, op);
		}

        public void AddExpression(string pattern, Expression exp)
        {
            expressions.Add(new Regex("^" + pattern), exp);
        }
		
		public void AddConstant(string name, double constant, bool custom)
		{
            AddConstant(name, new ScalarValue(constant), custom);
		}

        public void AddConstant(string name, Value constant, bool custom)
        {
            var lname = name.ToLower();

            if (constants.ContainsKey(lname))
                constants[lname] = constant;
            else
                constants.Add(lname, constant);

            if (!custom)
                o_constants.Add(lname, constant);
        }
		
		public void AddFunction(string name, FunctionDelegate f, bool custom)
		{
			var lname = name.ToLower();
			
			if(functions.ContainsKey(lname))
				functions[lname] = f;
			else
				functions.Add(lname, f);
			
			if(!custom)
				o_functions.Add(lname, f);
		}
		
		#endregion
		
		#region Remove elements
		
		public void RemoveConstant(string name)
		{
			var lname = name.ToLower();
			
			if(o_constants.ContainsKey(lname))
				AddConstant(name, o_constants[lname], true);
			else if(constants.ContainsKey(lname))
				constants.Remove(lname);
		}
		
		public void RemoveFunction(string name)
		{
			var lname = name.ToLower();
			
			if(o_functions.ContainsKey(lname))
				AddFunction(name, o_functions[lname], true);
			else if(functions.ContainsKey(lname))
				functions.Remove(lname);
		}
		
		#endregion

        #region Variables

        public void AssignVariable(string name, Value value)
        {
            if (value != null)
            {
                if (variables.ContainsKey(name))
                    variables[name] = value;
                else
                    variables.Add(name, value);
            }
            else if (variables.ContainsKey(name))
                variables.Remove(name);
        }

        public Value GetVariable(string name)
        {
            if (variables.ContainsKey(name))
                return variables[name] as Value;

            return null;
        }

        #endregion

        #region Find elements

        public Value FindConstants(string name)
		{
			var lname = name.ToLower();

			if(constants.ContainsKey(lname))
				return constants[lname];

            throw new SymbolException(name);
		}
		
		public FunctionDelegate FindFunction(string name)
		{
			var lname = name.ToLower();

			if(functions.ContainsKey(lname))
				return functions[lname];
			
			throw new FunctionNotFoundException(name);
		}

		public Operator FindOperator(string input)
		{
			var maxop = string.Empty;
			var notfound = true;

			foreach(var op in operators.Keys)
			{
				if(op.Length <= maxop.Length)
					continue;

				notfound = false;

				for(var i = 0; i < op.Length; i++)
					if(notfound = (input[i] != op[i]))
						break;

				if(notfound == false)
					maxop = op;
			}

			if(maxop.Length == 0)
				throw new ParseException(input);

			return operators[maxop].Create();
		}
		
		public Expression FindExpression(string input)
		{
			Match m = null;

			foreach(var rx in expressions.Keys)
			{
				m = rx.Match(input);

				if(m.Success)
					return expressions[rx].Create(m);
			}
			
			throw new ExpressionNotFoundException(input);
		}
		
		#endregion
		
		#region Singleton
		
		static Tokens _instance;
		
		public static Tokens Instance
		{
			get
			{
				if(_instance == null)
				{
					_instance = new Tokens();
					_instance.RegisterTokens();
				}
				
				return _instance;
			}
		}
		
		public static IFormatProvider NumberFormat
		{
			get { return numFormat; }
		}
		
		#endregion
		
		#region Misc
		
		public void Touch()
		{
			//Empty on intention
		}
		
		#endregion
	}
}

By viewing downloads associated with this article you agree to the Terms of Service 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 Code Project Open License (CPOL)

Share

About the Author

Florian Rappl
Architect
Germany Germany
Florian lives in Munich, Germany. He started his programming career with Perl. After programming C/C++ for some years he discovered his favorite programming language C#. He did work at Siemens as a programmer until he decided to study Physics.

During his studies he worked as an IT consultant for various companies. After graduating with a PhD in theoretical particle Physics he is working as a senior technical consultant in the field of home automation and IoT.

Florian has been giving lectures in C#, HTML5 with CSS3 and JavaScript, software design, and other topics. He is regularly giving talks at user groups, conferences, and companies. He is actively contributing to open-source projects. Florian is the maintainer of AngleSharp, a completely managed browser engine.

You may also be interested in...

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web04 | 2.8.190214.1 | Last Updated 30 Sep 2012
Article Copyright 2012 by Florian Rappl
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid